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
Yahoo! as an ACS Identity Provider Published: April 7, 2011 Updated: March 4, 2015 Applies To: Azure Microsoft Azure Active Directory Access Control (also known as Access Control Service or ACS) supports federation with Yahoo! as an identity provider using the OpenID 2.0 authentication protocol. There are no prerequisites that you must complete before you can add Yahoo! as an identity provider in an Access Control namespace. In the context of ACS, Yahoo! is a preconfigured identity provider. You have to configure the following settings when you add Yahoo! as an identity provider using the ACS Management Portal: - Login link text—Specifies the text that is displayed for the Yahoo!. To download a login image for Yahoo!, see Yahoo! OpenId Buttons (). - Relying party application—Specifies all existing relying party applications that you want to associate with the Yahoo!. The following table shows the claim types that are available to ACS from Yahoo! See Also ConceptsIdentity Providers
https://msdn.microsoft.com/da-dk/library/gg185921
CC-MAIN-2015-22
refinedweb
157
51.04
Find the Largest Cube formed by deleting minimum number of digits from a number Get FREE domain for 1st year and build your brand new site Reading time: 20 minutes | Coding time: 5 minutes Given a number N, our task is to find the largest perfect cube that can be formed by deleting minimum digits (possibly 0) from the number. Any digit can be removed from the given number to reach the goal. X is called a perfect cube if X = Y^3 for some integer Y. If the number cannot be perfect cube print -1. Explanation let N = 1205; if we remove 0 from the above number we will get 125 as remaning number, which is cube root of 5(5 * 5 * 5 = 125). let N = 876 if we remove 7 and 6 then we will have 8 which is cube root of 2 (2 * 2 * 2 = 8) Algorithm We explored two approaches: - A brute force approach O(2^N) - A greedy approach O(N^(1/3)log(N)log(N)) Naive Solution O(2^N) Check for every subsequence of the number check the number is cube or not and then compare it with the maximum cube among them. To generate all substring we remove last character so that next permutation can be generated. We have a number num = "123" we add each element to curr string which will give us: 1 12 123 after this the recuression will return back with "12", then '2' is removed and the next iteration will be called which will give subsequence "13". This will complete the resuresion for '1', the subsequence will start from '2' which will give "2" and "23" after that "3". This will give all the subsequence of the given number 123 1 12 123 13 2 23 3 CODE #include <bits/stdc++.h> using namespace std; #define ll long long ll mx = INT_MIN; bool is_Cube(ll x) { int found = 0; for (int i = 2; i <= (x / 2); i++) { if (x % i == 0) { if ((i * i * i) == x) found = 1; } } if (found == 1) return true; else return false; } void printSubSeqRec(string str, int n, int index = -1, string curr = "") { if (index == n) return; if (curr != "") { ll temp = stoi(curr); if (is_Cube(temp)) mx = max(mx, temp); } for (int i = index + 1; i < n; i++) { curr += str[i]; printSubSeqRec(str, n, i, curr); curr = curr.erase(curr.size() - 1); } return; } int main() { int nums = 102050; string str = to_string(nums); printSubSeqRec(str, str.size()); if (mx != INT_MIN) cout << mx; else cout << "NOT FOUND ANY CUBE"; return 0; } OUTPUT 1000 The Time complexity of the above code is more than 2^n, where n is the number of digit the given number. Greedy Algorithm O(N^(1/3)log(N)log(N)) Now, we know that the largest cube will be smaller the number its self, so we can generate perfect cubes of all numbers from 1 to N, and keep them in an array, after that starting from the largest cube we check if the cube is a subsequence of the given number if yes then we got the desired number otherwise no such number exists. Explanation Given Number is N = 102050 we generate all the perfect cube from 1 to N. perfectCubes={1,8,27,64,125,216,343,512,729,1000,1331,1728,2197,2744, 3375,4096,4913,5832,6859,8000,9261,10648,12167,13824,15625,17576,19683, 21952,24389,27000,29791,32768,35937,39304,42875,46656,50653,54872,59319, 64000,68921,74088,79507,85184,91125,97336} Now we check from the largest number weather its a subsequence of the given N number. like here 1000 is the subsequence of 102050, so 1000 is the Largest Cube formed by Deleting minimum Digits from a number. To check if a number is a subsequence of the given number, we iterate over the number and check if the each digit is present in the the number or not. Eg: we have a number nums = 1025, and we have a perfect cube pc = 125, we iterate over the nums, check if nums[0] is equal to pc[index], then we move to check nums[1] is equal to pc[1], then nums[2] with pc[1], next nums[3] with pc[2], if we reach the end of the pc then pc is a subsequence of the nums, other wise not. Code #include <bits/stdc++.h> using namespace std; // Returns vector of Pre Processed perfect cubes vector<string> calPerfectCube(long long int n) { vector<string> perfectCubes; for (int i = 1; i * i * i <= n; i++) { long long int iThCube = i * i * i; // convert the cube to string and push into // perfectCubes vector string cubeString = to_string(iThCube); perfectCubes.push_back(cubeString); } return perfectCubes; } //Returns the Largest cube number that can be formed string CheckSubSequence(string num, vector<string> perfectCubes) { // reverse the calPerfectCubeed cubes so that we // have the largest cube in the beginning // of the vector reverse(perfectCubes.begin(), perfectCubes.end()); int totalCubes = perfectCubes.size(); // iterate over all cubes for (int i = 0; i < totalCubes; i++) { string currCube = perfectCubes[i]; int digitsInCube = currCube.length(); int index = 0; int digitsInNumber = num.length(); for (int j = 0; j < digitsInNumber; j++) { // check if the current digit of the cube // matches with that of the number num if (num[j] == currCube[index]) index++; if (digitsInCube == index) return currCube; } } // if control reaches here, the its // not possible to form a perfect cube return "Not Possible"; } void FLC(long long int n) { // pre process perfect cubes vector<string> perfectCubes = calPerfectCube(n); // convert number n to string string num = to_string(n); string ans = CheckSubSequence(num, perfectCubes); cout << "Largest Cube is " << ans << endl; } // Driver Code int main() { long long int n; n = 105200; FLC(n); return 0; } Output Largest Cube is 1000 Complexity - Worst case time complexity: O(N^(1/3)log(N)log(N) - Space complexity: O(N^(1/3))
https://iq.opengenus.org/find-the-largest-cube-formed-by-deleting-minimum-digits-from-a-number/
CC-MAIN-2021-43
refinedweb
980
57.34
IRC log of svg on 2012-09-17 Timestamps are in UTC. 07:01:47 [RRSAgent] RRSAgent has joined #svg 07:01:47 [RRSAgent] logging to 07:01:49 [trackbot] RRSAgent, make logs public 07:01:49 [Zakim] Zakim has joined #svg 07:01:51 [trackbot] Zakim, this will be GA_SVGWG 07:01:51 [Zakim] I do not see a conference matching that name scheduled within the next hour, trackbot 07:01:52 [trackbot] Meeting: SVG Working Group Teleconference 07:01:52 [trackbot] Date: 17 September 2012 07:03:04 [heycam] Meeting: SVG WG Switzerland F2F Day 1 07:03:07 [heycam] Chair: Cameron 07:03:45 [birtles] birtles has joined #svg 07:04:22 [heycam] Agenda: 07:06:06 [krit] krit has joined #svg 07:06:31 [krit] Zakim, krit is me :D 07:06:31 [Zakim] I don't understand 'krit is me :D', krit 07:09:22 [Tav] Tav has joined #svg 07:10:39 [nikos] nikos has joined #svg 07:11:11 [nikos] scribenick: nikos 07:11:49 [nikos] Topic: Pass Path object to SVG path 07:11:49 [stakagi] stakagi has joined #svg 07:12:22 [nikos] krit: It would be better to discuss this when Tab is here 07:12:26 [nikos] Topic moved 07:13:12 [nikos] Topic: Linking to external style sheets — should we have <link>? 07:13:38 [nikos] heycam: I was wondering, in the spec at the moment (1.1), it says if you want to reference external stylesheets you should use xml processing instruction 07:13:42 [nikos] ... we should have another way as well 07:13:47 [nikos] ... we at least need to say @import works 07:13:55 [nikos] ... referencing css should get that for free 07:14:23 [nikos] krit: Is it not possible currently? 07:14:27 [nikos] heycam: You can 07:15:32 [heycam] s/can/can't/ 07:16:18 [nikos] heycam: you can't use the xml stylesheet processing instruction in html so we should decide what is the prefered way to link to external stylesheets 07:16:27 [nikos] ... one option is to have link in svg, just like in html 07:16:35 [nikos] birtles: yes 07:16:57 [nikos] ed: What would happen if you copy pasted svg with link element into html5 07:17:30 [nikos] ... link is current an html element so if you pasted svg that is using it into html would it go back to html? 07:17:40 [nikos] ... you can create it with the dom or put it in a foreignObejct 07:17:51 [nikos] s/foreignObejct/foreignObject 07:17:58 [nikos] heycam: it seems to work in firefox 07:18:57 [nikos] heycam: I was testing whether the parser breaks out into html 07:19:01 [heycam](document.getElementsByTagName(%27link%27 )%5B0%5D.namespaceURI)%3C%2Fscript%3E 07:19:13 [nikos] shepazu: Isn't there a white listing of svg elements? or is that just for changing case? 07:19:22 [nikos] heycam: Yes, just changing case 07:19:47 [nikos] krit: what happens if you move the node in the DOM? 07:20:02 [nikos] heycam: I think the link element in the html namespace doesn't have any effect at the moment 07:20:29 [nikos] ... if you try and reference some stylesheet would it work? 07:20:48 [nikos] ... it looks like the way it behaves is - you can have it anywhere in the document 07:21:00 [nikos] ... if we want it to work we specify it the same way except it's in the svg namespace 07:21:29 [andreas] andreas has joined #svg 07:21:40 [victor] victor has joined #svg 07:21:42 [nikos] ... I think we are eventually going to have a bunch of these elements that either share or that can work in both svg and html namespaces 07:21:57 [nikos] krit: I'm just testing safari, if you put a link elements it's in the svg namespace 07:22:55 [nikos] heycam: what do you think of the idea dirk? 07:23:11 [nikos] krit: I like it but I'm wondering what happens when you move nodes in the DOM 07:23:41 [nikos] ... I'm a bit afraid the namespace won't change if you move it in the DOM 07:23:48 [nikos] heycam: nothing changes automatically when you move it 07:23:52 [nikos] krit: and is that ok? 07:24:11 [nikos] shepazu: henry will complain about changes to the parser - are there any? 07:24:18 [nikos] heycam: not for this because it's already in the svg namespace 07:24:25 [nikos] ... maybe it would be a problem if it broke out 07:24:30 [birtles] s/henry/henri/ 07:24:32 [nikos] krit: I wish to have the link element 07:24:40 [nikos] heycam: it gets put in the html namespace 07:24:59 [nikos] ... you can't declare namespaces explicitly but the dom nodes get created in the namespace 07:25:20 [nikos] shepazu: I think the reason for doing it this way is to allow authors to do it without thinking about it - they already know how to do it in html 07:25:28 [nikos] heycam: I think it would work nice and obviously 07:26:07 [nikos] cabanier: it works in Chrome 07:27:06 [nikos] shepazu: if that's true, we should match that user agent 07:28:01 [nikos] heycam: I couldn't get it work in Chrome 07:28:48 [nikos] cabanier: I know it loads the sheet (can see it in the debugger) but I don't know if it applies it 07:28:56 [nikos] ... so it's like half implemented 07:30:04 [ed] 07:30:09 [nikos] heycam: anyone think it's bad idea 07:30:12 [nikos] all: no 07:30:20 [nikos] shepazu: we should ask the html working group 07:30:28 [nikos] heycam: we should ask them if there is anything we haven't thought of 07:30:54 [nikos] Resolution: We will add a link element to SVG that behaves in the same way as HTML 07:32:00 [nikos] Action: Cameron to email the HTML and WhatWG working groups to ask if there any problems related to adding the HTML link element into SVG 07:32:00 [trackbot] Created ACTION-3351 - Email the HTML and WhatWG working groups to ask if there any problems related to adding the HTML link element into SVG [on Cameron McCormack - due 2012-09-24]. 07:32:21 [konno] konno has joined #svg 07:33:23 [nikos] Topic: enable-background naming in relation to compositing and blending 07:33:35 [nikos] cabanier: The name is a bit confusing 07:33:44 [nikos] ... it doesn't match what users are familiar 07:33:50 [nikos] ... in the compositing spec it was replaced with isolation 07:34:16 [nikos] ... so we have the existing enable-background keyword, we can't get rid of it or it will break content 07:34:22 [nikos] ... we were thinking of having it shadow 07:34:26 [nikos] ... like an alias 07:34:35 [nikos] krit: css wg tries to define shadowing properly 07:34:47 [nikos] ... they have the same problem for some text properties 07:35:37 [andreas] andreas has joined #svg 07:36:01 [nikos] nikos: we are thinking that the property should apply to compositing and blending and filter effects 07:36:08 [nikos] ... you shouldn't be able to specify different modes for each 07:36:28 [nikos] heycam: so there's 2 issues really, having the property apply to both and the naming 07:36:37 [nikos] heycam: do you have an example of css shadowing? 07:36:56 [nikos] krit: not yet, we don't have a specification, but the css wg have expressed an interest in the idea 07:37:05 [nikos] heycam: what about if you use the css om to look up property values? 07:37:18 [nikos] ... like there's a single variable underneath but there's 2 properties 07:37:30 [nikos] krit: the question is which takes effect if both are specified 07:37:34 [nikos] cabanier: I think the last one wins 07:39:24 [nikos] ... what happens currently if you say 'opacity=1 opacity=0.5'? 07:39:51 [nikos] heycam: what happens currently for prefixed and not when you support them both? 07:40:03 [nikos] krit: they are both in the style declaration as far as I know 07:40:08 [nikos] heycam: with one underlying variable? 07:40:17 [nikos] krit: I'll have to check 07:40:30 [nikos] heycam: I assume the css working group wants to define how this works and not us 07:40:37 [nikos] cabanier: so are we ok combining them? 07:40:47 [nikos] heycam: I think so - as long as enable-background works for existing things 07:40:59 [nikos] ... so enable-background has numbers when you specify new? or did we get rid of that 07:41:03 [nikos] krit: we got rid of that 07:41:35 [nikos] krit: looking at the source code - we treat them as different properties 07:42:09 [nikos] ... for box-shadow and webkit-box-shadow we have two different style declarations 07:42:23 [nikos] ... you can set box-shadow and webkit-box-shadow and they can be different 07:42:36 [nikos] ... when rendering one will win but I'm not sure which 07:42:47 [nikos] heycam: I think that as long as it is worked out then I'm ok with it 07:43:01 [nikos] cabanier: do we know who is working on the shadowing? 07:43:08 [nikos] krit: no, we'll have to ask 07:44:07 [nikos] Resolution: We want isolation property to shadow enable-background and we will ask the CSS working group about the details 07:44:19 [nikos] Action: Rik to ask CSS WG about how shadowing will work for enable-background 07:44:19 [trackbot] Created ACTION-3352 - Ask CSS WG about how shadowing will work for enable-background [on Rik Cabanier - due 2012-09-24]. 07:45:02 [nikos] krit: I think we will put both properties in Filter Effects and mark one as preferable 07:45:24 [nikos] nikos: So is it ok for one property to control both filter-effects and compositing and blending? 07:45:28 [nikos] all: yes that's ok 07:46:03 [nikos] Resolution: The enable-background/isolation will apply to both Filter Effects and Compositing and Blending 07:46:34 [nikos] Topic: Filter Effects - keep new fe*elements that lack description ATM? 07:47:04 [krit] 07:47:17 [krit] 07:47:35 [nikos] krit: We have different filter effects that lack definition and I would like to know if we want to keep them and add description or is it not neccesary? 07:47:54 [nikos] ... I'm just talking about filter primitives and not the shorthands 07:48:15 [nikos] cabanier: does anybody implement these? 07:48:17 [nikos] krit: no 07:48:28 [nikos] krit: we are about to implement feCustom 07:48:33 [nikos] heycam: who wanted them ? 07:48:48 [nikos] ed: diffuse specular was meant to be an optimisation to give better performance 07:48:58 [nikos] ... I'm not sure if it's really needed as the filter chain does the optimisation 07:49:08 [nikos] heycam: would it make it better for authors? 07:49:11 [nikos] ed: probably not 07:49:17 [nikos] heycam: I say get rid of them then 07:49:31 [nikos] ed: I don't mind removing them if they don't seem to be useful 07:50:37 [nikos] ed: you could do feUnsharpMaskElement with scripting and other filter effects 07:50:41 [nikos] ... but we don't have a shorthand for it 07:50:46 [nikos] Resolution: Remove feUnsharp and feDiffuseSpecular from Filter Effects specification for now - may be added again in future 07:50:54 [krit] 07:51:05 [nikos] Topic: Filter Functions 07:51:19 [nikos] are other shorthands needed? 07:51:36 [nikos] krit: The question is do we put in a bug report on Safari for functions that are not implemented? 07:52:07 [ed] s/filter chain does the optimisation/implementation can analyze the filter chain and do the same optimisation 07:52:25 [nikos] krit: I had suggestions for other filter functions that we could have, but I have not had any feedback 07:52:31 [nikos] ... so I'm wondering if we can remove the issue 07:53:02 [nikos] heycam: it doesn't hurt to keep it in, but if you're wanting to finalise and go to last call then you can remove it 07:53:10 [nikos] krit: there's no problem adding new shorthands in the later version 07:53:17 [nikos] ... the question is do we freeze what we have now? 07:53:28 [nikos] heycam: I think the set that is there currently is a reasonable set 07:54:20 [nikos] Resolution: Remove filter function suggestions (issue 5) from Filter Effects spec 07:55:03 [nikos] Action: Dirk to file a bug and track filter functions (issue 5) removed from Filter Effects spec 07:55:04 [trackbot] Created ACTION-3353 - File a bug and track filter functions (issue 5) removed from Filter Effects spec [on Dirk Schulze - due 2012-09-24]. 07:55:53 [nikos] Topic: Removing pixelUnitToMillimeter{X,Y} and screenPixelToMillimeter{X,Y} 07:56:06 [nikos] heycam: I didn't know this existed and I'm not sure anyone would use these API functions 07:56:09 [nikos] krit: Is anyone using them? 07:56:14 [nikos] heycam: I'm not sure, I can check. 07:56:30 [nikos] andreas: is there an alternative way to get at the pixel size? 07:56:48 [nikos] heycam: I think not but I think it's been discussed in the CSS WG whether you should access the real DPI and do something based on that 07:56:57 [nikos] cabanier: you mean the HD stuff? 07:56:59 [nikos] heycam: I'm not sure 07:57:03 [nikos] krit: so why do you want to remove it? 07:57:17 [nikos] heycam: our implementation returns a constant value assuming 96 dpi. 07:57:22 [nikos] cabanier: what does webkit do? 07:57:25 [nikos] krit: the same thing 07:57:58 [nikos] cabanier: it could be implemented to not be constant in the future - for HD devices 07:58:26 [nikos] krit: the idea is that we want to know how many mm it is on the screen 07:58:36 [shepazu] shepazu has joined #svg 07:58:40 [nikos] heycam: I remember people objecting to that in some other context 07:59:00 [nikos] cabanier: how do you know what the screen size is? 07:59:44 [nikos] krit: Firefox used to expose that information in an API but removed it. 07:59:54 [nikos] heycam: now everyone has converged on CSS units being a fixed number of pixels 08:00:08 [nikos] krit: the problem is that some platforms don't give you the exact DPI, so it could not be implemented on some platforms 08:01:00 [nikos] heycam: I think one of the problems with physical units is you want to know it for different reasons - like touch events (finger size) and font size (but how far away are they from the screen) 08:01:16 [nikos] krit: I don't know how they would be used 08:01:45 [nikos] shepazu: you'd be surprised - some people implement for one browser and if it's implemented in one browser it gets used 08:02:04 [nikos] ed: Opera is hard coded also 08:02:28 [nikos] ... I think it's the same value as other implementations 08:03:04 [nikos] krit: the css working group is looking into ways to get screen pixels per CSS pixel. 08:03:15 [nikos] heycam: but it doesn't tell you the physical size 08:03:35 [nikos] cabanier: are you going to remove pixels per inch as well? 08:03:43 [nikos] heycam: yep there's not 4 methods 08:03:59 [nikos] cabanier: I think somebody somewhere is using them 08:04:05 [nikos] ed: I'd be surprised to see them used 08:05:09 [nikos] heycam: I just googled screenPixelToMillimeterX and got no hits 08:05:14 [nikos] ... with svg file types 08:05:34 [nikos] cabanier: I wonder if they will become more useful 08:05:39 [nikos] ... in future 08:08:01 [nikos] heycam: I would like to ask the CSS WG what they think about units 08:08:23 [nikos] krit: the question is how to get the physical size, but I don't think the CSS WG is working on that 08:08:39 [nikos] heycam: the topic about mm not being real mm anymore comes up often and I'd like to know the details 08:08:55 [nikos] ... is it because it's probably not what authors want 08:09:15 [nikos] krit: if I say 2cm but then project it on the wall I don't want it to be 2 cm 08:10:59 [nikos] heycam: I'll ask Chris 08:12:51 [nikos] Topic: How to internationalize "title"? 08:13:05 [nikos] Tav: This came up at SVG open. Someone was asking whether it could be done. 08:13:21 [nikos] heycam: My first suggestion would be to allow system language on the title element. 08:13:25 [nikos] ed: that's already done isn't it ? 08:13:30 [nikos] heycam: I'll look 08:13:42 [nikos] ... The question is how to internationalise the title 08:13:50 [nikos] shepazu: how about we use switch? 08:14:33 [nikos] Tav: how would it work? 08:14:44 [nikos] shepazu: you would have the switch element with different copies of the titles 08:15:02 [nikos] heycam: what is switch a child of ? 08:15:13 [nikos] shepazu: how about we change switch to allow text content ( if it doesn't already) 08:15:36 [nikos] ... I think switch only works at an element level now and not at a text level 08:15:41 [nikos] ... I think we should change it to text 08:15:51 [nikos] ... then you would switch on the actual text content rather than on the element 08:15:57 [nikos] ... title would be a child element 08:16:27 [nikos] krit: can you change paragraphs in HTML to change content based on the language? 08:16:31 [nikos] shepazu: there is no mechanism for doing that 08:16:57 [nikos] ... since we are changing switch anyway, we could add something like a span that is basically meaningless? We have tspan - it's not a child of title 08:17:10 [nikos] ... we have a few options 08:17:18 [nikos] ... we can change switch to have text content, but what is the child element of the switch 08:17:33 [nikos] ... we can change title apply to the parent of the switch 08:17:50 [nikos] ... if title is encased in a switch element it jumps up one level - the switch is transparent in regards to the title 08:18:11 [nikos] Tav: what about the desc element? 08:18:19 [nikos] shepazu: or tooltip, or whatever 08:18:27 [nikos] ... they'd be the same 08:18:45 [nikos] heycam: on switch you can have all the group attributes. 08:18:56 [nikos] shepazu: people shouldn't use switch for that - you can but you shouldn't 08:19:01 [nikos] ... switch should be transparent 08:19:12 [nikos] heycam: I think you should be able to do multiple title elements 08:19:37 [nikos] ... like <rect><title systemLanguage="..." /> 08:19:52 [nikos] ... or have language tags which are subsets 08:20:11 [nikos] ... we could resolve that the first title element that matches the conditional processing attributes is used 08:20:20 [nikos] ... if you want a fallback you have a title without conditional attributes 08:20:25 [ed] just playing a bit with the systemLanguage: 08:20:31 [nikos] ... and resolve that only one title applies to an element 08:20:46 [nikos] shepazu: that's good. So we'd be getting rid of the switch element for this case 08:21:02 [nikos] ... we should tell people, for legacy reasons, always put the default first 08:21:15 [nikos] krit: and instead of systemLanguage can we just use lang? 08:21:30 [nikos] shepazu: it might not be the system language it might just be the language of preference, so that sounds like a good idea 08:21:37 [nikos] ... we can change it in switch as well 08:21:52 [nikos] ... anything camel cased needs to die, die, die, die, die! 08:22:14 [nikos] ... I agree with something short but we'd be overloading lang then 08:22:18 [nikos] ... but that's actually useful 08:22:35 [nikos] ... the problem is, what happens if you do 08:22:57 [nikos] <text><tspan lang="de">Hallo</tspan><tspan lang="en">he said.... 08:23:11 [nikos] heycam: I would be fine with allowing lang on title as a special thing 08:23:14 [nikos] shepazu: it seems strange 08:23:27 [nikos] krit: in general you can just display one title 08:23:38 [nikos] shepazu: are we going to generalise this and get rid of the switch element in other circumstances? 08:23:45 [nikos] heycam: I don't think it would work in other cases 08:24:05 [nikos] shepazu: ok I'm fine with it for any meta element (description also) 08:24:28 [nikos] shepazu: we are giving special characteristics to title with respect to what the language is 08:24:31 [nikos] heycam: I'm ok with that 08:24:54 [nikos] ... I think systemLanguage makes more sense with the current functionality but lang looks nicer 08:25:18 [nikos] shepazu: lets leave lang as a special meta data thing that is a special case of switch 08:25:52 [nikos] ed: for title it works not sure about desc 08:26:01 [nikos] Tav: how is title as an attribute different from title as an element? 08:26:14 [nikos] ... do the browsers treat it differnet? 08:26:20 [nikos] s/differnet/differently 08:26:25 [nikos] shepazu: We just hint what you should do 08:26:45 [nikos] heycam: one of the arguments of having title as an element is good for languages which require disambiguation of direction 08:27:02 [nikos] ... svg doesn't have the elements to control that so I think it's a moot issue for us 08:27:42 [nikos] heycam: what about if we had title as a property? 08:27:59 [nikos] shepazu: that would promote poor practice for internationalisation 08:28:11 [nikos] heycam: I don't know if you'd want to download a big file with lots of languages 08:28:36 [nikos] shepazu: I quite like using many languages in SVG. it wasn't designed to be text heavy. 08:29:09 [nikos] ... one thing we didn't talk about is - a common workflow for skins is to point to an external resource for the languages 08:29:27 [nikos] ... it looks up the value and inserts it. We could enable something like that for SVG 08:29:37 [nikos] ... people could point off to their text file that contains different languages 08:29:45 [nikos] heycam: I think you could already do that for text other than title 08:29:52 [nikos] shepazu: we should define how that happens 08:29:56 [nikos] heycam: it's defined. 08:30:13 [nikos] shepazu: We should give examples of how it works to promote best practices 08:30:43 [nikos] ... it could be an href like tref and if it's defined you go and retrieve it and thats where all the switching stuff is done. 08:30:57 [nikos] ... if it doesn't get the file then it could use the default of what you put in the <text> 08:31:22 [nikos] ... I think it would allow people to customise these things more easily - it's just a proposal 08:31:36 [nikos] Tav: allowing lang on title solves the use case that was put to be at SVG open 08:33:04 [nikos] krit: so the first title doesn't need a lang but the rest do? 08:33:27 [nikos] heycam: current implementations look at the first title only, so if you are happy having that as a fallback that will always work you need to put it first 08:33:38 [nikos] and then you could still put lang on it if that's what you want for the default 08:35:15 [nikos] heycam: the issue is, I think, if you have the first title and it has an obscure language, you don't want that to be the default in the new system if other languages are provided 08:35:19 [nikos] krit: I don't agree, 08:35:50 [nikos] shepazu: for implementations that support this it will check every language and display the first match 08:35:54 [nikos] ... so it has the behaviour you want 08:36:01 [nikos] ... it's just for legacy purposes the default is the first 08:36:06 [nikos] krit: that's ok 08:36:20 [nikos] heycam: the only downside is the order checking is different from switch 08:36:30 [TabAtkins] TabAtkins has joined #svg 08:36:31 [nikos] shepazu: it's not switch though it's something different 08:36:44 [nikos] Resolution: Add lang to title and desc 08:36:53 [TabAtkins] Ugh, I slept straight through my alarm, wow. Where are we? Like, physically? 08:37:27 [TabAtkins] kk 08:38:19 [nikos] Action: Tav to add lang to tile and desc 08:38:20 [trackbot] Created ACTION-3354 - Add lang to tile and desc [on Tavmjong Bah - due 2012-09-24]. 08:41:09 [nikos] Topic: Removing pixelUnitToMillimeter{X,Y} and screenPixelToMillimeter{X,Y} 08:41:18 [nikos] andreas: I did some reasearch 08:41:43 [nikos] ... there's a property you can create in Javascript called window.devicePixelRatio 08:41:57 [nikos] ... Opera supports it but it has a different value than WebKit 08:42:04 [nikos] ... that's all I've really found that does that 08:42:17 [nikos] Tab: It's a proprietary webkit thing right now 08:42:28 [andreas] 08:42:56 [nikos] Tab: I think if they're useful remove them but they could be useful since we have the possibility of non-square pixels 08:43:23 [nikos] s/I think if they're useful remove them but they could be useful since we have the possibility of non-square pixels/I think if they're use-less remove them but they could be useful since we have the possibility of non-square pixels 08:43:59 [nikos] nikos: would it be more useful to just get the ratio and not worry about the size? 08:44:10 [TabAtkins] TabAtkins has joined #svg 08:44:24 [nikos] Tab: I think getting the X width is the most useful and then Y could either be an actual height or a ratio 08:45:03 [nikos] heycam: this seems to be a bit different since the SVG functions relate to a specific size on the screen rather than a ratio 09:12:29 [ed] scribeNick: ed 09:12:42 [ed] topic: passing path object to svg path 09:12:44 [krit] 09:12:52 [nikos] nikos has joined #svg 09:13:01 [cabanier] cabanier has joined #svg 09:13:06 [ed] DS: in html canvas we have an interface to build a path object 09:13:18 [ed] ... would be good if we could get the path and pass it to the svgdom 09:13:30 [ed] ... to append to the svg path 09:13:42 [ed] CM: can it serialize to the svg pathstring? 09:13:55 [ed] DS: no, there are some differences 09:14:03 [ed] ... arcto for example 09:14:21 [ed] ... suggest we leave it up to the browser to normalize the path 09:14:34 [ed] ... and not specify exactly how 09:14:47 [ed] CM: i think it should be specified 09:15:58 [ed] RC: if you draw a circle it stores a bunch of bezier curves 09:16:08 [ed] ... so if you read the path out it looks ok, but it's no longer a circle 09:16:35 [ed] doug: so if I do a circle in skia and a circle in cairo i would get the same result? 09:16:52 [ed] DS: might be different, but should look the same 09:17:10 [ed] doug: is this exposed to the user? 09:17:30 [ed] TA: the UA would need to remember the original commands, doesn't do this atm 09:17:54 [ed] DS: i'd prefer the first version to not specify the normalization 09:17:59 [ed] CM: i don't like it 09:18:14 [ed] TA: if you're doing it in script you're going to have to do it anyway 09:18:43 [ed] BB: scripts handle one segments produces in one browser, that's how most authors work 09:19:28 [ed] Doug: experienced that with freaky mouth example, didn't work in opera due to how path normalization worked there 09:19:37 [ed] CM: we could require one or more beziers 09:19:43 [ed] ... not knowing how many you get 09:19:59 [ed] Doug: doesn't help the author at all 09:20:19 [ed] CM: the predictable thing is that you'll get a number of beziers 09:20:34 [ed] doug: think about animation 09:20:58 [ed] DS: we could specify how arc is normalized, as quadratic curves 09:21:36 [ed] TA: all implementations support cubic beziers 09:22:00 [ed] CM: why not have a configurable thing to store the original path commands? 09:22:36 [ed] TA: we should specify how many beziers an arc gets turned into 09:23:24 [ed] BB: is there a concrete usecase for this? or is this just about the procedural api for creating the path? 09:23:32 [ed] TA: i think the api is a use-case 09:23:51 [ed] BB: we could just support the canvas path api in svg 09:25:14 [ed] TA: the path is a toplevel global api, so you can create the path object without having a canvas 09:26:34 [ed] ... will break paper.js, but that's fine, will just shadow the native interface 09:27:06 [ed] CM: there's an interface CanvasPathMethods that we could inherit 09:27:27 [ed] ... to have them directly on the <path> element 09:27:56 [ed] DS: but then you can't use this to create a canvas path, and reuse the path object 09:28:23 [ed] RC: you can contruct it with an svg path string 09:29:13 [ed] TA: we could also make it serialize out to something that works in svg path@d attribute 09:29:33 [ed] DS: like that idea 09:29:56 [ed] ...but it doesn't make sense that it has to serialize and then reparsed by svg 09:30:00 [ed] ED: agree 09:30:31 [ed] Doug: element.addPath(obj) to append that path 09:30:49 [ed] ... you might want to animate and reuse and so on 09:31:16 [ed] CM: how would you get arcs? 09:31:30 [ed] ... with the procedural api 09:31:44 [ed] DS: you can't, you'd get cubics back 09:32:10 [ed] Doug: everybody hates the arc syntax in svg 09:32:50 [ed] ... with catmull-rom we thought to translate that into beziers anyway 09:33:05 [ed] ... you should be able to find out what it converted to 09:33:35 [shepazu] shepazu: and you could chain commandas 09:33:46 [shepazu] s/commandas/commands/ 09:33:50 [ed] CM: would like the native api to be able to create the native path commands, like arc, catmull-rom etc 09:34:58 [ed] ... so if I create an arc with the API and put it into an svg <path> element that the arc is still an arc 09:35:12 [ed] DS: but then the mapping isn't 1:1 09:36:30 [ed] CM: you can't tweak everything afterwards if it's normalized 09:37:36 [ed] ... but the arc syntax might be different betweent the api and the svg commands 09:39:20 [ed] doug: there should be a way to get the non-normalized path out, you should be able to get both that and the normalized variant 09:40:44 [ed] TA: we want to normalize (which needs to be specified) lineto,moveto, cubic beziers and close path 09:41:09 [ed] CM: i want to be able to say .arc and have that turn into arc command 09:41:20 [ed] TA: why? the syntax is different 09:42:44 [ed] CM: if we have the nicer path syntax in svg then we could have a direct mapping 09:43:31 [ed] TA: so taking the path commands and adding it to svg, plus extending the api? 09:43:47 [andreas] andreas has joined #svg 09:44:12 [ed] CM: as long as it's possible procedural things and get the actual path commands 09:45:50 [ed] (discussion on spec stability) 09:47:53 [ed] TA: the path object stringifies to a normalized path string 09:48:21 [ed] CM: how many beziers does an arc get turned into? 09:48:26 [ed] TA: needs to be specified 09:49:52 [ed] RESOLUTION: we want to add a stringifier on the path object that returns a string using normalized svg path syntax 09:52:25 [ed] RESOLUTION: svg path elements gains a addPath method that appends path to the path 09:52:53 [ed] s/appends path to the path/appends path object to the path 09:53:07 [ed] CM: does canvas paths need to start with a moveto? 09:53:22 [ed] TA: not required, starts at 0,0 09:53:37 [ed] ... some things start implicit subpaths 09:53:48 [ed] ... e.g the rect command 09:55:09 [heycam] String(new Path("M … A …")) 09:55:29 [heycam] normalizes the path back to an SVG path segment list 09:56:58 [ed] RESOLUTION: it will be possible to normalize explicitly and stringify the result 09:57:07 [TabAtkins] (new Path().addPath("M... A...")+'' 09:57:13 [TabAtkins] (new Path()).addPath("M... A...")+'' 09:58:03 [ed] RESOLUTION: there will be a method that normalizes any svg shape into a path object 09:59:26 [ed] BB: so adding the canvas api methods to the svgpath elements 09:59:43 [ed] TA: if we put it on the path element id' expect it to be normalized 09:59:43 [birtles] s/svgpath elements/svgpathseglist/ 10:00:02 [ed] ... but if we put it on the svgpathseglist then i'd expect non-normalized 10:00:28 [ed] CM: where you put the interface is just baout how much you want to help the authors 10:00:54 [ed] TA: so seglists could be smarter 10:00:59 [ed] CM: seems confusing 10:01:34 [ed] BB: i do want a simple api, but avoiding duplication is maybe better 10:01:53 [ed] CM: e.d.arcTo(...) 10:02:02 [ed] CM: e.arcTo(...) 10:02:26 [ed] ... think the second one is not necessary 10:02:42 [ed] RC: if you do addPath it works 10:03:09 [ed] CM: i'd like to be able to set the svg path from a string directly 10:03:45 [ed] BB: think it should be on the seglist interface 10:04:26 [ed] CM: so adding addPath to the svgpathseglist 10:04:40 [ed] DS: i think it should be on the path element 10:05:08 [ed] CM: think it makes sense to have all path manipulations on the svgpathseglist interface 10:06:08 [ed] DS: what's on the svgpathseglist api now? 10:06:14 [ed] TA: path manip methods 10:06:21 [ed] DS: doesn't quite fit tehre IMO 10:06:50 [ed] CM: BB thinks it'd be more useful to have retained pathseglists 10:07:03 [ed] ... without having it attached to a path element 10:07:05 [ChrisL] ChrisL has joined #svg 10:08:02 [ed] ... so the worry is that we'll have two such path object representations (svgpathseglist and the path object) 10:09:20 [ed] BB: who's going to revise the path apis in svg? 10:09:28 [ed] CM: i think i have an action to do that 10:09:51 [ed] ... new SVGPathSegList(canvaspath) 10:10:34 [ed] Andreas: does addPath start a new subpath? 10:10:59 [ed] Doug: you can use clear to clear out the path so that you can have a blank canvas to draw on 10:11:56 [ed] ... addPath will add a new moveto, but what if you want to add commands to that? 10:12:08 [ed] ... to a existing path 10:12:25 [ed] CM: you could stringify and strip out the movetos 10:12:58 [ed] Doug: couldn't we just have addSegment to just append/continue the path? 10:13:56 [ed] ... could we make addSegment strip out the implicit path API moveto? 10:14:58 [ed] ... usecase: to append segments to an existing path 10:15:31 [ed] TA: you don't know if the moveto was explicit or implicit 10:15:45 [ed] ...due to normalization 10:16:41 [ed] TA: i want addPath and extendPath 10:16:59 [ed] ... extendPath cuts off the first moveto 10:18:43 [ed] RESOLUTION: add extendPath - which acts as addPath but trims off the initial moveto 10:19:16 [ed] doug: so are we adding arcTo? 10:20:04 [ed] ... and what do we do with catmull-rom? 10:21:07 [ed] CM: these new commands should be on the canvas path api so both can use them? 10:21:14 [ed] doug: yes, sounds useful for both 10:22:36 [ed] RESOLUTION: add new procedural methods for catmull-rom and add canvas-like arc commands in svg path syntax 10:23:10 [ed] CM: there are arc and arcto, and ellipse 10:23:47 [ed] TA: arc and ellipse use startangle,endangle 10:25:45 [ed] RESOLUTION: add a 'd' property to the svg path element for accessing the pathseglist 10:26:26 [ed] BB: allow svgpathseglists to be created independent of the svg path element 10:27:06 [ed] ... allow assigning a pathseglist object ot the path element (pathelm.d = seglist) 10:27:52 [ed] doug: should have a json serialization of the path, in addition to the stringification 10:28:25 [ed] CM: someone has requested toJSON for passing objects around, e.g for web workers 10:28:40 [ed] BB: to be able to set and get an array of floats 10:28:57 [ed] ... you already have normalization for moveto, lineto, closepath 10:29:46 [ed] ... faster with float arrays than to use pathseglist 10:31:02 [ed] CM: so, stringifier, jsonifier, and pointifier? 10:31:16 [ed] BB: there are a number of ways you could do this 10:31:39 [ed] ... there are libs that work on arrays of points directly 10:33:49 [ed] ... you're really working on arrays of arrays 10:34:14 [ed] CM: for subpaths you could flag it somehow 10:34:57 [ed] TA: boolean at the end? 10:35:24 [ed] BB: needs to be there when you set it back again 10:35:51 [ed] CM: alternative is to have a function isSubpathClosed, and pass in the subpath 10:36:20 [ed] BB: that's a bit less flexible 10:37:11 [ed] ... want to just read out the point array, manipulate and set it back 10:37:54 [ed] TA: so you have an array of points per subpath 10:38:16 [ed] BB: and you have array of subpaths, which each have an array of points 10:39:07 [ed] TA: so defer until we get some feedback on this, on the list? 10:39:44 [ed] CM: the json thing then... 10:40:08 [ed] TA: not quite ready to resolve on that yet, but similar to the array one, should probably be discussed on the list 10:40:25 [ed] -- 1h break for lunch -- 11:58:01 [stakagi] stakagi has joined #svg 11:59:17 [TabAtkins] TabAtkins has joined #svg 11:59:57 [birtles] birtles has joined #svg 12:00:12 [birtles] scribenick: birtles 12:01:04 [birtles] topic: new arc command 12:01:32 [birtles] heycam: problem is the existing arc is unintuitive and you often want to animate the angles of arc rather than the endpoints 12:01:49 [birtles] ... it's really hard with declarative animation 12:01:54 [nikos] nikos has joined #svg 12:01:55 [birtles] ... you have to do all the trig yourself 12:02:11 [birtles] ... which of the canvas arc commands let you specify the angle? 12:02:53 [birtles] TabAtkins: arc and ellipse are basically the same... 12:03:30 [birtles] ... arc(x, y, radius, startAngle, endAngle, acw) 12:03:42 [birtles] ... coordinates are absolute 12:03:56 [birtles] ... ellipse is the same but the radius has x and y and a rotation argument 12:04:07 [birtles] ... arc2 is a separate command that takes... 12:04:16 [birtles] s/arc2/arcTo/ 12:04:51 [birtles] heycam: is the implicit start point on the circle? 12:05:40 [birtles] cabanier: no, it automatically draws a line to the start of the arc 12:05:51 [birtles] TabAtkins: arcTo is a little more interesting... 12:06:09 [birtles] ... it does a straight line segment but it provides C1 continuity 12:06:33 [birtles] ... arcTo(x1, y2, x2, y2, radius) 12:07:25 [birtles] ... (draws a diagram explaining how arcTo works) 12:07:49 [birtles] shepazu: I'd like to add a rounding algorithm to SVG based on this mechanism 12:08:17 [birtles] TabAtkins: there is no rounded rect, you just use four arcTo commands 12:08:27 [birtles] ... there are the two arc commands in canvas 12:08:56 [birtles] krit: but are we running over the letters in the alphabet in the SVG path syntax? 12:09:10 [birtles] TabAtkins: but we could allow identifiers that are more than a single letter 12:09:51 [birtles] shepazu: we could just say "arc" 12:10:21 [birtles] heycam: is it useful to have both? 12:10:27 [birtles] everyone: yes 12:10:46 [birtles] TabAtkins: we could just have "arc" and "arcTo"? 12:10:55 [birtles] heycam: are you sure we don't want to use single letters? 12:11:05 [birtles] ... what about "e"? 12:11:06 [glenn] glenn has joined #svg 12:11:14 [birtles] krit: that conflicts with scientific notation 12:11:52 [birtles] (which is now in CSS by the way) 12:12:04 [birtles] TabAtkins: I don't think we can continue with single letters 12:12:16 [birtles] heycam: what about leading punctuation? 12:13:02 [birtles] ChrisL: we've talked about having longhand before 12:13:10 [birtles] shepazu: it's also better for compression 12:13:47 [birtles] (talking about using expanded elements for path commands) 12:14:21 [birtles] heycam: so use "arc" and "arcTo" as the commands? 12:15:10 [birtles] TabAtkins: I'd be inclined to call them "circle", "ellipse" and "arcTo" 12:15:38 [birtles] ... so that we can use "arc" later as a longform for the existing arc command 12:16:02 [birtles] heycam: it might be more important to match the command name with the method 12:16:12 [birtles] ... rather than accommodating the existing arc command 12:16:19 [birtles] ... we could give it some other name in the future 12:16:36 [birtles] ChrisL: do we want to deprecate the existing arc command? 12:16:42 [birtles] TabAtkins: no, it's sometimes useful 12:16:50 [birtles] ChrisL: ok 12:17:14 [andreas] andreas has joined #svg 12:17:40 [birtles] TabAtkins: ok, let's keep consistency with the canvas method names for now 12:17:59 [birtles] ChrisL: we should have a resolution about whether we want the longhand form or not 12:18:21 [birtles] TabAtkins: need to decide priorities (when you have both) 12:18:44 [cyril] cyril has joined #svg 12:18:57 [birtles] heycam: it seems like a lot of duplication when sometimes it's probably easier just to separate out paths of the path string, rather than having 10 new elements 12:19:08 [birtles] ed: like having a fragment of the path as a separate element 12:19:17 [birtles] ChrisL: I think we'll probably have that too 12:19:33 [birtles] ... but we've often been asked for the verbose form 12:21:27 [birtles] ... the two big advantages are (a) better compression, (b) adding IDs / event handlers to specific parts 12:22:04 [birtles] (discussion about whether we could stroke sections differently) 12:22:37 [birtles] krit: what about adding length (units) to the path data 12:23:06 [birtles] ChrisL: when we originally considered that there was feedback that said that was really difficult 12:23:40 [birtles] heycam: what about percentages? 12:23:49 [birtles] krit: percentages are difficult, just lengths would be enough 12:23:54 [birtles] heycam: percentages would be useful 12:24:12 [birtles] TabAtkins: what measure do you resolve against for a diagonal line 12:24:22 [birtles] heycam: depends which coordinate of the command 12:24:40 [birtles] ... if it's the y coord it is resolved against the height 12:25:06 [birtles] ... since unit identifiers are currently more than one letter there shouldn't be clashes with the path commands? 12:25:24 [birtles] shepazu: using units in paths has often been requested 12:25:38 [birtles] ... sometimes this is because people don't understand how to set units at the root 12:25:46 [birtles] ... but percentages are often valid 12:26:54 [birtles] krit: when are percentages are resolved? 12:27:09 [birtles] TabAtkins: if it's created in JS, what do you resolve the percentages against? 12:27:20 [birtles] heycam: it's similar to creating SVGLength objects 12:27:29 [birtles] ... what do they get resolved against? 12:27:41 [birtles] ... using createSVGLength 12:28:05 [birtles] ... we never really resolved how that should work 12:30:25 [birtles] RESOLUTION: We will add arc, ellipse, and two forms of arcTo to the SVG path syntax based on the canvas methods of the same names 12:31:17 [birtles] TabAtkins: the only remaining command on canvas that's not available with the d attribute is "rect" 12:32:01 [birtles] ChrisL: what do we need to spec out with regards to that resolution 12:32:08 [birtles] heycam: DOM API etc. 12:32:49 [birtles] TabAtkins: it would be nice to make the "d" attribute of the SVGPathElement return a sane version of SVGPathSegList 12:33:09 [birtles] ... (and not just an alias of pathSegList) 12:33:34 [birtles] krit: does this work for repeated commands? 12:33:50 [birtles] ... since the number of arguments to arcTo varies 12:34:01 [birtles] TabAtkins: arcTo comes in a 5 arg and a 7 arg version 12:34:12 [birtles] ChrisL: we could solve it by giving them different names 12:34:24 [birtles] ... or just say you have to repeat the command 12:35:25 [birtles] TabAtkins: what if we have ellipseTo 12:35:40 [birtles] ChrisL: and just document what ellipseTo equates to in canvas terms 12:35:55 [birtles] ... then you wouldn't have to have an exception where these commands can't be repeated 12:36:48 [birtles] heycam: we should look into adding ellipseTo to canvas (as an alias to the equivalent arcTo command) 12:36:56 [birtles] TabAtkins: I'll propose it 12:37:45 [birtles] ACTION: Tab to propose to the HTML WG that the 7 argument form of arcTo be replaced with an ellipseTo method 12:37:45 [trackbot] Created ACTION-3355 - Propose to the HTML WG that the 7 argument form of arcTo be replaced with an ellipseTo method [on Tab Atkins Jr. - due 2012-09-24]. 12:38:13 [birtles] (this is because the elliptical version of arcTo is not implemented anywhere so we are still free to change the name) 12:38:51 [birtles] heycam: I'll try to write this up in the spec since my name is down next to this item in the requirements list 12:39:10 [birtles] ChrisL: what about lengths and percentages in paths? 12:39:29 [birtles] krit: I'm still not sure about how you resolve percentages 12:40:38 [birtles] TabAtkins: let's defer percentages to further discussion on the list and just stick to lengths for now 12:40:44 [birtles] heycam: em units still need a context 12:40:56 [birtles] TabAtkins: you can resolve against a default font size 12:41:01 [birtles] heycam: what about calc? 12:41:09 [birtles] TabAtkins: it's not problematic by itself 12:41:27 [birtles] ... only if one of its components is a length we can't resolve 12:41:45 [birtles] heycam: more discussion is needed on lengths 12:42:05 [birtles] ... particularly for what to do when you don't have a context for resolving against 12:42:10 [birtles] ... what about points on a polyline? 12:42:17 [birtles] krit: yes, since we have that for shapes in CSS 12:43:05 [birtles] ACTION: Dirk to tell the CSS WG that we changed the SVG path syntax 12:43:06 [trackbot] Created ACTION-3356 - Tell the CSS WG that we changed the SVG path syntax [on Dirk Schulze - due 2012-09-24]. 12:43:43 [birtles] ACTION: Dirk to prepare a proposal for supporting lengths/percentages in paths and polylines 12:43:43 [trackbot] Created ACTION-3357 - Prepare a proposal for supporting lengths/percentages in paths and polylines [on Dirk Schulze - due 2012-09-24]. 12:43:56 [birtles] ChrisL: what about element syntax for paths? 12:44:14 [birtles] TabAtkins: I think it's useful 12:46:06 [birtles] ACTION: Chris to produce a proposal for expanded element syntax for paths (including finding the results of testing improved compression ratios with the expanded syntax) 12:46:07 [trackbot] Created ACTION-3358 - Produce a proposal for expanded element syntax for paths (including finding the results of testing improved compression ratios with the expanded syntax) [on Chris Lilley - due 2012-09-24]. 12:47:12 [birtles] cyril: I think it's good to be able to break paths into fragments but not necessarily an element per point 12:47:23 [birtles] ChrisL: it wouldn't be per point but per command 12:48:05 [birtles] heycam: sometimes you don't want to go down to individual commands but just fragments 12:48:16 [birtles] ... it would be nice to use the same mechanism for that 12:48:52 [birtles] shepazu: it would be nice to refer to segments and include them reversed etc. 12:51:34 [birtles] ChrisL: if you have multiple paths and you want to combine those to make one path you sometimes need to reverse a segment 12:51:39 [birtles] shepazu: it would be nice to be able to get the geometry of the reversed version 12:54:21 [birtles] cyril: if we have elements for each command, you'd end up with a lot of DOM nodes 12:54:29 [birtles] ... is it worth having the parse collapse them? 12:54:50 [birtles] TabAtkins: no, you don't want the parser doing that kind of special magic 12:54:54 [birtles] everyone: no magic 12:55:18 [birtles] andreas: what about polar coordinates? 12:55:36 [birtles] heycam: we rejected the request for polar coordinates in transforms 12:56:51 [birtles] ... in place of that we have proposed the turtle graphics which solves many of the cases but not all 12:57:17 [birtles] ChrisL: it reminds me of the syntax used in Raphael which provides a SVG path-like syntax for describing transforms 12:58:30 [birtles] krit: polar coordinates are definitely useful... 12:58:44 [birtles] ... but then the whole coordinate system should be in polar coordinates 12:58:50 [birtles] ... otherwise you have to map them 13:00:27 [birtles] andreas: sometimes you have a series of survey results that are best described using polar coordinates, like a cave 13:00:34 [birtles] ... everything is relative to the last position 13:01:12 [birtles] ... it's typically a series of straight line segments and rotations 13:01:29 [birtles] heycam: that should be possible using the turtle graphics command 13:02:08 [birtles] ... but polar coordinates in general are difficult and we rejected that requirement 13:02:43 [birtles] (description of turtle graphics proposal, the 'r' and 'R' commands) 13:04:15 [birtles] (now talking about Catmull-Rom curves) 13:04:47 [birtles] shepazu: adding a segment affects the previous segment 13:05:06 [birtles] ... and you need two endpoints 13:05:33 [birtles] ... so if you start with a P command (the Catmull-Rom command) you can't draw the curve until you get a second point 13:06:51 [birtles] ChrisL: with regards to the issue of segments affecting the previous segment, if you duplicate the points of the last segment (i.e. a zero-length segment which degenerates to a straight line segment) it won't affect the previous segment 13:07:16 [cabanier] cabanier has joined #svg 13:07:47 [birtles] topic: <image> as paint server for SVG (already resolved to have <gradient>) 13:08:07 [birtles] krit: we already allow <gradient> 13:08:15 [birtles] ... and we resolved how it applies to path elements 13:08:25 [birtles] ... and it's not limited to gradient box (as defined in CSS) 13:09:11 [birtles] TabAtkins: in CSS gradients are infinite 13:09:16 [birtles] ... but they get chopped to their box 13:09:26 [birtles] ... but SVG can define gradients so that extend to infinity 13:09:36 [birtles] ... but other image types can't be trivially extended in the same way 13:10:01 [birtles] ChrisL: in SVG 2 we could also have a painted bounding box (aka decorated bounding box) 13:10:09 [birtles] ... we could use that instead 13:10:30 [birtles] shepazu: i.e. use that instead of the gradient bounding box 13:10:56 [birtles] cyril: but with an image you can say that it only fills 50% of the box 13:11:01 [birtles] ... how do you fill the rest of the object? 13:11:06 [birtles] krit: not at all 13:11:11 [birtles] ChrisL: transparent black 13:11:36 [birtles] TabAtkins: CSS lets you specify repetition etc. 13:11:51 [birtles] ... if we wanted to do that in SVG we'd have to make fill etc. a shorthand 13:12:20 [birtles] ... or we could specify those properties when specifying a paint server (e.g. a pattern) 13:12:33 [birtles] ChrisL: there's another consequence of this painted bounding box 13:12:37 [glenn] glenn has joined #svg 13:12:59 [birtles] ... previously if you had a gradient on a horizontal line you'd end up with nothing unless you special case it 13:13:09 [birtles] ... but if you use the painted bounding box you can get around that 13:13:32 [birtles] krit: what if you have a rectangle that you stroke 13:13:42 [birtles] ... you stroke it with an image 13:13:57 [birtles] ... if you use the geometric bounding box only half the stroke gets painted 13:14:50 [birtles] TabAtkins: what about backwards compatibility about using the painted bounding box 13:15:28 [birtles] shepazu: you'd use the geometric bounding box for existing SVG gradient elements, and the painted bounding box for CSS gradients 13:16:10 [birtles] (discussion about providing a new keyword like objectBoundingBox when defining an SVG gradient so it can use the painted bounding box) 13:16:47 [birtles] TabAtkins: that's important since we also want to be able to use SVG gradients in CSS 13:17:09 [birtles] (discussion about the definition of the decorated bounding box) 13:17:56 [birtles] TabAtkins: when using a CSS gradient function in SVG, do we want stroke to use the painted bounding box and the fill to use the geometric? 13:18:05 [birtles] ChrisL: I'd like to have the flexibility to use both 13:18:21 [birtles] TabAtkins: I think fill should default to geometric and stroke to painted 13:18:48 [birtles] TabAtkins: in summary, we want to expose the ability to switch between geometric and painted bounding boxes 13:19:08 [birtles] ... we will add an optional keyword to the fill/stroke properties to allow switching between the two 13:19:23 [birtles] ... with appropriate defaults for each (specifically fill = geometric, stroke = painted) 13:19:31 [birtles] heycam: what about markers? 13:21:44 [birtles] ... are they included in the calculation of the decorated bounding box (as they are in the DOM method)? it might be less useful when stroking to include markers 13:21:52 [birtles] ... it needs more thought 13:23:52 [birtles] TabAtkins: for stroke, the default is the painted bounding box 13:24:23 [birtles] ... but when referring to an SVG gradient element it will defer to an attribute on the gradient specifying which bounding box to use 13:24:35 [birtles] ... and *that* will default to the geometric bounding box for backwards compatibility 13:24:40 [birtles] ... just like we're doing with maskign 13:24:46 [birtles] s/maskign/masking/ 13:25:13 [birtles] ... for the more general issue of the CSS <image> type... 13:25:38 [birtles] ... if you draw a gradient using the geometric bounding box 13:25:56 [birtles] ... it will size itself using the inner bounding box but it still can extend beyond that box 13:26:13 [birtles] ... the gradients are defined such that they extend infinitely 13:26:18 [birtles] ... then CSS just clips that result 13:26:26 [birtles] ... but SVG might not do that 13:26:59 [birtles] ... what do we do outside the box for other CSS image types 13:27:06 [birtles] ... do we just paint them as transparent black? 13:27:38 [birtles] (other CSS image types being all those other than gradient functions) 13:27:49 [birtles] ... if you want it to repeat, put it in a pattern and use that 13:29:15 [birtles] ... CSS just defines that outside the box you're transparent black unless you use background properties to repeat the image 13:30:08 [birtles] heycam: the alternative is to introduce background-repeat etc. into SVG 13:30:17 [birtles] ... and I'd rather not do that 13:30:28 [birtles] TabAtkins: me too, use patterns for repeating 13:31:54 [glenn] glenn has joined #svg 13:32:45 [birtles] RESOLUTION: We will add a control to fill and stroke to determine which bounding box (geometric or decorated) to use for sizing paint servers 13:33:13 [cyril] for sizing and positioning too 13:33:23 [birtles] RESOLUTION: We will add attribute to the existing paint servers in SVG defaulting to the geometric bounding box (like the maskType attribute) 13:34:09 [birtles] RESOLUTION: When using CSS image types that are finite in extent are expanded to infinity by using transparent black (not by repeating the result) 13:34:31 [birtles] s/extent are/extent, they are/ 13:35:13 [birtles] ACTION: Tab to amend the definition of fill,stroke in SVG to allow the CSS <image> type 13:35:13 [trackbot] Created ACTION-3359 - Amend the definition of fill,stroke in SVG to allow the CSS <image> type [on Tab Atkins Jr. - due 2012-09-24]. 13:36:23 [birtles] heycam: is there a clash since fill,stroke already take a URL but so does the <image> type 13:36:42 [birtles] ... are the mechanics for how you interpret it different? 13:38:00 [birtles] TabAtkins: it should be ok 13:38:06 [birtles] birtles: it's the same for masks 13:38:24 [birtles] ... you have one behavior when you refer to a whole document (a.svg) vs an element within a document (a.svg#mask) 14:03:41 [cabanier] cabanier has joined #svg 14:03:45 [TabAtkins__] TabAtkins__ has joined #svg 14:03:51 [andreas] andreas has joined #svg 14:03:59 [TabAtkins__] ScribeNick: TabAtkins__ 14:04:09 [TabAtkins__] Topic: color interpolation filters for shorthands 14:04:27 [TabAtkins__] krit: Currently we have the color-interpolation property for all filters. 14:04:32 [TabAtkins__] krit: How do we apply it to the shorthand functions? 14:04:56 [TabAtkins__] heycam: Would you normally want to apply it to specific filter primitives? 14:05:33 [TabAtkins__] chrisl: In general you want to do linear, but there are cases where you want to stay in the sRGB as you pass values between, to avoid loss. 14:05:58 [TabAtkins__] krit: For shorthands, we're okay with just using the default colorspace. If you want different shorthands, use the SVG <filter> element. 14:06:31 [nikos] 14:06:34 [krit] 14:07:19 [ChrisL] ChrisL has joined #svg 14:07:24 [TabAtkins__] krit: [lists the shorthand functions] 14:09:20 [TabAtkins__] krit: So, first question, are we okay with saying that the filter shorthands just use the default colorspace? 14:10:11 [TabAtkins__] RESOLVED: Filter shorthands only use the default colorspace (*not* the current value of 'color-interpolation-filters' on the element, either). 14:11:05 [TabAtkins__] krit: Note, obviously, that you can use an SVG <filter> (with color-interpolation set on the <filter> element or the subfilters) and then reference it with url(). 14:11:38 [TabAtkins__] Topic: Perlin noise 14:12:05 [TabAtkins__] krit: Do we want to add a new type of noise function that is easier to hardware-accelerate? 14:12:18 [TabAtkins__] ChrisL: In addition to existing turbulence, or replacement? 14:12:47 [TabAtkins__] TabAtkins__: Addition - too much content already relying on it. 14:12:55 [ChrisL] ok good 14:12:58 [TabAtkins__] ChrisL: Is there a definition for the algorithm that's free? 14:13:21 [TabAtkins__] krit: We need to decide on the new algorithm, with discussion or further research. 14:13:28 [TabAtkins__] ed: I think we discussed Simplex noise before. 14:14:03 [ChrisL] 14:14:29 [ChrisL] Noise Hardware - Ken Perlin 14:14:47 [TabAtkins__] RESOLVED: Add a new type of noise algorithm to the filters spec, for easier hardware acceleration. (Further research for what type, possibly Simplex noise.) 14:16:11 [TabAtkins__] Topic: Need a new filter shorthand for noise? 14:16:31 [TabAtkins__] krit: Often the noise functions are not used standalone - they're used with other filter primitives. 14:17:21 [ChrisL] glsl implementation of Perlin and simplex noise 14:20:33 [ed] here's an example using a bit of turbulence:öm.net/svg/presentations/svgopen2012/presentation/introimage-static-grain-toothpaste.svg 14:20:34 [TabAtkins__]. 14:22:13 [TabAtkins__] ChrisL: I've come across an impl of both classic and simplex noise in glsl, and it says explicitly that both algorithms can be done fine even on low-end (e.g. phone) GPUs. 14:22:55 [TabAtkins__] ChrisL: So why is this a problem that we need to solve? 14:23:24 [TabAtkins__] krit: Based on list discussion, Simplex is a smaller O() complexity, which is of concern with the often-large images that will be used in CSS. 14:23:25 [konno_] konno_ has joined #svg 14:23:33 [ChrisL] ok 14:24:25 [ChrisL] demo 14:25:10 [heycam] ScribeNick: heycam 14:25:39 [ed] the demo chrisl pasted demos 3d-perlin noise I believe 14:25:39 [heycam] TabAtkins__: the filter function in filter effects is of type CSS <image> 14:25:48 [heycam] s/TabAtkins__/krit/ 14:25:56 [TabAtkins__] s/filter function/filter() function/ 14:26:21 [heycam] TabAtkins__: so you can introduce a noise filter shorthand and then use it in the filter function 14:26:40 [TabAtkins__] s/TabAtkins__/krit/ 14:26:54 [heycam] TabAtkins__: my argument is that the filter function as written still takes an <image> as an argument 14:26:56 [heycam] krit: that would change 14:27:01 [heycam] TabAtkins__: if you make that optional it's less troublesome 14:27:07 [heycam] ... I think it's weird that we have no-input filters 14:27:09 [cabanier] filter function: 14:27:12 [heycam] … I think that was a hack in the original SVG 14:27:29 [heycam] … and instead just said "these are not paint servers but some filter primitives" 14:27:45 [heycam] … I am somewhat opposed to extending that confusion into the CSS version of the syntax 14:27:52 [heycam] … if we are producing an image, I would want to produce an <image> directly 14:28:02 [heycam] krit: then you can put this <image> as input to the filter function 14:28:13 [heycam] ed: if you want the same number of parameters that the SVG turbulence has? 14:28:18 [heycam] TabAtkins__: I don't know what's needed 14:28:53 [heycam] TabAtkins__: you would have "filter: noise(…) ..." 14:28:59 [heycam] krit: wouldn't the parser get confused? 14:29:03 [heycam] TabAtkins__: no 14:29:11 [heycam] … the filter function takes the first argument is an image, the next is filter list 14:29:40 [heycam] s/filter: noise(…) .../background-image: filter(noise(…), …)/ 14:29:55 [heycam] krit: you could use this as an input to custom filter primitives too 14:30:03 [heycam] TabAtkins__: so this seems fine to me 14:30:07 [heycam] krit: do we still want to have a shorthand noise function? 14:30:15 [heycam] … and is that in Images or Filter Effects? 14:30:28 [heycam] TabAtkins__: I don't think we do, because it's only a generation 14:30:34 [heycam] … and we can't do tree-based filter chains in the filter property 14:30:51 [heycam] … if we do do that, we can allow <image>s as well as inputs to compositing filters for example 14:31:40 [heycam] … I think making feTurbulence a filter primtiive and not a paint server was a mistake 14:31:56 [heycam] krit: in the end it probably doesn't matter, but yes where do we put it logically 14:32:05 [heycam] TabAtkins__: we should only allow pass through filters in the filter property 14:32:11 [heycam] krit: I agree 14:32:37 [heycam] ed: would we have a corresponding element in SVG filters? 14:32:42 [heycam] … we have feTurbulence 14:32:46 [heycam] krit: deprecate but not drop it 14:32:55 [heycam] TabAtkins__: for filters do we want to correct this historical mistake? 14:33:03 [heycam] … you can't just take a paint server directly, you need to specify bounds to fill 14:33:13 [heycam] krit: we could use feImage taking CSS <image> as well 14:33:18 [heycam] ed: I think it would be handy to have in SVG filters too 14:33:59 [heycam] ed: I don't mind if it's a new primitive or an 'image' referenced from <feImage> 14:34:10 [heycam] ed: a new in="" value? 14:34:18 [heycam] TabAtkins__: you just need to combine a paint server with a rect 14:34:36 [heycam] krit: in general, we need to redefine in and in2 14:34:45 [heycam] … to have CSS <image>s as input in there is fine 14:35:58 [heycam] TabAtkins__: you can't use colors in there 14:36:04 [heycam] .. because "blue" might be a name of a result 14:36:22 [heycam] … the <image> function in CSS can produce solid colors 14:36:27 [heycam] … image(blue) 14:36:44 [Cyril] Cyril has joined #svg 14:36:57 [heycam] krit: feImage still has subregion clipping 14:37:49 [heycam] … you could use media fragments for selecting the region, but there's no way to do preserveAspectRatio 14:38:01 [heycam] krit: a question about the noise function, how do you define the size of it? 14:38:05 [heycam] TabAtkins__: I would do the same as gradients 14:38:13 [heycam] … it's sized into the box it's drawn into 14:38:19 [heycam] … it has no intrinsic size 14:38:27 [heycam] … in SVG's case, it can still do an extension out to infinite case 14:38:40 [heycam] ed: one complication is having tiling 14:38:50 [heycam] … if you tile the noise function without stitchTiles you can see the tile edges 14:39:40 [heycam] TabAtkins__: any primitive tiling mechanisms will cause discontinuities at the edges of tiling 14:39:47 [heycam] … unless you tell the noise algorithm to stitch the edges 14:39:56 [heycam] ChrisL: we shouldn't be padding noise out, just which region we really want to cover 14:40:05 [ed] 14:41:12 [heycam] krit: primitives are always clipped to the filter region 14:41:19 [heycam] … if you have feOffset you can reach the edge of the noise function 14:41:42 [heycam] TabAtkins__: we should just generate noise at whichever pixels are going to be touched 14:42:48 [heycam] ACTION: Dirk to look into allowing CSS <image> values in in="" and in2="" 14:42:48 [trackbot] Created ACTION-3360 - Look into allowing CSS <image> values in in="" and in2="" [on Dirk Schulze - due 2012-09-24]. 14:43:00 [heycam] ACTION: Tab to work with Dirk to spec out a noise() <image> value 14:43:00 [trackbot] Created ACTION-3361 - Work with Dirk to spec out a noise() <image> value [on Tab Atkins Jr. - due 2012-09-24]. 14:43:37 [heycam] TabAtkins__: some things need the size you're drawing into 14:43:50 [heycam] … CSS gradients need to know how big their box is before drawing 14:44:05 [heycam] … media fragments don't apply to most CSS <image>s, just url() images 14:45:13 [heycam] ed: for SVG I would like to have 3D noise and to be able to connect the time domain to the third dimension 14:45:18 [heycam] … so you can have continuous effects 14:45:29 [heycam] … with feTurbulence it can move things in x and y, but you can't really have a fire/plasma effect 14:45:34 [heycam] krit: I'd suggest using shaders for that 14:45:38 [heycam] ed: you couldn't implement it that way 14:45:45 [heycam] …but it would be nice to have filter primitives for that 14:45:52 [heycam] krit: do we really want 3d noise? maybe, don't know. 14:45:57 [heycam] … is simpled 2d or 3d? 14:46:05 [heycam] ed: you can extend it to how many ever dimensions 14:46:13 [heycam] … I think that would be really nice to have 14:46:24 [heycam] … I want to allow that when we go with <image> generation, so we can animate the timing 14:46:57 [heycam] TabAtkins__: the CSS <image> type is now animatable, in Images 4 14:47:02 [heycam] … there's a generic animation type that does a cross-fade 14:47:10 [heycam] … but cross-fade and gradients animate argument-wise 14:47:16 [heycam] … so that's fine to have animation of noise() 14:47:34 [heycam] ed: Chris' link earlier shows the 3d noise animation 14:49:34 [heycam] shepazu: when we're talking about stitching, does this also apply to Tiling & Layering? 14:49:54 [heycam] TabAtkins__: just if you're using a noise function of a certain noise, or inside a pattern element that ends up being repeated, you need to tell the algorithm to make sure the edges tile well 14:51:09 [heycam] Topic: Masking issues 14:51:16 [heycam] krit: we said we wanted to have attribute maskType for <mask> 14:51:31 [heycam] … that says you specifically want to use this mask with alpha or luminance 14:51:35 [heycam] … do we want to make this a presentation attribute 14:51:55 [heycam] ed: why would you want to? 14:52:06 [heycam] krit: we already define mask-type for CSS masking 14:52:44 [heycam] heycam: so this would just use the same attribute/property on both the <mask> and the thing being masked 14:52:45 [krit] 14:52:45 [heycam] krit: yes 14:53:05 [heycam] krit: second question is if you use maskType="" as we currently defined it, it's camel case 14:53:15 [heycam] … which HTML editors don't want, because they need to special case it for the parser 14:53:21 [heycam] … I have no problems if they need to special case it 14:53:52 [heycam] ChrisL: the reason we had camel case was we originally had hyphenation, and the DOM people requested camel casing 14:54:42 [heycam] shepazu: if I'm converting from a property name to a DOM name, removing the hyphen is trivial, adding the camel-cased letter is kind of trivial with regex, but... 14:54:44 [heycam] krit: still trivial 14:54:50 [heycam] … the only problem is HTML is not case sensitive 14:55:02 [heycam] shepazu: could we go to all lower case? 14:55:56 [heycam] TabAtkins__: you would need to define what happens if you accept both camel case and lower case 14:56:05 [heycam] TabAtkins__: I'm fine with all lower case or keeping camel case in attributes 14:56:09 [heycam] … updating the list isn't a big deal 14:56:37 [heycam] … given every implementation just has a list of attribtues with cases, it's easy to update 14:57:42 [heycam] heycam: I'm slightly concerned that the case in the DOM changes after the parser is updated 14:58:16 [heycam] TabAtkins__: that's only a problem if people try to use the feature before implementations add the feature 14:58:32 [heycam] … you could define that with conflicting case names, just use the last one … that's what the HTML parser does 14:59:46 [heycam] TabAtkins__: maybe we should keep camel case, because when you are using the property with CSS, you use camel case in the DOM 15:00:08 [heycam] heycam: have the presentation attribute be camel case for a hyphenated property name? 15:01:22 [heycam] TabAtkins__: dashes are hard for the DOM, but we could accept hyphens too 15:02:09 [heycam] krit: it's easy in WebKit to have the dashed version of the presentation attribute 15:02:13 [heycam] …we just pass that to the CSS engine 15:02:31 [heycam] heycam: if it's going to become a presentation attribute, it should be mask-type not maskType 15:02:40 [heycam] krit: so do we want it to become a presentation attribute / property? 15:02:47 [heycam] TabAtkins__: I think we do 15:03:17 [heycam] birtles: just wondering when you'd want to set mask-type on <mask> with a style sheet 15:03:27 [heycam] TabAtkins__: you could set all <mask> elements to alpha with a style rule 15:03:28 [heycam] birtles: ok 15:04:36 [heycam] heycam: is it confusing that mask-type means slightly different thinks applied to <mask> and masked elements? 15:08:40 [heycam] TabAtkins__: we could merge in the "alpha" or "luminance" back into mask-image 15:08:44 [heycam] … instead of the separate mask-type 15:08:51 [heycam] … and just use mask-type to apply to <mask> 15:09:45 [heycam] birtles: I'd rather this 15:09:53 [heycam] TabAtkins__: and I think it's fine to think of the alpha-ness of luminance-ness as part of the image 15:11:21 [heycam] [discussion about changes to serizliation and computed values for -webkit-mask] 15:12:10 [heycam] RESOLUTION: mask-type now only applies to <mask>, and the [ alpha | luminance | auto ] goes in the mask-image value 15:12:31 [heycam] krit: next problem is related 15:12:38 [heycam] … mask-image has syntax like background-image 15:12:40 [heycam] … so it clips to a region 15:12:57 [heycam] … we have a predefined clipping regions border-box, content-box and padding-box 15:13:01 [heycam] s/have a/have/ 15:13:15 [heycam] … I would suggest defining for SVG that border-box means painted rectangle 15:13:28 [heycam] heycam: what's the default? 15:13:46 [heycam] TabAtkins__: border-box 15:14:23 [heycam] ed: if you ahve an SVG inline in HTML, you might want the actual border-box of the outer <svg> 15:14:28 [heycam] TabAtkins__: yes it should mean that on the outer <svg> 15:14:30 [heycam] s/ahve/have/ 15:16:14 [heycam] TabAtkins__: padding-box should map to normal bounding box 15:16:18 [heycam] krit: that's what it is currently 15:17:05 [heycam] RESOLUTION: {border-box, content-box, padding-box} should map to {painted bbox, normal bbox, normal bbox} for mask-clip 15:17:17 [heycam] ed: would you ever want to have a box that includes the filters? markers? 15:17:19 [heycam] krit: we need to discuss this 15:17:28 [heycam] … I'd rather no, because we would do this masking on the gpu 15:17:43 [heycam] heycam: markers are already included in border-box 15:21:59 [heycam] TabAtkins__: if you have a drop shadow applied to an element, then using mask-clip will clip that away 15:22:59 [heycam] krit: the old mask property still works the same way 15:23:16 [heycam] … the url() references <mask> and can still have x/y/width/height on it 15:26:18 [shepazu] 15:26:49 [ed] RRSAgent, make minutes 15:26:49 [RRSAgent] I have made the request to generate ed 15:37:26 [cabanier] cabanier has joined #svg 15:42:17 [cabanier] cabanier has joined #svg 15:44:43 [konno_] konno_ has joined #svg 16:04:39 [shepazu] shepazu has joined #svg 16:09:10 [krit] krit has joined #svg 16:15:02 [jet] jet has joined #svg 16:30:31 [jarek] jarek has joined #svg 16:31:18 [Zakim] Zakim has left #svg 16:56:09 [konno] konno has joined #svg 17:32:35 [cabanier] cabanier has joined #svg 18:21:10 [thorton] thorton has joined #svg 19:00:45 [victor] victor has joined #svg 20:56:12 [shepazu] shepazu has joined #svg 21:50:20 [cabanier] cabanier has joined #svg 21:52:27 [krit] krit has joined #svg 23:39:41 [glenn] glenn has joined #svg
http://www.w3.org/2012/09/17-svg-irc
CC-MAIN-2015-14
refinedweb
13,317
57.84
NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab. Microcontroller Programming » 4 Digit 7 Segment LED Display Hello All, I am new to the world of programming with a Nerdkit therefor I have a lot to learn. I have run into a road block on my latest project and although I have made some progress in the right direction I feel as though I am at a lose with where to go next. To give you a brief description of my project, I simply would like to display time on a 4 digit LED Display. I did a test run and I was able to display a two digit number on two different 7 Segmented LEDs. I run into my problem when I try to use a 4 digit display. After a little bit of research I found out that I am to use the SPI Bus. I tried to mimic what was done in the multi-LED array project with no success. I wanted to know if anyone can guide me in the right direction with what to do? I found two different data sheets for this display. Here is one for the chip that drives the display and this is all I could find on the display itself This is as far as I have gotten in my code. // // FourDigitDisplay.c // // // Created by Sean on 9/7/13. // // #define F_CPU 14745600 #include <stdio.h> #include <avr/io.h> #include <avr/interrupt.h> #include <avr/pgmspace.h> #include <inttypes.h> #include "../libnerdkits/delay.h" #include "../libnerdkits/uart.h" // PIN DEFINITIONS: // Red Rail Pin 1 on Display // PB5 - SCK Pin 3 on Display // PB4 - MISO Pin 5 on Display // PB3 - MOSI Pin 4 on Display // PB1 - SS Pin 2 on Display // Blue Rail Pin 6 on Display logic high (slave not active) to low to activate it PORTB &= ~(1<<PB1); } int main() { //ledarray_init(); master_init(); // activate interrupts sei(); // init serial port uart_init(); FILE uart_stream = FDEV_SETUP_STREAM(uart_putchar, uart_getchar, _FDEV_SETUP_RW); stdin = stdout = &uart_stream; while(1) { //this loop never executes, scrolling display should loop forever in this mode of operation //everythign exciting happens in the interrupt handler, and in do_scrolling display } return 0; } I tried experimenting with sending info to the display but im really not sure how to do it. If I could be pointed in the direction of how to light up even one segment Im sure I could figure out the rest. thanks Sean Hi Affarram, I have used this type of display as part of one of my projects. You can take a look at this and this. The code is for Energia but it should be compatible with Arduino/AVR. -Raja Balu Hi Sean - From a quick look through the data sheet, that's an interesting driver chip. Seems to be overkill for your application but if it came with the LED module I guess it can do some of the work for you. The wiring should be fairly straightforward, common and 5v are obvious, DIN (from your second link above) should go to MCU pin 18, CLK to MCU pin 19, and CS to MCU pin 16. If we assume the PT 6961 chip is wired correctly to the LEDs the first step would be to initialize the 6961 chip. I'm pretty sure the CS pin in the LED picture is actually the strobe pin on the actual 6961 chip so you can use the terms as the same so we can call it STB from now on. If you're at the stage where you can control the 2-segment LED, you'll know how to make the STB/MCU pin 16 high in your initialize routine and to make it low before each command or data sent to the 6961 (and high afterward). SPI is very easy to use, first set the byte you want to send in the SPDR register and wait. The whole sequence is here... PORTB &= ~(1<<PB2); // pull the STB line low SPDR = data_to_send; // upload data while (!(SPSR & (1<<SPIF))); // wait for data to be transferred PORTB |= 1<<PB2; // set STB line high Once you are sure that works, follow the flow chart on page 13 of your first link to send commands and data to the 6961 chip. Hope this helps, be sure to update your progress/road blocks. Please log in to post a reply.
http://www.nerdkits.com/forum/thread/2782/
CC-MAIN-2019-35
refinedweb
733
76.45
It’s possible to explain Simple Object Access Protocol (SOAP) communication principles using existing Web technologies like JavaScript, HTML forms, and Perl CGI. The obvious drawback to this approach is that SOAP-like messages don’t have the proper SOAP syntax—it’s a nonstandard solution. XML syntax is the correct syntax for SOAP messages. SOAP is XML and HTTP SOAP messages are just plain old XML files. XML provides the syntax that lets you use different varieties of markup. Instead of an <html> tag, the SOAP specification describes an <envelope> tag. In order to make a SOAP request, three sets of tags are required. Once the tags are assembled, combine them into a document. This document is the SOAP message. Finally, the message must be sent somewhere. Almost certainly you’ll want to send not one but two messages: a request-response pair. One is a ”please work on this data” message, and the other is a “here’s what I did to it” message. The SOAP standard uses HTTP for the request-response message pair—sending SOAP data is no different than loading a Web page or submitting a form. Later I’ll examine how using HTTP affects the content sent over the Internet between Web browser (or request client) and Web server (or response server). First, I’ll take a closer look at a SOAP transaction. The sample SOAP transaction In an earlier SOAP icebreaker article, three pieces of information were sent to the server: name, age, and hair color. One piece of information was returned: a description of the person in the form of a sentence of text. Let’s take a look at an example: - · A person: name (John Doe), age (21), and hair color (Brown). - · A sentence description: John Doe is a young brunette. Easy. Now write both down again in simple XML and call these send.xml and recv.xml: send.xml: <person> <name>John Doe</name> <age>21</age> <color>Brown</color> </person> recv.xml: <description> John Doe is a young brunette </description> Except for some careful revision of the syntax, both SOAP messages are finished. It’s really only the buckets of official syntax that disguise the simplicity of SOAP. You need to tidy up (read: put all the junk in) these SOAP messages. Polishing request and response messages The main problem with the initially constructed messages is that all of the syntax comes out of thin air. There’s no hint that the messages are XML, and there’s certainly no hint about what the various tags infer. Improve the send.xml message in this way: <?xml version="1.0" ?> <p:person xmlns: <p:name>John Doe</p:name> <p:age>21</p:age> <p:color>Brown</p:color> </p:person> Using XML namespaces (xmlns), I’ve identified all the tags as belonging to some “p” collection of tags called “.” If the sender and the receiver of the message both understand the collection, the message is meaningful. But where does that collection of tags originate? That collection of tags is specified in another XML file. That file is full of tags from the XSchema standard. The XSchema standard is a way of describing new tags, such as <person>. Since I invented the <person> tag, I have an Xschema document defining what that <person> tag looks like. It’s confusing, but all XSchema documents end (by convention) with .xsd, not .xml, and the .xsd extension is left off when the schema is referred to. So htttp://saturn.test.com.au/2002/person is a person.xsd file, which is just an XML file. It looks like Listing A. The programmer creates this XML file. It refers to another XML file, the one at “.” It’s written for you by the standards body, so there’s nothing to do except use it every time you make a schema file like person.xsd. XSchema defines the second set of tags needed. The <element> tag is the primary one. This person.xsd file uses two <element> tags to define the <person> and <description> tags in my example. There’s quite a bit of detail in this schema file, but what’s important to note here is that all message tags are defined, and all the tags have types. For example, the <age> tag is of type=”positiveInteger”, and it can only appear inside a <person> tag. Data types are important because SOAP messages usually send data, not free text. Even the simple response message (<description>), which could be free text, is instead nominated as a string. Put the requests into a SOAP envelope Creating a SOAP message is a bit like writing and mailing a letter. Once you’ve created a SOAP message, put it in a SOAP envelope and write instructions on the front. Here’s what a SOAP envelope looks like: <Envelope> <Header> ... </Header> <Body> ... </Body> </Envelope> The ellipses (three dots) indicate where the letter and other content goes. Of course, this piece of XML is as lazy as the first send.xml, so clean the syntax up a bit: <?xml version="1.0" ?> <env:Envelope xmlns: <env:Header> </env:Header> <env:Body> </env:Body> </env:Envelope> This is the third set of tags you’ll need. The <Envelope>, <Header>, and <Body> tags (case-sensitive!) are all specified for you by the SOAP standard—they describe the pieces of the envelope that surrounds the SOAP data, even though the envelope is technically separate from the data you’re actually trying to send. The whole thing is called a “SOAP message.” Now let’s put the message in the envelope, as shown in Listing B. Three “xmlns” XML namespace declarations for the three collections of tags are used in the message: two visible above (one is repeated), and one in the person.xsd file. But what’s the <p:control> tag? As well as putting the data into the envelope, you can take advantage of the SOAP header features. Attaching SOAP’s “mustUnderstand” attribute to the <p:control> tag indicates to the receiver of the message that the message must be intelligently processed or else fail totally. The <control> tag is a new tag created just to carry that attribute. Add it to the person.xsd schema, perhaps like this: <schema:element <schema:complexType> </schema:complexType> </schema:element> There’s an XSchema trick here that stops the <control> tag from carrying any content—it resembles an <hr> tag in HTML. Now the SOAP message is complete. If you do all that for the other message, it’ll look like Listing C. All that remains is to send these two messages. Binding the SOAP messages to HTTP HTTP is responsible for sending SOAP messages back and forth. It’s the equivalent of a postman carrying the SOAP envelope in his hand to the destination. If you want to send a SOAP message from some programming language, like Perl, Java, or C++, then no browser is involved. You need to know what HTTP headers to use for the request. Here’s what you need for the final send.xml: POST /transactions/AnalysePerson HTTP/1.1 Host: jupiter.test.com.au Content-Type: application/soap; charset="utf-8" SOAPAction: "" Content-Length: 447 The SOAPAction header is optional and sort of a cheat. It tells the receiving system how to handle the incoming message without requiring the receiver to look inside and deduce the content is SOAP content. If a SOAP server is ready to use, you just need to determine if the server adds anything when this header is present. Of course, the headers for the recv.xml SOAP message will start: HTTP/1.1 200 OK Content-Type: application/soap; charset="utf-8" Content-Length: 406 This is because the recv.xml message is returned inside a HTTP Response that matches the POST HTTP Request. SOAP messages can be composed and sent by modern browsers, so you might expect the list of HTTP headers to be a little larger. From a browser, it doesn’t matter what all the headers are, but for completeness, a genuine, fully compliant SOAP request from a client might look like Listing D. In the end, the same three pieces of information are sent (name, age, color), but a lot of extra junk is passed with it. That’s the price of the flexible, character-based HTTP and XML standards. Seal the envelope SOAP is a system for passing messages between programs, and the syntax is very straightforward. As long as you remember that the central task is just to define the tags that add structure to the data you send, all the rest is just a load of tasteful Christmas-tree decoration. Don’t be fazed by it. If your ambition leads you to work with SOAP extensively, the best thing you can do is study the SOAP and XSchema standards.
http://www.techrepublic.com/article/a-soap-syntax-breaker/
CC-MAIN-2017-30
refinedweb
1,482
65.32
. Update: Add expression: HorScale/VerScale to get scaled value. For example, HorScale(-10,10) will return (-10 + HorPercent*(10-(-10))). The idea is comes from this thread. Thank for your works I have a question I download your C2 repository application but the news plugins not appear is abandoned? Uh, I edit expression: HorScale/VerScale. Now user could assign felixsg Uh, just have not upload yet. I will update all later. tnx Rex...i was getting worried :)))) Update Support official save/load feature. Is this behaviour more CPU consuming than me setting up an "Every 0.05 seconds, check if object.y < 500 IF yes then set object.y to 501 " Thank you rexrainbow, probably the awesomest human being in the world... Is this behaviour more CPU consuming than me setting up an "Every 0.05 seconds, check if object.y < 500 IF yes then set object.y to 501 " Thank you rexrainbow, probably the awesomest human being in the world... Yes, this behavior check the position every tick, so that it will consume more CPU power. Rewrite this document. Now this behavior could clamp the position in the boundary, or wrap the position to the other side of boundary. rexrainbow - awesome behavior! I also like how if you are moving the boundary that the objects stay locked inside. Develop games in your browser. Powerful, performant & highly capable. Add "Expression:HorPercent2PosX" / "Expression:HorPercent2PosY" - Get position X/Y from percentage (0-1) of horizontal / vertical boundaries by "Expression:HorPercent2PosX" / "Expression:HorPercent2PosY". Sample capx Hey rex, is there a way to force the boundary rules for an object if setting its x and/or y position directly? — You could move the object by dragdrop behavior or setting position directly now, this boundary behavior will clamp or wrap the position. rexrainbow Im having trouble with pinned objects ignoring the behaviour.
https://www.construct.net/en/forum/extending-construct-2/addons-29/behavior-boundary-47700
CC-MAIN-2020-45
refinedweb
307
60.72
How to Write Feasibility Report and Project Appraisal Report Project Appraisal Reports - Investing in Port Introduction, How we will do it- the plan, Phase I The target market, Phase II The Evaluation of InvestmentPhase III Identification of Key performance Indicator (KPI) Bottlenecks to growth and developments Phase IV Restructuring and Re-engineeri - Real Estate Development Detail Plan for Healthcare City Pune - Healthcare City Saudi Arabia This brief project description om the Healthcare City Project to be developed in Saudi Arabia - Islamic Finance Market 1. Definition of Financial Market 31.1. Financial Market Instruments 4Capital Markets 4Financial Instruments 4Negotiability of Financial Instruments 5Role of the Primary Market 5The Role of the Secondary Market 62. Islamic Approach for the Financial - Islamic Bank Business Plan Islamic Bank, Business Plan, Sustainable, Ethical and Transparent, Planning for Customer Needs - Feasibility Report Biotech and IT Park Global economic uncertainty make it imperative that GCC countries should develop competitive, diversified economies, To diversify local economy To increase high end employment opportunities for the national To develop Knowledge based economy for t - Feasibility Report Real Estate Brokerage Feasibility Report of Real Estate Brokerage Services in GCC. Real estate is very big and one of the most important industry. Even though this industry is Growing, the services related to this industry are that growing at the same pace and there is en - Investing 2010 Geography of Growth Investing in 2010 new perspecive, regional potential, India, Indonesia, Brazil, Saudi Arabia, Russia, Malayisa has strong growth potential Project Appraisal Report Feasibility Report and Project Appraisal 1) General Information a) Name b) Constitution and sector c) Location d) Nature of industry and product e) Promoters and their contribution f) Cost of project and means of finance 2) Promoters Details 3) Market Feasibility Report a) Segments b) Competition c) Pricing d) SWOT Analysis e) Marketing and Selling Arrangements 4) Particulars of the Project a) Product and Capacity b) Plant and Machinery c) Raw Material d) Utilities 5) Technical Feasibility Report a) Technology b) Alternatives c) New Developments d) Competing Technologies e) SWOT Analysis of technology f) Technical Arrangement 6) Production Process 7) Environmental Aspects 8) Schedule of Implementation 9) Financial Feasibility a) Cost Details b) Working Capital c) Means of Finance d) Profitability Estimates e) Assumptions f) Projections i) Projected Income Statement ii) Projected Balance Sheet iii) Projected Cash Flow Statement iv) Coverage Ratio’s v) Break Even Analysis 10) Economic Consideration 11) Appendices a) Depreciation Schedule b) Repayment, interest schedule of term loan and bank finance c) Working Capital and margin money for working capital schedule d) Tax Computation e) Details of Plant and Machinery f) Requirement of skilled and unskilled labor g) Cost of Project Details Aspects of Project Appraisal - Market Appraisal. - Technical Appraisal. - Financial Appraisal. - Economic Appraisal. - Market Appraisal. The market appraisal is attempted to answer two important questions. (i) What is the size of the total market for the proposed product or service? (ii) What is the product's share of total market? Two answer the questions market analyst complies and analysis the date relating to the following aspect. (a) Past & present trends. (b) Present and prospective supply position. (c) Level of imports and exports. (d) Structure of competition. (e) Price and cross elasticity of demand (f) Consumer requirements. (g) Production constraints. - Technical Appraisal. (i) Availability of the required quality and quantity of raw material. (ii) Availability of utilities like power and water etc. (iii) Appropriateness of the plant designs and layout. (iv) The proposed technology vis a vis alternative technologies available. (v) Optimality of scale of operations. (vi) The technical specifications of plant and machinery in relation to the proposed technology. (vii) Assembly line balancing. (i) Cost of project (ii) Means of financing. (iii) Projected Revenue and cost. (iv) Pay back period. (v) NPV (vi) Rate of return. (vii) Internal Rate of Return. (i) Impact of the project one the distribution of income in the society. (ii) Impact of project on the level savings and investment in the society and socially desirable objectives like self sufficiently, employment etc. (iii) Contribution of project. Assessing project feasibility – Market. (i) Selecting target market. (ii) Measuring selected market. Measurement of target market (i) Demand (ii) Supply (iii) Distribution. (iv) Prices. (v) Government Policies. Assessing Project Feasibility – Technical (i) Selection of technology. (ii) Manufacturing process. (iii) Estimation of Inventory requirement. (a) Raw Material Survey. (iv) Selection of equipment. (v) Plant Layout. (vi) Plant Capacity (a) Installed capacity. (b) Capacity Utilization. (vii) Utilities – Availability. (a) Water (b) Electricity (c) Other Utilities. (viii) Estimation of manpower needs. (ix) Estimation of Building needs. (x) Selection of project location. (a) Nature of land. (b) Nature of raw material. (c) Utilities (d) Effluent disposal. (e) Transport. (f) Labour. Implementation Schedule. 4. Assessing Project Feasibility. Financial Projections (i) Cost of Project. Land and site develiopment. (a) Availability of investment subsidy. (b) Availability of concessional finance. (c) Sales tax determents/exemptions. (d) Income tax benefit. Building and civil works. (a) Basic cost of indigenous machines. (b) Basic cost of imported machines. (c) Duties on indigenous machinery. (d) Duties on imported machinery. (e) Other expenses – erection charges etc. (iv) Miscellaneous fixed assets. (v) Preliminary expenses (2.5% of cost of project) (vi) Preoperative expenses. (a) Promotional expenses. (b) Organizational and training cost. (c) Rent, Rates, taxes. (d) Travelling expenses. (e) Postage, telegrams and telephone expenses. (f) Printing and stationery expenses. (g) Advertisement expenses. (h) Guarantee commission. (i) Insurance during construction. (j) Interest during cons. period. (vii) Provision for contingencies. (a) Firm Cost – 5% (b) Non Firm cost – 10% (viii) Technical know how fees. (ix) Margin money for working capital. (x) Means of finance. (a) Equity capital (b) Performance capital. (c) Debenture capital. (d) Term loan. (e) Deferred credit. (f) Unsecured loans and deposits. (g) Capital subsidy and development loans. (xi) Fixing Means of finance. (a) Debt-equity ratio (b) Promoters contribution. (xii) Sales Estimation (a) Cost of production (b) Product mix (c) Installed capacity (d) Capacity utilization. (xiii) Elements of cost of production. (a) Raw materials (b) Chemicals. (c) Components. (d) Consumables. (e) Total raw material cost (a)+(b)+(c)+(d) (f) Utilities (g) Power (h) Water (i) Fuel (ii) Total utilities (e)+(f)+(g)+(h) (j) Wages (k) Factory supervision and salaries. (m) Bonus and PF (iii) Total Labour (i)+(j)+(k) (o) Repairs & maintenance (p) Light (q) Rent & taxes on factory. (r) Insurance on factory assets. (s) Packing material. (t) Miscellaneous factory overheads. (u) Contingency at 5%. (iv) Total factory overheads ( o to u) (v) Cost of manufacturing/operating cost (i) + (ii) + (iii) + (iv) (vi) Total Administrative expenses. (vii) Total sales expenses. (viii) Royalty and know how payable. (ix) Total cost of production (v) + (vi) + (vii) + (viii). 4. Assessing Project Feasibility - Financial Appraisal. (i) Cost & benefits are measured in terms of cash flow i.e. cash in flow and cash outflow. (ii) Evaluating projects in terms of costs and benefits is based on marginal or incremental cash flows. The marginal or incremental cash flows. The marginal cash flow is the change in total firm cash flow from adopting that investment. (iii) As already mentioned n (i) above cash flows are always measured in post tax terms as that represents net flow from the firm point of view. (iv) Focus should be on long term funds. (i) Present value. (ii) Internal rate of return (simply rate of return). (iii) Payback period. (iv) Accounting rate of return. (v) Debt service coverage ratio. (vi) Benefit cost ratio. The present value of a cash flow is, flow what it worth in today. It states that an investment should be adopted only if the present value of the cash it generates in future exceeds its cost. NPV = Present value of cash flow – Initial cost. = CF1 (PVIF,K,I)+------------------- Internal Rate of Return – An internal rate of return is the rate we expect to earn on an investment of project. IRR is that rate which discounts a projects cash flow to an NPV=0. CF CF CF 0 = ----- + ----- + ------- ------ - I 1+r (1+r)2 (1+r)n = CF(PV1FA,r,n) – I The pay back period measures the length of time required to recover the initial investment on a project. ACCOUNTING RATE OF RETURN – The accounting rate of return (ARR) equal the average annual after tax accounting profit generated by the investment divided by the average investment. average annual profit ARR = ------------------------------ (1 – s) 2 DEBT service coverage ratio – The capacity of the project to meet the interest payment and principal repayments on time. 1 n PA Tt + Dt + It DSCR = --- S ------------------------ n t=1 It + Lt PA Tt = Profit after tax in year t. Dt = Depreciation charge in year t. It = Interest on long term loans in year t. n = Period over which the loan has to be repaid. Benefit cost ratio (BCR) PV BCR = ------ I BCR = Benefit Cost Ratio PV = Present value of future cash flows. I = Initial investment BCR > 1 NBCR > 0 Accept BCR < 1 NBCR < 0 Reject Break Even Point. The point at which the entire fixed costs are covered. Fixed Cost BEP = ----------------------------------- Sales price - variable cost Fixed cost = ----------------------- Contri bution POINTS TO BE DISCUSSED 1. Debt Equity Ratio – Chaebol Korea/BPL 2. Rate of interest/Subsidy/optional sources-Enron/BPL 3. Working capital management/Bajaj/SME main problem. Repayment cycles 30/60/90 4. Turn around – Restructuring i. Steel industry in India ii. Daewoo iii. SME Project Project Finance More by this Author -... - 2 What Is a Project? Introduction The first stage in developing an understanding of project management is to define what a project is and, by contrasting with other production systems, what a project is... Dear Zia Ahmed Khan, Good morning, Hope u are fine. Thanks for the information you have provided in the MARKET FEASIBILITY REPORT, which i have submit to my company. I will do my best as per the points to include. Very informative and you have enlightened my knowledge, Thank you Sir, Allah Kareem!!!my mail id: jk_navin@yahoo.com Gud information These are good points on writing a good feasibility report. I also found this link helpful:... Dear Sir,We are running an NGO. Pl.send us a detailed feasibility study project report for study purpose on any product/process.Thanks. We are running an NGO.Pl.send us a feasibility report/study to manufacture plastic bottles. We also offer you any computerization of priject finance work free of cost for your free delivery to self employment programmes / NGOs all over the world.Thanks. It was good to come through such a knowledgeable article .. made life easier for me. Iam very happy to come across something educative like this online.if u think education is expensive pls try ignorant.iam pleased with the content and the mode it was analysed.pls keep it up may God be with u. I'm on an assignment work. your hub made my life structured as I came across. Thanks It is quite pleasure to be informed with various knowledgeable thinks. Thanks lot to hubpage. this is execellent definitely good I so much apreciate this...because it reduces my stress. this is very useful info thank you hub, please keep this spirit growing. Cheers Project feasibility...just thinking about it makes my head aches. Good I come across to this article. Great hub...very helpful! Thanks Zla Ahmed Khan... Great post here...Very informative hub. Project feasibility report is a tough task, thanks for the tips and infos. Great Hub!!!!!! The hub is explicitly dedicated to project feasibility report. The hub is focused towards decreasing the ratio or rich and poor. The hub contains excellent information regarding budding entrepreneurs. I await your future hub with great curiosity. Keep on Hubbing assalaamalaikum, Very good information for budding entrepreuners, THANKS and best regards, Athar Good hub giving outlines for project feasibility report. For mega project, social appraisal is the main document. Unfortunately, social appraisal is not as objective as financial appraisal. Therefore, there are certain guidelines to gauge impact of project in reduction of rich:poor gap: Are the sponsors new, is the location an underdevelopment area, number of people employed, number of people benefitted indrectly? Is raw material local, Is machinery locally manufactured. Is product new or traditional. A yes to all such questions reflects favorably on poverty reduction. 24
http://hubpages.com/business/How-to-Write-Feasibility-Report-and-Project-Appraisal-Report
CC-MAIN-2016-50
refinedweb
2,041
52.15
You can subscribe to this list here. Showing 14 results of 14 > I will change the setup to have both interfaces served by Jetty. I attach a patch to org.exist.StandaloneServer. It removes the xmlrpc listener on port 8081. Instead, xmlrpc requests are now also handled by the minimal Jetty server configured in the class. This means that the base xmldb uri to access the db changes from: xmldb:exist://localhost:8081 to xmldb:exist://localhost:8088/xmlrpc Please tell me if this fixes your port problem. If it does, I will commit the change to the CVS. 24= 0 > seconds and then disappear, but this is too long. when I use the REST > interface I only get a single port which is what I would expect. This seems to indicate a bug in the xmlrpc library. When running stand-alone, xmlrpc requests are directly handled by the xmlrpc lib. The REST interface is going through Jetty. I will change the setup to have both interfaces served by Jetty. Wolfgang I'm new to XML:DB, so please bear with me. I took the Adding a document example from the documentation page, and modified it slightly for my environment. I get a NullPointerException on col.storeResource(document); I've tested f, document, and col for null, and none of them are. Any suggestions? Thanks, Mano Marks import org.xmldb.api.base.*; import org.xmldb.api.modules.*; import org.xmldb.api.*; import javax.xml.transform.OutputKeys; import org.exist.xmldb.XQueryService; import java.io.File; public class StoreExample { public final static String URI = "xmldb:exist://localhost:8084/LibraryWeb/db";; public static void main(String args[]) throws Exception { String collection = "db", file = "C:\\LibTestFiles\\hamlet.xml"; // initialize driver String driver = "org.exist.xmldb.DatabaseImpl"; Class cl = Class.forName(driver); Database database = (Database)cl.newInstance(); DatabaseManager.registerDatabase(database); // try to get collection Collection col = DatabaseManager.getCollection(URI ); if(col == null) { // collection does not exist: get root collection and create // for simplicity, we assume that the new collection is a // direct child of the root collection, e.g. /db/test. // the example will fail otherwise. System.out.println(URI + collection); Collection root = DatabaseManager.getCollection(URI); CollectionManagementService mgtService = (CollectionManagementService) root.getService("CollectionManagementService", "1.0"); col = mgtService.createCollection(collection.substring("/db".length())); } // create new XMLResource; an id will be assigned to the new resource XMLResource document = (XMLResource)col.createResource("", "XMLResource"); File f = new File(file); if(!f.canRead()) { System.out.println("cannot read file " + file); return; } document.setContent(f); System.out.print("storing document " + document.getId() + "..."); col.storeResource(document); System.out.println("ok."); } } Wolfgang Meier wrote: > [...] > >Nice work, thanks a lot. I committed all your changes to CVS. There's >just one problem: the example build.xml file doesn't run through as >expected. It complains: > >/home/wolf/Devel/eXist/eXist-stable/samples/ant/build.xml:119: XMLDB >exception during remove: org.exist.EXistException: Destination >collection /db/test/sub2/sub1 not found > > That is the move task there was a logical error in the test, have fixed this. Furthermore I uncommented the adduser, rmuser, xquery and xupdate tasks in the all target. I could not get adduser to work and didn't want to remove a standard user in the test case (rmuser should work) The xquery and xupdate I must admit that I need to further look into these as my knowledge of XQuery and XUpdate is not good enough yet for a good test case. So it should be running now. >Can you check this? I don't see where sub1 is removed. > > > >>I had problems to understand how the tasks would ever get names like >>xdb:store, this didn't work for me so I have changed the antlib.xml so >>that all tasks consistently are named like >> >> > >You specify the uri in the typedef: > ><typedef resource="org/exist/ant/antlib.xml" > > >I would prefer to use a namespace for the tasks. However, if >namespaces don't work for all users it's probably better to remove >them. > > Ok, I've read the Ant manual once more, obviously one needs to specify the URI specified in antlib.xml as XML namespace in the project, like this: <project default="all" basedir="." xmlns: .... Then the xdb: prefix works. I've changed the antlib.xml and build.xml to take care of this style. Thanks for pointing me to this feature, I didn't know about this. Peter -- Peter Klotz blue elephant systems GmbH Tel.: +49 711 451017-570 Wollgrasweg 49 Fax.: +49 711 451017-573 D-70599 Stuttgart Email: peter.klotz@... WWW: Sitz : Stuttgart, AG Stuttgart, HRB 24106 Geschäftsführer: Joachim Hörnle, Thomas Gentsch, Holger Dietrich > 2) Is there a way to hold the database in memory only? (Like hypersonic > can do) No, though it would be a nice feature to have. We would need an in-memory implementation of the core DBBroker interface... > One idea is to use an encryption handler (custom serializer) between the > file-representation of the database and the eXist engine itself. eXist requires random access to pages by their absolute position within the database file. I think this makes it impossible to encrypt the whole file. It might be possible to encrypt every single page if you can guarantee that the encrypted data will still fit into the page. =20 > Another idea is to encrypt only these elements of the XML documents, > which have to be encrypted, and let the other (meta-) data being > unencrypted for indexing. Probably the better solution, but how do you query the encrypted elements? Wolfgang Hi Adam, > What im wandering is in the java code how do I parse/examine this node th= at > is passed in by the function call from an xquery?=20 >=20 > So for example an xquery calls my function with the node parameter =3D > <message><to>exist-open@...</to><from>adam.retter@...= .gov.uk</from></message> >=20 > If my node parameter is in args[0], how in the java code can I get the va= lue > of /message/to and /message/from ?=20 If the tree structure isn't too complex, the best way is to use DOM methods to walk the tree. For example, the org.exist.xquery.functions.transform.Transform function does this. Wolfgang Hi Clemens, > but there's one thing that keeps me from squealing with glee: I've scedul= ed > 10.000 Updates and they are still running - but one XUpdate takes about > 90(!) seconds! Since the document still is only 250KB in size I wonder wh= y > querying is so slow?=20 This is for the test script you sent me? The test script generates new element names all the time, which results in eXist writing out its internal symbol table after every update. As the symbol table keeps growing, the db gets slower and slower. For my test, I temporarily disabled this mechanism. In a real environment, you don't have that many element names. I also observed a second problem: the compiled xpath expressions used in the xupdate select are buffered in the xquery cache, where they remain until they time out. If the xpath changes for every update, you get thousands of compiled statements in the cache. The CVS version thus introduces a maximum limit for the xquery cache. 240 seconds and then disappear, but this is too long. when I use the REST interface I only get a single port which is what I would expect. Yes it is XP_SP2. I think I will go over to use the REST API, is there any major limitations to using this API? Leigh.. > I have found out why this is happening. My XP machine is running out of > ports and hence times out when it requests a new port. Do you mean running out of available sockets? Is this with SP2? If so, are you seeing a lot of Event ID code 4662 in Event Viewer? That indicates you are hitting the throttle on simultaneous connections built into SP2, which is compounded by that long period during which a failed socket is marked as unavailable after a connection has timed out. Michael Beddow Hi,=20 when i try to copy from a webdav folder to a webdav folder i get a data-corruption.=20 It helps restarting the Database. The copied doc can't be retrieved or deleted. It is possible to delete the parent-collection.=20 Webdav<->filesystem works. I also tried webdav to webdav(different-uri) but my windows-explorer hung up and i had to kill the process.=20 Perhaps you can fix or disable this, because it is quite dangerous. Manuel=20 Ps.: im am using 20050411 snapshot I have found out why this is happening. My XP machine is running out of ports and hence times out when it requests a new port. For some reason (including using the eXist Admin Client) everytime a client talks over xmlrpc to the server it uses a NEW port. These ports take 240 seconds (the default to get released) so it is quite easy to reach the OS limit. I'm using eXist in server mode. Is there another way of speaking to the server or an option to set so I don't keep getting this problem? I don't want to use embedded-mode as my database could be located anywhere. Leigh.. Thanks Michael, That article that you link to is very usefull. The book I have "Xquery by Michael Brundage" wasn't very clear on this. So from that article I have devised the following code, which seems to do what I want (Select only items that are in both lists) - declare variable $list1 { <list> <item>wheel</item> <item>can</item> <item>beans</item> </list> }; declare variable $list2 { <list> <item>beans</item> <item>wheel</item> </list> }; (: returns only items that are in list1 and list2 :) for $i in $list1/item where not(empty($list2/item[string($i) = .])) return $i -----Original Message----- From: Michael Beddow [mailto:mbexlist-2@...] Sent: 26 April 2005 22:11 To: exist-open@... Subject: Re: [Exist-open] intersect, except and union operators? > Does eXist support the intersect, except and union XQuery operators? I think there's a misunderstanding here. eXist does implement these operators, but it's important to realise that they work on the basis of node identity (which is a fundamental feature of the XQuery data model). They pay no attention whatever to names or values. Node identity is determined by the place of a given node in the hierarchy of the document that contains it. Hence two nodes in two distinct documents can never be identical in the XQuery data model sense of the word, even if they are elements with the same name and the same text content. In your example code you are in effect constructing two separate documents. So by definition no node in your $list1 can be identical to any node in your $list2. Hence the intersect operator quite correctly returns the empty sequence if you apply it to the two sequences you are testing. If, however, you had pulled two sequences out of the *same* document via different XPath expressions, then the intersect operator would return a sequence consisting of any identical nodes that occured in both sequences. That's the sort of thing the intersect and except operators are for. I was rather suprised to discover how little coverage there is of this rather fundamental point in the literature of XQuery that I know of, either on-line or in print. However, it is explained very clearly in one piece by Don Chamberlin in the IBM Systems Journal vol 41 (2002) . There's a pdf at Look at pp 607-8. Michael Beddow ------------------------------------------------------- SF.Net email is sponsored by: Tell us your software development plans! Take this survey and enter to win a one-year sub to SourceForge.net Plus IDC's 2005 look-ahead and a copy of this survey _______________________________________________ Exist-open mailing list Exist-open@... Peter MacDonald wrote: [...] > When I run the very same query within a PHP script, I get only 1 hit in the results set. [...] The difficulty here is that, as you've established, the eXist core is behaving properly. Your results appear to be being truncated by PHP and/or whatever mechanism you are using to connect from PHP to eXist (I don't think you told us just what that is). The fact that you get the same problem when you roll back your eXist version to 20050330 confirms that whatever has changed must either be in your PHP code or in the PHP/eXist binding (which could of course be adversely effected by changes in eXist's handling of whatever protocol you are using for PHP access). Do you really have to use PHP for your application? If so, you may have to seek help from the people who wrote the PHP bindings, who may well read this list but don't seem to field any issues that look as though they might be PHP specific. That suggests that the PHP bindings in the distribution are not supported to the same extent as other interfaces, so I personally wouldn't use it for production purposes. If you indeed have to use PHP, I'd suggest you use or create simple classes that communicate with eXist via the REST interface. That way, the PHP-specific part is minimised and the bulk of your interactions with eXist would be via a very-well supported interface with which you would get more effective assistance. Michael Beddow Hi, =20 about a month ago I wrote about our issues using XUpdate with exist, querying from PHP/SOAP Interface. To cut a long story short: we use eXist to store xml documents which build a project database. After about a week of work, eXist crashes and leaves us with scrambled indices - XQueries deliver wrong/empty results and the database keeps crashing with "Signal 11". Reindexing the documents - even after the first crash - did not help us. Reinstall and restore from backup was the only way to get back to work. Btw: our documents are not terribly big (about 10-20KB). =20 Though the last snapshot brought a huge gain in terms of stability, our problems are still the same - the database's "lifespan" is now about 10+ days. So I wrote a little PHP program which inserts and queries randomly generated tags into a document and stupidly repeats this process as often as configured. The Database was crashing after about 8.000-10.000 XUpdates. Wolfgang Meier rewrote this little test in Java, but could not reproduce our issues. =20 Since I used the SOAP interface for queries and Wolfgang Meier used the Java API (at least I think so :) I thought maybe switching to the REST-API would help. I adapted the test and started it yesterday at about 3pm. When I arrived today the database was still up and running, no warnings, no crash. but there's one thing that keeps me from squealing with glee: I've sceduled 10.000 Updates and they are still running - but one XUpdate takes about 90(!) seconds! Since the document still is only 250KB in size I wonder why querying is so slow? =20 I thought the slowdown may be linked with the document and decided to store it in another collection and retry with a new document. I renamend th collection using webdav, recreated the old one, and now the document is gone, hmmmm :( I opened it before renaming the collection and it had about 7.000 lines of tags in it (250KB as mentioned before). In case you wonder where the other tags have gone: the PHP program randomly deletes some nodes at the end of the script to mix indices up a bit :) =20 Finally, here's my question: anyone knows where to tweak to increase XUpdate performance? =20 Thanks for reading! Best regards =20 Clemens Prerovsky
http://sourceforge.net/p/exist/mailman/exist-open/?viewmonth=200504&viewday=27
CC-MAIN-2014-52
refinedweb
2,656
65.22
I'm trying to write a script to make my 2D character roll to a side, I am using Addforce for this, as I would do when jumping, but i can't make the rolling feel right. If I use a small amount of force, it barely moves but if I use a greater force it makes it look like I am teleporting. So my question how can I go about making it feel smoother? the code I wrote is really simple and I'm not worried about the conditions of when to roll, I just want to make the rolling better. A quick nodge in the right direction would be nice, thanks. public class PlayerControl : MonoBehaviour { public float maxSpeed = 10f; public float dodgeForce = 300f; private Rigidbody2D body; void Start () { body = GetComponent<Rigidbody2D>(); } void Update () { if (Input.GetKeyDown(KeyCode.LeftShift)){ if (body.velocity.x > 0) body.AddForce(new Vector2(dodgeForce,0)); else body.AddForce(new Vector2(-dodgeForce,0)); } } void FixedUpdate(){ float movex = Input.GetAxis ("Horizontal"); float movey = Input.GetAxis ("Vertical"); body.velocity = new Vector2 (movex * maxSpeed, movey * maxSpeed); } } Answer by SquarePieStudios · Apr 27, 2015 at 08:53 AM The reason for this is because you're adding a whole second's worth of force each frame. Multiply dodgeForce, movex, and movey by Time.deltaTime and I think you'll see the results you. dodge roll in mouse direction in a 2D Top down game,Top down dodge roll in mouse direction 0 Answers Unity 5.4 - Sprite Shadow 0 Answers 2D Car problem with motor 0 Answers Client Getting Tile Info on Top Down Game 0 Answers Setting start point for player 2d 2 Answers EnterpriseSocial Q&A
https://answers.unity.com/questions/954598/how-to-make-my-2d-character-roll.html
CC-MAIN-2022-21
refinedweb
278
73.47
Retain/recall semantics enable selected data on the call stack to be accessible from descendant frames.They are similar to dynamic scoping and the structural opposite of throw/catch. For many problems that developers currently use global data to address, retain/recall can be more convenient and flexible. The approach is safe for concurrent, recursive, and re-entrant code. In this article, I explain retain/recall and give an efficient implementation of the idea in C++ using the Posix and Win32 threading libraries. Introducing Retain/Recall In a typical modern programming language, information comes from: - local (automatic) data - passed (argument) data - instance data if the code is part of an instance of an object. - class (static) data if the code is part of a class, but not an instance. - global data. While global and class (static) data can be used from anywhere, they represent a shared resource that can break recursion, re-entrancy, and multithreading. Other items, though, have more limited accessibility, and a software engineer occasionally discovers that a program requires data to which there is no easy access. For example, there may be a decoding library that was designed for internal algorithms, but now needs to have access to a system key store, which needs some kind of authorization context in order to open. At this point, the developer typically has two options (both with significant drawbacks): - Rewrite the software or infrastructure so that the necessary data does get to that point (as instance or argument data). This may be impossible or create an unwieldy solution. - Add global or class (static) data that is more universally accessible. Error conditions used to suffer an analogous fate. Before throw/catch, a new error state could be handled in two ways: - Return a new kind of error status to the caller, and upgrade the infrastructure so this potential error status traversed back to where it could be managed. - Add global or class (static) data that recorded the error state. Hope that all the intervening code did not really break something before the error state was noticed and managed. The throw/catch construct addresses this by allowing error conditions to safely work back through the call stack to a handler, even when the condition was not foreseen by the programmer who wrote the intervening text. In a sense, the throw/catch extends the visibility model so that exceptions (data about exceptional situations) can reach arbitrarily back in the call stack to address them. This allows a third resolution to error handling; namely, throw an exception where it occurs and catch it (lower in the call stack) where you can handle it. This approach addresses the error handling problem without modifying infrastructure between the throw and catch frames or introducing global state. If there are more than one acceptable catch clauses for a given error, the latest one on the stack applies. Thus, nesting and recursion work fine and is there no global state to hinder re-entrance or multithreading. If passing data from the current frame back in ancestral frames is such a good thing, what about accessing data from ancestral frames from code in the current frame? We call this kind of data visibility retained visibility because data values are retained (remembered) in a frame, which can then be recalled from any later frame. Figure 1 shows how throw/catch and retain/recall are related. Figure 1: Comparing throw/catch (left) with retain/recall (right). The stack grows upward in the illustration. In Figure 1, a throw unwinds the stack to the first matching catch, but the text for a recalled value executes in the current frame. Note that a thrown value is caught once, but a retained value can be recalled zero or more times. Note that, for throw/catch, text1 may rethrow a in order to activate text2(). Similarly, for retain/recall, a deepening recall would give access to a2, which is hidden from a simple recall by a1. Having retained visibility allows for a new solution to the data access problem: Retain a value where you know it; recall it (higher in the call stack) when you need it. Retain/Recall Semantics The semantics for retain/recall in a language that supports retained visibility are as follows: - Retain a value for a type. This must be a statement within executable text. From the point of retention to the forget (explicit) or the end of the enclosing block/frame (implicit), we say that value is retained as that type, and structurally is a new block. It should be possible to retain any value derivable from the given type. - Forget a value for a type. This must happen after a retain for the same type and value in the same block. It may be implicit at the end of the block containing a retain (but in the reverse order in the case of multiple retains). - Retain a value for a type if a condition is true. Retain as above if the condition is true. A language may use a short-circuited evaluation of value in cases where the condition is false ( so the value is unused). - Recall a value for a type. This must be an expression within executable text. A language may match this to a retain narrowly or broadly. A recall looks successively through each ancestral block/frame; the first block/frame that retained a value as the same type (narrow) or a derived type (broad) resolves the recalled value. Note that a given retain can resolve many recalls. If there is no matching retain, the recall fails. - Deepening recall of a given type. There must be a mechanism for obtaining the sequence of retained values matching a given recall in frame deepening order. - Failure. It must be possible to determine if a recall or the next step in a deepening recall will fail. A broad matching of a recall to an ancestral retain would keep retain/recall in structural symmetry with throw/catch, since a catch will typically match a throw of a derived type value. However, this may not be in the best interest of the programmer. Allowing catch-alls is a convenience when trying to account for any number of error conditions, as might be the case nearer the root of the call tree. But recalls tend toward the branches of the call tree, where a recall of something specific is likely to be more useful. It also reduces the possibility of a hidden retention, where the desired value is retained, but a retention of a different (but derivable) type effectively hides it from recall (but not a deepening recall). Implementing Retained Visibility in C++ Figure 2 illustrates how the retain of a given type can be implemented for a given thread. The structure has to be repeated for each thread and each type for which there are retained values. Figure 2: Retained structure. Each frame that has a retain for the given type is part of a linked list on the stack. s_current is a thread-local value that refers to the top most element in this list. Each retain keeps the address of the value it is retaining as. To recall a value, we only need to look at the m_as field of the s_current record. Retain-if records where the condition is false are skipped in the linked list. For the sake of simplicity, consider the following retain class and recall function to support retained values of type T in a single-threaded environment. For the nonce, I have ignored template, access, and initialization notational details. class retain { static retain* s_current=0; // initial null/0 value retain* m_previous; // previous retained T* m_as; // what this retains as retain(T* as) { m_previous=s_current; s_current=this; m_as=as; } ~retain() { s_current=m_previous; } }; bool retained() { return retain::s_current != 0; } T* recall() { return retain::s_current->m_as; } Now consider the following test of retain/recall (used as a template): #include <assert.h> #include "retain.hpp" void inc() { int *p=recall<int>(); ++(*p); } int main() { int x=0,y=0; { auto retain<int> as(&x); inc(); assert(x == 1); { auto retain<int> as(&y); inc(); assert(y == 1); } inc(); assert(x == 2); } return 0; } There is a static value, retain, for the address of the current retain record, and the construction of a new retain instance creates two pointer values: one that stores the previous retain record, and one pointer to what the record is retaining, as. Recalling is simply returning the as pointer from the retained static value. In the multithreaded case, the ideas are all the same, except that the static s_current value is kept in thread-local storage instead. The header file retain.hpp defines a thread-safe version of this idea as a template using Posix or Win32 thread-local storage. See the section on using the reference C++ Posix/Win32 implementation toward the end of this article for an explanation of the various APIs that are based on this approach.
http://www.drdobbs.com/cpp/access-data-items-in-ancestor-stack-fram/240155450?cid=SBX_ddj_related_news_default_why_im_not_an_architect&itc=SBX_ddj_related_news_default_why_im_not_an_architect
CC-MAIN-2017-09
refinedweb
1,495
52.29
Homework Struct Quadrilateral - Tying together what we've done I want to think about creating a struct to represent quadrilaterals, i.e. polygons with four sides. This should tie together much of what we've already done. One thing we're going to do is reuse code. This idea is very dear to those of us who are lazy ... which definitely includes me. A quadrilateral is defined by its four vertices, which are of course points, and we've done points to death already. As a matter of fact, going through the lecture notes, I find at least all these defintions for dealing with points. And we could round this out to include subtraction of points, or I/O, or whatever else we wanted. Instead of reinventing the wheel, let's reuse this code. Given this, I'll represent a quadrilateral by the four points that are its vertices, and in the context I have in mind, I'll also give each quadrilateral a character that acts as a label. The struct for quadrilateral, which I'll call Quad, has the following simple definition: struct Quad { char label; point *vert; }; Here's a simple main() using the struct. All it does is read in a Quad and print it back out again. Notice how I create an object of type Quad. It takes two steps, one actually creates the Quad object, and one allocates the array of four points that stores the vertices.; } This gives us a pretty good look at how we've done things so far, and you can look at the complete program to make sure you see how all these pieces fit together. Breaking programs into pieces Looking at the program we just wrote, you should see that it breaks up into two obvious pieces - the old code, which is all the point stuff, and the new code, which is the Quad definition and the main function. Furthermore, the point stuff falls into two obvious pieces - the struct definitions & function prototypes, and the function definitions. Prototypes for point stuff #include <iostream> #include <fstream> using namespace std; /******************* PROTOTYPES & STRUCT DEFINITIONS*/ struct point { double x, y; }; point operator+(point a, point b); point operator/(point P, double z); ostream& operator<<( ostream& OUT, point p); istream& operator>>( istream& IN, point &p); New code - definition for Quad and main struct Quad { char label; point *vert; };; } Definitions for point-related functions /******************* FUNCTION DEFINITIONS**/ point operator+(point a, point b) { point S; S.x = a.x + b.x; S.y = a.y + b.y; return S; } point operator/(point P, double z) { point Q; Q.x = P.x / z; Q.y = P.y / z; return Q; } ostream& operator<<(ostream& OUT, point p) { OUT << '(' << p.x << ',' << p.y << ')'; return OUT; } istream& operator>>(istream& IN, point &p) { char c; IN >> c >> p.x >> c >> p.y >> c; return IN; } It's fairly natural, then, to split our original program up into three files: point.h, main.cpp, and point.cpp. Now, to use the struct point and all of its related functions, we really only need the function prototypes and struct definition - the definitions of the functions don't really concern us as users of point. We only care about what's available for us to use, not how it works. So, the file main.cpp begins with the line: #include "point.h" which means literally pretend that the entire contents of point.h was typed in starting at this point. Thus, as far as the compiler is concerned, it's like that struct definition and all those prototypes were right there. You'll notice that point.cpp also begins with #include "point.h", since those function definitions won't make sense to the compiler without the defintition of the struct point and the prototypes. So, your compiler views your program as consisting of two files, main.cpp and point.cpp, both of which use point.h. It's perfectly willing to compile point.cpp, saying "I believe there is a main function somewhere that's going to use these function definitions. And the compiler is perfectly willing to compile main.cpp saying "I believe there are some .cpp files somewhere that define these functions that main uses and whose prototypes are given in the included file point.h. Then, when the program is linked, these two compiled pieces are brought together (along with any standard library code we need) to form a complete program. Breaking programs up into separate files this way doesn't really change what you can or can't do, but it makes it much easier to organize your code, and it makes it much easier to reuse structs and functions from previous programs. In fact, your start thinking of big programs as different modules to write: each module containing a .h file (or header file) that gives the outside world all the information it needs to use the module, and a .cpp file that contains the source code that implements the module (i.e. that tells the compiler how all these functions really work). What you saw up above was a very simple point module. One key thing that's missing from my simple point module, however, is documentation. The header file needs a lot of documentation so that the user of the module understands how to use the struct and the various functions the module offeres. They don't need to know how it works, but they do need to know what it does! Static Arrays There are two types of arrays in C++. What we've seen are called dynamic arrays, because the size of the arrays can change from run to run of the program. If your program creates and array to store data in a file, and the file (rather than you the programmer) is what determines how many elements ought to be in the array, the size of the array is bound to change from run to run of the program, because the file may change. The other kind of array is static A static array has its size determined when the program is compiled, so from run to run of the program the array's size is always the same. A static array wouldn't work for a program that reads in data from a file that contains an unknown amount of information. How big should you the programmer make the array? You don't know. Dynamic arrays are more general - anything you can do with static arrays you can do with dynamic arrays, and then some. However, in some instances static arrays are simple - for example if you wanted to hardcode the names of the days of the week into a program. You know the size will be 7, so there's no point in making a dynamic array. The syntax for creating a static array is a little bit different than for creating a dynamic array. Creating an Array of 6 ints Dynamic Array: int *A = new int[6] Static Array: int A[6] Using the array after its been created is pretty much the same for either. One difference is that if A is a static array, the pointer A cannot be changed. The contents of the array to which it points can, of course, be changed. But not the pointer itself. Other differences are best illustrated by an example. The above program uses arrays to store the vertices of a quadrilateral. Since we know that a quadrilateral always has exactly four vertices, we could use static arrays. struct Quad { char label; point vert[4]; }; To understand the difference between this version of Quad and the previous version, consider this picture: You see that in the static array version the array of vertices is embedded in the Quad object. In the dynamic version, the pointer is embedded in the object, while the array is outside of the object, somewhere else in memory. Compare the static array version of main with the dynamic array version of main. The above picture really tells you all you need to know to understand the difference between using static and dynamic arrays ... when you really can use static arrays. Let's look at one example to see what consequences arise from this picture. Suppose that I have a Quad object S that contains the label 'Q' and the vertices (0,0) (1,0) (1,1) (0,1). Then suppose we run the following code: Quad R; R = S; R.label = 'P'; for(int i = 0; i < 4; i++) R.vert[i].x = R.vert[i].x + 1; So, I create a copy of S, which I call R. I then add one to the x-coordinate of each vertex of R. Suppose I then print out S and then I print out R. What will I get? Well, it depends whether I'm using the static version of Quad or the dynamic version: Static Version Q (0,0) (1,0) (1,1) (0,1) P (1,0) (2,0) (2,1) (1,1) Dynamic Version Q (1,0) (2,0) (2,1) (1,1) P (1,0) (2,0) (2,1) (1,1) Why the difference? Look at the picture! Dynamic Version Static Version This is not a reason to use static over dynamic, but it is a good example of how and why they behave differently. Here's another example: how does swap(A,B) behave differently for two Quads, A and B, with the dynamic versus static array versions of Quad? Once again, the picture should tell you that while the result it the same, a lot more work gets done in the static case, where the entire contents of the arrays are swapped, rather than simply the pointers. Problems - Look at this program from last lecture. The pogram uses a pointstruct and a struct hhmmss. Break the program up into separate pointand hhmmssmodules, and of course a main file. We have the following pieces: - The "point" module (from above): point.h and point.cpp. - The "hhmmss" module: hhmmss.h and hhmmss.cpp. - The "main program": main.cpp. datum, but it seems less likely to be reused, so there's a less compelling reason for doing it. Write a program that reads a date in mm/dd/yyyy format and prints it out in "dd monthname yyyy" format. It might be helful to know that a static array can be initialized with a list of values in { }'s. For example, an array of the first 10 prime numbers can be constructed like this: int prime[10] = {2,3,5,7,11,13,17,19,23,29}; Note: this is purely about static arrays, it doesn't concern structs at all. Here's my solution.
https://www.usna.edu/Users/cs/taylor/courses/si204/lec/l33/lec.html
CC-MAIN-2018-43
refinedweb
1,791
71.95
Hello, i am using Sikuli,unittest and HTMLTestRunner . I have a CSV file that looks like this for example: startApp, startApp, For each line in the CSV I'm creating a test. The code is this: def TestSuiteFactory(): suite = unittest. pathCSV = r'pathToCsv\ with open(pathCSV, 'rb') as csvfile: reader = csv.reader(csvfile) for row in reader: for item in row: return suite So here there 2 tests that will be built and run with the help of this method. The problem is that inside the html test report, for each test i get this error: TypeError: 'NoneType' object is not callable I couldn't find proper solutions for this. Anyone has an idea? Question information - Language: - English Edit question - Status: - Answered - For: - Sikuli Edit question - Assignee: - No assignee Edit question - Last query: - 2019-01-21 - Last reply: - 2019-01-22 This comes apparently from HTMLTestRunner.py line 678: def run(self, test): Still can't figure out how to solve it I am not really able to work still for the next 2 days. Apparently in the inner call the parameter test is None, which in turn must be the result of your Suite construction. I will try to come back asap. No problem. I found a solution for this, i will come back with a detailed answer when I have time. Forgot to add the code for main: if __name__== "__main__": myClass. createFolder( HagercadConfig. HAGERCAD_ TEST_REPORTS_ FOLDER) unittest. TextTestRunner( verbosity = 2) nfig.HAGERCAD_ HTML_REPORT_ FILE,"w+ ") HTMLTestRunner( stream= output, title=HagercadC onfig.HAGERCAD_ HTML_REPORT_ TITLE, description= HagercadConfig. HAGERCAD_ HTML_REPORT_ DESCRIPTION, dirTestScreen shots=HagercadC onfig.HAGERCAD_ TEST_REPORTS_ FOLDER) output = open(HagercadCo runner = HTMLTestRunner.
https://answers.launchpad.net/sikuli/+question/677960
CC-MAIN-2019-09
refinedweb
274
66.44
Arduino 6 Wire Stepper Motor Tutorial Introduction: Arduino 6 Wire Stepper Motor Tutorial Arduino Stepper Motor Tutorial How this tutorial I'll show you how we can figure out how to connect the stepper motor to an Arduino and control it using the Adafruit motor shield. The easiest way to do this is with a simple multimeter. If you don't have one, it's worth buying one as you can get one for just a few bucks nowadays, and even the cheapest one you can find is good enough for this sort of project. Step 1: Measure and Record the Resistance for All Six Wires. Here are the resistances is that I measured Step 2: Determine Which Wires to Ignore.. Step 3: Uploading the Sketch The adafruit motor shield Has a library called AFmotor , which is a high level library running the motor shield, we will use this library. Here's the code copied from the stepper motor example that is included with the AF motor library . #include <AFMotor.h> // Adafruit Motor shield library // copyright Adafruit Industries LLC, 2009 // this code is public domain, enjoy! // Connect a stepper motor with 48 steps per revolution (7.5 degree) // to motor port #2 (M3 and M4) AF_Stepper motor(50, 2); void <strong>setup</strong>() { <strong>Serial</strong>.begin(9600); // set up Serial library at 9600 bps <strong>Serial</strong>.println("Stepper test!"); motor.setSpeed(30); // 10 rpm } void <strong>loop</strong>() { <strong>Serial</strong>.println("Single coil steps"); motor.step(50, FORWARD, SINGLE); motor.step(50, BACKWARD, SINGLE); } Step 4: Running the Sketch Here's a video of the sketch running I put a little piece of paper on the stepper motor just to observe how long it took to make a full rotation, the example code assume steps per rotation, but after tinkering with it for a while I believe this particular motor is not 48, but 50 steps per rotation. Here is another example application of a motor shield. Thanks for this tutorial! Very helpful :D I have a question: How can i determine a starting position for a stepper motor ? I want to put my stepper indicator at 180 degrees trigonometrically and work from 180 to 0 (trigonometrically). Any ideas ? When I measuring ohm any wire with red wire show half of resistance of any wire combination. But no open circuit show. have any problem in my motor? Is it allowed topost urls here? testing.. :v can i run six wire spteper motor without driver ic thanks nice, basically what you did is to run a unipolar motor as a bipolar. But that is perfectly possible... as long as the motor has 2 common wires Nice!
http://www.instructables.com/id/Arduino-6-wire-Stepper-Motor-Tutorial/
CC-MAIN-2017-34
refinedweb
448
63.59
13-Step Guide to Performance Testing in Kubernetes 13-Step Guide to Performance Testing in Kubernetes Take a look at this demonstration of performance testing on Kubernetes using JMeter and Docker by developing, storing, and analyzing a Spring Boot app. Join the DZone community and get the full member experience.Join For Free Kubernetes is an open-source container orchestrator built by Google that helps run, manage, and scale containerized applications on the cloud. All the major cloud providers (Google Cloud, AWS, Azure, etc.) have managed Kubernetes platforms. In this article, we will discuss how to deploy a Spring Boot-based microservice with Google Cloud and undertake performance testing. Prerequisites - Maven, a build automation tool provided by Apache - Docker hub account Install gcloud-sdk kubectl, the command line interface for running commands against Kubernetes Version control system Git You may also enjoy: Microservice Architecture on Kubernetes Step 1: Setting Up a GCP account Follow this link and login to your Google Cloud Platform account. If this is your first time on GCP, you can get a $300 free trial. You will have to provide your credit card details, but you will not be charged unless you enable billing. Connect to Your GCP Account Remotely In your terminal, execute sudo gcloud init. This will prompt you to pick a configuration. Select the number corresponding to Create a new configuration, and give it a name as you wish. Upon providing a name, it will prompt you to choose the account you would like to use to perform operations for this configuration. Select Log in with a new account. Follow the URL generated, and log into your respective GCP account. Selecting/Creating a project If you already have a project, you can choose to continue with it. If you do not have one or would like to perform the tests in a separate project, go ahead and create one. In the Menu bar, click on Select-project. If this is your first time using GCP, this might sometimes say "My-First-Project." Select New-project from the pop-up window. Give your project a name and click Create. Step 2: Creating a Kubernetes cluster A cluster is the foundation of Google Kubernetes Engine. All containerized applications run on top of a cluster. Let’s now create a cluster for our testing. In Navigation Menu > Kubernetes Engine > Clusters Click on Create Cluster. Choose the Standard cluster template or choose an appropriate template depending on your workload. Give a name for your cluster, like "performance-testing." Select the us-central1-a as the zone. In the default pool configuration, under Machine type select n1-standard-1. This will assign each node 1 vCPU and 3.75GB RAM. Configure the kubectl command-line access by running the following command: #Commandline access to the Kuberenetes Cluster gcloud container clusters get-credentials [name of the cluster] --zone [selected zone] --project [name of the project] #Example clusters get-credentials performance-testing --zone us-central1-a --project springboot-performance-test Now that we have done the setup, let’s move on to how to deploy microservices in Kubernetes. Step 3: Testing the Application and Creating the Jar file In this experiment, we will use a simple prime web service written in Spring Boot, which returns true or false for the number we provide (depending on whether the number is prime or not) as the query parameter. Let us now discuss how to deploy this web service on Kubernetes. The GitHub repo for the Spring boot based web service which we test can be found here. You can test your own application or continue with the sample test application. To continue, clone the GitHub repository. To build an executable jar, navigate the directory where pom.xml is located and execute mvn clean install. This will generate a jar file in the target directory. To test whether the application has the desired behavior, send a request to localhost:9000/prime?number=90 through your browser. This should show up false, as number 90 is not a prime number. Alternatively, you can use the curl command to verify the functionality. xxxxxxxxxx #Clone the repository git clone #Navigate to the directory where pom.xml file is located. cd springboot-test/complete #Build the project mvn clean install #Run the application java -jar gs-actuator-service-0.1.0.jar #Verify the application is running. curl localhost:9000/prime?number=90. Now that we have verified the functionality of the application, let's continue to deploying the application in Kubernetes. Step 4: Creating a Docker Image for The Application Docker is an open-source platform designed to make it easier to create, deploy, and run applications by using containers. Containers allow developers to package up and ship an application with all requirements such as libraries and dependencies. Docker builds images automatically by reading the instructions from a Dockerfile. A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. FROM java:8 WORKDIR /home ADD gs-actuator-service-0.1.0.jar gs-actuator-service-0.1.0.jar EXPOSE 9000 CMD java -jar gs-actuator-service-0.1.0.jar FROM - A Dockerfile must begin with a FROMinstruction. This specifies the underlying OS architecture used to build the image. Some form of the base image is required to get started with building an image. As our application is based on Java version 8, we use java:8as the base image. WORKDIR - This command is similar to the change directory ( cd) command executed in the terminal. It sets the working directory for any command that follows it in the Dockerfile. (Depending on your requirement you can change the working directory). ADD - ADDcommand lets you copy files from a specific location into a Docker image. As we require the built jar to run the application, we add it to the Docker image EXPOSE - The EXPOSEinstruction informs Docker that the container listens on the specified network ports at runtime. Our application is running in port 9000, therefore, we specify it. CMD - The CMDcommand provide defaults for executing a container. The command we provide here runs the built application. Now that we understand the Dockerfile, let's proceed with creating the Docker image. xxxxxxxxxx #Build docker image docker build --no-cache -t [DockerHub account name]/[name of the Docker image] [location of the Dockerfile] #Example: docker build --no-cache -t anushiya/app . Note: There is a dot at the end of the command. The dot at the end of the command refers to the current directory. After building the Docker image, push it to Docker Hub. Docker Hub is the largest cloud-based repository for container images. This repo is used to find and share container images among users. If you have not used Docker Hub before, follow the link to create a user account. After creating one, log in remotely to your Docker Hub account and then push your image. To login, execute docker login in your terminal and enter your username and password when prompted. Upon successful login, push your Docker image to Docker Hub. xxxxxxxxxx #remote login to Docker hub docker login #push the docker image to Docker hub docker push [Docker Hub account name]/[name of the deployment]:[version] #Example: docker push anushiya/app:latest docker push anushiya/app:v1 We have successfully built the Docker image of our application and pushed it to Docker Hub. Now let's create the deployment in Kubernetes. Step 5: Creating a Kubernetes Deployment for Application In this step, we will describe how to deploy the Spring Boot application is Kubernetes. The desired state for the application is described in the deployment YAML file. The file is submitted to Kubernetes master and the master creates a deployment object. The deployment controller is responsible for maintaining the desired state described in the deployment YAML file. It executes routine tasks to ensure the desired state is maintained. xxxxxxxxxx #app.yaml apiVersionapps/v1 kindDeployment metadata namespringboot-app labels appspringboot-app spec replicas1 selector matchLabels appspringboot-app template metadata labels appspringboot-app spec containers namespringboot-app imageanushiya/app latest resources limits cpu"100m" requests cpu"100m" ports containerPort9000 In the above example, A Deployment named springboot-app is created, indicated by the metadata: name field. The Deployment creates one replicated Pod, indicated by the replicas field. The Pod template, or spec: template field, indicates that its Pods are labeled app: springboot-app. The Pod template's specification, or template: spec field, indicates that the Pods run one container, springboot-app, which runs the anushiya/app (Docker image built previously) Docker Hub image at the latest version. In the Pod template's specification, resources: limits and resources: requests indicate the maximum and minimum resource allocation for the container. The Deployment opens port 9000 for use by the Pods. Apply the created YAML file to create the deployment. xxxxxxxxxx kubectl apply -f path/to/the/file #Example kubectl apply -f deployments/app/app.yaml Kubernetes Service is an abstract way to expose an application running on a set of Pods as a network service. To make the deployed application accessible across the cluster, we are exposing it using a Service object. xxxxxxxxxx #app-svc.yaml apiVersionv1 kindService metadata namespringboot-app-svc spec ports nameprime-service port80 targetPort9000 selector appspringboot-app typeNodePort This specification creates a new Service object named “springboot-app-svc". A Service can map any incoming port to a targetPort. In this case, port 9000 of the container is mapped to port 80. The spec: selector specifies that the Pods labeled springboot-app are being served by the Service object. The type: NodePort indicates the type of Service object. Apply the Service YAML to create the Service object. xxxxxxxxxx kubectl apply -f path/to/the/file #Example kubectl apply -f deployments/app-svc.yaml By sending a curl request, verify the functionality of the application. xxxxxxxxxx #To send a request, service IP address or name of the service can be used curl springboot-app-svc:9000/prime?number=71 Step 6: Creating the Docker Image for JMeter To test the performance of the Spring Boot app we use JMeter as the load testing client. To deploy the JMeter we need to first create a Docker image. The following is the Dockerfile for the JMeter. Note that we are installing Python as we use Python to process the performance data. xxxxxxxxxx FROM anushiya/jmeter-plugins:v1 ADD bash /home/kubernetes-performance/bash ADD jar /home/kubernetes-performance/jar ADD jmx /home/kubernetes-performance/jmx ADD python /home/kubernetes-performance/python WORKDIR /home/kubernetes-performance/bash RUN chmod +x start_performance_test.sh RUN apt-get update && apt-get install python3.5 -y RUN apt-get install python-pip -y RUN pip install numpy requests schedule The base image anushiya/jmeter-plugins of version v1 is used. This image includes JMeter version 5.1 and its plugins. Required files are added to the Docker container using ADD command. - The WORKDIR is set to /home/kubernetes-performance/bash. - Executing permission is set to the start_performance_test.sh script file. - Python version 3.5 is installed using apt-getcommand. - Required Python libraries are installed. Let's now build the Docker image and push it to Docker Hub. Note: The files added to the Docker image in the above Dockerfile require modifications if you are to perform the tests. We'll be discussing it in the following steps. xxxxxxxxxx #Build the Docker image docker build --no-cache -t anushiya/perf-test:v1 . #push the image to Docker Hub docker push anushiya/perf-test:v1 Step 7: Creating Persistent Volumes to Store Performance Data Results of the performance tests should be stored permanently. Here, we use host volume to store the test results. You can use Cloud Filestore or any other persistent storage volume for this purpose. To get the details of the nodes in your Cluster, execute the below command. xxxxxxxxxx #Get the nodes kubectl get nodes #Output NAME STATUS ROLES AGE VERSION gke-performance-testing-default-pool-b6e4d476-78zn Ready <none> 11m v1.13.11-gke.14 gke-performance-testing-default-pool-b6e4d476-kfn8 Ready <none> 11m v1.13.11-gke.14 gke-performance-testing-default-pool-b6e4d476-n538 Ready <none> 11m v1.13.11-gke.14 To create a host volume, ssh into any of the above nodes. xxxxxxxxxx #ssh into a node sudo gcloud beta compute --project "[name of the project]" ssh --zone "[zone]" "[name of the node]" #example sudo gcloud beta compute --project "performance-testing" ssh --zone "us-central1-a" "gke-performance-testing-default-pool-b6e4d476-78zn" Create a directory to mount the data. sudo mkdir /mnt/data/results Now create a persistent volume. xxxxxxxxxx apiVersionv1 kindPersistentVolume metadata namepv-volume labels typelocal spec storageClassNamemanual capacity storage10Gi accessModes ReadWriteOnce hostPath path"/mnt/data/results" Create a persistent volume claim. x apiVersionv1 kindPersistentVolumeClaim metadata namepv-claim spec storageClassNamemanual accessModes ReadWriteOnce resources requests storage6Gi After performing the tests, the results will be available in the mnt/data/results directory we created above. Step 8: Creating the Performance Testing Job and Deploying It Using the Docker image we built above for the JMeter, we will create a job to perform the load testing. The main function of a job is to create one or more pod and track the success of the pods. They ensure that the specified number of pods run to completion. When a specified number of successful pods is completed, then the job is considered complete. x apiVersionbatch/v1 kindJob metadata nameperf-test spec template spec containers nameperf-test imageanushiya/k8-performance-test v1 imagePullPolicyAlways command"bash" "start_performance_test.sh" volumeMounts mountPath"/home/jmeter/results" namepv-storage restartPolicyNever volumes namepv-storage persistentVolumeClaim claimNamepv-claim backoffLimit4 A job named "perf-test" is created, indicated by the metadata: name field. The Job template's specification, or template: spec field, indicates that the Job runs one container, perf-test, which runs the anushiya/perf-test:v1 image. The volumeMounts: mountPath specifies the mounted volume. The nodeSelector selects the node in which the Job will run. Execute the kubectl get nodes --show-labelscommand to get the labels of each node. In the list of labels, find the one with the key kubernetes.io/hostname and replace the value in the above YAML. The spec: volumes indicates the volume claim we use. Apply the YAML file to initiate the performance test. xxxxxxxxxx kubectl apply -f deployments/perf-test.yaml Step 9: Collecting Metrics from Stackdriver Monitoring API Monitoring the stats during a performance test is important as it allows us to get an understanding of the behavior of various parameters (e.g. resource utilization) during the performance test. In this article, we use the Stackdriver Monitoring API to get the performance statistics. (Note: Metrics will be collected when running performance tests. These are pre-steps to be performed). Firstly, Stackdriver Monitoring API must be enabled for us to use it. To enable, click on Navigation Menu > APIs & Services > Dashboard. Search for Stackdriver in the search bar. If the API is not enabled, click Enable. To send API requests while running our tests, we require the following credentials. API key - An application programming interface key (API key) is a unique identifier used to authenticate a user, developer, or calling program to an API. OAuth 2.0 access token - The access token represents the authorization of a specific application to access specific parts of a user’s data. Generate API Key To generate the API key, in the Navigation Menu > APIs & Services > Credentials. Click on Create credentials. Select API key from the drop-down menu. This will generate the API key. Generate OAuth2.0 Access Token To create the Access Token, first, we require Client ID and Client Secret. In the Navigation Menu > APIs & Services > Credentials. Click on Create credentials. Select OAuth client ID from the drop-down menu. Select Other for the Application type. Give the desired Name for the client ID (e.g., OAuth client 1) and click Create. Now that we have created the Client ID and Client secret, we will use them to create the Access token. You can use many ways to create the Access token. We are using Postman to create one. Launch Postman. Create a new request by clicking on the (+) icon. Select the Authorization tab. In the Authorization tab, select OAuth2.0 from the "Type" dropdown menu. Click on Get New Access Token. Fill the popup dialogue box with the following details and click Request Token. Token Name: gcp_auth_token (you can give any name you wish) Grant Type: Authorization code Auth URL: Access Token URL: Client ID: [Client ID generated in the above steps] Client Secret: [Client secret generated in the above steps] Scope: Add the following URLs separated by space Client Authentication: Send as Basic Auth Header You will be prompted to log in to your Google account. Provide login credentials. Access Token will be returned upon authenticating. Step 10: Metrics Collection Script The following Python script file is responsible for collecting metrics from Stackdriver Monitoring API. This script gets called at the end of tests run. We first import all the required libraries. Next, we import all the Python functions from other Python files. For example, from container_cpu_utilization_stats import * — Imports all the Python functions from container_cpu_utilization_stats.py file Variables start_time, end_time, andsize are assigned with parameters received when the Python file is called. These are called system arguments. The metrics collection period is the time between start_time and end_time. Let’s now try to understand the query_metrics()functions Both start_time and end_time are URL percentage encoded. This encoding is required to define the URL to send the API request. The container_metrics_list contains the list of metrics that we plan to monitor and collect. Based on your requirement, you can add any number of metrics to this list, as you wish. The complete list of GCP metrics can be found here. In order to send the API request and collect the metrics, we require API key and Access token. We have generated both of them in the above steps. Replace the [ACCESS_TOKEN] with the Access Token you generated. Also at the end of the URL, replace the [API_KEY] with the generated API key. We send an API request using the requests library and record the response. For each metric in the container_metrics_list, we perform the API request and log the response. The JSON response is huge, and we do not require all the details on it. Therefore, we process the JSON file to extract only the required information. (You can find all these files in the repository). Step 11 : Preparing Performance Testing Scripts Creating JMX Open JMeter Open JMeter Right click on Test Plan > Threads (Users) > Thread Group Thread group Fill the dialog box with following parameters Name: group1 Number of Threads (users): ${__P(group1.threads)} Duration (seconds): ${__P(group1.seconds)} Configuration Right click on group1 > Add > Sampler > HTTP Request HTTP Request Fill the dialog box with following parameters: Name: HTTP Request Server name or IP: ${__P(group1.host)} Port number: ${__P(group1.port)} Method: GET Path: /${__P(group1.endpoint)} Click Add at the bottom of the window Name: ${__P(group1.param)} Value: ${__P(group1.data)} Content-Type: text/plain Check Include Equals Save the file as jmeter.jmx Step 12: Automating the Performance Tests When running performance tests, we need to run these tests for a range of workload scenarios (e.g. concurrency levels, heap sizes, message sizes, etc.). Running the tests manually for each of these scenarios is time-consuming and likely to cause errors. Therefore it is important to automate the performance tests prior to executing them. We automate our performance tests using a shell script: start_performance_test.sh. Let us now explain the main functionality of this script. First, we define the backend host IP address. This is the IP address of the prime service deployed (i.e. the Spring Boot application which we deployed above). You can either use the name of the service i.e. spring-boot-app-svc or give the IP address. Then we initialize the test duration and warm up time. run_time_length_seconds is the total time the performance test is performed. As the name suggests, this should be given in seconds. The paths of the required directories and file names are defined. Then we specify the configurations on which we perform the tests. We did tests with two different prime numbers (521, 100003) for different concurrency (1, 10, 50, 100, 500). To log the test results, separate directories are created. The file is named with the configurations set, to make it easily identifiable. The basic command to run a JMX file is as follows. xxxxxxxxxx jmeter -n -t ${jmeter_jmx_file_root}/jmeter.jmx -l ${jtl_report_location}/results.jtl -n : It instructs JMeter to run in non-gui mode -t : Name of JMX file that contains the Test Plan -l : Name of JTL (JMeter text logs) file to log results The rest of the parameters that start with -Jgroup1 are passed to the JMX file which we created above. We have looked at these parameters when we created the JMX file. The initial n minutes of the jtls collected by the JMeter is removed using the JTL splitter developed by WSO2. This data is removed as Java does JIT (Just In Time) compilation. To get stable performance results, initial results are removed Next, we process the test results collected by JMeter using a Python script and log the summary to a CSV file. Finally, we call the Python script responsible for collecting and processing metrics from Stackdriver Monitoring API. Step 13: Analysis of Performance Results The following figures show the behavior of the TPS vs. Concurrency and Average latency vs. Concurrency for the prime number 521. Let's now have a look at the metrics we collected from Stackdriver Monitoring API. Though we collected a list of metrics, let’s analyze the CPU utilization metric. The image below shows how CPU utilization varies with time. Further Reading Spring Boot Actuator: A Complete Guide Developing A Spring Boot Application for Kubernetes Cluster (Part 1) Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/performance-testing-in-kubernetes
CC-MAIN-2020-05
refinedweb
3,703
57.67
Contributed by Josh Juneau. Edited by James Branam. This tutorial is designed to show you the basics of using NetBeans IDE with the Python programming language. and so that they can begin to explore it's possibilities. With it's added support for various JVM and non-JVM languages, Netbeans opens new doors to programmers, giving them an easy-to-use environment for developing in many different languages including Python. Throughout this tutorial, you will be developing a small application (hockeyRoster.py) from the ground up. You will develop an application to contain and manage a sports team. You need the Python EA download of the NetBeans IDE or the Python plugins installed to complete this tutorial. Expected duration: 20 minutes Contents To follow this tutorial, you need the following software and resources. In this introductory tutorial, you develop an application to manage a hockey team, a command-line application to add a list of players, their preferred position, and if their current status ("BENCHED" or "ACTIVE") to an external file. At that point, you will be able to list the contents of the file via Python as well as update records. This tutorial covers file I/O and does not delve into database specifics. Before you create your application, make sure that you have Python installed on your machine. Then, download the Python Early Access (EA) version of the IDE, or install the NetBeans Python plugin in the Plugin Manager. The NetBeans Python plugin is easy to install and configure, and after installation, the IDE detects your various environments. You can configure the IDE for Python support in the Python Platform Manager. This window allows you to add or remove Python installations available to the IDE. Using the Python Platform Manager, you can also set up and configure your Python and Java paths. In doing so, you can place Java jar files or Python modules in your path so that they are available to use each time you start up the IDE. To take it one step further, you can even define different Java or Python paths for each installation you configure. In the main toolbar, choose Tools > Python Platforms Manager. The Python Platform Manager opens, as seen in the following image. If your Python installation does not appear by default, click New, browse to the installation you want to use and choose Open. The IDE add the installation to the the list of Platforms. If you are unsure of the location of the installation, click Auto Detect. You can also rename the Platform name if necessary. Begin by creating a new Python project in the IDE. The New Project wizards contains built-in templates for numerous project types. You can access the New Project wizard in a number of ways. You can choose File > New Project in the main toolbar, or you can right-click in the Projects window and choose New project. In the main toolbar, choose File > New Project. Note: Python is displayed as the project when only the Python EA version of the IDE has been installed on your machine. Other categories may appear if Python EA was added to the IDE as a plugin. Select Python Project as the Project Type, as seen in the following image. Click Next. Enter HockeyRoster as the Project Name, as seen in the following image. Select the version of Python you want to use with the project and rename the main file HockeyRoster.py. The IDE creates a project folder based on the name of the project. You can change the name and location of this folder. Select the Python Platform you want to use from the drop down list, then click Finish to create the project. The IDE creates the project. Note how your project is displayed in the Projects window. Note that the HockeyRoster.py file is open in the Source Editor of the IDE, displaying basic information, as seen in the following image. Netbeans IDE automatically documents the author and date of the project along with providing a short sample print "Hello" program. Now you create two source files for the application. In the Projects window, right-click the project's Sources node and choose New > Empty Module, as seen in the following image. The New Empty Module wizard opens. Type Player as the file name and click Finish. The file opens in the Source Editor. The Projects window should now resemble the following image. In this section, you add Python code to the files you created in the previous section of the tutorial. If is not already apen, open the Player.py file in the Source Editor Type the following code in the Player.py file. # Player.py # # Container to hold our player objects class Player: # Player attributes id = 0 first = None last = None position = None # Function used to create a player object def create(self, id, first, last, position): self.id = id self.first = first self.last = last self.position = position The Source Editor should then resemble the following image. Note how the IDE assists you by entering parentheses and colons for you. Open HockeyPlayer.py in the Source Editor. Erase the existing code in the Hockeyplayer.py and type the following code. This first piece of code consists mainly of comments, but it also does two important things: # HockeyRoster.py## Implementation logic for the HockeyRoster application# Import Player class from the Player modulefrom Player import Player# Define a list to hold each of the Player objectsplayerList = [] Now you add more code to application. This piece of code creates a selector for the application by creating a function that prints output to the Output window, which is based on what the user enters. # makeSelection()## Creates a selector for our application. The function prints output to the # command line. It then takes a parameter as keyboard input at the command line# in order to choose our application option. def makeSelection(): validOptions = ['1','2','3','4'] print "Please choose an option\n" selection = raw_input("Press 1 to add a player, 2 to print the team roster, 3 to search for a player on the team, 4 to quit: ") if selection not in validOptions: print "Not a valid option, please try again\n" makeSelection() else: if selection == '1': addPlayer() elif selection == '2': printRoster() elif selection == '3': searchRoster() else: print "Thanks for using the HockeyRoster application." Right-click anywhere in the Source Editor and choose Format, as ssen in the following figure. Now you add code that accepts keyboard input from the Output window. The user enters a player's first name, last name, and position. # team roster\n" addNew = raw_input("Add another? (Y or N)") makeSelection() Note how the IDE's code completion makes suggestions for you as you type, as seen in the following image. In this step you add code that prints the contents of the list as a report to the Output window. #() Now you enter code that takes input for a player's name from the Output window and searches the roster list for a match. # searchRoster()## Takes input from the command line for a player's name to search within the# roster list. If the player is found in the list then an affirmative message# is printed. If not found, then a negative message is printed. def searchRoster(): index = 0 found = False print "Enter a player name below to search the team\n" first = raw_input("First Name: ") last = raw_input("Last Name: ") position = None while index < len(playerList): player = playerList[index] if player.first.upper() == first.upper() or player.last.upper() == last.upper(): found = True position = player.position index = index + 1() Now it is time to test the application. In NetBeans IDE, resultsfrom Python applications are printed to the Output window. In the Projects window, right-click the project node and choose Run. The application appears in the Output window, as seen in the followiong image. To test the appilcation, type 1 and press Enter. You are prompted to enter a first name, last name, and position for the player you want to add, as seen in the following figure. Try adding more players. Then, print the team roster by typing 2 and pressing Enter in the initial application prompt. The roster is printed in the Output window, as seen in the following image. Now search for a player by typing 3 and presing Enterin the initial application prompt. The results are once again displayed in the utput window. Now try searching for a player that you know is not in the roster. The Output window informs you that the player is not in the roster. In this tutorial, you created a simple Python application with user input using NetBeans IDE. You created a Python project, added an new empty module to the project, experimented with code completion, and ran your applcation, viewing the results in the Output window of the IDE.
http://netbeans.org/kb/69/python/python-quickstart.html
crawl-003
refinedweb
1,480
65.12
Details - Type: New Feature - Status: Closed - Priority: Major - Resolution: Fixed - Affects Version/s: None - - Component/s: general/build - Labels:None - Lucene Fields:New Description ourselves? Issue Links - relates to LUCENE-4725 Use Animal-Sniffer ANT task to enforce JDK compatibility - Open Activity - All - Work Log - History - Activity - Transitions +1 for the blog post as documentation. Especially the portion in red text! +1 for making it reusable. It should be built into javac [branch_4x commit] Uwe Schindler LUCENE-4570: Add missing license headers [trunk commit] Uwe Schindler LUCENE-4570: Add missing license headers I started a google code project: This is a fork with many new additions: - auto-generated deprecated signature list (from rt.jar) - support for "bundled" and project-maintained signature lists (like the deprecated ones for various JDK versions, the well known charset/locale/... violators) - no direct ASM 4.1 dependency conflicting with other dependencies: The ASM library is jarjar'ed into the artifact - not yet: Comments for every signature thats printed in error message - not yet: Mäven support (Mojo) -> Selckin already started a fork in Github, but as the new project is almost a complete rewrite of the API (decouple ANT task from logic), I will need his help - not yet: Mäven Release, so IVY can download it Once there is a release (hopefully soon), this can ivy:cachepath'ed and taskdef'ed into the Lucene build Nice! I already committed the comments in signatures to the googlecode repo, so the error message now contains explanation of the forbidden api (e.g. deprecated, uses default charset,...). Remaining issue is Mäven support, which is not important for Lucene. The forbidden-api checker is now available on sonatype-snapshots with the maven-coordinates: groupId=de.thetaphi artifactId=forbiddenapis version=1.0-SNAPSHOT Attached is a patch for Lucene trunk, removing the forbidden api checker from checkout and use the snapshot version. To enable the download of snapshots, I added for now (until it is released) the sonatype-snapshots repo to ivy-settings.xml. There is some cleanup needed in the patch: - It somehow relies on tools compiled, otherwise some properties are not defined, to locate the txt files. This can be solved by placing the not-bundled lucene-specific signature files outside tools (where its no longer need to be). Just place solr ones in solr and lucene ones in lucene. - I have to review the API files and also move e.g. commons-io.txt to the checker JAR file, so we have more bundled signatures and dont need to maintain them inside lucene. This of course does not apply to specific solr/lucene ones to prevent specific test patterns. By the way: The new checker finds use of a deprecated API, that was missing from the hand-made jdk-deprecated.txt: File.toURL(). Its used at three places in analyzers - which is a bummer, because it will prevent using those analyzers on configs where the lucene files are in a directory with e.g. umlauts or other special symbols (see deprecated message). Here the message: -check-forbidden-jdk-apis: [forbidden-apis] Reading bundled API signatures: jdk-unsafe-1.6 [forbidden-apis] Reading bundled API signatures: jdk-deprecated-1.6 [forbidden-apis] Reading API signatures: C:\Users\Uwe Schindler\Projects\lucene\trunk-lusolr3\lucene\tools\forbiddenApis\executors.txt [forbidden-apis] Loading classes to check... [forbidden-apis] Scanning for API signatures and dependencies... [forbidden-apis] Forbidden method invocation: java.io.File#toURL() [Deprecated in Java 1.6] [forbidden-apis] in org.apache.lucene.analysis.compound.hyphenation.PatternParser (PatternParser.java:101) [forbidden-apis] Forbidden method invocation: java.io.File#toURL() [Deprecated in Java 1.6] [forbidden-apis] in org.apache.lucene.analysis.compound.HyphenationCompoundWordTokenFilter (HyphenationCompoundWordTokenFilter.java:151) [forbidden-apis] Forbidden method invocation: java.io.File#toURL() [Deprecated in Java 1.6] [forbidden-apis] in org.apache.lucene.analysis.compound.hyphenation.HyphenationTree (HyphenationTree.java:114) [forbidden-apis] Scanned 5468 (and 432 related) class file(s) for forbidden API invocations (in 2.29s), 3 error(s). I fixed the violations for now... [trunk commit] Uwe Schindler LUCENE-4570: Fix deprecated API usage (otherwise may lead to bugs if Hyphenation filters load files from directories with non-ascii path names) [branch_4x commit] Uwe Schindler Merged revision(s) 1435146 from lucene/dev/trunk: LUCENE-4570: Fix deprecated API usage (otherwise may lead to bugs if Hyphenation filters load files from directories with non-ascii path names) Here a new patch for Lucene+Solr, that makes use of all new features and bundled signatures shipped with the forked forbidden-api checker: - it now forbids to call sun.* and com.sun.* APIs from rt.jar - new signatures files: jdk-system-out, commons-io-unsafe (now keyed by the version number). The commons-io version number is now in common-build.xml and used by forbidden-apis and ivy.xml (to be always consistent). I am shortly before releasing the forbidden API checker. Once this is done, Steven Rowe can hopefully help to add the plugin to the Maven build. To test this, you have to delete de.thetaphi from your ~/ivy2/cache folder, so IVY dowinloads the new snapshot version. Updated patch: use complete classpath, so the checks are more correct (as every class used can be resolved) In general, the classpath is very hacky. Theoretically, the forbidden api checks should be done per module and after the javac runs (with uptodate). Then every module could use the standard classpath to run the checks. The next version of forbidden apis will throw errors by default if a symbol is undefined while parsing. Fix classpath. Lucene works, Solr still has problems, the thorough checks were disabled. It is currently impossible to generate a top-level classpath that contains all classes and referenced jars. The only fix for this is to make the forbidden-checks per module! de.thetaphi:fobiddenapis:1.0 was released to sonatype release repository. Attached is the patch to make use of this version 1.0 in Lucene. The patch still has some TODOs for a later stage, when we should really make the forbidden-checks per module. As a workaround, Solr checks are currently not so thourough, because the full classpath is not available on top-level. We can now also add the check to the Maven build. I will update the documentation on the project web page tomorrow, while waiting for the release to be pushed to maven central. The attached patch already works, as Lucene's IVY config has Sonatype available as default repository. For those who want to try out/download: Seems to be released on Maven Central, too: I will commit the patch later and open a new issue to make the checks per-module. [trunk commit] Uwe Schindler LUCENE-4570: typo [trunk commit] Uwe Schindler LUCENE-4570: Use the Policeman Formbidden API checker, released separately from Lucene and downloaded via Ivy I committed the attached patch to trunk and 4.x. I am now working on completing the documentation on the Google Code page: Thanks to the "default locale/charset/timezone ghostbuster"! [branch_4x commit] Uwe Schindler Merged revision(s) 1442507-1442508 from lucene/dev/trunk: LUCENE-4570: Use the Policeman Forbidden API checker, released separately from Lucene and downloaded via Ivy LUCENE-4570: typo Patch adding forbidden-api calls to the Maven build. Currently fails when running against test classes because the MavenMojo hard-codes using the compile-scope classpath: - here's the error I get: [ERROR] Failed to execute goal de.thetaphi:forbiddenapis:1.1:forbiddenapis (check-forbidden-jdk-apis) on project lucene-core-tests: Check for forbidden API calls failed: java.lang.ClassNotFoundException: Loading of class org.apache.lucene.util.LuceneTestCase failed: Not found -> [Help 1] Uwe, can you look into adding a way for MavenMojo to change which classpath to use? Maybe look at the name of the phase to which an execution is bound, and if it contains the word "test" (e.g. "process-test-classes", use the test-scope classpath instead of the compile-scope classpath? Hi Steve, it is a known problem that the Mojo currently cannot handle test classes (I think thats documented, unless I missed to add it!). So it is currently not supported to change the default phase. I will work on this in a later version - the way to go in this case is to have 2 separate Mojos (this is how other plugins does it) or like you mentioned, perhaps add a check on the current phase. The problem with the latter is: The mojo defines its dependency resolution mode (see annotation), and this cannot be changed at runtime. For now, I would only check the main classes (which works without any other configuration settings) and leave the tests away. Patch that enables maven usage of forbidden-apis, against 1.2-SNAPSHOT. Works for me. This is not committable as-is: there is a snapshot plugin repository declaration (for oss.sonatype.org) and dependency on a -SNAPSHOT version. Thanks! Looks good, I only dont like the repeated code in every module. Maybe we can improve that later. I am working on fixing more bugs at the moment (Äpple Java 6 on OSX was not detected as valid JDK because the directory layout of this JDK was not laid out according to the "Oracle Java standard", after fixing this I had problems with IBM J9 v7.0. Detecting booclasspath is not easy and most code available on the web is incorrect! Once I am ready to release I will update the dependency in Lucene and you can commit that patch with the released version. Looks good, I only dont like the repeated code in every module. Maybe we can improve that later. Yeah, I don't like it either, but Maven doesn't have a directly supported way to find the base directory in a multi-module build; this is required to locate the rule files. I looked around the web for solutions today, and I found two possible alternatives to the technique I use (i.e.: have each module define its own ${top-level} property pointing to the project base directory in relative terms): - package resources into a jar on which each sub-module depends; the plugin can then extract resources from the jar - use an embedded groovy script to set recursively find the project base directory, then set a property containing the absolutized directory. I think I've tried #2 in the past, but I'll try again. Patch reducing forbiddenapi plugin configuration to a minimum. I had to leave the previous approach (hard-coded per-module relative path to project basedir) in place to specify (re)source directories, but for the rest, including locating forbiddenapi resources, I was able to write a one-line Groovy script to set a property containing the absolute project basedir. This patch also removes redundant maven-surefire-plugin configuration in Solr. I tested on OS X with Maven 3.0.3 and 2.2.1, and on Win7+Cygwin with Maven 2.2.1. All work. Uwe – the location of standard libraries is indeed a problem under various distros. J9 in particular has things scattered all over different JAR archives. My trick of the past was to enumerate several library classes (from different packages) and locate their bytecode based on their own class loader's getResourceAsURL call pointing to those classes' bytecode. This still won't work for certain classes that are native in J9, for example. I needed it for proguard but it's essentially the same problem – where the heck the library classes are. public class DetectRtJar { public static void main(String[] args) throws Exception { Set<File> jars = new TreeSet<File>(); Class<?> [] keyClasses = { java.lang.annotation.Annotation.class, java.lang.management.ManagementFactory.class, java.util.logging.Logger.class, java.awt.Component.class, java.beans.BeanDescriptor.class, java.io.File.class, java.lang.Object.class, java.math.BigDecimal.class, java.net.URL.class, java.nio.Buffer.class, java.security.Security.class, java.sql.Array.class, java.text.Collator.class, java.util.List.class, java.util.concurrent.ConcurrentHashMap.class, java.util.zip.ZipEntry.class, org.w3c.dom.Document.class, }; ClassLoader cl = ClassLoader.getSystemClassLoader(); for (Class<?> clazz : keyClasses) { URL url = cl.getResource( clazz.getName().replace('.', '/') + ".class"); if (url.getProtocol().equals("jar")) { JarURLConnection juc = (JarURLConnection) url.openConnection(); jars.add(new File(juc.getJarFile().getName())); } else { // Other scheme? wtf? throw new RuntimeException("Unknown scheme: " + url.toString()); } } StringBuilder b = new StringBuilder(); for (File f : jars) { b.append("-libraryjar ").append(f.getAbsolutePath()); b.append("(java/**)"); b.append("\n"); } } } Thanks Dawid! I had the same problem with J9 like you explained (e.g. java.lang.Object is in some crazy extension dir). I solved the problem in the exact same way like you did (checking the URLConnection instance type and use more exotic class names). The final solution I comitted was easier: RuntimeMXBean.getBootClassPath() and is supported on all recent JDKs (although its documented that it may be unsupported, they have a boolean getter to detect this). I build a Set from the classpath components (JAR files and directories). When loading the classes later, i lookup the JarFile's of the class that was loaded by the checker to find out if it is a RuntimeClass or not: I like the bootClassPath trick, didn't know about it. Steven: I released version 1.2 including the fix to correctly support test classes in Maven. It has also fixes the "unsupported JDK" issue with JDK 6 on Mäcintrash. It is already available on Sonatype Releases (), on Maven Central hopefully after a few hours. The changelog is here: 1.2 is on Maven Central now: I'll test running the build with my patch after I remove -SNAPSHOT from forbiddenapi version and remove the sonatype repository. Patch for running ForbiddenAPI checker in the Maven build - updating to 1.2 release, and removing the Sonatype Maven repository. Committing shortly. I wondered how much time running ForbiddenAPI checker, executed multiple times in each of ~40 modules, adds to the Maven build, so I ran mvn -DskipTests install, and then mvn process-test-classes, both pre- and post-patch. This excludes performing compilation, since I didn't mvn clean inbetween. On my Macbook pro, with Oracle Java 1.7.0_13 and Maven 3.0.3, the best (fastest) of five runs of mvn process-test-classes for pre-patch: 20s. Best of five for post-patch: 22s. So it looks like this adds 2 seconds to build time, assuming a populated OS filesystem cache. If I use sudo purge to clear the OS filesystem cache before every run, pre-patch best of five runs still took 20s, but post-patch best of five took 26s. So with an empty OS filesystem cache, this adds 6 seconds to the build time. I think this slowdown is live-with-able. Committing now. [trunk. [branch_4x. (merged trunk r1446991) I think this slowdown is live-with-able. By the way, there is already an issue open to make the tests in Lucene also per-module ( LUCENE-4753). The current setup is far from manageable, especially Solr's global classptah that is still broken (resulting in relaxed checks). I ran a Maven build on Jenkins and inspected the log files, looks good. One thing to mention: In the (current) Lucene build, we run the forbidden checks in a first step for core and test classes at once (because we have no clear separation on the top-level, this will change wth LUCENE-4753). After that we run some additional checks afterwards. Because of of this global-then-specific behaviour, I am not sure if all checks in Maven are identical. I think the executors.txt should be run for both maven main and test classes. Currently the executors check is only run for main classes, not tests. Ant build runs it on both. Maybe add the executors next to tests.txt, too. I think the executors.txt should be run for both maven main and test classes. Currently the executors check is only run for main classes, not tests. Ant build runs it on both. Maybe add the executors next to tests.txt, too. Ok, I'll do that. I was trying to make the Maven setup the same as the Ant setup, and missed this difference. [branch_4x (merged trunk r1447138) [trunk [branch_4x commit] Uwe Schindler Merged revision(s) 1412598 from lucene/dev/trunk: LUCENE-4570: Add missing license headers Closed after release. I think we should release the whole stuff, including parts of my blog post () as documentation. The question is: Are there any restrictions from the Apache side by re-releasing source code (+ the TXT files) under a different name? I will go ahead already and add a ASF license header on top of our forbiddenApis/*.txt files!
https://issues.apache.org/jira/browse/LUCENE-4570
CC-MAIN-2017-09
refinedweb
2,793
56.35
Today we are pleased to announce that we’ve extended the range of Raygun to target Xamarin projects for Android and iOS developers. This is an extension of the existing Raygun4Net provider and is very simple to use. Once you integrate the Raygun4Net provider into your application and deploy it to the store, your Raygundashboard will collect lots of information to help you debug any exceptions that occur. This information includes the stack trace, OS version, phone model, device orientation and much more. How to use it Sign into your account at Raygun.com. If you don’t have an account yet, sign up now for a free 14 day trial. Create a new application, give it a name and change your notification settings if desired. After clicking the Create Application button, you’ll come to a page prompting you to select a framework. Select either Xamarin.iOS or Xamarin.Android to see the instructions of how to setup the Raygun4Net provider in your application. On this page, you’ll also see your application API key – you’ll be needing this soon. Following the instructions, you’ll see the next thing to do is install the Raygun4Net provider into your application. This can be done by searching for “Raygun4Net” in either NuGet or the Xamarin Component Store. For NuGet, right click the project in Visual Studio and select “Manage NuGet Packages”. For the Xamarin Component, double click the Components folder in Xamarin Studio, or right click the Components folder in Visual Studio and click “Get More Components”. Once installed, you simply need to use the static RaygunClient.Attach method to get the provider to send all unhandled exceptions to your Raygun dashboard. When calling this method, pass in your application API key mentioned above. For Android applications, the best place to call this is in the main/entry Activity of the application. For iOS apps, you can make this call in the Main entry point of the application. The RaygunClient is in the Mindscape.Raygun4Net namespace. RaygunClient.Attach("YOUR_APP_API_KEY"); And that’s all you need to do to get started. After setting this up, we recommend raising an exception in your application to check that things are wired up correctly. If all is well, the instruction page mentioned above will be replaced with the error dashboard displaying the exception. Since you are probably building both an Android and iOS application, repeat these steps to integrate Raygun4Net into your other project. Support for no internet When customers are using your application on the move, there are bound to be times when their device is not connected to the internet. If an exception occurs in your application when there isn’t an internet connection, rather than giving up, the Raygun4Net provider will temporarily store the exception message on the device and then report it to Raygun whenever it gets another chance. This way, you won’t miss out on any of those important error messages. If you haven’t got a Raygun account yet, sign up for the free trial now and get ready to have the most bug free mobile applications on the market. If you have any questions, feature requests or feedback, we’d love to hear from you. Happy error blasting.
https://raygun.com/blog/2013/08/new-raygun-provider-for-xamarin-developers/
CC-MAIN-2019-30
refinedweb
542
63.39
- 04 Oct, 2010 1 commit internally, as the primary key in the tables, but the CM/SA APIs no longer use them. The CH still accepts them for now. We can probably stop putting them into manifests and advertisements at this point as well. For slivers, stop using the uuid of the node as the uuid of the sliver itself; generate a new one. As above, this is cause the uuid is the primary key in the table, but the URN is what we use for lookups, etc. - 01 Oct, 2010 1 commit backwards compatible with old SAs and CMs until new code makes it out to everyone. So the CM now does a version check at the target SA, and if an old version 1, use the bogus self signed cred. If the SA is version 1.01, send a proper sliver credential. In the SA, accept older bogus credential for now, but start accepting the new sliver credential, and apply more stringent checks. - 29 Sep, 2010 1 commit rid of self signed certs that are bogus (for other authorities that are not us). - 22 Sep, 2010 1 commit the vinterface instead of the interface. - 12 Aug, 2010 1 commit shared nodes. - 04 Aug, 2010 1 commit DB so that when the ticket is redeemed (and we run the mapper again to actually insert the DB state), we get the same ifaces. We really cannot depend on assign to pick the same ifaces each time. Sure hope this works! - 20 Jul, 2010 1 commit - 19 Jul, 2010 2 commits <disk_image name="urn:publicid:IDN+emulab.net+image+GeniSlices//UBUNTU91-LAMP" /> In other words, allow "GeniSlices" for the project, so we can add images to be used from the rspec. impotent, except that actually nalloc the nodes, and retry if the nodes are sucked up by someone else inthe meantime. Also, in the CM, add better ssh key checking. - 14 Jul, 2010 1 commit - 23 Jun, 2010 2 commits - 10 Jun, 2010 1 commit We will deal with Resolve versioning issues later. - 07 May, 2010 3 commits - 03 May, 2010 1 commit - 26 Apr, 2010 1 commit Add support for disk loading (disk_image tag). -. - 07 Apr, 2010 3 commits Formatting with the suggested coding style and added support for max_components policy and its exception credentials. - 06 Apr, 2010 3 commits keeping it as xml element makes it easier to access when required. Otherwise, we need to Parse and serialize many times unnecessarily. keeping it as xml element makes it easier to access when required. In teh othe rcaase we need to parse and serialize many times unnecessarily. 1) Exception for allow_externalusers policy 2) Exception for Max_sliver_lifetime policy 3) Bug Fix in GeniXML. - 11 Mar, 2010 2 commits Bug fix to UpdateManifest(); need to pluck the vlantag out of the linked lan (the underlying vlan when its an encapsulated link). - 03 Mar, 2010 1 commit creating or terminating genislice experiments (unless there is an error) and send all CM mail to protogeni-errors. Required a smaill change in libaudit to specify the "to" address. - 26 Feb, 2010 2 commits node info. Not sure this will survive. Add routines to update as well. Also add Update and Refresh routines. Export VMAC for virtual interfaces as for cooked mode. - 24 Feb, 2010 1 commit Fix XML. Don't try to canonicalize to print. That has too much unwanted baggage. Create a copy of the node instead which will automatically add namespace declarations to it. - 12 Feb, 2010 4 commits - 09 Feb, 2010 1 commit is looking more and more like a urn, and so have to be careful when using it to lookup a local node.
https://gitlab.flux.utah.edu/emulab/emulab-devel/-/commits/b3c8e72ea8f42d763afd5a6d4ed9150b22cae574/protogeni/lib/GeniCM.pm.in
CC-MAIN-2020-45
refinedweb
613
73.58
Hey guys, Im new to this forum and I really never thought my schooling would be this bad to find help from an online community..but heres the deal: Im a masters student in MIS and I needed this java programming course for my degree. I figured it would be pretty easy except my professor doesnt teach us anything. I have been trying to learn on my own through the book and youtube videos and colleagues, which it was going pretty well for a little while. However, my professor gives us really hard programs to do and no one in the class knows how to solve them, not even the guy who writes 2 other languages. So I desperately need help cuz I have no idea what I'm doing. Here's the problem he gave us::: A parking garage charges a $2 minimum fee to park for up to 3 hours. The garage charges and additional .50 cents per hour or part thereof, in excess of three hours. The max charge for any 24 hour period is $10. Assume that no car parks for longer than 24 hours at a time. Writ a java app which will calculate and display the parking charges for each customer who parked in the garage yesterday. You should wnter the hours parked for each customer. The program should display the charge for the current customer and should calculate and display the running total of yesterday's receipts. The program should have at least 3 methods: 1. Enter and return the hours parked by a customer 2. Calculate and return the charge given it was sent to the hours parked 3. Send the charge for each customer and the running total thus far and prints them The output should look somethng like this::: Enter hours this customer parked: 2.5 The charge for this customer is $2.00 The total for the day is $2.00 Enter hours this customer parked: 5 The charge for this customer is $3.00 The total for the day is $5.00 and so on.... Its supposed to be a program for multiple methods but I did multiple classes bc its the only way I know how to do it. Here is what I have so far... My main method::: Code : import java.util.Scanner; class Prog_4{ public static void main(String[] args){ Scanner input = new Scanner(System.in); hours hoursObject = new hours(); System.out.println("Enter the number of hours parked: "); double temp = input.nextDouble(); hoursObject.setHours(temp); hoursObject.summary(); charge chargeObject = new charge(); double cost = input.nextDouble(); chargeObject.setCharge(cost); chargeObject.rateSummary(); My hours class::: Code : public class hours{ public double numberOfHours; public void setHours(double hours){ numberOfHours = hours; } public double getHours(){ return numberOfHours; } public void summary(){ System.out.printf("The number of hours parked was %s", getHours()); } } MY charge class::: Code : public class charge{ public double rate; public void setCharge(double charge, double hours){ if(hours<=3.0){ (charge= "$2.00"); } else if(hours<= 4.0){ (charge= "$2.50") } else if(hours<=5.0){ } } } } public double getCharge(){ return rate; } public void rateSummary(){ System.out.printf("The charge for this customer is %s", getCharge()); I'd greatly appreciate any help at all. Even if you could just dumb it down for me and get me in the right direction. Thanks so much!
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/3908-completely-lost-problem-multiple-methods-printingthethread.html
CC-MAIN-2016-07
refinedweb
556
75.4
On Thu, 15 Jul 1999, T.E.Dickey wrote: > > > > When does core dumps happen? (How often, on which configuration, any > > > > files on > > > > > > On about 1/3 of the files. It's especially noticeable on the win32 and > > > OS/2 ports (leading me at first to suspect my integration of HS's > > > changes) > > > but once I pinpointed it there, it took about 5 minutes to make a test > > > case > > > on Linux with ElectricFence. (It dies in split_line near the end - your > > > anchor pointer's no longer valid during some usages). > > > > Can you send me that test case (I hope it's html file) and describe these > > I ran lynx in dired mode on the lynx source tree, and visited and revisited > the first half-dozen files. > >[...] Ok, I witnessed crashing lynx when in dired on source tree. Here is a patch that fix it. It was due to the fact, that my code did initialization in HTML_new, rather than in HText_new (thus 'last_anchor_on_previous_line' pointed in a wrong place when viewing non-html files). Moving it there fixes the problem. I tested it crawiling lynx source tree again - and was unable to crash it. Best regards, -Vlad diff -ru orig/GridText.c fixed/GridText.c --- orig/GridText.c Thu Jul 15 09:50:47 1999 +++ fixed/GridText.c Fri Jul 16 07:56:28 1999 @@ -300,6 +300,15 @@ PUBLIC void ht_justify_cleanup NOARGS { + wait_for_this_stacked_elt = !ok_justify +# ifdef USE_PSRC + || psrc_view +# endif + ? 30000/*MAX_NESTING*/+2 /*some unreachable value*/ : -1; + can_justify_here = TRUE; + can_justify_this_line = TRUE; + form_in_htext = FALSE; + last_anchor_of_previous_line = NULL; this_line_was_splitted = FALSE; } @@ -692,7 +701,10 @@ #endif CTRACE(tfp, "GridText: start HText_new\n"); - + +#ifdef EXP_JUSTIFY_ELTS + ht_justify_cleanup(); +#endif return self; } diff -ru orig/HTML.c fixed/HTML.c --- orig/HTML.c Thu Jul 15 09:50:47 1999 +++ fixed/HTML.c Fri Jul 16 08:03:03 1999 @@ -7832,19 +7832,6 @@ me->outUCLYhndl, me->outUCI); #endif -#ifdef EXP_JUSTIFY_ELTS - wait_for_this_stacked_elt = !ok_justify -# ifdef USE_PSRC - || psrc_view -# endif - ? MAX_NESTING+2 /*some unreachable value*/ : -1; - can_justify_here = TRUE; - can_justify_this_line = TRUE; - form_in_htext = FALSE; - - ht_justify_cleanup(); -#endif - me->target = stream; if (stream) me->targetClass = *stream->isa; /* Copy pointers */
http://lists.gnu.org/archive/html/lynx-dev/1999-07/msg00423.html
CC-MAIN-2016-40
refinedweb
341
65.12
Overview Differences Between G4 and G5 Overview of Instruction Flow through G5 The Caches Tuning for Double Precision Floating Point Writing G5 Specific Code Using the PowerPC 970 Cycle Accurate Simulator The PowerPC 970 (G5) is largely similar to previous PowerPC processors in the sense that all of the previous good practices apply. These include enabling full compiler optimizations, loop unrolling, function call inlining, proper alignment of data, attention to pipeline latencies, dispatch limitations, etc. As always, the largest opportunities for performance improvement comes from high level optimization techniques, most importantly choosing the right algorithm. Once you have selected the right algorithm and done all important high level tuning, then the usual collection of techniques common to achieving peak G4 performance are applicable to the G5. There are some key differences between the G4 architecture and the G5, however, that can dramatically affect how you approach solving low level code tuning problems. Developers should be familiar with the general tuning advice for G5 offered in these two documents: TN2086: Tuning for G5: A Practical Guide TN2087: PowerPC G5 Performance Primer In addition, beyond these pages, the best source of PowerPC 970 tuning advice and architectural documentation is likely to be the Power4 Tuning Guide. This is because the Power4 and PowerPC 970 have nearly identical scalar cores. The addition of a AltiVec (VMX) unit is the largest difference. We will spend most of our time talking about that here. This page is intended to be an addendum to the above sources with information specifically relevant to tuning for AltiVec and high performance programming in general. It is targeted towards the segment of the developer population that is already knowledgeable about high performance programming and using AltiVec on the G4 processor family. NEW! IBM has released some additional information about the PowerPC 970fx (G5), including a PowerPC 970fx User Manual. The User Manual should contain the most up to date and accurate description of the G5 and should be your primary source of reference. (January 20, 2005) It is expected that developers will find that the G5 delivers a large step up for AltiVec performance. Memory bandwidth on the G5 is greatly enhanced over its predecessors. This will greatly improve code performance on code operating on uncached data. For data in cache, the G5 provides twice the number of load/store units of previous PowerPC processors. Since most AltiVec code is limted by load / store performance, many vectorized applications will see large immediate performance gains on G5. These will solidify as further attention is given to tuning for the new architecture. In our experience, tuning for the G5 more often than not results in a performance improvement for G4, so tuning your code to be responsive to the needs of the G5 is often an all around win. Beyond two LSUs, parallelism in the G5 core is greatly enhanced in a number of other ways. Up to 4 instructions plus one branch may be dispatched per cycle, up from three per cycle on the 7450. Most pipelines are longer on the G5 as well. Finally, there are dual scalar floating point units for top floating point performance. With all this added parallelism, up to 200 instructions can be in flight simultaneously in the G5 core, compared to a few dozen on the G4. The G5 aggressively reorders the execution of instructions much more so than the G4 did. This is accomplished through the use of reordering issue queues. This can complicate your understanding of instruction flow through the machine. Apple has made available a PowerPC 970 cycle accurate simulator as part of the CHUD 3.0 performance tools package to help you understand better how your code is performing on the new architecture. When vec_lde (vector load element) is used, the contents of the other elements in the vector are undefined. The G4 zeros the unused elements. The G5 treats the instruction as a lvx, meaning that the data in the other elements are drawn from the surrounding data as it appears in memory.. vscr Please note that the behavior of vec_lde continues to be undefined for elements other than the one that is loaded, and the implementation may change again in the future. The AltiVec PEM requires that the number of bytes/bits for the shift be splatted across all bytes of the vector containing the number of bytes/bits to shift. Some previous G4 models did not enforce this restriction. (The Motorola AltiVec PIM pictures are also a bit misleading in this regard.) The G5 requires that the shift count be splatted across all bytes of the shift mask, otherwise behavior is undefined. The shift left or right by octet variants on these instructions do not have this restriction. The streaming prefetch instructions should be used with care on the G5. DST's are serializing and may introduce an approximately 10 cycle bubble in your program execution each time they are used. They can have detrimental effects when used in the inner loop in some functions. Since the typical usage pattern for dst is often to prefetch small (128-256 byte) blocks just in time before they are needed, it is recommended that you switch back to using dcbt. On a G5, a single dcbt prefetches a 128 byte block of data, and so in many cases can simply replace the dst instruction. For linear data access, often the G5 hardware prefetchers can be relied upon to do a good job bringing data into the caches. dst dcbt vec_dst can still be used to good effect on G5. It works best for medium sized data segments less than 4K in size and large enough that it is more efficient than a few dcbt instructions. An example might be prefetching the next pixel row as you work on the current one. LRU loads and stores are treated as regular loads and stores. dcba dcbz The dcba instruction is illegal on a G5. It is trapped by the kernel and treated as a noop. Code that calls dcba will run slowly on a G5. The dcbz instruction still zeros aligned 32 byte segments of memory as per the G4 and G3. However, since that is not a full cacheline on a G5 it will not have the performance benefits that you were likely hoping for. There is a dcbzl instruction newly introduced for the G5 that zeros a full 128-byte cacheline. On a G4, it behaves as a dcbz, and zeros a 32 byte cacheline. Code that uses dcbzl needs to dynamically determine the cacheline size at runtime and respond accordingly. The cacheline size may change again in the future. The size of the region zeroed by dcbzl will change with it. noop dcbzl fres fres: mean error max error PPC750: 1/15848.4 1/5256.11 PPC7450: 1/5462.39 1/2049 PPC970: 1/669.415 1/256 Likewise, the frsqrte instruction is supposed to have no more than one part in 32 error. Some earlier processors were more accurate than that. frsqrte frsqrte: mean error max error PPC750: 1/1757.2 1/5410.66 PPC7450: 1/180.623 1/59.9534 PPC970: 1/83.235 1/32 If you previously did not verify that your use of fres and frsqrte would tolerate the allowable error bounds provided by the PowerPC specification, it is possible your code is misbehaving on G5. Please note that not all processors in a class necessarily have the same precision. For example, not all G3s provide better than 12 bit accuracy for fres and frsqrte. How accurate is your processor? Find out! The way the G5 handles instructions in its core is fundamentally different than the way a G4 does it in a number of respects. Some discussion of the execution pathway is therefore warranted. For comparison, a discussion of the 7400 execution model is to be found in the Performance Measurement section and the 7400 and 7450 User Manuals. The chief differences arise from the fact that the G5 may crack or microcode instructions, while the G4 does not. Also the G5 groups instructions into dispatch groups that dispatch and complete together. There are a number of complicating factors associated with what instructions may and may not group together. Finally, the G5 has reorder queues in front of the execution units that allows the G5 to execute instructions even more out of order than the G4 does. The G5 has dual load/store units and dual floating point units. This can result in a profound performance improvement for many code samples. Instructions enter the G5 in fetch blocks of 8 instructions aligned to 32 bytes and placed in an instruction fetch buffer. The instruction fetch buffer can hold 32 instructions. While this is not especially unusual, what happens from this point forward is a significant departure from G4. The processor reads through these in order, biting off up to five instructions to form a dispatch group each cycle. The instructions in the dispatch group will stay together as a group until they are retired, returning all their renames to the free pool and releasing any other resources as a set, unless an error is detected. Because of this instruction grouping, the core of the G5 is somewhat VLIW-like. The dispatch groups can be up to five instructions in size, consisting of up to four non-branch instructions plus one optional branch instruction, appearing in the order that they appear in the instruction stream. The branch, if present, always terminates a dispatch group.. A dispatch group may also be terminated early if any of the following conditions is true: Certain dependencies are not allowed within a group. For example, if a load and store in the same group are to the same address (or to addresses with the same lower 16 bits), then it is not correct to execute them concurrently, since the aliasing order might not be correct. When the processor encounters this situation, it aborts processing the instructions and breaks the dispatch group apart, and executes the instructions individually. Unfortunately, the processor can't know whether this has happen until the effective address is calculated for both, which happens near the end of execution. This abort/retry process is very expensive, since it amounts to a pipeline flush. It is seen most frequently in processes that move data from one register file to another wherein there are data size changes, such as int to float conversions. Recent versions of GCC-3.3 and later can detect and avoid this pattern. Shark will also automatically detect this pattern. The G5 does instruction cracking and microcoding. A number of PowerPC instructions are divided up into two or more internal instructions called microoperations (µops). Those that are broken into two are said to be cracked. Such instructions take up two spaces in the dispatch group. Those that are broken into three or more are said to be microcoded, and take up an entire dispatch group unto themselves. No AltiVec instructions are cracked or microcoded, though vector stores have a vector and LSU component that is visible in the simulator. These only take up one slot in the dispatch group, but take up two issue queue slots as per other stores one in the LSU and one in the vector store unit. Cracked and microcoded instructions are typically LSU and integer operations. Most notably, the update indexed forms of the various load and store instructions may be microcoded. Their use is therefore discouraged for performance reasons. Most dot forms of instructions are cracked or microcoded. In addition, misaligned loads and stores may be microcoded. Here is a list of cracked and microcoded instructions (tags inactive mode). The good news is that some misaligned floating point LSU operations, while microcoded, are at least handled in hardware. Once a dispatch group is formed, it enters the dispatch phase during which processor resources are gathered to make sure it has everything it needs for all the instructions to execute to completion. There must be at least four spaces available in the store reorder queue (SRQ) in case all four non-branch instructions are stores, and an appropriate number of entries in the load reorder queue (LRQ) for any loads. In addition, each instruction in the group that returns a result must be assigned a register to hold the result. The G5 has eighty 128-bit vector registers. At any given time, 32 of these are devoted to serve as the 32 architected AltiVec registers. The other 48 are available as rename registers for allocation in the dispatch phase. When the various resources required to execute the instructions in the dispatch group are gathered, the instructions are dispatched to various issue queues to await their operands to appear so that they can begin execution. Each issue queue feeds into an execution unit. There is one for the VALU, one for the vector permute unit, one for the branch unit, one for CR, and two each for the dual FPUs and LSU/FXUs. (The LSUs and FXUs share a pair of issue queues.) Up to four instructions can go into each family of issue queues for most execution units. It is possible to dispatch four vector floating point unit instructions per cycle into the VALU queue, for example. Any combination of these is of course allowed, e.g. two loads, a permute and a VALU instruction can be dispatched in a cycle. Only one branch per cycle can be issued because only one branch is allowed in a dispatch group. Only two CR modifying instructions are allowed per cycle. Where there is more than one execution unit capable of performing a given task, (there are two FPUs, two LSUs and two pseudo-symmetric integer units), then each execution unit has its own queue. Which queue the instruction goes into depends on its position in the dispatch group. Instructions at position 0 and 3 in the dispatch group go into the queue for execution unit 0. Instructions at position 1 and 2 in the dispatch group go into the queue for execution unit 1. (See illustration of data flow through the FPU as an example.) Thus, instruction ordering can be at times important, since certain patterns may result in all instructions of a certain type going to just one of the two execution units. An instruction can be dispatched into the VALU and VPERM queues from any and all slots in the dispatch group, except the optional fifth slot dedicated to branch instructions. In order to determine where an instruction appears in the dispatch group, one must know the alignment of the dispatch groups. Dispatch groups start at a branch target address, and generally happen every four instructions for branchless code after that, except when one of the other hazards described above happens. You can recognize dispatch groups in the Shark assembly view as strided samples that appear every four instructions or so, with no samples in between. This happens because samples are attributed to the first instruction in a dispatch group. Shark also has a static simulator feature that does a reasonably good job of predicting them. They can also be seen with more accuracy in the cycle accurate PowerPC 970 simulator in CHUD 3.0.1 or later.. The decode and dispatch process takes 6 cycles. The issue queues feed directly into the execution units. Each cycle one instruction will be moved from each issue queue into its corresponding execution unit, provided that there is an instruction for which all the data dependencies are resolved. The instructions do not flow through the queues in a first-in first-out manner. This is a departure from G4, where instructions within a certain execution unit would execute in the order they appear in the instruction stream. Instead the G5 can reorder within the context of the queue. Usually it tries to execute the oldest instructions first, but if an old one is blocked because the input operands are not ready yet, another item in the issue queue will execute first instead. The number of instructions that can fit in the queues are as follows: The integer and load/store units share a issue queue. The integer/load/store queue can issue two instructions per cycle one to an integer unit and one to a load/store unit. Since there are two such queues, 2 integer and 2 LSU operations can be issued per cycle. The queues provide buffering capacity that will help more efficiently deal with data dependency stalls. In certain cases involving very small loops, the issue queues can have the effect of automatically unrolling loops for better pipeline usage. In extreme cases, this might be used as a strategy to save registers if 32 registers are not enough to saturate the pipelines with your algorithm, though generally speaking, the issue queues are not large enough for this to work with most unrolled AltiVec code, nor are there necessarily enough rename registers to support this technique. Some care is required as it would also require that you schedule code with lots of serial data dependencies that would execute quite poorly on processors without reordering issue queues such as the G4. The queues consume rename registers. This happens because the rename registers are allocated in the dispatch phase before the instructions enter the issue queue. Instructions waiting to execute in the issue queues therefore tie up processor resources without doing work. For vector code, up to 36 of these can be sitting in the LSU issue queues for stalled loads. Another 36 can be in the VPERM and VALU issue queues for stalled vector instructions. Finally, renames are required for instructions that are currently executing or waiting to retire because other instructions in their instruction group have not finished executing. (The LRQ has 32 entries, and 80 vector instructions can be in flight before we run out of dispatch groups, so this number is actually somewhat smaller.) As a result, it remains important for you to schedule your code carefully to avoid having a lot of stalled instructions sitting in issue queues on G5, even with an aggressive code reordering facility to back you up. Once the instructions enter the execution unit pipelines, they move through in the usual fashion. Up to 10 instructions can enter execution each cycle: 2 LSU, 2 FXU, 2 FPU, 1 VPERM, 1 VALU, 1 CR and 1 branch. The pipeline lengths are as follows: Latencies presented are from empirical measurements for back to back serially dependent operations, except LSU operations. Latencies presented are from empirical measurements for back to back serially dependent operations, except LSU operations. Latencies presented are from empirical measurements for back to back serially dependent operations, except LSU operations. The permute unit and VALU each maintain their own copies of the vector register file, which are synchronized on the half cycle. This adds one cycle of latency when a VALU result is used by a permute operation or a permute result is used for a VALU operation. These pipelines are longer than what you will find in a G4. For code to scale with processor frequency on a G5, it is often necessary to unroll loops more than what is normal for a G4. It is recommended that you unroll all code to a depth of at least 8, so that 8 independent instructions can occupy the pipelines concurrently. This will help avoid pipeline bubbles and make sure you use the processor to its fullest potential. Future processors are likely to have even longer pipelines. More unrolling will help make sure that your code scales with new processors as they are released. When all instructions from a dispatch group have finished executing, the dispatch group can be retired. The rename registers and other resources that it used will be returned to the free pools. Up to 20 dispatch groups can be in flight concurrently. Dispatch groups must be retired in the order that they are created. One dispatch group may be retired per cycle. The level 1 data cache is 32kB and 2 way set-associative. The unified level 2 cache is 512kB and 8-way set associative. In comparison, the more recent G4s have a 256kb L2 cache. The PowerPC 7457 (used in the newer aluminum powerbooks) has 512kB cache. The data coherency point on the G5 is the L2 cache, rather than the L1. For this reason, stores are always sent to the L2 cache in addition to the L1 cache. The G5 has no L3 cache, so the amount of space available to use in the cache hierarchy may be reduced on the G5 compared to some G4 systems. The G4 supports up to 2 MB of L3 cache. Developers should be cautioned that a 512kb chunk of data that is contiguous in the virtual address space is not likely to fit in a 512kb L2 cache on any PowerPC. This is because the cache is physically mapped and the set of physical pages used to service a set of contiguous virtual pages are not themselves likely to be contiguous. (Read More.) As always, experimental determination of the best tile size to break your problem set into is required. Front side bus performance is dramatically improved on a G5 compared to the G4. To illustrate, let's do a small throughput comparison between G4 and G5. We are going to be totally unfair in this comparison. We will compare L1 to register throughput on a G4 against front side bus performance on a G5. Normally on any computer, we'd expect that the L1 to register throughput would be many times greater than its front side bus performance. Looking at the most common data size, a 32 bit integer load or store on a G4, we find that we can do one of these per cycle on a G4. On a 1.4 GHz G4, this means we can do: 4 byte load or store per cycle * 1.4e9 cycles/second = 5.6e9 bytes / second This corresponds to about 5.3 GB/s for data throughput between the L1 cache and register. Of course, that is only in one direction, load or store. If you intend to copy data an operation that involves both loading and storing then the peak theoretical throughput is cut in half to about 2.67 GB/s, for data copies in the L1 cache. Most functions load and store data, so this is a probably a better thing to look at. In comparison, the G5 front side bus (the data path between the memory controller and the processor) on a 2 GHz G5 operates at 1 GHz and can transfer 4 bytes per beat in each direction. There is some transactional overhead in this process, so the maximum throughput is 3.2 GB/s in each direction, rather than a full 3.8 GB/s (4e9 bytes/s). Traffic between memory controller and DRAM has a peak theoretical throughput of 6.4 GB/s. The read and write busses are independent, so aggregate throughput (copies must do both) is actually twice that. This gives us a peak theoretical throughput of roughly 6.4 GB/s. However, for copy operations we need to look at the throughput of the entire copy, so 3.2 GB/s is the right number to look at. Therefore, peak theoretical front side bus throughput for RAM to RAM copies on a G5 is faster than L1 to L1 copies on the fastest G4 when the G5 was released! For completeness, the L1 to register throughput on a 2.0 GHz G5 for 32 bit ints is: (4 byte load + 4 byte store per cycle) * 2.0e9 cycles/second = 16.0e9 bytes/second The G5 has two load store units, so it can move two 32 bit words per cycle rather than one. (Two loads per cycle are also possible. Two stores per cycle are not possible.) Of course, this discussion is complicated by the fact that the G5 has 64-bit integer registers and both machines have AltiVec (128 bit registers). Floating point stores on recent G4's (PPC745x) are not pipelined and so were not considered for this discussion. Store throughput is much slower on the G4 compared to G5. Of course, throughput is only half the story. The latency for touching RAM still remains long on a G5. It is by no means comparable to the latency between L1 cache and register on a G4, 2 cycles. Writing real world code that gets close to theoretical performance to DRAM is harder than to L1. Latency to RAM is over 100 nanoseconds on a G5. This means an unprefetched cacheline that misses all the way to RAM can take over 200 cycles on a 2 GHz G5. Since instructions must complete in the order they appear in the instruction stream, load stalls have the potential to stall the processor. Clearly, prefetching data into the caches is important! Demand loads have the following latencies on G5: . The latency advantage to pre-fetching data into the caches should be clear. Prefetching works without stopping program flow because the heavy lifting happens asynchronously. Prefetch instructions don't return any results to register, and so don't alter program order. They can complete as soon as the instruction finishes address translation and the cacheline address can be placed in the load miss queue. Since we don't have to wait for the data to appear for a prefetch hint, the instruction flow can continue unabated. As described in the memory performance section, simply put, prefetching allows program execution and bus activity to happen in parallel. The G5 has 4 automatic hardware prefetchers that try to automatically detect when to start prefetching data, based on when cache misses happen. With repeated cache misses in sequentially increasing or decreasing cachelines, the prefetcher is reinforced and begins bringing in more and more data with longer look ahead times to cover latencies. The stream stops when the prefetcher crosses a page boundary. (Pages are 4k in size on MacOS X.) Nonetheless, in certain cases, the hardware prefetcher can be more efficient than software prefetching, The two can conflict a bit too over internal hardware resources. The AltiVec streaming data touch instructions (dst*) piggyback off this facility. Because the hardware prefetcher is primarily devoted to linear reads through memory, the dst implementation on G5 is somewhat limited in functionality. They only reference the first data segment and also stop when they cross a page boundary. DSTs are also execution serializing, which makes them less ideal for use in the inner loop. The older dcbt instruction operates normally, bringing in a single cacheline. Since cachelines on a G5 are 128 bytes, dcbt does significantly more work than its counterpart on a G4. It is not execution serializing. In most cases, dcbt is preferred over DST on G5 for performance reasons. Please see the memory performance section for more discussion on this issue. To make optimal use of two floating point units, you'll need to unroll your loops to at least 12 way parallelism to keep both six cycle pipelines busy all the time. This can be a bit tricky with 32 registers for some algorithms, but well worth the effort. You also need to make sure that the floating point instructions are evenly partitioned between the two FPUs. The FPUs are not allocated dynamically. Instead which FPU your instruction goes to depends on the position of the instruction in the dispatch group. (See illustration below.) Instructions at slots 0 and 3 go to FPU 0. Instructions at slots 1 and 2 go to FPU 1.. Because of this partitioning scheme, it is possible (although unlikely) for poorly scheduled code to utilize exclusively one of the two FPUs. Likewise, if you only use dispatch group slots 0 and 2 for FPU instruction (with 1 and 3 for loads, for example) then you will only have 5 of the 10 issue queue slots available used each FPU. This is because you will only be using the even half of each. To help make sure the processor is not data starved, the G5 provides two load/store units to support your work. (Earlier PowerPC processors have one.) The way instructions flow through the LSUs is very similar to the FPUs. The LSU issue queues are shared with the two integer units. One integer and one LSU operation can be issued from each LSU/FXU queue per cycle. Load latencies for the FPUs are a bit longer than for the integer units. The double precision floating point functionality in vecLib.framework has been retuned for G5 for MacOS X.2.7 and later. Additional performance enhancements, especially to matrix multiplication in the BLAS, are available in MacOS X.3, Panther. Generally speaking, it is a mistake to tie specific software features to certain processors. Doing so is necessarily fragile because as new processors come out your code will not grow to take advantage of them. In certain cases, G5 specific code might be required to work correctly on the next processor as well. One example might be using dcbz, for which the size of the cacheline is critical. Code that assumes that only G5 has a 128 byte cacheline, and all others are 32 bytes will fail if another processor arrives that no longer calls itself a G5, but which has 128 byte cacheline size. Instead, Apple recommends that you tie your code to specific processor features. This way as new processors are introduced, your code will dynamically adjust to do the right thing. MacOS X.3, Panther, introduces a new API to replace sysctl, called sysctlbyname, which has been enhanced to return 64 bit results for key items like processor frequency that no longer fit in 32 bits or are unlikely to do so in the near future. There are a number of keys available to determine if various processor features are available. sysctl sysctlbyname Here is sample code for determining the number of bytes in a cacheline: ; const char key[] = "hw.cachelinesize"; u_int64_t result = 0; size_t typeSize = sizeof( result ); int err = sysctlbyname( key, &result, &typeSize, NULL, 0 ); if( 0 != err ) return 0; return result; } A great many other selectors are available. For more information, please see the sysctlbyname man page and /usr/include/sys/sysctl.h. The G5 core is much more complicated than the G4. A cycle accurate simulator is a must to truly understanding the roots of code performance on G5. While certainly not required to optimize every piece of code, some time spent with the G5 simulator is almost always a well spent learning experience that should help you anticipate and avoid performance pitfalls. Apple provides such a simulator in the form of simg5, available with CHUD 3.0.1 or better. To use SimG5, the first thing you have to do is collect a trace as per what you would do for SimG4. On MacOS X, this is done using amber. We mostly use a supervisor level instruction as a trigger and collect the next 5000 instructions afterwards. The trigger toggles sample collection on and off. Other approaches work fine too, but many of them may lead to huge traces of stuff you don't want to see. To insert a supervisor level instruction, add this one line where you want to start tracing: #if defined( __GNUC__ ) #include <ppc_intrinsics.h> #endif int myTempVariable = __mfspr( 1023 ); #if defined( __GNUC__ ) #include <ppc_intrinsics.h> #endif int myTempVariable = __mfspr( 1023 ); ...and then recompile with GCC or MWCW. (Other compilers may not recognize __mfspr() and may require other syntax to introduce that instruction.) This will cause your program to crash when it hits that instruction. Run the program under amber however, and it will intercept the exception and start tracing at that point. CHUD 3.0.1 and later users may instead elect to use the following function call to start or stop a trace at a specific point: void chudStartStopAmber(void); void chudStartStopAmber(void); If your app is called a.out, you can collect a trace of 5000 instructions after the supervisor level instruction from the command line as follows: amber -x 5000 -I ./a.out amber -x 5000 -I ./a.out If you have a Cocoa app, navigate down to myApp.app/Contents/MacOS/ where you will find the actual executable for the app, and use that in place of a.out above. If you have a CFM app, then you need to run your app through LaunchCFMApp through amber: /usr/bin/amber -x 5000 -I /System/Library/Frameworks/Carbon.framework/Versions/A/Support/LaunchCFMApp ./a.out /usr/bin/amber -x 5000 -I /System/Library/Frameworks/Carbon.framework/Versions/A/Support/LaunchCFMApp ./a.out Set up some aliases and things will be simpler. You can collect a trace on a G4 if you like. A G5 is not required. When amber is done, it should produce a directory called trace_001, and inside you will find a file called thread_001.tt6e, that contains information on what instructions were issued in what order and some additional information like addresses for loads and stores. So far, everything in this procedure has been the same as what you'd do to collect a trace for SimG4. Once you have the trace in hand, you can run the simulator as follows from the terminal: simg5 thread_001.tt6e 5000 100 1 simg5 -p 1 -b 1 -e 5000 This will produce two files, simg5.pipe and simg5.config that contain the simulator output. When running simg5, you may find a few other options handy, especially the -inf* options for turning off things like cache misses. These can be distracting if your code spends most of its time in load stalls. -inf_L1 -inf_tlb -inf_translate -inf_L2 -inf_store The output files can be visualized with the java viewer as follows: scrollpv -pipe simg5.pipe -config simg5.config Please be aware that this process is not all that speedy, so give it a minute or two to appear. 5000 instructions is actually quite a lot for this java app. When the java viewer comes up, the first thing you will want to do is turn on autoscroll based on F: Select Symbol tracking from the Scroll Mode menu in the window. Enable Track on F with offset of 0. This will help keep the interesting region in the window as you move the vertical scroll bar. SimG5 doesn't wrap the way SimG4 did. This can also be done by double clicking on F. You'll see something that looks like the SimG4 horizontal scroll pipe. You can mouse over the various symbols in the window and the viewer will tell you what they mean. Each column is a cpu cycle. Each row is an instruction. As you read along a row from left to right you can see that instruction progress through the processor. You can see the dispatch groups of four as sets of four instructions that begin dispatch/decode (DDDDDM) and enter completion (C) together. As described above, the instruction first is fetched (FVB) into the instruction buffer. Then there is a delay for some number of cycles before the dispatch mechanism reaches those instructions and forms a dispatch group out of them. They go through 5 cycles of decode (DDDDD) and one of dispatch (M). At that point they are sitting in the issue queues in front of each execution unit. There they may reside for a few (or a great many) cycles (su) until the resources they need become available for them to issue into the execution units. You can see that instructions can be reordered within these queues. For example, the add that appears right after the noop actually enters execution after an addi that appears seven instructions later. Which execution unit they issue into is given by the number that follows the (I). Move the mouse over it to find out which one it is. Once the instructions are in the execution unit, they execute for a while and then finish (f). Finally, there is a delay while the CPU waits for all instructions in a dispatch group to finish and the group before it to finish, before the group can complete (C). Dispatch groups must complete in the order that they were dispatched. add addi The simg5 simulator and scrollpv viewer are available from Apple in CHUD 3.0.1 and later. Table of ContentsNextPrevious Get information on Apple products. Visit the Apple Store online or at retail locations. 1-800-MY-APPLE
http://developer.apple.com/hardwaredrivers/ve/g5.html
crawl-001
refinedweb
6,103
62.98
> GENIE-SHELL.rar > arp Swedish Institute * of Computer Science and its contributors. *: arp.h,v 1.4 2002/03/04 10:47:56 adam Exp $ * */ #ifndef __NETIF_ARP_H__ #define __NETIF_ARP_H__ #include "lwip/pbuf.h" #include "ipv4/lwip/ip_addr.h" #include "lwip/netif.h" packed struct eth_addr { u8_t addr[6]; } PACK_STRUCT_STRUCT; packed struct eth_hdr { struct eth_addr dest; struct eth_addr src; u16_t type; } PACK_STRUCT_STRUCT; #define ARP_TMR_INTERVAL 10000 #define ETHTYPE_ARP 0x0806 #define ETHTYPE_IP 0x0800 /* Initializes ARP. */ void arp_init(void); /* The arp_tmr() function should be called every ARP_TMR_INTERVAL microseconds (10 seconds). This function is responsible for expiring old entries in the ARP table. */ void arp_tmr(void); /* Should be called for all incoming packets of IP kind. The function does not alter the packet in any way, it just updates the ARP table. After this function has been called, the normal TCP/IP stack input function should be called. */ void arp_ip_input(struct netif *netif, struct pbuf *p); /* Should be called for incoming ARP packets. The pbuf in the argument is freed by this function. If the function returns a pbuf (i.e., returns non-NULL), that pbuf constitutes an ARP reply and should be sent out on the Ethernet. */ struct pbuf *arp_arp_input(struct netif *netif, struct eth_addr *ethaddr, struct pbuf *p); /* arp_loopup() is called to do an IP address -> Ethernet address translation. If the function returns NULL, there is no mapping and the arp_query() function should be called. */ struct eth_addr *arp_lookup(union ip_addr *ipaddr); /* Constructs an ARP query packet for the given IP address. The function returns a pbuf that contains the reply and that should be sent out on the Ethernet. */ struct pbuf *arp_query(struct netif *netif, struct eth_addr *ethaddr, union ip_addr *ipaddr); #endif /* __NETIF_ARP_H__ */
http://read.pudn.com/downloads57/sourcecode/windows/shell/202117/GENIE-SHELL/INC/TCPIP/netif/arp.h__.htm
crawl-002
refinedweb
280
66.33
List comprehension From HaskellWiki List comprehensions are syntactic sugar like the expression import Data.Char (toUpper) [toUpper c | c <- s] 1 Examples One may have multiple generators, separated by commas, such as [(i,j) | i <- [1,2], j <- [1..4]] yielding the result [(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4)] Note how each successive generator refines the results of the previous generator. Thus, if the second list is infinite, one will never reach the second element of the first list. For example, take 10 [ (i,j) | i <- [1,2], j <- [1..]] yields [(1,1),(1,2),(1,3),(1,4),(1,5),(1,6),(1,7),(1,8),(1,9),(1,10)] In such a situation, a nested sequence of list comprehensions may be appropriate. For example, take 5 [[ (i,j) | i <- [1,2]] | j <- [1..]] yields [[(1,1),(2,1)], [(1,2),(2,2)], [(1,3),(2,3)], [(1,4),(2,4)], [(1,5),(2,5)]] One can also provide boolean guards. For example, take 10 [ (i,j) | i <- [1..], j <- [1..i-1], gcd i j == 1 ] yields [(2,1),(3,1),(3,2),(4,1),(4,3),(5,1),(5,2),(5,3),(5,4),(6,1)] Finally, one can also make local let declarations. For example, take 10 [ (i,j) | i <- [1..], let k = i*i, j <- [1..k]] yields [(1,1),(2,1),(2,2),(2,3),(2,4),(3,1),(3,2),(3,3),(3,4),(3,5)] Here is an example of a nested sequence of list comprehensions, taken from code implementing the Sieve of Atkin: [[[ poly x y | i <- [0..], let x = m + 60*i, test x y ] | j <- [0..], let y = n + 60*j ] | m <- [1..60], n <- [1..60], mod (poly m n) 60 == k ] The result is a list of infinite lists of infinite lists. The specification of list comprehensions is given in The Haskell 98 Report: 3.11 List Comprehensions.)
http://www.haskell.org/haskellwiki/List_comprehension
CC-MAIN-2014-42
refinedweb
331
67.96
Move some apps to a community project organisation Hello all, I would like to put Stellarium app or others projects to a more community place, can it be a good candidate to move here ? Can it also benefit of Ubports weblate server as well as setting up the CI for click builds? - CiberSheep last edited by I'm not sure but I thought GitLab would allow you to use CI on any project. Look Dekko gitlab-ci.yml As per weblate, it would be great to have an instance for community project indeed. There were a try some time ago. Poeditor has some free space for open source projects. @CiberSheep ubports weblate community project would be great, I have not big motivation to make my app translatable otherwise. So can Stellarium be part of the family ?, and with a proper namespace too ( today it is me.lduboeuf ). As the big challenge for me was to port and make it usable for UT, i would to let it fly its way. As well for sfxr, drumkit, and almost all apps that i've ported, i would be pleased to leave them part of a kind of "ubports incubator" or "ubports app" organisation on gitlab. @lduboeuf It's not a core app so I think it shouldn't be under that project (likewise, I think a couple of things that are there should not be there, and should be moved out separately, as they are community projects and not really under the purview of UBports Foundation). I don't know if it makes sense to create an organization to let anyone put projects under. We'd need a list of real benefits to everyone, particularly how it will not simply become a dumping ground of randomly ported apps that nobody wants to maintain. But ofc, the "UT app dev community" can create its own gitlab organisation and perhaps openstore namespace and develop apps together there... I like that idea. Lets discuss which advantages it would have, to collect UT apps in a common place...(?) @hummlbach yes something that can bring contributions more easily i think. If it allows to have translations and CI easily setup, would be nice. When I read the proposition of Lionel I thought about the most popular fully featured apps. For me, requirements to get into this kind of repository should be something like: - UT app (port of existing app to UT, native app) - Popularity the user base should be large enough to draw developers/designers to contribute Of course popularity is hard to define, but I agree that some advanced apps should benefit from the visibility given by the foundation to help find people to contribute. I also agree with @dobey that the separation should be clear between community apps, core apps and the OS. Problems are who could be in charge of the gitlab, how to manage access rights, etc. I have very little knowledge of how it can be done. Meanwhile if a developer cannot continue maintaining their app, the forum is a good place to call for a new maintainer and ask for help to keep a nice project alive.
https://forums.ubports.com/topic/4737/move-some-apps-to-a-community-project-organisation/6?lang=en-US
CC-MAIN-2020-45
refinedweb
526
68.3
Opened 9 years ago Closed 9 years ago #5313 closed bug (fixed) wrong dylib name using GHC package Description > import qualified GHC > import qualified GHC.Paths > > main = GHC.runGhcT (Just GHC.Paths.libdir) $ do > -- begin initialize > df0 <- GHC.getSessionDynFlags > let df1 = df0{GHC.ghcMode = GHC.CompManager, > GHC.hscTarget = GHC.HscInterpreted, > GHC.ghcLink = GHC.LinkInMemory, > GHC.verbosity = 0} > _ <- GHC.setSessionDynFlags df1 > -- begin reset > GHC.setContext [] [] > GHC.setTargets [] > _ <- GHC.load GHC.LoadAllTargets > return () compiling this on ubuntu with ghc 7.0.3 $ ghc --make test.lhs -dynamic -package ghc [1 of 1] Compiling Main ( test.lhs, test.o ) Linking test ... vagrant@lucid64:~$ ./test test: <command line>: can't load .so/.DLL for: /usr/local/lib/ghc-7.0.3/ghc-prim-0.2.0.0/libHSghc-prim-0.2.0.0-ghc7.0.3.so (lib/usr/local/lib/ghc-7.0.3/ghc-prim-0.2.0.0/libHSghc-prim-0.2.0.0-ghc7.0.3.so.so: cannot open shared object file: No such file or directory) notice the -so.so link. Change History (5) comment:1 Changed 9 years ago by comment:2 Changed 9 years ago by We ought to make the GHC API work with -dynamic, even if it fails horribly when some packages or modules are not compiled with -dynamic. comment:3 Changed 9 years ago by commit aed43f7a1ed96277e9c14c6ef643eb134d5bf7f6 Author: Simon Marlow <marlowsd@…> Date: Tue Jul 12 12:16:17 2011 +0100 Fix DLL/SO loading (see #5313). The code in here is a bit of a mess. I've fixed up some inconsistencies I can see, but it could do with an overhaul. this is boiled down from using HINT -
https://trac.haskell.org/trac/ghc/ticket/5313
CC-MAIN-2020-05
refinedweb
278
61.43
05-09-2009 Steven D'Aprano <steve at remove-this-cybersource.com.au> wrote: > On Fri, 04 Sep 2009 22:37:15 +0200, Jan Kaliszewski wrote: > >> Named tuples (which indeed are really very nice) are read-only, but the >> approach they represent could (and IMHO should) be extended to some kind >> of mutable objects. [snip] > What sort of extensions did you have in mind? Two useful (from my point of view) concepts have appeared (or been linked to) in this thread -- on python-list and python-ideas: * the namespace/AttrDict concept (see Ken Newton's, Nick Coghlan's and my posts). * record concept (see George Sakkis post). >>. I don't think so, especially if we say about the former. IMHO it is simply useful in practice, especially for scripting (but not only) -- being more convenient than using empty class. It offers (in compact way, without additional efforts and verbose syntax -- once you have got such a tool implemented) three things at the same time, without necessity to choose between them: comfortable static attribute access, flexible dict-like dynamic access when needed and possibility of iteration. > It's just a change in syntax. Whether you write x.key or x['key'] is a > matter of convenience. Attribute access is optimized for when you know > the key names at compile time, key access is optimized for when you don't > know the names until runtime. Exactly. It is a matter of *convenience* (as well as large areas of Python) and that's the point. I suppose that that is the reason for people to repeatedly implement it for themselves. 05-09-2009 Steven D'Aprano <steve at remove-this-cybersource.com.au> wrote: > On Fri, 04 Sep 2009 22:51:39 -0700, Ken Newton wrote: [snip] >>. > > If you do need such functionality, it's easy to implement. Here's one: Neither you nor me have hard evidence about popularity/unpopularity of the idea (number of places where you can find similar, more or less successful, attempts to implement it seems to testify in favour of the idea) -- nor about how it is used or abused. Obviously there are a lot of bad programmers who are able to use globals instead of function arguments etc.... Thats the fate of every language feature. But it's not the reason to resign from a feature that has particular common and proper use-cases. Even official Python tutorial mentions a case that is typical for the matter: > As a > general rule, if obj.x is an attribute, then every valid obj should have > an attribute x. But if obj['x'] is a key/value, then it is data-specific: > some instances will have an 'x' key, and some won't. It's often true but not always (see e.g. the above example in docs). Cheers, *j -- Jan Kaliszewski (zuo) <zuo at chopin.edu.pl>
https://mail.python.org/pipermail/python-ideas/2009-September/005661.html
CC-MAIN-2018-05
refinedweb
479
63.59
03 April 2009 14:52 [Source: ICIS news] TORONTO (ICIS news)--HSBC has raised its rating and target price for the shares of Dow Chemical following the completion of Dow’s acquisition of specialty chemicals producer Rohm and Haas, it said in a research note on Friday. The London-based international bank raised its rating to “neutral,” from “underweight,” and it raised its target price to $10, from $5. Dow’s shares closed at $9.94 on Thursday in ?xml:namespace> “We believe that with [Dow’s] asset sale process well underway and with the overhang of a dividend cut, equity issuance, and credit rating downgrade mostly lifted, the stock should start trading on fundamentals again,” the analysts said. The analysts also said the $1.675bn (€1.240bn) price Dow achieved on the divestment of its Morton Salt business to Germany’s fertilizer firm K+S was “respectable.” “We consider this price at the higher end of our and company expectations,” they said. In a K+S conference call on Thursday, analysts said the price was surprisingly low. (
http://www.icis.com/Articles/2009/04/03/9206028/hsbc-upgrades-dow-after-rohm-deal-raises-price-target.html
CC-MAIN-2015-11
refinedweb
178
61.36
Search: Search took 0.02 seconds. - 17 Dec 2012 12:28 AM 1. Yes, i will try with a small peace of code. 2. I'm talking about new generated output file, in this file when "exclude -namespace Ext" is used, all Ext classes are not included, but functions and... - 16 Dec 2012 9:26 AM the sample from first post seems that include all classes (Ext library and application), and "exclude \ -namespace=Ext" simply remove all classes from Ext library, but only... - 14 Dec 2012 9:27 AM Hi, thanks for suggestion, i don't know how this tool work, but using your example, even if I remove " exclude -n Ext", my output file have 0 kb. In my case, the difference is that I don't... - 12 Dec 2012 1:13 PM Can anyone help me with the following scenario: path to Ext library: /var/ext4.1.1a/src/ path to Ext JS application: /var/webapp/app1/ I want to compile a build and extract into one JS file... - 31 May 2012 9:51 AM - Replies - 89 - Views - 50,928 Hi Doug, when you estimate to get done a functional release of ManagedIframe 4 for Ext 4.1.0 version ? You said that a simplified version (for simple needs) exists on /examples/ux/Iframe.js. Can... Results 1 to 5 of 5
http://www.sencha.com/forum/search.php?s=f915258582599226454b16c371025dba&searchid=9885274
CC-MAIN-2015-06
refinedweb
224
71.34
Description Using the standalone web server, I want to add a moin parser - I can add TEST.py to my wiki-instance/plugin/parser and nothing happens (even after re-starting the server). - I can add TEST.py to site-packages/MoinMon/parser and nothing happens. The solution I discovered (after much annoyance) was to make sure that the .py file had already been compiled into a pyc file (I did this by importing MoinMoin.parser.TEST froma command line python shell). This may only occur with the standalone server (I haven't tested any others, but I seem to remember similar problems in the past; possibly under Apache: in particular, never being able to put my parser into the wiki-instance, possibly for this exact same reason). Steps to reproduce - copy CSV.py to TEST.py in the site-packages/MoinMoin/parser directory - call both the CSV and TEST parsers TEST won't work. now, run python -c "import MoinMoin.parser.TEST" re-load the wiki-page and TEST will now work. Example see above description. Component selection parser loading code (ie where it determines which parsers are available) (maybe wikiutil.py:wikiPlugins('parser') which ultimately calls __import__() ?) Details Workaround import the module to create a pyc. Discussion Reporter - try this: - Copy new parser module to your wiki/data/plugin/parser/ directory - Restart standalone server Edit a page and add a new parser invocation e.g. { { {#!foo Text parsed by parser named foo. } } } - The new parser should work Note: If you added the parser invocation before the parser was installed, the page is cached using plain text parser, and the new parser will not loaded until the page cache is deleted. To force the page to render and look for the parser, delete the page cache (More Actions > Delete Cache). (see moin maint cleancache for removing all cache files from all pages) If the problem is different, provide the steps to reproduce it like the steps above. Plan - Priority: - Assigned to: - Status:
http://www.moinmo.in/MoinMoinBugs/NewParsersDontWorkUnlessPrecompiled
crawl-003
refinedweb
333
66.54
The Meta-Object Compiler, moc, is the program that handles Qt's C++ extensions. The moc tool reads a C++ header file. If it finds one or more class declarations that contain the Q_OBJECT macro, it produces a C++ source file containing the meta-object code for those classes. Among other things, meta-object code is required for the signals and slots mechanism, the run-time type information, Doesn't Qt Use Templates for Signals and Slots?_ENUMS()); Priority priority() const; }; generates a makefile that does all the necessary moc handling. If you want to create your makefiles yourself, here are some tips on how to include moc handling. For Q_OBJECT class declarations in header files, here is a useful makefile rule if you only use GNU make: moc_%.cpp: %.h moc $. moc does not handle all of C++. The main problem is that class templates cannot have signals or slots. Here is an example: class SomeTemplate<int> : public QFrame { Q_OBJECT ... signals: void mySignal(int); }; Another limitation is that moc does not expand macros, so you for example cannot use a macro to declare a signal/slot or use one to define a base class for a QObject. Less importantly, the following constructs are illegal. All of them have alternatives which we think are usually better, so removing these limitations is not a high priority for us. If you are using multiple inheritance, moc assumes that the first inherited class is a subclass of QObject. Also, be sure that only the first inherited class is a QObject. // correct class SomeClass : public QObject, public OtherClass { ... }; Virtual inheritance with QObject is not supported.. When checking the signatures of its arguments, QObject::connect() compares the data types literally. Thus, Alignment and Qt::Alignment are treated as two distinct types. To work around this limitation, make sure to fully qualify the data types when declaring signals and slots, and when establishing connections. For example: class MyClass : public QObject { Q_OBJECT enum Error { ConnectionRefused, RemoteHostClosed, UnknownError }; signals: void stateChanged(MyClass::Error error); }; Since moc doesn't expand #defines, type macros that take an argument will not work in signals and slots. Here is an illegal example: #ifdef ultrix #define SIGNEDNESS(a) unsigned a #else #define SIGNEDNESS(a) a #endif class Whatever : public QObject { Q_OBJECT signals: void someSignal(SIGNEDNESS(int)); }; A macro without parameters will work. Here's an example of the offending construct: class A { public: class B { Q_OBJECT public slots: // WRONG void b(); }; }; Signals and slots can have return types, but signals or slots returning references will be treated as returning void. moc will complain if you try to put other constructs in the signals or slots sections of a class than signals and slots. See also Meta-Object System, Signals and Slots, and Qt's Property System.
http://doc.qt.nokia.com/4.6/moc.html
crawl-003
refinedweb
463
53.61
Agenda See also: IRC log -> Accepted. -> Accepted. Regrets from Mohamed -> -> Alex: I'm concerned about parameters being available. We have in-scope parameters and importing parameters and no concept of the delta. Norm revisits the rationale. Alex suffers telecommunications issues and his discussion is postponed Henry: I've been working on DTDs and Schemas and so I've found lots of details. ... I'm still concerned about the question of step naming. It's irritating that because pipelines may have QNames for names that the pipe element has to have a QName rather than an NCName for its step attribute. ... The 99.999% case will be than an NCName will do. ... And there can never be more than one pipeline in scope. Norm wonders why it matters more to Henry than XSLT template names or modes. Henry: Because they were invented at the same time as XSLT. XSLT got to say that the interpretation of QNames was different for mode and template names. ... So at the very least, it seems like calling the QNames but having them follow the old XSLT rules not the Schema rules is a little bit unhelpful. ... Especially since it's a corner case of the extreme sort. I'm not going to lie down in the road, but it seems tacky. ... At the very least, more prose is needed in 5.7 Norm: Let's explore a little bit. Henry: The schema union type of NCName|QName does admit to the right semantics and syntax. Some discussion of the alternatives Henry: What if we said that pipelines like all other steps were named with NCNames. ... And pipeline libraries had a namespace. ... Then you could refer to a pipeline from the outside with a QName but with an NCName from inside. ... The only substantive change is that it requires all the pipelines defined in a library to be in the same namespace. Norm: Uhm, it seems a little arbitrary, but it does solve the problem. Henry: It does seem every so slightly odd to define pipelines in different namespaces in the same library. Norm: Does anyone else have a feeling about this proposal? Proposal: We'll try Henry's proposal: Names of steps are NCNames, pipeline-libraries have a target namespace, all pipelines in that library are in that namespace. Therefore, you can refer to them by QName from outside and NCName from inside. Accepted. Michael: I've been struggle to keep up in the technical discussion, but not necessarily succeeding very well. ... I've exploited that fact by reading them as a sort of stranger. ... The biggest question I have when I read the spec is why are we doing this two-level specification where we have an abstraction and an XML syntax. ... To do that, you need a coherent story about how these two abstractions map to each other. ... As far as I can tell, if you try to read the document solely at the abstraction level, we don't say nearly enough. ... You don't say how our abstractions relate to each other, which ones are legal or not, how they're different from blocks of wood. ... In fact, we rely on the XML syntax for many of these things. ... It would be better to just treat all the extra stuff you need as additional information associated with XML elements. ... I think we thought it was a good idea at the time, but it has turned out not to be. Doing it well would be too expensive. Norm agrees wholeheartedly. Richard: I don't agree. The conceptual sections may not have had anything about the ordering of steps. But it could have done. Norm: Indeed, it could have been done that way, but it would be a lot of work. Are you in favor of improving the conceptual model. <MSM> [They could indeed have done. But when you look at the abstraction level as a thing in itself, the question becomes "why are they doing it this way?" And imposing an order for the purpose of calculating defaults seems like an unmotivated design feature.] Henry: It won't surprise you to know that I have a residual preference for keeping the conceptual model separate, but I also don't think that as thing stand the difference is doing enough work to justify arguing against the editor. ... Looking at XSLT 1.0 as a model, it quite cheerfully talks about templates and template rules independent of the elements, but it doesn't make a big deal about the differenc.e ... I think it's easier to read because it doesn't attempt to go as far as Michael suggests. <MSM> [? I think XSLT speaks about templates only in ways compatible with the statement "a template is an XML element"] Henry: I think it would be confusing to try to talk about only the elements. Michael: Two things: One, the way of talking about things that XSLT 1.0 uses seems about right. With that, I'm in full agreement. But second, Henry believes they're talking about things that are different than the XML elements and I don't think that's the case. ... Perhaps I could be persuaded to believe that XSLT 1.0 postulates a level of abstraction distinct from the elements, but I don't think it does. <alexmilowski> BTW, I absolutely 110% disagree with Henry's proposal. <alexmilowski> Stupid cell phone... Micheal: You don't need to make a big thing of it, and I think the easiest way to do that is to say that it's an element, just like a "for" loop in C is a sequence of characters. ... There are lots of unanswered questions in the abstraction that are trivially answered by the XML syntax. <ht> HST would rather be silent on the relationship, but I'm happy to be ruled by what the editor finds congenial and/or we find out what XSLT actually does in this regard Norm: I don't hear anyone objecting to the editor attempting to merge the two sections. Richard: "A template rule is specified with the xsl:template element..." In fact, they have three different things: they have the template rule, the xsl:template, and the template itself. ... There's something abstract here. No objections. The Editor will try. Norm: Alex, would you like to revisit the QName/NCName step issue. Alex: A p:import can import a single pipeline that isn't in a library. ... That's a feature that we'd lose if we did this change. Norm: Indeed, that is the case. Alex: I think QNames are really simple. Norm recounts Henry's objection vis-a-vis interpretation of unprefixed names. Alex: Yes, but some people think that Schema got that wrong. MSM: Does the definition of QName specify where the namespace bindings come from? I don't think it does. ... My instincts tend to be with Henry here, but I want to understand the technical issue. ... The Namespace spec says that the way that unqualified element and attribute names are resolved is different. XSLT 1.0 goes further. And XSLT 2.0 goes even further with respect to funcction names. ... I think we could say that interpreting step names it works this way, and I don't think that's incompatible with the way that QName is defined. ... And we could write a last call comment on the datatypes spec if we do find that. ... And if it isn't clear, we could comment on that too. Henry: With respect to the datatypes spec, I think it is clear that the in-scope namespaces in the infoset is referred to. ... I think it's very clear that it is an error to have an unqualified name of type QName in an instance document if there's no binding for the default namespace. ... We can certainly write our own rules. It's the fact that 99.999% of the time NCNames are all that's needed. ... I'm not at all clear that the case Alex mentioned should be enough to change our position. <MSM> [W.r.t writing our own rules - I think the point of disagreement here may be just whether doing so means we ought not to use the QName type, or must use a union of NCName and QName.] There's no way to predict if importing pipelines or pipeline-libraries will be more common. Henry: I still like the resolution above and what it amounts to when importing single pipelines is that you risk a name conflict. Norm: We did resolve this. Is there anyone that on the basis of Alex's observations wishes we'd resolved it differently? No one heard. Norm: Has anyone looked at the draft that includes options? Henry: Yes, a while ago. It looks good on the face of it, but I haven't looked at it line-by-line. Mohamed: I looked at it. ... I found the way that it's explained reflects the discussion, so I think we should keep it. Norm: Anyone want to reject the options draft as the status quo. Accepted. Norm: Did anyone see anything in the 28 Feb draft that they'd object to seeing in the next public draft. Mohamed: I'm concerned about the consistency of viewport-source, iteration-source, and xpath-source. ... I don't find the explanation about why some are one way and some are not very clear. ... I think sequences are just not very clear at a deep level. <MSM> [Checking the current Datatypes spec diff w/1.0, I don't see any mention of [in-scope namespaces] in the section on QName. There's a note that says that the mapping requires a namespace declaration to be in scope for the mapping to work, but that doesn't seem to determine the treatement of unqualified names. (It appears to contradict the normal assumption that if there is no default ns declaration, the QName mapping is well defined.)] Norm: I'll publish a new draft this week that I'd like to vote on for making public at the next telcon. <alexmilowski> [That seems more consistent with XSLT vs XQuery ] Norm: So next week, I'll see if anyone has any show-stoppers and then we'll look at the component list. No one objects to that plan. Henry: I would like to see the various schemas appearing in the draft. <ht> Michael, you are right, and I was wrong -- only Schema Representation Constraint: QName Interpretation in Part 1 is unequivocal, and _it_ as written only applies to attrs of type QName (not elts), and _could_ be claimed to only apply to attrs in schema docs Ok.
http://www.w3.org/XML/XProc/2007/03/15-minutes.html
CC-MAIN-2015-32
refinedweb
1,785
73.37
Full Text Search: The Key to Better Natural Language Queries for NoSQL in Node.js Watch→ Answer: There are a couple of different ways that you can "apply" an XSL document to an XML one, depending upon what you are trying to do. If you simply want the XML document to always use the XSL filter as a style sheet (somewhat analogous to CSS), then you can simply place a header for the XSL document as a namespace link: However, one of the benefits for using XSL style sheets as independent entities is that you can apply different style sheets, depending upon the desired output. Using the MSXML DOM, you can accomplish this through the transformNode() function. In an IE5 Web page, you could output this as follows: You should never explicitly need a CAB file when working with IE5 for the XML capabilities, as those files are already implicitly available in the IE5 download. Please enable Javascript in your browser, before you post the comment! Now Javascript is disabled. Your name/nickname Your email WebSite Subject (Maximum characters: 1200). You have 1200 characters left.
http://www.devx.com/tips/Tip/25142
CC-MAIN-2018-13
refinedweb
185
59.33
Introduction We all know that vulnerabilities in web pages are quite common these days. They range from SQL injections, XSS vulnerabilities, CSRF, etc. In this article we’ll provide basic examples of the most common vulnerabilities you’ll find in web pages—including and especially WordPress. We’ll describe them in detail below. 1. DoS (Denial of Service) The denial of service happens for various reasons, but we won’t describe anything like attackers trying to DoS a specific web site with a botnet of compromised computers, but we’ll rather describe how a DoS vulnerability can happen when writing a code. Usually we have to make a logical mistake to create a DoS scenario in our web application. Let’s present such a scenario with a little PHP code. The code below is a PHP sample code that contains a logical error that can be exploited to cause a denial of service. 1 <?php if(empty($_GET['file'])) die('You didn't enter the file parameter.'); $file = $_GET['file']; if(!file_exists($file)) die('The chosen file does not exist.'); include($file); ?> 1 In the above code, we're first checking whether the file parameter exists. If yes, we're reading the value stored in the file parameter, otherwise we're closing the application with an error message that says that we didn't enter the file parameter. Thus, we have to provide the file parameter in order to continue execution of the application. After that, we're reading the value stored in the file parameter and checking whether the file exists. If it doesn't, we're again closing the application with an error message about a non-existent file. But if a file does exist, we're including it into the current application execution. From the above code it's not instantly evident that the code contains a vulnerability that can result in a denial of service. Let's say that we saved the above code as index.php and we're supplying a value of "testing.php" in a file parameter. In such a scenario everything works fine as long as the testing.php file exists and does some work. But what happens if we provide index.php as a value for the file parameter. In such a case, the index.php file is including itself into the current execution, and this happens infinitely, resulting in a denial of service. By default, the operating system allocates just so much memory to each application, and if that application wants more memory, it is usually forcibly closed by the operating system. This is exactly what happens in this case. When the index.php allocates as much memory as permitted, the operating system forcibly closes it. Let's also present a request that we would have to send to the above application to force a DoS. Such a request is presented below: GET /index.php?file=index.php HTTP/1.0 SQL injection vulnerability is still quite common these days even though it's been present for over ten years. SQL injection vulnerability happens when the application isn't checking the input values for special characters and encapsulating them, and uses the inputted value in the SQL query. An example of such an application can be seen below: 1 <html> <body> <?php $show = 1; if(!empty($_GET['username']) and !empty($_GET['password'])) { $user = $_GET['username']; $pass = $_GET['password']; mysql_connect("localhost", "admin", "admin"); mysql_select_db("db"); $result = mysql_query("SELECT * FROM users WHERE username='".$user."' AND password='".$pass."';"); $row = mysql_fetch_row($result); if($row) { echo "Welcome user: ".$user; $show = 0; } } ?> <?php if($show) { ?> <form action="#"> Username: <input type="text" name="username" /><br /> Password : <input type="password" name="password" /><br /> </form> </body> </html> <?php } ?> 1 We can see that we're checking whether the parameters username and password exist and have a correspondent value. If they have, we're reading the values into the $user and $pass variables. Afterwards we're connecting to the SQL database on localhost:3306 with a username admin and password admin and selecting the database db. Then we're constructing an SQL query sentence in which we're including the exact values from the username and password inputted values without checking it for special characters. But we should do that, because the above code is vulnerable to SQL injections, because we're not encapsulating the username and password inputted values. Imagine that we enter a value ' OR 1=1--' into both the username and password field. After that the constructed SQL query will be as follows: SELECT * FROM users WHERE username='' OR 1=1--'' AND password='' OR 1=1--'' This effectively selects all users from the table users because of the OR directive we've passed to the vulnerable application. The above SQL query is always evaluated to true and we don't need to enter the right username and password, which would log us into the application. Instead we can enter special input values to break the logic behind the application and login nevertheless. 3. CSRF (Cross-Site Request Forgery) The cross-site request forgery vulnerability is present when we can plant a request to the user, which is then sent to the targeted web site in his/her name. The request then executes certain action on the target web site in the user's name. There are two questions we need to ask ourselves: - How can we plant a request to the user? - What kind of action can we execute on the target web site? The answer to the first question is simple. We can plant a request to the user in various ways through which the end goal is the same: the user's browser has to send the request to the target web site on one way or another. We can plant the request to the user in one of the following ways: - In case the target web site is vulnerable and we can temporarily inject some code into it, we need to construct the right URI that we sent to the user, who must click on it. Upon clicking on the URI, the initial request will be sent, but because of the vulnerability a second request will be made to request the action that we specified. - In case the target web site is vulnerable and we can permanently inject some code into it, we can simply insert another request into the source code of the web page. When the user visits that specific web page sometime in the future, our custom request will be executed in the user's name. This approach doesn't even need social engineering to work, because all the user has to do is visit the vulnerable web page. - We can also construct our own web page, which we have total control over. This is why we can include the code that will do the malicious request in the source code of the web page alone. But in the end the user must still visit that web page, which is why we must send him/her a link to our own web page. When the user visits the web page, the requests embedded into the web page alone will be executed in the user's name. We can see that there are various ways to plant a request to the user's browser, which must execute the request. But this is only half of the story; we still need to talk about what kind of request we can embed into the web page. The requested action can really be anything we like, but the targeted web page must support that action and execute accordingly. Let's say that we programmed the web page presented below: <html> <body> <img src=""/> </body> </html> When the user visits this web page, a new request will be made requesting the index.php resource on the web page "" with parameters id=1000 and action=up. Now, if that web page doesn't have the resource index.php the request will fail. But if the index.php is present but doesn't use the parameters id and action, the request will again fail. This means that we need to know about the files present on the targeted web page as well as the parameters that the web page uses to do some action. This way we could alter the results of the survey, where we would make a request that would vote for the first candidate of the survey instead of the other (which might be more popular). After that we would need to attract users to our page, so the voting requests will be sent to the survey as well. But this is just a tip of the ice berg; imagine what we could do if we could send requests that would add another administrator user to some database, delete all the usernames, or even send arbitrary emails to contacts in users' mailbox signed by that user, etc. Now we're going to explore other web vulnerabilities, which are also both prominent and common. XSS (Cross-Site Scripting) This attack is arguably as common as the original three. The cross-site scripting attack allows us to inject arbitrary code into the vulnerable web page, which we can use to obtain sensitive information like usernames, passwords, cookies, etc. With the XSS attack we can circumvent the same-origin policy, which is present in all scripting languages executing at the client-side in a web browser. An example of such a language is Javascript. The same-origin policy allows the web browser to execute the client-side code only on a web page from which the code originated. There are three types of XSS attacks: a. Reflected XSS The webpage is vulnerable if it accepts the user input and displays its contents on a web page without proper validation of special characters like slash ('/'), apostrophe ('"'), etc. In such cases we can include a Javascript in the URI that we send to the user, which clicks on a link. Upon that, the included Javascript is executed in the users' browser. The Javascript can grab the users' cookie and sends it to the attackers' network. An example of an application that contains the reflected XSS vulnerability is seen below: <html> <body> <?php if(isset($_GET['p'])) { print "V parametru p se nahaja vrednost: " . $_GET['p']; } else { print "Niste nastavili parametra p."; } ?> </body> </html> First we're checking to see if the parameter p is set and displaying its value without filtering any of the special characters. We can store a Javascript code in a value of parameter p that will be executed when the user clicks on the URI (which also includes that malicious Javascript code). An example of the URI that contains the Javascript code, which will display the user's cookie, is as follows: GET /index.php?p=<script>alert(document.cookie)</script> HTTP/1.1 b. Stored XSS A stored XSS attack is present when we can store the malicious code inside the vulnerable web page permanently. Thus, our code will be executed every time the user visits the vulnerable web page. Because the code is stored right in the web page, we don't have to send emails to users convincing them to click on the link or something. Such a web page must use some kind of a backend database where the user inputted values are stored. When a user visits a web page, those values are taken from the database and displayed on the web page, thus executing the malicious code. c. DOM-based XSS DOM-based XSS attack happens when we send a malicious URI to the user, who clicks on it. But this isn't the same as with reflected XSS attack, because the web site returns a valid non-malicious response (thus the web site is not vulnerable to reflected XSS attack). The attack happens because the web site uses a Javascript code that in turn uses the values from the URI address. An example of a DOM-based XSS is presented in the code below: <html> <body> <script type="text/javascript"> p = document.location.href.substring(document.location.href.indexOf("p=")+2); document.write("V parametru p se nahaja vrednost: " + p); </script> </body> </html> From the source code we can see that we're getting that Javascript back as a response on a request. That Javascript first reads the value of parameter p from the used URI address into a variable p. Afterwards it displays the value of the parameter p. Because of this, the Javascript is actually referring to the value stored in parameter p, which can be a malicious Javascript. Let's say that we're executing the request below: /index.php?p=<script>alert(document.cookie)</script> When the Javascript from the response is executed, it will read the value of parameter p, which is <script>alert(document.cookie)</script> and include it into processing. Therefore the malicious code in parameter p is executed nevertheless, even if the web site itself is not vulnerable to reflected or stored XSS attack. Buffer Overflow Sometimes we can see executable programs being used as part of the application providing unique features. But even though the executables are being used as part of web applications, buffer overflow vulnerabilities still exist. Imagine that a web application is calling a system function to call an executable with the user inputted parameter. This doesn't prevent the buffer overflows that could be present in executables from overflowing the program stack or heap structures. An example of a C program that contains a buffer overflow vulnerability is as follows: void copy(char **argv) { char array[20]; strcpy(array, argv[1]); printf("%sn", array); } main(int argc, char **argv) { copy(argv); } The program accepts an input argument, but doesn't check for the length of the argument. When it accepts the input argument, that argument is sent to the copy function, which copies the argument into a local buffer with the strcpy function call. But there are only 20 reserved bytes in the local array, so if we copy an argument that is longer than 20 characters, a buffer overflow will occur. This will crash the program at least, but a specifically crafted input argument could execute arbitrary code on the target system. Format String Format string is a special vulnerability where the user can control what gets inputted into a function call like printf, fprintf, sprintf, snprintf, vprintf, vprintf, vsprintf and vsnprintf. To understand this attack it's best to look at the example. An example code written in programming language C that contains a format string vulnerability is presented below: #include <stdio.h> int main(int argc, char **argv) { printf(argv[1]); return 0; } We can see that the program accepts one input argument, which is directly passed to the printf function call. By default, the program echoes the input argument on the screen, but what if we enter some special character that the printf function will treat differently, like %n, %x or %s. If we enter the special character %x, the printf function will output four bytes from the stack, if we enter two %x characters, the printf function will output eight bytes from the stack, etc. This happens because we've called the function printf without the necessary parameters, which should be present. But the function can't know if those parameters are present or not and takes the next value from the stack (where the missing parameter should be). With the %x we can read arbitrary values from the stack, whereas with %n we can write an arbitrary value on an arbitrary address in the memory. With both the %x and the %n, we can gain control over the execution of the program and execute arbitrary code. Directory Travers The working directory traversal vulnerability can be present in an application that allows the users to read the files from the filesystem, but fails to properly identify which file the user is allowed to read. The vulnerability is usually present because the application doesn't check what file the user is trying to read. The basic problem is that application is not checking whether the user is trying to move up the directory chain into the parent directory with the use of special characters "../" or "..". Therefore the user can not only read files from the allowed directory, but also from all other directories the application has access to. An example of a vulnerable application written in PHP is <?php if(empty($_GET['file'])) die('You didn't enter the name of the file.'); $file = getcwd().'/'.$_GET['file']; if(!file_exists($file)) die('The filename doesn't exist.'); readfile( reading the file from the constructed path and displaying it to the user. The problem occurs because we're not checking for any malicious characters in the value of parameter p. This allows the attacker to traverse up the directory tree by using the special sequence of characters "../" or "..". Let's present the request that would read the file /etc/password from the system even though the application doesn't have access to that file. The request would have to look something like as follows: GET /index.php?file=../../../../etc/passwd HTTP/1.0 This effectively reads and displays the system file /etc/password that contains all the usernames on the system. File Inclusion The file inclusion attack is very similar to directory traversal attack. The only difference is that with directory traversal attack, we can only read the file we're not allowed to read, but with file inclusion we're including the file into the current web page execution, thus executing the file we're not allowed to execute. We must know that there are two types of file inclusion attacks: - LFI (Local File Inclusion) Here we're including the local file into current execution. By local file we mean the file that is already present on the server's system. The LFI attack is possible because the application doesn't encapsulate the user inputted data. - RFI (Remote File Inclusion) Here we're including the remote file into current execution. This can happen if the application has an option to upload the file to the server's filesystem. In such cases, we can upload the malicious file from our client to the server and execute it. With this attack, we can upload a malicious web shell onto the vulnerable application and obtain total control of the web server (under the context of the application's user of course). An example of a vulnerable code can be seen in the source code output below: <?php if(empty($_GET['file'])) die('You didn't enter the name of the file.'); $file = getcwd().'/'.$_GET['file']; if(!file_exists($file)) die('The filename doesn't exist.'); include( including the file from the constructed path into the current execution of the web page. Command Injection The command injection vulnerability can be present in an application where the user inputted value can affect the command that gets executed on the server. An example of a vulnerable application written in PHP is as follows: <html> <body> <?php if(empty($_GET['user'])) die('You didn't enter the name of the user.'); $user = $_GET['user']; system("id $user"); ?> </body> </html> In the above code we're first checking if the parameter user exists and if it does, we're reading the value of that parameter into a local variable. After that we're executing the command "id user" on the system. The vulnerability is present because the application doesn't check the inputted value for special characters. Because of that we can execute a second command on the system if we pass a value like "root;ls -l /" in parameter user. The application will then execute the following command: "id root;ls -l /". But because the ';' is a separator between multiple commands, the application will actually execute two commands one after another, returning the result of both of them. Privilege Escalation Privilege escalation attack is the attack where we're using the logical error in the application to obtain privileges to do something we're not supposed to do. This vulnerability often happens in applications that use multiple user roles like unauthorized user, authorized user, administrator, etc. It's redundant to say that some user roles have more permissions than others. For example, the administrator should have the right to add other user accounts, while other user roles shouldn't have that privilege. The vulnerability would then happen if the normal user could create new user accounts nevertheless. Conclusion We've seen that there are many vulnerabilities that we need to watch out for when programming a web based application. We looked at basic examples of most common vulnerabilities and explained them in detail to better present the vulnerabilities out there. This can be a reference of most common mistakes in web applications that web developers can study and use. “Directory Traversal” – “File Inclusion” Did you mean parameter “file”? Great article Again excellent article. nice article keep it up. I miss how to overcome those problems. Maybe in a future article? ;)
http://resources.infosecinstitute.com/web-vulnerabilities-explained/
CC-MAIN-2014-15
refinedweb
3,529
52.7
timeline This provides a back-end for Timelines JS 3. You can use external links to media or link to internal objects. Initial Setup Install it via pip: pip install django-timelines Modify INSTALLED_APPS: INSTALLED_APPS = [ ... "contentrelations", "timelines", ] Set TIMELINES_BACKGROUND_IMAGE_MODEL setting before you migrate the app. This model should be a photo management application that you use. This setting allows swapper to set up the relationship between that model and the timelines models: TIMELINES_BACKGROUND_IMAGE_MODEL = "media.Photo" Set TIMELINES_SETTINGS. The BACKGROUND_IMAGE_RELATED_FIELD is the actual FileField or ImageField on the TIMELINES_BACKGROUND_IMAGE_MODEL: TIMELINES_SETTINGS = { 'BACKGROUND_IMAGE_RELATED_FIELD': 'photo', } Creating Adapters In order to use an existing model in your timelines, you need to create an adapter for it. The adapter allows you to customize or map the information required by Django Timelines to your model. A couple of notes about adapters: - The adapter for a model does not need to be in the same application as the model. This allows you to adapt models installed via pip and which you have no control. - Django Timelines will import the adapters module for every installed application at startup. That’s a good place to put your adapters. Adapter Example from timelines.registration import registry, TimelineAdapter from .models import Photo class PhotoAdapter(TimelineAdapter): def get_headline(self): return self.instance.title def get_clickthrough_url(self): return self.instance.get_absolute_url() def get_credit(self): return self.instance.taken_by def get_text(self): return self.instance.description def get_media_url(self): return self.instance.photo.url def get_thumbnail(self): return self.instance.photo.url registry.register(Photo, PhotoAdapter) Using adapters Adapters define several attributes and their accessor methods. - clickthrough_url and get_clickthrough_url(): a URL that, if provided, adds a “READ MORE” link to the description. Return Noneto omit link. - credit and get_credit(): the credit information for the media provided. - headline and get_headline(): the headline for the slide. - media_url and get_media_url(): the URL to the media for the slide. - text and get_text(): the text of the slide. - thumbnail and get_thumbnail(): a thumbnail for the timeline To minimize the amount of work you have to do, the adapter is smart enough to look for the attribute name on the model instance. Instead of adapter.get_headline() you should just use adapter.headline so the adapter can use its internal logic to get the correct value. When you access one of the required attributes, the adapter first tries the get_FOO() method. If the value returned is “falsey”_, then the adapter looks for the attribute on the model instance. So if your model already has a text attribute, you do not need to define a get_text method unless you wish to modify the value. Defining media for a Timeline or Slide Both Slides and Timelines (for the title slide) define a piece of media to show on the slide. Django Timelines allows either the specifying of an external URL or a link to an internal object. The benefit of an internal object link, is that it can provide the values for the other fields for you, and modifications of the object automatically appear on the timeline. Even if you specify an internal object, you can still override the values provided by that model’s adapter. - Specify the media: - For external URLs, simply enter the value in the Media URL field. - For internal objects, select the model from the Media content type field (only models with registered adapters are shown). Then click on the magnifying glass icon to open a window to browse for an object. You can also create a new object on the fly here. - Set the content fields: - For external URLs, you must set appropriate values manually. - For interal objects, the help text under each of the fields will tell you the default as determined from the model’s adapter. You only need to enter values if necessary. - Modify the background (optional) - Click Use media as background to use the URL or object specified in #1 as the background for the slide. - You can specify an alternative image to use as the background by specifying a Background image. - You can specify a color for the background (default is white). Creating a Timeline - Follow the instructions above in Defining media for a Timeline or Slide to specify the title slide information and background. - In the Other Information section, you can alter the Scale, add Eras (see Eras below) and mark the Timeline as Published. Adding slides to a Timeline - Click on Add another Slide. - Click on the magnifying glass icon. - Select or create a slide. Once you have saved the Timeline, you will see summary data about the slide and a link to edit the slide. - TimelineJS has the ability to organize events in the same row or adjecent rows based on their group. You can fill in the group attribute if necessary. - Enter in the Order if necessary. Slides are automatically sorted by their date. However, since several events could have the same date, use the order field for fine control over them. Creating a Slide - Set a start date and optional time. See Dates, times and resolution below for more information regarding dates. - Optionally set an end date and time. - Set the media and content according to Defining media for a Timeline or Slide above. Dates, times and resolution You can specify a date with variable resolution. The allowed resolutions are: - Year (e.g. 1776) - Month (e.g. July 1776) - Date (e.g. July 4, 1776) - Datetime (e.g. July 4, 1776 at 5:24 PM) Dates are sorted from lowest resolution to heighest resolution, in that: - Year resolution is sorted before January 1 of the same year. Consider it January 0th of that year. - Month resolution is sorted before the 1st of the month of that year. Consider it the 0th of the specified month. - Date resolution is sorted before Midnight of that date. Consider it the -1 AM of that date, since Midnight is 0. - Datetime resolution is sorted according to the time. Eras Eras are used to label a span of time on the timeline navigation component. Eras are reusable across Timeline objects. They consist of a start and end date and an optional label. 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/django-timelines/
CC-MAIN-2017-47
refinedweb
1,040
58.89
If you read my co-worker Neal Hindocha's recent post "Debugging Android Libraries using IDA" you notice he mentioned using a "custom library loader". We had used this on a recent mobile penetration test to have complete control over some home grown custom native libraries the target application was using. The biggest problem we were facing with the test was that the library in question was being used for anit-rooting and anti-debug functionality to protect the app, and part of our job was to bypass this and patch it out. Of course, attaching directly to the running Android app to get at the code in this library was problematic, since most of the protections were likely loaded before we could attach. What we needed was something like dllloader for Olly or Immunity that we could use to load the target .so file independently of the process, so we could have total control and access. Here is what we came up with. While obviously not as feature rich as dllloader, this quick and dirty loader did the job: #include <stdio.h>#include <stdlib.h>#include <dlfcn.h>int main(){ printf("Loading libs\n"); int (*pt2Function)(void) = NULL; //pointer to a void function - change this to match method sig void* sdl_library = dlopen("/system/libtarget.so", RTLD_LAZY); if (sdl_library == NULL) { // report error ... printf("Unable to load library\n"); char *errstr; errstr = dlerror(); if (errstr != NULL) printf ("A dynamic linking error occurred: (%s)\n", errstr); } else { printf("Lib loaded, getting dlysm\n"); void* initializer = dlsym(sdl_library,"JNI_OnLoad"); if (initializer == NULL) { // report error ... printf("Unable to get address of JNI_OnLoad\n"); char *errstr; errstr = dlerror(); if (errstr != NULL) printf ("A dynamic linking error occurred: (%s)\n", errstr); } else { // cast initializer to its proper type and use printf("calling get process\n"); //asm("BKPT #0"); pt2Function = initializer; printf("got get process, setting up\n"); printf("Ok, lets Calling the function"); int result=pt2Function(); printf("Result of call is %d", result); //asm("BKPT #0"); } } return 0;} As you can see, our target was the 'JNI_Onload' function. In our case, we targeted this because it was in this function that the anti-debug and system monitoring functionality was set up. We could have set up the function pointer to point to ANY of the .so's exported functions and called them. This code could easily have been compiled on run on any standard linux system. We used dlopen() to dynamically load the library and dlsym() to obtain a pointer to the exported function we wanted to test. We could then call the target function directly and pass in any parameters (if any) the function took in order to follow code execution or even to fuzz, looking for exploits. The only ARM specific code we had (which it turns out we really didn't need) are the commented out ARM breakpoints. To compile this, you simply use the Android NDK and create an ndk-specific Android.mk file: LOCAL_PATH := $(call my-dir)include $(CLEAR_VARS) # give module nameLOCAL_MODULE := loader # list your C files to compileLOCAL_SRC_FILES := test.c# Build executables instead of a library for android.include $(BUILD_EXECUTABLE) You place the files in the normal Android NDK file structure - code and the Android.mk file, including the C code for the lib goes under the jni directory and your executable will appear under libs/armabi/ directory. To build, you open a terminal in the root of your project directory (same level as jni and libs) and execute the following command: Mike-Park:android-loader mpark$ /path-to/android-ndk-r8e/ndk-build In my case, I created a directory called 'android-loader' that contained jni/ and libs/ and ran from there. After a few warnings, you should get a perfectly useable ARM executable in the libs/armabi/ directory called loader. You can then use adb push to place this in the /system directory (after a remount of course) along with your target .so and run it from there. It works great in the emulator and on the devices we tried. Again, this is a quick and dirty bit of code that works. We used it for debugging with IDA, but it could easily be adapted for fuzzing and to take the library to load from the commandline. I'd like to make it more robust, so any feedback or suggestions are welcome. In the meantime, enjoy hacking android native code.
https://www.trustwave.com/en-us/resources/blogs/spiderlabs-blog/custom-native-library-loader-for-android/
CC-MAIN-2019-47
refinedweb
732
60.35
The team blog for Microsoft Excel and Excel Services. Defined names are a very useful tool for authoring formulas. Defined names allow users to name cell ranges, formulas, and values and refer to those names in their formulas. Used in formulas, defined names make formulas easier to read and more robust. Additionally, when writing formulas, names are less likely to get mis-typed than cell references, and they are easier to remember than cell references (“Tax_Rate” as opposed to “G36”). In this article, I would like to discuss some of the work we’ve done to defined names in Excel 12 – specifically, how we have added new management and creation UI, and how we have added comments to names. The new Manage Names Dialog Probably the most common piece of feedback we receive about defined names is that the user interface we provide to manage names is inadequate. When we visit customers on site, we often see workbooks with dozens or hundreds and even thousands of defined names, which makes tasks like deleting multiple names, renaming names, and finding broken ones challenging. Enter the new Manage Names dialog, which is designed specifically for viewing and managing the defined names in a workbook. The entry point to the Manage Names dialog is in the centre of the new Formulas tab. Here is a shot of the Formulas tab in current builds - you can see a big button titled "Name Manager". (Click to enlarge) When you click on the Name Manager button, you will see the Manage Names dialog. Using this dialog, you can: View existing Defined Names Create New Names Edit existing names Delete Names quickly Sort the Name list Resize the Manage Names dialog Filter the Name List One thing we would be interested in hearing is whether hidden names should be surfaced in this dialog. The current design allows users to show hidden names using a control on the filter drop-down, but they are not displayed by default. Our reasoning for this is that customers tell us hidden names cause many problems for users and generate helpdesk issues. At the same time, some solution providers use them as variables with the knowledge that you can't see them in the UI. Our current design would allow savvy users to find the hidden names without writing code. Note, there is a workaround for solution developers, which is to use very hidden names which can be created by using the hidden namespace in XLM (i.e. SET.NAME). The New Name/Edit Name Dialog While we were improving name management, we set another goal to simplify the experience of creating a name. To do this, we created a dialog that surfaces the UI needed to define a new name or edit an existing name (the title of the dialog changes between New Name and Edit Name depending on the context of how it was launched). Of note is the Scope drop down which allows the user to easily set the scope of their name to a specific sheet or the entire workbook (no more secret knock needed). For mouse users, we’ve made it easier to get to the new name UI by adding a right-click menu option that will launch the dialog with the selected range in its refers-to box. Other entry points exist on the Ribbon and Manage names dialog. Name Comments Finally, I’d like to talk about an enhancement to the Defined Name object itself – we have added a name comment property. The comment property allows the user to document what a name refers to, what it should and should not be used for, etc. This field can be edited from both the UI (New/edit name dialogs) and the OM and is surfaced as the name’s tooltip in formula auto complete as well as in the Manage Names dialog. Some Interesting uses of this field might include Another thing we would be interested in hearing is how would you use the name comment feature. That wraps up "Formula Editing Improvements Week"; I hope you found this interesting. Talk to you next week. Today's author, Charlie Ellis, a Program Manager on the Excel team, shares a spreadsheet he built in PingBack from
http://blogs.msdn.com/excel/archive/2005/10/21/483661.aspx
crawl-002
refinedweb
710
64.85
: public class MonkeySniffer { public static void main(String[] args) { do { System.out.println("Inside the loop!"); } while (3 > 4); } } What the above does, is to print out Inside the loop! once, then it checks the boolean expression in the while statement, if it is true then the loop will be repeated, if it is false, in this case it will be since 3 is not greater than 4, then the loop is done and the code will continue. Thats it really, nothing too fancy here, this loop is really suited to situations where you must do something at least once, but possibly multiple times. Anything I’ve missed please let me know! Happy coding. One thought on “The do-while loop, always executes at least once…”
http://www.jameselsey.co.uk/blogs/techblog/the-do-while-loop-always-executes-at-least-once/
CC-MAIN-2016-50
refinedweb
126
71.04
Ticket #1702 (closed defect: fixed) Scheduler doesn't ever shut down if interval_task was executing when interrupt sent Description If you ctrl-c a turbogears process that has interval_tasks running in it, the interval_tasks will continually be rescheduled forever. Because Scheduler.stop() doesn't stop Tasks from Task.reschedule()ing, a running task can reschedule itself after the scheduler is supposed to be stopped. The problem seems to be in the 1.0 and 1.1 branches. Attachments Change History comment:3 Changed 10 years ago by xentac It's been a while since I thought about this code... But I think one of the problems was that there's no difference between not running and shutting down. If I want to shut down the scheduler, I don't ever want to reschedule anything. You could make a Scheduler.shutdown method that set self.shuttingdown = True and everywhere that you check self.running you check self.shuttingdown also. If self.shuttingdown is True then don't execute anything (vs. queuing in the case of self.running). Then in the startup module make it call scheduler._shutdown_scheduler() instead of scheduler._stop_scheduler(). If having another property doesn't seem like a good solution, make the state an Enum: "stopped", "running", "shuttingdown" comment:4 Changed 10 years ago by xentac I could probably write a patch if my explanation wasn't good enough. comment:5 Changed 10 years ago by Chris Arndt - Priority changed from normal to low - Status changed from new to assigned - Owner changed from anonymous to Chris Arndt Sorry, I can't reproduce this. from turbogears import scheduler def do_something(): print "XXXXXXXXXXXXXXXXX Hello world." time.sleep(20) print "XXXXXXXXXXXXXXXXX Hello again." scheduler.add_interval_task(action=do_something, taskname='do_something', initialdelay=0, interval=10) Killing TH with Ctrl-C shuts down the scheduler normally. Can you post some code, which exhibits the problem? comment:6 Changed 10 years ago by xentac I think the difference in my code vs. this code is I was using the sequential scheduler, not the threaded one. comment:7 Changed 10 years ago by Chris Arndt Please post your actual code and don't keep me guessing. Thanks! comment:8 Changed 10 years ago by xentac scheduler.add_interval_task(taskname='Job Scheduler', action=do_something, initialdelay=10, interval=10, processmethod=turbogears.scheduler.method.sequential) This is how I add the task. Right now, we're using 0.9a6 (I know, it sucks) but the scheduler code hasn't changed significantly since then. If you still can't reproduce it, I will try creating a tg 1.1 project and reproducing it there. comment:9 Changed 10 years ago by Chris Arndt - Keywords confirmed, needs patch added Ok, now I can reproduce it. I'll look into it asap. comment:10 Changed 10 years ago by Chris Arndt - Milestone changed from 1.1 to 1.1.x bugfix I didn't have time to find a solution for this in time for the 1.1rc1 release. If you can provide a patch within next week, I might consider it for 1.1final but probably it will have to wait for 1.1.1. comment:11 Changed 10 years ago by chrisz I think the fix is very easy (see patch), or am I overlooking something? Changed 10 years ago by chrisz - attachment scheduler.patch added Simple patch for not rescheduling after shutdown comment:12 Changed 10 years ago by Chris Arndt Yes, this seems to fix it. I just didn't have the time to look more closely at this problem during the last release preparations. Can you please apply to all 1.x branches? Thanx comment:13 Changed 10 years ago by chrisz - Status changed from assigned to closed - Resolution set to fixed
http://trac.turbogears.org/ticket/1702
CC-MAIN-2019-22
refinedweb
623
67.45
IRC log of svg on 2010-11-04 Timestamps are in UTC. 08:33:44 [RRSAgent] RRSAgent has joined #svg 08:33:44 [RRSAgent] logging to 08:33:46 [trackbot] RRSAgent, make logs public 08:33:48 [trackbot] Zakim, this will be GA_SVGWG 08:33:48 [Zakim] I do not see a conference matching that name scheduled within the next hour, trackbot 08:33:49 [trackbot] Meeting: SVG Working Group Teleconference 08:33:49 [trackbot] Date: 04 November 2010 08:33:51 [ed] chair: ed 08:34:56 [pdengler] pdengler has joined #svg 08:35:33 [anthony] anthony has joined #svg 08:36:40 [ed] Zakim, remind me in 8 hours that anthony is wearing an IE tshirt and opera needs to bring some next time ;) 08:36:40 [Zakim] ok, ed 08:38:15 [jun] jun has joined #svg 08:38:30 [anthony_work] anthony_work has joined #svg 08:39:34 [anthony] scribe: anthony 08:39:38 [anthony] scribeNick: anthony 08:39:44 [anthony] chair: Erik 08:39:53 [anthony] Topic: High Level Scenarios 08:40:24 [anthony] PD: I've been thinking about what we should be working on 08:40:35 [anthony] ... and my thinking is that we have two sets of work 08:40:38 [anthony] ... two chunks 08:40:54 [anthony] ... one is rationalizing all the technologies we have in front of us 08:41:05 [anthony] ... HTML, CSS, SVG and Webapps modules 08:41:15 [anthony] ... I don't think there is any mystery there 08:41:22 [anthony] ... Then there is what are the new things we can do 08:41:29 [anthony] ... and thing I would like to see us do 08:41:48 [anthony] ... is see us do a short release of the integration stuff 08:42:04 [anthony] ... where we say we stablise these technologies 08:42:16 [anthony] ED: I guess it depends on how many people we have working on it 08:42:22 [anthony] ... depends on how many people we have working on it 08:42:29 [anthony] PD: You think it's a resource issue? 08:42:33 [anthony] ED: Yes to some degree 08:42:40 [anthony] ... you can have people working on advance gradients 08:42:48 [anthony] ... and it's just research and syntax 08:43:05 [anthony] ... if it's really separate then it can run in parallel 08:43:27 [anthony] ... When there is something that affects other parts of SVG 08:43:32 [anthony] ... the it becomes tricky 08:43:42 [anthony] PD: There is a finite set of technology 08:43:52 [anthony] ... that can bring it together 08:43:59 [anthony] ... I think it's animation 08:44:59 [anthony] AG: I think it's that and it's also the rendering model 08:45:03 [anthony] ... and how things interact with that 08:45:20 [ed] s/... depends on how many people we have working on it// 08:45:32 [anthony] PD: I think that my first slice with that paper is to say that perhaps solving both problems at once 08:45:34 [anthony] ... would take too long 08:45:49 [anthony] ... What I'm reading is tough luck we need to figure that out 08:46:04 [anthony] ... Let's just decide to do one all the other 08:46:15 [anthony] ... if we do the simpler one then we have something we can achieve 08:46:23 [anthony] ED: I think it's not a small problem 08:46:32 [anthony] ... there are a finite set of things that could easily be targetted 08:46:45 [anthony] PD: I'm watching the developers from RIM who played with it 08:46:49 [anthony] ... and Opera's played with it 08:47:01 [anthony] ED: I don't see any problem with applying transitions to SVG 08:47:13 [anthony] ... there are things where you can use them together 08:47:22 [anthony] PD: That's my question. Is it that if you're both 08:47:28 [Hyeonsoo] Hyeonsoo has joined #svg 08:47:31 [anthony] ... If you're using both 08:47:39 [anthony] ... Opera, Mozilla and Webkit 08:47:43 [anthony] ... and I mixed them today 08:47:48 [anthony] ... would I get the same experience 08:47:50 [anthony] ED: I'm not sure 08:47:54 [anthony] ... they are on the same level 08:47:56 [anthony] ... but if they were 08:47:59 [anthony] ... then yes 08:48:04 [anthony] PD: So it's defined enough 08:48:18 [anthony] ED: Sure SMIL can listen for events 08:48:35 [anthony] ... and trigger the transitions 08:48:45 [anthony] PD: SMIL can listen for events 08:48:47 [anthony] ... and trigger it 08:49:01 [anthony] ED: You can listen for mouse click 08:49:34 [anthony] ... using SMIL and then animate the class name so you get a transition trigger using the class name 08:49:47 [anthony] PD: The thing that I was thinking that might cause collisions 08:49:57 [anthony] ... is first off when there are shared properties 08:50:01 [anthony] ... e.g. Transforms 08:50:17 [anthony] ... lets identify those attributes we want to make properties and resolve those conflicts 08:50:24 [anthony] .... I know we haven't done it across the board 08:50:34 [anthony] ... but we've decided it for Transforms at least 08:50:42 [anthony] ... Let's take opacity which is a property 08:50:45 [jdaggett] jdaggett has joined #svg 08:50:53 [anthony] ... if CSS is animating and SMIL is animating them at the same time 08:51:06 [anthony] ... will I get a interoperable behaviour? 08:51:12 [anthony] ED: Why would you do that in the first place? 08:51:17 [anthony] PD: Only thing I can think of 08:51:29 [anthony] ... is it's accidentally done 08:51:35 [anthony] ... or I've lifted a style sheet 08:51:39 [anthony] ED: It's not defined 08:51:46 [anthony] ... you'd probably get some kind of behaviour 08:51:53 [anthony] PD: That was part of my paper that said 08:51:57 [anthony] ... lets leave that undefined 08:52:03 [anthony] ... unless we decide to work on that 08:53:08 [anthony] ED: I don't think the scenario of animating the same element with two different technologies is a likely case 08:53:24 [anthony] PD: The only thing I can think of there is contrive a scenario 08:54:02 [anthony] s/there is contrive/here, and I'm going to contrive/ 08:54:13 [anthony] ... If I have a banner add animation 08:54:16 [ed] s/scenario of animating the same element with two different technologies is a likely case/scenario of animating the same property at the same time with two different technologies is a likely case, and probably not something you'd want to be doing in the first place/ 08:54:23 [anthony] ... declarative animation 08:54:36 [anthony] ... and there is vector art moving it across the the screen 08:54:39 [anthony] ... using SMIL 08:54:54 [anthony] ... and there is CSS transition where every time I hover over the <g> element it changes the scale 08:54:59 [anthony] ... is that contrived? 08:55:04 [anthony] ... is that a real scenario? 08:55:08 [anthony] ED: Yeah... 08:55:17 [anthony] PD: Maybe we do need to figure this out 08:55:29 [anthony] ED: It's not more complicated than having hover figured out 08:55:37 [anthony] PD: I can use SMIL to change the transform attribute 08:55:40 [anthony] ... right? 08:55:42 [anthony] ED: Sure 08:55:49 [anthony] PD: I'm doing transform translate 08:55:54 [anthony] ... to translate the 'x' 08:56:14 [anthony] ... and then you're using a CSS transition to change the scale function on transform 08:56:21 [anthony] ... I have two things changing the transforms 08:56:31 [anthony] ED: If we have the transforms draft that Anthony is working on 08:56:46 [anthony] ... then you'd apply the SMIL animation then whatever the CSS transition is applied 08:56:54 [anthony] ... so it's being overridden by the transition 08:56:57 [dino] dino has joined #svg 08:57:02 [anthony] PD: So now I have a defined behaviour 08:57:07 [anthony] ... CSS wins 08:57:15 [anthony] ... because that's the defined order of operation 08:57:45 [anthony] ... Lets say I had the <g> as the entire banner 08:58:00 [anthony] ... and I'm SMIL animating the translate transform 08:58:19 [anthony] ... and I use a class to change the inner vector art on the banner 08:58:28 [anthony] ... is that a problem? 08:58:31 [anthony] ED: I think that is ok 08:58:40 [anthony] ... most of these problems that you're trying to figure out 08:58:43 [anthony] ... can be worked around 08:58:59 [anthony] ... it is possible to get the behaviour you want 08:59:19 [anthony] PD: I'm trying to tease out if there are any areas that need to be defined still 08:59:54 [anthony] ... like did the DOM consistently change, I'm trying to think if there are any cases 09:00:04 [anthony] AG: I thought we discussed this at a telcon 09:00:16 [anthony] ... and Alex D said that transitions sits on top of the sandwich model 09:00:33 [anthony] ED: I think the thing that needs to be defined 09:00:37 [anthony] ... is the base valuye 09:00:45 [anthony] s/valuye/value/ 09:01:07 [anthony] ... I think that should be something that goes into the Transitions spec 09:01:19 [anthony] ... when do apply it to the SMIL model 09:01:56 [anthony] PD: Should we find a single area owner to define this 09:02:01 [anthony] ... or do we need to spread it out 09:02:16 [anthony] ED: I think this is a single thing 09:02:26 [anthony] ... that we can give someone an action to follow through on that 09:02:37 [anthony] PD: And you believe that belongs in the Transitions spec? 09:02:39 [anthony] ED: Right 09:03:58 [anthony] ACTION: pdengler to Communicate base value issue between SMIL and Transitions with CSS Working Group 09:03:59 [trackbot] Created ACTION-2889 - Communicate base value issue between SMIL and Transitions with CSS Working Group [on Patrick Dengler - due 2010-11-11]. 09:04:27 [anthony] PD: So the other thing I thought through 09:05:34 [anthony] ... was can or should SMIL work with HTML when it is a foreignObject in SVG? 09:05:43 [anthony] ... and does that start to go through... 09:05:52 [anthony] ... because those properties will keep cascading 09:06:05 [anthony] ED: The thing is you can do the same thing with transitions 09:06:14 [anthony] ... even if you didn't come close to touching it 09:06:20 [anthony] ... I think the same thing applies to SMIL 09:06:35 [anthony] PD: I think a key scenario for SMIL is advertisement 09:06:38 [anthony] AG: I agree 09:06:57 [anthony] PD: And in those I don't want to just animate SVG in an ad. Can SMIL animate HTML and SVG? 09:07:02 [anthony] ... we want it to 09:07:07 [anthony] ED: I guess you could 09:07:18 [anthony] PD: Why would I want stop at a vector graphic with SMIL 09:08:02 [anthony] DS: I think if we are going to have this conversation we should get dino on the call 09:08:11 [anthony] [break for 5 mins] 09:12:39 [shepazu] shepazu has joined #svg 09:16:21 [shepazu] Zakim, call Saint_Clair_3B 09:16:21 [Zakim] sorry, shepazu, I don't know what conference this is 09:16:55 [shepazu] Zakim, room for 3? 09:16:56 [Zakim] ok, shepazu; conference Team_(svg)09:16Z scheduled with code 26634 (CONF4) for 60 minutes until 1016Z 09:17:10 [shepazu] Zakim, call Saint_Clair_3B 09:17:10 [Zakim] ok, shepazu; the call is being made 09:17:11 [Zakim] Team_(svg)09:16Z has now started 09:17:33 [shepazu] dino: can you please call zakim, code 26634? 09:20:47 [anthony] PD: [Brings Dino up to speed] 09:21:38 [anthony] DJ: The combined in the agenda topic - what is that? 09:21:47 [anthony] ED: I haven't really seen a combined proposal so far 09:22:01 [anthony] PD: Are you asking if there is going to be a larger conversation? 09:22:07 [anthony] DJ: Interested in both 09:22:32 [sylvaing] sylvaing has joined #svg 09:23:28 [anthony] DS: Since I.E. is examining the higher level of animation is that of interest to you? 09:23:31 [anthony] DJ: Yes 09:23:44 [anthony] PD: I have a third topic is overlapping technologies 09:23:51 [anthony] ... Today we can talk about Transitions 09:24:20 [anthony] ... I'm assuming that CSS Transitions is a baked spec upfront 09:24:35 [anthony] ... the thing I'm trying to get my head around is how they work together when they are on the same page 09:24:50 [anthony] ... and SVG has SMIL and we were walking through if and any collisions might happen 09:24:58 [hidetaka] hidetaka has joined #svg 09:25:04 [anthony] ... I think the end outcome and in the Transforms spec that Anthony has been working on 09:25:21 [anthony] ... there has been discussion that when the transform or any property gets animated 09:25:28 [anthony] ... by transitions or animations 09:25:34 [anthony] ... there's a defined order 09:25:38 [anthony] ... in which they apply 09:25:45 [anthony] ... so SMIL animates first then Transitions are applied 09:25:48 [anthony] ... is that correct? 09:26:08 [anthony] ... There's an issue about how do Transitions affect the base value 09:26:26 [anthony] DS: As I understand it, SMIL says that it is a separate OM to the DOM and the CSS OM 09:26:35 [anthony] ... they are presentation a but they are higher? 09:26:50 [anthony] ... is that a fair characterization? 09:26:56 [anthony] ED: Not entirely correct 09:27:07 [anthony] ... SMIL is exposed to the DOM 09:27:12 [fantasai] fantasai has joined #svg 09:27:20 [anthony] DJ: I think it is undefined at the moment 09:27:39 [ed] s/SMIL/the animVal (SMIL)/ 09:27:48 [anthony] ... The only thing that Transitions and Animations say that the style value on the element is not effect by CSS Animation 09:28:00 [anthony] ... but if you want computed value 09:28:37 [anthony] ... for an element 09:28:56 [anthony] DS: But for SMIL, it never defined it well? 09:29:05 [anthony] DJ: SMIL defined it's own DOM extension 09:29:25 [anthony] ... I have no idea if implementations do this 09:29:37 [anthony] ... so CSS Animations works at the same level that SMIL does 09:29:44 [anthony] ... if you have a transition running 09:29:48 [anthony] ... and a CSS Animation 09:29:55 [anthony] ... the Animation will always win 09:30:05 [anthony] DS: My suggestion in an earlier SVG telcon 09:30:13 [anthony] ... the SMIL OM is obscure and not very clear 09:30:19 [anthony] ... and we need to resolve the interactions 09:30:39 [anthony] ... between what happens when something is SVGA and Transitions 09:31:00 [anthony] ... SVGA should operate on the same level as a CSS Animation 09:31:16 [anthony] ... so they complement each other 09:31:19 [anthony] DJ: Good idea 09:31:43 [anthony] ... The problem is things like radius on a circle, something that SVGA can animate 09:31:55 [anthony] ... you need to be able to query the current animated state 09:33:15 [anthony] ... Maybe there is some other method to get the current animated value 09:33:28 [anthony] DS: Even if we don't treat them as properties 09:33:35 [anthony] ... even those these are attributes 09:33:40 [anthony] ... we are exposing them to the CSS OM 09:33:47 [anthony] ... because we are allowing them to be animated? 09:34:05 [shepazu] s/we are exposing them to the CSS OM/we could expose them to the CSS OM 09:34:24 [anthony] DJ: So the CSS OM is a bit horrible, the discussion of combining CSSA and SVGA is we should just have a single model 09:34:29 [anthony] ... that would just make more sense 09:34:33 [anthony] ... it would nice 09:34:40 [anthony] ... if we can say windowGetAnimatedElement 09:34:49 [anthony] ... get the current animated state 09:35:09 [anthony] ... You're suggestion to expose SVG properties 09:35:11 [anthony] ... to CSS 09:35:50 [anthony] ... you'd have to come up with some extra mechanism to expose it 09:36:01 [anthony] ... e.g. prefix a name or something 09:36:16 [anthony] PD: I think the interesting thing is to have a consistent query 09:36:24 [anthony] ... to have a way to get what's happening 09:36:30 [anthony] ... which ever is animating 09:36:49 [anthony] DS: If we want to come up with a better way to do the animation 09:36:53 [anthony] ... I'm all for it 09:37:00 [anthony] ... a cleaner neater model 09:37:10 [anthony] ... that works better than the CSS OM, I'd be fine with 09:37:16 [anthony] DJ: We can start small 09:37:37 [anthony] ... It wouldn't be too much of a burden 09:37:53 [anthony] ... I don't know where we are in the discussion 09:38:05 [anthony] ... but CSS animation is about at the same level as SMIL 09:38:15 [anthony] ... and we have to define which overrides each other 09:38:36 [anthony] PD: I think I heard that SMIL and CSSA are at the same level 09:38:46 [anthony] ... but CSSA overrides SMIL 09:39:02 [anthony] DJ: I don't think anyones tried that, but we just have to decide 09:39:18 [anthony] ... my suggestion was have them be applied at the same level 09:39:40 [anthony] DS: I think we are all agreed that we want to get the animated value 09:39:50 [anthony] ... for attributes and properties 09:40:26 [anthony] ... and I think that we are agreed that it should be same object model? 09:40:32 [anthony] ED: Depends on what you mean exactly I guess 09:41:02 [anthony] DS: Computed style is part of the CSS OM and the animated value of attributes is different 09:41:14 [anthony] ... but don't we really want to expose both properties 09:41:23 [anthony] ... we want one mechanism to do that 09:41:24 [anthony] ... not two 09:41:34 [anthony] ED: We have the trait access stuff in Tiny 1.2 09:41:59 [anthony] ... that gives you the animated presentation value or the base value and it works on both 09:42:09 [anthony] ... properties and attributes 09:42:14 [anthony] ... but it wasn't meant for 1.1 09:42:29 [anthony] DS: We're not talking about 1.1 09:42:36 [anthony] ... we are talking about SVGA 09:43:05 [anthony] PD: Here is where my mind is cloudy, the question is one animation model more powerful than an other 09:43:13 [ed] s/but it wasn't meant for 1.1/but it wasn't meant for 1.1 (lacks some things that are defined in 1.1, only covers 1.2T stuff) 09:43:20 [anthony] ... SMIL is more powerful than CSSA 09:43:23 [anthony] DS: In some ways 09:43:36 [anthony] PD: But CSSA is more preferred by web develoeprs 09:43:42 [anthony] .. .because CSS is well known 09:44:02 [anthony] ... CSS doesn't apply to enough things (attributes) where as SMIL does 09:44:10 [anthony] ... I'm caught between so many differences 09:44:27 [anthony] ... is there a single declarative animation system? 09:44:38 [anthony] ... or are we bring them forward together? 09:45:19 [anthony] DS: Core Animation it is very like SMIL with out time containers and other SMIL components 09:45:40 [anthony] DJ: The implementation in webkit uses both 09:45:58 [anthony] ... I wouldn't bring Core Animation into the mix 09:46:02 [anthony] ... I think it's worth nothing 09:46:08 [anthony] ... that when Core Animation was starting 09:46:19 [anthony] ... they found the SMIL animation model as a nice model to follow 09:46:26 [anthony] ... and CSS follows it as well 09:46:34 [anthony] ... forget about syntax and the more complex parts 09:46:46 [anthony] ... like syncing time bases 09:46:56 [anthony] ... and it was really easy to describe that model in CSS 09:47:11 [anthony] ... The reason we applied animations in CSS is it made sense at that level 09:47:19 [anthony] ... it was more familiar to web authors 09:47:29 [anthony] ... and there wasn't a clear way to apply animation to HTML 09:47:55 [anthony] ... the problem is that CSS and SVG is that it's not clear what happens when you combine the two 09:48:09 [anthony] PD: The thing is you have a syntax that is popular 09:48:20 [anthony] ... we get way more compliments on CSSA than we do complaints 09:48:34 [anthony] ... and I don't want to keep adding to CSSA where it's gaining massive adoption 09:48:39 [anthony] ... so there are things we can fix easily 09:48:52 [anthony] ... and SMIL which is also an excellent model to apply to SVG 09:49:02 [anthony] ... it has this legacy where people don't like SMIL 09:50:05 [anthony] DJ: Patrick raised the issue about what direction we can go in 09:50:26 [anthony] DS: I think we agree that SVGA and CSSA should both use the same underlaying model 09:50:38 [anthony] ... if that means simplifying the SVGA model 09:50:41 [anthony] ... then so be it 09:50:50 [anthony] ... because you certainly don't want to implement two 09:51:09 [anthony] ... and we want to have a single API that can apply to both 09:51:24 [anthony] ... I think that is actually two fundamental points of agreement 09:51:32 [anthony] DJ: Yep I agree with that 09:51:46 [anthony] PD: I think you're right, give me some time 09:53:22 [shepazu] zakim, drop Saint_Clair_3B 09:53:22 [Zakim] Team_(svg)09:16Z has ended 09:53:23 [Zakim] Attendees were 09:53:25 [Zakim] sorry, shepazu, I don't know what conference this is 10:13:20 [TabAtkinsTPAC] TabAtkinsTPAC has joined #svg 10:15:05 [anthony] s/... we get way more compliments on CSSA/DJ: we get way more compliments on CSSA/ 10:17:20 [sylvaing] sylvaing has joined #svg 10:17:35 [dino] s/... and I don't want to keep adding to CSSA where it's gaining massive adoption/... it's rapidly gaining adoption so it is important to stabilize the specification/ 10:17:39 [jun] jun has joined #svg 10:18:04 [ed] [back from break] 10:18:58 [shepazu] zakim, call Saint_Clair_3B 10:18:58 [Zakim] sorry, shepazu, I don't know what conference this is 10:19:23 [dino] zakim, room for 3 10:19:23 [Zakim] I don't understand 'room for 3', dino 10:19:27 [shepazu] Zakim, room for 3? 10:19:27 [dino] zakim, room for 3? 10:19:28 [Zakim] ok, shepazu; conference Team_(svg)10:19Z scheduled with code 26634 (CONF4) for 60 minutes until 1119Z 10:19:30 [Zakim] dino, an adhoc conference was scheduled here less than 2 minutes ago 10:19:35 [shepazu] zakim, call Saint_Clair_3B 10:19:35 [Zakim] ok, shepazu; the call is being made 10:19:36 [Zakim] Team_(svg)10:19Z has now started 10:19:48 [adrianba] adrianba has joined #svg 10:21:45 [anthony] PD: I have the questions figure that I want 10:21:53 [anthony] ... but I'm going to have make them as statements 10:22:05 [anthony] ... SVG is an XML format and it's started that way 10:22:13 [anthony] ... and that's why it's attribute based 10:22:15 [anthony] ... correct? 10:22:17 [anthony] DS: Yes 10:22:46 [anthony] PD: And HTML is not? It's a derivative? 10:22:53 [anthony] DS: HTML is a text document language 10:23:00 [anthony] ... SVG is a language to describe shapes 10:23:12 [anthony] ... it makes more sense for attributes to be attributes 10:23:20 [anthony] ... if SVG wasn't XML 10:23:25 [anthony] ... it would've been similar model 10:23:28 [anthony] ... look at VMLL 10:23:33 [anthony] s/VMLL/VML/ 10:23:41 [glazou] glazou has joined #svg 10:23:51 [anthony] PD: One of the things we talked about was, maybe alot of SVG attributes and are presentation 10:24:01 [anthony] ... and should be in CSS and that is not going to happen 10:24:03 [anthony] ... and that is that 10:24:11 [dbaron] dbaron has joined #svg 10:24:12 [anthony] ... I believe that the biggest use case for SVG going forward 10:24:16 [anthony] ... is in an HTML document 10:24:22 [anthony] DS: I think that is arguably correct 10:24:30 [anthony] PD: Then it falls in to web developers hands 10:24:36 [anthony] ... and we want them to adopt it 10:24:51 [anthony] DS: Of course we want them to adopt it 10:25:11 [anthony] PD: They are experienced with document content, CSS and script 10:25:20 [anthony] DS: I want to illustrate some differences 10:25:23 [anthony] .. between HTML and SVG 10:25:38 [anthony] ... if you look at those elements in SVG that are not for marking up text 10:25:41 [anthony] ... such as form 10:25:43 [anthony] ... stuff 10:25:49 [anthony] ... they are heavily attribute beased 10:25:58 [anthony] ... I think similar design choices were made for SVG 10:26:05 [anthony] ... the radius of a circle is presentation 10:26:16 [anthony] ... it's the actually circle 10:26:22 [anthony] ... Path 10:26:28 [anthony] .. .the geometry of the path is the path 10:26:42 [anthony] ... it's not a presentation of the path 10:26:52 [anthony] ... CSS makes more sense for HTML than it does in SVG 10:27:17 [anthony] ... Let me rephrase that SMIL makes less sense for HTML than it does for SVG 10:27:27 [anthony] ... where as CSS animation makes sense for both 10:27:44 [anthony] PD: Are we saying there is a presentation technology for non-presentation and for presentation technology 10:27:55 [anthony] DS: Almost. Having one animation technology that works for both 10:28:00 [anthony] ... makes perfect sense 10:28:08 [anthony] ... but that metric may not make sense for HTML 10:28:40 [anthony] PD: So you don't want to have multiple animation models 10:28:52 [anthony] ... but you are ok with multiple animation syntaxes 10:29:14 [anthony] DS: I'm ok with CSSA being able to animate the radius of a circle 10:29:27 [anthony] PD: In an ideal world we'd have model and one syntax 10:29:32 [anthony] DS: I'm not yet convinced 10:30:04 [anthony] AG: I think you'd what both 10:30:14 [anthony] DS: For chaining animations, you'd want both 10:30:36 [anthony] ... the element syntax is element is better for CSS syntax for somethings 10:30:56 [anthony] DJ: SVGA is an element in the DOM and CSSA is not 10:31:09 [anthony] ... there is no way to get a reference to the CSS object 10:31:14 [TabAtkinsTPAC] Yet. 10:31:52 [anthony] AG: I have written SVG script that modifies the animation in the DOM 10:31:58 [anthony] DJ: T\his is something in SVGA that is currently supported in CSSA 10:32:07 [anthony] ... in an ideal world it would be great to have one syntax 10:32:16 [anthony] ... but I don't think two is necessarily bad 10:32:31 [anthony] ... CSSA may fit better when creating a document 10:32:47 [anthony] ... but SVGA may be good for generated content 10:32:55 [glazou] +1 TabAtkinsTPAC 10:34:40 [TabAtkinsTPAC] That... is all of it? I'm not in the room. 10:34:44 [Liam] Liam has joined #svg 10:35:07 [TabAtkinsTPAC] Oh! 10:35:17 [TabAtkinsTPAC] TabAtkinsTPAC: believes a third syntax, specialized for creating and running animations purely in JS, is desirable as well. 10:35:28 [TabAtkinsTPAC] TabAtkinsTPAC: It should be close to the existing syntaxes, but something like "x = new Animation({0:{top:100}, 100:{top:200}}); x.animateElement(elem);" 10:35:45 [anthony] PD: Elements and attributes aside is it reasonable to predict that CSSA features will be on par with what SMIL does in SVG? 10:35:48 [anthony] DS: Dino? 10:35:57 [anthony] DJ: It is definitely realistic 10:36:10 [anthony] ... It would be possible to get to same level of functionality 10:36:22 [anthony] ... it's just not wanting to keep adding to a sped that's in development 10:36:32 [shepazu] s/sped/spec/ 10:36:39 [anthony] ... it's a point where it's almost getting out of control of what the working group wants to do with it 10:37:01 [anthony] ... Adobe are now demonstrating tools that convert Flash to CSSA 10:37:33 [anthony] ... I see comments that ability to chain animations 10:37:41 [anthony] ... have one animation start at the end of another one 10:37:50 [anthony] ... which would be easy to add and implement 10:38:25 [anthony] ... I dunno how much we want to change CSSA until we get some base level 10:38:49 [anthony] DS: High level comment - I really want Adobe to start attending these telcons. From Dreamweaver or Flash 10:38:59 [anthony] ... it's hard to guess what they're intentions are 10:39:30 [anthony] DB: There has been some discussion if you have the same feature sets 10:39:33 [anthony] ... and the same model 10:40:07 [anthony] PD: I would love for Apple to attend these telcons more frequently 10:40:15 [anthony] DB: and my understanding is that some of the model is substantially different 10:40:32 [anthony] ... I don't know how unified you want the model to be 10:40:52 [Liam] Liam has joined #svg 10:41:05 [anthony] DS: Dino is saying that the models can be completely unified 10:41:13 [anthony] DJ: I'm not a CSS expert 10:41:20 [anthony] ... but as far as animations go 10:41:28 [Hyeonsoo] y 10:41:31 [anthony] ... then yes 10:41:47 [anthony] DB: I thought mostly about transitions and how they interact with SMIL 10:42:01 [anthony] DS: I have to confess that I have not looked much at transitions 10:42:13 [anthony] ... as I understood it they were CSSA country cousin 10:42:27 [anthony] DB: Because of their model they have to fit in a specific place 10:42:47 [anthony] ... and animations to a degree is built on top of transitions 10:42:51 [hidetaka] hidetaka has joined #svg 10:43:01 [anthony] DJ: That might be just a fall over 10:43:10 [anthony] ... that as a implementer that they are really the same implementation 10:43:23 [anthony] ... but I think they are fairly separate 10:43:40 [anthony] DB: The way I read it was you declare points and force how to transition between the points 10:43:52 [anthony] DJ: I would say that animations would apply on what the current style is 10:44:02 [anthony] ... at the code level it's the other way aroud 10:44:07 [anthony] s/aroud/around/ 10:44:20 [anthony] DJ: Transitions happen when the current style changes 10:44:26 [anthony] ... Animations trump that 10:44:34 [anthony] ... and will always compute the final style 10:45:24 [anthony] DS: Patrick you started this session by saying you know the questions you wanted to ask 10:45:52 [anthony] PD: If the use cases and scenarios are the same for HTML and SVG and I'll give one particular scenario which started before 10:46:00 [anthony] ... which is an advertisement 10:46:09 [anthony] ... if the scenario is the same and the developer is the same 10:46:22 [anthony] ... why shouldn't the syntax and the underlying model should be same 10:46:45 [anthony] DS: I think that if the same functionality is going to be same; if they cover the same things 10:47:01 [anthony] ... I think it makes sense for the same developer use the same syntax 10:47:08 [anthony] ... and that syntax is the CSS syntax 10:47:42 [anthony] PD: How do you make the syntax the same when SVG is attribute based 10:48:14 [anthony] DS: I perfectly ok with CSS animating SVG attributes in some way 10:48:21 [anthony] ... even though they are attributes they can still be animated 10:48:38 [anthony] ... and this new API (similar to traits maybe) the way of getting the animated value 10:48:49 [anthony] ... access is both equally 10:49:28 [TabAtkinsTPAC] TabAtkinsTPAC is also fine with CSS animating attributes. I'd prefer it, actually, to be available more widely than SVG. 10:49:29 [anthony] SG: In orders to use animations those attributes become properties in the sytle sheet 10:49:38 [anthony] s/sytle/style/ 10:49:49 [anthony] PD: Isnt' there is alternative way? 10:49:51 [anthony] SG: No 10:50:09 [anthony] PD: Lets't take the case where there is an attribute that has a corresponding property 10:50:39 [anthony] ... and if you set a style sheet with rect and a width=100 and the style sheet has a width=50 10:50:43 [anthony] ... how do you solve that case 10:50:49 [anthony] .. how do you solve the 'd' case 10:50:57 [dino] it's ugly, but you could do something like -svg-rx: 10px; 10:51:30 [anthony] DJ: One suggestion is you put some kind of namespace on properties that come from SVG 10:51:37 [anthony] ... maybe you don't allow them as property names 10:51:42 [anthony] ... in that they can't be set in animations 10:51:47 [pdengler] pdengler: would you consider attrib-rx: 10px 10:52:05 [anthony] s/set in animations/set in CSS/ 10:52:09 [anthony] ... but are able to be animated 10:52:33 [anthony] DB: From a CSS perspective you'll pay most of the cost of making them properties 10:52:46 [anthony] DS: I have no problems with making them properties 10:53:13 [anthony] ... we need to check to see if it makes sense to make them in to CSS 10:53:37 [TabAtkinsTPAC] TabAtkinsTPAC reiterates that he's in favor of animating arbitrary DOM properties. 10:54:34 [anthony] AG: I don't care what model we use, but as long as the animation lives in the DOM 10:54:47 [anthony] ... so agree with Tab 10:55:28 [anthony] PD: When we animate opacity with CSSA it affects the DOM 10:55:33 [sylvaing] but what's a 'dom property' ? do you want to animate offsetWidth or the type attribute ? animating style properties is the primary scenario imo 10:56:08 [TabAtkinsTPAC] TabAtkinsTPAC: Yes, animating offsetWidth is what I'm talking about. And arbitrary attributes on elements. 10:56:15 [anthony] DS: It is likely that people will use both 10:56:25 [anthony] PD: I don't think they'll use both 10:56:27 [dbaron] I'm curious what "affects the DOM" means above 10:56:40 [glazou] glazou has left #svg 10:57:02 [sylvaing] except offsetWidth is read-only so it makes no sense really 10:57:06 [anthony] DS: I'm saying that in my idea of the unified model, that SVGA can be done with element syntax 10:57:16 [anthony] PD: I'm not saying kill that off 10:57:31 [anthony] ... but I don't know what the issue is 10:57:48 [anthony] DS: Chris has claimed that the CSS WG is against taking on a bunch of properties 10:58:01 [anthony] DB: Some people don't want more and more properties 10:58:09 [anthony] SG: But it still happens anyway 10:58:19 [anthony] PD: If you want more functionality... 10:58:21 [TabAtkinsTPAC] TabAtkinsTPAC: sylvain, argh, you're right. Sorry. Properties that are writeable. 10:58:55 [anthony] DB: Would want to Homecome in on this discussion 10:58:59 [sylvaing] tab, sure but aren't the ones of most interest to authors style properties 10:59:11 [dbaron] s/Homecome/Håkon/ 10:59:29 [anthony] PD: There is at least an underlying model for SVGA and CSSA 10:59:40 [anthony] ... and there are developers who will not deprecate SVGA 10:59:57 [anthony] ... and if we can allow CSSA to do more with SVG 11:00:25 [anthony] ED: What do you include in the underlying model? 11:01:39 [anthony] DS: same underlaying data model 11:01:43 [anthony] ... same functionality' 11:01:51 [anthony] ... share data model 11:02:08 [anthony] ... when you change it in SVGA it is exactly the same if you changed it with CSSA 11:02:13 [anthony] ... they have the same effect 11:02:18 [anthony] ... accessed through the same API 11:02:25 [anthony] ... and they have the same value 11:02:40 [anthony] ... however that proposal is managed 11:02:53 [anthony] DB: What's separate from computed style? 11:03:29 [anthony] DS: I think we can agree we want the same underlying feature set 11:03:59 [anthony] ... and data model 11:04:47 [anthony] SG: We can resolve to have a proposal based on that 11:05:16 [TabAtkinsTPAC] TabAtkinsTPAC: sylvaing, yeah, style properties are the most common now. But we're, for example, experimenting with hooking up js-based models with elements directly, so you can auto-monitor/respond to attribute changes. So I'd like to keep it open to animate arbitrary attributes at least, even if we don't directly address it yet. 11:06:24 [TabAtkinsTPAC] TabAtkinsTPAC: It's probably okay if that's only possible via the js api. 11:06:27 [anthony] RESOLUTION: To have a proposal to have the same shared data model and functionality across SVGA and CSSA 11:07:35 [anthony] ACTION: Dino to Work with PatrickD on drafting up a proposal for the same shared data model and functionality across SVGA and CSSA 11:07:35 [trackbot] Sorry, couldn't find user - Dino 11:07:54 [anthony] ACTION: Dean to Work with PatrickD on drafting up a proposal for the same shared data model and functionality across SVGA and CSSA 11:07:54 [trackbot] Created ACTION-2890 - Work with PatrickD on drafting up a proposal for the same shared data model and functionality across SVGA and CSSA [on Dean Jackson - due 2010-11-11]. 11:11:44 [anthony] DS: My suggestion is that based on conversations with Dion is that the CSS OM is not necessarily the most efficient way of handling the animations 11:11:53 [anthony] ... and we would want an API to inspect the data model 11:11:55 [dino] s/Dion/Dean/ 11:12:20 [anthony] ED: Inspecting the data model and not just the values would be useful 11:12:26 [TabAtkinsTPAC] TabAtkinsTPAC: CSSOM, as currently exists, is the suckiest way to handle the data model. Its only virtue is that it exists. 11:12:48 [dino] Dean: I agree with Tab. 11:13:00 [anthony] AG: +1 with what Tab said 11:13:15 [anthony] DS: As part of the effort going forward we would like to define this API 11:13:21 [ed] s/model and not just the values would be useful/model and not just the animated (presentational) values would be useful/ 11:13:27 [anthony] PD: In terms of what Dino is going to write up 11:13:35 [anthony] ... one of the things I want to stress 11:13:49 [anthony] ... we need to keep this channel open with the CSS Working Group 11:13:49 [dino] DJ: Another positive outcome of such API investigation is that it *might* open the door to simplification of the SVG DOM - we might not need the whole .baseVal thing any more. 11:14:55 [anthony] DS: It's a separate discussion, but it's my hope as well 11:15:00 [anthony] ED: It is a separate discussion 11:16:06 [anthony] JF: I think we should have someone from Adobe to discuss the interface 11:16:15 [anthony] DS: I think you're absolutely right 11:16:27 [anthony] DB: You're talking about an API to trigger one animation to the other 11:16:37 [anthony] DS: A way to access the current state of animations 11:17:00 [anthony] DB: So one way was to animate from one value to another, and the other 11:17:14 [anthony] ... is an API to give the page a notifications a time that it should update stuff 11:17:50 [anthony] ... to give pages the ability to animate that can't be done declaratively 11:18:29 [anthony] ... Just giving the browser the ability to update the frame rate 11:18:38 [anthony] ... it's just exposing a small part of the animation model 11:19:02 [anthony] DS: I think that every body agrees here authors would love to have a better animation model 11:19:18 [dbaron] 11:19:34 [anthony] DS: If you want to bring the experiment to the group that would be great 11:21:06 [anthony] DJ: When we start writing up the model, we can propose the API 11:23:37 [Zakim] Team_(svg)10:19Z has ended 11:23:38 [Zakim] Attendees were 11:24:00 [ed] <set attributeName="lunch" to="break" dur="1.5h" begin="0s"/> 11:24:39 [anthony] anthony has left #svg 11:27:56 [myakura] rrsagent, make minutes 11:27:56 [RRSAgent] I have made the request to generate myakura 12:02:01 [myakura] myakura has joined #svg 12:24:53 [jun] jun has joined #svg 12:41:18 [myakura] myakura has joined #svg 12:41:47 [adrianba] adrianba has joined #svg 12:48:33 [sylvaing] sylvaing has joined #svg 12:49:22 [pdengler] pdengler has joined #svg 12:53:22 [kohei_] kohei_ has joined #svg 12:57:50 [shepazu] shepazu has joined #svg 13:00:35 [dbaron] dbaron has joined #svg 13:01:48 [anthony] anthony has joined #svg 13:01:51 [pdengler] scribeNick: pdengler 13:03:18 [smfr] smfr has joined #svg 13:03:41 [smfr] RRSAgent: pointer 13:03:41 [RRSAgent] See 13:03:45 [kennyluck] kennyluck has joined #svg 13:03:51 [ed] [back from lunchbreak] 13:04:04 [plinss_] plinss_ has joined #svg 13:04:06 [pdengler] topic: SVG Transforms 13:04:41 [johnjan] johnjan has joined #svg 13:06:34 [pdengler] pdengler has joined #svg 13:07:23 [anthony] 13:07:39 [homata] homata has joined #svg 13:07:47 [smfr] what's the call-in number? 13:08:34 [shepazu] Zakim, room for 3? 13:08:36 [Zakim] ok, shepazu; conference Team_(svg)13:08Z scheduled with code 26635 (CONF5) for 60 minutes until 1408Z 13:08:49 [TabAtkinsTPAC] TabAtkinsTPAC has joined #svg 13:08:59 [shepazu] Zakim, call Saint_Clair_3B 13:08:59 [Zakim] ok, shepazu; the call is being made 13:09:00 [Zakim] Team_(svg)13:08Z has now started 13:09:19 [dsinger] dsinger has joined #svg 13:10:08 [shepazu] RRSAgent, make minutes 13:10:08 [RRSAgent] I have made the request to generate shepazu 13:10:25 [hidetaka] hidetaka has joined #svg 13:10:36 [pdengler] summary of previous discussion on animations 13:11:01 [jfkthame] jfkthame has joined #svg 13:11:24 [pdengler] resolved that we want to use the same model for data, API and feature set across CSSA and SVGA 13:11:49 [pdengler] shepazu: This is to make sure we are only implementing 1 animation model. 13:12:39 [ed] 13:13:17 [pdengler] return to topic on transforms 13:13:26 [pdengler] topic: transforms across SVG and CSS 13:13:57 [pdengler] anthony: I've been working on the CSS 2d Trasnforms and SVG transforms that are relevant have been merged into 1 spec 13:13:57 [anthony] 13:14:30 [pdengler] anthony: There are still some areas to finish off. It is not as complete as the draft in CSS trasnforms as it is missing the DOM interface; but the rest is well spec'd 13:15:04 [smfr] yep 13:15:15 [pdengler] smfr: On Monday the CSS Working group resolved to move 2d Transforms forward, and the section on animation moved to the transitions spec 13:15:39 [pdengler] anthony: I'd like to work on a single spec that both groups can use 13:15:49 [dsinger] dsinger has joined #svg 13:16:12 [pdengler] chrisl: Sounds like you've done a lot of work; we thought we had agreed to move it to FX for that purpose 13:16:30 [pdengler] anthony: The idea was to use this spec for SVG 2.0 for the transforms chapter 13:16:42 [pdengler] anthony: I'm also happy to commit to helping with tests for that as well 13:17:02 [pdengler] smfr: We have to figure out how the spec gets published 13:17:36 [pdengler] chrisl: what I have seen inthe past, is that once a taskforce is ready to publish, then it is taken back to both working groups 13:18:00 [pdengler] chrisl: Since they are done in parallel, it usually only takes a week 13:18:30 [pdengler] anthony: We don't want to hold up the CSS group, so I can put in the extra hours to bring it up to the same speed as the current CSS 2d Transforms spec 13:18:34 [ChrisL] ChrisL has joined #svg 13:19:26 [Liam] Liam has joined #svg 13:20:17 [pdengler] smfr: With a combined specification, the two languages means that there is additional complexites as certain functions only apply to certain languages 13:21:03 [pdengler] anthony: There are areas in the spec where I had to change some wording that does have to take into account CSS and SVG. 13:22:40 [pdengler] ed: We should make sure that the transform for SVG becomes a presentation property thus little (or maybe no) specifics around SVG have to be mentioned in the CSS specification 13:23:41 [pdengler] action: anthony to spec the SVG Attribute as a presentation property removing the need to keep same behavior as in other presentation properties in SVG 13:23:41 [trackbot] Created ACTION-2891 - Spec the SVG Attribute as a presentation property removing the need to keep same behavior as in other presentation properties in SVG [on Anthony Grasso - due 2010-11-11]. 13:24:12 [pdengler] pdengler: corretino :SVG Transform Attribute 13:24:19 [dbaron] dbaron has joined #svg 13:24:44 [anthony] s/correctino :/correction: / 13:24:53 [smfr] could dbaron approach the phone? 13:24:57 [pdengler] dbaron: What we decided to move the section on animations from the transforms into the transition spec 13:25:13 [ed] s/We should make sure that the transform for SVG becomes a presentation property thus little (or maybe no) specifics around SVG have to be mentioned in the CSS specification/'transform' is defined as a property in the fx-CSS2d spec, but it should probably be explicitly stated how it the integrates into the svg model as a new presentation attribute/ 13:25:44 [cslye] cslye has joined #svg 13:26:05 [pdengler] anthony: One of the issues that olaf pointed out on the mailing list, was how to determine the difference between an SVG Trasnform and SVG Transform property 13:26:26 [dbaron] Also there are two references to FX that say XF by mistake. 13:26:58 [ChrisL] pdengler: if the svg already says a property in css overrides a res artr, the old content still renders and the difference between defaults is only apparent when someone applies styling 13:27:38 [ChrisL] ... so if i put a transform without a default origin, in svg it rotates about 0,0. If I put a transform in CSS is would use the CSS defsult for origin 13:27:49 [ChrisL] ... so existing content does not break 13:28:11 [pdengler] shepazu: We talked before about having different defaults for CSS and SVG with regards to transform orgin 13:28:31 [johnjan] s/ defsult/ default 13:28:39 [pdengler] shepazu: It should have the same default when styled with CSS 13:29:26 [r12a] r12a has joined #svg 13:29:52 [pdengler] pdengler: Then we should only have to worry abou the unit type (def) and then support the more granular API's 13:30:14 [pdengler] shepazu: There is an issue of being able to get any particular point of a transformed element and the reverse 13:30:38 [pdengler] smfr: The CSS workking group at this point doesn't want any script API in the spec 13:30:46 [pdengler] dbaron: I don't think there is an objection there. 13:31:04 [pdengler] dbaron: We have four browser implementation of the transforms spec, and not hold it up for additions 13:31:33 [pdengler] shepazu: My concern is that there is a known solution that is relatively simple to implement. If we don't solve it, they will be scripting around this problem for a long time 13:31:50 [pdengler] dbaron: What's the signature of the method? 13:32:20 [pdengler] smfr: In webkit we have a method on the Window object convertPointFromNode and convertPointToNode 13:32:41 [pdengler] smfr: Folks were resistant to putting new methods on elements, but on the window it wasn't as much of an issue 13:32:52 [pdengler] dbaron: You could also have an API that converted from one node to another 13:33:19 [pdengler] smfr: In the CSS working group, was there an objection to having the jscript API ..... 13:33:24 [smfr] dbaron: was the objection to dependencies on CSSValues primarily? 13:33:45 [plinss_lyon] plinss_lyon has joined #svg 13:33:51 [pdengler] dbaron: There were two objects. There was only one impelmentation of the API, and that we didn't want a new API on CSSValues 13:34:29 [pdengler] smfr: The other issue is that in the CSS spec we have the Matrix API and 2d vs 3d 13:35:10 [pdengler] anthony: I did see that there may be a need to resolve CSS vs SVG Matrix. Would it make sense to have both names as an alias 13:35:35 [pdengler] smfr: Trying to remember if the multiply is backward on one of them 13:35:49 [smfr] multLeft vs multRight 13:35:50 [pdengler] anthony: We should examine this very soon and sort them out 13:36:06 [pdengler] shepazu: I think we would be doing a disservice by not putting this in 13:36:45 [pdengler] smfr: how do we get a spec that we can move forward on 13:36:56 [pdengler] anthony: Resolving the issues with the API is necessary 13:37:08 [pdengler] shepazu: Who had concerns about the script aspects of the API 13:37:20 [pdengler] dbaron: That part of the CSS object model in genereal didn't want additions 13:38:11 [pdengler] sylvaing: For authors to manipulate portions of the transform without having to parse strings 13:39:07 [pdengler] smfr: we need to make sure that the matrix is the same, row major vs. column major 13:39:26 [pdengler] shepazu: Why would there have been an incompatability in the first place 13:39:57 [pdengler] anthony: SVG did it one way, CSS did it another. 13:40:05 [pdengler] shepazu: Could we change the way that CSS is done? 13:40:16 [pdengler] dbaron: It doesn't get exprssed in an API 13:40:43 [pdengler] shepazu: Is it too late to change it? 13:41:00 [pdengler] smfr: We should hold off on deciding on anything until I look into it 13:41:31 [pdengler] shepazu: We should also include the point transformation in the spec regardless of the matrix 13:41:54 [manyoung] manyoung has joined #svg 13:43:40 [pdengler] dbaron: Coordinate system transforms is important across the board 13:43:48 [dbaron] (not just for transforms) 13:44:55 [dbaron] (I guess I don't have strong feelings about one spec or two.) 13:45:15 [pdengler] RESOLUTION: Include the transform to point API in the Transform spec 13:45:27 [smfr] go Zakim 13:45:31 [ChrisL] zakim, get a clue 13:45:31 [Zakim] I don't understand 'get a clue', ChrisL 13:46:10 [shepazu] Zakim, who is here? 13:46:10 [Zakim] On the phone I see no one 13:46:12 [Zakim] On IRC I see plinss_lyon, r12a, cslye, dbaron, Liam, ChrisL, dsinger, jfkthame, hidetaka, TabAtkinsTPAC, homata, pdengler, johnjan, kennyluck, smfr, anthony, shepazu, kohei_, 13:46:14 [Zakim] ... sylvaing, adrianba, jun, fantasai, anthony_work, RRSAgent, karl, ed, trackbot, heycam, Zakim 13:46:19 [pdengler] anthony: We need to have simon finish his action item for the API's. I just need to finish the introduction, and add the SVG examples 13:46:32 [pdengler] ed: Will it supercede the CSS spec, or just become one 13:46:54 [pdengler] ChrisL: If the later edits are in both specs, we should just merge into one 13:47:24 [pdengler] anthony: We need the CSS working group to accept this 13:47:51 [smfr] now i can 13:50:03 [hidetaka_] hidetaka_ has joined #svg 13:50:12 [pdengler] fantasai: Each time the FX has a resolution it should be added as an agenda item for each WG 13:50:26 [pdengler] shepazu: This is a separate topic 13:51:36 [pdengler] shepazu: It is our understanding that these are joint deliverables. The SVG WG doesn' t need a separate reslution as we all attend 13:52:01 [pdengler] shepazu: We didn't take into account the size or the way the CSS working group exeucutes. Does CSS needs a seperate CSS resolution? 13:52:35 [smfr] pdengler: can you minute? 13:52:40 [pdengler] plinss_lyon: Yes, we should make sure we are clear about ownership and terms to avoid confusion about procedure 13:52:57 [pdengler] anthony: I wasn't implying anything 13:53:21 [pdengler] plinss_lyon: I was just relaying back that it added confusion to how the task force works. There aren't really objections, just people looking for more clarity 13:53:54 [pdengler] shepazu: Logistically speaking it would be useful to have our FX taskforce earlier in the week, such that we can communicate these to the CSS working group 13:54:13 [smfr] dbaron: thanks 13:54:24 [pdengler] chrisl: That could happen on Wendesday 13:55:19 [pdengler] chirsl: FX taskfoce on Monday; if we decide to request publication assuming a Thursday date. On Wednesday it can get approvel by the CSS working group 13:57:04 [Liam] Liam has joined #svg 13:59:19 [pdengler] anthony: I have enough work to do to finish this off and work with simon to do so 13:59:50 [pdengler] shepazu: This general process applies across the FX task force so we don't have to resolve this again for filters, trasnforms, animations, etc 14:00:33 [pdengler] topic: filters 14:00:45 [ed] 14:01:12 [pdengler] ed: Above is the proposal for filters, mask and clip path from Mozilla 14:01:42 [pdengler] ed: This is a proposal at this point. I have an action item to move it into the FX spec 14:02:00 [anthony] pdengler: I was just impressed by what was done here 14:02:04 [anthony] ... and I want to move it quicker 14:02:13 [anthony] ... want to get it to the same spot as transforms 14:02:26 [anthony] ... I had seen the implementation but hadn't read this 14:02:41 [anthony] ... The only thing that has potential to make improvements to the model 14:02:49 [anthony] ... does it make sense to have things cascade 14:02:58 [anthony] ... what I saw the implementation doing 14:03:02 [anthony] ... was using the defs 14:03:08 [anthony] .. and using it as a style 14:03:17 [anthony] ... was that an issue with doing that in HTML? 14:03:26 [anthony] ... All in one file 14:03:37 [anthony] chrisL: In that case you'll get the cascading 14:03:42 [anthony] ... if you apply something in HTML 14:03:49 [anthony] ... it will inhert to SVG 14:03:57 [anthony] pdengler: If I want a filter to just apply to HTML 14:04:06 [anthony] shepazu: use name spaces 14:04:15 [anthony] pdengler: If I want to apply a filter just to HTML 14:04:22 [anthony] ... I can't do that with just the SVG filters today 14:04:39 [anthony] chrisL: You mean that I have just a HTML document I want to apply SVG filters? 14:05:12 [anthony] ... In HTML you can have another file in the side and it can be referenced 14:05:21 [anthony] shepazu: I think he's asking where it is defined 14:05:29 [anthony] ... Yes you can 14:05:39 [anthony] ... there is another thing called Canned Effects 14:05:47 [anthony] pdengler: There is a Canned Effects 14:05:54 [anthony] ... and do they apply to SVG 14:06:25 [anthony] chrisL: Don't need to put it in <defs> 14:06:31 [ed] you can also use datauri:s for putting the filter into the stylesheet 14:06:31 [anthony] pdengler: Need to have the SVG in there 14:06:38 [anthony] ... in order to apply the filter to HTML 14:06:43 [anthony] shepazu: Hang on 14:06:57 [anthony] ... [draws example on the board] 14:07:08 [smfr] you could also invent a syntax to refer to a filter in an external file: filter: url(foo.svg#bar) 14:07:29 [ed] smfr: that's already possible 14:07:34 [ChrisL] ChrisL has joined #svg 14:07:42 [smfr] s/invent a/use the :) 14:07:42 [dbaron] smfr, it's the normal way, even... 14:07:47 [ChrisL] rrsagent, here 14:07:47 [RRSAgent] See 14:08:19 [anthony] pdengler: They continue to be and are SVG filters? 14:08:25 [anthony] shepazu: Yes 14:08:41 [anthony] pdengler: So they are SVG 14:08:58 [anthony] dbaron: I think at one point we'd want an alternative syntax 14:09:00 [anthony] ... for CSS 14:09:01 [smfr] i heard *other than canned effects*, right? 14:09:59 [anthony] dbaron: One thing we'll want is more input primitives 14:10:10 [anthony] ... e.g. other sources 14:10:48 [anthony] ... in addition to sourceBackground, sourceGraphics 14:11:45 [pdengler] shepazu: There shouldn't be any 'canned effect' that could not be composed 14:12:06 [ed] s/composed/decomposed/ 14:12:25 [pdengler] dbaron: For CSS you might be able to seperately apply filters to border, background and different portions of the box model 14:12:45 [dbaron] and the contents 14:12:47 [pdengler] shepazu: We are all interested in expanding filters in intereting new ways 14:13:21 [pdengler] fantasai: We made a list of interesting things to filter: background, border, contents and the composites 14:13:32 [pdengler] dbaron: You can achieve the composites with SVG Filters 14:13:54 [pdengler] fantasai: We coudl just start with background 14:14:14 [pdengler] s/coudl/could/ 14:14:19 [smfr] +q 14:15:14 [pdengler] ed: Should they go into the same specification? 14:16:06 [dbaron] ack smfr 14:16:29 [pdengler] smfr: Can we agree that we are going to use the filter property in CSS. The problem being microsoft using <filter> 14:16:36 [smfr] example of filter: 14:16:37 [smfr] filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( 14:16:37 [smfr] src='images/transparent-border.png', 14:16:37 [smfr] sizingMethod='scale'); 14:17:24 [cslye] cslye has joined #svg 14:17:38 [pdengler] chrisl: There is a problem with sites using <filter> is using to detect IE 14:18:01 [pdengler] sylvaing: We don't support this long term, but people use these today 14:18:43 [pdengler] sylvaing: We can allow for the use of the standards <filter> in standards mode support 14:19:07 [smfr] do the MS filters always start with "progid"? 14:20:04 [pdengler] ChrisL: The standard filter property is quite distinct and easy to recognize. 14:20:14 [pdengler] shepazu: We should an informative note in filters specification 14:20:26 [smfr] can we resolve to use the "filter" CSS property? 14:20:59 [pdengler] action: ed to add informative note about how to handle MS <filter> from before 14:20:59 [trackbot] Created ACTION-2892 - Add informative note about how to handle MS <filter> from before [on Erik Dahlström - due 2010-11-11]. 14:21:32 [pdengler] topic: MS Filters that aren't supported 14:21:39 [pdengler] ChrisL: There is opacity 14:22:41 [pdengler] sylvaing: MSFT already has opacity always wins 14:24:41 [pdengler] action: pdengler to submit new filter effects proposals 14:24:41 [trackbot] Created ACTION-2893 - Submit new filter effects proposals [on Patrick Dengler - due 2010-11-11]. 14:25:27 [pdengler] pdengler: There were two models we were thinking of. Introducing new primitives, or opening an extensibility model 14:26:26 [pdengler] shepazu: Are they relatively expensive to implement? 14:26:48 [pdengler] shepazu: It could also take a while to get them right, which makes it useful to have an extensibility model 14:27:17 [pdengler] ChrisL: This is where you need a good authoring tool 14:27:53 [smfr] someone could write a webapp for this 14:28:39 [ChrisL] someone could indeed 14:29:17 [pdengler] TabAtkinsTPAC: In terms of CSS, gradients are going to change from the current draft 14:29:22 [pdengler] topic: Gradients 14:29:40 [pdengler] TabAtkinsTPAC: For linears, we will move to a scheme that are easier to interpolate 14:30:00 [pdengler] TabAtkinsTPAC: There are currently two different modes for interopolating that rely on two different sources 14:30:49 [pdengler] TabAtkinsTPAC: SVG Radial gradients are completely different 14:31:15 [pdengler] anthony: You cannot do conical graidents in SVG 14:31:23 [pdengler] TabAtkinsTPAC: You cannot do conical in CSS either 14:31:44 [pdengler] TabAtkinsTPAC: A proposal was made to do linears the same as SVG. It seems sort of confusing. 14:32:23 [pdengler] TabAtkinsTPAC: I have another proposal to solve the interopolation issues. I need to sit down with simon 14:32:34 [pdengler] anthony: You are not happy then with boundingBox proposal 14:32:57 [pdengler] TabAtkinsTPAC: I think that's wierd and unexpected 14:33:19 [pdengler] anthony: (drawing) 14:34:18 [pdengler] gradients in CSS are not skewed 14:34:26 [pdengler] shepazu: Adopting CSS gradients is fine with me 14:34:47 [pdengler] shepazu: I would like a way to specificy SVG Gradients...I would just like there to be more similarities 14:35:05 [pdengler] shepazu: Starting from different points seems wrong 14:35:42 [pdengler] TabAtkinsTPAC: Adopting the SVG model doesn't solve the interpolation; you cannot support intermediate forms. 14:35:57 [pdengler] ChrisL: Sounds like you have only looked at bbox and not userspaceonuse 14:36:42 [pdengler] TabAtkinsTPAC: The problem is transitioning from one to the other. I'm trying to find ways to do it. I might have to give up on radials. It may end up being that if we cannot find out how to solve it in radials, we might not solve it in linears. 14:36:55 [pdengler] anthony: Are you talking about transitions? 14:37:10 [pdengler] TabAtkinsTPAC : Yes, I should be able to transition from one to the other 14:37:46 [pdengler] dbaron: There is sitll mutiple possibilities. Its still not clear if you are transitioning the entire gradient line or stops 14:38:06 [pdengler] anthony: The stops need to be realigned according to the vector you are transforming 14:38:48 [pdengler] dbaron: It seems that is what most people want. The oringinal model for animate gradients is that they would only animate with the same number of stops 14:39:08 [pdengler] dbaron: One alternative is to animate the end points, and then the color irrespective of where the stops happen to be 14:39:26 [pdengler] dbaron: Or you could animate the color to the new color. They are different effects. 14:39:51 [pdengler] anthony: Would it make it sense then to only animate graidents with the same amount of stops 14:40:07 [pdengler] TabAtkinsTPAC: how does SVG animate gradients 14:40:31 [pdengler] chrisl: you animate at a more granular level. The developer puts together the transition themselves. 14:41:25 [pdengler] TabAtkinsTPAC: You want to avoid step transitions. It's not obvious that they bbox and userspace are different things 14:41:46 [pdengler] anthony: Is there any reason why CSS gradients are going down this path as opposed to the SVG model. 14:42:19 [pdengler] TabAtkinsTPAC : The most natural way to use it is like an image value, an URL. The SVG model is not natrual to the CSS model. 14:42:49 [pdengler] plinss_lyon: This seems to be a problem with borders 14:42:54 [pdengler] 2 minute break 14:44:30 [Zakim] Team_(svg)13:08Z has ended 14:44:30 [Zakim] Attendees were 15:00:44 [freedom] freedom has joined #svg 15:02:01 [freedom] freedom has left #svg 15:03:22 [parkjy] parkjy has joined #svg 15:04:37 [homata] homata has joined #svg 15:06:49 [hidetaka] hidetaka has joined #svg 15:10:06 [plinss_lyon] plinss_lyon has joined #svg 15:10:58 [ed] ACTION: ed to move to the main wikipage and break it into subpages 15:10:58 [trackbot] Created ACTION-2894 - Move to the main wikipage and break it into subpages [on Erik Dahlström - due 2010-11-11]. 15:11:36 [pdengler] shepazu: Is gradients a deliverable of FX or CSS? 15:11:47 [pdengler] TabAtkinsTPAC: It's CSS 15:12:03 [shepazu] Zakim, room for 3? 15:12:05 [Zakim] ok, shepazu; conference Team_(svg)15:12Z scheduled with code 26637 (CONF7) for 60 minutes until 1612Z; however, please note that capacity is now overbooked 15:12:40 [Zakim] Team_(svg)15:12Z has now started 15:12:43 [shepazu] Zakim, call Saint_Clair_3B 15:12:43 [Zakim] ok, shepazu; the call is being made 15:13:42 [pdengler] TabAtkinsTPAC: I'm afraid that gradients are complex enough that the language you express them in makes a difference 15:14:16 [shepazu] Zakim, call Saint_Clair_3B 15:14:16 [Zakim] ok, shepazu; the call is being made 15:15:06 [pdengler] pdengler: Does this mean that if they are fundamentally different the CSS should still apply to SVG 15:15:13 [pdengler] yes 15:16:11 [pdengler] tabAtkinsTPAC : Things that can be expressed in CSS cannot be expressed in SVG, because for example, applying a gradient to unknown dimension 15:16:23 [pdengler] ... CSS is a superset of SVG Gradients 15:16:36 [pdengler] ed: If we have CSS gradients, I would expect to be able to use them in SVG as well 15:16:57 [pdengler] chrisl: Then its the case of managing conflicts 15:18:33 [pdengler] tabAtkinsTPAC: A CSS Gradient should act like a paint server 15:18:36 [jfkthame] jfkthame has joined #svg 15:19:15 [pdengler] anthony: We've consider coons patches gradients, mesh gradients 15:19:46 [pdengler] chrisl: (describes these gradients) 15:20:20 [pdengler] chrisl: These create texture or 3d like effects 15:21:13 [pdengler] tabAtkinsTPAC: Property need only take an URL from SVG and apply as CSS gradient 15:21:22 [pdengler] fantasai: Can this be done today? 15:21:38 [pdengler] chrisl: There should be no reason why it shouldn't. Browsers just need to support it 15:23:18 [pdengler] maintin CSS gradients for simple cases, and then be able to refer to SVG model for more complex gradients 15:23:46 [pdengler] fantasai: Just have a separate file then for gradients. I don't see the reason for using @ rules on SVG gradients 15:24:07 [fantasai] s/on SVG/in CSS/ 15:24:24 [ChrisL] ChrisL has joined #svg 15:24:29 [fantasai] s/gradients/for complex SVG gradients/ 15:25:00 [pdengler] action: tAtkinsJ to write requirements document on gradients and how they work in HTML as related to SVG 15:25:00 [trackbot] Sorry, couldn't find user - tAtkinsJ 15:26:35 [pdengler] action: pdengler follow up on tabAtkins gradient requirement document 15:26:35 [trackbot] Created ACTION-2895 - Follow up on tabAtkins gradient requirement document [on Patrick Dengler - due 2010-11-11]. 15:26:41 [TabAtkinsTPAC] TabAtkinsTPAC has joined #svg 15:27:23 [pdengler] topic: embed SVG in an HTML with CSS 15:28:18 [pdengler] fantasai: Issue is with replace element. If I am writing a document on vertical text, and I want to put a diagram in this document. 15:29:42 [fantasai] 15:30:40 [pdengler] fantasai: The problem is SVG says height and width is 100%. 15:31:22 [pdengler] chrisl: The spec says, that SVG drawns 100% inside the container 15:31:36 [pdengler] dsinger: But the problem happened earlier when you follow the rules for replaced elements in CSS 15:31:52 [pdengler] fantasai: Which says look at the width and height of the element 15:32:21 [pdengler] fantasai: in CSS there are two widths/heights. One is the actualy width/height vs width/heigh attributes. 15:32:34 [pdengler] chrisl: SVG should give you back the viewbox 15:33:48 [pdengler] fantasai: When SVG is asked for its intrinisc size, if it is a fixed width it give you that back, if it does not, then it does not have an intrinsic width/height, but it has an intrinsic aspect ratio 15:34:52 [shepazu] q+ 15:35:21 [anthony] DB: If you say have a viewBox of 100 100 15:35:30 [anthony] ... and width = 4in 15:35:35 [anthony] ... and height = 100% 15:35:42 [anthony] ... so based on what you said earlier 15:35:53 [anthony] ... is a 4 inch by 8 inch box 15:36:10 [anthony] s/100%/50%/ 15:36:33 [anthony] CL: If you do put in a 50% it says 15:36:37 [anthony] ... give the size you want to draw in 15:36:41 [anthony] ... and I'll use half of that 15:37:05 [anthony] DB: I still think you should end up with 4 x 8 in that case 15:37:14 [anthony] CL: I guess it depends on which order you consider the arguments here 15:37:27 [anthony] ... with that you have an aspect ratio 15:37:34 [anthony] TA: That's what I've specified 15:37:53 [anthony] ... CSS asks do you have the definite width and height 15:38:13 [anthony] DS: I think there are some pros in the spec about intrinsic dimensions which should be taken out 15:38:18 [fantasai] 15:38:23 [anthony] EE: I think there is some stuff in SVG Tiny 1.2 15:38:27 [anthony] ... that is non normative 15:38:32 [anthony] .... about htis 15:38:38 [anthony] s/htis/this/ 15:38:55 [anthony] DS: What authoring tools do now, Illustrator and Inkscape 15:39:12 [anthony] ... they give an intrinsic size for the image 15:39:14 [ed] 15:39:35 [anthony] DS: You tell people to make a scalable image you put in a viewBox 15:39:41 [anthony] ... and make width and height 100% 15:39:51 [anthony] ... people I've talking to say this is conceptually difficult 15:40:05 [fantasai] "The intrinsic width and height of the viewport of SVG content must be determined from the 'width' and 'height' attributes. If either of these are not specified, the lacuna value of '100%' must be used. Note: the 'width' and 'height' attributes are not the same as the CSS width and height properties. Specifically, percentage values do not provide an intrinsic width or height, and do not indicate a percentage of the containing block." 15:40:11 [fantasai] Note the "Note:" 15:40:44 [anthony] DS: So I've talked to a lot of people about this and I can help them change the doc 15:40:55 [anthony] ... and you start talking about coordinate spaces and they don't understand 15:41:10 [anthony] CL: I've spoken to people who've come across this as well 15:41:55 [anthony] ... and explained this to them 15:42:22 [anthony] HL: Is there a document which has best practices for this? 15:42:36 [anthony] CL: I agree that this is a good thing to thing to have 15:42:40 [anthony] ... but we don't have one 15:43:26 [anthony] DS: I don't think there is any harm in providing short hand way 15:43:30 [anthony] ... to do something 15:43:40 [anthony] ... here is the particular short hand I think we should add 15:43:56 [anthony] ... we add an attribute that says you can have width and height, scaling 15:44:16 [anthony] s/scaling/and you have a property scaling/ 15:44:44 [anthony] ... that why they don't have to worry about what they've specifiefd 15:44:49 [anthony] PD: Would that override? 15:44:51 [anthony] DS: Yes 15:45:12 [anthony] ... I think people have a really hard time understanding the width and height issue 15:46:05 [anthony] s/width and height issue/difference between ratio and width and height/ 15:46:12 [anthony] ... but the default would be take into account the width and height 15:46:32 [anthony] ... and the viewBox 15:49:22 [anthony];%20charset=iso-8859-1 15:49:36 [anthony] or 15:49:36 [anthony] 15:50:01 [anthony] ACTION: Chris to Copy the Intrinsic sizing wording in Tiny 1.2 to Full 1.1 2nd Edition 15:50:01 [trackbot] Created ACTION-2896 - Copy the Intrinsic sizing wording in Tiny 1.2 to Full 1.1 2nd Edition [on Chris Lilley - due 2010-11-11]. 15:51:12 [fantasai] 15:58:14 [dbaron] dbaron has joined #svg 16:00:48 [mmielke] mmielke has joined #svg 16:04:59 [anthony] trackbot end telcon 16:05:09 [anthony] trackbot, end telcon 16:05:09 [trackbot] Zakim, list attendees 16:05:09 [Zakim] As of this point the attendees have been (none) 16:05:10 [trackbot] RRSAgent, please draft minutes 16:05:10 [RRSAgent] I have made the request to generate trackbot 16:05:11 [trackbot] RRSAgent, bye 16:05:11 [RRSAgent] I see 10 open action items saved in : 16:05:11 [RRSAgent] ACTION: pdengler to Communicate base value issue between SMIL and Transitions with CSS Working Group [1] 16:05:11 [RRSAgent] recorded in 16:05:11 [RRSAgent] ACTION: Dino to Work with PatrickD on drafting up a proposal for the same shared data model and functionality across SVGA and CSSA [2] 16:05:11 [RRSAgent] recorded in 16:05:11 [RRSAgent] ACTION: Dean to Work with PatrickD on drafting up a proposal for the same shared data model and functionality across SVGA and CSSA [3] 16:05:11 [RRSAgent] recorded in 16:05:11 [RRSAgent] ACTION: anthony to spec the SVG Attribute as a presentation property removing the need to keep same behavior as in other presentation properties in SVG [4] 16:05:11 [RRSAgent] recorded in 16:05:11 [RRSAgent] ACTION: ed to add informative note about how to handle MS <filter> from before [5] 16:05:11 [RRSAgent] recorded in 16:05:11 [RRSAgent] ACTION: pdengler to submit new filter effects proposals [6] 16:05:11 [RRSAgent] recorded in 16:05:11 [RRSAgent] ACTION: ed to move to the main wikipage and break it into subpages [7] 16:05:11 [RRSAgent] recorded in 16:05:11 [RRSAgent] ACTION: tAtkinsJ to write requirements document on gradients and how they work in HTML as related to SVG [8] 16:05:11 [RRSAgent] recorded in 16:05:11 [RRSAgent] ACTION: pdengler follow up on tabAtkins gradient requirement document [9] 16:05:11 [RRSAgent] recorded in 16:05:11 [RRSAgent] ACTION: Chris to Copy the Intrinsic sizing wording in Tiny 1.2 to Full 1.1 2nd Edition [10] 16:05:11 [RRSAgent] recorded in
http://www.w3.org/2010/11/04-svg-irc
CC-MAIN-2014-41
refinedweb
13,033
57.1
FieldInfo.GetValue Method When overridden in a derived class, returns the value of a field supported by a given object. Namespace: System.ReflectionNamespace: System.Reflection Assembly: mscorlib (in mscorlib.dll) Parameters - obj - Type: System.Object The object whose field value will be returned. Return ValueType: System.Object An object that contains the value of the field reflected by this instance. In Silverlight, only accessible fields can be retrieved using reflection. If the field is static, obj is ignored. For nonstatic fields, obj should be an instance of a class that inherits or declares the field. Note that the return type of GetValue is Object. For example, if the field is of type Boolean, its value is boxed and returned as an instance of Object. Platform Notes Silverlight for Windows Phone The following example retrieves all the fields of the Test class and displays the field values. If a field value cannot be retrieved because of the field's access level, the exception is caught and a message is displayed. The internal fields (Friend fields in Visual Basic) are accessible in this example because the Example and Test classes are in the same assembly. using System; using System.Reflection; public class Test { public static string SA = "A public shared field."; internal static string SB = "A friend shared field."; protected static string SC = "A protected shared field."; private static string SD = "A private shared field."; public string A = "A public instance field."; internal string B = "A friend instance field."; protected string C = "A protected instance field."; private string D = "A private instance field."; } public class Example { public static void Demo(System.Windows.Controls.TextBlock outputBlock) { // Create an instance of Test, and get a Type object. Test myInstance = new Test(); Type t = typeof(Test); // Get the shared fields of Test, and display their values. This does not // require an instance of Test, so null is passed to GetValue. FieldInfo[] sharedFields = t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); foreach( FieldInfo f in sharedFields ) { try { outputBlock.Text += String.Format("The value of Shared field {0} is: {1}\n", f.Name, f.GetValue(null)); } catch { outputBlock.Text += String.Format("The value of Shared field {0} is not accessible.\n", f.Name); } } // Get the instance fields of Test, and display their values for the instance // created earlier. FieldInfo[] instanceFields = t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); foreach( FieldInfo f in instanceFields ) { try { outputBlock.Text += String.Format("The value of instance field {0} is: {1}\n", f.Name, f.GetValue(myInstance)); } catch { outputBlock.Text += String.Format("The value of instance field {0} is not accessible.\n", f.Name); } } } } /* This example produces the following output: The value of Shared field SA is: A public shared field. The value of Shared field SB is: A friend shared field. The value of Shared field SC is not accessible. The value of Shared field SD is not accessible. The value of instance field A is: A public instance field. The value of instance field B is: A friend instance field. The value of instance field C is not accessible. The value of instance field D is not accessible. */ For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.
http://msdn.microsoft.com/en-us/library/vstudio/system.reflection.fieldinfo.getvalue(v=vs.95).aspx
CC-MAIN-2014-15
refinedweb
538
60.92
Program to print X characters up to X in C++ In this tutorial we will learn how to print X characters up to X in a word. The program accepts a word and an integer X. The program finds the length of the word and checks it’s divisibility with X . If the divisibility is satisfied the program splits the X characters up to X. How to find the length of the string? The length of the string can be found using the function strlen(). The strlen() function can be used only when the header file #include<string.h> is included. How to get the input values? char str[1000]; cin>>str; int X; cin>>X; In the above code, The word and the integer X are obtained. The length of the string is calculated and if it is divisible by X , it starts spliting the word into X characters INPUT 1: Enter the Word to be split: codespeedy Enter the value of X: 2 C++ code to print X characters up to X : #include<iostream.h> #include<string.h> using namespace std; int main(){ char str[1000]; int X,count=0; cout<<"Enter the Word to be split:"<<"\t"; cin>>str; cout<<"\nEnter the value of X :"<<"\t"; cin>>X; int len=strlen(str); if(len%X==0){ cout<<"X characters up to X:"<<"\n"; for(int i=0;i<len;i++){ if(count<X){ cout<<str[i]; count++; } else if(count==X){ cout<<"\n"; cout<<str[i]; count++; count=1; } } } else{ cout<<"The word cannot be split into "<<X<<" equal parts."; } } In the above code, The variable str[1000] and X are obtained. strlen() function calculates the length of the string and stores it in the variable len. The count variable is initialized with 0 and incremented on each character. If the count value is less than X the characters are printed. The count if reaches the value X, it is reset to 1 and therefore it reaches the next line. If the length of the string is not divisible by X then the program prints that the word cannot be split into X equal parts. OUTPUT 1: X characters up to X: co de sp ee dy INPUT 2: Enter the Word to be split: program Enter the value of X: 4 OUTPUT 2: The word cannot be split into 4 equal parts. The program prints X characters up to X. We hope this tutorial helped you to understand how to print X characters up to X using C++. You may also read:
https://www.codespeedy.com/cpp-program-to-print-x-characters-up-to-x/
CC-MAIN-2020-24
refinedweb
426
70.63
Angular v4 has been released. Read the major takeaways from ng-conf 2017 (April 5) Day 1. TL;DR: Learn about the topics covered by speakers at ng-conf 2017 on April 5, 2017 (Day 1 of 3). ng-conf 2017 ng-conf is the flagship Angular / AngularJS conference in Salt Lake City, Utah. The conference typically features talks from Angular core team members as well as ancillary Angular projects (such as Material and Protractor) and members of the community. The conference is primarily single track but does have a Fair Day of workshops and fun events in between the two main talk days. This year's ng-conf runs from April 5-7, 2017. I am attending ng-conf 2017 in Salt Lake City and bringing you summaries of the sessions and activities each day of the conference. This year's ng-conf opened with a theme of empathy and inclusivity. The code of conduct was reviewed and emphasized, as community is extremely important to Angular, its creators, and the developers who support and use it. Keynote Speakers: Igor Minar, Stephen Fluin, Brian Martin Major Takeaways (TL;DR) - Angular fosters a community of inclusivity and wants to enable creation of apps that people love to use and developers love to build. - The Angular ecosystem is thriving and growing, with intentions to extend in several directions. - Language Services intelligence for IDEs was announced. - Ionic version 3 was announced. - Angular v4 is better for users and developers and is state of the art. - Semantic version and time-based releases were covered with major releases every 6 months. - Major releases will be simple upgrades, aiming to mitigate upgrade obstacles. - Angular LTS (Long Term Support) was announced for Angular v4 through October, 2018. - Angular version 5 will use AOT by default in both dev and production. - "You can build with us!" is the Angular team's overall message to the developer community this year. Full Summary Igor Minar kicked off the keynote speaking about why the Angular team builds Angular: to enable creation of applications that people love to use and that developers love to build. He spoke about the desire for the community to be welcoming and inclusive, upholding and protecting values of mutual respect. Angular has a code of conduct as well as an email where people can reach out regarding conduct concerns (conduct@angular.io). Stephen Fluin then went on to speak about the Angular ecosystem. For consistency, AngularJS should be used to refer to the framework version 1.x and Angular should refer to version 2 and above. This helps peole entering the community to understand the famework version and branding, and will also improve and clarify SEO. Next, some community metrics were presented. There are currently 727 Angular Meetup groups worldwide in over 100 countries. Stack Overflow developer survey results for 2017 reported that 44% of JavaScript framework/library users use AngularJS or Angular. The Angular team wants to continue to support companies that provide support or training for developers getting started or needing help with AngularJS or Angular. Community projects are also an important part of the Angular ecosystem, including integrated dev environments, scaffolding education, seed apps, tools for linting, and more. The concept of "Build on Us" was introduced next. This is the premise that frameworks can be built on top of Angular. Guidelines called the Library Spec were announced for how to build and ship libraries with Angular. These guidelines will describe how to build and distribute extension projects in a way that is easy for devlelopers to use and consume. Angular Material is an example of a component library built on Angular; its purpose is to build tools that make component authoring easier. Angular Material's component dev kit demonstrates best practices for a variety of features, such overlays, gestures, and accessibility. The Angular CLI reached version 1.0 a few weeks ago and is one of the best ways to build Angular applications today. Best practices and wisdom is built into the CLI, and the Angular team is exploring ways to extract those best practices into SDKs. For example, Angular IDE by Webclipse builds on the CLI. Language Services was also announced. This is a set of intelligence building on top of Angular that is now available in VS Code, WebStorm, and Angular IDE. Ionic version 3 was announced today, built on Angular v4. The Ionic team maintained open communication and collaboration with the Angular team while building the latest version. Version 2 has over one million installs. The state of Angular today covered some additional metrics. There are 100 applications launching in Angular per day. Although a vast majority (90%) of Angular applications are behind a firewall, 17% of public domain Angular apps are already using Angular v4. Angular's use within Google is also extremely significant. Over 200 Google apps are built with Angular. Brian Martin then spoke about using Angular on NBA.com. His development team likes Angular because of TypeScript, its standards-first approach, and that Drupal and Angular share programming principles, allowing developers to switch between the two easily while integrating. He also cited the great Angular ecosystem (integration with Dragula, Redux, and D3), performance, and data integration that meets all NBA.com's use cases. Igor and Stephen went on to speak about Angular v4, covering the following: v4 is Better for Users: - There was a need for Angular to evolve, and v4 is the first step in that direction. - Ease of use was enhanced. - Migration from v2 to v4 is easy. - Apps are smaller with faster bootstrap (build size of apps was reudced by approximately 60%). v4 is Better for Developers: - New APIs (ngIf, ngFor) with an improved reactive paradigm. - The way Angular is packaged has been changed to achieve a smaller build size and reduce latency for a faster build. - Version 4 is the first Angular release with a stable release of Angular CLI. - No breaking changes to stable APIs or common usage patterns. v4 is State of the Art: - The Angular Universal community project was brought into the core repository. - Angular Universal allows the entire Angular app to run and load on the server, and bootstrap Angular on top of that. - Applications are then a little bit faster; the time the user has to wait to see a fully rendered application is reduced. - Service workers are shipped as a flag in the CLI that can be turned on. - The team is excited to continue to invest in this. Finally, Igor spoke about what's next for Angular. Angular will continue to evolve incrementally and predictably to keep pace with the continually evolving ecosystem outside of Angular itself. Semantic versioning was specified with time-based releases: - Patch releases: 4.0.x(every week) - Minor releases: 4.x.0(every month during the first three periods of the release cycle), contain new features and/or automated updates - Major releases: x.0.0(every 6 months), will have new features but still support simple upgrades so a major version update doesn't result in an obstacle Igor also talked about how Angular is used at Google. All Google apps use the latest pre-release version of Angular with a large test suite, upgraded pull request by pull request. The version of Angular used at Google is latest in the master branch. The Angular team encourages users to stay as close to head as they're comfortable with. This way, they will receive the latest features and fixes and these are the versions that will afford compatibility with the latest tools. The Angular team also understands that some people can't always upgrade, so LTS (Long Term Support) was announced. Version 4 LTS will provide critical bugfixes and security patches until October, 2018. Finally, version 5 themes were presented. Angular version 5 aims to simplify the way new applications are compiled. Currently, JIT (Just In Time) compilation is used in development mode, then AOT (Ahead of Time) compilation is used when going to production. Version 5 aims to make AOT the default to reduce friction when moving an app to production. Speed and size are also a focus, particularly when using component libraries like Material or Ionic, with better tree-shaking for components. The keynote concluded by revisiting last year's final keynote takeaway. In 2016, the core Angular team established "come sit with us" as their invitation to the community to establish a rapport, to contribute, share, and ask questions. This year, the mantra was "You can build with us!" Angular CLI Tips The Angular CLI can easily generate components, services, models, and more with minimal effort and very few keystrokes. The --dry-run flag can report what will be outputted so you can check your work with the CLI before generating anything. The CLI also makes lazy loading much easier in Angular than AngularJS. Wwith the ability to eject Webpack, Angular CLI supports full customization and extension for any desired build configuration. Tools like the Angular CLI help reduce cognitive burden when developing while ensuring standards and best practices are followed at the same time. John Papa demonstrated several CLI commands using a sample application, including the following: ng serve -olaunches the app in the browser ng g c navshortcuts ng generate component nav; the CLI now adds generated components to the app.module.tsfor you ng g cl rebelscreates a class with the specified name (useful for models) ng g s data -m app.modulecreates a service and provides it in the app.module.tsfile Tip: ng new [your-app-name] --routing --prefix [your-prefix] --style scss --dry-run, removing --dry-runwhen happy with the results to generate files. John Papa's Pluralsight course on the Angular CLI is available here. Angular Compiler A front-end compiler accepts input and performs lexical and static program analysis before producing output. The Angular compiler can be leveraged to determine if a program is compatible with the styleguide. The compiler can also be used to detect deprecations and remove them. In addition, it is capable of producing Abstract Syntax Trees (AST) of Angular applications in highly visual ways. Minko Gechev's impressive ngworld 3-D AST visualizer is available here. Aside: Unofficial Angular Docs Joe Eames announced the Unofficial Angular Docs as a community collection of articles, tutorials, and resources for learning Angular. WebVR with Angular WebVR is an open standard and requires WebGL to create rich and immersive environments. A-frame framework for building VR web experiences is similar to Angular. Therefore, can we implement WebVR with Angular? In order to implement WebVR in Angular, several things are needed. Custom renderers need to abstract away the creation of DOM elements and addition of styles and components to a scene. Third party libraries and polyfills are also currently necessary to produce stereoscopy and duplicate camera. Finally, WebVR in Angular needs to run outside of zones to be removed from change detection. Currently, performance starts to bottleneck. However, in the future, compilers could potentially take Angular components and compile to native VR headset applications. Modules An ES2015 module is simply a code file with export / import. ES2015 modules are "micro" in nature, whereas Angular modules ( @NgModule) are "macro" in nature and define a set of components, related files, and dependencies. Angular apps can have an app module, feature modules, and shared modules for better organization. Modules also enable lazy loading. 3 things are needed for lazy loading: - The app needs feature modules: otherwise there's nothing to load, because lazy loading only loads modules. - Routes need to be grouped under a single component-less parent route. This is a path with children of a single route and components are associated with the children, not the parent. - Feature modules should not be imported in the appmodule; this defeats the purpose of lazy loading. Using Components with Intent Initially, Angular's ability to componetize can lead to developers wanting to "componetize all the things"! However, there are costs to doing this: - Component tax: every component costs resources to render, execute, and compile. - Payload tax: creating lots of components increases the overall JavaScript payload. - Execution tax: bootstrapping, lazy loading, and compilation cost resources. - Container element tax: we usually default to custom elements, but we can cut down on extra containers by using attributes instead. - Tree coupling tax: the Decision and Presentation pattern utilizes smart parent components with dumb child components, but this can result in deep nesting for no good purpose other than chaining and passthrough. Ultimately, everything has a tax and the trick is to take a balanced approach so that decisions are made with intent. We can combine Decision/Presentation with services, observables, or Redux to solve problems and decouple when necessary. "As developers, we're always battling to put queen size sheets on a king size bed." —Justin Schwartzenberger Animations in Angular v4 As of Angular v4.0, the @angular/animations module is now separate from the Angular core. Lots of changes have been implemented in the internal API, as follows: BrowserAnimationsModuleis for users. NoopAnimationsModuleis for testing. - The new animation()function defines a reusable animation. - The animateChild()function can accept input variables for duration, start, and end, with defaults. Programmatic animations can be implemented by injecting AnimationBuilder into a component. This allows for building animations on the fly with scrubbing, playback controls, etc. For route animations, data is passed to the transitions and the developer can determine what kind of transition is desired for the route change. An animations demo is available from Matias Niemela here. The Sandbox Injection attacks take place when you let your users inadvertantly run code on your system. The potential of executing user content is bad. Escaping ensures that user code is not executed, it's just ugly text on the screen. The expression sandbox prevented developers from being able to reference the prototype of an object or items on the global scope. The sandbox has been removed as of AngularJS 1.6. The sandbox wasn't meant for security, it was to help developers. However, the real problem is that it allowed users to define things in your template: passing user content to $compile allowed expressions to flow through escape logic. This can be demonstrated by Ryan Hanson's article on How I Stole Plunker Session Tokens with an Angular Expression. If users can set their information to an exploit string which will be parsed as an expression by Angular, malicious code will render. Important guidelines: - Don't mix server templates with client templates. - Don't generate template source code by concatenating user input and templates. - Be suspicious. User content might show up in unexpected places. - Hack your app. It's fun. (Don't do it in production.) What do I have to do? - Stop mixing server and client-side templates. - Use ng-non-bindable/ ngNonBindable - Don't pass user content to $watch, $watchGroup, $watchCollection, $apply, $compile, etc. - Your templates might do more than you think. Ie., if ng-appis on the HTML or body tag, everything within that is Angular, so bootstrap Angular where you need it and make sure that everything within is fully under your control. Thoughtful Component Design This talk went more in-depth into some principles of better components. For some components, augmenting the native element is preferable over hiding the element inside some custom element, ie.: <button md-button>, <nav md-tab-nav-bar ...>, etc. What are the benefits of augmenting native elements? Firstly, familiar API: developers know how to use HTML. In addition, if we're concealing component internals within custom elements, it's hard to know if the right thing is being done for accessibility underneath. At a glance, how will we see how an input inside a custom component interact with a screen reader with roles or ARIA? We can make components simpler and can avoid a huge mess of code and binding so that the user can interact directly with the native element. If there is no native element (such as a datepicker), we need thoughtful component composition. It can be helpful to have separate elements that are connected to each other. This provides benefits such as single responsibility, flexibility, and friendliness to native elements. Manipulating the DOM Care should be taken when it's necessary to directly manipulate the DOM; this should only be done if there is no Angular alternative, such as for measuring, sizing, or positioning of elements after CSS styles have been applied. Reaching outside the Angular app to find information can require this as well (ie., needing to find out if the layout is right to left or left to right, <html dir="rtl">. Make sure that you are thoughtful about interactions with zone, Angular's change detection mechanism. Zones provide an asynchronous execution context for Angular and are Angular's way of knowing about everything that happens in the app, including asynchronous activity like setTimeout or HTTP requests. With zones, we have more control over when change detection runs. For example, we can implement ngZone.runOutsideAngular(() => { ... }); to execute something outside the Angular context. This won't trigger Angular change detection. Running custom animation (as mentioned above with regard to WebVR) is a good example for needing this to avoid unintended slowdown in your application. Upgrading From Angular 1.x For most developers, the primary upgrade pain points are time and priority. These are influenced by: - Business incentive: companies don't necessarily make more money by using the latest and greatest technologies, so upgrading can be a hard sell. - Team proficiency: engineering teams can experience hesitation or fear of the prospect of needing to learn a new framework from scratch. - Upgrading from AngularJS to Angular often means a full rewrite. - All the additional new tooling can be daunting. Note: Research showed that syntax is not a factor. The primary concerns with upgrading are time to learn and fear of change. Tips for making upgrading easier - Start with a component-based architecture (AnglarJS v1.5+). - Write full SPAs: don't use an AngularJS container within a website. - Install dependencies with NPM (or Yarn) instead of downloading code from a website and inserting script tags. - Bring in Webpack. - Use TypeScript. Finally, it was emphasized that if there is a legitimate reason why you cannot upgrade, know that the Angular team and community feels your pain and will do their best to help you move forward. The "You can sit with us" mantra from ng-conf 2016 was repeated: empathy is important. "If you're experienced, take the time to help somebody out." —Sergio Cruze Memory Leaks A memory leak refers to memory that should be released back to the system because it's no longer needed and it's not correctly released back to the operating system. Memory leaks cause significant performance issues over time. There are two types of memory leaks: - Contrived examples - The real ones you find in your giant application that the contrived example didn't show you at all Some memory leaks in Angular are easy to solve, such as console.log removal and long-lived observables. Chrome devtools provides a timeline view that gives great insights into overall performance. This can show when the leak happening, allowing the devleper to determine if it be isolated to some certain event and how big it is. Final takeaways were: - What actions cause the leak? - Test like a real user. - Remove code. Angular CLI in Detail Hans Larsen, the Angular team lead for Angular CLI, spoke indepth about the history and future of the CLI. He understood that when you start up a new project, it's very difficult to keep track of all the configurations and boilerplate. The concern was that it should be simple, not complex. Angular CLI was built so that "it just works" without requiring too much thought or cognitive burden. The CLI saves hours and hours of working on Webpack configurations. The Angular CLI is a small tool with a lot of big ambitions: it wants to fit your needs for large or small projects. Hans spoke about what's going on under the hood of the CLI in dev and prod modes and how the CLI detects lazy routes, creating multiple bundles to potentially be loaded later. He then touched on ng eject (ejection of the webpack.config.js and Webpack dependencies for customization), concluding that segment with: "Please eject responsibly." —Hans Larsen What's coming for CLI v1.x? Future 1.x releases aim to reduce the size of bundles with more aggressive tree-shaking. There are also plans to increase performance of AOT compiling so that you can develop in AOT instead of JIT and reduce production bugs. Error messaging will also be improved with actionable items detailing how to fix errors. Angular CLI v2 Version 2.0 of the Angular CLI may possibly look more like an SDK, with plugin support and a set of libraries that can be used by other tools like IDEs and other CLIs. The CLI may also support more customizable templates, test frameworks, and build systems, allowing developers to mix and match. However, the CLI will maintain the same small interface and feel familiar if you keep using the CLI. It will integrate with more and continue to dream bigger while remaining simple to use. Reactive Programming with RxJS Ben Lesh and Tracy Lee talked about how learning RxJS is difficult, but once mastered, it's extremely powerful and useful. Ben talked about creating new observables using the new Observable constructor, which has methods for error, and complete. There are other observable creation options, but they all use new Observable under the hood. They then demonstrated an RxJS Pun App with lookahead search, API, and speech recognition. Tips - Subjects are observables and observers which allow us to push values through by using the nextmethod. - When importing from RxJS, only include what you need by importing from the module path directly. For example: import {Subject} from 'rxjs/Subject'; - Remember to catch errors and return an empty observable: .catch(err => { return Observable.empty(); } - The switchMapoperator converts the value to a new observable, switches to that observable, and unsubscribes from the previous observable. - The async pipe ( | async) subscribes to the observable immediately when Angular initializes and unsubscribes when removed from the view. - The share()operator makes your observables multicast, allowing one subscription and multiple subscribers. Same Shaped-ness Same Shaped-ness refers to streams that share the same shape. For example, in the demo app, spoken keywords and typed keywords are both observables of arrays of strings. They are same shaped and can therefore be merged and shared. Slides for this talk are available here. Creativity Justin Searls, the co-founder of Test Double, concluded Day 1 of ng-conf 2017 with an excellent talk on turning negative and toxic emotion and converting it to creativity. What is creativity? - Passion? Passion fizzles out. - Art? Coding is creative, but not all code is artistic on its merits. - Vision? Vision doesn't create anything. Programming is one of the most creative endeavors humankind has undertaken, but many programmers don't consider themselves creative. Justin's creativity flows from getting riled up by something, and creating a new library as a result. "I pass npm modules like kidney stones." —Justin Searls Taking negative and toxic emotion and turning it into creativity Justin's fuel for creativity reads like a mad lib: "I feel (express indignation), but I (admit incompetence). Maybe if I build it, I'll (feel less incompetent)." —Justin Searls Fear of bad code can be paralyzing, so it's important to find a safe space where working is more important than perfect. Getting out of the line of fire lowers pressure and enables us to build something to impress. Working code can sell ideas, so it's always helpful to bring a demo to the table. Justin spoke about creating Must Stache, a serverless Chrome browser extension that used face.com facial recognition to overlay mustaches on photos of people. However, when face.com was shut down, former users were angry that the extension no longer worked, cultivating a toxic atmosphere as a result of popularity. The Thoughtleader's Dilemma The thoughtleader's dilemma occurs when you: - Do interesting work. - Stop doing work. - Are now in danger of thoughtleading people off a cliff because you're not doing the work anymore. Justin spoke about how he went too long without validating his ideas, resulting in an approach that was too hand-wavey. Everything seems simple at a distance as you get detached from the work. Many managers have this problem. Pattern recognition yields generic advice. The solution is to trust the people who are closest to the work to make decisions regarding the work. To maintain creativity and avoid this dilemma, learn about something, build a tool, share it with others, then go back to learning. If you're not getting through, tweak your message. Not winning != not worthwhile In the open source community, we often create something and then businesses come to depend on it. This results in entitled developers, which in turn leads to sadness at entitlement. Justin notes that the happiness experienced by open source developers is often inversely proportional to the popularity of their libraries. The solution? Build something no business could ever want. Justin designed own programming language called emoruby to compile emojis to Ruby. The repo has 0 GitHub issues. In conclusion: it's okay to build stuff for fun! Negative feelings are a symptom, not the problem. When performing root cause analysis, reflect on your feels and accept those emotions as being valid. Then ideas will just come down, so find a creative outlet for those ideas. Aside: Auth0 for Angular Angular v4 was just released, the Angular CLI has a stable release, and Angular LTS was also announced. 1 of ng-conf 2017 was packed with information and great sessions. Day 2 is a Fair Day, comprised of activities for entertainment and networking as well as dozens of workshops running simultaneously. Day 3 returns to single track sessions. You can tune into the ng-conf 2017 livestream here as well as watch recorded streams from previous days.
https://auth0.com/blog/amp/ngconf2017-summary-day1/
CC-MAIN-2019-18
refinedweb
4,367
56.15
read the columns of worksheet and set any data in the colums named with "Date" in the title to format "dd/mm/yyyy" By joeloyzaga, in AutoIt General Help and Support Recommended Posts Similar Content - By ahha I AnonymousX Hello, I'm trying to be able to switch back and forth between multiple excel spreadsheets and I can't seem to get the WinActivate function to work, and bring the desired window the be the active window. Could I please get some assistance, I've tried a few things and nothing seems to work quite right. Below is a test case where I'm just trying to make the first excel sheet that was opened become the active window, and testing it by grabbing a cell value off that workbook. The message box produces the correct answer if both files are closed before running but the 2nd test file will appear to be the active window. If the code is run again without closing the excel files, nothing works (file does not appear to be active and message box will not give an answer). #include <Excel.au3> Opt("WinTitleMatchMode", 2) ;1=start, 2=subStr, 3=exact, 4=advanced, -1 to -4=Nocase ;Open Test1 Excel Workbook local $oExcel = _Excel_open() Local $ofile = @ScriptDir & "\test1.xlsx" Local $oWorkbook = _Excel_BookOpen($oExcel,$ofile) ;Open Test2 Excel Workbook local $mExcel = _Excel_open() Local $mfile = @ScriptDir & "\test2.xlsx" Local $mWorkbook = _Excel_BookOpen($mExcel,$mfile) ; This workbook is completely blank WinActivate($oWorkbook); should make Test1 the active window local $read1 = _Excel_RangeRead($oWorkbook,Default,"B2"); Cell B1 in Test1 workbook contains the word Test MsgBox(0,0,$read1);Should returns the word test - By meral40 #include <Excel.au3> #include <MsgBoxConstants.au3> #include <Array.au3> ; Create application object and open an example workbook Local $var1= "D:\Documents\testbook.xls" Local $oExcel = _Excel_Open() Local $oWorkbook = _Excel_BookOpen($oExcel, $var1) Local $sRead = _Excel_RangeRead($oWorkbook, Default, "Q2") Local $sRead2 = _Excel_RangeRead($oWorkbook, Default, "Q2") $text1= "hello there" $text2= "read me" While 1=1 If $sRead = $text1 Then ;MouseClick Consolewrite($sRead) Elseif $sRead2 = $text2 Then ;MouseClick Consolewrite($sRead2) EndIf sleep(30000);reads field every 30s WEnd Ok I am writing a script in excel that monitors a field that changes every so often then creates an action based on whether it is text1 or text2 I have problem here if I run script it will read the right text but if I go edit the text in excel it still displays the text before the change. Thanks for your help.
https://www.autoitscript.com/forum/topic/166167-read-the-columns-of-worksheet-and-set-any-data-in-the-colums-named-with-date-in-the-title-to-format-ddmmyyyy/
CC-MAIN-2019-04
refinedweb
413
50.91
I installed the Intel Parallel Studio XE 2020 Update 1 on my macOS (Catalina/10.15.5) and chose only the command line option and not the Xcode integration. I hoped that I can manually use intel compilers when I need them and from a terminal session, by running `source <install_dir>/bin/compilervars.sh intel64`. But, after installation, it automatically creates symlinks to /usr/local/bin, where all the compilers are on my PATH. Is there a way to prevent this behavior except manually removing all the created symlinks? Hi, Ideally, sourcing the compilers with script file (like you mentioned) should place the compilers in path and the global behavior is not expected. I shall escalate this case to the concerned team. Thanks for reporting the issue. --Rahul Do you have another system with older macOS (e.g. Catalina/10.15.1) to try and see if the problem still persists? | Do you have another system with older macOS (e.g. Catalina/10.15.1) to try and see if the problem still persists? No, I do not. Currently, I resolved the issue by modifying the intel linking script compilers_and_libraries_2020.1.216/mac/link_install.sh and removing all the created links in /usr/local/bin by # remove all links COMPXE_RMLINKS() { PRINT "COMPXE_RMLINKS()" if [ ${TARGET} == "mac" ]; then # remove links for binary and non-env script program files for THIS_FILE in $INTEL_PROGRAM_FILES_LIST; do if [ -e "$ROOT_DIR"/usr/local/bin/$THIS_FILE ]; then rm $RM_OPTIONS "$ROOT_DIR"/usr/local/bin/$THIS_FILE 2>/dev/null fi if [ -e "$ROOT_DIR"/usr/local/bin/$THIS_FILE-$VERSION ]; then rm $RM_OPTIONS "$ROOT_DIR"/usr/local/bin/$THIS_FILE-$VERSION 2>/dev/null fi if [ -e "$ROOT_DIR"/usr/local/bin/$THIS_FILE-$VERSION.$VERSION_UPDATE.$PACKAGE_NUM ]; then rm $RM_OPTIONS "$ROOT_DIR"/usr/local/bin/$THIS_FILE-$VERSION.$VERSION_UPDATE.$PACKAGE_NUM 2>/dev/null fi done fi } The other major problem/issue is reported before:... The same thing is happening here. It is simply failing on `hello.c` test case. #include <stdio.h> int main() { // printf() displays the string inside quotation printf("Hello, World!"); return 0; } >> icc hello.c hello.c(1): catastrophic error: cannot open source file "stdio.h" #include <stdio.h> ^ compilation aborted for hello.c (code 4)
https://community.intel.com/t5/Intel-C-Compiler/Intel-Parallel-Studio-XE-2020-update-1-macOS-command-line-option/td-p/1187290
CC-MAIN-2020-34
refinedweb
361
51.75
08 June 2011 23:40 [Source: ICIS news] HOUSTON (ICIS)--?xml:namespace> IPA pricing was confirmed down 4 cents/lb ($88/tonne, €60/tonne) from one producer and down 5 cents/lb from another, largely because feedstock chemical-grade propylene (CGP) prices fell by 15 cents/lb for June, sources said. In contrast, CGP prices rose sharply in April and May. It was not yet certain whether a third major IPA producer had lowered its current contract prices. “We have seen numbers come off 3-4 cents/lb this week,” a fourth producer said. “Everyone has different competitive situations. Buyers are trying to drive prices down with the news of June propylene,” the seller said. The status of a 6 cent/lb IPA June price-hike initiative from one seller was not yet known. IPA prices were not yet assessed lower by ICIS, pending market confirmation of broad reductions, but current prices were $1.12-1.15/lb. If reductions are broadly implemented, most would occur at the low end of the current range, sources said. Domestic IPA remained snug, buyers said, but some limited spot volumes were said to be available this week. ($1 = €0.68) For more on isoprop
http://www.icis.com/Articles/2011/06/08/9467689/us-ipa-contracts-begin-to-drop-on-lower-propylene-prices.html
CC-MAIN-2014-52
refinedweb
201
72.87
On Thu, Oct 14, 2010 at 3:02 PM, David Daney <ddaney@caviumnetworks.com> wrote: > Using the forthcoming open firmware (OF) on mips patches, requires > that several interrupt related definitions be added. > > In the future we may want to allow some sort of override for > irq_create_mapping, but for now it is just supplies an identity > mapping. > > Signed-off-by: David Daney <ddaney@caviumnetworks.com> > Cc: Grant Likely <grant.likely@secretlab.ca> Hi David, If you try my current next-devicetree branch then this patch should not be necessary. I was able to build the mips patch before I posted it. > --- > arch/mips/include/asm/irq.h | 33 +++++++++++++++++++++++++++++++++ > 1 files changed, 33 insertions(+), 0 deletions(-) > > diff --git a/arch/mips/include/asm/irq.h b/arch/mips/include/asm/irq.h > index dea4aed..f109e67 100644 > --- a/arch/mips/include/asm/irq.h > +++ b/arch/mips/include/asm/irq.h > @@ -16,6 +16,39 @@ > > #include <irq.h> > > +. linux-2.6$ git grep '#define[ \t]*NO_IRQ[^_]' arch/arm/include/asm/irq.h:#define NO_IRQ ((unsigned int)(-1)) arch/microblaze/include/asm/irq.h:#define NO_IRQ (-1) arch/mn10300/include/asm/irq.h:#define NO_IRQ INT_MAX arch/parisc/include/asm/irq.h:#define NO_IRQ (-1) arch/powerpc/include/asm/irq.h:#define NO_IRQ (0) arch/xtensa/variants/s6000/include/variant/irq.h:#define NO_IRQ (-1) drivers/input/touchscreen/ucb1400_ts.c:#define NO_IRQ 0 drivers/of/irq.c:#define NO_IRQ 0 drivers/pcmcia/pd6729.c:#define NO_IRQ ((unsigned int)(0)) drivers/rtc/rtc-m48t59.c:#define NO_IRQ (-1) drivers/scsi/arm/fas216.h:#define NO_IRQ 255 As far as I can tell, only arm, microblaze, mn10200, parisc, and xtensa define NO_IRQ to -1, and of those I've got a pending patch to change Microblaze to use 0. arm is the hard holdout because of all the legacy board ports. > + > +/* > + * This type is the placeholder for a hardware interrupt number. It > + * has to be big enough to enclose whatever representation is used by > + * a given platform. > + */ > +typedef unsigned long irq_hw_number_t; > + > +static inline void irq_dispose_mapping(unsigned int virq) > +{ > + return; > +} > + > +struct irq_host; > + > +/** > + *. > + */ > +static inline unsigned int irq_create_mapping(struct irq_host *host, > + irq_hw_number_t hwirq) > +{ > + /* For now, an identity mapping. */ > + return (unsigned int)hwirq; > +} > + > #ifdef CONFIG_I8259 > static inline int irq_canonicalize(int irq) > { > -- > 1.7.2.3 > > -- Grant Likely, B.Sc., P.Eng. Secret Lab Technologies Ltd.
http://www.linux-mips.org/archives/linux-mips/2010-10/msg00175.html
CC-MAIN-2014-41
refinedweb
387
54.29
Scripter for Scene and other updates At the beginning of this year, Pythonista 3.2 brought support for ui.View.update, and thus made Scripter available for everyone. I have been using Scripter for UI animations in about every one of my projects for the past months, have been happy with its efficiency and stability, and thus wanted to just promote it a bit more. Here are some recent updates to the tool: - Scrolling banner view - Scripter in scene animations - Scripter for long-running tasks and polling Scrolling banner view c = ScrollingBannerLabel( text='Happy Pythonista 3.2 *****', text_color='green', font=('Futura', 24), initial_delay=0.5, scrolling_speed=50) Simple utility view, handy for news ticker type use cases, with an adjustable initial delay and scrolling speed: Scripter for Scene Nodes Turned out that it was very easy to enable Scripter in Scenes. Whereas on the UI side I would consider Scripter 'essential' (providing functionality that is not really there otherwise), for Scenes it is 'nice to have', or available if you want to use the same syntax in both UI and Scenes. Here's an example: from scripter import * from scene import * class MyScene (Scene): @script # setup can be a script def setup(self): self.background_color = 'black' s = self.ship = SpriteNode( 'spc:PlayerShip1Orange', alpha=0, scale=2, position=self.size/2, parent=self) yield 1.0 pulse(self, 'white') s = self.ship show(s, duration=2.0) scale_to(s, 1, duration=2.0) yield wobble(s) yield move_by(s, 0, 100) yield fly_out(s, 'up') yield l = LabelNode( text='Tap anywhere', position=self.size/2, parent=self) reveal_text(l) yield 2.0 hide(l) @script # touch events can be scripts def touch_began(self, touch): target = Vector(touch.location) vector = target - self.ship.position rotate_to(self.ship, vector.degrees-90) yield move_to(self.ship, *target, duration=0.7, ease_func=sinusoidal) run(MyScene()) Long-running task, polling etc. This is not an update to Scripter, just an expansion of my understanding on what it can be useful for. As Scripter has a lot parallels to things like asyncio, it can also be used to run long-running computations without freezing the UI and without threads, or to implement polling for some conditions. These require that you can insert a yieldstatement somewhere in your computation or loop, so calling long-running third party functions is not really an option. @mikael tried out the banner, its nice and simple to use and smooth. I could see a small decrease in performance when I changed the text_colour and bg_color. However, this could be just a perceived thing. I was just doing green text on a black bg. Also the roll to, rotate and rotate by generate the below trace back. I haven't checked them in the lib yet. If you close the error window, and click the buttons they work. So its something in the first call i guess. I am glad you posted this thread. I really should try and learn to use your Lib. It's for sure something I can not write myself. But used sparingly and correctly I am sure it could help ppl like me that struggle with animation math make some more professional looking UI's. I assume when making a UI, you would use Scripter along with your other lib gestures. Thanks again for your time and effort. Traceback (most recent call last): File "/private/var/mobile/Containers/Shared/AppGroup/3533032E-E336-4C25-BBC4-112A6BF2AF75/Pythonista3/Documents/site-packages-3/scripter/scripter.py", line 215, in update wait_time = next(gen) File "/private/var/mobile/Containers/Shared/AppGroup/3533032E-E336-4C25-BBC4-112A6BF2AF75/Pythonista3/Documents/site-packages-3/scripter/scripter.py", line 383, in slide_value delta_value = delta_func(start_value, end_value) File "/private/var/mobile/Containers/Shared/AppGroup/3533032E-E336-4C25-BBC4-112A6BF2AF75/Pythonista3/Documents/site-packages-3/scripter/scripter.py", line 375, in <lambda> delta_func = delta_func if callable(delta_func) else lambda start_value, end_value: end_value - start_value TypeError: unsupported operand type(s) for -: 'float' and '_ui.Transform' @mikael , I have been trying more in Scripter, mind you I am slow :( But 2 things that stand out. - There is no constants definitions for the 'ease' functions. If defined they could appear in the auto complete. - You have done scripts for example fly_out, but not fly_in. It may seem trivial, but you sort of expect to have the inverse script/func in the Lib API. Either though param or seperate func/method call. Just my feed back as a simple guy trying to use the Lib. Oh, one last thing. It seems like some utility functions that help you prepare a view(objects in a view) to be animated by a script would be nice. I dont have this clear in my mind, but for example a move_offsceen(v) would be an example. Maybe I am wrong, but I am trying to work out the best workflow to create a view, then animate it into existence as generically as possible. I realise, you have the creation of the view you want to present(animate), as well as you also have triggered/actions that your will also want to animate inside your view as a result of user interaction. @mikael , I hope you dont mind all my replies.... But I did the below code, just testing. I have got some things wrong, but its ok. But the attempt was to try to make objects within a view a little self describing. Maybe its a very bad idea, but even bad ideas lead to good ideas sometimes :). My example only tries this with one label. But i can see many different ways to approach this. Maybe each obj as a custom class with a std method name like animate_view for example and then the main view could call the animate_view methods in the correct sequence. Oh well food for thought! I am guessing you have sort of workflow as you say you have used Scripter in multiple projects you have been working on lately. import ui from scripter import * def move_offscreen_x(obj): if obj.frame.max_x: obj.x = -(obj.x + obj.frame.max_x) def mk_header_panel(w, h, hm=0, vm=0, **kwargs): h = ui.View(width=w, height=h, **kwargs) lb = ui.Label(frame=h.bounds, text='••• Altered Carbon •••', alignment=ui.ALIGN_CENTER, alpha=1) lb.font = ('Arial Rounded MT Bold', 48) h.add_subview(lb) ''' Just an idea, maybe a bad one! The idea is within the object creation, define the script func as well as the params. I have not thought this out. I just wanted to try... This example, does not work 100% because the text is aleady rendered in the view. ''' h.script = reveal_text h.params = {'view': lb, 'duration': 2} return h class CardA(ui.View): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.header = None self.cv = ui.View(frame=self.bounds.inset(12, 12), bg_color='purple', border_width=.5, corner_radius=12, flex='WH' ) self.add_subview(self.cv) self.make_view() def make_view(self): header = mk_header_panel(self.width, 150, bg_color='deeppink') self.cv.add_subview(header) self.header = header move_offscreen_x(self.header) self.card_reveal_script() @script def card_reveal_script(self): slide_value(self.cv, attribute='x', end_value=6, target=None, start_value=-self.width, duration=.3, delta_func=None, ease_func='easeIn', current_func=None, map_func=None, side_func=None) yield slide_value(self.header, attribute='x', end_value=0, target=None, start_value=self.width, duration=1, delta_func=None, ease_func='easeIn', current_func=None, map_func=None, side_func=None) yield ''' Just trying something different here! See if our object has a script attr, if it does we assume it has a param attr also. Another assumption(does not need to be an assumption) is that the params dict contains a key called view. Its popped of the dict, then rest of the dict is passed as the **kwargs to the obj.script func/method ''' if self.header.script: v = self.header.params.pop('view') self.header.script(v, **self.header.params) yield if __name__ == '__main__': f = (0, 0, 600, 800) c = CardA(frame=f) c.present('sheet') @Phuket2, thanks for pointing out the error. It is fixed in the repo. I will get back to the other points soon. @mikael , thanks! Rotating examples working now. Maybe its not a big deal, but in the demo, maybe some of the btns like 'roll to' should have the button's enable property set to False until its finished animating. Look its a small issue, But more than likely in an implementation you would want this behaviour. , thanks for the update. It appears that maybe you haven't pushed the last update to the repo. Last update appears to be the corrections for the rotation. Yes I understand your comments about self animating views (so to speak). Over the last few days I haven't had much time to experiment all though I do some stuff each day. But look for whatever reason, animations scare the hell out of me :) Just a mental block about the math. Eg. Easy for me to get confused. So its slow going for me. But, I am going to stick at it. The prospect of being able to construct views like this and other View animations on this site is exciting to me. Anyway, I will keep working on it. I have always been a little suprised that some of these more tantalising animations/transitions views have not shown up in Pythonista apps. Aka the feeling you are using a very polished native app. Its not a criticism, I just think its not a real focus for a lot of Python programmers (UI). Maybe I need to be burnt at the stake for that , ok no problems. I just misunderstood your post. I started having problems yesterday (I think after I updated to 11.2.5) about script not being defined. Strange, the trace back is below. I didn't have much time to found out the cause. The only thing i can think of is how I copied the Scripter code into Pythonista (I did a drag and drop copy from a clone of the repo in Working Copy). I am not really sure. Anyway, I am not really reporting it here as I need to try more things first. Anyway, when I come across this issue, I was just going to make a view that used your wobble script to wobble a ui.Button at regular interval (to draw attention to it). I was just interested to see how this all would work out. I.e the containing view having and update method as well as calling the script on the container views update fire. I assume it would work. As far as I can see there is no way for a script to re-animate given a duration/pause(maybe I am wrong) but I think its an interesting point, as some elements in a ui, you would like them to continue to animate forever, but with a pause between the animations so its not over the top. Even better the pause could have a ease function. Anyway, I am just talking giving my ideas. I dont expect anything from you, its your project. I come from the dummies side of things, meaning the less I need to know about using a Lib the better. But I do understand that libs are also written with a certain expectation that the user of the Lib/module has a degree of understanding of some primitives core to the lib. Traceback (most recent call last): File "/private/var/mobile/Containers/Shared/AppGroup/3533032E-E336-4C25-BBC4-112A6BF2AF75/Pythonista3/Documents/site-packages-3/scripter/scripter-demo.py", line 90, in <module> @script NameError: name 'script' is not defined , thanks for your reply. As regards to the error I am having, I am pretty sure somehow I have corrupted something. But at the moment my home internet is on and off like a yoyo :( Its cable issues in the streets. So its not so easy to do app downloads etc to reset. I will have to wait until they sort it out, again! I like your example notice! But it really does illustrates something. How you intend your lib to be used. I know its going to seem stupid, but the name of the Lib does says it all. I didn't really get that somehow. I was looking at your lib more from a macro point of view rather than a micro POV. I am not sure I have explained that clearly or not. But as I say, I will keep trying to get my head around it. In terms of doing animated views vrs PowerPoint slides concept. One could say they are they same or very similar(but they are not). I think the great thing is that your lib/module can support either direction. At least I think that... @Phuket2, I hear you. I think the approach here is to ”script” and publish the most generalized scripts as ”macros”, but unless you sort of internalize the basic ”philosophy of yielding”, it is very difficult to get the best out of the lib.
https://forum.omz-software.com/topic/4671/scripter-for-scene-and-other-updates
CC-MAIN-2021-21
refinedweb
2,180
67.55
NAME Module::List - module `directory' listing SYNOPSIS use Module::List qw(list_modules); $id_modules = list_modules("Data::ID::", { list_modules => 1}); $prefixes = list_modules("", { list_prefixes => 1, recurse => 1 }); DESCRIPTION This module deals with the examination of the namespace of Perl modules. The contents of the module namespace is split across several physical directory trees, but this module hides that detail, providing instead a view of the abstract namespace. FUNCTIONS - list_modules(PREFIX, OPTIONS) This function generates a listing of the contents of part of the module namespace. The part of the namespace under the module name prefix PREFIX is examined, and information about it returned as specified by OPTIONS. Module names are handled by this function in standard bareword syntax. They are always fully-qualified; isolated name components are never used. A module name prefix is the part of a module name that comes before a component of the name, and so either ends with "::" or is the empty string. OPTIONS is a reference to a hash, the elements of which specify what is to be returned. The options are: - list_modules Truth value, default false. If true, return names of modules in the relevant part of the namespace. - list_prefixes Truth value, default false. If true, return module name prefixes in the relevant part of the namespace. Note that prefixes are returned if the corresponding directory exists, even if there is nothing in it. - list_pod Truth value, default false. If true, return names of POD documentation files that are in the module namespace. - trivial_syntax Truth value, default false. If false, only valid bareword names are permitted. If true, bareword syntax is ignored, and any "::"-separated name that can be turned into a correct filename by interpreting name components as filename components is permitted. This is of no use in listing actual Perl modules, because the illegal names can't be used in Perl, but some programs such as perldoc use a "::"-separated name for the sake of appearance without really using bareword syntax. The loosened syntax applies both to the names returned and to the PREFIX parameter. Precisely, the `trivial syntax' is that each "::"-separated component cannot be "." or "..", cannot contain "::" or "/", and (except for the final component of a leaf name) cannot end with ":". This is precisely what is required to achieve a unique interconvertible "::"-separated path syntax on Unix. This criterion might change in the future on non-Unix systems, where the filename syntax differs. - recurse Truth value, default false. If false, only names at the next level down from PREFIX (having one more component) are returned. If true, names at all lower levels are returned. - use_pod_dir Truth value, default false. If false, POD documentation files are expected to be in the same directory that the corresponding module file would be in. If true, POD files may also be in a subdirectory of that named " pod". (Any POD files in such a subdirectory will therefore be visible under two module names, one treating the " pod" subdirectory level as part of the module name.) Note that the default behaviour, if an empty options hash is supplied, is to return nothing. You must specify what kind of information you want. The function returns a reference to a hash, the keys of which are the names of interest. The value associated with each of these keys is undef. SEE ALSO AUTHOR Andrew Main (Zefram) <zefram@fysh.org> LICENSE This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
https://metacpan.org/pod/Module::List
CC-MAIN-2016-50
refinedweb
581
55.84
Hi, I'm developing a web app, and I'd like to log some information to help me improve and observe the app. (I'm using Tomcat6) First I thought I would use StringBuilders, append the logs to them and a task would persist them into the database like every 2 minutes. Because I was worried about the out-of-the-box logging system's performance. Then I made some test. Especially with log4j. Here is my code: Main.java public static void main(String[] args) { Thread[] threads = new Thread[LoggerThread.threadsNumber]; for(int i = 0; i < LoggerThread.threadsNumber; ++i){ threads[i] = new Thread(new LoggerThread("name - " + i)); } LoggerThread.startTimestamp = System.currentTimeMillis(); for(int i = 0; i < LoggerThread.threadsNumber; ++i){ threads[i].start(); } LoggerThread.java public class LoggerThread implements Runnable{ public static int threadsNumber = 10; public static long startTimestamp; private static int counter = 0; private String name; public LoggerThread(String name) { this.name = name; } private Logger log = Logger.getLogger(this.getClass()); @Override public void run() { for(int i=0; i<10000; ++i){ log.info(name + ": " + i); if(i == 9999){ int c = increaseCounter(); if(c == threadsNumber){ System.out.println("Elapsed time: " + (System.currentTimeMillis() - startTimestamp)); } } } } private synchronized int increaseCounter(){ return ++counter; } } } log4j.properties log4j.logger.main.LoggerThread=debug, f log4j.appender.f=org.apache.log4j.RollingFileAppender log4j.appender.f.layout=org.apache.log4j.PatternLayout log4j.appender.f.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n log4j.appender.f.File=c:/logs/logging.log log4j.appender.f.MaxFileSize=15000KB log4j.appender.f.MaxBackupIndex=50 I think this is a very common configuration for log4j. First I used log4j 1.2.14 then I realized there was a newer version, so I switched to 1.2.16 Here are the figures (all in millisec) LoggerThread.threadsNumber = 10 1.2.14: 4235, 4267, 4328, 4282 1.2.16: 2780, 2781, 2797, 2781 LoggerThread.threadsNumber = 100 1.2.14: 41312, 41014, 42251 1.2.16: 25606, 25729, 25922 I think this is very fast. Don't forget that: in every cycle the run method not just log into the file, it has to concatenate strings (name + ": " + i), and check an if test (i == 9999). When threadsNumber is 10, there are 100.000 loggings and if tests and concatenations. When it is 100, there are 1.000.000 loggings and if tests and concatenations. (I've read somewhere JVM uses StringBuilder's append for concatenation, not simple concatenation). Did I miss something? Am I doing something wrong? Did I forget any factor that could decrease the performance? If these figures are correct I think I don't have to worry about log4j's performance even if I heavily log, do I? I've read that: "The typical cost of actually logging is about 100 to 300 microseconds." Is it correct? (log4J manual)
http://ansaurus.com/question/3053134-log4j-performance
CC-MAIN-2019-30
refinedweb
467
53.98
Closed Bug 909178 Opened 8 years ago Closed 8 years ago Make jsclass .h not depend on jsapi .h Categories (Core :: JavaScript Engine, defect) Tracking () mozilla26 People (Reporter: n.nethercote, Assigned: n.nethercote) References Details (Whiteboard: [js:t]) Attachments (2 files) Making jsclass.h not depend on jsapi.h is critical for reducing the amount of Gecko code that depends on jsapi.h. This is a necessary precursor to the next patch, and a whole lot that will follow in other bugs. The need for IdForward.h is explained in a comment. Annoying, but I don't see a better way to do it. Attachment #795241 - Flags: review?(luke) This patch moves a bunch of class-related stuff from jsapi.h to jsclass.h, and renames jsclass.h as js/Class.h. This allows jsapi.h to now include jsclass.h, rather than the other way around. This is critical for reducing the number of Gecko files that depend on jsapi.h, because heaps of Gecko code (esp. DOMJSClass.h) needs class-related stuff but not other jsapi.h stuff. Also, it's better to have a big header depend on a small header than the other way around. It also makes a lot of sense -- it was weird having half of the class-related stuff in jsapi.h and half in jsclass.h. Attachment #795243 - Flags: review?(jwalden+bmo) Comment on attachment 795241 [details] [diff] [review] (part 1) - Move |jsid| from jsapi.h into js/Id.h. Review of attachment 795241 [details] [diff] [review]: ----------------------------------------------------------------- ::: js/src/jsapi.cpp @@ -125,5 @@ > > -#ifdef JS_USE_JSID_STRUCT_TYPES > -const jsid JSID_VOID = { size_t(JSID_TYPE_VOID) }; > -const jsid JSID_EMPTY = { size_t(JSID_TYPE_OBJECT) }; > -#endif I'd kinda rather just leave it here rather than make a whole new Id.cpp, unless later patches add to Id.cpp? Attachment #795241 - Flags: review?(luke) → review+ > I'd kinda rather just leave it here rather than make a whole new Id.cpp, > unless later patches add to Id.cpp? They don't. But I like having .cpp files that correspond to js/*.h files, because they provide a place where the .h file is included before any others, and so guarantees that the .h file is self-sufficient. See bug 905507. Also, imagine a glorious future in which jsapi.h has been entirely broken up into smaller headers. Will jsapi.cpp still remain to hold the code that we didn't want to bother creating separate .cpp files for? Comment on attachment 795243 [details] [diff] [review] (part 2) - Make jsclass.h not depend on jsapi.h, and rename it js/Class.h. Review of attachment 795243 [details] [diff] [review]: ----------------------------------------------------------------- I didn't look too closely at the contents of js/public/Class.h after this, to see if what was in jsclass.h that wasn't in context (or wasn't touched) should really sensibly be there. Ditto, in reverse somewhat, for jsapi.h. Probably it's mostly reasonable as-is, didn't seem worth fine-toothed-combing it. ::: js/public/Class.h @@ +3,5 @@ > * This Source Code Form is subject to the terms of the Mozilla Public > * License, v. 2.0. If a copy of the MPL was not distributed with this > * file, You can obtain one at. */ > > #ifndef jsclass_h Please add an overview comment /* JSClass definition and its component types, plus related interfaces. */ between license block and include-guard. That'll show up on and help people reading our code understand where things are, slightly. @@ +267,5 @@ > +typedef void > +(* JSFinalizeOp)(JSFreeOp *fop, JSObject *obj); > + > +// Finalizes external strings created by JS_NewExternalString. > +typedef struct JSStringFinalizer JSStringFinalizer; Remove the typedef, we're C++ now. Attachment #795243 - Flags: review?(jwalden+bmo) → review+ For what it's worth, Id.cpp for those library externs seems fine to me. (In reply to Nicholas Nethercote [:njn] from comment #4) > But I like having .cpp files that correspond to js/*.h files, > because they provide a place where the .h file is included before any > others, and so guarantees that the .h file is self-sufficient. Oh, I forgot about that; that's a good reason. Status: ASSIGNED → RESOLVED Closed: 8 years ago Resolution: --- → FIXED Target Milestone: --- → mozilla26
https://bugzilla.mozilla.org/show_bug.cgi?id=909178
CC-MAIN-2021-10
refinedweb
689
71
Ankur and Rishabh are two friends and want to buy some fruits from the market. They both have a list of their favourite fruit represented by strings. Your task is to help them find out their common favourite fruit with the minimum index sum. If there is a tie in the choice between them then output all of them with no order requirement. You can assume that there will always exist an answer. Example Input [“Apple”, “Orange”, “Mango”, “Lichi”] [“Guava”, “Strawberry”, “Lichi”] Output Lichi Explanation Lichi is the only common fruit between them. Input [“Orange”, “Mango”, “Lichi”, “Apple”, “Strawberry”] [“Strawberry”, “Orange”, “Apple”] Ouput Orange Explanation The fruit which is favourite of both and has the least index sum is “Orange” with index sum 1 (0+1). Algorithm for Minimum Index Sum of Two Lists - Get the two lists as our input values. - Declare the map and a Vector. - Add the values of list1 into the map with their indexes. - Traverse the list2 and check if the element of list2 is present in the map and set ‘minimum’ to the maximum value of the integer. - If found then store the sum of the current index and found element index into sum and store into sum. - Check if the minimum is less than the sum if true then store sum into a minimum. - Clear the resultant vector and store the new element. - If the sum is equal to the minimum then simply add the value into the resultant vector. - Print the output vector, we will get our answer. Explanation First of all, we are two lists as commonThings1 and commonThings2. These are our input values. So what we are going to do is we are going to pass these lists into our function in which we going to find our output. We get those lists in which some strings are store in it as list1 and list2 as our input. We are going to use hashing and using a HashMap as our collection. Using HashMap we can store the elements into Map and their indexes, indexes help us to find out the least index sum. We can declare a vector of string “output” in which we going to store our output and later print that. So we can take an example to understand this. list1: [ “Apple”, ”Orange” , ”Mango” , “Lichi”] list2: [“Guava”, “Strawberry”, “Lichi”] We will traverse the list1 and add all the value of list1 into the map. Then we will check for the list2 elements if the map contains any one of the list element then we found the item, but we will search for the least minimum index, for that we will be declaring the sum and minimum, we will be checking the list1 element index and list2 element index we found, the sum of them is minimum of all, if we found minimum then we clear the resultant output and make a new entry in that, and also if two elements least index sum is equal, previous and current, then we will just push the new element. In the example, we have taken, in this. we have only match found that is Lichi, and of the least minimum index and in all of that it is the only element found in the lists. C++ Program for Minimum Index Sum of Two Lists #include<bits/stdc++.h> #include<unordered_map> #include<vector> using namespace std; void getCommonString(vector<string> list1, vector<string> list2) { unordered_map<string, int> map; for (int index = 0; index < list1.size(); index++) map[list1[index]] = index; vector<string> output; int minimum = INT_MAX; for (int j = 0; j < list2.size(); j++) { if (map.count(list2[j])) { int sum = j + map[list2[j]]; if (sum < minimum) { minimum = sum; output.clear(); output.push_back(list2[j]); } else if (sum == minimum) output.push_back(list2[j]); } } for (int i = 0; i < output.size(); i++) cout << output[i] << " "; } int main() { vector<string> commonThings1; commonThings1.push_back("Apple"); commonThings1.push_back("Orange"); commonThings1.push_back("Mango"); commonThings1.push_back("lichi"); vector<string> commonThings2; commonThings2.push_back("Guava"); commonThings2.push_back("Strawberry"); commonThings2.push_back("lichi"); getCommonString(commonThings1, commonThings2); return 0; } lichi Java Program for Minimum Index Sum of Two Lists import java.util.HashMap; import java.util.Vector; class commonThings { public static void getCommonString(Vector<String> list1, Vector<String> list2) { Vector<String> output = new Vector<String>(); HashMap<String, Integer> map = new HashMap<>(); for (int index = 0; index < list1.size(); index++) map.put(list1.get(index), index); int minimum = Integer.MAX_VALUE; for (int j = 0; j < list2.size(); j++) { if (map.containsKey(list2.get(j))) { int sum = j + map.get(list2.get(j)); if (sum < minimum) { minimum = sum; output.clear(); output.add(list2.get(j)); } else if (sum == minimum) output.add(list2.get(j)); } } for (int i = 0; i < output.size(); i++) System.out.println(output.get(i) + " "); } public static void main(String[] args) { Vector<String> commonThings1 = new Vector<String>(); commonThings1.add("apple"); commonThings1.add("mango"); commonThings1.add("banana"); commonThings1.add("lichi"); Vector<String> commonThings2 = new Vector<String>(); commonThings2.add("guava"); commonThings2.add("strawberry"); commonThings2.add("lichi"); getCommonString(commonThings1, commonThings2); } } lichi Complexity Analysis for Minimum Index Sum of Two Lists Time Complexity O(l1+l2), where l1 and l2 are the lengths of list1 and list2. Space Complexity O(l*x) where x is the length of the resultant list used to store the result and l is the maximum string length.
https://www.tutorialcup.com/interview/array/minimum-index-sum-of-two-lists.htm
CC-MAIN-2021-39
refinedweb
888
65.01
Hello everyone, I have two files i.e Rules.txt and Members.txt. I have set different rules for different members. Now i have break down the rules comma seperately using the for loop. I want to compare each index of the 1st file with the respective index of the second file. If it matches so it should do something and vice versa. Please let me know how can i compare them? I am new to python. Thanks in advance. def compare(): file1=open("D:\Rules.txt") for rules in file1: print rules.split(',') membersFile=open("D:\Members.txt") for members in membersFile: print members.split(',') compare()
https://www.daniweb.com/programming/software-development/threads/504480/python-comparing-two-values-of-lists
CC-MAIN-2018-30
refinedweb
107
80.48
Journey into Haskell, part 3 Today I need a wrapper script to drop arguments from a command-line. I instinctively reached for bash, but then thought it would be a good exercise for my infant Haskell knowledge. The task The task at hand is to write a wrapper script for /usr/bin/ld that drops arguments beginning with -Wl,-rpath,. Since it must deal with arguments containing spaces, and I didn’t want to get into executing external programs with Haskell just yet, I wrappered the wrapper: #!/bin/bash $(dirname $0)/ld-wrapper "$@" | xargs -0 /usr/bin/ld Here ld-wrapper is expected to return its arguments separated by NUL characters so I can feed it to xargs, and from there to /usr/bin/ld. I’m sure there’s an easy, all-in-one way to do this with Haskell, I just haven’t reached that chapter yet. Haskell version Anyway, here is the Haskell script: import Data.List import System.Environment main = do args <- getArgs putStr $ intercalate "\0" $ filter (not . isPrefixOf "-Wl,-rpath") args Pretty basic: it filters the input arguments, keeping each one which does not begin with the sought-for string, and joins the list together using NUL as the separator. Ruby version As a quick sanity check, I wrote the same thing in Ruby, since it has facilities for being just as succinct: print ARGV.select { |y| !y.include?("-Wl,-rpath") }.join("\0") + "\0" I wanted to do this with an “inverse grep” instead of select, but couldn’t find a way to grep for the opposite of a pattern. What’s interesting is that the Ruby version is marginally faster than the compiled Haskell one. For filtering 40,000 arguments, here are the averaged run-times over 20 invocations: My guess is that Haskell is creating 40,000 different strings in memory as it constructs the final result, while Ruby is pasting one together as it goes. I don’t know which. Syndicated 2009-03-19 05:59:06 (Updated 2009-03-19 08:04:05) from Lost in Technopolis
http://www.advogato.org/person/johnw/diary/59.html
CC-MAIN-2013-48
refinedweb
346
60.55
Hello, With JeCARS we need(ed) a backup facility to be prepared for nodetype evolution and general backup reasons. I decided to do things a bit different, perhaps I am missing some points :-)... but anyway the first version works fairly well. The JeCARS backup facility can export a part of the tree (or the complete tree) it will generate two files for namespaces (exportNamespaces.jb) and a CND nodetype definition (exportNodeTypesCND.jb). The third file (exportJeCARS.jb) contains the complete tree information (except for the binary data) in a "own" format. The binary data are stored as seperate files in the same directory. The import facilty will use the information to restore the repository. The sourcecode is available at the backup tool code is in the package org/jecars/backup. It can be used with any Jackrabbit repository. Non jackrabbit repositories should also work with exception of the nodetype import. Our repositories don't use versioning (yet!) so no solution for that.... am afraid... But hopefully it can help other users also.... And if there is some interest I could give more information or create a seperate .jar. Greetings, Jacco van Weert
http://mail-archives.apache.org/mod_mbox/jackrabbit-users/200710.mbox/%3Cfd7bdf180710020814y289eab1fm1cf53250a79729e1@mail.gmail.com%3E
CC-MAIN-2014-52
refinedweb
192
60.41
Often we save settings or configurations in json files. If you’ve spent some time using NodeJS, you’d know that there are quite a few ways to read json files in NodeJS Two of the most common ones are : let jsonData = require('./file.json') // let jsonData = require('./file') // omitting .json also works The other way is using the fs module. We can either do it synchronously const fs = require('fs') let jsonData = JSON.parse(fs.readFileSync('file.json', 'utf-8')) Or we can do it asynchronously - const fs = require('fs') let jsonData = {} fs.readFile('file.json', 'utf-8', (err, data) => { if (err) throw err jsonData = JSON.parse(data) }) Now obviously the question that comes to mind is which method to use, and if there are any obvious benefits to any one method Let us discuss the differences - Caching : (If the file data changes) require() will cache the file in the require graph. So during the lifetime of the node app, if the file.json is changed, you will not get the new data, even if you re-run require('./file.json') On the other hand fs.readFile or fs.readFileSync will always re-read the file, and pick up changes. Encoding : (UTF-8 is used 99% times, but still…) In require you cannot define the file encoding. 99% of the times, that is not a problem. Nevertheless if your json is not encoded in Unicode/UTF-8, you’d have to use fs.readFile as it supports encodings such as ascii or latin1 or even base64 (yes, yes, I hear you, no one saves JSON as base64) Sync vs Async require() is synchronous, and hence blocking in nature. fs provides both sync and async methods as shown above. If you want to read your JSON file without blocking, then fs.readFile is your only option. NOTE: From NodeJS 10.x, import file from './file.json' would be possible because of support for modules, which would allow async reading of json files without fs I hope you’ll be able to take an informed decision in your future projects based on the points discussed here.
http://blog.codingblocks.com/2017/reading-json-files-in-nodejs-require-vs-fs-readfile
CC-MAIN-2018-43
refinedweb
355
74.29
graphql with vuex / quasar - MusicForMellons @s-molinari I think I noticed you trying to pull this of in several repos etc. (using e.g. Appollo). As I am interested in this as well: any solution that works now? Nope. Not yet. The closest is this: That is what I was intending to implement, once I get that far. From my small understanding, Vue 2.0 should play a lot better with redux, so vue-apollo is worth looking at. Scott - joaopaulofilho I’m also interested int this config and have researched a lot about this. For the time being, apollo can’t ad hoc integrate with vuex (although has integration wit redux). My solution so far is to implement import ApolloClient from 'apollo-client' const apolloClient = new ApolloClient({ ... }) Then in vuex const store = new Vuex.Store({ ... mutations: { apolloClient.query({ ... }) } }) Working well, but several things is manually integrated. @jo I’ve been doing the same research and s.molinari you come up everywhere I look too! Totally agree it would be a winning combination. I’m also interested in providing an offline-first experience and I’d really like a realtime reactive graph database - preferably queried with graphQL. There doesn’t seem to be anything out of the box that fits my ridiculous expectations though, haha. Of course, it can all be done if you implement it yourself, but it’s above my current skill level Looks like we are in the same boat. @jolyon I am, however, working slowly but surely towards that goal. But, if I can influence others to get it done faster, that is also what I’ll do (and why you see me in such discussions often). Scott
http://forum.quasar-framework.org/topic/104/graphql-with-vuex-quasar
CC-MAIN-2017-17
refinedweb
282
65.01
Indicator warmup period Imagine, we want to run strategy during 2017year using RSI(14)indicator on daily basis. Strategy should say that warmup period is 14 days. How to know that strategy need some data from 2016to start trading from 1st of January 2017before running whole trading loop. Because you want an RSIindicator with period 14(which actually needs 15data points to produce values) This is simply common sense and no magic. If you want to load the smallest possible dataset, you have to do two runs: A dry run to see what the auto-calculated minimum period is A run loading the data and executing your backtesting Even in this case you don't exactly when the original dataset has to start (date-wise) because some days may have been bank holidays. But in any case to get the auto-calculated minimum period: In the startmethod of a strategy Check the attribute: _minperiod Should several timeframes be in place then: - Check the attribute _minperiodswhich is a list containing the minimum period that applies to each timeframe (in the order in which the data/timeframes were inserted in the system) Thanks for the information about _minperiod. Seems like exceptions in dry run are needed to immediately stop first execution. @Maxim-Korobov You don't have to pass the actual data to do a dry run. Just something that let you see the _minperiod. Or you can call cerebro.runstop()as soon as your strategy gets started. Docs - Cerebro - Maxim Korobov last edited by You don't have to pass the actual data to do a dry run Yes, all internals of strategies are called even without passing data. But strategies_info = back_trader.run() returns empty list when run without data. How to reach strategies data from the outside? You don't have to pass the actual data This doesn't mean you don't have to pass one data feed. You can pass a data feed which has no data. But no data, no fun. Could you please provide such fake data feed? I tried class FakeFeed(btfeeds.DataBase): def __init__(self): super(FakeFeed, self).__init__() which crashed internally: class Average(PeriodN): ... for i in range(start, end): dst[i] = math.fsum(src[i - period + 1:i + 1]) / period Because of empty src. Run in the non-once mode, cerebro.run(runonce=False). The runoncepreprocess all indicators before the logic is run. Thank you! With this flag it works like a charm. Code: import backtrader as bt class WarmupDetector: @staticmethod def detect(strategies): greatest_warm_up_period, strategy_name = 0, "" runner = bt.Cerebro() for sta in strategies: runner.addstrategy(sta, silent=True) stub_data = bt.DataBase() runner.adddata(stub_data) sis = runner.run(runonce=False) for si in sis: period = si.get_warm_up_period() if period > greatest_warm_up_period: greatest_warm_up_period, strategy_name = period, si.__class__.__name__ return greatest_warm_up_period, strategy_name @staticmethod def detect_period(strategies): return WarmupDetector.detect(strategies)[0] Usage: warm_up_period, warm_up_strategy_name = WarmupDetector.detect(strategies_to_add) works for me with period = si._minperiod instead of period = si.get_warm_up_period()
https://community.backtrader.com/topic/167/indicator-warmup-period
CC-MAIN-2020-40
refinedweb
494
50.94
sandbox/Antoonvh/isotropicLES.c Large Eddy Simulation of isotropic Turbulence. On this page we aim to validate the Large Eddy Simulation (LES) formulation as defined in the SGS.h header file. Fortunately, benchmark results from a Direct Numerical Simulation (DNS) are provided under /src/examples here. We only need to slightly alter the formulation presented there to turn the DNS into an LES. This page will highlight these changes and present the results. Setup First we include the Sub-Grid-Scale formulation. Furthermore, we include a function to help visualize the contours. #include "grid/multigrid3D.h" #include "navier-stokes/centered.h" #include "SGS.h" #include "lambda2.h" #include "structurefunction.h" #define MU 0.01 face vector av[]; FILE * fp1; Second, Facilitated by our filtered approach, we reduce the resolution from to . int maxlevel = 5; int lin = 0; int main (int argc, char * argv[]) { if (argc > 1) maxlevel = atoi(argv[1]); L0 = 2.*π; foreach_dimension() periodic (right); a = av; N = 1 << maxlevel; run(); } Third, a relevant value for the SGS-tuning constant is set and we tell the simulation that the molecular viscosity is the MU value. Additionally, we open a file to we can display the results on this page. event init (i = 0) { Csmag=0.2; molvis=MU; fp1=fopen("LES.dat","w"); foreach() { u.x[] = cos(y) + sin(z); u.y[] = sin(x) + cos(z); u.z[] = cos(x) + sin(y); } boundary ((scalar *){u}); } event acceleration (i++) { coord ubar; foreach_dimension() { stats s = statsf(u.x); ubar.x = s.sum/s.volume; } foreach_face() av.x[] += 0.1*((u.x[] + u.x[-1])/2. - ubar.x); } Fourth, The dissipation should be calculated with the eddy viscosity. event logfile (i+=10; t <= 300) { coord ubar; foreach_dimension() { stats s = statsf(u.x); ubar.x = s.sum/s.volume; } double vd; double ke = 0., vdt = 0., vdm = 0.,vde = 0., vol = 0.; foreach(reduction(+:ke) reduction(+:vdt) reduction(+:vde) reduction(+:vdm) reduction(+:vol)) { vol += dv(); foreach_dimension() { // mean fluctuating kinetic energy ke += dv()*sq(u.x[] - ubar.x); // viscous dissipation vd = dv()*(sq(u.x[1] - u.x[-1]) + sq(u.x[0,1] - u.x[0,-1]) + sq(u.x[0,0,1] - u.x[0,0,-1]))/sq(2.*Δ); vde+=(Evis[]-MU)*vd; vdm+=MU*vd; vdt+=Evis[]*vd; } } ke /= 2.*vol; vdm /= vol; vde /= vol; vdt /= vol; if (i == 0) fprintf (fp1, "t dissipationt energy disse dissm perf.t perf.speed\n"); fprintf (fp1, "%g %g %g %g %ld %g %g\n", t, vdt, ke, vde, vdm, perf.t, perf.speed); } As a concsistency check, we evaluate the second-order structure function at fixed time intervals. Or is it really the structure funtion we aim for? event structurefun(t+=50){ char name2[100]; lin++; sprintf(name2,"structure%d.dat",lin); FILE * fp2 = fopen(name2,"w"); long2structure(fp2,u,1000,L0/2.,100); fflush(fp2); fclose(fp2); } For our visual statisfaction, we also generate an animated gif with 250 frames. event gfsview (t += 0.2; t <= 50) { scalar λ[]; lambda2(u,λ); static FILE * fp = popen ("gfsview-batch3D isotropicLES.isotropic.gfv | ppm2gif > isoLES.gif", "w"); output_gfs(fp); fprintf (fp, "Save stdout { format = PPM width = 500 height = 500}\n"); } Results Movie before plots: Evolution of the contours. We also look at some statistics. The resolved kinetic energy is shown below: Evolution of kinetic energy Compared to the spectral results, the LES ‘suffers’ from the early onset of turbulence, similar as the DNS run with Basilisk. The fluctuating kinetic energy after this initial transition (i.e. ) appears to be quite well captured. So atleast the implementation of the SGS formulation did not totally ruin the results. However, one may argue that energy is a rather simple quantity to get correct as it may very well be a result of the construct of the case definition. Therefore, we also look at the resolved dissipation of the simulations. Evolution of dissipation Seems OK. However, the initial transition shows a bit of a deveation, even between both Basilsik-based runs. We look at it in a bit more detail: Evolution of the dissipation during the initial instability and its partitioning The second-order longitudional structure function was also computed and it is plotted below. We do observe a range with a scaling characteristic. But is is not the 2/3 law I was expexting. We conclude that the SGS-model is not able to properly capture the dissipation dynamics within the transition. This is not a show stopper perse, more that this serves as a cautionary note; for an accurate representation of certain flow statistics an LES is not always a suitable approach. The fact that the SGS model was able to preserve large-eddy quantities, like the kinetic energy, is motivating for its future usage. Furthermore, after the transition the turbulent strucures become larger and the spectrum more resolved. The SGS controbutions also vanish in that case. That is a nice feature. Finally, note that the reduction from a grid to a grid results is approximately times less effort. Meaning that instead of using 512 cores for the original example, this simulation is reasonably fast on a single processor. So in that respect, well done LES-techniques! Also I checked the overhead of the LES formulation on my own system, using a single core. In DNS mode, I obtained an averaged performance figure of points/sec during the first time units, and with the LES formulation this number was reduced to points/sec. Thus a reduction of 15%. These numbers were obtained with no movie output and less frequent calls to the diagnostic event.
http://basilisk.fr/sandbox/Antoonvh/isotropicLES.c
CC-MAIN-2018-43
refinedweb
929
59.4
Hi, What is the limitation of number of columns in single worksheet of 2007 Excel format? The sheet I am going to generate is consisting more than 4068 columns. It is throwing an exception : com.aspose.cells.CellsException: Formula error. Cell[Patent1 To 322!EZQ11]: name index(-1) not found! Thanks, Vimlesh Hi, Hi Vimlesh, Well, there is no limitation in terms support for Excel 2007 format for Aspose.Cells for Java product. The component just supports the same as MS Excel (2007) does (Worksheet size = max 1,048,576 rows by max 16,384 columns). I have tested your scenario a bit using the following sample code with the attached version and it works fine. Sample code: Workbook workbook = new Workbook(); Worksheets worksheets = workbook.getWorksheets(); Worksheet worksheet = worksheets.getSheet(0); for(int i = 0; i< 500; i++) { for(int j=0;j<5000;j++) { worksheet.getCells().getCell(i,j).setValue(i+j); } } workbook.save(“d:\files\MyTestBook.xlsx”,FileFormatType.EXCEL2007); Well, when filling large dataset into a sheet with large number of columns/rows, the process would surely require a lot of memory but there is not any known issue for it. You got to make sure that you have sufficient amount of memory assigned to your JVM too I have also attached the latest fix for you if you can give it a try. If you find any issue, kindly give us your sample code and template file(if you have) to reproduce the issue and we will check it asap. Thank you. Thanks for quick reply. Yes, you are right. Number of columns is not creating a problem. Problem is with formula that is being set. If a formula being set in any cell is ‘EZQ11’. It is creating a problem while saving the workbook. This is one of the cases. May be there are many more column references, being used as formula, that are creating problems in being set. Exception thrown in this case is : java.io.IOException: Formula error. Cell[Patent1 To 322!EZQ11]: name index(-1) not found! at com.aspose.cells.Workbook.save(Unknown Source) Please look into this part of problem. May be the problem is related to formula being set in aspose java. Thanks, Vimlesh Hi,<?xml:namespace prefix = o Thank you for considering Aspose. Aspose.Cells does not support more than 256 columns (Excel 2003 max column count) in formulas. We have registered your required feature in our issue tracking system with issue if CELLSJAVA-14274. We will look into it and try to support it soon. Thank you & Best Regards, Hi, Please try the attached version. We have supported setting formulas that refer to row/column/parameters count that exceeds excel2003’s limit.<o:p></o:p> To remove the limit of excel2003 for row, column and parameters count, please set the file format of Workbook to other file formats than EXCEL97TO2003. Code like following: Workbook wb = new Workbook(); wb.setFileFormatType(FileFormatType.EXCEL2007); //....................... Cell cell = cells.getCell(0, 0); cell.setFormula("=EZQ11"); Thank you The issues you have found earlier (filed as 14274) have been fixed in this update. This message was posted using Notification2Forum from Downloads module by aspose.notifier.
https://forum.aspose.com/t/what-is-limitation-of-number-of-columns-in-2007-excel-format/140745
CC-MAIN-2022-27
refinedweb
532
60.41
Plush Toy, Singing With Mommy's Voice Introduction: Plush Toy, Singing With Mommy's Voice This Instructables is about upgrading a plush toy to give it the ability to sing when baby presses its belly. Most importantly : it will not play a stupid pre-recorded music, but actually sing mommy's songs, with mommy's voice ! This project started with two goals in mind: customizing a nice gift for my baby, and raising support from my wife in my electronics hobby :-) Material needed Toy - plush toy (one that you can tear apart without regret) - Velcro strips Electronics - Arduino Uno - MP3 shield (I recommend Sparkfun's - the code I will provide is based on this model) - 0.5W speaker - 9V battery with its connector and a 2.1mm Jack to plug in the Arduino - pushbutton - on-off switch (optional) - crimp connectors (optional) Other components - used credit or fidelity card - empty business card box. Level : I assume the reader is comfortable with both Arduino (and shields) and general electronics, including soldering. I will skip many details but do not hesitate to ask in comments, I will reply. Acknowledgment : Bill Porter has written a MP3 librairy for the Sparkfun shield that greatly facilitated my work (as well as further support in his forum). His website is Step 1: Ripping Apart Teddy Bear and Stitching It Back As the title suggest, this step involves sharp blades and open-heart surgery. Jokes aside - It is important to open the plush toy in the cleanest fashion possible, in order to be able to put in back together at the end. Look for a long sewing line, for example in the back, and cut the sewing threads with a cutter blade. Then remove all filler from the belly, and keep it in a plastic bag. Last step for the preparation of the plush toy : sew two bands of Velcro on each side of the cut. Step 2: Assembling the Electronics - the Pushbutton The first picture show the assembly diagram. (Note: read this Instructable until the end before. Some of these wires need to go through a hole of the box, before soldering) First, solder the connectors to the MP3 shield and plug it into the Arduino. Then, let us deal with the pushbutton. 1) The pushbutton connects the +5V to the pin 5 of the shield, one of the few pins left available on the Sparkfun MP3 shield. a 10kOhm pull-down connects the pin 5 to the ground. 2) There will probably be no room for breadboard in the toy, so you will have to solder the wires and the resistor on a small piece of proto board, as shown on the 2nd picture. Then, insert a small piece of insulator (extruded polystyrene, cardboard, ...) between the MP3 shield and the proto board, to avoid any short circuits. 3) Notice that the pushbutton connection to the proto board is through a crimp connector. This is optional, but is very convenient later when arranging the electronic enclosure. The final overview of the pushbutton can be seen on the last picture Step 3: Assembling the Electronics - Speaker and Battery Now let us connect the speaker and the battery. 1) Because the space in the business card box was so tight, I had to remove the plastic protection of the jack, to solder directly the wires to the connectors, then bend them away to make room for the battery. You may not need to do this if your box is slightly bigger, on your battery slightly smaller. If you use the same trick then don't forget : the positive pin is inside, the ground is outside. 2) Directly solder the ground from the battery to the Arduino jack. 3) Connect the positive side through a on-off switch. This is optional, but very convenient. Otherwise, in order to save battery life when your baby is done playing with the toy, you'd have to remove the battery. (Note: read this Instructable until the end before. this wire need to go through a hole of the box, before soldering) 4) Solder the speaker connection to the L and R connections of the MP3 shield. Note that we don't use the audio ground connector named "-", because the shield library comes with a "Differential Output" mode that allows for more volume this way. Once again, for convenience, I recommend to use Molex connectors but this is optional. Step 4: Recording the Songs Here is the funny part of the Instructables. Use a recording device of your choice to capture the nursery rhymes your baby likes. You can, of course, use commercial MP3 files, but it is so much more fun and sweet if you and/or your spouse sings the songs ! If the recorded files are not MP3 - convert them. Many tools are available, I used Format Factory. When you convert audio files to MP3, make sure you choose "192 kbits/s", because this is what the Sparkfun MP3 shield uses. Name the file track001.mp3, track002.mp3, etc... Then, transfer them on a micro-SD card that fits into the shield slot. Step 5: The Arduino Code The sketch below plays a song when the button is pressed. Another pression on the button interrupts the song. A counter is incremented each time to go through all the tracks. Note 1: the variable nbTracks has to be initialized with the number of files on your SD card. Note 2: a few librairies need to be installed for the code to work. Luckily for us, Bill Porter has GREATLY simplified them, so that the code is real simple. go to for description, and to for files. ---------------------------------------------------------------------------------------------------- //This code plays an MP3 song when a button is pressed //When the button is pressed, the MP3 shield plays the track00x song (a counter x is incremented) //When pressed again, the track is stopped (if it was playing) //The musics tracks are stored on the SD card as track00x.mp3 format //libraries come from //github source : #include <SPI.h> //bus SPI #include <SdFat.h> //SD card #include <SdFatUtil.h> //SD card tools #include <SFEMP3Shield.h> //shield library SFEMP3Shield MP3player; //player SdFat sd; //card const int pinButton = 5; const int nbTracks = 5; //CHANGE THIS VALUE TO THE NUMBER OF SONGS ON YOUR SD CARD const int volume = 6;//-3dB. The higher number, the lower volume int counter = 1; void setup() { //Serial.begin(9600); sd.begin(SD_SEL, SPI_HALF_SPEED); //start card pinMode(pinButton, INPUT); //setup of player MP3player.begin(); //start player MP3player.setDiffertialOutput(1); //higher output power MP3player.setVolume(volume, volume); } void loop(){ if (MP3player.isPlaying() && digitalRead(pinButton)){ //if playing, then a press of the button stops the music MP3player.stopTrack(); //Serial.println("music stopped"); delay(500); //to release button } else if(!MP3player.isPlaying() && digitalRead(pinButton)){ //if not playing, then a press of the button starts the music //first, increment counter counter += 1; if (counter > nbTracks) counter = 1; int errorCode; //used to debug errorCode = MP3player.playTrack(counter); //play /* Serial.print("playing track "); Serial.print(counter); Serial.print(" at "); Serial.print(-volume/2); Serial.println("dB"); Serial.print("error code (0 is OK): "); Serial.println(errorCode); */ delay(500); //to release button } } Step 6: Preparing the Enclosure Box - Bottom A business card box is used to store the Arduino and the MP3 shield. The size fits just right - only the space for the battery is a bit cramped - and I was able to procure a few of these boxes for free. Obviously, if you have access to another small plastic box, it would work the same. The task of this step is to drill holes in order to screw the boards in place. 1) Position the board against one end of the box and, looking from below, mark the position of the mounting holes (second picture) 2) Use a 3mm or 4mm drill. Wood drill bit ("Lip and Spur" drill bit, the experts call them) is ideal. Go very slowly, the plastic is easy to drill but may melt or break if you go too fast. 3) Not shown on this picture: drill an additional hole above the jack alimentation of the Arduino board. The wires coming from the on-off switch go through this hole. 4) Screw the boards in place Step 7: Preparing the Enclosure Box - Top Similarly, mark and drill holes in the top of the box, and insert the pushbutton and speaker wires through them. Solder the wires to the button connectors and to the speaker as well. Then, solder the Molex male connectors to these wires. The components will then be attached to the top of the box, you will have to un-solder them to take them out. You may drill larger holes, if you want to make a temporary assembly only. Step 8: Closing the Box First, connect all Molex connectors as well as the battery. Close the box carefully, making sure all wires fold wherever there is room for them. Wrap an elastic band around the box to hold it in place. Then, slide a plastic card (an unused fidelity card, or an unactivated credit card, for example) between the button and the elastic band. It will provide a larger area to press the button. The button should not be pressed all the time, obviously. Adjust the rubber band if it is the case, or add some stuffing from the toy between the credit card and the box, to remove some of the pressure. Step 9: Final Assembly Finally, insert the box into the Teddy Bear body. You may be able to push the speaker into the head. Add some stuffing in front of, on the sides of, and behind the box. Make sure the card has not slid. Then, switch ON the whole device, close the velcro straps, and give it to your baby. Enjoy the fun ! I think there is a mistake in your code here: Line 27 says : MP3player.setDiffertialOutput(1); //higher output power and it has to be MP3player.setDifferentialOutputOutput(1); //higher output power good catch, thanks Hi Donmatito, Great hacking you did there! I was looking for a project similar to the idea I have and I found yours! Although not exactly the same. Thanks to the instructions! May I use the photos in here for the presentation I will be doing? This is my first time ever to do these kind of things and the steps you have here is already a great help. Thanks in advance! Don't worry, I will give you all the credit you deserve! Keep it up! Hey, you're most welcome, especially if you attribute. Can you tell me a bit more about your project and the context where you want to show mine ? Hi donmatito, thanks for the reply! Project is for my EdX Delft online course. It is a "talking hanger" that gives clothing ensemble suggestions in accordance to outside temperature. (e.g. If it is -12 °C outside, the hanger would say: "it's freezing outside! You need a long sleeve shirt with your thermo pants..etc..etc..) It has a clock, weather station and in/outside temperature. I can imagine it will be complicated with the programming and not sure if it is doable, but it is a concept :-) For now, I will be needing a couple of your photos showing the assembled mechanics in that plastic box for my project presentation. Again, a million thanks! P.S. I would appreciate any input on my project. Thanks!:-) Hello, and thanks for your comments ! the current code is actuallly going through the list of songs each time you press the belly. cf step 5. Hello! This is such a brilliant idea, thank you for sharing! May I ask if you have any ideas on how to tweak the code such that multiple mp3 recordings can be played - a different one every time you press the button? What was your total cost for this build? 20-25€ for the arduino, about 30€ for the shield, 8€ for the speaker. Then, 9V batteries don't last long and cost 2-5€ depending on quality - I need to replace them by a stack of accumulators Hi I'm not entirely sure of what is your project but I understand your question refer to the pushbutton resistor. If it is correct, yes, I think you should have a resistor, otherwise you are creating a short-circuit when the button is pressed Ahhh!!!! Oh okay. Please post a video! this was awesome! thanks but I'm not sure I know how to I've been thinking about trying this. With this instructable how can I not? What a great idea. :D And don't hesitate to vote it up in the valentine's contest if you like it! Thanks jessy
http://www.instructables.com/id/Plush-toy-singing-with-Mommys-voice/?comments=all
CC-MAIN-2017-47
refinedweb
2,127
72.76
BizTalk server relies on a config file to store certain application information. This config file is located in \Program Files\Microsoft BizTalk Server 2004 and is named BTSNTSvc.Exe.Config. View your file here (DO NOT CHANGE THIS FILE WITHOUT BACKING UP!!!). Let's say that you have some .NET components that you want to consume from your BizTalk solution. Let's also assume that these components are possibly shared with another solution, and make use of a config file for things such as connection strings, directory locations, etc., a fairly common situation. Now, keep in mind when you call a component, and that component makes use of a config file, it uses the config file of the calling application (at least for EXE's). So, we have a couple of options. We can take what's in the shared components config file and paste it into the BTSNTSvc.Exe.Config file. But, this means we now have 2 places to maintain the information. What if we then have a multi server configuration, we now have 2 config files to maintain in more than one location. Not good. Wouldn't it be nice if we could somehow have the BizTalk config file "point" to the components config file? Then, we could maintain the other applications config file as we normally would. Well, the good news is you can.!!! Take a look at my sample config file to follow along. I'll explain a couple of the sections. It is important to remember to always take a copy of you current BTSNTSvc.Exe.Config file before making any changes as changing it incorrectly will prevent BizTalk from running. a new domain for your particular situation to run in. *** define this a little better. You will give your domain a name, and then you will use this name later to correlate the calling piece of your BizTalk solution with the called components config file. This section defines where the called components config file resides. You can use absolute paths, or I believe you can use relative paths also. In this section you are going to link your AppDomain (which contains the ConfigurationFile section) to the part of you BizTalk solution that calls the shared component. Let me clarify "part of your BizTalk solution". When you create your orchestrations, you give them a namespace. They probably run under the same namespace, or at least the same root namespace. So, in the example you see "Source.Test.Orchestrations.*" as the pattern assignment rule. What this is saying is that any orchestration that is under this namespace would be associated with that particular app domain, and would then be able to make use of the configuration file listed under that app domain. Hopefully with the example and the explanation, this will make some sense. There is some information in the help file about adding the new sections, but they don't go into much detail of how all the pieces fit together, and what the pattern assigment rule is really supposed to point to, etc. DON'T FORGET...BACK UP YOUR CURRENT CONFIG FILE BEFORE MAKING CHANGES. This will save a lot of headaches. One last point to remember...and I won't go into a lot of detail, but remember that if you are calling components from BizTalk, they must be GAC'd. It is possible that the shared components you are calling didn't require to be GAC'd prior to calling them from BizTalk. Now that they are in the GAC however, you will need to change your shared components config file slightly. When you are defining your section for that component, you will have to change the attributes a bit so that you are including the following - The values for component name, version, culture and token you can get out of .NET Framework Configuration admin tool. Just look for you component, and make note of the values listed. The only one that should change would be the version. Print posted @ Friday, October 08, 2004 3:41 PM Title: Name: Website: Comment: Be sure to check out the BizTalk 2006 Whitepapers from Microsoft.....
http://geekswithblogs.net/toddu/archive/2004/10/08/12381.aspx
crawl-002
refinedweb
691
64.51
SharePoint Calendar Lists not only offer standard “1:00-2:30 pm” type entries, but also entries that span multiple days, and all-day items, which have no set start or end time. Retrieving this data means learning something about CAML queries and SharePoint gotchas – and I hope this article saves you some time. The “sliding window” calendar web part shows data for 1- 7 contiguous days. The number of days displayed can be configured via the tool pane. If the web part is set to show 3 days, you’ll see today, tomorrow, and the day after that. For example, if today is Wednesday, you’ll see Wednesday-Thursday-Friday; on Thursday, the window “slides” to Thursday-Friday-Saturday. The goal is to display a lot of information in a small amount of space. To that end, only the title of each item is listed and hyperlinked - and when the mouse hovers over an item, a tooltip displays the start and end times, title, location, and description. using (SPWeb web = SPContext.Current.Site.OpenWeb(listCalendarUrl)) { SPList list = null; try { list = web.Lists[listCalendar]; } catch { } if (null == list) return; DateTime[] weeks; if (((int)StartDay + NumberOfDays) > 7) // the time span goes over the weekend weeks = new DateTime[] { StartDate, StartDate.AddDays(7) }; else weeks = new DateTime[] { StartDate }; If the sliding window spans the weekend, then we’ll need to look at two weeks’ worth of items, so we’ve stored our target days in the “weeks” array, and we’ll create as many queries as we need. weeks foreach (DateTime day in weeks) { // include recurring events by using a DateRangesOverlap query SPQuery queryRecurring = new SPQuery(); queryRecurring.ExpandRecurrence = true; queryRecurring.CalendarDate = day; queryRecurring.Query = "<Where><DateRangesOverlap>" + "<FieldRef Name=\"EventDate\" /><FieldRef Name=\"EndDate\" />" + "<FieldRef Name=\"RecurrenceID\" />" + "<Value Type=\"DateTime\"><Week />" + "</Value></DateRangesOverlap></Where>"; SPListItemCollection listItems; listItems = list.GetItems(queryRecurring); CAML – Collaborative Application Markup Language. CAML queries are used to retrieve SharePoint data. They look a bit like SQL queries expressed in XML, but in a prefix notation. For schema information on CAML queries, try: Query Schema, and for help with building queries, try: U2U CAML Query Builder and Execution Tool Released. Gotcha: In CAML queries, you must use the name of the column, not the display name, and the real name can be hard to find, especially, if you renamed any columns. To find column names for any SharePoint list, open the list, edit the list settings, and scroll down until you find the list of columns. Click on a column name to view its properties: In the textbox at the right, the column name is “Start Time” - but that is the display name. The real column name is at the end of the URL(!). Look at the rightmost bit of the address bar to see “Field=EventDate”; and “EventDate” is the name we want. EventDate Back to the CAML query. Recurring events … recur. For example, a seminar that occurs every week for 10 weeks, from 2 – 3 pm on Thursdays. These list items are created at runtime, not stored in the database (like an ordinary event), and a standard query will not return them. The DateRangesOverlap element must be used to find recurring events; it will return everything for the specified interval. DateRangesOverlap In this example, we’re choosing to look at one week at a time. Let’s take another look at that CAML query in an easier-to-read format: In the FieldRef elements of the query (which use the real column name), EventDate is the start date, EndDate the end date, and RecurranceID is not only the ID you’ll need for the hyperlink, but contains the start day and the time of the recurring event. An example of a RecurranceID for a recurring event: “4.0.2008-05-27T17:00:00Z”. In contrast, an example of a RecurranceID for an ordinary event: “7”. FieldRef EndDate RecurranceID A couple of attributes need to be set on the query also: queryRecurring.ExpandRecurrence = true; queryRecurring.CalendarDate = day; Set ExpandRecurrence to true so the recurring values get created. The CalendarDate property sets the actual date, which, combined with the CAML query’s “Week” value, will cause the query to grab all the entries in the week containing the “CalendarDate”. ExpandRecurrence true CalendarDate Week Now that we have the item collection, we need to figure out if each item is an all-day, multi-day, or ordinary item; check if the item’s start date is in our date range, and if so, add it to our sorted list, calendarCells. calendarCells If it is a multi-day item, there will be only one occurrence, and we’ll need to add the other days manually; but, there may be one each week if the time span bridges the weekend. This raises the possibility of accidentally adding the same items twice, so we’ll save the uniqueId property in the Hashtable, processedListItems, so we can screen for already-added items. Each “cell” in the sorted list, calendarCells, will be 1 hour of a day. uniqueId Hashtable processedListItems bool multiday; bool allday; foreach (SPListItem item in listItems) { DateTime itemStartDate = (DateTime)item["EventDate"]; DateTime itemEndDate = (DateTime)item["EndDate"]; multiday = (itemEndDate - itemStartDate > new TimeSpan(1, 0, 0, 0)) ? true : false; allday = (itemEndDate - itemStartDate == new TimeSpan(23, 59, 0)) ? true : false; if (multiday) // is the calendar start day within // the Multi-Day span? if so, reset itemStartDay if (day >= itemStartDate && day <= itemEndDate) itemStartDate = day; if (!ItemIsInDateRange(itemStartDate, day, weeks)) continue; // Create key for assigning to gridrows. // Example: key for Thursday 8 am would be 08-4; // key for Monday 3 pm would be 15-1 // Example: key for an All Day item on Friday would be ..-5 // Example: keys for a Multi-Day item spanning // Thursday-Friday-Saturday: ..-4 ..-5 ..-6 string key = string.Empty; if (multiday || allday) key = AllDayHour + "-" + ((int)itemStartDate.DayOfWeek).ToString(); else { key = itemStartDate.TimeOfDay.Hours.ToString() + "-" + ((int)itemStartDate.DayOfWeek).ToString(); if (key.Length < 4) key = "0" + key; } string titleText = string.Empty; if (multiday || allday) titleText = item["Title"].ToString(); else titleText = itemStartDate.ToShortTimeString() + " " + item["Title"].ToString(); string linkUrl = web.Url + "/" + item.Url.ToString().Substring(0, item.Url.LastIndexOf("/") + 1) + "DispForm.aspx?ID=" + item.RecurrenceID.ToString(); // Example for javascript tooltips: //string titleLink = "<a href=" + Quote(linkUrl) // + " onmouseover=\"Tip('" + tip(item, multiday || allday) + // "')\" onmouseout=\"UnTip()\" >" + // titleText + "</a>"; string titleLink = "<a href=" + Quote(linkUrl) + " title=" + Quote(tip(item, multiday || allday)) + " >" + titleText + "</a>"; string UniqueID = item.UniqueID + item.RecurrenceID; if (!processedListItems.Contains(UniqueID)) { AddCell(key, titleLink); if (multiday) { // Multi-Day events appear as one list item; add remaining days DateTime thisEndDate = (StartDate.AddDays(NumberOfDays) < itemEndDate) ? StartDate.AddDays(NumberOfDays) : itemEndDate; for (DateTime nextDay = itemStartDate.AddDays(1); nextDay <= thisEndDate; nextDay = nextDay.AddDays(1)) { if (ItemIsInDateRange(nextDay)) { key = AllDayHour + "-" + ((int)nextDay.DayOfWeek).ToString(); AddCell(key, titleLink); } } } processedListItems.Add(UniqueID, null); } } // foreach ListItem } // foreach day in weeks } // using SPWeb web ... } You’ll notice that tooltips (or screentips) here are handled by assigning them to the title attribute of the <a>tags, and there are commented-out lines nearby assigning JavaScript functions to the onmouseover and onmouseout events. If you prefer to use JavaScript tooltips, just un-comment these lines, and also the script-registering code in the OnLoad method, and a few lines in the tip method. (Don’t forget to upload the JavaScript file to the web server.) With JavaScript tooltips, you can include images, links, etc., in the tooltips. title <a> onmouseover onmouseout OnLoad tip Once the sorted list is built, we’re ready to build a DataTable, add matching columns to a GridView, and set the GridView’s DataSource to the table. A naming convention is used to tie the DataTable columns to the GridView columns. The Gridview columns are template fields, so HTML can be used. DataTable GridView DataSource Gridview One of the challenges of web part design is that there is no design surface, so you really can’t “see” what you’re doing. I found it very helpful to preview the GridView in a separate project -a sort of workbench- where I could just throw things on a design surface, set properties, play with the code, and spin it up fast. Note: WebPart deployment is not covered here; for an introduction, see: Write Custom WebParts for SharePoint 2007. Another note: You’ll probably need to refresh the project reference to the Sharepoint.dll, typically found here – C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI\Microsoft.SharePoint.dll. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) private string calendarName = string.Empty; [WebBrowsable(true), Personalizable(), WebPartStorage(Storage.Personal), FriendlyName("Name of calendar"), // caption display in property pane WebDescription("Enter the name of the calendar to be displayed. Example: LR1 Calendar"), // tool tip Category("Custom")] public string CalendarName { get { object o = ViewState["CalendarName"]; if (o != null) return (string)o; else return calendarName; } set { calendarName = value; } } private string calendarUrl = string.Empty; [WebBrowsable(true), Personalizable(), WebPartStorage(Storage.Personal), FriendlyName("Relative URL for calendar"), // caption display in property pane WebDescription("Enter the url relative to the website root. Example: /ca/mbae/lr1/ "), // tool tip Category("Custom")] public string CalendarUrl { get { object o = ViewState["CalendarUrl"]; if (o != null) return (string)o; else return calendarUrl; } set { calendarUrl = value; } } private bool ItemIsInDateRange(DateTime itemDate) { DateTime StartDateMidnight = new DateTime(StartDate.Year, StartDate.Month, StartDate.Day, 0, 0, 0); DateTime EndDate = StartDateMidnight.AddDays(NumberOfDays).AddMinutes(-1); if (itemDate >= StartDateMidnight && itemDate <= EndDate) { return true; } else { return false; } } General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
https://www.codeproject.com/Articles/26472/SharePoint-Sliding-Window-Calendar-Web-Part?msg=2575509
CC-MAIN-2017-22
refinedweb
1,601
55.34
import {ZoneIdFactory} from 'js-joda/src/ZoneIdFactory.js' ZoneIdFactory Static Method Summary Static Public Methods public static from(temporal: TemporalAccessor): ZoneId source Obtains an instance of ZoneId from a temporal object. in queries via method reference, ZoneId::from. Params: Return: Throw: public static getAvailableZoneIds(): string[] source Gets the set of available zone IDs. This set includes the string form of all available region-based IDs. Offset-based zone IDs are not included in the returned set. The ID can be passed to of to create a ZoneId. The set of zone IDs can increase over time, although in a typical application the set of IDs is fixed. Each call to this method is thread-safe. Return: public static of(zoneId: string): ZoneId source Obtains an instance of ZoneId from. - If the zone ID equals 'Z', the result is ZoneOffset.UTC. - If the zone ID consists of a single letter, the zone ID is invalid and DateTimeException is thrown. - If the zone ID starts with '+' or '-', the ID is parsed as a ZoneOffset using ZoneOffset#of. - If the zone ID equals 'GMT', 'UTC' or 'UT' then the result is a ZoneId with with the specified UTC/GMT/UT prefix and the normalized offset ID as per ZoneOffset#getId. The rules of the returned ZoneId will be equivalent to the parsed ZoneOffset. - All other IDs are parsed as region-based zone IDs. Region IDs must match the regular expression [A-Za-z][A-Za-z0-9~/._+-]+, otherwise a DateTimeException is thrown. If the zone ID is not in the configured set of IDs, ZoneRulesException java.util.TimeZone. Params: Return: Throw: public static ofOffset(prefix: string, offset: ZoneOffset): ZoneId source Obtains an instance of ZoneId wrapping an offset. If the prefix is 'GMT', 'UTC', or 'UT' a ZoneId with the prefix and the non-zero offset is returned. If the prefix is empty '' the ZoneOffset is returned.
https://doc.esdoc.org/github.com/js-joda/js-joda/class/src/ZoneIdFactory.js~ZoneIdFactory.html
CC-MAIN-2021-21
refinedweb
315
58.18
Code Inspection: Field can be made readonly (Private Accessibility) Say you have decided to make an immutable Person class, initialized only via the constructor. You go ahead and implement the following: public class Person { private string name; private int age; public Person(string name, int age) { this.name = name; this.age = age; } public override string ToString() { return string.Format("Name: {0}, Age: {1}", name, age); } } ReSharper can detect that private name and age fields are only being assigned in the constructor and offers to create an additional safeguard – by marking them readonly, we get to ensure that this class will not inadvertently assign these fields anywhere within its methods. See Also Last modified: 15 December 2016
https://www.jetbrains.com/help/resharper/2016.2/FieldCanBeMadeReadOnly.Local.html
CC-MAIN-2018-26
refinedweb
116
52.7
CodePlexProject Hosting for Open Source Software Hi, I am using Composite and found it quite useful for what I need. The forum has been of great help in solving the most of my queries but I cannot figure this one out. I have installed the Composite.News package and managed to create different news articles. The News Article and News Latest functions were displaying well, but when I try to access the news feed by clicking on the link, the following error is given: HttpException unhandled by useer code : "The incoming request does not match any route." public class MvcHttpHandlerWrapper : MvcHttpHandler { public void ProcessRequest(HttpContextBase httpContext) { base.ProcessRequest(httpContext); //error given here } } One of the packages installed is the Composite.AspNet.MvcPlayer which is also appearing on the webpage and I started the website using the Omnicorp sample website. Am I missing something? Thanks. Update: I restarted the whole website without installing the MVC Plugin and used the Empty version of the CMS instead. The News articles are working fine and dandy. I did try to uninstall the MVC plugin in the old installation but error still persisted as it was conflicting with the Omnicorp News package. Hello, Composite.AspNet.MvcPlayer uses PathInfo to determine corresponding route and Composite.News uses PathInfo to show News details, so you can not use these two functions on the same page as when you will try to view some News details and your URL will be like this , the MVC player will try to find corresponding route by this path "2011/09/08/MyNews" and error will occur "The incoming request does not match any route." Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
http://c1cms.codeplex.com/discussions/271528
CC-MAIN-2017-51
refinedweb
309
63.19
Bart De Smet's on-line blog (0x2B | ~0x2B, that's the question) Today (11/29/06) I received a mail from one of my blog readers: Hi Bart, in the following Block you mention an powershell commandlet for creating an SHA hash: Could you please publish or mail me some code snipes? My own code wont work proper. THX for sharing so much knowledge about .NET. Regards, Thomas Apparently I promised so time in the past to upload a cmdlet for file hashing but it never made it to my blog. So here it is today. Let's create a cmdlet for file hashing, called get-hash. It should take two parameters: one with the algorithm desired (SHA1, MD5, SHA256, SHA384, SHA512) and one with the file. The latter one can either be passed from the command line (e.g. dir *.cs | get-hash sha1 should work fine) or using some aliases specifying the name of the file as a string. Taking all these requirements together, we end up with the following: 1 using System; 2 using System.ComponentModel; 3 using System.IO; 4 using System.Management.Automation; 5 using System.Security.Cryptography; 6 using System.Text; 7 8 [Cmdlet("get", "hash")] 9 public class HashCmdlet : PSCmdlet 10 { 11 private string algorithm; 12 13 [Parameter(Position = 0, Mandatory = true)] 14 public string Algorithm 15 { 16 get { return algorithm; } 17 set { algorithm = value; } 18 } 19 20 private string file; 21 22 [Alias("File", "Name")] 23 [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true)] 24 public string FullName 25 { 26 get { return file; } 27 set { file = value; } 28 } 29 30 protected override void ProcessRecord() 31 { 32 HashAlgorithm algo = HashAlgorithm.Create(algorithm); 33 if (algo != null) 34 { 35 StringBuilder sb = new StringBuilder(); 36 using (FileStream fs = new FileStream(file, FileMode.Open)) 37 foreach(byte b in algo.ComputeHash(fs)) 38 sb.Append(b.ToString("x2")); 39 WriteObject(sb.ToString()); 40 } 41 else 42 { 43 string s = String.Format("Algorithm {0} not found.", algorithm); 44 ErrorRecord err = new ErrorRecord(new ArgumentException(s), s, ErrorCategory.InvalidArgument, null); 45 WriteError(err); 46 } 47 } 48 } 49 50 [RunInstaller(true)] 51 public class HashSnapin : PSSnapIn 52 { 53 public override string Name { get { return "FileHasher"; } } 54 public override string Vendor { get { return "Bart"; } } 55 public override string Description { get { return "Computes file hashes."; } } 56 } A few remarks: Download the code and execute the following steps on a VS2005 command line: Below you can see a sample of our get-hash cmdlet: 1 PS C:\temp> add-pssnapin filehasher 2 3 PS C:\temp> type extfi.ps1xml 4 <Types> 5 <Type> 6 <Name>System.IO.FileInfo</Name> 7 <Members> 8 <ScriptProperty> 9 <Name>MD5</Name> 10 <GetScriptBlock> 11 get-hash md5 $this 12 </GetScriptBlock> 13 </ScriptProperty> 14 <ScriptProperty> 15 <Name>SHA1</Name> 16 <GetScriptBlock> 17 get-hash sha1 $this 18 </GetScriptBlock> 19 </ScriptProperty> 20 </Members> 21 </Type> 22 </Types> 23 24 PS C:\temp> update-typedata extfi.ps1xml 25 26 PS C:\temp> dir *.cs | gm -type P* 27 28 TypeName: System.IO.FileInfo 29 30 Name MemberType Definition 31 ---- ---------- ---------- 32 PSChildName NoteProperty System.String PSChildName=bar.cs 33 PSDrive NoteProperty System.Management.Automation.PSDriveInfo PS... 34 PSIsContainer NoteProperty System.Boolean PSIsContainer=False 35 PSParentPath NoteProperty System.String PSParentPath=Microsoft.PowerS... 36 PSPath NoteProperty System.String PSPath=Microsoft.PowerShell.C... 37 PSProvider NoteProperty System.Management.Automation.ProviderInfo P... 38 Attributes Property System.IO.FileAttributes Attributes {get;set;} 39 CreationTime Property System.DateTime CreationTime {get;set;} 40 CreationTimeUtc Property System.DateTime CreationTimeUtc {get;set;} 41 Directory Property System.IO.DirectoryInfo Directory {get;} 42 DirectoryName Property System.String DirectoryName {get;} 43 Exists Property System.Boolean Exists {get;} 44 Extension Property System.String Extension {get;} 45 FullName Property System.String FullName {get;} 46 IsReadOnly Property System.Boolean IsReadOnly {get;set;} 47 LastAccessTime Property System.DateTime LastAccessTime {get;set;} 48 LastAccessTimeUtc Property System.DateTime LastAccessTimeUtc {get;set;} 49 LastWriteTime Property System.DateTime LastWriteTime {get;set;} 50 LastWriteTimeUtc Property System.DateTime LastWriteTimeUtc {get;set;} 51 Length Property System.Int64 Length {get;} 52 Name Property System.String Name {get;} 53 MD5 ScriptProperty System.Object MD5 {get=get-hash md5 $this;} 54 Mode ScriptProperty System.Object Mode {get=$catr = "";... 55 SHA1 ScriptProperty System.Object SHA1 {get=get-hash sha1 $this;} 56 57 PS C:\temp> dir *.cs | format-table Name,MD5,SHA1 58 59 Name MD5 SHA1 60 ---- --- ---- 61 bar.cs d541e9719077844ba1fa136... 8662e86f3302578a59da5e... 62 downloadfilecmdlet.cs 0c74a0c905f3b1cd6e22d52... ab3c4dcee4f9e3c48daded... 63 hashcmdlet.cs 41b01139d6168df3f3cec13... dd478c60f77b19b64fa0d7... 64 test.cs 477405d2be4a8f327d39a01... c632fe67a71baa0f333675... 65 66 PS C:\temp> dir *.cs | format-list Name,MD5,SHA1 67 68 Name : bar.cs 69 MD5 : d541e9719077844ba1fa13626f5122cb 70 SHA1 : 8662e86f3302578a59da5e9c936b69ab0d4ff9aa 71 72 Name : downloadfilecmdlet.cs 73 MD5 : 0c74a0c905f3b1cd6e22d52831b92b31 74 SHA1 : ab3c4dcee4f9e3c48daded97f01ee01e8c572a2a 75 76 Name : hashcmdlet.cs 77 MD5 : 41b01139d6168df3f3cec13b9663e633 78 SHA1 : dd478c60f77b19b64fa0d7c62944ec1b948419c9 79 80 Name : test.cs 81 MD5 : 477405d2be4a8f327d39a015db255fdf 82 SHA1 : c632fe67a71baa0f333675f5cdc16fc547772c33 83 84 PS C:\temp> get-hash MD5 bar.cs 85 d541e9719077844ba1fa13626f5122cb 86 87 PS C:\temp> get-hash SHA1 bar.cs 88 8662e86f3302578a59da5e9c936b69ab0d4ff9aa 89 90 PS C:\temp> get-hash SHA256 bar.cs 91 a1e6764cf77d02804e909427aff62ade6b9894924a69284f3d83fd0d2904548b 92 93 PS C:\temp> get-hash SHA384 bar.cs 94 875bde9e789f88e76aa9fe18f82adc8a8beb920cdf1d50692a0b9473ecc296a750e888844a184d7 95 6e610d434a3bec3a5 96 97 PS C:\temp> get-hash SHA512 bar.cs 98 f88b40bd4618dcb99e17af14c7f2368b00ea55a9b7d6d71e73d519e197ca3d6c3847fd46834fb1e 99 c4acb9c45729441ac76611de2f7f86b032b59e1a3b7384a3a 100 101 PS C:\temp> get-hash bla bar.cs 102 get-hash : Algorithm bla not found. 103 At line:1 char:9 104 + get-hash <<<< bla bar.cs This sample is available in the download as well. Let's explain it in a bit more detail: One drawback of our cmdlet is that it can't report progress when a hash operation takes a bit of time, especially for larger files. So, use it with care and rely on an explicit call to get-hash when you need to calculate a hash.! Only a couple of days ago I posted about creating a file downloader cmdlet in Windows PowerShell which contained the following little sentence: One could make this method more complex in order to provide a seconds remaining estimate based on the download speed observed. One of my readers (dotnetjunkie) was so kind to leave a piece of feedback: I think you should add transfer speed and estimated remaining time, that would make it even more useful and cooler ! ;) Well, I couldn't agree more. So I revisited my piece of code I wrote some weeks ago (12th of November to be precise) and added download speed tracking and a seconds remaining indicator. There are undoubtly different ways to implement such an estimate. My approach is to measure the number of bytes transferred during intervals of approximately 5 seconds (kind of "instant download speed") and to derive the estimated time remaining from this. I'll discuss the code changes in a few steps. We need 4 additional members to produce statistics: Here's the piece of code: /// <summary> /// Stopwatch used to measure download speed. /// </summary> private Stopwatch sw = new Stopwatch(); /// <summary> /// Bytes per second indicator (bytes/sec, KB/sec, MB/sec, ...). /// </summary> private string bps = null; /// <summary> /// Seconds remaining indicator. /// </summary> private int secondsRemaining = -1; /// <summary> /// Number of bytes already transferred. /// </summary> private long transferred = 0; In the ProcessRecord method we start our Stopwatch; just that: // // Check validity for download. Will throw an exception in case of transport protocol errors. // using (clnt.OpenRead(_url)) { } // // Start download speed stopwatch. // sw.Start(); // // Download the file asynchronously. Reporting will happen through events on background threads. // clnt.DownloadFileAsync(_url, _file); Time for the real stuff. On to the DownloadProgressChanged event handler. When we observe that the Stopwatch has an elapsed time of 5 or more seconds, we'll stop it, update stats and restart it. The code is shown below: 1 /// <summary> 2 /// Reports download progress. 3 /// </summary> 4 private void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) 5 { 6 // 7 // Update statistics every 5 seconds (approx). 8 // 9 if (sw.Elapsed >= TimeSpan.FromSeconds(5)) 10 { 11 sw.Stop(); 12 13 // 14 // Calculcate transfer speed. 15 // 16 long bytes = e.BytesReceived - transferred; 17 double bps = bytes * 1000.0 / sw.Elapsed.TotalMilliseconds; 18 this.bps = BpsToString(bps); 19 20 // 21 // Estimated seconds remaining based on the current transfer speed. 22 // 23 secondsRemaining = (int)((e.TotalBytesToReceive - e.BytesReceived) / bps); 24 25 // 26 // Restart stopwatch for next 5 seconds. 27 // 28 transferred = e.BytesReceived; 29 sw.Reset(); 30 sw.Start(); 31 } 32 33 // 34 // Construct a ProgressRecord with download state information but no completion time estimate (SecondsRemaining < 0). 35 // 36 ProgressRecord pr = new ProgressRecord(0, String.Format("Downloading {0}", _url.ToString(), _file), String.Format("{0} of {1} bytes transferred{2}.", e.BytesReceived, e.TotalBytesToReceive, this.bps != null ? String.Format(" (@ {0})", this.bps) : "")); 37 pr.CurrentOperation = String.Format("Destination file: {0}", _file); 38 pr.SecondsRemaining = secondsRemaining - (int)sw.Elapsed.Seconds; 39 pr.PercentComplete = e.ProgressPercentage; 40 41 // 42 // Report availability of a ProgressRecord item. Will cause the while-loop's body in ProgressRecord to execute. 43 // 44 lock (pr_sync) 45 { 46 this.pr = pr; 47 prog.Set(); 48 } 49 } So, what's going on here. Basically we want to provide a seconds remaining estimate on line 38 and a download speed estimate on line 36. This should be pretty self-explanatory. The real work happens in lines 11 to 30 where the number of bytes transferred in the last 5 seconds are obtained and divided by the expired milliseconds during the last 5 seconds (which should be around 5000 obviously). The rest is maths, except for the BpsToString call as shown below. BpsToString is the method to convert the bytes per second rate to a friendly string representation: /// <summary> /// Constructs a download speed indicator string. /// </summary> /// <param name="bps">Bytes per second transfer rate.</param> /// <returns>String represenation of the transfer rate in bytes/sec, KB/sec, MB/sec, etc.</returns> private string BpsToString(double bps) { string[] m = new string[] { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" }; //dreaming of YB/sec int i = 0; while (bps >= 0.9 * 1024) { bps /= 1024; i++; } return String.Format("{0:0.00} {1}/sec", bps, m[i]); } I think the code fragment above is pretty optimistic for what transfer speeds is concerned, but with the expected life time of PowerShell in mind this should be no luxury :-). This is the result (needless to say the figures are indicative only, it are estimates after all): And here's the code download link. A few days ago, I posted this little quiz on batch scripting mysteries. The batch script given was: @echo off for %%f in (a,b,c) do ( echo 1 %%f 2 set x=x1 %%f x2 echo %x% ) Here's the output: C:\temp>test1 a 2ECHO is off.1 b 2ECHO is off.1 c 2ECHO is off. C:\temp>test1 a 2x1 c x21 b 2x1 c x21 c 2x1 c x2 Not what you might have expected :-). I did some research but HELP SET didn't give the complete answer, so a workaround seems a good solution: @echo off for %%f in (a,b,c) do ( echo 1 %%f 2 call :print %%f ) goto eof :print set x=x1 %1 x2 echo %x% :eof And of course Windows PowerShell helps us out too: PS C:\Users\Bart> ('a','b','c') | foreach { echo "1 $_ 2"; $x = "x1 $_ x2"; echo $x } 1 a 2 x1 a x2 1 b 2 x1 b x2 1 c 2 x1 c x2 Yet another reason to choose Windows PowerShell? (Notice the variable expansion in strings too.) In my previous post on file downloads in PowerShell I mentioned how to download a file in Windows PowerShell using System.Net.WebClient. No big deal if you know the Base Class Libraries. However, there was a drawback: the lacking download status reporting. In order to fix this, I've created a simple sample cmdlet that uses reporting (WriteProgress) while performing a download. Enter download-file. The basic idea is pretty simple: We'll call our cmdlet download-file, so the declaration will be like this: [Cmdlet("download", "file")] public class DownloadFileCmdlet : PSCmdlet { } Parameterization of a cmdlet is piece of cake as explained in a bunch of previous posts already, and will look like this: /// <summary> /// Url of the file that has to be downloaded. /// </summary> [Parameter(Mandatory = true, Position = 0)] public Uri Url { get { return _url; } set { _url = value; } } private string _file; /// <summary> /// Target file name (optional). /// </summary> [Parameter(Position = 1)] public string To { get { return _file; } set { _file = value; } } Next, we'll have to define the ProcessRecord overload of the cmdlet to do the processing. This is where things get tricky because of the following reasons: The solution to all of the problems above is some nice piece of thread synchronization. Basically the "main thread" (the one where ProcessRecord was called on) has to create the WebClient, hook in event handlers and start the asynchronous download job. Once that's done, it has to wait for any of two events to occur: either a ProgressRecord instance is available or DownloadFileCompleted has executed. In the first case, we can perform a WriteProgress to report progress on the right thread. In the second case, we can exit the ProcessRecord method because of download completion. Here's the complete code: 1 using System; 2 using System.ComponentModel; 3 using System.IO; 4 using System.Management.Automation; 5 using System.Net; 6 using System.Threading; 7 8 [Cmdlet("download", "file")] 9 public class DownloadFileCmdlet : PSCmdlet 10 { 11 /// <summary> 12 /// Wait handle to report download completion. 13 /// </summary> 14 private ManualResetEvent exit = new ManualResetEvent(false); 15 16 /// <summary> 17 /// Wait handle to report availability of a ProgressRecord item in pr. 18 /// </summary> 19 private AutoResetEvent prog = new AutoResetEvent(false); 20 21 /// <summary> 22 /// Array of the wait handles above (set in ProcessRecord) to perform WaitAny. 23 /// </summary> 24 private WaitHandle[] evts; 25 26 /// <summary> 27 /// ProgressRecord indicating the current download status. 28 /// </summary> 29 private ProgressRecord pr; 30 31 /// <summary> 32 /// Synchronization object for pr. 33 /// </summary> 34 private object pr_sync = new object(); 35 36 private Uri _url; 37 38 /// <summary> 39 /// Url of the file that has to be downloaded. 40 /// </summary> 41 [Parameter(Mandatory = true, Position = 0)] 42 public Uri Url 43 { 44 get { return _url; } 45 set { _url = value; } 46 } 47 48 private string _file; 49 50 /// <summary> 51 /// Target file name (optional). 52 /// </summary> 53 [Parameter(Position = 1)] 54 public string To 55 { 56 get { return _file; } 57 set { _file = value; } 58 } 59 60 /// <summary> 61 /// Entry-point for the cmdlet processing. 62 /// </summary> 63 protected override void ProcessRecord() 64 { 65 // 66 // Construct wait handles array for WaitHandle.WaitAny calls. 67 // 68 evts = new WaitHandle[] { exit, prog }; 69 70 // 71 // If no target file name was specified, derive it from the url's file name portion. 72 // 73 if (_file == null) 74 { 75 string[] fs = _url.LocalPath.Split('/'); 76 if (fs.Length > 0) 77 _file = fs[fs.Length - 1]; 78 } 79 80 // 81 // Construct web client object and hook in event handlers to report progress and completion. 82 // 83 WebClient clnt = new WebClient(); 84 clnt.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged); 85 clnt.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted); 86 87 try 88 { 89 // 90 // Check validity for download. Will throw an exception in case of transport protocol errors. 91 // 92 using (clnt.OpenRead(_url)) { } 93 94 // 95 // Download the file asynchronously. Reporting will happen through events on background threads. 96 // 97 clnt.DownloadFileAsync(_url, _file); 98 99 // 100 // Wait for any of the events (exit, prog) to occur. 101 // In case of index 0 (= exit), stop processing. 102 // In case of index 1 (= prog), report progress. 103 // 104 while (WaitHandle.WaitAny(evts) != 0) //0 is exit event 105 { 106 lock (pr_sync) 107 { 108 WriteProgress(pr); 109 } 110 } 111 112 // 113 // Write file info object for the target file. Can be used for further processing on the pipeline. 114 // 115 WriteObject(new FileInfo(_file)); 116 } 117 catch (WebException ex) 118 { 119 // 120 // Report an error. Could be more specific for what the ErrorCategory is concerned, by mapping HTTP error codes. 121 // 122 WriteError(new ErrorRecord(ex, ex.Status.ToString(), ErrorCategory.NotSpecified, clnt)); 123 } 124 } 125 126 /// <summary> 127 /// Reports download progress. 128 /// </summary> 129 private void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) 130 { 131 // 132 // Construct a ProgressRecord with download state information but no completion time estimate (SecondsRemaining < 0). 133 // 134 ProgressRecord pr = new ProgressRecord(0, String.Format("Downloading {0}", _url.ToString(), _file), String.Format("{0} of {1} bytes transferred.", e.BytesReceived, e.TotalBytesToReceive)); 135 pr.CurrentOperation = String.Format("Destination file: {0}", _file); 136 pr.SecondsRemaining = -1; 137 pr.PercentComplete = e.ProgressPercentage; 138 139 // 140 // Report availability of a ProgressRecord item. Will cause the while-loop's body in ProgressRecord to execute. 141 // 142 lock (pr_sync) 143 { 144 this.pr = pr; 145 prog.Set(); 146 } 147 } 148 149 /// <summary> 150 /// Reports download completion. 151 /// </summary> 152 private void webClient_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) 153 { 154 // 155 // Signal the exit state. Will cause the while-loop in ProcessRecord to terminate. 156 // 157 exit.Set(); 158 } 159 } 160 161 [RunInstaller(true)] 162 public class DownloadFileSnapIn : PSSnapIn 163 { 164 public override string Name { get { return "DownloadFile"; } } 165 public override string Vendor { get { return "Bart De Smet"; } } 166 public override string Description { get { return "Allows file download."; } } 167 } Starting at the bottom of the cmdlet definition we can see the two event handlers, webClient_DownloadProgressChanged and webClient_DownloadFileCompleted. The first one creates a ProgressRecord (lines 134-137) which is the way for a cmdlet to communicate status to the PowerShell host application. The parameters and properties are self-explanatory. One could make this method more complex in order to provide a seconds remaining estimate based on the download speed observed. In this basic sample we're happy with some status messages and a percentage. In order to report progress, some thread synchronization stuff is needed. Remember the WriteProgress method can only be called on the ProcessRecord's thread. So, we copy (line 144) the constructed ProgressRecord to the pr member of the class (line 29) which is synchronized by pr_sync (line 34, used in line 142). Finally the availability of the record is signaled using the wait handle prog in line 145. Notice it's an AutoResetEvent (line 19), which means that it gets reset automatically (to false) once the consuming thread (ProcessRecord) has sucked it (in WaitAny in our case, line 104). The webClient_DownloadFileCompleted event handler is straightforward an just signals the exit "download completion" state on line 157 that will be caught on line 104's WaitAny. Real work happens in ProcessRecord of course. First (line 68) an array of wait handles gets constructed to be used in the WaitAny call (line 104). WaitAny means to wait till either one of these handles has been set. For example: if a progress record is available, prog will be set (by webClient_DownloadProgressChanges on line 145) and WaitAny will return 1 because prog is on index 1 in the evts handles array. In a similar way, WaitAny will return 0 if the 0'th element of evts, i.e. exit, has been set (by webClient_DownloadFileCompleted on line 157). Next, the case of no specified target file is taken care of in lines 73 to 78, taking the source file name as the target name. Now (lines 83-85) the WebClient instance is created and the event handlers are hooked in. Finally, the download progress can be started. In order to cause an exception - for example in case of a 404 error code - before download begins, we call OpenRead on line 92. The asynchronous download job is started on line 97. The summum of our code is in lines 104-110, where ProgressRecord instances are consumed every time the prog wait handle is set. These are reported to the PowerShell host by means of a WriteProgress call (line 108), taking care of the required locking. Finally, in line 115, a FileInfo object for the target file is written on the pipeline which might be useful for further processing. WebExceptions are caught on line 117 and reported via WriteError on line 122. The snap-in for the cmdlet goes without further explanation, see lines 161 to 167. Compiling this goes as follows: See the pictures below for the cmdlet in action (H): Download the code over here. Have fun! From the code fragment below non-Dutch speaking readers can already predict what I'm building for the moment. For the Dutch folks, there's something funny in the translated C# compiler errors: downloadfilecmdlet.cs(38,10): error CS1502: De beste treffer voor de overbelaste methode voor System.Management.Automation.Cmdlet.WriteError(System.Management.Automation.ErrorRecord) heeft enkele ongeldige argumenten (I'm currently working on a machine which has the Dutch .NET Framework 2.0 installed with now developer tools, and so I'm doing some command-line compiles.) This reminds me of the "lower case" translation into "onderkast" (see a pretty old post on that one). Time for a little PowerShell tip for my IT Pro friends. I know it's just BCL (Base Class Library) stuff, but nevertheless you might find it useful: what about downloading a file from an HTTP server during script execution? Here it is: PS C:\temp> $clnt = new-object System.Net.WebClientPS C:\temp> $clnt | gm d* TypeName: System.Net.WebClient Name MemberType Definition---- ---------- ----------Dispose Method System.Void Dispose()DownloadData Method System.Byte[] DownloadData(String address), S...DownloadDataAsync Method System.Void DownloadDataAsync(Uri address), S...DownloadFile Method System.Void DownloadFile(String address, Stri...DownloadFileAsync Method System.Void DownloadFileAsync(Uri address, St...DownloadString Method System.String DownloadString(String address),...DownloadStringAsync Method System.Void DownloadStringAsync(Uri address),... PS C:\temp> $url = ""PS C:\temp> $file = "c:\temp\ps.txt"PS C:\temp> $clnt.DownloadFile($url,$file)PS C:\temp> type $fileWelcome to Windows PowerShell 1.0! Drawback to this approach: no download reporting (as with write-progress) while downloading a large file. Solution: coming up later. Enjoy! Time to pre-empt some other posts for a great Channel 9 video with Anders Hejlsberg and Chris McConnell on LINQ, Desktop Search, WinFS, Functional and Intentional Programming. Interesting view and stuff to think about. Watch it here. In the previous posts on DynCalc, we explored how to write a simple parser for simple calculations, transforming it from infix to postfix and finally to a tree that can be interpreted or compiled for execution of the calculation. In a short summary, we did the following: As of C# 3.0, there's library support for expression trees and compilation of these. In this post, we'll transform our DynCalc sample into an equivalent application using C# 3.0 Expression Trees. As illustrated in Part 2: Building an expression tree we take a queue of MathOpOrVal tokens (representing either a mathematical operation or an integer value) and turn it into an expression tree as follows: static TreeNode ToTree(Queue<MathOpOrVal> q) { Stack<TreeNode> stack = new Stack<TreeNode>(); foreach (MathOpOrVal mv in q) { if (mv.Value != null) stack.Push(new TreeNode(mv.Value.Value)); else { TreeNode right = stack.Pop(); TreeNode left = stack.Pop(); stack.Push(new TreeNode(mv.Op.Value, left, right)); } } return stack.Pop(); } In here, the TreeNode was an internal class to represent a tree node consisting of an operation together with a left and right node. All of this can be replaced by the C# 3.0 Expression Trees, as follows: 1 static Expression<Func<int>> ToTree2(Queue<MathOpOrVal> q) 2 { 3 Stack<Expression> stack = new Stack<Expression>(); 4 5 foreach (MathOpOrVal mv in q) 6 { 7 if (mv.Value != null) 8 stack.Push(Expression.Constant(mv.Value.Value)); 9 else 10 { 11 Expression right = stack.Pop(); 12 Expression left = stack.Pop(); 13 switch (mv.Op.Value) 14 { 15 case MathOp.Add: 16 stack.Push(Expression.Add(left, right)); 17 break; 18 case MathOp.Sub: 19 stack.Push(Expression.Subtract(left, right)); 20 break; 21 case MathOp.Mul: 22 stack.Push(Expression.Multiply(left, right)); 23 break; 24 case MathOp.Div: 25 stack.Push(Expression.Divide(left, right)); 26 break; 27 case MathOp.Mod: 28 stack.Push(Expression.Modulo(left, right)); 29 break; 30 } 31 } 32 } 33 34 return Expression<Func<int>>.Lambda<Func<int>>( 35 stack.Pop(), 36 new ParameterExpression[0] 37 ); 38 } Let's explain this code step-by-step: The cool thing of the built expression is that it doesn't require manual compilation as we did in Part 3: Compilation to IL. Instead we can just call Compile() on the expression. To illustrate this, the Main method is changed as follows: 1 static void Main(string[] args) 2 { 3 Console.WriteLine("Dynamic calculator"); 4 Console.WriteLine("------------------"); 5 Console.WriteLine(); 6 7 Console.Write("Expression: "); 8 string expr = Console.ReadLine(); 9 10 Queue<MathOpOrVal> q = Expr.InfixToPostfix(expr); 11 12 Console.WriteLine(); 13 Console.Write("Postfix representation: "); 14 Print(q); 15 16 Console.WriteLine(); 17 Console.WriteLine("Tree representation:"); 18 //TreeNode tree = ToTree(q); 19 //Print(tree); 20 Expression<Func<int>> f = ToTree2(q); 21 StringBuilder sb = new StringBuilder(); 22 f.BuildString(sb); 23 Console.WriteLine(sb.ToString()); 24 25 Console.WriteLine(); 26 Console.Write("Dynamic calculation: "); 27 //Console.WriteLine("Result = {0}", Execute(tree)); 28 Console.WriteLine("Result = {0}", f.Compile().Invoke()); 29 } As you can see (line 28), execution is piece of cake thanks to the System.Expressions library. Also, printing the tree is relatively straightforward using a StringBuilder (lines 20 to 23). A sample execution of this application is shown below: Dynamic calculator ------------------ Expression: ((1+2)+3)*2-8/4 Postfix representation: 1 2 Add 3 Add 2 Mul 8 4 Div Sub Tree representation: () => Subtract(Multiply(Add(Add(1, 2), 3), 2), Divide(8, 4)) Dynamic calculation: Result = 10 Notice the equivalence of our tree representation, i.e. +Sub +Mul +Add +Add 1 2 3 2 +Div 8 4 and the C# 3.0 Expression Tree lambda expression, i.e. () => Subtract(Multiply(Add(Add(1, 2), 3), 2), Divide(8, 4)) Stay tuned for even more Expression Tree fun in the!
http://community.bartdesmet.net/blogs/bart/archive/2006/11.aspx
CC-MAIN-2016-26
refinedweb
4,316
59.4
Identity in the Browser, Firefox style By bblfish on Nov 25, 2009 Mozilla's User Interface chief Aza Raskin just put forward some interesting thoughts on what Identity in the Browser could look like for Firefox. As one of the Knights in search of the Golden Holy Grail of distributed Social Networking, he believes to have found it in giving the browser more control of the user's identity. Weave Identity Account Manager project site: The User Interface: One enhancement the Firefox team could immediately work on, without inventing a new protocol, would be to reveal in the URL bar the client certificate used when connected to a https://... url. This could be done in a manner very similar to the way proposed by Aza Raskin in the his Weave Account manager prototype pictured above. This would allow the user to - know what HTTPS client cert he was using to connect to a site, - as well as allow him to log out of that site, - change the client certificate used if needed From there it would be just a small step, but one that I think would require more investigation, to foaf+ssl enhance the drop down description about both the server and the client with information taken from the WebID. A quick reminder: foaf+ssl works simply by adding a WebID - which is just a URL to identify a foaf:Agent - as the subject alternative name of the X509 certificate in the version 3 extensions, as shown in detail in the one page description of the protocol. The browser could then GET the meaning of that URI, i.e. GET a description of the person, by the simplest of all methods: an HTTP GET request. In the case of the user himself, the browser could use the foaf:depiction. The Synchronization Piece Notice how foaf+ssl enables synchronization. Any browser can create a public/private key pair using the keygen element, and get a certificate from a WebId server, such as foaf - about the user (name, depiction, address, telephone number, etc, etc) - a link to a resource containing the bookmarks of the user - his online accounts - his preferences The Security Problem So what problem is the Weave team solving in addition to the problem solved above by foaf+ssl?. It is to solve this problem that Weave was designed: to be able to publish remotely encrypted information that only the user can understand. The publication piece uses a nearly RESTful API.. Generalization of Weave To make the above protocol fully RESTful, it needs to follow Roy Fielding's principle that "REST APIs must be hypertext driven". Linked Data. By defining both a way of getting objects, and their encoding, the project is revealing its status as a good prototype. To be a standard, those should be separated. That is I can see a few sperate pieces required here: - An ontology describing the public keys, the symmetric keys, the encrypted contents,... - Mime types for encrypted contents - Ontologies to describe the contents: such as People, bookmarks, etc... By separating the first two from (3), the Weave project would avoid inventing yet another way to describe a user for example. We already have a large number of those, including foaf, Portable Contacts,. The Client Side Password removed the reverse DNS namespace requirement. In any case such a solution can be very generic, and so the Firefox engineers could go with the flow there too. RDF! You crazy? I may be, but so is the world. You can get a light triple store that could be embedded in mozilla, that is open source, and that is in C. Talk to the Virtuoso folks. Here is a blog entry on their lite version. My guess is they could make it even liter. KDE is using it.... Posted by uberVU - social comments on November 25, 2009 at 03:13 PM CET # I think Gnome Tracker also has a C triple store implementation. It might also be possible to on the Linux desktop at least use a triple store exposed over dbus so that firefox would share it's data with the rest of the OS. Posted by Gavin Carothers on November 25, 2009 at 04:40 PM CET # Regarding the final section of the article, "RDF! You crazy?". It seems like the technology used in MIT's RDF browser Tabulator would be more appropriate tech than the virtuoso sql-lite option you mention. Tabulator's code is all open-source, and it has a JS based SPARQL implementation, and includes code for flat file RDF serialisation, for persisting RDF in Firefox. And it is a FF plugin, so probably easier to port, I am not sure but i have a feeling that the code-base is definitely "lighter" than virtuoso ;) Posted by Mischa on November 26, 2009 at 05:07 AM CET # How about bringing Kerberos into this conversation? On the client side, the pieces to pull together into the kind of Firefox user interface you're suggesting are falling into place. The good folks at MIT have already written the API that a project like Firefox could build an API on top of, and released it with their software distribution. Here's some mac documentation, though I think the API itself is cross-platform: ...and here's a presentation about that API, by a developer who worked on it, describing exactly how it can help with the multiple-identities problem: Adoption of this would also help many, many organizations easily build single sign-on systems. And those scary sounding kerberos principal names? They can be made to look exactly like email addresses. That fits people's mental models of identity better than URLs. Thoughts? Posted by Charlie O'Keefe on December 21, 2009 at 03:32 AM CET # Kerberos identity is already supported in web-browsers (at least Firefox/IE and if I remember correctly, Safari too), via HTTP SPNEGO. The problem with Kerberos is that it's a very centralised way of managing identities, even when federating multiple realms. You also need both the server and the user to be registered with the KDC (same realm or same federation). This goes against the principle of the global, decentralised identifier. Posted by Bruno Harbulot on December 21, 2009 at 05:43 PM CET # Yes, kerberos is already supported by browsers via SPNEGO using the Negotiate header. That is part of the reason I'm viewing it as low hanging fruit! What is \*not\* already supported in current browsers is a good interface enabling a user to manage a collection of identities. The KIM API I linked to above describes how client tools such as browsers could build such an interface. This would be a great way to take authentication out of the browser frame and instead put it in the browser 'chrome' as this post suggests. I agree with your observation that federation between kerberos realms is an impractical way to handle authentication at internet scale. That is best left to organizations that actually have some real-world trust relationship. Given that fact, I think what I'm describing is a great way for a user to authenticate to an identity provider, but the communication between that identity provider and another service acting as an identity consumer would in most cases have to be accomplished using some other protocol. Posted by Charlie O'Keefe on December 21, 2009 at 06:55 PM CET #
https://blogs.oracle.com/bblfish/entry/identity_in_the_browser_firefox
CC-MAIN-2016-07
refinedweb
1,239
57.4
Consul Miniseries: Spring Boot Application and Consul Integration Part 15 will focus on preparing two services and Consul docker containers. Later on in each part of the series, we will change the code to show more interesting applications of Consul. The first service we will use will be responsible for storing user data. It will contain a small amount of information about the user, namely, his name and surname. It will also have a REST API, allowing other services to ask for that data (for simplification, we will only use one GET endpoint, and some static data). The first part of the application is a very simple DTO object: @Value class User { String name; String surname; } We need only two fields, name and surname. We also use Lombok @Value annotation, just to keep things simple in this example (for more information on Lombok, see). The controller we will use for accessing static user data looks like this: @RestController class UserController { @GetMapping("/user") User getUser() { return new User("Spring", "Guru"); } } There is only a single GET endpoint /user that allows us to fetch a hardcoded name and surname. We will also change the default port the service starts with, from 8080 to 8081 in application.properties file: server.port=8081 When we run this application and make a request to the endpoint above, we get: { "name": "Spring", "surname": "Guru" } This is a trivial example, but it is enough for us to show what Consul has to offer. Hello service Hello service is another simple service, which purpose is to call User service and print a hello message, using data received from User service. First, let us make a call to user service, to receive the data: @FeignClient(name = "users-service", url = "") public interface UsersServiceClient { @RequestMapping("/user") User getUser(); } We use Open Feign from the spring cloud to make an external call. Feign client annotation requires us to pass a name, so for our case users-service is fine. Url is hardcoded now to the localhost, which may not work very well in a distributed world. We may have services on different servers and the localhost may not be the place on which the service exists. In the second part of this tutorial, we will change this to show how we can use Consul for service discovery. The only request we will require is to get user data from user service. As we do not have any parameters to pass to the call, only such a simple path in request mapping annotation is sufficient. We also have to use the same user DTO as in the previous example, to be able to parse received JSON into an object: @Value public class User { String name; String surname; } Next, we have a service class: @Service @RequiredArgsConstructor public class HelloService { private final UsersServiceClient client; String getUserHello() { User user = client.getUser(); return "Hello " + user.getName() + " " + user.getSurname() + "!!!"; } } The single method here, getUserHello(), uses data received by calling an external service to prepare a hello message. Last part of this service is a controller: @RestController @RequiredArgsConstructor public class HelloController { private final HelloService service; @GetMapping("/hello") String getUserHello() { return service.getUserHello(); } } Similar to the user service, we have only one GET call here, that returns user hello message: Hello Spring Guru!!! To achieve the result above, two services should be started simultaneously on the local machine and an HTTP call to GET should be made. This is possible because we have used two different ports, and both of these services run on the same machine. Containers Let us now move to the containerization of those services, along with a Consul server, so we will be ready for the next part of the tutorial. Building application jars To run our services in containers, we would need an executable java file, which in our case will be a jar (Java archive) file. To create those, in the root directory of each application, run gradlew.sh or gradlew.bat file with clean build arguments, depending on which system you work on (for example, in case of Ubuntu Linux system, run ./gradlew clean build). Thanks to that, the jar file will be generated in build/libs folder, under the root directory of the application. Configuration file To run all of the necessary services, we will use docker-compose. Compose is a tool that allows defining and running applications that are composed of several containers. We just have to write some configuration in the YAML file, and start all the containers with a single command. Our docker-compose.yml configuration file looks like this:" ports: - 8081:8081 command: "java -jar app.jar" consul: image: consul:1.7 network_mode: host For version, we have picked 3, as this is the most recent one. Next, we have a services block. In this block, we have 3 services configured: - hello-service – contains our Hello application configuration - users-service – contains Users application configuration - consul – for starting Consul server Hello and users services configuration The configuration of both applications is similar. We have a docker base image, for which we picked OpenJDK java 14 alpine version (you can read about particular java versions and images on docker hub –). Following is the volumes block. Volumes are mounts of host paths into the container. In our case, we copy created jar files from our host system into the container. In both cases, jar file will be available on container path /app.jar. If you run on any troubles with volumes, be sure to check the official docker-compose reference site –. Ports part says which port in a container we would like to map to which host port. In our case, we map hello service 8080 container port to 8080 host port. Accordingly, in users service, we have set it to 8081. Thanks to that, we are able to start both services on the same machine, and we are able to access them using corresponding port numbers. The last part of the configuration of our services is a command. A command is used to tell docker which instruction it should run after the container startup. In our case, we want to run provided jar archive, so we do that using java -jar operation. Consul service configuration Consul configuration is much simpler because we are fine with default values that the Consul image starts with. For the Consul image, we have picked a 1.7 version, and we leave the default port, which is 8500. We also set up a network here ( network_mode parameter), to override a default bridge setting and we set its value to host. What that means is that docker will use host networking for this container, instead of separating container from the host as with default bridge network mode. Setting network to host is recommended for Consul, as it has some protocols that are sensitive to delays and packet loss. You can read more about network modes in docker reference, and information about why host mode is recommended for Consul you can find on the official docker hub page here. Running containers With configuration finished, we can run all these containers simply by running docker-compose up command in a directory where we have placed our docker compose.yml file. To check if every container works as it should, we can simply check if we can call them through our browser. Let us try with Users service using: {"name":"Spring","surname":"Guru"} For Hello service, we will not get a nice hello JSON right now. Instead, we will get an error page saying that connection to users service was refused: This happens because we have a hardcoded call to localhost as feign parameter, and running that in a container will fail, as we have no users service in the hello service container. Do not worry though, we will solve this issue in the second part of the series in which we will talk about service discovery. We can also check if our consul service works, by going to: Right now under the services tab, we can only see consul service itself. In the next part, we will add our applications here and allow them to communicate using Consul as service discovery. Summary In this tutorial, we have prepared a solid ground for future parts, in which we would introduce such concepts as service discovery or key/value datastore. We created two containerized applications, that work well when used on a local computer, but they do not work well without service discovery in containers. This will be solved in the next part of the tutorial. We have also prepared a container with a Consul server, that we can use to connect our applications, so they work well even in containers. The second part will introduce service discovery using Consul, where we will make calls in services using a service name instead of hardcoded url. 5 comments on “Consul Miniseries: Spring Boot Application and Consul Integration Part 1” Bunga In the hello service, we cannot deserialize User when created with lombock @Value decorator. Bunga Thanks fo sharing 🙂 Arijit Chaudhury Hi, I am getting a error connection refused when try to access “”. Do I need to set ports and host ip address in docker-compose file? Anuj K While running the docker compose command i am getting Invalid or corrupt jarfile app.jar for all my services.I believe the path in the volumes could be incorrect.I Have given the below path. Please let me know what is that i am missing movie-info-service: image: openjdk:14-alpine volumes: – “./movie-info-service/target/movie-info-service-0.0.1.jar:/app.jar” command: “java -jar app.jar”
https://springframework.guru/consul-miniseries-spring-boot-application-and-consul-integration-part-1/
CC-MAIN-2021-43
refinedweb
1,608
60.75
I was trying to do the following thing with HashMap. I create a Map<Key, String> Idea of this key class is that the object of Key is same if value in i is same. Now, I created the following Map. Now, I change the Key Key(2) such that value of i in it is 1 which is same as of the Key(1). Now, the Map has two key which actually equals, which is not possible if we add the keys using Put method. Also, on getting previous one is generated. This is fine. But the interesting part is that when i remove the key only one key is lost. Also, if I removed once, I cannot retrieve the re That means the Key whose value was 2 is lost (another memory leak in Java). Can anybody explain/put his thoughts on this behavior? Or can anybody answer the followings? 1. Why only first object is returned and not second (always) when there are two keys. 2. When removing the key, why did not it remove both? 3. Why did map.containsValue("2") returned true, even when after removed the key? SCJP 5.0 Yes, there is a possible memory leak, but that is because you have not followed the advice in the Map interface. You have used a mutable class, which by the way has a poorly-designed equals() method. [Using instanceof in an equals method can cause incorrect behaviour if an instance of a subclass is submitted for equals().] This is what happens with a hash-based Map (which I shall call HM because there are other classes besides HashMap which show the same behaviour): So, your problem is typical of what happens if you try using a mutable object as the Key for an HM. Thanks for the Quick and detailed reply. I understand the issue. The issue was the original Key have id as 2 had hashCode as 2 and they key is stored with this hashCode in Map.. On the side note, can you please comment on why the equals method is poorly designed? (I might be missing some basic design principle) Thanks Sandeep Jindal SCJP 5.0 Sheriff Sandeep Jindal wrote:Now, I change the Key Key(2) such that value of i in it is 1 which is same as of the Key(1). If you do that while you've used that Key object in the map, then that's a problem. The Map doesn't know that the value of the key has changed and gets confused, and the behaviour of the map will become unpredictable. you should only use immutable classes a keys in a map. Sandeep Jindal wrote. It doesn't make much sense to try to reason what will happen in this case - the behaviour is undefined, so in principle anything can happen. It depends on how HashMap is implemented internally. What happens may be different on different versions of Java. Imagine this classand thisas well as your previous Key class. Now k.equals(kk) and kk.equals(k) should give the same result. Compile those classes, correct any spelling errors, and see what happens. Look for the appropriate chapter in Bloch's Effective Java (it used to be possible to find that part of the 1st edition as a sample chapter online) or Google for Angelika Langer Java equals for lots more information. In your case, the best design is to change your Key class to an immutable class. Change public class Key to public final class Key and change int i to final int i. In a final class, the instanceof keyword/operator does exactly what you think it does, so making the class final allows you to get correct results without changing the equals() method. Understand the contract of HashMap which says do not play with keys, or never play with keys atleast when iterating (correct?) but what if I have a requirement in such a way that I need to update my keys based on some operations and that is my requirement. Can you please suggest what to do in that case. Example of my requirement is: I maintain No of Order and the residuals of that orders. While doing some operations, I need to modify the No Of orders. Also, I need to maintain Map whose key is No Of orders because I frequently require to get the residuals for a particular no of orders (in short, I need some value based on some key(no of orders) and that key needs to be modifiable). What do the experts suggest in this case? Regards Sandeep Jindal SCJP 5.0 Sandeep Jindal wrote:but what if I have a requirement in such a way that I need to update my keys based on some operations and that is my requirement. Can you please suggest what to do in that case. The only thing that works is: remove the element from the map, change the key, and put it back in the map. There's no way to make it work while leaving the key in the map. What I have done is (even before your reply) following: I have taken all the key and put that into an ArrayList. Now, I iterated the arraylist and changed the values of the keys (and since its refences, it has changed the corrospding keys) Ofcourse, I have taken care that the hashcode for all these key is same(which was very important). Please comment on this, if you think this is not the correct or not the best approach. SCJP 5.0 Jesper has already told you only to use immutable objects as keys in a Map. Thanks for your answer. To explain you the scenario: I have Order ID and Number of Orders. For this I store some information. e.g. (OID: 1, NO 2 AND OID: 2, NO. 3 ) is one key (OID: 2, NO 3 AND OID: 4, NO. 3 ) is another key Now, I as part of my algoirthm, I need to store and get Information for this Key (OrderID, Number). Also, in some process of my algorithm, say I got I more order and I need to add this in each key. Say I got another OID:6, No.1. I need to add this into each key and my keys wills be (OID: 1, NO 2 AND OID: 2, NO. 3, OID:6, No.1 ) is one key (OID: 2, NO 3 AND OID: 4, NO. 3, OID:6, No.1 ) is another key I could have used different approach, but I frequency need Values based on the keys mentioned above. This is my scenario and I need to update keys for some operation. I totally agree with you that they List approach I mentioned is very bad in term of HashCode, but this is the best I could think of. SCJP 5.0 I put it another way. I have Orders and Order's Residuals. Since I need to get Residuals for a particular type of order, I am strong it in a Map<Orders, Residuals> Is that fine? Now, Orders which is a key, is a Map<ID[Integer], Number[Integer]> (this map is not a problem). Say my Initial state is this. Order<{1,1}>, Residual1 Order<{1,2}>, Residual2 Order<{2,2}>, Residual3 Now, for each of entry in this Map, I need to add one more Order <{1,1}> which shall result the following: Order<{1,2}>, Residual1 Order<{1,3}>, Residual2 Order<{2,2}, {1,1}>, Residual3 I understood what Jesper said and one of the right ways but it would work for me, unless I remove all and then start adding and for this, I am temporary saving the keys in list. SCJP 5.0
https://coderanch.com/t/474584/java/Behaviour-HashMap
CC-MAIN-2018-22
refinedweb
1,303
80.41
Ticket #1145 (closed defect: fixed) ran_migration receives the app name as string, but migration as migration object. Description I have a code snippet as such: def check_need_to_run(app=None, migration=None, method=None, *args, **kwargs): if app == "foo" and migration == "0041_add_new_bar": process_post_migration() ran_migration.connect(check_need_to_process) But it errors out because south.migration.base's eq method is being called. The documents should be updated to reflect that the migration object is being passed, or else south.migration.migrator.Migrator should be updated to pass the migration name as a string object. Change History Note: See TracTickets for help on using tickets. Docs corrected in [aa19d6a1a7b0].
http://south.aeracode.org/ticket/1145
CC-MAIN-2014-41
refinedweb
105
51.24
The location is very convenient for getting out and about with young children as the trams and trains are all within easy walking distance. Excellent for shopping and cafes. Our room was spacious, but sheets were not clean and bathroom was mouldy. A cockroach ran up my leg whilst in the bathroom :-O Staff were polite but lacking warmth - it's just a job! We were lucky? to land a half price deal for our three night stay, but certainly not worth the average 'discount' price. We atayed at the Vic on our return (also reviewed) and it was much better value. Pros: Location, has a bath so great for smaller children, super comfy beds Cons: unclean -, Travelocity, Orbitz, Booking.com, Expedia, ACCOR, Hotwire, Agoda, Priceline,
https://www.tripadvisor.com/ShowUserReviews-g255100-d256930-r64113182-Novotel_Melbourne_on_Collins-Melbourne_Victoria.html
CC-MAIN-2017-22
refinedweb
126
74.39
Opened 7 years ago Closed 5 years ago #13870 closed New feature (fixed) Document transaction/connection management outside the web server context Description First some background info: - PostgreSQL provides several transaction isolation levels. - Django's psycopg backend defaults to ghost-read-preventing isolation. - psycopg isolation modes automatically create the isolating transaction whenever you execute your first SQL statement. - psycopg expects you to tell it when you're done with your work by either running connection.commit()or connection.rollback() - When you terminate the transaction, psycopg will wait for the next SQL statement and start a new isolating transaction. The problem is: Django breaks assumption 4 and never commits or rollbacks the isolating transaction. Note I'm not talking about the transactions explicitly started by django, I'm talking about the transaction implicitly started by requesting a non-zero isolation level. This has the nasty side-effect of leaving the connection permanently in-transaction. Try it yourselves: start a django server, make it use the DB and then try to - say - VACUUM FULL the table it selected from. Or try to ALTER the table (run a south migration). You will end up with a hanging connection, waiting for Django to leave the transaction block. The attached patch makes it work for psycopg2 by introducing a new method in the backend class. It needs a call to leave_transaction_management() so it works best with the TransactionMiddleware. Now for a real solution: I think it would be better to introduce some sort of enter_isolation_block() / leave_isolation_block() API. "Enter" would call set_isolation_level(1) (currently done unconditionally), "leave" would terminate the isolation transaction. Then introduce a default middleware that wraps all the views in these calls. It just doesn't seem intuitive to mix the transactions implicitly created by isolation API with the explicit transaction management API. Attachments (2) Change History (14) Changed 7 years ago by comment:1 Changed 7 years ago by I ran into to this problem from Django 1.0 and ended up using the following workaround to explicitly close the connection after the model was used. from django.db import connection connection.close() In my case there was a shared table lock which ended up being held by the process using the model classes (because of the uncommited transaction) which in turn caused a deadlock as another process requiring an exclusive lock on the table would block forever. comment:2 Changed 7 years ago by I have had the same problem on Django 1.2. I just applied this patch and will report back on my progress. In the past I have partially worked around this problem by manually calling connection.close(). I noticed that when I write custom command-line scripts that use my models via Django's ORM, then I have to close connections manually. I assume the transaction middleware doesn't execute (and therefore close the connection) in that sort of environment, but for some reason it still opens transactions. The easiest way to notice when things go wrong is, well, every time I try to alter a table during development: The connection just hangs forever. The only way I found to work around it is to restart the postgresql process. (I can't find an easy way to break these locks from the command-line psql client or make them expire.) It also looks like the transaction middleware code that's supposed to roll back transactions or close the connection is not guaranteed to execute, but I haven't looked very deeply into it. What happens when your code encounters errors and you get an unhandled exception? Another possible workaround would be to somehow make all locks expire after a short period of time, but I can't find how to do that. Or to close connections from the postgresql server end after a short period of inactivity. Again, not even sure if that's possible. Or perhaps if it was possible to only enter a transaction if you perform an update query? Then at least this wouldn't happen quite so often. But something is certainly wrong. Another option would be to just steer clear of automatic transactions. comment:3 Changed 7 years ago by comment:4 Changed 7 years ago by Does not look related. comment:5 Changed 7 years ago by Per this discussion on django-dev (especially Gabriel's comment there), I think this is mainly a documentation issue. Adding a page on using the ORM outside of request/response flow would be best, imho. Dunno if adding 2 non-public method will help, here. comment:6 Changed 7 years ago by Adding methods won't help but moving their invocation to middleware or a decorator will let people decide if they want isolation and when to terminate it when dealing with models outside of views. comment:7 Changed 7 years ago by comment:8 Changed 6 years ago by My first thought was "Django probably started closing connections at the end of each request after this ticket was reported, the problem must be fixed"; the mailing list thread contains this clarification: The problem is not with regular views but with Celery tasks, long-running management commands such as daemons and any other place where you access the ORM from outside of the usual request→dispatcher→view→response flow. These cases all end up with an isolating transaction spanning their whole life span. In case of daemons it results in permanently blocking the database structure (for example causing "VACUUM FULL" to hang). Gabriel wrote a complete explanation here: I'm accepting this as a documentation issue — Django is primarily a web framework and I don't like the idea of complicating transaction management for offline tasks. Changed 5 years ago by comment:9 Changed 5 years ago by Added a doc patch based on Gabriel's stackoverflow post. comment:10 Changed 5 years ago by I think this needs to be changed: As soon as you perform an action that needs to write to the database, ... to mention that only write actions through the ORM count here. This paragraph seems to be out of place / context: This goes against the fact that PostgreSQL thinks the transaction requires a ``ROLLBACK`` because Django issued a ``SET`` command for the timezone. Also, the section discussing the dirty flag isn't accurate. The dirty flag has nothing to do with doing the commit in autocommit mode - the commits are done manually in the write operations Django performs by issuing commit_unless_managed. The docs should only mention that as long as you perform any query which isn't a write using the ORM, then there will be an open transaction and this will not be closed automatically by Django. Typo: meeded -> needed The docs additions do not take into account multidb. I think it would be a good idea to add a context manager @close_connections which ensures all connections (known to Django) will be closed. This would simplify the solution part a lot: use @close_connections, be done with it (except if you are playing with threads). It might be a good idea to commit the docs changes with the above suggested changes apart of the multidb stuff. We might want to do more extensive edit of the transaction handling docs for multidb, or we might want to add the close_connections decorator. But, I don't know what the schedule for those are, so they shouldn't block the currently available improvements. Partial workaround (see description)
https://code.djangoproject.com/ticket/13870
CC-MAIN-2017-51
refinedweb
1,245
60.14
Defines the Profile interface. More... #include <Profile.h> Defines the Profile interface. An abstract base class for representing object location information. This is based on the CORBA IOR definitions. Constructor. If you have a virtual method you need a virtual dtor. To be used by inherited classes. Decrement the object's reference count. When this count goes to 0 this object will be deleted. Increase the reference count by one on this object. Obtain the object key, return 0 if the profile cannot be parsed. The memory is owned by the caller! Reimplemented in TAO_Unknown_Profile. Add a protocol-agnostic endpoint. Reimplemented in TAO_IIOP_Profile. Add the given tagged component to the profile. Set the addressing mode if a remote servant replies with an addressing mode exception. If this profile doesn't support a particular addressing mode, this method needs to be overridden signal the appropriate error. ** RACE CONDITION NOTE ** Currently, getting and setting the addressing mode is not protected by a mutex. Theoretically, this could cause a race condition if one thread sends a request, then gets an exception from the remote servant to change the addressing mode, and then another thread sends a different request to the same servant using the wrong addressing mode. The result of this is that we'll get another address change exception. (Annoying, but not that bad.) In practice at the current time, the above theoretical case never happens since the target specification always uses the object key except for MIOP requests. Remote ORBs can't respond to MIOP requests even to send exceptions, so even in this case, the race condition can't happen. Therefore, for the time being, there is no lock to protect the addressing mode. Given that the addressing mode is checked in the critical path, this decision seems like a good thing. Return the current addressing mode for this profile. In almost all cases, this is TAO_Target_Specification::Key_Addr. Return a pointer to this profile's endpoint. If the most derived profile type uses an endpoint that is a type that does not derive from the endpoint type of the base profile, then this method returns the base type's endpoint. For example, SSLIOP_Profile derives from IIOP_Profile, but SSLIOP_Endpoint does not derive from IIOP_Endpoint. Because SSLIOP is tagged the same as IIOP, this method is required to facilitate the Endpoint Policy's filtering function. The default implementation of base_endpoint simply returns endpoint. Reimplemented in TAO_IIOP_Profile. Compare the object key for this profile with that of another. This is weaker than is_equivalent Creates an encapsulation of the ProfileBody struct in the cdr. Implemented in TAO_IIOP_Profile, and TAO_Unknown_Profile. This method is used to get the IOP::TaggedProfile. The profile information that is received from the server side would have already been decoded. So this method will just make a IOP::TaggedProfile struct from the existing information and return the reference to that. This method is necessary for GIOP 1.2. Initialize this object using the given CDR octet string. Reimplemented in TAO_Unknown_Profile. Helper for decode(). Decodes endpoints from a tagged component. Decode only if RTCORBA is enabled. Furthermore, we may not find TAO_TAG_ENDPOINTS component, e.g., if we are talking to nonRT version of TAO or some other ORB. This is not an error, and we must proceed. Return 0 on success and -1 on failure. Implemented in TAO_IIOP_Profile, and TAO_Unknown_Profile. Decode the protocol specific profile details. Implemented in TAO_IIOP_Profile, and TAO_Unknown_Profile. Profile equivalence template method invoked on subclasses. TAO_Profile subclasses must implement this template method so that they can apply their own definition of profile equivalence. Implemented in TAO_IIOP_Profile, and TAO_Unknown_Profile. Encode this profile in a stream, i.e. marshal it. Reimplemented in TAO_Unknown_Profile. Encodes this profile's endpoints into protocol specific tagged components. This is used for non-RTCORBA applications that share endpoints on profiles. The only known implementation is IIOP, using TAG_ALTERNATE_IIOP_ADDRESS components. Reimplemented in TAO_IIOP_Profile. Encodes this profile's endpoints into a tagged component. This is done only if RTCORBA is enabled, since currently this is the only case when we have more than one endpoint per profile. Implemented in TAO_IIOP_Profile, and TAO_Unknown_Profile. Return a pointer to this profile's endpoint. If the profile contains more than one endpoint, i.e., a list, the method returns the head of the list. Implemented in TAO_IIOP_Profile, and TAO_Unknown_Profile. Return how many endpoints this profile contains. Implemented in TAO_IIOP_Profile, and TAO_Unknown_Profile. Return the first endpoint in the list that matches some filtering constraint, such as IPv6 compatibility for IIOP endpoints. This method is implemented in terms of TAO_Endpoint::next_filtered(). MProfile accessor. Keep a pointer to the forwarded profile. This object keeps ownership of this object. Accessor for the client exposed policies of this profile. Return a hash value for this object. Implemented in TAO_IIOP_Profile, and TAO_Unknown_Profile. Verify profile equivalance. Two profiles are equivalent if their tag, object_key, version and all endpoints are the same. trueif this profile is equivalent to other_profile. Allow services to apply their own definition of "equivalence.". This method differs from the do_is_equivalent() template method in that it has a default implementation that may or not be applicable to all TAO_Profile subclasses. Reimplemented in TAO_Unknown_Profile. Return the next filtered endpoint in the list after the one passed in. This method is implemented in terms of TAO_Endpoint;:next_filtered(). If the supplied source endpoint is null, this returns the first filtered endpoint. The object key delimiter. Implemented in TAO_IIOP_Profile, and TAO_Unknown_Profile. Get a pointer to the TAO_ORB_Core. Initialize this object using the given input string. Supports URL style of object references Reimplemented in TAO_Unknown_Profile. Protocol specific implementation of parse_string (). Implemented in TAO_IIOP_Profile, and TAO_Unknown_Profile. This method sets the client exposed policies, i.e., the ones propagated in the IOR, for this profile. Remove the provided endpoint from the profile. Some subclasses of TAO_Profile already have a protocol-specific version of remove_endpoint, but this generic interface is required. The default implementation is a no-op. Protocol maintainers wishing to add support for the EndpointPolicy must implement remove_generic_endpoint to call their protocol-specific version of remove_endpoint Reimplemented in TAO_IIOP_Profile. Helper method that encodes the endpoints for RTCORBA as tagged_components. Returns true if this profile can specify multicast endpoints. Returns true if this profile supports non blocking oneways. The tag, each concrete class will have a specific tag value. The tag, each concrete class will have a specific tag value. Access the tagged components, notice that they they could be empty (or ignored) for non-GIOP protocols (and even for GIOP-1.0) Return a string representation for this profile. Client must deallocate memory. Only one endpoint is included into the string. Implemented in TAO_IIOP_Profile, and TAO_Unknown_Profile. Verify that the current ORB's configuration supports tagged components in IORs. Verify that the given profile supports tagged components, i.e. is not a GIOP 1.0 profile. Return a pointer to this profile's version. This object maintains ownership. The current addressing mode. This may be changed if a remote server sends back an address mode exception. Flag indicating whether the lazy decoding of the client exposed policies has taken place. The TAO_MProfile which contains the profiles for the forwarded object. Object_key associated with this profile. Number of outstanding references to this object. The tagged components. Our tagged profile. Having (tagged_profile_ != 0) doesn't mean yet that tagged_profile_ building is finished. A lock that protects creation of the tagged profile.
http://www.dre.vanderbilt.edu/Doxygen/5.7.7/html/tao/a00324.html
CC-MAIN-2013-20
refinedweb
1,225
53.27
Not sure if you’ve already noticed it, but every button or menu item you see inside the Topobase panel comes from a plug-in. The entire Topobase architecture is based on plug-in technology. This gives of us all many possibilities to customize, configure and extend the Topobase solution. You’d like to see some examples? No problem. Here is a list that shows how you can extend Topobase with plug-ins: - extend the context menu of a feature class with a new entry - add new capabilities to the attributive form accessible through a button - validate features before they are inserted or updated into the database - maintain and extend the structure of your own data model automatically In fact, many of the Autodesk Topobase components are based on plug-ins created by our developers. Some examples are the Workspace Management and Administration dialog, Map Interface, COGOs, and the reporting tool. So let’s take a look at some code. In this code fragment you can see what a plug-in class looks like. This plug-in class extends the context menu of all point feature classes in the Document Explorer with one new menu item. The capabilities of the menu item can then be anything you like. // Create a new class which is derived from our Document Plugin class. // A Document Plugin will automatically be loaded per document when a workspace is opened. public class MyDocument : Topobase.Forms.DocumentPlugin { // Create a new MenuItem object. public Topobase.Forms.MenuItem myMenuItem1 = new Topobase.Forms.MenuItem(); // Override the OnInit method to add our own menu item. public override void OnInitMenus(object sender, Topobase.Forms.Events.MenusEventArgs e) { // Obtain the context menu to which you want to add your new MenuItem. Topobase.Forms.Menu pointMenu = e.Menus.Item(Topobase.Data.FeatureClassType.Point); // Add your MenuItem with the text “My MenuItem1” to the context menu. pointMenu.MenuItems.Add(myMenuItem1, "My MenuItem1"); // Add a click event handler to the menu item, there you can implement the logic. myMenuItem1.Click += new MenuItemClickEventHandler(MyMenuItem1_Click); } ... // other code } Take a look at the folder C:\Program Files\Autodesk Topobase Client 2008\Development. Then go to the Samples subfolder and take a look at Sample 10: 10_Document_ContextMenu. There you have a fully functional C# or VB.NET solution, which creates a plug-in and extends the context menu.
http://topobaseinsiders.typepad.com/the_topobase_insiders/2008/01/index.html
CC-MAIN-2017-51
refinedweb
388
57.77
With the increasing standardization of attributes, we get the opportunity to make our code clearer not only to other humans but also to the compiler and other tools. Attributes are a standard way to deal with non-standard compiler extensions. This might sound strange at first, but let’s have a look at how some compiler extensions work. Apart from the larger extensions that completely tweak the language, many compilers add the possibility to add some little annotations to functions, variables, classes and so on. Usually, those annotations are pure additions, i.e. if you remove them, you get valid standard C++. Often they use identifiers that contain double underscores because those are reserved for the implementation, so you can’t get conflicts when you port standard C++ code to another compiler. One example is the __fastcall annotation in MSVC that tells the compiler to pass the first two sufficiently small arguments in registers on x86 architectures. In GCC, a similar behavior can be achieved by using __attribute__((fastcall)). This already shows the problem: There was no standardized way to handle this kind of compiler extensions prior to C++11. Different compilers would use different ways to describe those annotations. This makes code non-portable or requires to manage the annotations by using preprocessor macros. C++11 attributes With C++11, the way to write these annotations was standardized. Attributes can now be portably written using double square brackets: [[xyz]] void foo(int i, int j) { //... } Sadly, this does not yet solve the overall problem: Only a few of the attributes are standardized. Compilers are allowed to use their own attributes, but they have to be placed in compiler specific namespaces. E.G., the fastcall attribute in GCC now can be written in a standard-compliant way as [[gnu::fastcall]], but other compilers are not required to understand this. Until C++17, other compilers are even allowed to fail compilation on unknown attributes, from C++17 on they are required to ignore them. In fact, it seems that MSVC 2015 still does not support the new attribute syntax at all. Standardized attributes Compliance issues aside, there are some attributes that have been standardized. Here are the ones that are most important for maintainability: [[deprecated]], [[deprecated("Because it's old")]]: With these attributes, we can mark functions, variables, classes and so on that should not be used anymore, e.g. because they will be removed in the future. Deprecating things like this can be especially useful if you are in the process of refactoring a piece of software, but simply removing a feature is not possible due to its widespread use. [[fallthrough]]: Put this at the end of a case block in a switch statement to signal that you did not write a breakstatement there on purpose. Otherwise, static analyzers and code reviewers might warn about the missing break, and this it the way to tell everyone that you know what you are doing. switch(something) { case SPECIAL_CASE: prepareForSpecialCase(); [[fallthrough]] default: handleAllCases(); } [[nodiscard]]: This attribute tells the compiler to warn about uses of a function or its return type that would discard the value. Values are discarded if they are not assigned to a variable. This is especially the case if a function with a return value is called as a statement or as the left hand of a comma operator. The warning can be turned off by explicitly casting the value to void. struct [[nodiscard]] X { int i; }; X foo() { return {42}; } [[nodiscard]] int bar() { return 3; } void moo() { foo(); //Warning: discarded X auto i = (bar(), 55); //Warning: discarded bar() (void)bar(); //OK } [[maybe_unused]]does basically the opposite as [[nodiscard]]: Many compilers already warn about unused values in certain cases. [[maybe_unused]]says that it’s actually OK to not use values marked with this attribute. [[noreturn]]is for function declarations only and tells the compiler that this function will not return. That is, the function will either throw exceptions or call finishing functions like exitor terminateon allexecution paths. While it is mainly useful for optimizations it also adds a bit of documentation. Conclusion The implementation, as well as the further standardization of attributes, is still work in progress. Still, what is already there can be useful and we should use it where appropriate. If you want to see some more detailed information about attributes, check out Bartlomiej Filipek’s blog post! 3 Comments Permalink Permalink As a minor update, it looks like MS won’t be adding any of the new attribute behaviors for VS2017. According to an MS dev no compiler features were added between Preview 5 and the release candidate; and it doesn’t look like any of the C++ 2017 attribute changes made the cutoff. Permalink The page you linked to states that VS2015 does support attribute syntax. In fact: [[deprecated]] int Something() … 1>d:\sandbox\try1\try1.cpp(20): error C4996: ‘ABC::Something’: was declared deprecated
https://arne-mertz.de/2016/12/modern-c-features-attributes/
CC-MAIN-2017-47
refinedweb
820
52.49
This topic lists the following common issues that occur when you work with Web tests in Visual Studio Team Edition for Testers. The Remote Name Could Not Be Resolved JavaScript and ActiveX Controls Do Not Run Coded Web Test Error Caused by Unbound Data Source. Using "default" as your proxy setting can cause performance problems when you run your Web test under load. It is better to specify a proxy other than "default" when you run your Web test in a load test.. The proxy server can also be specified through code in following way: 1. Open a web test. 2. Right click on test and choose "Generate Code". Specify the proxy server in generated code as follows: public class WebTest1Coded : WebTest { public WebTest1Coded() { this.PreAuthenticate = true; this.Proxy = "default"; } ...............
http://msdn.microsoft.com/en-us/library/ms318556(VS.80).aspx
crawl-002
refinedweb
130
73.98
Hi, it´s me again and I have been playing around with the new Web Engine feature that came with CE9.9.0 a few days ago. This is just a wonderful feature with so many different use-cases that I don´t really know where to start. But the most obvious use-case is to re-purpose the device while it is not in use with Digital Signage, and at the same time have the option to create on-demand web views or web apps when needed. First of all, what is the difference between a web app and a web view? Well, nothing really but there is a difference on what the devices support. The Webex Board has a big touch screen and also have a mode called; Interactive Mode, which basically means you can interact with the web page you have opened, perfect for "Web Apps". The other devices you may view a web site but you cannot interact with it. So for now, Webex Board is the only device that support interactive "Web Apps", you can even create native shortcut icons to open different apps on-demand without creating complex macros, which is great for those who likes it simple. I like to make it a little bit more complicated for the benefit of flexibility, but we will take a look at both aspects as we go. Please enjoy, and I hope this will inspire you to create something amazing! Supported hardware Cisco Webex Board (all models), Room Kit, Room Kit Plus, Room55, Room 55 Dual, Room 70 (Dual), Room 70 G2 (Dual), Room Kit Mini, Room Kit Pro The Web Engine is the core feature used for Digital Signage and Web Apps. So, the first thing you must do is to enable this from the web interface or which ever method you prefer. xConfiguration WebEngine Mode: On We will be talking about Digital Signage and then about the UI Extensions while moving towards Web Apps. Digital Signage is a feature designed for re-purposing devices for displaying content of a web page when not in use. When the device enters half-wake the device will temporary display the content of the URL provided for the signage configuration until the device goes into standby. For Webex Boards there is also an interactive mode, which allows a user passing by the device, to interact with the web page displayed on the board. This could be a map of the building, todays lunch menu or whatever you want! Typical use cases When the device enters standby it will no longer display the web page on screen to save power (for example outside office hours). Today we do not have a native way of defining office hours on the devices, although you can do, with a macro. This means that it is possible to make the device display content, only during office hours and never go into standby during this time. Extending the standby timer will increase the duration of the web view, but it is limited to 120 minutes (2 hours) for now. xConfiguration Standby Delay: 120 Lets look at some examples on how to configure and set up Digital Signage. Configurations First of all, and I cannot stress this enough, you need to make sure the Web Engine is turned on for Digital Signage to work. xConfiguration WebEngine Mode: On Then you can enable the standby signage mode. Set the Standby Signage Mode to On and how often you want the page to refresh in seconds. Then finally, type in the URL to the page you want to load. xConfiguration Standby Signage Audio: Off xConfiguration Standby Signage InteractionMode: NonInteractive xConfiguration Standby Signage Mode: On xConfiguration Standby Signage RefreshInterval: 1 xConfiguration Standby Signage Url: "http://<url to something awesome>" Important note: Self-signed or other custom CA certificates on any HTTPS sites you are trying to open will not work in CE9.9.0 :( as it only validates toward a pre-installed list of Certificate Authorities. This will most likely improve in later versions of CE. Interaction mode is for Webex Boards only and allow you to navigate the displayed web page, clicking links and filling in forms and so on using the pop-up on-screen keyboard. For example, if you have a website monitoring statistics of some kind, this can be displayed on the system screen while in "Halfwake". When the device enters Standby mode the screen will go black as usual to save power. Here is a simple example on how to setup standby control during office hours, I have just tested this quickly so you probably want to expand on this and fix the bugs you may encounter :D. const xapi = require('xapi'); //Define office hours and days 1 = Monday etc const dayFrom = 1; const dayTo = 5; const hourFrom = 8; const hourTo = 16; /* * Timer interval, checking the time of day. If the time is in office hours it will check the current state. * If the device is in standby (which it will usually be in the mornings, it will automatically set the device in halfwake. * After checking the standby state it will reset the standby timer, not the halfwake timer which means that the device will go into halfwake but never in standby during the office hours. */ function signageControl() { setInterval(function() { if (checkOfficeHours()) { xapi.status.get('Standby State').then(standbyState => { if (standbyState === "Standby") { xapi.command('Standby Halfwake'); } else if (standbyState === "Halfwake") { resetStandbyTimer(); } }); } }, 50 * 1000); } function checkOfficeHours() { var d = new Date(); var hour = d.getHours(); var day = d.getDay(); if (day >= dayFrom && day <= dayTo) { return (hour >= hourFrom && hour < hourTo); } return false; } function resetStandbyTimer(){ xapi.command('Standby ResetTimer', { Delay: 5 }); } signageControl(); You can expand on the above as well to display different content at different time of the day. I could expand on this forever, but we have to move on :). Feel free to copy any of these examples and make them your own and better. Remember that whatever web site you choose to display on the screen and what functionality is provided is up to the content creator (maybe that is you?) either if it is a static web page with information or a dynamic web app with animations or interaction capabilities. Examples (Interactive mode) Lets create a simple interactive signage example, I mean -really- simple and I am not focusing on creating something slick here, it´s just to plant a seed in your brain. Use your favorite web server accessible by the Webex Board (IIS, apache, nginx or whatever). I am going to use a simple background using CSS and a couple of links that the user can click to interact with the Board. index.php (could also be .html) which is located in the <web-root>/signage web-root/signage <!DOCTYPE html> <html> <style> body{ background-image: url('cisco.png'); background-size: cover; height: 100vh; padding:0; margin:0; } a { font-size: 3em; text-decoration: none; } </style> <center><h1>WELCOME TO CISCO</h1></center> <a href='map.php'>Click here to see a map</a> <br> <a href='lunch.php'>Click here to see todays lunch menu</a> </html> I then set the correct configurations: xConfiguration WebEngine Mode: On xConfiguration Standby Signage Audio: Off xConfiguration Standby Signage InteractionMode: Interactive xConfiguration Standby Signage Mode: On xConfiguration Standby Signage RefreshInterval: 0 xConfiguration Standby Signage Url: "" I set the refresh interval to 0 so that the page never refreshes automatically, you should consider this as it can be disturbing for users navigating the page. As the final step the end I set the URL to my web server. Note: The refresh interval is in seconds and is useful if the page displaying content has dynamic values that needs to be refreshed or if the server logic is to show random content on each request (depending on the use-case etc..). If the content is heavy to load, you should use a longer refresh timer so that the page gets time to load and display the content for a while. If the device is currently NOT in halfwake, nothing will happen after setting the configurations. If you see the black screen and the device is in standby it is normal since the web page will only show as long as the device is in halfwake mode. You can trigger halfwake from the web interface or xAPI: xCommand Standby Halfwake The beautiful result! Note the black line at the bottom saying "Tap here to start". This is visible when a web page is being displayed in signage mode (not using web app), as tapping the screen anywhere else will try to interact with the web view. Pressing the "home" button on the webex board will also wake the system up from halfwake. The screen now renders my web page, which is quite simple. The links on the screen are just normal <a href> links but I have not created them yet, so when I click the links it will display: not found If you use broken links, like I have in this case, you will see "File not found". A floating "back" button will appear when you start navigating so you can move back in case you get lost on the web page. There is no forward button. The Room Devices render the web pages but you have no standard browser functionality (like typing in a URL, bookmark etc, but you do have a back button, which helps a lot). floating back button So lets take a look at the "map.php". map.php <!DOCTYPE html> <html> <style> body{ background-image: url('cisco.png'); background-size: cover; height: 100vh; padding:0; margin:0; } a { font-size: 3em; text-decoration: none; } </style> <a href='index.php'><<-Go back</a> <center> <h1> Here is a map of the building</h1> </center> <iframe src='' height='100%' width='100%'> </iframe> </html> The markup above will render a link to navigate back to the "index.php" and will also render an external page using an iframe. Map As you now see how this works in a simple form, you can start create your own signage flow or help customers understanding how they should get started. The burden is on the user that is creating this to get the flow properly in place like with any web site you are creating for whatever purpose. Note that you don´t have to create this from scratch if you already have a working site, just type in the URL to the site you want to open. The device needs to be able to access the page over the network. Example of rolling signage in NonInteractive mode using a macro Other Room Devices do not support Interactive mode, which means that the user cannot click links or interact with the web page. So this mode is for displaying either static content or over-time dynamic content, for example, information about on-going activities in the workplace or other useful information / statistics / recognitions etc.. NonInteractive mode works exactly the same way as the examples above but without the navigation options, if you touch the screen anywhere, it will wake up the system. You can customize the server side to show a slideshow / gif or video content. Macros can also customize the behavior to an extent where you can randomize the content on intervals the way you want. There are apps or other ways of creating automated slideshows without updating the link every time, but here is a macro example (see description after the code example): signageCarousel.js const xapi = require('xapi'); //1 const baseUrl = ''; const links = [ 'image1.jpg', 'image2.jpg', 'image3.jpg' ]; var slideshowInterval; var standbyInterval; let index = -1; //2 function resetStandbyTimer() { xapi.command('Standby ResetTimer', { Delay: 100 }); } //3 function show() { ++index; if (index >= links.length) { index = 0; } xapi.config.set('Standby Signage Url', baseUrl + links[index]); } //4 function init(state) { if (state == "Halfwake") { slideshowInterval = setInterval(show, 15000); standbyInterval = setInterval(resetStandbyTimer, 90000); } else { clearInterval(slideshowInterval); clearInterval(standbyInterval); } } //5 xapi.status.get('Standby State').then(init); xapi.status.on('Standby State', init); Description: 1: Define the base url and an array of "links", I have used images to create an image carousel (without any server side coding), the images are just stored on the web server. 2: resetStandbyTimer() will reset the standby timer to prevent the device from entering standby until someone puts it in standby or wakes it up from halfwake. This is not recommended as the device will constantly loop through the images forever and during weekends. But I use it in my example to show that it is possible. It is also possible to tweak the example to extend the standbytimer to only reset during office hours. 3: show() is the URL changer. It will loop through one of the links index each time it is called by the interval and set a new URL in the config which will take effect instantly (as the device is already in halfwake mode). 4: init() is the function that starts and stops the intervals depending on the standby state. If the standby state is halfwake, we will start two intervals, one to control the standbytimer and one to change the signage URLs on a given interval (15 seconds). 5: It will get the current status of the standby state and test the value through the init function. If the state is Off or the device is in Standby, nothing happens. If the state is in halfwake it will start the carousel right away. xapi.status.on will start a listener for change in the standby state and test the value through init every time. So if someone wakes up the system by tapping the touch panel the carousel will stop and start again when entering halfwake. Again, this may not work perfectly so feel free to change the behavior as you please. UI Extensions editor Just to make it clear, In-Room Control is now re-named to "UI Extensions", it still has the same basic functionality as before but with a few updates to the editor it-self. You can now select what kind of buttons you want to create and on a Webex Board there is a brand new button you can add, called "Web Apps". These are simply buttons for opening Web Apps from a connected Touch 10 or on-screen from a Webex Board. Note that the web app button is only supported on Webex Board for the time being because it has interactive mode. You can of course emulate the same thing using a macro and an action button on the other devices. Let´t take a quick look at creating a webapp button. Button type selection Having a button that natively opens a web app without the need for creating a supplementing macro is great for many use-cases where you only need to open a web app on demand. You can create many web app buttons to get a selection up there so, knock your self out! New webapp So what is special about this button is that you configure the URL it is supposed to open, directly in the UI Extensions button properties. Easy, right? :) This is all I need to do before pushing the button to the codec using the now highlighted blue button on the top menu. What about the icon you may wonder.. yes, and this is pretty cool. The device will look for a favicon on the web site its trying to open and set this as the button icon, and yes, you may choose your own icon by setting a specific URL to an image that will become the icon image. News webapp button That's it, now you press the button and it opens the bbc.com web site. Using this feature will enable the user to annotate on the web page as well (different from signage)! You can move this button around on the screen as well. Annotation / back button Creating your own buttons for web views on devices that do not have the web app option Access the web interface of the device. Now go into the UI Extensions editor (former In-Room Control editor) on the web interface. Integration > UI Extensions Editor UI Extensions Editor As you see in the screenshot above I have create one panel that should open the BBC News page. The button is configured to show "Out of Call" only. This is because Web Views only works out of call, so it does not make any sense to have the button display while in a call. Type in the name of the button and select an suitable icon and color. Tip: Select the globe icon if nothing else matches. The panel ID is set to "bbc" and is the event we will be listening for in our macro example. Once done, upload the button to the codec by pressing the highlighted "Up arrow" in the top bar. Creating the macro Please see below for a simple example to get make the buttons bring up the web view. Note that the xAPI command for Web View is the feature we use here. const xapi = require('xapi'); function open(url) { xapi.command('UserInterface WebView Display', { Url: url }) .catch(e => console.log('Not able to open url', e.toString())); } function guiEvent(event) { console.log('Pressed button', event.PanelId); // First button on your home page. change the panel id and url below to what you want // The panel id must match the id you typed in the inroom editor if (event.PanelId === 'bbc') { open(''); } // Second button on your home page else if (event.PanelId === 'office') { open(''); } } xapi.event.on('UserInterface Extensions Panel Clicked', guiEvent); The "open" function will open the URL that is passed to it from the guiEvent function depending on which button is pressed. At the very bottom an event listener has started to pick up the "Clicked" events from the panel that will contain our panel Id's that we setup earlier in the UI part. If the panelId is "bbc" we will open "" using the xapi.command('UserInterface WebView Display', {Url: url}) as you see above. Remember to activate the macro before you press the action button, and you are good to go! :) Note that it makes more sense displaying web pages that shows all the information needed in one page because on these systems you cannot navigate the web page. If you want to display a QR code or something similar this would work perfectly with this example. A button to clear the web view / or a timeout on the webview it self can also be useful to improve user experience. Compatibility Since the browser is based on a standard Chromium browser, most of the features you expect from a modern desktop browser is available. Features such as HTML5, EcmaScript 6, CSS3, web fonts, multi-touch, SVG, canvas, iframes, web sockets, web assembly, web workers and more are available. Note that the following features are currently NOT supported: Some of the above may be added later, but no guarantees can be provided now. How many windows / tabs are supported? Only one web tab / window is supported. If a web page tries to open a page in a new window or tab, it will replace the existing page. Multimedia Standard video codecs are supported, such as WebM and Mpeg4. Decoding is done through software. It is not recommended to go beyond 720p resolution as this will lead to choppy performance! Multimedia is supported What about audio / volume? The volume follows the volume setting of the video system. For digital signage, the audio is "Off" by default to avoid unwanted noise by accident, but it can be controlled with the following configuration. xConfiguration Standby Signage Audio: <on/off> You can of course enforce volume and mute control on top of this by using JavaScript audio frameworks. Browser info: The web engine is based on Chromium / Qt WebEngine with V8 JavaScript. The Chromium version is upgraded every time Cisco updates the Qt version in RoomOS/CE, meaning it will not be as up-to-date as your Chrome laptop version, but will be updated periodically. You can inspect the version at any time by looking at the user agent, i.e. by visiting on your device. User-agent Is user data persisted? For digital signage, web engine is running in persistent ("desktop browser") mode, meaning that cookies, local storage etc. are saved to disk and persisted across reboots and even upgrades. This means its possible to have persisted logins for team dashboards etc. Are touch events supported (developer related)? Yes, the Webex Board supports up to 10 simultaneous touch events, using ontouchstart, ontouchmove and ontouchend. The traditional onclick event is also supported but not recommended since it incurs a slight delay to detect gestures. Note that the ordering of touch events is not stable so use the touch event "identifier" to keep track of simultaneous touches. How to prevent the standard zoom gestures in the rendered web views? Two finger zoom is default of accessibility and convenience, but not always wanted, for example in immersive apps, such as Google Maps, whiteboards and games where you need more control. You can overwrite this with preventDefault: document.querySelector('.myCanvas').ontouchstart = (e) => { e.preventDefault(); // .. my action } // similar for ontouchmove and ontouchend What is the viewport / screen size? The logical viewport is 1920 pixels wide, and 1080 pixels high minus whatever is used for the toolbar (typically less than 200 pixels). The actual rendering is done on a 4k canvas (3840 x 1260, similar to Apple´s Retina mechanism, so text and images will be crisp. Be sure to provide high resolution images and assets for the optimal user experience. Developers can also modify the viewport meta tag, i.e.: <meta name="viewport" content="width=960, initial-scale=1"> Are JavaScript dialogs available? Yes, most of the JavaScript dialogs such as alerts, prompt and confirm works like on a desktop and is implemented using the native dialogs of the video system. Uploading and downloading dialogs are not supported! What fonts are available? Currently only the system font of RoomOS / CE (sans serif). Web fonts are supported though so third party app developers can add their own fonts as needed with CSS, i.e.: @font-face { font-family: handwriting; src: url(handwriting.woff); } div { font-family: handwriting; } Login and authorization One of the most challenging aspects for a web app on a shared video device is the user login. We cannot just store the users credentials like on a personal device, since it can be used by anyone, and entering the username and password on a large-screen, soft keyboard device is both annoying and unsafe.We will strive towards a solution that makes this easy and safe in the future. In the meantime, the model solution is to use a second, personal device for authentication and authorization. User flow: The Microsoft Authenticator for Office 365 an example of how this can be implemented in a way that is convenient, fast and safe for the user. What animations are supported? Both CSS transitions and web animations are supported and hardware accelerated whenever possible. This typically means the transform and opacity CSS property. Try to avoid doing animations that requires DOM or layout operations. How to improve performance? The web engine has the difficult task of running modern, full scale web content on a 4K screen while having lower priority than the main video features. This means it can sometimes struggle with heavy web sites such as Google Maps 3D and similar. But there are many things a developer can do to improve performance. This is worthy of its own guide, but here are a few things you can try: Can I create offline applications? Yes. Web workers are supported, and can be used to speed up initial loading of heavy web apps. Note that currently the web views are not available if the device does not have network, so real offline apps are not possible. Keyboard input The RoomOS / CE soft keyboard behaves similarly to the touch keyboards on Android and iOs, and pops up any time an input field gets focus. The content also scrolls up if needed so both the input field and keyboard are visible. It does not support specialized formats such as numeric, calendar and color picker at the moment. A vertical soft keyboard does not encourage a lot of text input and provides little privacy, so keep that in mind. Localization The web engine sends the language header of the current language in each HTTP requests, i.e. Accept-Language: fr for French. A web app can then translate the content to the current language, either server side by looking at the header, or in JavaScript by querying useragent.language in the browser. Non-fullscreen windows? Currently only fullscreen web views are supported. In the future we may support different types such as web dialogs and side-bars. Multiple screens? For digital signage, content is cloned to the extra screens. A web view cannot be logically stretched across multiple screens. In other cases than signage, only the primary monitor will display the web view. Best practices Writing web apps for a shared device with a huge touch screen comes with its own set of challenges. A dedicated best practice manual may be offered later, but here are a couple of pointers: Style guide As a third party developer you do of course have the tools and freedom to design the web content exactly as you like or to match your company's visual profile. If you prefer something that feels native and in line with the Cisco design language, you can find everything you need at. As well as styles and guide lines, this web site contains CSS, assets, fonts and icons and component support for popular web frameworks. Can the content access the xAPI? At the moment, not directly. The Cisco video systems provide rich and powerful API integrations through the xAPI, such as making calls, starting presentations, counting the number of people in the room etc. Currently a web view does not have direct access to the xAPI, but it can access it the same way as other integrations, provided that credentials to the video systems are available. Alternatives include local REST APIs (on premise deployments), HTTP feedback (web hooks), cloud APIs or direct web socket communication. For more info about these, see separate RoomOS / CE developer documentation. Be careful about exposing credentials in your client side code, though, and consider going through your web app's server. What about non-touch / non-interactive devices? At the moment, the only supported device that has touch screen capability is the Webex Board, but all the new Cisco video devices such as Room Kit, Room Kit Mini, Room 55 etc also support web view. Page lifecycle: As soon as the user hits the home button, the state of the web page is lost. When the user starts the web activity again, the same url is reloaded. You can save the current state of the page and and re-apply it by always saving to local storage (or session storage), then fetching those state values whenever the page loads. Remote developer console xConfiguration WebEngine RemoteDebugging: On The remote developer console is by far the most important and powerful tool available to third-party developers. This is a standard Chrome dev console, that you can run remotely on your own laptop to inspect what is happening in the web engine. See the log console and manipulate the content live just like with local web development. When this is enabled all the web views will display a prominent warning that they may be monitored as a privacy warning. Accessing the remote debugger via a browser is done like this when remote debugger is enabled (the URL is also listed on the device screen together with the warning): http://<codecip>:9222 Remote debugger is only supported with Google Chrome browser and Chromium Browser. Using this tool I can troubleshoot failing functions or check elements that are not displayed correctly in the web view. In the above screenshot I can view the page that is rendered on the device from my laptop. This tool should be used for debugging and development only. Remember to turn it off when done. System Resources The web engine has a lower priority than the main video features and is restricted. Currently it is limited to 1 CPU core and 650 MB of memory (excluding GPU usage). If the web page requires more memory than allowed, Chromium will try to optimize usage with the memory pressure handler. Failing this the web view will eventually be terminated and show an error page. The web view may also be terminated if the video system is running on low memory in general. For Room Kit Pro there are 6 cores and 8 GB of memory but the restriction is currently the same as the other devices. Special thanks to Tore Bjolseth for all the details. This looks interesting! Will it be implemented on Webex desk series devices in time? I would like to see a web app that opens the CUCM self care portal for on premisis or hybred devices. Guess your note about Login and authorization could be an obsticle to this? Thanks for info! These WebEngine features look great but virtually everything I want to connect to is in the cloud. That means we need proxy support to get there. Are there thoughts of implementing proxy support for this purpose? Currently there is "HTTP proxy support" but it's listed as only being used to get to Cisco's cloud for device registration. We need proxy support for WebEngine for devices that are connected on prem. Magnus, this looks good. One question: I´m currently trying to implement a solution via WebEngine to run some tutorial videos. The video is stored on vBrickrev platform and is accessible from a Webex Room Kit with CE9.12.3 version running. Autoplay and fullscreen display for the video works well, but audio is muted from Chromium browser. I found out that this feature is disabled from Chromium itself. As the Webex Room series does not provide interactivity with the screen or any input method, how can I enable audio for autoplay videos? It seems that override of the Chromium code would be needed. I didn´t find any Javascript code to implement this in a macro directly. Any ideas or thoughts? Regards Christoph
https://community.cisco.com/t5/collaboration-voice-and-video/a-dive-into-web-engine-and-the-new-ui-extensions-editor-digital/ba-p/3947191
CC-MAIN-2021-31
refinedweb
5,091
61.67
Simple order making system This project received 5 bids from talented freelancers with an average bid price of $309 USD.Get free quotes for a project like this Skills Required Project Budget$30 - $250 USD Total Bids5 Project Description I need someone to develop simple web app in Vaadin 7.x (preferably) or in Ext JS 4.x with PHP as back end. It must be developed according to modern software design principles MVC, or MVP. This is simple order placing and tracking system with some parts already built. These are main details that need to be implemented: - Read and display one table from MS SQL (articles). - After clicking on one row in table select from MS SQL and display sub table (qty in different warehouses). - Doubleclicking, or pressing enter while item in main table is selected adds that item to third (order) table. Repeating adds one more item. - Quantity in order table should be editable by hand, e.g it should be text field and not display field. - Clicking on Place order button would save order in MS SQL, create .xlsx or .ods file with order details and send by email. - After receiving ordered goods, another employee would open Orders table, click on row to select order and get Order Items - In Order items he would be able to enter quantity of received goods and also to add new items, not ordered. - After clicking on save, order would be saved in another MS WQL table, and new .xlsx or .ods file would be created and sent by email. In total: 5 or 6 editable tables. All tables should be sortable by all columns. All tables should have “Export to XLSX or ODS”. After accepting bid, I would send specification of MS SQL tables and basic form and table blueprints. All code should be well organized and in appropriate namespaces so that I can copy it
https://www.freelancer.com/projects/PHP-Java/Simple-order-making-system/
CC-MAIN-2016-44
refinedweb
316
74.08
> lwip-1.3.0.rar > sys_arch.c /** * @file - sys_arch.c * System Architecture support routines for Stellaris devices. * */ /* * * */ /* * Copyright (c) 2008 Luminary Micro, Inc. * */ #include "lwip/opt.h" #include "lwip/sys.h" /* * Luminary Micro DriverLib Header Files required for this interface driver. * */ #include "../../../../hw_memmap.h" #include "../../../../hw_types.h" #include "../../../../hw_ints.h" #include "../../../../src/interrupt.h" #if SYS_LIGHTWEIGHT_PROT /* * This function is used to lock access to critical sections when lwipopt.h * defines SYS_LIGHTWEIGHT_PROT. It disables interrupts and returns a value * indicating the interrupt enable state when the function entered. This * value must be passed back on the matching call to sys_arch_unprotect(). * * @return the interrupt level when the function was entered. * */ sys_prot_t sys_arch_protect(void) { tBoolean bRet = 1; bRet = IntMasterDisable(); return((sys_prot_t)bRet); } /* * This function is used to unlock access to critical sections when lwipopt.h * defines SYS_LIGHTWEIGHT_PROT. It enables interrupts if the value of the lev * parameter indicates that they were enabled when the matching call to * sys_arch_protect() was made. * * @param lev is the interrupt level when the matching protect function was * called * */ void sys_arch_unprotect(sys_prot_t lev) { /* * Only turn interrupts back on if they were originally on when the * matching sys_arch_protect() call was made. * */ if(!(lev & 1)) { IntMasterEnable(); } } #endif /* SYS_LIGHTWEIGHT_PROT */
http://read.pudn.com/downloads119/sourcecode/internet/tcp_ip/507869/lwip-1.3.0/ports/stellaris/sys_arch.c__.htm
crawl-002
refinedweb
197
51.14
getrlimit, setrlimit, prlimit − get/set resource limits #include <sys/time.h> The getrlimit() and setrlimit() system calls get and set resource limits respectively. Each resource has an associated soft and hard limit, as defined by the rlimit structure: − rlim_cur. (This strangeness occurs because negative numbers cannot be specified as resource limit values, since they typically have special meanings. For example, RLIM_INFINITY typically is the same as −1.) Linux-specific prlimit() system call combines and extends the functionality of setrlimit() and getrlimit(). It can be used to both set and get the resource limits of an arbitrary process.. On success, these system calls return 0. On error, −1 is returned, and errno is set appropriately. The prlimit() system call is available since Linux 2.6.36. Library support is available since glibc 2.13. getrlimit(), setrlimit(): SVr4, 4.3BSD, POSIX.1-2001.. A child process created via fork(2) inherits its parent’s resource limits. Resource limits are preserved across execve(2).(). In older Linux kernels, the SIGXCPU and SIGKILL signals delivered when a process encountered the soft and hard RLIMIT_CPU limits were delivered one (CPU) second later than they should have been. This was fixed in kernel 2.6.8. −−>rlim_cur was greater than rlim−>rlim_max. The program below demonstrates the use of prlimit(). #define _GNU_SOURCE #define _FILE_OFFSET_BITS 64 #include <stdio.h> #include <time.h> #include <stdlib.h> #include <unistd.h> #include <sys/resource.h> } while (0) int main(int argc, char *argv[]) { struct rlimit old, new; struct rlimit *newp; pid_t pid; if (!(argc == 2 || argc == 4)) { fprintf(stderr, "Usage: %s <pid> [<new−soft−limit> " "<new−hard−limit>]) == −1) errExit("prlimit−1"); printf("Previous limits: soft=%lld; hard=%lld\n", (long long) old.rlim_cur, (long long) old.rlim_max); /* Retrieve and display new CPU time limit */ if (prlimit(pid, RLIMIT_CPU, NULL, &old) == −1) errExit("prlimit−2"); printf("New limits: soft=%lld; hard=%lld\n", (long long) old.rlim_cur, (long long) old.rlim_max); exit(EXIT_FAILURE); }) This page is part of release 3.53 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at−pages/.
http://man.linuxtool.net/centos7/u3/man/2_getrlimit.html
CC-MAIN-2019-30
refinedweb
352
53.07
Quoting Andy Lutomirski (luto@MIT.EDU):> Every now and then, someone wants to let unprivileged programs change> something about their execution environment (think unsharing namespaces,> changing capabilities, disabling networking, chrooting, mounting and> unmounting filesystems). Whether or not any of these abilities are good> ideas, there's a recurring problem that gets most of these patches shot> down: setuid executables.> > The obvious solution is to allow a process to opt out of setuid> semantics and require processes to do this before using these shiny new> features. [1] [2]> > But there's a problem with this, too: with LSMs running, execve can do> pretty much anything, and even unprivileged users running unprivileged> programs can have crazy security implications. (Take a look at a> default install of Fedora. If you can understand the security> implications of disabling setuid, you get a cookie. If you can figure> out which programs will result in a change of security label when> exec'd, you get another cookie.)> > So here's another solution, based on the idea that in a sane world,> execve should be a lot less magical than it is. Any unprivileged> program can open an executable, parse its headers, map it, and run it,> although getting all the details right is tedious at best (and there's> no good way to get all of the threading semantics right from userspace).> > Patch 1 adds a new syscall execve_nosecurity. It does an exec, but> without changing any security properties. This means no setuid, no> setgid, no LSM credential hooks (e.g. no SELinux type transitions), and> no ptrace restrictions. (You have to have read access to the program,> because disabling security stuff could allow someone to ptrace a program> that they couldn't otherwise ptrace.) This shouldn't be particularly> scary -- any process could do much the same thing with open and mmap.> (You can easily shoot yourself in the foot with this syscall -- think> LD_PRELOAD or running some program with insufficient error checking that> can get subverted when run in the wrong security context. So don't do> that.)> > Patch 2 adds a prctl that irrevocably disables execve. Making execve do> something different that could confuse LSMs is dangerous. Turning the> whole thing off shouldn't be. (Of course, with execve disabled, you can> still use execve_nosecurity. But any program that does that should take> precautions not to shoot itself in the foot.) (In a future revision,> this should probably be a new syscall.)> > Sadly, programs that have opted out of execve might want to use> subprocesses that in turn run execve. This will fail. So patch 3> (which is ugly, but I don't see anything fundamentally wrong with it)> allows processes to set a flag that turns execve into execve_nosecurity.> This flag survives exec. Of course, this could be used to subvert> setuid programs, so you can't set this flag unless you disable ordinary> exec first.> > [1] Unprivileged:> [2] securebit approach: responses for a month after this was sent. Really, thanks, I doappreciate the work at another approach.I'll be honest, I prefer option [1]. Though I think it's reasonableto require privilege for prctl(PR_SET_NOSUID). Make it a separatecapability, and on most systems it should be safe to have a filesitting in /bin with cap_set_nosuid+pe. If OTOH you know you havelegacy or poorly coded privileged programs which would not be safebc they don't verify that they have the needed privs, you just don'tprovide the program to do prctl(PR_SET_NOSUID) for unprivileged users.( I did like using new securebits as in [2], but I prefer theautomatic not-raising-privs of [1] to simply -EPERM on uid/gidchange and lack kof checking for privs raising of [2]. )Really the trick will be finding a balance to satisfy those wantingthis as a separate LSM, without traipsing into LSM stacking territory.I myself think this feature fits very nicely with established semantics,but not everyone agrees, so chances are my view is a bit tainted, andwe should defer to those wanting this to be an LSM.Of course, another alternative is to skip this feature altogether andpush toward targeted capabilties. The problem is that path amountsto playing whack-a-mole to catch all the places where privilege mightleak to a parent namespace, whereas [1] simply, cleanly cuts them alloff at the source.thanks,-serge
http://lkml.org/lkml/2010/4/19/231
CC-MAIN-2015-11
refinedweb
723
62.38
gnutls_x509_crt_get_dn_by_oid — API function #include <gnutls/x509.h> should contain a gnutls_x509_crt_t structure holds an Object Identified in null terminated string In case multiple same OIDs exist in the RDN, this specifies which to send. Use (0) to get the first one. If non−zero returns the raw DER data of the DN part. a pointer where the DN part will be copied (may be null). initially holds the size of buf This function will extract the part of the name of the Certificate subject specified by the given OID. The output, if the raw flag is not used, will be encoded as described in RFC4514. Thus a string that is ASCII or UTF−8 −− in hex format current index.:
https://man.linuxexplore.com/htmlman3/gnutls_x509_crt_get_dn_by_oid.3.html
CC-MAIN-2021-31
refinedweb
119
73.78
An Intro to Dapr with Spring Cloud Gateway Last modified: June 2, 2022 1. Overview In this article, we'll start with a Spring Cloud Gateway application and a Spring Boot application. Then, we'll update it to use Dapr (Distributed Application Runtime) instead. Finally, we'll update the Dapr configuration to show the flexibility that Dapr provides when integrating with cloud-native components. 2. Intro to Dapr With Dapr, we can manage the deployment of a cloud-native application without any impact on the application itself. Dapr uses the sidecar pattern to off-load deployment concerns from the application, which allows us to deploy it into other environments (such as on-premise, different proprietary Cloud platforms, Kubernetes, and others) without any changes to the application itself. For more details, check out this overview on the Dapr website. 3. Create Sample Applications We'll start by creating a sample Spring Cloud Gateway and Spring Boot application. In the great tradition of “Hello world” examples, the gateway will proxy requests to a back-end Spring Boot application for the standard “Hello world” greeting. 3.1. Greeting Service First, let's create a Spring Boot application for the greeting service. This is a standard Spring Boot application with spring-boot-starter-web as the only dependency, the standard main class, and the server port configured as 3001. Let's add a controller to respond to the hello endpoint: @RestController public class GreetingController { @GetMapping(value = "/hello") public String getHello() { return "Hello world!"; } } After building our greeting service app, we'll start it up: java -jar greeting/target/greeting-1.0-SNAPSHOT.jar We can test it out using curl to return the “Hello world!” message: curl 3.2. Spring Cloud Gateway Now, we'll create a Spring Cloud Gateway on port 3000 as a standard Spring Boot application with spring-cloud-starter-gateway as the only dependency and the standard main class. We'll also configure the routing to access the greeting service: spring: cloud: gateway: routes: - id: greeting-service uri: predicates: - Path=/** filters: - RewritePath=/?(?<segment>.*), /$\{segment} Once we build the gateway app, we can start the gateway: java -Dspring.profiles.active=no-dapr -jar gateway/target/gateway-1.0-SNAPSHOT.jar We can test it out using curl to return the “Hello world!” message from the greeting service: curl 4. Add Dapr Now that we have a basic example in place, let’s add Dapr to the mix. We do this by configuring the gateway to communicate with the Dapr sidecar instead of directly with the greeting service. Dapr will then be responsible for finding the greeting service and forwarding the request to it; the communication path will now be from the gateway, through the Dapr sidecars, and to the greeting service. 4.1. Deploy Dapr Sidecars First, we need to deploy two instances of the Dapr sidecar – one for the gateway and one for the greeting service. We do this using the Dapr CLI. We'll use a standard Dapr configuration file: apiVersion: dapr.io/v1alpha1 kind: Configuration metadata: name: daprConfig spec: {} Let's start the Dapr sidecar for the gateway on port 4000 using the dapr command: dapr run --app-id gateway --dapr-http-port 4000 --app-port 3000 --config dapr-config/basic-config.yaml Next, let's start the Dapr sidecar for the greeting service on port 4001 using the dapr command: dapr run --app-id greeting --dapr-http-port 4001 --app-port 3001 --config dapr-config/basic-config.yaml Now that the sidecars are running, we can see how they take care of intercepting and forwarding requests to the greeting service. When we test it out using curl, it should return the “Hello world!” greeting: curl Let's try the same test using the gateway sidecar to confirm that it also returns the “Hello world!” greeting: curl What's going on here behind the scenes? The Dapr sidecar for the gateway uses service discovery (in this case, mDNS for a local environment) to find the Dapr sidecar for the greeting service. Then, it uses Service Invocation to call the specified endpoint on the greeting service. 4.2. Update Gateway Configuration The next step is to configure the gateway routing to use its Dapr sidecar instead: spring: cloud: gateway: routes: - id: greeting-service uri: predicates: - Path=/** filters: - RewritePath=//?(?<segment>.*), /v1.0/invoke/greeting/method/$\{segment} Then, we'll restart the gateway with the updated routing: java -Dspring.profiles.active=with-dapr -jar gateway/target/gateway-1.0-SNAPSHOT.jar We can test it out using the curl command to once again get the “Hello world” greeting from the greeting service: curl When we look at what's happening on the network using Wireshark, we can see that the traffic between the gateway and the service goes through the Dapr sidecars. Congratulations! We have now successfully brought Dapr into the picture. Let's review what this has gained us: The gateway no longer needs to be configured to find the greeting service (that is, the port number for the greeting service no longer needs to be specified in the routing configuration), and the gateway no longer needs to know the details of how the request is forwarded to the greeting service. 5. Update Dapr Configuration Now that we have Dapr in place, we can configure Dapr to use other cloud-native components instead. 5.1. Use Consul for Service Discovery Let's use Consul for Service Discovery instead of mDNS. First, we need to install and start Consul on the default port of 8500, and then update the Dapr sidecar configuration to use Consul: apiVersion: dapr.io/v1alpha1 kind: Configuration metadata: name: daprConfig spec: nameResolution: component: "consul" configuration: selfRegister: true Then we'll restart both Dapr sidecars with the new configuration: dapr run --app-id greeting --dapr-http-port 4001 --app-port 3001 --config dapr-config/consul-config.yaml dapr run --app-id gateway --dapr-http-port 4000 --app-port 3000 --config dapr-config/consul-config.yaml Once the sidecars are restarted, we can access the Services page in the consul UI and see the gateway and greeting apps listed. Notice that we did not need to restart the application itself. See how easy that was? A simple configuration change for the Dapr sidecars now gives us support for Consul and, most importantly, with no impact on the underlying application. This differs from using Spring Cloud Consul, which requires updating the application itself. 5.2. Use Zipkin for Tracing Dapr also supports integration with Zipkin for tracing calls across applications. First, install and start up Zipkin on the default port of 9411, and then update the configuration for the Dapr sidecar to add Zipkin: apiVersion: dapr.io/v1alpha1 kind: Configuration metadata: name: daprConfig spec: nameResolution: component: "consul" configuration: selfRegister: true tracing: samplingRate: "1" zipkin: endpointAddress: "" We'll need to restart both Dapr sidecars to pick up the new configuration: dapr run --app-id greeting --dapr-http-port 4001 --app-port 3001 --config dapr-config/consul-zipkin-config.yaml dapr run --app-id gateway --dapr-http-port 4000 --app-port 3000 --config dapr-config/consul-zipkin-config.yaml Once Dapr is restarted, you can issue a curl command and check out the Zipkin UI to see the call trace. Once again, there's no need to restart the gateway and greeting service. It requires only an easy update to the Dapr configuration. Compare this to using Spring Cloud Zipkin instead. 5.3. Other Components There are many components that Dapr supports to address other concerns such as security, monitoring, and reporting. Check out the Dapr documentation for a full list. 6. Conclusion We have added Dapr to a simple example of a Spring Cloud Gateway communicating with a back-end Spring Boot service. We've shown how to configure and start the Dapr sidecar and how it then takes care of cloud-native concerns such as service discovery, communication, and tracing. Although this comes at the cost of deploying and managing a sidecar application, Dapr provides flexibility for deployment into different cloud-native environments and cloud-native concerns without requiring changes to the applications once the integration with Dapr is in place. This approach also means that developers don't need to be encumbered with cloud-native concerns as they are writing the code, which frees them up to focus on business functionality. Once the application is configured to use the Dapr sidecar, different deployment concerns can be addressed without any impact on the application – no need for re-coding, re-building, or re-deploying applications. Dapr provides a clean separation between application and deployment concerns. As always, the complete code for this article can be found over on GitHub.
https://www.baeldung.com/dapr-spring-cloud-gateway
CC-MAIN-2022-27
refinedweb
1,449
51.99
colors¶ This page contains tutorials about the colors package. Do’s and Don’ts¶ When utilizing a color constant, you must not change it’s RGBA values as that will change the value of the constant itself: from colors import RED print([x for x in RED]) RED.r = 128 In the above example, if you reload the plugin, the value for RED.r has been permanently changed. If you wish to get a different color, use the following instead: from colors import Color from colors import RED # You can just set the color directly using the Color object my_red = Color(128, 0, 0, 255) # Or, you can utilize RED itself to create a different value my_red = Color(*RED) my_red.r = 128 Getting a different alpha value is a little bit easier: from colors import RED # Again, you DO NOT want to use the following RED.a = 128 # Instead, use the "with_alpha" method of the Color object my_red = RED.with_alpha(128)
http://wiki.sourcepython.com/developing/module_tutorials/colors.html
CC-MAIN-2022-27
refinedweb
161
58.32
This: - using dynamic send ports, the destination URI and the configuration of the send port can be set programatically in the orchestration for every outgoing message. This method has the advantage that no ports have to be pre-created. - using role-links and parties. For each party you need to pre-create and configure a pyshical send port. You will have pretty much a party per destination. You enlist the parties in the appropriate role. Then, in the orchestration the only thing that you need to do is set the party associated with the role-link. The physical send port of the party associated with the role-link will be used to process the outgoing message. Thanks for posting this information. My next question is this; I plan to drop an xml file into one of about 160 document libraries depending on what the Orchestration decides. I’ve found that in order for InfoPath 2003 to recognise the xml I have to create the InfoPath form first based on the schema, then publish to a document library on Share Point. Would I have to publish the same form 160 times, or is there a quicker way to do this? Do I have to publish the same form 160 times? No. You can use the ‘Yes’ option instead of ‘Yes (InfoPath Form Library)’, details below. You will still need some script to create the document libraries because the adapter does not create document libraries or folders. WSS adapter supports 2 models for integration with InfoPath: the adapter implemented integration with InfoPath (works with any document library not only with Form Libraries) when ‘Microsoft Office Integration’ is set to ‘Yes’. When using ‘Yes (InfoPath Form Library)’, there is one InfoPath solution per WSS form library and it’s stored in a hidden folder inside the form library. All the documents stored in the form library must have the same XSD schema and they all use the same InfoPath solution. These restrictions don’t apply to the next option. When using ‘Yes’ the documents in a document library can use any InfoPath solution and they don’t have to have the same XSD schema. All your solutions can be stored in a primary document library (and optionally fallback document library). You will have to create a document library (call it Solutions) that has a Namespace column (single line of text) and upload all your InfoPath solutions in this document library. For each InfoPath solution, edit the Namespace column to specify the target namespace (defined in XSD schema) of the documents that can be opened with that solution. When you create a send port, define the Microsoft Office Integration options so that the adapter will search into your Solutions document library for the appropriate InfoPath XSN solution that can be used to open your XML document. I’ve created an InfoPath form using the XSD from my Biztalk project and published it to a folder called ‘InfoPathSolutions’ under the following URL:”>. I want to use this as the template for the XML that comes in via Biztalk. Within Biztalk I’ve created a dynamic send port and configured it in an Expression shape. In there I’ve set the following: WSS.ConfigOfficeIntegration = yes WSS.Url = WSS.ConfigTemplatesDocLib = WSS.ConfigTemplatesNamespaceCol = Namespace I’ve then created another site underneath my home site called. Within this I’ve created a document library called ‘Expenses’ and I want to drop XML files here and use the InfoPath template to view them. But I keep getting an error in HAT saying that it can’t find the folder I’ve specified as storing the templates. I’ve tried different combinations of url / non – url but it’s almost as though I can’t store the templates on a different site to the xml files. Is this true? Mark. Yes it’s true. The templates must exist on the same site as the XML document. Also you need to specify the name of the document library and not the full/relative URL. When creating WSS adapter ports you need to pay attention to the field names, if they don’t mention URL then you are required to enter a name. Some fields require names others require relative or full URLs. Hi… I´m trying to communicate BizTalk – Sharepoint following the steps that you show in your video… the following problem appears when the receive location poll to sharepoint: The adapter "Windows SharePoint Services" raised an error message. Details "Client found response content type of ‘text/html; charset=utf-8’, but expected ‘text/xml’. any help? Thank you. This happens when the web service is not found or when it doesn’t run for some reason. Basically, BizTalk runtime received back an HTML page with the error instead of XML. Did you install and configure the web service? (in BizTalk Setup under Additional Software, in BizTalk Configuration under SharePoint Adapter). If yes, make sure that your receive location is using the same port number as the II site where you installed the web service. Open the web service web.config (to find it, in IIS select BTSharePointAdapterWS, right click and select open) and remove the <remove name="Documentation" /> line (or something like that) and then try browsing to the web service to see if it’s working. I am facing the same problem with sharepoint adapter.I tried to doing it above. It didn’t work. can anybody please help me out in this Did you install and configure the web service? Did you check your receive location is using the same port number as the II site where you installed the web service? Did you browse with IE to the web service and saw that it works? If all of these worked, what are the errors that you see in the event viewer or in BizTalk MMC console for the outgoing message? If some of the above didn’t work, what was the error that you got back? Hello Adrian! I’ve been trying to set the dynamic address for the WSS adapter, but at runtime the adapter can’t find the document library. Here is the URL for the document library: In SharePoint, I have changed the Shared Documents document library name to AIBErrors. I have 6 "System Source" folders in the AIBErrors doc library, and 3 "Error type" folders under each of those. I am trying to dynamically direct files to the correct folder based on source and type. Here is the dynamic configuration for setting the destination: SendCbeErrorToSharepoint(Microsoft.XLANGs.BaseTypes.Address) = "wss://servername:27298/sites/AIBErrorHandling/AIBErrors/" + cbeError.errSystem + "/" + cbeError.errType; Here is the error I get when I run the application: [Microsoft.SharePoint.SPException] The virtual server that is referenced here is not in the config database. This error was triggered by the Windows SharePoint Services receive location or send port with URI wss://servername:27298/sites/AIBErrorHandling/AIBErrors/Agile/Application. Windows SharePoint Services adapter event ID: 12310 I have tried hard-coding the wss uri, as well as trying to create a different top level document library as a destination. No success in either case… In your video you use the path: "wss://demobt/sites/WSSAdapterWalkthrough/Lists/Tasks" In all of the examples I’ve seen online for documents they say to use the format: "’wss://ServerName/sites/MySite/MyDocumentLibrary/" Is there a prefix like "Lists" that should preface the actual doc library name? TIA for your help! Hello Adrian- in the 04-WSSAdapter-PropsInOrchestration.wmv video you demonstrated how to create a task by filling its title, status and priority . I want to know how do i fill the "Assigned To" field for a new task dynamically from BizTalk. i used the following string but it gave me an error: Message_Task(WSS.ConfigPropertiesXml)="<ConfigPropertiesXml><PropertyName1>Title</PropertyName1><PropertySource1>Purchase order trial Task</PropertySource1><PropertyName2>Assigned To</PropertyName2><PropertySource2>MOL\Administrator</PropertySource2><PropertyName3>Status</PropertyName3><PropertySource3>Not Started</PropertySource3><PropertyName4>Priority</PropertyName4><PropertySource4>High</PropertySource4></ConfigPropertiesXml>"; any suggestions ? Take out the space in the column name
https://blogs.msdn.microsoft.com/ahamza/2007/03/07/is-there-a-way-to-configure-one-send-port-to-send-a-message-to-a-document-library-based-on-a-parameter/
CC-MAIN-2017-47
refinedweb
1,342
54.52
29 June 2011 17:15 [Source: ICIS news] LONDON (ICIS)--Shell will continue running its 5.5m tonne/year refinery in Hamburg-Harbug, Germany, until March 2013, almost a year longer than planned, the energy and chemicals major said on Wednesday. Meanwhile, talks to sell the refinery’s base oil operations are continuing, Shell added without disclosing details. Shell said in January it plans to sell the base oil assets and convert the site into a terminal for oil products after a two-year effort to sell the refinery failed. Under those plans, Shell was to close the refinery in the second quarter of 2012 and to complete the conversion of the site into a terminal in the course of 2012. Shell said it obtained approval from authorities to continue running the refinery for an additional 10 months to March 2013. A further extension will not be possible, it added. Last year, Shell sold its refinery at Heide, near ?xml:namespace> Shell has also sold its Stanlow refinery in the UK, and it is converting a refinery in
http://www.icis.com/Articles/2011/06/29/9473769/shell-extends-operations-at-hamburg-refinery-to-march.html
CC-MAIN-2014-35
refinedweb
178
60.75
Bug Description I'm compiling inkscape aqua using macports. I'm using variants +aqua +no_x11, and also goes around the issue described in https:/ When using "save" directly, all is fine, but as soon as I try to exit from the "save as..." GUI, with save or cancel, I get the following crash: Program received signal EXC_BAD_ACCESS, Could not access memory. Reason: 13 at address: 0x0000000000000000 0x00007fff863d5120 in objc_msgSend () (gdb) bt #0 0x00007fff863d5120 in objc_msgSend () #1 0x00007fff88039504 in _DPSNextEvent () #2 0x00007fff880387a9 in -[NSApplication nextEventMatchi #3 0x0000000101e05fcd in poll_func () #4 0x00000001022a8fa8 in g_main_ #5 0x00000001022a92a5 in g_main_loop_run () #6 0x0000000101a029f0 in gtk_main () #7 0x00000001000306b0 in sp_main_gui () #8 0x000000010002fd2e in main () As requested: OS X 10.6.6, intel gtk2 @2.22.1 gtkmm @2.22.0 glib2 @2.26.1 glibmm @2.24.2 It seems related to the 'save bug' described in the following thread: http:// The crash report attached to that thread has the exact same backtrace. I turned GDK_WINDOWING_ https:/ Reproduced with Inkscape 0.48+devel r10101 on OS X 10.5.8 (i386), gtk2 @2.22.1_ Program received signal EXC_BAD_ACCESS, Could not access memory. Reason: KERN_INVALID_ 0x9254b818 in objc_msgSend_fpret () (gdb) bt #0 0x9254b818 in objc_msgSend_fpret () #1 0x92dd9dcf in _DPSNextEvent () #2 0x92dd8f88 in -[NSApplication nextEventMatchi #3 0x0246b457 in poll_func () #4 0x02f1642f in g_main_ #5 0x02f16887 in g_main_loop_run () #6 0x017a6e71 in gtk_main () #7 0x011bcd4b in Gtk::Main::run () #8 0x00004e6c in ~vector [inlined] () at stl_vector.h:986 #9 sp_main_gui (argc=1, argv=0xbffff3a8) at main.cpp:993 #10 0x00003a66 in start () (gdb) quit Raising bug status to 'Critical' - this is a major blocker IMHO for GTK+/Quartz based Inkscape ports to Mac OS X. Please revert if you don't agree. > I turned GDK_WINDOWING_ > seems that I am able to go past this bug, Would you be willing to share details or attach diffs so that others can test the same set of changes (without having to do (duplicate) research about it)? The crash is only triggered when using the commands from the menubar: using the keyboard shortcuts ('Shift+Ctrl+S' "Save as…", 'Shift+Ctrl+Cmd+S' "Save a copy as…') works as expected and without crash. (tested with unchanged build r10101 (no local patches) using @2.22.1_ <off-topic> Unexpectedly, the key 'Cmd' acts the same as 'Alt' under X11, whereas the real 'option/alt' key doesn't seem to be recognized by Inkscape. </off-topic> Sure can, but it may take a little while. I have a few other modifications in a local branch I need to clean up and then share. Here is the patch to remove all trace of mac integration. Ah, that's the "brut force" way ;) I had hoped that you had figured out the crucial point (or file) to undef GDK_WINDOWING_ #ifdef GDK_WINDOWING_ (…) #endif /* GDK_WINDOWING_ From there, I think I would like to try to get integration back from ige-mac- There is GtkOSXApplication for x86_64, and ige-mac-integration for the others. [1] <https:/ Ok, I made some progress on this bug. See attached patch menus.diff -- it's a big one. Here's what I did, with substeps: 1. Changed the ige-mac-integration dependency to gtk-mac- 1. As a prerequisite, added gtk-mac-integration as a pkg-config definition on configure.ac. 2. Removed old ige-mac-integration code completely, as Inkscape +quartz now requires the libgtkmacintegr 2. Changed the menu integration code to reflect the new dependencies. 1. Moved the integration code from interface.cpp to desktop-widget.cpp. 2. Added some extra code to conforms to the new dependency on gtk-osx-application (a subcomponent of gtk-mac- This patch is applicable on Inkscape 0.48.2. Those who are interested in trying it out in MacPorts are welcome to contact me for help. > This patch is applicable on Inkscape 0.48.2 Apparently the diff is against the sources from the tar ball release (as used in MacPorts) and doesn't apply to a checkout of the sources from bzr … any chance you could provide a patch against current trunk (lp:inkscape)? Note that there have been many changes in trunk (for 0.49) which will never be backported to 0.48.x. Any limitations with regard to switching to 'gtk-mac- @Roy Liu - many thanks for working on this! Initial notes on testing the patch with Inkscape 0.48.2 (patched and installed via MacPorts [1]) on Mac OS X 10.5.8 (i386): + dynamic submenus are back - that's great news :) + no crashes so far when using the menu commands to open dialogs or other documents + … - opening additional document windows duplicates the menubar entries (screenshot attached) - after closing a new window, one of the duplicate menubars is removed, but the other menus no longer work (or not consistently) - no keyboard shortcuts displayed in the menus - many warnings about manu accelerators: GLib- - … [1] 0.48.2 built ok after I figured out that the linker flag '-lX11' needs to be removed not only from 'configure' but from 'configure.ac' as well ;) (apparently, menus.diff triggers a regeneration of configure on 'make', based on 'configure.ac' which still includes the '-lX11' linker flags in INKSCAPE_LIBS) Inkscape 0.48.2 + patch (menus.diff) cont.: - menu 'File > Open Recent' opens the first file no matter which file was selected from the list - the same problem also occurs with the global menu on Ubuntu /Unity: <https:/ Regressions with GTK+ 2.24.7 (not seen in earlier GTK+ dot releases, not related to the menubar integration): - GTK+ Fullscreen mode fails (menu 'View > Fullscreen) the application window as well as the menu bar simply disappear - Function keys no longer work for keyboard shortcuts (e.g. once fullscreen mode has been entered and the window disappears, there is no way to return to normal state except by killing inkscape) suv, Thank you for your reply. There are still some issues to be addressed: 1. I am aware of the "accel-closure" problem. I'm not an expert on GTK, but I think it has something to do with changes in quartz keyboard acceleration. This is probably also related to having no keyboard shortcuts displayed. 2. I know why you're getting menubar duplicates. Putting extra code in desktop-widget.cpp was the wrong choice, because those desktop widgets aren't unique. Every time one is created, the code I inserted gets duplicated. 3. Sometimes Inkscape crashes on startup. Perhaps you can reproduce this by trying to restart it repeatedly? 4. The patch is on top of 0.48.2. 5. Do you know of an in-house GTK expert I can ask? -Roy Does this patch make the duplicates problem go away? > Does this patch make the duplicates problem go away? Yes, no more duplicate menu bars… thx I do get reproducible crashes though: 1) launch inkscape 2) open second document window (I used the first button on the commands bar) 3) close second window (I used the close button of the window decoration) 4) change view mode to 'Outline' in the remaining (first) document window (menu 'View > Display mode > Outline') -> crash The crash does not occur when changing view mode in the second window, nor when changing it in the first window before opening and closing the second window. Backtrace attached (Inkscape was compiled with newly installed gtk2 2.24.8). Minor issue I noticed with the 'Display mode' submenu: it does not update the currently used view mode after changing it. Another crash also related to opening/closing a second window: 1) launch Inkscape, open an existing file 2) open new document, close it again 3) modify the file opened in step 1 4) use 'File > Revert' to revert to the saved version -> crash 'File > Revert' works fine if no second document window had been opened and closed. We should probably better use a separate (new) bug report to track issues with the proposed patch to use 'gtk-osx- As it stands, the current version of Inkscape crashes with it's current Mac OSX menu-bar integration. Therefore, unless you've memorized the keystrokes, or have remove the integration code yourself, Inkscape will crash. Can we apply the no_integration patch for now, and leave the re-integration with the newer code for later? > Can we apply the no_integration patch for now (…) Attaching updated 'patch- (the old patch no longer works - 2 hunks fail). > (…) and leave the re-integration with the newer code for later? Personally I would agree (though it takes off pressure to get it fixed properly, i.e. migrating to gtk-mac-integration and gtk-osx- I have been using the patch for months now with quartz-based test builds from trunk on Mac OS X 10.5.8 (i386) (Apple GCC 4.2.1), and as far as I can tell it does not affect building on other platforms with different gtk backends (tested with r10946 and GTK+/X11 2.24.9 on OS X Lion, one build using Apple llvm-gcc-4.2, another one with FSF GCC 4.6.2). If removing the old ige-mac-menu.* stuff gets agreed on, I would urge to backport it to the 0.48.x branch as well, see also Inkscape bug #721424 and related trac tickets in MacPorts: Linker flags: <http:// Crashes due to broken menu integration code: <http:// <http:// <http:// Patch from comment #23 also tested with of Inkscape 0.48+devel r10946 and r10947 on - Mac OS X 10.45.8 Leopard (i386), GTK+/X11 2.24.8, Apple GCC 4.2.1 (build succeeds without failure, and application runs fine) Patch backported to 0.48.x branch, tested ok with Inkscape 0.48.x r9865: 1) normal build (no special configure options) - OS X 10.7.2 Lion 64bit, GTK+/X11 2.24.9, Apple llvm-gcc-4.2 2) configured with --enable-osxapp, and packaged as Inkscape.app (requires local backport of trunk changes for packaging script) - Mac OS X 10.5.8 Leopard (i386), GTK+/X11 2.24.4, Apple GCC 4.2.1, - Mac OS X 10.5.8 Leopard (i386), GTK+/Quartz 2.24.8, Apple GCC 4.2.1, @SislaC - based on my tests, the patches should be save for trunk as well as for the 0.48.x branch: - it works with Quartz-based builds (trunk, stable) - it does not affect X11-based builds on OS X (trunk, stable) I could not verify the changes to 'CMakeLists.txt' myself - AFAIK cmake is broken in the 0.48.x branch anyway, and in trunk the change removes the reference to the two deleted files (src/ige- Setting target 0.48.3 - backporting to 0.48.x would allow to have more stable Quartz-based builds on Mac OS X (albeit without using the global menu bar). See also comment #23-24. Was the patch based on Roy Liu's work what we ended up using? I just want to make sure we get the right person assigned. ScislaC wrote: > Was the patch based on Roy Liu's work what we ended up using? No (not yet) - the patch to remove the old code for the menu integration was originally done by Gellule (see comment #10). Hopefully Roy Liu's work can be picked up to implement full support of the global menu bar based on gtk-mac-integration and gtk-osx- Sorry for being silent for so long. The patch to remove Mac OS X menu integration looks good. That way any changes I make to *add* menu integration will look clearer. I wish I knew more GTK and had more time, but I'll try to invest more time into this over the coming months. Would appreciate some help in understanding how GTK is architected, especially gtk-mac- Could you provide details about your platform (OS X version, arch)? Also, it would be helpful to add the versions of the main dependencies (like gtk+, glib, gtkmm and glibmm) used for your current build to the report (as MacPorts updates quite frequently and things might change with later versions).
https://bugs.launchpad.net/inkscape/+bug/721448
CC-MAIN-2018-17
refinedweb
2,012
72.56
Ryan, Thank you for your comments. I am sorry for the long point by point response. I am updating my patch to address all of your comments. Please read my response for explainations. Thank you. rbb@covalent.net wrote: > ...USE_SFIO...VOIDUSED...USE_STDIO? These were historical. I didn't notice them there. > > find_start_sequence and find_end_sequence are basically the same > functions. The biggest differences are the values that are set in the ctx > structure, this could and should be handled with flags. This code is too > complex to duplicate. I disagree. Yes the code is similar, but there are enough differences that the code becomes ugly to the point of being unreadable if it is merged using flags etc. I know because I started with a single merged function. > > > if ((ctx->combined_tag = malloc (ctx->tag_length + 1)) == NULL) { > > return (APR_ENOMEM); > > Why are we malloc'ing here? This data (if I understand the comments) is > never sent to the client. This should be a palloc, or even better a > pcalloc. In one of my design notes I commented that I wasn't sure of the best place to (m|c|p)alloc from for this. My thinking was that I didn't want to grow the pool size by pallocing from there for something that was strictly internal to mod_include. My thinking was that by mallocing here I could free it when I am done. I also don't think this is going to happen very frequently. > > get_combined_directive deals with two distinct brigades. Why aren't they > concatenated? This would simplify the code, and it isn't an expensive > operation. I thought it was expensive to setaside the rest of the brigade just so I could throw it away. All I am doing is copying the bytes from the buckets of the directive. As soon as I am done processing I throw all of those buckets away. Why pay the price to set aside the buckets just to throw them away. I don't think it adds that much complexity to handle two brigades. > > get_combined_directive also uses AP_BUCKET_PREV(dptr) != bb_end. From > reading the code, this could be simplified to > !AP_BRIGADE_SENTINEL(dptr). This would again simplify the code and make > it easier to understand and debug. You are quite correct. I learned about AP_BRIGADE_SENTINEL after I wrote this code. > > get_tag_and_value returns the value using return, and returns the tag in > an argument. For consistancy it should return both as arguments. Ok. Easily fixed. > > get_directive should use a hash table to store the tags. The key is the > directive, the value is the function to call when that directive is > encountered. (This also allows modules to easily extend mod_include's > capabilities to handle more directives, allowing us to remove > USE_PERL_SSI, because that becomes part of mod_perl.) I can see the added flexiblity visa-vie removing the USE_PERL_SSI stuff, but the problem with this is that the main send_parsed_content function does different wrapper code for each directive. For some it needs to check "printing" for others it needs to deal with "if_nesting_level", and for others I need to send the preceding buckets before processing the subrequest. Getting back a generic function pointer doesn't help this. It also doesn't improve performance for checking such a small number of directives. > You can't do this with any transient buckets. The point behind transient > buckets is that they are stack data, but in order for them to work, you > have to call the set-aside function on those buckets. If you don't, the > data just disappears out from under the bucket. Since your data is > disappearing immediately, this should just be put in a heep or pool > bucket. > > Same problem here. Ok. Chalk this up to ignorance on my part. > > You have ap_r* functions in the main-line code. This is not allowed. #1, > a handler that uses buckets cannot also use ap_r*. #2 and more important, > NO filter can use ap_r* functions, ever. I assume you are referreing to ap_r(v)puts and not ap_run_sub_req or ap_regex. I actually knew that those were problems and had it on my list to clean up. I believe that all of those are in the parse_expr function which I left to last to work on and then didn't get to. Those are just leftover from before and I had already figured out how to get rid of them, I just didn't actually do it. > What exactly is parse_expr doing? It is a huge function, and I don't even > want to try to figure out what it is up to. It is doing what it did before ;) (I didn't touch it yet). It is the expression parser for the "if" and "else" directives. I should be able to clean it up and simplify it, but it was not broken at the moment and so didn't need fixing (other than the ap_r* calls). > > LOG_COND_STATUS is broken. You can't use a transient bucket in this > way. Same as above. Ok. Same as above. > > The handle_* function abstraction is still wrong. It shouldn't be up to > send_parsed_content to split the brigade and pass it if > necessary. Sometimes, the include directive requires a sub_request, > sometimes it doesn't (error condition). Why do we always split and send > the brigade? The abstraction is simple, the handle_* function gets the > whole brigade, and a pointer to the start of the tag. The handle_* > function can then decide if it wants to split and pass the brigade or not. Easy change to move this from send_parsed_content in to the handle functions. > > Think of it this way. Right now, this code is not easily extensible, to > make it extensible is easy however. Instead of hard-coding the directives > that are understood, take a modular approach. Use a hash table to store > the directives that are understood, and just pass the processing off to > those functions. This allows another module to register a new SSI > directive easily. In order for this to work, the handle_* function needs > to have complete discretion over how the brigade is handled. Again, this > would simplify code, making this module easier to debug. Ok. I see your hash table argument now. I was leaving the wrapper code outside of the handle_* functions to avoid unnecessary function calls. You are advocating moving all of the code into the handle_* functions so that they are self contained for future flexibility. I can see and agree to this point. This is also an easy thing to fix. By the way, how do you see other modules to register handle_* functions with mod_include? > > What is FREDDY_KRUGER_VEGAMATIC_MODE? This was testing code to pathologically slice the brigade into a bunch of brigades with a single bucket with a single byte in it. Hence the reference to Freddy Kruger (sp) of Nightmare on elm street fame. > > CREATE_ERROR_BUCKET is brokecn because of the transient problem. Ok. Same as above. > In general, instead of the re-write making mod_include easier to deal > with, it has become a bigger monster, doubling in size and adding another > 600 lines of code (not counting the include file). I don't mind more > lines of code, I do mind when those lines of code are almost impossible to > wade through. A fair number of the added lines of code are comments added to try to make the change easier to understand. The code has grown by about 35% including the comments. What do you feel makes them impossible to wade through. This strikes me as sour grapes simply because you didn't write the code and are therefore unfamiliar with it. > I have started to try to debug this module, but I am giving up now. I am > unlikely to touch this version of the module again, because it is just too > much. I'm going back to the original version. If somebody else wants to > debug the new one, feel free. I didn't ask you to debug the module, I am not asking you to fix the module, and I sure as hell am not expecting you to rewrite the module. The comments that you made are all easily fixed in this code. I don't see a single one of them that warrants this sort of inane response. I will have a fixed patch soon addressing all of your comments. -- Paul J. Reder ----------------------------------------------------------- "The strength of the Constitution lies entirely in the determination of each citizen to defend it. Only if every single citizen feels duty bound to do his share in this defense are the constitutional rights secure." -- Albert Einstein
http://mail-archives.apache.org/mod_mbox/httpd-dev/200011.mbox/%3C3A1A9481.804B6FA8@raleigh.ibm.com%3E
CC-MAIN-2018-43
refinedweb
1,434
74.79
Sorry to bother you guys again, but I need help with I/O files again. I'm using \\Fla_Mega_Money_Hist.txt" );\\Fla_Mega_Money_Hist.txt" );Code:ifstream a_file ( "D:\\LotteryPrograms\\Fla_Mega_Money to open a file to read, so "a_file" can update a series of variables (from n1 thru n44), using "int x = 0" to hold data temporarily so "a_file" can update the variables (n1++...n44++). X is not required to keep anything for very long. It is not what's in x that I want, it is what is in n1 thru n44 that's important to me. I'm using to write the result of :to write the result of :Code:ofstream b_file ( "D:\\LotteryPrograms\\Fla_Mega_Money\\Loto_Temp_Program.txt" ); all the way to n44++all the way to n44++Code++; in file Loto_Temp_Program, where it gives me both, the original number and its frequency (n1 = [ n = a variable, and 1 = the # ] ). However, while the b_file writes: all the way to n44, what is in place of the variable (n1 thru n44) are "0"all the way to n44, what is in place of the variable (n1 thru n44) are "0"Code:for ( int i = 0; i != EOF; i++ ); { b_file << "#1 has a frequency of " << n1 << endl, ios::app; b_file << "#2 has a frequency of " << n2 << endl, ios::app; I do not know if the program is actually updating but not writing, or just not updating. What I get is: all the way to #44all the way to #44Code:#1 has a frequency of 0 #2 has a frequency of 0 #3 has a frequency of 0 #4 has a frequency of 0 #5 has a frequency of 0 the screen does displays all the cout text, making me wonder if the program did the work, but just not writing it in b_file. My code is: b_file is writing in the assigned file, but it seems that the updating is either not being done, or the updated valuesb_file is writing in the assigned file, but it seems that the updating is either not being done, or the updated valuesCode:#include <iostream> #include <fstream> #include <string> #include <ios> #include <stdio.h> #include <stdlib.h> using namespace std; int main () { int first = 0, second = 0, third = 0, fourth = 0, MB = 0; cout << "You have chosen to play Florida's Mega_Money Lotto," << endl << endl; // ================================================================ int x = 0; char str [6], str2 [6]; // initialize 44 vairables to receive and count the numbers from 1 thru 44 int n1=0; int n2=0; int n3=0; int n4=0; int n5=0; int n6=0; int n7=0; int n8=0; int n9=0; int n10=0; int n11=0; int n12=0; int n13=0; int n14=0; int n15=0; int n16=0; int n17=0; int n18=0; int n19=0; int n20=0; int n21=0; int n22=0; int n23=0; int n24=0; int n25=0; int n26=0; int n27=0; int n28=0; int n29=0; int n30=0; int n31=0; int n32=0; int n33=0; int n34=0; int n35=0; int n36=0; int n37=0; int n38=0; int n39=0; int n40=0; int n41=0; int n42=0; int n43=0; int n44=0; ifstream a_file ( "D:\\LotteryPrograms\\Fla_Mega_Money\\Fla_Mega_Money_Hist.txt" ); //Opens Temp_Program for reading the file cout << "Please wait while I read the file... This may take a while" << endl << endl; ofstream b_file ( "D:\\LotteryPrograms\\Fla_Mega_Money\\Loto_Temp_Program.txt" ); //Creates an instance of ofstream, and for ( int i = 0; i != EOF; i++ ); { //int x = 0; a_file >> x; // reads a number from the file MegaMill++; if (x == 13) n13++; if (x == 14) n14++; if (x == 15) n15++; if (x == 16) n16++; if (x == 17) n17++; if (x == 18) n18++; if (x == 19) n19++; if (x == 20) n20++; if (x == 21) n21++; if (x == 22) n22++; if (x == 23) n23++; if (x == 24) n24++; if (x == 25) n25++; if (x == 26) n26++; if (x == 27) n27++; if (x == 28) n28++; if (x == 29) n29++; if (x == 30) n30++; if (x == 31) n31++; if (x == 32) n32++; if (x == 33) n33++; if (x == 34) n34++; if (x == 35) n35++; if (x == 36) n36++; if (x == 37) n37++; if (x == 38) n38++; if (x == 39) n39++; if (x == 40) n40++; if (x == 41) n41++; if (x == 42) n42++; if (x == 43) n43++; if (x == 44) n44++; cout << "I have read the file and updated all the number frequencies." << endl << endl; cout << "I will now try to put them in file Loto_Temp_Program." << endl << endl; // a_file >> n1; a_file >> n2; a_file >> n3; a_file >> n4; // cin.get(); } // ===================================================================================== for ( int i = 0; i != EOF; i++ ); { b_file << "#1 has a freqienvy of " << n1 << endl, ios::app; b_file << "#2 has a freqienvy of " << n2 << endl, ios::app; b_file << "#3 has a freqienvy of " << n3 << endl, ios::app; b_file << "#4 has a freqienvy of " << n4 << endl, ios::app; b_file << "#5 has a freqienvy of " << n5 << endl, ios::app; are not being passed to b_file. Please, what am I doing wrong?. . . . therry
http://cboard.cprogramming.com/cplusplus-programming/147689-i-o-trouble-again.html
CC-MAIN-2014-23
refinedweb
835
62.35
China glazed eaves roofing tile for private gardens US $0.8-2 5000 Pieces (Min. Order) Left and Right Eaves Tiles Hip Tiles Fittings of Clay Roof ... US $0.55-0.75 1000 Square Meters (Min. Order) Chinese roofing and waterproof expo 2012 eave tiles US $35-85 50 Square Meters (Min. Order) glazed roof eaves tiles for Chinese garden architecture US $20-50 50 Square Meters (Min. Order) corrugated metal roofing tile /decorative stone wall tiles /r... US $2.75-4 1000 Pieces (Min. Order) left & right eave edge tile--accessory of roof tile 1000 Square Meters (Min. Order) Eave tiles stone coated metal roofing tile / Sand coated ston... US $3.4-4.5 1000 Pieces (Min. Order) Concrete eave tile US $1-2.5 10000 Pieces (Min. Order) Stone coated Eaves Flashing tile US $1.5-2.5 1500 Pieces (Min. Order) 2015 Manufacturer Eaves Stone Coated Roof Tile For Per Sheet ... US $3-6 100 Pieces (Min. Order) Asa Synthetic Resin Plastic Flat Sheet Roof,Roof Tile,Roof ... US $4.56-7.23 50 Square Meters (Min. Order) import the roof tile from China 1000 Square Meters (Min. Order) fireproof artificial thatch roof tiles US $1-50 500 Pieces (Min. Order) foshan chinese traditional asian style roof tiles US $29-100 500 Square Meters (Min. Order) pe fireproof artificial palm synthetic thatch roofing tiles US $4.2-9.85 6000 Pieces (Min. Order) Cheap Extrusion decoration plastic synthetic thatch roof ... US $1.9-4.5 500 Pieces (Min. Order) Jieli new spanish style plastic roof tile US $4-7 1000 Square Meters (Min. Order) metal PVC synthetic concrete roof tile US $6.5-9 500 Square Meters (Min. Order) Synthetic thatch roof tiles for decoration US $2.5-5.5 100 Pieces (Min. Order) 1050 or 5052 aluminum sheet for roof tile US $2600-3500 3 Metric Tons (Min. Order) Aluminium artificial fire-proof synthetic thatch roofing ... US $18.5-27 1 Square Meter (Min. Order) Acidproof New Popular Thailand Tourist Cottage Synthetic Roo... US $3-5 1000 Pieces (Min. Order) pvc color flat synthenic galvanized steel roof tile US $3.0-5.58 1 Piece (Min. Order) 2015 china supply colorful stone coated metal roof tile US $6-10 100 Pieces (Min. Order) Corrugated Roofing Tile US $3.1-7.8 300 Meters (Min. Order) Superior Quality roof metal tile for villa US $450-1000 50 Tons (Min. Order) Blue residential spanish roofing tile US $5-8 500 Square Meters (Min. Order) Roofing Tiles 600 Square Meters (Min. Order) Outdoor Synthetic Thatch Roofing from GreenShip/man-made gra... US $9.55-19.57 300 Pieces (Min. Order) Classic Colorful Stone Coated Metal Roofing Tile / Metal Corr... US $2.5-4 2 Tons (Min. Order) stone coated steel tile (Dezhou) US $3.2-4.8 8000 Pieces (Min. Order) Modern Classical Galvanized Color Iron Roofing Tiles US $2-3 100 Square Meters (Min. Order) Stone coated roof tiles(Zn-al galvanized steel tile) US $2.5-5 100 Sheets (Min. Order) wall steel tile EUR 1.5-3.5 10000 Meters (Min. Order) black roof tiles US $0-10 500 Square Meters (Min. Order) colorful 0.4mm stone coated metal roof tile US $3.3-4.63 100 Pieces (Min. Order) steel sheeting roofing tile steel sheet steel roof tile 100 Square Meters (Min. Order) corrugated tile US $2
http://www.alibaba.com/showroom/eaves-tiles.html
CC-MAIN-2015-48
refinedweb
562
80.28
Hello! Here are some things you may or may not have noticed about DNS: - when you resolve a DNS name in a Python program, it checks /etc/hosts, but when you use dig, it doesn’t. - switching Linux distributions can sometimes change how your DNS works, for example if you use Alpine Linux instead of Ubuntu it can cause problems. - Mac OS has DNS caching, but Linux doesn’t necessarily unless you use systemd-resolvedor something To understand all of these, we need to learn about a function called getaddrinfo which is responsible for doing DNS lookups. There are a bunch of surprising-to-me things about getaddrinfo, and once I learned about them, it explained a bunch of the confusing DNS behaviour I’d seen in the past. where does getaddrinfo come from? getaddrinfo is part of a library called libc which is the standard C library. There are at least 3 versions of libc: - glibc (GNU libc) - musl libc - the Mac OS version of libc (I don’t know if this has a name) There are definitely more (I assume FreeBSD and OpenBSD each have their own version for example), but those are the 3 I know about. Each of those have their own version of getaddrinfo. not all programs use getaddrinfo for DNS The first thing I found surprising is that getaddrinfo is very widely used but not universally used. Every program has basically 2 options: - use getaddrinfo. I think that Python, Ruby, and Node use getaddrinfo, as well as Go sometimes. Probably many more languages too but I did not have the time to go hunting through every language’s DNS library. - use a custom DNS resolver function. Examples of this: - dig. I think this is because dig needs more control over the DNS query than getaddrinfosupports so it implements its own DNS logic. - Go also has a pure-Go DNS resolver if you don’t want to use CGo - There’s a Ruby gem with a custom DNS resolver that you can use to replace getaddrinfo. getaddrinfodoesn’t support DNS over HTTPS, so I assume that browsers that use DoH are not using getaddrinfofor those DNS lookups - probably lots more that I’m not aware of you’ll sometimes see getaddrinfo in your DNS error messages Because getaddrinfo is so widely used, you’ll often see it in error messages related to DNS. For example if I run this Python program which looks up nonexistent domain name: import requests requests.get(" I get this error message: Traceback (most recent call last): File "/usr/lib/python3.10/site-packages/urllib3/connection.py", line 174, in _new_conn conn = connection.create_connection( File "/usr/lib/python3.10/site-packages/urllib3/util/connection.py", line 72, in create_connection for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): File "/usr/lib/python3.10/socket.py", line 955, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno -2] Name or service not known I think socket.getaddrinfo is calling libc getaddrinfo somewhere under the hood, though I did not read all of the source code to check. Before you learn what getaddrinfo is, it’s not at all obvious that socket.gaierror: [Errno -2] Name or service not known means “that domain doesn’t exist”. It doesn’t even say the words “DNS” or “domain” in it anywhere! getaddrinfo on Mac doesn’t use /etc/resolv.conf I used to use a Mac for work, and I always felt vaguely unsettled by DNS on Mac. I could tell that something was different from how it worked on my Linux machine, but I couldn’t figure out what it was. I still don’t totally understand this and it’s hard for me to investigate because I don’t currently have access to a Mac but here’s what I’ve gathered so far. On Linux systems, getaddrinfo decides which DNS resolver to talk to using a file called /etc/resolv.conf. (there’s apparently some additional complexity with /etc/nsswitch.conf but I have never looked at /etc/nsswitch.conf so I’m going to ignore it). For example, this is the contents of my /etc/resolv.conf right now: # Generated by NetworkManager nameserver 192.168.1.1 nameserver fd13:d987:748a::1 This means that to make DNS queries, getaddrinfo makes a request to 192.168.1.1 on port 53. That’s my router’s DNS resolver. I assumed this was getaddrinfo on Mac also just used /etc/resolv.conf but I was wrong. Instead, getaddrinfo makes a request to a program called mDNSResponder which is a Mac thing. I don’t know much about mDNSResponder except that it does DNS caching and that apparently you can clear the cache with dscacheutil. This explains one of the mysteries at the beginning of the post – why Macs have DNS caching and Linux machines don’t always. musl libc getaddrinfo is different from glibc’s version You might think ok, Mac OS getaddrinfo is different, but the two versions of getaddrinfo in glibc and musl libc must be mostly the same, right? But they have some pretty significant differences. The main difference I know about is that musl libc does not support TCP DNS. I couldn’t find anything in the documentation about it but it’s mentioned in this tweet) I talked a bit more about this TCP DNS thing in ways DNS can break. Some more differences: - the way search domains (in /etc/resolv.conf) are handled is slightly different (discussed here) - this post mentions that musl doesn’t support nsswitch.conf. I have never used nsswitch.conf and I’m not sure why it’s useful but I think there are reasons I don’t know about. more weird things: nscd? When looking up getaddrinfo I also found this interesting post about getaddrinfo from James Fisher that straces glibc getaddrinfo and discovers that apparently calls some program called nscd which is supposed to do DNS caching. That blog post describes nscd as “unstable” and “badly designed” and it’s not clear to me how widely used it is. I don’t know anything about nscd but I checked and apparently it’s on my computer. I tried it out and this is what happened: $ nscd child exited with status 4 My impression is that people who want to do DNS caching on Linux are more likely to use a DNS forwarder like dnsmasq or systemd-resolved instead of something like nscd – that’s what I’ve seen in the past. that’s all! When I first learned about all of this I found it really surprising that such a widely used library function has such different behaviour on different platforms. I mean, it makes sense that the people who built Mac OS would want to handle DNS caching in a different way than it’s handled on Linux, so it’s reasonable that they implemented getaddrinfo differently. And it makes sense that some programs choose not to use getaddrinfo to make DNS queries. But it definitely makes DNS a bit more difficult to reason about.
https://jvns.ca/blog/2022/02/23/getaddrinfo-is-kind-of-weird/
CC-MAIN-2022-21
refinedweb
1,194
71.65
Read the next line of the protocol name database file #include <netdb.h> struct protoent * getprotoent( void ); The getprotoent() function reads the next line of the protocol name database file, opening the file if necessary. It returns a pointer to a structure of type protoent, which contains the broken-out fields of a line in the network protocol database, /etc/protocols. A pointer to a valid protoent structure, or NULL if an error occurs. This function uses static data; if you need the data for future use, copy it before any subsequent calls overwrite it. Currently, only the Internet protocols are understood.
http://www.qnx.com/developers/docs/qnxcar2/topic/com.qnx.doc.neutrino.lib_ref/topic/g/getprotoent.html
CC-MAIN-2020-45
refinedweb
102
63.19
. On almost every family holiday I take a good book. Not being distracted by the continuous flow of the Internet and with enough time to let stuff sink in, holiday time makes a good time to see things in perspective again and come home with a fresh mind full off ideas. Last time this worked very well to give myself a real boost on building enterprise applications domain-driven style. Jimmy Nilsson's Applying Domain-Driven Design and Patterns was a quite pragmatic coding based approach which really accelerated my way of building applications. So this time I considered it time to finally do a thorough read of Eric Evans's bible of DDD There are plenty of reviews on the web, on Amazon alone you will find loads and loads of information on it's content and value. Besides that it has a website. Fragments of it's content is found in so many posts on Codebetter that it almost seems implicit knowledge over here. But as I enjoyed it that much I would like to draw some more attention to this modern classic itself. Inside you will not find a lot of code. Besides that all code is Java code; the .net platform is not even mentioned once. The book is about the essentials of code. All revolves around one central object oriented domain model. A model which serves the developer to write the implementation but it is also a model which speaks the language of the domain expert who understands the required functionality of the software. The model is described in an ubiquitous language whose meaning is understood in the same way by all team members and so serves good communication. By refactoring the developer as well as the domain expert work in cooperation on the same model. This may sound somewhat vague but chapter by chapter all aspects, from database persistence to a vision statement come by including very clear examples. Reading gave me many points of recognition as well as some aha-moments. A very pleasant moment was the conclusion of part 3, Crisis as an opportunity, where Eric mentions "punctuated equilibria", the (r)evolutionary model of a recent rant of mine. How a domain model can evolve over time also fits perfectly in that story. At first I only felt sorry I had waited that long to start reading (or going on a holiday :)). The book is written very clear, does give a great overview of the subject and is very systematic in making its point. It is absolutely a classic that every developer, architect (is there a real difference ?) or anyone else who is involved in building software should read. Not everybody does agree on this, between all the five star reviews on Amazon you will find some less enthusiastic ones. So, on second thought, I would not always recommend this book as a starting point for DDD. In case you have troubles reading it start Jimmy Nilsson's Applying DDD and patterns and make sure you really start doing some hands-on DDD stuff yourself. And sooner or later you will really appreciate this book as it will structure all you've read and done back into one clear and flexible model. And that's what DDD is about. And now you should start reading it yourself.. In a relative short span of time nHibernate has become a major member of my toolbox. It has become the way to work with a database, not only a small hap-snap apps but it's also making big strides into a constantly evolving system I'm working on. Setting up nHibernate several times has given me the opportunity to do some playing around. Browsing around you can find several ways to do it, some ways just focus on getting it done, some ways focus on performance, and some ways focus on resource management. Here I would like to discuss my way where I tried to take all aspects in account. Don't take it as the way; please do share your thoughts. <update>After a very good comment by rui I have corrected some of the code for the repository part. Thanks ! Blogging is just the best public code review you can get :)</update> Code will work with two very important nHibernate objects I'm going to manage both the sessionfactory and the session in one nHibernateHelper class. The code needs only one sessionfactory, which has to be instantiated once. The sessionfactory is going to be a static (shared) member of the class. I took the idea to instantiate the sessionfactory in a static constructor from an nice article on theserverside. A static constructor fires the moment the class is loaded. That is the moment the class is first touched by running code. In the original code the configuration is loaded from a configuration file. My problem with that is that I want to be independent from that for reasons of testability and custom configuration. Most settings can be hard coded but something like the database connectionstring has to be set from code. A static constructor does not have any parameters and I can not set any members, the moment I touch the class the static constructor fires first and I'm too late. What does work is a small helper class. internal class nHibernateConnectionHelper internal static string connectionString = ""; props.Add("hibernate.dialect", "NHibernate.Dialect.MsSql2005Dialect"); cfg.AddAssembly("dlcr.domain"); When the nHibernateConnectionHelperClass is touched first the static constructor of the NhibernateHelper class reads the updated connectionstring. It is used like this: public class NhibernateHelperFactory public static INhibernateHelper CreateHelper(string dbConnection) nHibernateConnectionHelper.connectionString = dbConnection; return new NhibernateHelper(); Now the static constructor works as intended. This trick also works when both classes are in the same cs file. How the sessionfactory itself is set up is in a previous post. With the sessionfactory ready the nHibernatehelper can start its core business: managing a session. A new session is instantiated and opened in the instance constructor. This constructor performs some checks whether the sessionfactory will provide a session with the expected database. It reads the connectionstring from the sessionfactory property as described in the previous post.();
http://codebetter.com/blogs/peter.van.ooijen
crawl-001
refinedweb
1,030
62.38
2016-04-12 14:16 GMT+02:00 Victor Stinner <victor.stinner at gmail.com>: > I read your code and the code of CPython. I found many issues. > (...) > The exploit is based on two things: > > * update_wrapper() is used to get the secret attribute using the real > getattr() function > * update_wrapper() + A.__setattr__ are used to pass the secret from > the real namespace to the untrusted namespace Oh, I forgot to mention another vulnerability: you block access to attributes by replacing getattr and by analyzing the AST. Ok, but one more time, it's not enough. If you get access to obj.__dict__, you will likely get access to any attribute using obj_dict[attr] instead of obj.attr. I wrote pysandbox because I liked Tav's idea of *removing* sensitive dictionary keys of sensitive types like functions, frames and code objects. Again, it was not enough. Victor
https://mail.python.org/pipermail/python-dev/2016-April/143988.html
CC-MAIN-2022-33
refinedweb
145
67.76
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Numbers { public static void main(String[] args) { List<int[]> arrayList = new ArrayList<int[]>(); int[] srtArray = {1,2,3,100,201,730}; arrayList.add(srtArray) ; for (int i=0;i<arrayList.size();i++){ System.out.println(arrayList.get (arrays don't override Object.toString) Experts Exchange Solution brought to you by Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.Start your 7-day free trial int[] srtArray = {1,2,3,100,201,730}; //declares and initialises an int array called srtArray arrayList.add(srtArray) ; //adds the array srtArray to the arrayList for (int i=0;i<arrayList.size();i++ System.out.println(arrayLi } List<int[]> arrayList = new ArrayList<int[]>(); but a list of Integers: List<Integer> arrayList = new ArrayList<Integer>(); In which case your code should be: List<Integer> arrayList = new ArrayList<Integer>(); int[] srtArray = {1,2,3,100,201,730}; for (int j = 0 ; j < srtArray.length ; j++) { arrayList.add(srtArray[j]) } The good news is that if you have a List<Integer> then you don't need to do this: for (int j=0;j<arrayList.size();j++ System.out.println(arrayLi } to print them out, you can just do this: System.out.println(arrayLi Doug This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries. List<int> i am using is instead arraylist of primitive not wrapper type right? Open in new window why only one 1 reference for all bojcects in arraylist? Does not it look the elements within the strArray list. please advise because you have only put one object in there. viz : Open in new window srtArray being the object. List<int[]> arrayList = new ArrayList<int[]>(); where each element in the list is an array of items (very unusual to want this) and this: List<Integer> arrayList = new ArrayList<Integer>(); where each element in the list is a single integer value (you almost certainly want this). (You can'd do List<int> arrayList because Java doesn't allow it - so you do List<Integer> instead). In either case, if you print out the elements of the list, it works by taking one element at a time and printing it. If the element of the list is an "array of integers" then Java prints the gibberish output. You can see the same gibberish if you just do this: int[] srtArray = {1,2,3,100,201,730}; System.out.println(strArra Almost certainly what you want is a List<Integer>. Give the code I posted a try and see if it makes sense to you. Pretty sure your original code is going down a dead end that will leave you very confused. Doug i wonder why java does not allow. What is speciality of Integer compared to int. Is it is because int is not object type where as Integer is object type and list expects only object type but not primitive? Yes that's exactly it. A list has to be a list of objects. It can't be a list of primitives. Doug Open in new window I got output as [1, 2, 3, 100, 201, 730] . . . still not what you were expecting, then?
https://www.experts-exchange.com/questions/28483451/array-to-arraylist.html
CC-MAIN-2018-30
refinedweb
572
66.74
The sys module provides access to functions and values concerning the program's runtime environment, such as the command line parameters in sys.argv or the function sys.exit() to end the current process from any point in the program flow. While cleanly separated into a module, it's actually built-in and as such will always be available under normal circumstances. Import the sys module and make it available in the current namespace: import sys Import a specific function from the sys module directly into the current namespace: from sys import exit For details on all sys module members, refer to the official documentation.
https://riptutorial.com/python/topic/9847/sys
CC-MAIN-2019-04
refinedweb
105
51.18
NSPR's internal header file pr/include/md/_freebsd.h includes these lines, which go all the way back to rev 1.1: /* freebsd has INADDR_LOOPBACK defined, but in /usr/include/rpc/types.h, and I didn't want to be including that.. */ #ifndef INADDR_LOOPBACK #define INADDR_LOOPBACK (u_long)0x7F000001 #endif But NSPR's public header file prinet.h contains these lines: #if defined(FREEBSD) || defined(BSDI) || defined(QNX) #include <rpc/types.h> /* the only place that defines INADDR_LOOPBACK */ #endif This inconsistency is odd. NSPR makes its users include a file that it does not always include itself. Sun's NSPR/NSS team has received a request to change prinet.h to use the same #define technique as used in _freebsd.h, rather than continuing to #include <rpc/types.h> to resolve some issues with the file rpc/types.h in recent versions of FreeBSD. Here, I want to ask the NSPR developers: Is this a reasonable request? Wan-Teh, what's your opinion? This is fine. Is this still actual?
https://bugzilla.mozilla.org/show_bug.cgi?id=504248
CC-MAIN-2017-26
refinedweb
170
63.05
I'm having issues finding this information without the use of a forum, so here goes: I'm making a very basic program on Linux that spawns four child processes. Each child process runs a separate program in the same directory, in which it just keeps printing its ID out to the screen over and over again. After the parent process spawns these, it just does the same thing until about 20 seconds have passed since the program started, at which point it kills all processes and terminates. The code for the two programs is this: Parent Process Program: Child Process Program:Child Process Program:Code: #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <time.h> #include <signal.h> #ifndef FALSE #define FALSE (0) #endif #ifndef TRUE #define TRUE (!FALSE) #endif /******************************************************************************** * Method: void newProcesses() * * Purpose: to make four child processes, each of which will execute a certain * * program in the same directory * * Returns: N/A * * * * Approach: This method first creates an array for four separate process ID's. * * Then it goes through a four-iteration for loop, with each iter- * * ation involving the creation of a child process. Each time a * * process is supposedly created, the loop checks to see if the * * creation was successful. If not an error message is printed. * * If so, and if it is the child process that is currently execut- * * ing, then the child process is made to execute a program in the * * same path as this program, the former being called "Subprogram".* * Otherwise it is the parent process that is currently executing, * * so the for loop will just use the parent to print a message of * * successful creation, including the child process's ID. * ********************************************************************************/ void newProcesses() { /* method for making new processes */ int id[4]; /* process ID array */ int i; /* for loop iterator */ for (i = 0; i < 4; i++) { id[i] = fork(); if (id[i] == -1) /* an error occurred */ { printf("Creation of Child Process failed.\n"); } else if (id[i] == 0) /* this is the child process currently acting */ { execlp("/jroberts/Subprogram", "/jroberts/Subprogram"); } else /* this is the parent process currently acting */ { printf("Creation of Child Process #%d succeeded!\n",id[i]); } } } /******************************************************************************** * Method: int main() * * Purpose: to serve as the driving method for the entire program * * Returns: 0 to the operating system to signal successful termination * * * * Approach: First this method finds the current time in seconds and stores it * * in two different variables, initial and current. Then it gets * * the current (parent) process's ID and prints a message with * * that ID out to the screen. Then it calls void newProcesses() * * to make child processes and handle each of them accordingly. * * Finally it enters a loop, each iteration of which checks the * * clock and updates current. After it has been found that 20 * * seconds have gone by, the loop is ended, all the processes are * * killed, and the method is basically finished. * ********************************************************************************/ int main () { /* setting up the program's "timer" for the program to know when to kill processes */ time_t initial; // starting time of the program in seconds time_t current; // current time in seconds time(&initial); /* initializing both initial and current to the starting time current = initial; */ /* the master process will give out its ID, subsequently making new processes */ int ownID = getpid(); printf("Parent Process created with ID# %d.\n", ownID); /* now the child processes will be made. */ newProcesses(); /* at this point there should be child processes. Now the parent process will wait until the progrm has lasted for about 20 seconds, subsequently killing all processes. */ time(¤t); while(current - initial < 20) // the program has executed for less than 20 seconds { printf("Parent Process with #%d currently executing.\n",ownID); time(¤t); } kill(0,SIGKILL); return 0; } Yet when I execute the main program, I get this kind of output:Yet when I execute the main program, I get this kind of output:Code: #include <stdio.h> #include <sys/types.h> #include <unistd.h> #ifndef FALSE #define FALSE (0) #endif #ifndef TRUE #define TRUE (!FALSE) #endif int main () { int id = getpid(); while (TRUE) { printf("Process #%d\n",id); } return 0; } This is followed by the Parent Process print its ID innumerable times, and finally a Kill statement.This is followed by the Parent Process print its ID innumerable times, and finally a Kill statement.Code: Creation of Child Process #32039 succeeded! Creation of Child Process #32038 succeeded! Creation of Child Process #32041 succeeded! Creation of Child Process #32046 succeeded! Creation of Child Process #32043 succeeded! Creation of Child Process #32042 succeeded! Creation of Child Process #32040 succeeded! Creation of Child Process #32047 succeeded! Creation of Child Process #32045 succeeded! Creation of Child Process #32044 succeeded! Creation of Child Process #32051 succeeded! Creation of Child Process #32048 succeeded! Creation of Child Process #32049 succeeded! Creation of Child Process #32050 succeeded! Creation of Child Process #32052 succeeded! It shouldn't be making more than four child processes, and each of them should be taking turns printing their ID's, not just the Parent Process. What's going wrong here?
http://cboard.cprogramming.com/c-programming/120550-why-isnt-execlp-function-doing-anything-printable-thread.html
CC-MAIN-2015-06
refinedweb
834
64.1
Introduction to Metaprogramming in Nim2016-06-06 · Nim · Programming Introduction to the Introduction (Meta-Introduction) Wikipedia gives us a nice description of metaprogramming: Metaprogramming is the writing of computer programs with the ability to treat programs as their data. It means that a program could be designed to read, generate, analyse and/or transform other programs, and even modify itself while running. In this article we will explore Nim’s metaprogramming capabilities, which are quite powerful and yet still easy to use. After all great metaprogramming is one of Nim’s main features. The general rule is to use the least powerful construct that is still powerful enough to solve a problem, in this order: So before looking at Nim’s two main metaprogramming constructs, templates and macros, we’ll look at what we can do with procs and iterators as well. Regular Programming Constructs Normal procs We’re in normal programming land here. Regular procedures are what you know as functions elsewhere and they’re pretty easy to define and use: proc sayHi(name: string) = echo "Hello ", name sayHi("World") sayHi "World" "World".sayHi Generic procs With generics we can define procs that work on multiple types. Actually a new proc will be generated based on our generic definition for each instantiation: proc min[T](x, y: T): T = if x < y: x else: y echo min(2, 3) # more explicitly: min[int](2, 3) echo min("foo", "bar") # min[string]("foo", "bar") Inline iterators Inline iterators are the default iterators in Nim. They get compiled into high performance loops: iterator reverseItems(x: string): char = for i in countdown(x.high, x.low): yield x[i] for c in "foo".reverseItems: echo c So this code gets compiled into: let x = "foo" for c in countdown(x.high, x.low): let c = x[i] echo c Of course we can make iterators generic too: iterator reverseItems[T](x: T): auto = for i in countdown(x.high, x.low): yield x[i] Closure iterators Inline iterators simultaneously have the advantage and disadvantage of being translated into loops. This means you can not pass them around. This limitation can be lifted by using closure iterators instead: import math proc powers(m: int): auto = #return iterator: int {.closure.} = # Make a closure explicitly return iterator: int = # Compiler makes this a closure for us for n in 0..int.high: yield n^m var squares = powers(2) cubes = powers(3) for i in 1..4: echo "Square: ", squares() # 0, 1, 4, 9 for i in 1..4: echo "Cube: ", cubes() # 0, 1, 8, 27 echo "Square: ", squares() # 16 echo "Cube: ", cubes() # 64 for x in squares(): # Go through all the remaining squares echo "Square: ", x # 25, 36, 49, 64, ... As you can see closure iterators keep their state. You can call them again and get the next value, or use them inside of a for-loop to get out many values. Templates You can think of templates as Nim’s equivalent to the C preprocessor. But templates are written in Nim itself and fit well into the rest of the language. Templates simply insert their code at the invocation site, working at the level of the abstract syntax tree. They can be used in just the same way as procs. Logger A common example are loggers, which we looked at in another article already. Consider that you want to have extensive debug logging in your program. A trivial implementation would look like this: import strutils, times, os type Level* {.pure.} = enum debug, info, warn, error, fatal var logLevel* = Level.debug proc debug*(args: varargs[string, `$`]) = if logLevel <= Level.debug: echo "[$# $#]: $#" % [getDateStr(), getClockStr(), join args] proc expensiveDebuggingInfo*: string = sleep(milsecs = 1000) result = "Everything looking good!" debug expensiveDebuggingInfo() [2016-06-05 22:00:50]: Everything looking good! We have to call expensiveDebuggingInfo to get the debugging info, which is fine right now since our logLevel is set to Level.debug. But it stops being fine when we instead set logLevel to anything higher than debug. Then it still takes a full second to evaluate the expensiveDebuggingInfo parameter for debug, but inside of debug nothing is done with that information. This is of course a consequence of call-by-value argument evaluation, which Nim uses, just as most other languages do. A notable exception would be lazy evaluation in Haskell, where this kind of logger would work perfectly fine, only calling expensiveDebuggingInfo when its value is actually needed. But let’s stay in Nim-land and use a template instead of a proc to magically fix this: template debug*(args: varargs[string, `$`]) = if logLevel <= Level.debug: const module = instantiationInfo().filename[0 .. ^5] echo "[$# $#][$#]: $#" % [getDateStr(), getClockStr(), module, join args] [2016-06-05 22:01:30][logger]: Everything looking good! Note that we also conveniently use instantiationInfo() to find out at what location in the program our template was instantiated, something we could not do using a procedure. We can still call the template in the exact same way as the proc. But now we have the advantage that the template is inlined at compiletime, so expensiveDebuggingInfo is only called if the runtime logLevel actually requires it. Perfect. Safe locking Another problem that can be solved with a template is automatically acquiring and releasing a system lock: import locks template withLock(lock: Lock, body: stmt) = acquire lock try: body finally: release lock Compile with --threads:on for platform independent lock support. This looks pretty simple, we just acquire the lock, execute the passed statements and finally release the lock, even if exceptions have been thrown. We can pass any set of statements as the body. The usage is as easy as using a built-in if statement: var lock: Lock initLock lock withLock lock: echo "Do something that requires locking" echo "This might throw an exception" When our template accepts a value of type stmt we can use the colon to pass an entire indented block of code. When we have multiple parameters of type stmt the do notation can be used. This gets transformed into: var lock: Lock initLock lock acquire lock try: echo "Do something that requires locking" echo "This might throw an exception" finally: release lock Now we will never forget to call release lock. You could use this to make a higher level locking library that only exposes withLock instead of the lower-level acquire and release primitives. Macros Just like templates, macros are executed at compiletime. But with templates you can only do constant substitutions in the AST. With macros you can analyze the passed arguments and create a new AST at the current position in any way you want. A nice property of Nim is that these compiletime macros are also written in the regular Nim language, so there is no need to learn another language. A simple way to create an AST is to use parseStmt and parseExpr to parse the regular textual representation into a NimNode. For example parseStmt("result = 10") returns this AST: StmtList Asgn Ident !"result" IntLit 10 A very useful way to find the AST of a piece of code is dumpTree: import macros dumpTree: result = 10 This is the same output as you get with treeRepr: import macros static: echo treeRepr(parseStmt("result = 10")) Alternatively you can use lispRepr to get a lisp-like representation: StmtList(Asgn(Ident(!"result"), IntLit(10))) Finally there is also the repr proc, which turns a NimNode AST back into its textual representation. Many beginners start by piecing strings together and finally calling parseStmt on them. While this works it is inefficient and prone to bugs. Instead you can use the macros module to create NimNodes of all kinds yourself. dumpTree gives you a hint if you’re not sure how a specific piece of code will look in its AST representation. JSON Parsing JSON is pretty popular, so let’s improve the support for it in Nim. What we want is to have a magical %* so that we can write JSON directly in Nim source code and have it checked at compile time, like this: var j1 = %* [ { "name": "John", "age": 30 }, { "name": "Susan", "age": 31 } ] So far if you want to use JSON in Nim, you have to use the JSON constructor % a lot: import json var j2 = %[ %{ "name": %"John", "age": %30 }, %{ "name": %"Susan", "age": %31 } ] Looks annoying. How can we implement %*? As a macro of course!: macro `%*`*(x: expr): expr = toJson(x) Ok, that doesn’t do anything interesting yet. We just call the still unspecified compile time proc toJson and return the result. We want toJson to traverse the passed AST x and create a new AST, which inserts a % call at just the right places, exactly as it would happen if we added the % calls manually. For this purpose we print the AST of j2 by putting it into dumpTree from the macros module: import json, macros dumpTree: %[ %{ "name": %"John", "age": %30 }, %{ "name": %"Susan", "age": %31 } ] We get the following AST printed when compiling this program: Prefix Ident !"%" Bracket Prefix Ident !"%" TableConstr ExprColonExpr StrLit name Prefix Ident !"%" StrLit John ExprColonExpr StrLit age Prefix Ident !"%" IntLit 30 Prefix Ident !"%" TableConstr ExprColonExpr StrLit name Prefix Ident !"%" StrLit Susan ExprColonExpr StrLit age Prefix Ident !"%" IntLit 31 This turned out quite big, but from here we can see how the AST we want to construct looks like. We do the same for j1 to see what we’re working with: StmtList Bracket TableConstr ExprColonExpr StrLit name StrLit John ExprColonExpr StrLit age IntLit 30 TableConstr ExprColonExpr StrLit name StrLit Susan ExprColonExpr StrLit age IntLit 31 The idea now is to insert a % at each level, except in front of the "name" and "age" in our case, the first elements in colon expressions. proc toJson(x: PNimrodNode): PNimrodNode {.compiletime.} = case x.kind of nnkBracket: # Corresponds to Bracket in dumpTree result = newNimNode(nnkBracket) for i in 0 .. <x.len: result.add(toJson(x[i])) # Recurse to add % of nnkTableConstr: # nnk stands for Nim node kind result = newNimNode(nnkTableConstr) for i in 0 .. <x.len: assert x[i].kind == nnkExprColonExpr result.add(newNimNode(nnkExprColonExpr) .add(x[i][0]) # First element: no % .add(toJson(x[i][1]))): # Second element: Recurse to add % else: result = x # End of recursion result = result.prefix("%") # Surround this level with % And that’s it! Now our %* works just as we want it to. If we did anything wrong, we can modify the macro to check the actual code it produces: macro `%*`*(x: expr): expr = result = toJson(x) echo result.repr # Print code representation of AST This prints: % [% {"name": % "John", "age": % 30}, % {"name": % "Susan", "age": % 31}] Perfect! This macro we just developed landed in Nim’s json module already. Enum Parsing optimization With enums we can create new types that contain ordered values, just like this: type Fruit = enum Apple, Banana, Cherry Strings can be parsed to an enum using parseEnum from strutils: let fruit = parseEnum[Fruit]("cherry") If we do this a lot, we notice that it’s kind of slow though: for i in 1 .. 10_000_000: var select = parseEnum[Fruit]("cherry") doAssert select == Cherry This takes 2.2 seconds on my machine. Let’s look at the definition of parseEnum to find out why: proc parseEnum*[T: enum](s: string): T = ## Parses an enum ``T``. ## ## Raises ``ValueError`` for an invalid value in `s`. The ## comparison is done in a style insensitive way. for e in low(T)..high(T): if cmpIgnoreStyle(s, $e) == 0: return e raise newException(ValueError, "invalid enum value: " & s) We can see the problem already. We iterate through all the values inside the enum type, from low(T) to high(T). Then $e creates a string of each enum value, which is quite expensive. Since we already know the type of the enum at compile time, we could create the strings at compile time as well. Again, let’s think about what we want the result to look like before writing the macro. Basically what we want to do is unroll the for loop at compile time: if cmpIgnoreStyle(s, "Apple") == 0: return Apple if cmpIgnoreStyle(s, "Banana") == 0: return Banana if cmpIgnoreStyle(s, "Cherry") == 0: return Cherry raise newException(ValueError, "invalid enum value: " & s) Now we can create the proc. Other than in the last example we won’t create the AST manually this time. Instead we use parseStmt to create a statement AST from a string containing Nim code. An equivalent parseExpr for expressions exists as well. Here’s how the final proc with a macro inside looks: proc parseEnum*[T: enum](s: string): T = macro m: stmt = result = newStmtList() for e in T: result.add parseStmt( "if cmpIgnoreStyle(s, \"$1\") == 0: return $1".format(e)) result.add parseStmt( "raise newException(ValueError, \"invalid enum value: \"&s)") #echo result.repr # To make sure we get what we want m() # Actually invoke the macro to insert the statements here Running the same code with our new implementation of parseEnum takes 0.5 seconds now, about 4 times faster than before. Great! HTML DSL We can use Nim’s templates and macros to create domain specific languages (DSL) that are translated into Nim code at compiletime. Nim’s syntax is quite flexible, so this is a powerful tool. As an example we build a simple HTML DSL. The goal is to be able to write this: proc page(title, content: string) {.htmlTemplate.} = html: head: title: title body: h1: title p: "Default Content" p: content echo page("My own website", "My extra content") And thus print the following HTML: <html> <head> <title> My own website </title> </head> <body> <h1> My own website </h1> <p> Default Content </p> <p> My extra content </p> </body> </html> For convenience we want to use the htmlTemplate macro as a pragma, annotated as {.htmlTemplate.}. Instead we could also write it in this way: htmlTemplate: proc page(title, content: string) = html: head: title: title body: h1: title p: "Default Content" p: content The htmlTemplate macro shall transform the page proc, adding a string return type and creating a new body out of the DSL definition, into this: proc page(title, content: string): string = result = "" result.add "<html>\n" ... result.add "</html>\n" Looks simple enough, here’s how the macro works: macro htmlTemplate(procDef: expr): stmt = procDef.expectKind nnkProcDef # Same name as specified let name = procDef[0] # Return type: string var params = @[newIdentNode("string")] # Same parameters as specified for i in 1..<procDef[3].len: params.add procDef[3][i] var body = newStmtList() # result = "" body.add newAssignment(newIdentNode("result"), newStrLitNode("")) # Recurse over DSL definition body.add htmlInner(procDef[6]) # Return a new proc result = newStmtList(newProc(name, params, body)) The real magic of recursively handling the HTML tags happens in htmlInner of course, a compiletime proc that calls itself recursively to iterate over the body definition: template write(arg: expr) = result.add newCall("add", newIdentNode("result"), arg) template writeLit(args: varargs[string, `$`]) = write newStrLitNode(args.join) proc htmlInner(x: NimNode, indent = 0): NimNode {.compiletime.} = x.expectKind nnkStmtList result = newStmtList() let spaces = repeat(' ', indent) for y in x: case y.kind of nnkCall: y.expectLen 2 let tag = y[0] tag.expectKind nnkIdent writeLit spaces, "<", tag, ">\n" # Recurse over child result.add htmlInner(y[1], indent + 2) writeLit spaces, "</", tag, ">\n" else: writeLit spaces write y writeLit "\n" We can check that we get the expected output by adding a simple echo result.repr at the end of htmlTemplate: proc page(title, content: string): string = result = "" add(result, "<html>\x0A") add(result, " <head>\x0A") ... add(result, "</html>\x0A") Where \x0A is just the newline character. Looks good and the output works! emerald is a much more complete HTML DSL that works in a similar manner. A simpler HTML generator is included in the standard library in the htmlgen module. Conclusion I hope you enjoyed this trip through Nim’s metaprogramming capabilities. Always remember: With great power comes great responsibility, so use the least powerful construct that does the job. This reduces complexity and makes it easier to understand the code and keep it maintainable. For further information and reference see: Discuss on Hacker News and r/programming.
https://hookrace.net/blog/introduction-to-metaprogramming-in-nim/
CC-MAIN-2017-51
refinedweb
2,681
61.87
A tag cloud from a recent End Point blog post. Tag clouds have become a fairly popular way to present data on the web. One of our Spree clients recently asked End Point to develop a tag cloud reporting user-submitted search terms in his Spree application. The steps described in this article can be applied to a generic Rails application with a few adjustments. Step 1: Determine Organization If you are running this as an extension on Spree pre-Rails 3.0 versions, you'll create an extension to house the custom code. If you are running this as part of a Rails 3.0 application or Spree Rails 3.0 versions, you'll want to consider creating a custom gem to house the custom code. In my case, I'm writing a Spree extension for an application running on Spree 0.11, so I create an extension with the command script/generate extension SearchTag. Step 2: Data Model & Migration First, the desired data model for the tag cloud data should be defined. Here's what mine will look like in this tutorial: Next, a model and migration must be created to introduce the class, table and it's fields. In Spree, I run script/generate extension_model SearchTag SearchRecord and update the migration file to contain the following: class CreateSearchRecords < ActiveRecord::Migration def self.up create_table :search_records do |t| t.string :term t.integer :count, :null => false, :default => 0 end end def self.down drop_table :search_records end end I also add a filter method to my model to be used later: class SearchRecord < ActiveRecord::Base def self.filter(term) term.gsub(/\+/, ' ') .gsub(/\s+/, ' ') .gsub(/^\s+/, '') .gsub(/\s+$/, '') .downcase .gsub(/[^0-9a-z\s-]/, '') end end Step 3: Populating the Data After the migration has been applied, I'll need to update the code to populate the data. I'm going to add an after filter on every user search. In the case of using Spree, I update search_tag_extension.rb to contain the following: def activate Spree::ProductsController.send(:include, Spree::SearchTagCloud::ProductsController) end And my custom module contains the following: module Spree::SearchTagCloud::ProductsController def self.included(controller) controller.class_eval do controller.append_after_filter :record_search, :only => :index end end def record_search if params[:keywords] term = SearchRecord.filter(params[:keywords]) return if term == '' record = SearchRecord.find_or_initialize_by_term(term) record.update_attribute(:count, record.count+1) end end end The module appends an after filter to the products#index action. The after filter method cleans the search term and creates a record or increments the existing record's count. If this is added directly into an existing Rails application, this bit of functionality may be added directly into one or more existing controller methods to record the search term. Step 4: Reporting the Data To present the data, I create a controller with script/generate extension_controller SearchTag Admin::SearchTagClouds first. I update config/routes.rb with a new action to reference the new controller: map.namespace :admin do |admin| admin.resources :search_tag_clouds, :only => [:index] end And I update my controller to calculate the search tag cloud data, shown below. The index method method retrieves all of the search records, sorts, and grabs the the top x results, where x is some configuration defined by the administrator. The method determines the linear solution for scaling the search_record.count to font sizes ranging from 8 pixels to 25 pixels. This order of terms is randomized (.shuffle) and linear equation applied. This linear shift can be applied to different types of data. For example, if a tag cloud is to show products with a certain tag, the totals per tag must be calculated and scaled linearly. class Admin::SearchTagCloudsController < Admin::BaseController def index search_records = SearchRecord.all .collect { |r| [r.count, r.term] } .sort .reverse[0..Spree::SearchTagCloud::Config[:count]] max = search_records.empty? ? 1 : search_records.first.first # solution is: a*x_factor - y_shift = font size # max font size is 25, min is 8 x_factor = (Spree::SearchTagCloud::Config[:max] - Spree::SearchTagCloud::Config[:min]) / max.to_f y_shift = max.to_f*x_factor - Spree::SearchTagCloud::Config[:max] @results = search_records.shuffle.inject([]) do |a, b| a.push([b[0].to_f*x_factor - y_shift, b[1]]) a end end end The data is presented to the user in the following view: <h3>Tag Cloud:</h3> <div id="tag_cloud"> <% @results.each do |b| %> <span style="font-size:<%= b[0] %>px;"><%= b[1] %></span> <% end -%> </div> Step 5: Adding Flexibility In this project, I added configuration variables for the total number of terms displayed, and maximum and minimum font size using Spree's preference architecture. In a generic Rails application, this may be a nice bit of functionality to include with the preferred configuration architecture. Example tag cloud from the extension. Additional modifications can be applied to change the overall styling or color of individual search terms. Conclusion These steps are pretty common for introducing new functionality into an existing application: data migration and model, manipulation on existing controllers, and presentation of results with a new or existing controller and view. Following MVC convention in Rails keeps the code organized and methods simple. In the case of Spree 0.11, this functionality has been packaged into a single extension that is abstracted from the Spree core. The code can be reviewed here, with a few minor differences. 2 comments: Hi Steph, any particular reason you still using spree 0.11? Hi, We have a handful of clients that are on different versions of Spree. I believe only one of them is on Rails 3 Spree, but most of them are on 0.11 at the moment. On new projects, I wouldn't have start recommending using Spree Rails 3.0 until a month or so ago. For other clients on 0.11, it would be a large undertaking to upgrade because virtually all of their custom code would need to be refactored, and I don't think they'd have much gain from it in terms of Spree features at this point. ~Steph
http://blog.endpoint.com/2011/03/rails-tag-cloud-tutorial-spree.html
CC-MAIN-2016-36
refinedweb
994
57.98