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
Hi there ! I’m trying to make a menu in an LCD, this menu has 2 buttons, the first one is a selection button and the other one is an “OK” button, what I want is to select a song, and after that when I press “OK”, i’ll get, on the buzzer, a melody played by the buzzer depending on which menu I selected of course. What I need is a synchronization between the menu I’m actually choosing and the song to be played, what I mean by that is, in my menu, the first option, for example, Queen, must actually play me a Queen song and not any of the other melodies, what I thought might be a good idea is, to make a counter, which will count everytime I press the selection button, I have 4 different bands in my menu, so the counter will go 0 1 2 3 0 1 2 3 0 and therefore, when I’ll press OK, the program will check the counter, lets suppose for instance its equal to 2 and will launch melody 2. I know this may seem long and pretty basic, but I’m totally new to Arduino & programming so I’m trying to apply basic ideas. My program : #include <LiquidCrystal.h> LiquidCrystal lcd(12, 11, 7, 6, 5, 4); int RIGHT = 8; //This is the selecting button int OK = 13; //You know what this one is for int count = 0; //Initialising my counter const int menuSize = 4; //how many menus i want String menuItems[menuSize]; int currentMenu = 0; //The first menu you get when powering up the arduino bool RIGHTLastState = HIGH; //Helps for the menu program int buzzer = 3; //My buzzer void setup() { // put your setup code here, to run once: Serial.begin(9600); // First menu name menuItems[0]= “QUEEN” ; // Second menu name menuItems[1]= “PINK FLOYD” ; // third menu name menuItems[2]= “MUSE” ; // fourth menu name menuItems[3]= “LED ZEPPELIN” ; lcd.begin(16, 2); lcd.print(menuItems[currentMenu]); //Printing the first menu right when we plug in the arduino Serial.println(count); pinMode(OK, INPUT_PULLUP); pinMode(RIGHT, INPUT_PULLUP); pinMode(buzzer, OUTPUT); } void loop() { if(digitalRead(RIGHT) != RIGHTLastState) { if (RIGHTLastState = !RIGHTLastState) { if (currentMenu>0) { currentMenu–; count ++; if (count >= 4) { count = 0; } } else { currentMenu = menuSize - 1 ; } lcd.clear() ; lcd.print(menuItems[currentMenu]); Serial.println(count); } else { } } delay(150); } Now I have on my LCD the name of the four bands, the selecting button is working fine, however, the counter isnt working properly, I have at init on my serial board, 0 after that when I press the OK button, i have 0 and then 1 2 3 0 sometimes 0 1 1 2 3 0 sometings 0 1 2 3 3 0 I dont know why. So my issues are, first how do I fix this counter problem, and secondly how to make it play a melody depending on which number the counter is in, example, I want to play a Led Zeppelin melody, the country must be equal to 3, what can I add to my program to play me melody 2, knowing that I already have the melody in another program.
https://forum.arduino.cc/t/play-a-melody-using-pushbuttons-counter/448613
CC-MAIN-2021-31
refinedweb
525
50.13
From: Matthias Troyer (troyer_at_[hidden]) Date: 2002-05-17 07:23:19 On Friday, May 17, 2002, at 01:43 PM, Neal D. Becker wrote: >>>>>> "Victor" == Victor A Wagner, <vawjr_at_[hidden]> writes: > > Victor> At Thursday 2002/05/16 10:27, you wrote: >>> The problem seems to be: >>> >>> friend std::ostream& operator<<(std::ostream& os, const >>> shuffle_output& s) >>> { >>> os << s._rng << " " << s.y << " "; >>> std::copy(s.v, s.v+k, std::ostream_iterator<result_type>(os, " ")); > > Victor> std::copy(s.v, s.v+k, > Victor> > std::ostream_iterator<shuffle_output::result_type>(os, " ")); > > Victor> won't that work?? > > I would have guessed that would work, but it doesn't. gcc-3.1 gives a > parse error. > > I don't know what is a good fix for this problem. On the gcc-3.1 version of Apple for Darwin/MacOS X I got it to work just by adding another include: #include <iterator> // std::ostream_iterator I have sent the patch with a few extensions to boost::random to Jens, but I guess fixing this is more urgent than the extensions I sent to Jens. The same patch is needed in boost/random/mersenne_twister.hpp Best regards, Matthias Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2002/05/29822.php
CC-MAIN-2019-43
refinedweb
212
59.8
0 I am working on a struct. The two requirements are for the user to be able to input an entry and then view it. I have two questions, when entering the data shouldn't I be able to enter spaces when entering the address i.e. 654 smith st and store that as address1? and why am i getting a memory addres for my print function? it displays , -654649840 #include <string> #include <iostream> using namespace std; struct playerType { string first; string last; string address1; string address2; string city; string state; string zip; int jersey; }; //end struct void readIn(playerType player) { cin >> player.first >> player.last; cin >> player.address1 >> player.address2; cin >> player.city >> player.state; cin >> player.zip >> player.jersey; } void printPlayer(playerType player) { cout << endl << endl << player.first << " " << player.last << endl << player.address1 << endl << player.address2 << endl << player.city << ", " << player.state << " " << player.zip << endl << player.jersey << endl; } int main() { playerType player; cout << "Enter all of the player's information in order shown\n" "pressing Enter after each entry. First name, last name,\n" "address line 1, address line 2, city, state, zip, and jersey number: "; readIn(player); printPlayer(); } //end main
https://www.daniweb.com/programming/software-development/threads/68521/struct-output-help
CC-MAIN-2017-04
refinedweb
192
60.82
So the part where it gets fuzzy is the timestamp saved and converting it to readable and editable format. I am also not very good working with time still. So i figured the "save file" will save the unix epoch of the time the person quit smoking. The option of reseting the quit date to "now" is easy as it is just time.time(). But getting the users input of month, day, year, hour, minute, etc. and then converting that into a unix timestamp to save it is where i am having the problem. I may be missing a simple solution that you guys might know, but this was my first go at this problem. I figured to get the user input, convert that to unix epoch using the pattern, and save it that way? this is the code i have made for this - Code: Select all import time class TimeConvert: def __init__(self): self.time_string = '03/11/2013 11:05 AM' self.pattern = '%m/%d/%Y %I:%M %p' self.time_stamp = 0 self.tweny_four_hour_format = '%m/%d/%Y %H:%M:%S' #the H and no p self.twelve_hour_format = '%m/%d/%Y %I:%M:%S %p' #the I for 12's, and p for AM/PM def convert_string_to_epoch(self, string): self.time_stamp = int(time.mktime(time.strptime(string, self.pattern))) def convert_epoch_to_string(self, epoch, pattern=None): if not pattern: pattern = self.pattern self.time_string = time.strftime(pattern, time.localtime(epoch)) def update_pattern(self, new_pattern): self.convert_epoch_to_string(time.time(), pattern=new_pattern) self.pattern = new_pattern timer = TimeConvert() def test(timer): print(timer.time_stamp) print(timer.pattern) print(timer.time_string) #test(timer) timer.convert_string_to_epoch('03/11/2013 11:10 AM') test(timer) timer.convert_epoch_to_string(time.time()) test(timer) timer.update_pattern('%m/%d/%Y %I:%M %p') test(timer) The problem with this method is i was going to allow the user to edit the pattern as he sees fit, which would nullify the conversion to and from string_time and epoch. I am not sure how to do both. I have looked into datetime module, and i was first using that, but then i switched it all to use the time module. Probably beacuse i am more comfortable with it as i used it more. Not sure i havent messed with time much using python and i need to play wit hit to understand it more
http://www.python-forum.org/viewtopic.php?p=1361
CC-MAIN-2014-41
refinedweb
391
67.35
Attached simple NetBeans Platform Application which reproduces the problem, environment: Product Version: TestProject 200801291616 Java: 1.6.0_04; Java HotSpot(TM) Client VM 10.0-b18 System: Windows XP version 5.1 running on x86; Cp1250; cs_CZ (testproject2) I've created new NetBeans Platform Application, added TestAction (extends AbstractAction) and registered it in layer.xml as Actions/Other/testmodule-TestAction.instance and Menu/File/testmodule-TestAction.shadow (pointing to original testmodule-TestAction.instance). After the application started, two instances of TestAction were created but I expected that only one instance is created based on the structure of layer.xml. Setting priority to P2 as this caused serious problems in real application which were quite hard to debug and time-consuming to workaround (== rewriting tens of such actions to singletons). Real action registered itself as a listener to some component of my application and because of two action instances being registered each event produced duplicate results. Created attachment 59627 [details] Simple NetBeans Platform Application reproducing the problem Just a note - for debug purposes '>>> Created TestAction instance #{X}' is sent to the System.err when instance of the action is created, after the application starts you can find the following in logfile: >>> Created TestAction instance #1 >>> Created TestAction instance #2 I guess you do not expect me to fix and integrate this into 6.1, don't you? Otherwise you would have reported this issue a week ago... No I don't, take your time to investigate:o) I have to use 6.0.1 platform for now, anyway. Dafe, please take this one. I think I found it in InstanceDataObject - when instance creation is defined in xml layer through instanceCreate attribute (method call) and there is no instanceClass attribute, infrastructure has no way of finding out the instance class then to create instance and getClass() from it. However, this created instance is forgotten and creation is repeated again when instance is needed. This particular example will be fixable I think, but generally if instanceClass attribute is missing, infrastructure can't guarantee only one instance - when InstanceDataObject.findFO is called, then we can choose - either FO will not be found or we have to instantiate instance definition which is without instanceClass attribute. fixed with test, unfortunately writing the test took me almost two days, as I'm unfamiliar with the IDO and MenuBar code: Btw: jis, I think using "instanceCreate" methodvalue without "instanceClass" supplied may not be good for performance, instance is created sooner that it could be. Reopening, I have to rollback the fix, it caused P1 - 141682 This issue is not fixable - system can't guarantee only one instance of registrations which use "instanceCreate" attribute but are missing "instanceClass" attribute. System has no other chance but to actually create instance in order to get class name in this situation. Unfortunately, such instance is created too soon, for example during FolderLookup creation on some registration folder, and so it doesn't work OK, as whole system expects that instance is really created when instanceCreate(..) is called. Conclusion: Add instanceClass when using instanceCreate attribute. Otherwise your object can be created multiple times (2 times mostly it seems). I added warning log for such situations: Integrated into 'main-golden', available in build *200808010201* on Changeset: User: Dafe Simonek <dsimonek@netbeans.org> Log: backout of 80eea651d4d9 (fix of #131951) I'll report all the warnings to appropriate components [reference issue #142550] This doesn't look right to me. Please do not file issues for modules to add this attribute until the situation has been properly reviewed. I would recommend #d20eab2d47d8 also be reverted for now. <file name="testmodule-TestAction.instance"> <attr name="instanceCreate" methodvalue="testmodule.TestAction.create"/> </file> is a perfectly good instance registration. Adding an instanceClass attribute should not be necessary, and we have repeatedly told people in various forums not to add it. In general, <attr name="instanceClass" stringvalue="C"/> is just a shortcut for <!-- if needed --><attr name="instanceOf" stringvalue="C"/> <attr name="instanceCreate" newvalue="C"/> There is no guarantee in general that a FileObject attribute will be instantiated only once. The filesystem should cache the created value so long as it is held in some other way (i.e. weakly cache), and FolderInstance may cache instances associated with files for a while, but that is all. If a module breaks due to assuming that an object-valued attribute is created only once, the fault is generally in the module. Anyway no comment in this issue explains to my satisfaction what the real problem here was. No one should be calling InstanceCookie methods on an item in Actions/ or Menu/ except MenuFolder, which should ask for IC.instanceCreate anyway. If this is not the case, I want to see a stack trace. The original use case was for VisualVM which defines its own folder in layer for contents of its context menus. InstanceCookie is used here to resolve action instances. The problem is that VisualVM defines an action which needs to register itself as a listener to another class. This action needs to have exactly one instance, thus .instance is used in one folder and .shadow at other places of the layer. Expected behavior - only one action instance is created (otherwise the whole .shadow think doesn't make much sense for me). Actual behavior - two instances of the action are created, causing ugly side effects (2 listeners being registered) which are very difficult to debug. I haven't found any explicit note that more than one instance may be created when using .shadow, so if not fixable, I think that current logging the warning is the best approach. I would also strongly suggest to describe this behavior visibly in some docs, showing concrete code examples ensuring that exactly one instance being created (singleton). Given how much other actions could potentially be also affected (based on warnings logging during IDE startup) I'm also cc'ing performance as this may noticeable impact startup performance. I don't believe the issue has to do with use of *.shadow files, which just delegate their InstanceCookie to the original *.instance file anyway. I certainly agree it is desirable to not create more than one instance from a *.instance. I do not agree that the system is required to do so in all situations - just make a best effort. If registering >1 listener from your Action instance is a real problem rather than just an oddity when debugging (and you have do not use WeakListener, so both listeners remain active indefinitely), then you should register a single heavyweight listener from static code, and have the Action instances register lightweight proxy listeners to this static source (or use WeakSet to enable the static listener to refire changes to all extant instances). What I am opposed to specifically is the use of instanceClass as a workaround for some underlying bug which I have not seen adequately described or investigated. (Why is the object being instantiated more than once? Is the first instance being held strongly by infrastructure code or not? Who was calling InstanceCookie.instanceClass and why?) Probably instanceClass should be deprecated altogether as its functionality is completely subsumed by instanceCreate. (Plus instanceOf where this is necessary, which it should not be for action registrations - generally instanceOf should only be needed for instances in the effectively deprecated Services/ folder.) Furthermore, instanceClass and instanceCreate should be mutually exclusive. Since there has been no comment from Dafe so far, I am opening a separate issue #142836 requesting that the console warning be removed, and that no one be asked to use instanceClass gratuitously. This issue - that sometimes extra instances are created which ideally would not be - can be left as is or reopened independently. Jesse, I think we have misunderstanding here. Please read my detailed comments above, while I'll try to describe what we have: 1) Bug impact Looking at log info in related 142550, we can see that: - at least 25 menu actions is instantiated twice during every startup - at least 3 navigator panels are instantiated twice during every startup - about 10 other actions in Loaders/text and Editors/text are instantiated twice during every startup - about 12 option panel controllers are instantiated twice when Tools/Options is invoked for first time ...and probably lots of other things which wasn't caught I'll try to attach thread dumps of multiple instantiations 2) State of fix I did what i could and the best thing with which I could came is logging warning and using instanceClass attribute. if anybody come with better solution, I'm perfectly happy with it and I'll remove warning immediately. But so far, I think warning is the best what we have. Certainly we shouldn't let the things as they are now - I expected this issue to be P0 release stopper for performance team. Of course we should not gratuitously reinstantiate instances. The problem is the workaround with instanceClass, which makes no sense from an API perspective. If I had <file name="x.instance"> <attr name="instanceCreate" methodvalue="some.Factory.create"/> </file> where package some; public class Factory { public static Action create() { return new Action() {...}; } } should I then change my layer to the following? <file name="x.instance"> <attr name="instanceCreate" methodvalue="some.Factory.create"/> <attr name="instanceClass" stringvalue="some.Factory$1"/> </file> This is clearly not an acceptable long-term workaround. I have read your earlier comments in this issue but they do not explain what is needed to look for a proper fix: 1. Exactly what happens in the filesystems/datasystems/settings infrastructure (which module? which line of code?) that causes an object to be instantiated twice. 2. Why adding an instanceClass attribute causes this bug not to appear. Something like InstanceDataObjectModule38420Test should also be useful in debugging the problem, though this test does use instanceClass. Created attachment 66707 [details] thread dumps of instantiations, which explains what is going on After off line discussion with jtulach, I'm passing back to him for better fix. Sorry I didn't come with something better myself... Note I was not exact with my bug impact estimations - most of our actions somehow survive and are instantiated just once. It seems that only actions that extends javax.swing.Action purely are affected. SystemAction's, or indeed any objects assignable to SharedClassObject, would not be affected. FolderList seems to be calling instanceOf for a reasonable purpose - to find nested Lookup's, before actually creating normal instances. ActionsList is calling instanceOf just to check for JSeparator's, which it will not create. Should BinaryFS$AttrImpl.getValue be caching the value, at least during startup? Seems in general that caching of methodvalue/newvalue/serialvalue attributes is desirable. InstanceDataObject$Ser.instanceCreate does keep a soft cache of the created object, which is fine. There is an obvious problem that getClassName does not use this cache even when it exists! (If a full GC happened to intervene, and there was no extant hard ref, then the object would be recreated - which is OK.) Right, also see my first fix,, I tried to fill InstanceDataObject$Ser soft ref cache in getClassName, but the problem is that instance is created "too soon" and it leads to 141682, and possibly other similar issues, which I didn't know how to fix. I can add a special API to XMLFS and BinaryFS to provide special handling of "instanceClass" for newvalue and methodvalue. In case of newvalue, it is quite easy. In case of methodvalue, I would use the return type of the method - not absolutely correct, but hopefully correct enough. #80eea651d4d9 looks right to me. What was the problem? "Too soon" for whom exactly? "Too soon" for org.netbeans.modules.options.colors.FontAndColorsPanelController:82, description of what happened is in 141682. In short, Lookup.forPath("some valid path").lookupApp(Object.class) returned empty result for FontAndColorsPanelController instance - I wasn't able to exactly find out why. "Lookup.forPath("some valid path").lookupAll(Object.class) returned empty result" - that sounds more like the real problem. Perhaps a bug in FolderLookup? I guess the best fix is to enhance contract of XMLFileSystem.getAttribute. Passing to Jirka to review and apply the patch. Created attachment 67384 [details] hg out -p of the change that introduces getAttribute("class:attrName") handling Reviewers speak up, so that Jirka or me can integrate next week. Jesse is on vacation I think. DS01: What will happen if clients will code creation method returning not exact type, like this: public static synchronized Action create() ... instead of public static synchronized CreateOnlyOnceAction create()? I think info about class will not be precise then - isn't it a bit of problem - I mean that some isAssignable tests may fail, isn't it right? (I don't know if there are any such places in the system, just theoretically) Re. DS01, there is a test with Runnable to demonstrate the behaviour. Hopefully not many things fail due to that, but you are right, due to the methodvalue type guessing this is in fact semantically incompatible change. Ok VV01: We support C and C++ mime-types and have some actions with constructor MyAction(boolean cpp) we don't want to expose internal Action classes at all, so we have factory methods, but even if we are: public static MyAction craeteCAction() { return MyAction(false);} public static MyAction craeteCppAction() { return MyAction(true);} does it mean that now only one random (the first initialized) action will be instantiated? Re: VV1, right now your method craeteCAction() is called twice. As well as your craeteCppAction() method. After the fix, each of your methods will be called just once. Using MQ, or otherwise producing a single patch for review (e.g. using hg diff -r ... -r ...), would be more friendly than forcing reviewers to look over several patches of which the later partially overwrite the former. [JG01] The mistyped overload of methodValue (in both XMLMapAttr and BinaryFS) is confusing. Better would be to make it return Method (or null), and move the call to Method.invoke into the getObject method's body. [JG02] BinaryFS.getType should return Class<?>. Also apichanges should specify that a java.lang.Class object is returned, not a String class name. Re:[JG01] There is some logic which handles parameters of method. It needs to be duplicated if we want to separate it. Re:[JG02] Agree but apichanges doesn't need to be updated because BinaryFS.AttrImpl is not public API. Otherwise I am going to integrate the patch as it is. JG01 - it is true that methodValue would in fact need to return a struct of (Method, Object[]). No code duplication is needed; the current call point would call setAccessible and invoke, and the new call point would ignore the Object[] and just use Method.getReturnType. JG02 - sorry for confusion, the "apichanges" I was referring to was openide.filesystems/{apichanges,arch}.xml. BTW this description of behavior should IMO be moved to the XMLFileSystem class Javadoc, not arch.xml, and apichanges.xml should just have a brief mention of the change (leave the details to real documentation). Re: JG01 - OK, I added MethodAndParams to store Method and Object[]. Please, look at it if I get it right. Re: JG02 - Description moved from arch.xml to XMLFilesystem. If you feel it needs to be more polished, please send me a patch. Created attachment 68097 [details] Updated patch. JG01 - clearer, thanks. BTW you can delete getParams(). JG02 - the change I originally requested was to note that the value type is Class, not String. Don't forget to remove the warning in InstanceDataObject, and close issue #142550, issue #142539, issue #142541, issue #142543, issue #142544, issue #142546, issue #142540, and issue #142836 as INVALID. The warning shall stay there, imho. It is not printed if the underlaying fs supports the "class:XYZ" semantics, but in case someone would use for example custom SFS extensions, it could still be useful to identify ineffective registrations. Almost everyone in practice is going to be using XMLFileSystem (in unit tests) and BinaryFS (in the real app). Any warning printed in such a case is just confusing and irritating - filling up the log file with bad advice. In those cases where instanceOf is actually important (i.e. where a correct instanceOf may permit instanceCreate to never be called at all), then the correct attribute to declare is instanceOf, not instanceClass! A warning is acceptable in case (1) instanceOf actually matters (though this is perhaps impossible to check from InstanceDataObject, since it depends on the caller's behavior); (2) instanceOf has not been declared; (3) a strange FileSystem impl is in use which does not support 'class:instanceCreate'. > Almost everyone in practice is going to be using XMLFileSystem (in unit tests) and BinaryFS (in the real app). Any > warning printed in such a case is just confusing and irritating - filling up the log file with bad advice. The current patch prints no warnings in this cases - because both of these systems support "class:XYZ" extension. So please keep the warning there for the other cases that may happen when people inject their own filesystem implementations into the systemfilesystem. Integrated (warning not removed). The warning can stay for such hypothetical cases but it is still wrong - it should ask them to specify instanceOf, not instanceClass. Integrated into 'main-golden', available in build *200808251401* on Changeset: User: Jiri Skrivanek <jskrivanek@netbeans.org> Log: #131951 - Supress creating of two instances of a class. If you are interested just in the Class of an attribute, but without creating its instance, use fileObject.getAttribute("class:attrName"). This instructs the XMLFileSystem to scan its XML files for definition of attrName attribute and guess its class. Integrated into 'main-golden', available in build *200808280201* on Changeset: User: Jiri Skrivanek <jskrivanek@netbeans.org> Log: #131951 - Warning message should ask for instanceOf instead of instanceClass. Given this is an incompatible change, shouldn't it be marked as incompatible somewhere? BTW: java.debug is broken due to this, I will likely need to introduce ModuleInstall to fix it. In what way is this incompatible? How is java.debug broken? Consider filing a separate issue blocking this one. Yes, please report the incompatibility and let us know. I guess the incompatible change is in loaders, so please create new issue. From what I know, if a methodvalue references a method which return type is j.l.Object but would return an instance of String, and someone does lookup(String.class) (over the corresponding folder), the lookup result would contain the String from the method before this patch, but wouldn't after this patch. Jarda seems to talk about it in desc32. That's true, but unavoidable I think if the patch is to work at all. The workaround would simply be to declare <attr name="instanceOf" stringvalue="java.lang.String"/>
https://netbeans.org/bugzilla/show_bug.cgi?id=131951
CC-MAIN-2014-15
refinedweb
3,132
56.15
I created a public class with 2 static methods (string utilities) which work fine when this class file is in the same directory as the class file which is using an import statement to access it. So the next step seemed to be to put my string utility class in a myutils.jar file and store it in the jre\lib\ext directory so that I would be able to reference it in an import statement from other class files. A new class file that imports from and references the class in myutils.jar compiles fine, but running it at the command line gives a "NoClassDefFoundError". (This is using jdk1.3) Any thoughts, ideas, suggestions? Thanks in advance dm Forum Rules Development Centers -- Android Development Center -- Cloud Development Project Center -- HTML5 Development Center -- Windows Mobile Development Center
http://forums.devx.com/showthread.php?29004-Problem-accessing-a-class-in-a-jar-file&p=64744&mode=threaded
CC-MAIN-2017-51
refinedweb
137
63.19
@imz--IvanZakharyaschev comments on pehrs's answer that it may be possible with the introduction of namespaces, but this hasn't been tested and posted as an answer. Yes, that does indeed make it possible for a non-root user to use chroot. Given a statically-linked dash, and a statically-linked busybox, and a running bash shell running as non-root: dash busybox bash $ mkdir root $ cp /path/to/dash root $ cp /path/to/busybox root $ unshare -r bash -c 'chroot root /dash -c "/busybox ls -al /"' total 2700 drwxr-xr-x 2 0 0 4096 Dec 2 19:16 . drwxr-xr-x 2 0 0 4096 Dec 2 19:16 .. drwxr-xr-x 1 0 0 1905240 Dec 2 19:15 busybox drwxr-xr-x 1 0 0 847704 Dec 2 19:15 dash The root user ID in that namespace is mapped to the non-root user ID outside of that namespace, and vice versa, which is why the system shows files owned by the current user as owned by user ID 0. A regular ls -al root, without unshare, does show them as owned by the current user. ls -al root unshare Note: it's well-known that processes that are capable of using chroot, are capable of breaking out of a chroot. Since unshare -r would grant chroot permissions to an ordinary user, it would be a security risk if that was allowed inside a chroot environment. Indeed, it is not allowed, and fails with: unshare -r unshare: unshare failed: Operation not permitted unshare: unshare failed: Operation not permitted which matches the unshare(2) documentation (apologies for the weird bolding, but that's what it looks like): EPERM (since Linux 3.9) CLONE_NEWUSER was specified in flags and the caller is in a chroot environment (i.e., the caller's root directory does not match the root directory of the mount namespace in which it resides). EPERM (since Linux 3.9) CLONE_NEWUSER was specified in flags and the caller is in a chroot environment (i.e., the caller's root directory does not match the root directory of the mount namespace in which it resides).. By posting your answer, you agree to the privacy policy and terms of service. asked 4 years ago viewed 4869 times active 14 days ago
http://serverfault.com/questions/135599/ubuntu-can-non-root-user-run-process-in-chroot-jail?answertab=active
CC-MAIN-2014-52
refinedweb
385
57.71
Best Practice for storing custom sub functionsFrank Heuer Aug 12, 2015 2:25 AM Hello, I am just thinking about where to put script files with my custom functions within QDF. You know, each container has got the "..3.Include\4.Sub" folder. But isn't that folder an exclusive folder for the framework. So if I put a file there named i.e. "13.mysub.qvs" will it be replaced by an update procedure of QDF? Also: If I add my custom file to "99.LoadAll.qvs" I guess this adding will be worth nothing in respect to QDF updates. So is "..3.Include\6.Custom" a better location for placing custom sub scripts? I miss an advice from the QDF team in the documentation. So could you give an advice? Could you tell how QDF updates handle this use case? Regards Frank Re: Best Practice for storing custom sub functionsRumen Vasilev Jul 16, 2015 3:49 AM (in response to Frank Heuer) Hi Frank, I had the same issue last week. I have just stored my own files with a bigger number e.g. "101.mysub.qvs", "102.mysub.qvs", "103.mysub.qvs" and so on. Re: Best Practice for storing custom sub functionsDamian Waldron Jul 16, 2015 4:45 AM (in response to Frank Heuer) My approach to date has been to place custom sub routines in 99.Shared_Folders\3.Include\4.Sub\Custom - I place them in Shared as then all containers will automatically have access to the routines. Note that Shared is automatically loaded as part of init. - I create a Custom Folder to ensure that it is clear that these are not standard for the QDF. _ Although i haven't done it to date I am thinking of prefixing custom sub routines with Custom_ therefore ensuring that there is no chance of a standard routine with the same name. If you have some useful routines it would be great to share them. These may lead to further standard routines being included in the QDF. Re: Best Practice for storing custom sub functionsFrank Heuer Aug 12, 2015 2:41 AM (in response to Damian Waldron ) Hallo Damian (and Rumen), thank you for sharing your knowledge. Until know there are no more advices so I will start with Damians approach. I will create a subfolder named "Custom" and store my files there. Maybe I also put a 99.LoadAll file into it as well. I will prefix my function names as well so there will be a custom namespace for my functions. I will use the prefix "Custom." now. What do you think about the functions within QDF. Should future versions of QDF also prefix their functions with i.e. "QDF." (watch the full stop at the end, dividing prefix and function name) so that they have there own namespace as well? So if this is a "best practice" QDF team should add a named prefix and a "Custom" folder to the QDF standard and documentation. Let me know what you think about. Regards Frank
https://community.qlik.com/thread/172789
CC-MAIN-2017-30
refinedweb
510
73.68
while everyone is busy , i am free while everyone is busy , i am free Shiao Kung Chux wrote:1.public class Test { 2.public static void main(String [] args) { 3.byte [][] big = new byte[7][7]; 4.byte [][] b = new byte[2][1]; 5.byte b3 = 5 ; 6.byte b2 [][][][] = new byte[2][3][1][2]; 7. 8.} 9.} which code can insert into line 7 and compile successful (choise 4) A. b2[0][1] = b; B. b[0][0] = b3; C. b2[1][1][0]= b[0][0]; D. b2[1][2][0] = b; E. b[0][1][0][0] = b[0][0]; F. b2[0][1] = big; accord to the text book , the answer is A,B,E,F. i do not understand why C is false? if C is false why E is true? why D is false? if D is false, why A is true?
https://coderanch.com/t/252626/certification/SCJP-exam-array-variable-assign
CC-MAIN-2022-33
refinedweb
149
99.12
Our application complexity has hit its tipping point, and we decide to move past anemic domain models to rich, behavioral models. But what is this anemic domain model? Let’s look at Fowler’s definition, now over 6 years. For CRUD applications, these “domain services” should number very few. But as the number of domain services begins to grow, it should be a signal to us that we need richer behavior, in the form of Domain-Driven Design. Building an application with DDD in mind is quite different than Model-Driven Architecture. In MDA, we start with database table diagrams or ERDs, and build objects to match. In DDD, we start with interactions and behaviors, and build models to match. But one of the first issues we run into is, how do we create entities in the first place? Our first unit test needs to create an entity, so where should it come from? Creating Valid Aggregates Validation can be a tricky beast in applications, as we often see validation has less to do with data than it does with commands. For example, a Person might have a required “BirthDate” field on a screen. But we then have the requirement that legacy, imported Persons might not have a BirthDate. So it then becomes clear that the requirement of a BirthDate depends on who is doing the creation. But beyond validation are the invariants of an entity. Invariants are the essence of what it means for an entity to be an entity. We may ask our customers, can a Person be a Person (in our system) without a BirthDate? Yes, sometimes. How about without a Name? No, a Person in our system must have some identifying features, that together define this “Person”. An Order needs an OrderNumber and a Customer. If the business got a paper order form without customer information, they’d throw it out! Notice this is not validation, but something else entirely. We’re asking now, what does it mean for an Order to be an Order? Those are its invariants. Suppose then we have a rather simple set of logic. We indicate our Orders as “local” if the billing province is equal to the customer’s province. Rather easy method: public class Order { public bool IsLocal() { return Customer.Province == BillingProvince; } I simply interrogate the Customer’s province against the Order’s BillingProvince. But now I can get myself into rather odd situations: [Test] public void Should_be_a_local_customer_when_provinces_are_equal() { var order = new Order { BillingProvince = "Ontario" }; var customer = new Customer { Province = "Ontario" }; var isLocal = order.IsLocal(); isLocal.ShouldBeTrue(); } Instead of a normal assertion pass/fail, I get a NullReferenceException! I forgot to set the Customer on the Order object. But wait – how was I able to create an Order without a Customer? An Order isn’t an Order without a Customer, as our domain experts explained to us. We could go the slightly ridiculous route, and put in null checks. But wait – this will never happen in production. We should just fix our test code and move on, right? Yes, I’d agree if you were building a transaction-script based CRUD system (the 90% case). However, if we’re doing DDD, we want to satisfy that requirement about aggregate roots, that its invariants must be satisfied with all operation. Creating an aggregate root is an operation, and therefore in our code “new” is an operation. Right now, invariants are decidedly not satisfied. Let’s modify our Order class slightly: public class Order { public Order(Customer customer) { Customer = customer; } We added a constructor to our Order class, so that when an Order is created, all invariants are satisfied. Our test now needs to be modified with our new invariant in place: [TestFixture] public class Invariants { [Test] public void Should_be_a_local_customer_when_provinces_are_equal() { var customer = new Customer { Province = "Ontario" }; var order = new Order(customer) { BillingProvince = "Ontario" }; var isLocal = order.IsLocal(); isLocal.ShouldBeTrue(); } } And now our test passes! Summary and alternatives Going from a data-driven approach, this will cause pain. If we write our persistence tests first, we run into “why do I need a Customer just to test Order persistence?” Or, why do we need a Customer to test order totalling logic? The problem occurs further down the line when you start writing code against a domain model that doesn’t enforce its own invariants. If invariants are only satisfied through domain services, it becomes quite tricky to understand what a true “Order” is at any time. Should we always code assuming the Customer is there? Should we code it only when we “need” it? If our entity always satisfies its invariants because its design doesn’t allow invariants to be violated, the violated invariants can never occur. We no longer need to even think about the possibility of a missing Customer, and can build our software under that enforced rule going forward. In practice, I’ve found this approach actually requires less code, as we don’t allow ourselves to get into ridiculous scenarios that we now have to think about going forward. But building entities through a constructor isn’t the only way to go. We also have: The bottom line is – if our entity needs certain information for it to be considered an entity in its essence, then don’t let it be created without its invariants satisfied!
http://lostechies.com/jimmybogard/2010/02/24/strengthening-your-domain-aggregate-construction/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%253A+LosTechies+%2528LosTechies%2529
crawl-003
refinedweb
887
64.1
Category:Wren-regex This is an example of a library. You may see a list of other libraries used on Rosetta Code at Category:Solutions by Library. Wren-regex is a module which wraps most of Go's 'regexp' package for use by Wren programmers. It consists of two classes: Regex and File. The latter contains some basic text file handling methods which may be useful for this type of application. It is the thirty-sixth Wren source code (in the talk page) to a text file called regex.wren and place this in the same directory as the importing script so the Wren-regex executable can find it. Currently, Wren-cli does not support plug-ins though this or similar functionality is likely to be added in a future version (it's already present in DOME). Consequently, scripts using the Wren-regex module must be run under the control of a special executable whose source code (wren-regex.go) is also included in the talk page. This executable uses WrenGo to translate Wren method calls to calls to the corresponding Go 'regexp' functions and can be built with a command line such as the following using Go 1.18 or later: $ go build wren-regex.go If you're using an earlier version of Go than 1.18, then if you uncomment the 14th line in the file it may still work. However, you must have the latest version of WrenGo. If you then want to run a script called myscript.wren you would type at the command-line: $ ./wren-regex myscript.wren myscript.wren should include a line such as the following to import the classes you want to use in that particular script: import "./regex" for Regex, File The same executable can be used to run any other Wren-regex scripts unless they require additional functionality not available in Wren itself in which case the Go code will need to be suitably modified and rebuilt. Go and its standard packages are subject to this license. Pages in category "Wren-regex" The following 2 pages are in this category, out of 2 total.
https://rosettacode.org/wiki/Category:Wren-regex
CC-MAIN-2022-40
refinedweb
355
72.46
CLOCK_GETRES(2) Linux Programmer's Manual CLOCK_GETRES(2) clock_getres, clock_gettime, clock_settime - clock and time functions corre‐ sponding time values and the effect on timers is unspecified. Sufficiently recent versions of glibc and the Linux kernel support the following clocks: CLOCK_REALTIME A settable system-wide clock that measures real (i.e., wall- clock) time. Setting this clock requires appropriate privi‐ leges. This clock is affected by discontinuous jumps in the system time (e.g., if the system administrator manually changes the clock), and by the incremental adjustments per‐ formed by adjtime(3) and NTP. CLOCK_REALTIME sec‐ onds that the system has been running since it was booted. The CLOCK_MONOTONIC clock is not affected by discontinuous jumps in the system time (e.g., if the system administrator manually changes the clock), but is affected by the incremen‐ tal. CLOCK_MONOTONIC_COARSE (since Linux 2.6.32; Linux-specific) A faster but less precise version of CLOCK_MONOTONIC. Use when you need very fast, but not fine-grained timestamps. Requires per-architecture support, and probably also architec‐ ture support for this flag in the vdso(7). CLOCK_MONOTONIC_RAW (since Linux 2.6.28; Linux-specific) Similar to CLOCK_MONOTONIC, but provides access to a raw hard‐ ware it also includes any time that the system is suspended. This allows applications to get a suspend-aware monotonic clock without having to deal with the complications of CLOCK_REALTIME, which may have discontinu‐ ities if the time is changed using settimeofday(2) or similar. CLOCK charac‐ ter devices. Such devices are called "dynamic" clocks, and are sup‐ ported timeval tv; clockid_t clkid; int fd; fd = open("/dev/ptp0", O_RDWR); clkid = FD_TO_CLOCKID(fd); clock_gettime(clkid, &tv); clock_gettime(), clock_settime(), and clock_getres() return 0 for success, or -1 for failure (in which case errno is set appropriately).. ENOTSUP The operation is not supported by the dynamic POSIX clock device specified.. EPERM clock_settime() does not have permission to set the clock indicated. EACCES clock_settime() does not have write permission for the dynamic POSIX clock device indicated. These system calls first appeared in Linux 2.6. POSIX.1-2001, POSIX.1-2008, SUSv2.).) POSIX.1 specifies the following: Setting the value of the CLOCK_REALTIME clock via clock_settime()"). C library/kernel differences On some architectures, an implementation of clock_gettime() is provided in the vdso(7). Historical note for SMP systems Before).io.h> #include <stdlib.h> #include <stdbool.h> #include <unistd.h> #define SECS_IN_DAY (24 * 60 * 60) static void displayClock(clockid_t clock, char *name, bool showRes) { struct timespec ts; if (clock_gettime(clock, &ts) == -1) { perror("clock_gettime"); exit(EXIT_FAILURE); } printf("%-15s: %10ld.%03ld (", name, (long) ts.tv_sec, ts.tv_nsec / 1000000); long days = ts.tv_sec / SECS_IN_DAY; if (days > 0) printf("%ld days + ", days); printf("%2ldh %2ldm %2lds", (ts.tv_sec % SECS_IN_DAY) / 3600, (ts.tv_sec % 3600) / 60, ts.tv_sec % 60); printf(")\n"); if (clock_getres(clock, &ts) == -1) { perror("clock_getres"); exit(EXIT_FAILURE); } if (showRes) printf(" resolution: %10ld.%09ld\n", (long)) This page is part of release 5.07 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. 2020-04-11 CLOCK_GETRES(2) Pages that refer to this page: adjtimex(2), clock_adjtime(2), clock_nanosleep(2), nanosleep(2), stime(2), syscalls(2), timerfd_create(2), timerfd_gettime(2), timerfd_settime(2), ntp_adjtime(3), pthread_getcpuclockid(3), time(7), time_namespaces(7)
https://www.man7.org/linux/man-pages/man2/clock_settime.2.html
CC-MAIN-2020-29
refinedweb
549
50.63
Django app supporting Net Promoter Score (NPS) surveys. Project description Django NPS Django app supporting Net Promoter Score (NPS) surveys Background - Net Promoter Score The NPS is a measure of customer loyalty that is captured by asking your customers a singe question: How likely is it that you would recommend our [company|product|service] to a friend or colleague?" The answer to this question is a number from 0-10 (inclusive). These scores are then broken out into three distinct groups: ‘detractors’ (0-6), ‘neutral’ (7-8) and ‘promoters’ (9-10). The NPS is then the difference between the number of promoters and detractors (as a percentage of the whole population). For example, if you ask 100 people, and you get the following results: detractors: 20% neutrals: 10% promoters: 70% Then your NPS is 70 - 20 = 50. (NPS is expressed as a number, not a %) NPS was orginally developed at the strategy consultants Bain & Company by Fred Reichheld in 2003. They retain the registered trademark for NPS, and you can read all about the history of it on their site “Net Promoter System”. Usage This app is used to store the individual scores, and calculate the NPS based on these. It does not contain any templates for displaying the question itself, neither does it put any restriction around how often you ask the question, or to whom. It is up to the app developer to determine how this should work - each score is timestamped and linked to a Django User object, so you can easily work out the time elapsed since the last time they were asked. For example, if you want to ensure that you only survey users every X days, you can add a context property to the template using the display_to_user method: >>> # only show the survey every 90 days >>> UserScore.objects.days_since_user_score(request.user) > 90 True If you then show the survey - the output of which is a single value (the score) together with an optional reason (“what is the main reason for your score”), is then posted to the post_score endpoint, which registers the user score. The NPS value itself can be calculated on any queryset of UserScore objects - which allows you to track the score based on any attribute of the score itself or the underlying user. For instance, if you have custom user profiles, you may wish to segement your NPS by characteristics of those profiles. >>> # December's NPS >>> UserScore.objects.filter(timestamp__month=12).net_promoter_score() 50 The post_score endpoint returns a JsonResponse which contains a 'success': True|False value together with the UserScore details: { "success": True, "score": {"id": 1, "user": 1, "score": 0, "group": "detractor"} } If the score was rejected, the errors are returned in place of the score (errors are a list of lists, as returned from the Django Form.errors property: { "success": False, "errors": [["score", "Score must be between 0-10"]] } The app contains a piece of middleware, NPSMiddleware, which will add an attribute to the HttpRequest object called show_nps. If you add the middleware to your settings: # settings.py MIDDLEWARE_CLASSES = ( # standard django middleware 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ... 'net_promoter_score.NPSMiddleware', ) You can then use this value in your templates: <!-- show_nps template = {{request.show_nps}} --> {% if request.show_nps %} <div>HTML goes here</div> {% endif %} Settings NPS_DISPLAY_INTERVAL The number of days between surveys, integer, defaults to 30. This value is used by the default show_nps function to determine whether someone should be shown the survey. NPS_DISPLAY_FUNCTION A function that takes an HttpRequest object as its only argument, and which returns True if you want to show the survey. This function is used by the net_promoter_score.show_nps function. It defaults to return True if the request user has either never seen the survey, or hasn’t seen it for more days than the NPS_DISPLAY_INTERVAL. This function should be overridden if you want fine-grained control over the process - it’s the main hook into the app. Tests There is a full suite of tests for the app, which are best run through tox. If you wish to run the tests outside of tox, you should install the requirements first: $ pip install -r requirements.txt $ python manage.py test Licence MIT Contributing Usual rules apply: - Fork to your own account - Create a branch, fix the issue / add the feature - Submit PR Please take care to follow the coding style - and PEP8. Acknowledgements Credit is due to epantry for the original project from which this was forked. Thanks also to the kind people at Eldarion (website) for releasing the PyPI package name. Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/django-nps/0.3.1/
CC-MAIN-2018-34
refinedweb
791
59.43
Based on IRC log [Noah] Just sent editorial notes on XOP to distAPP. See [Noah] I'll try pasting the whole list here: [Noah] * Section 2.1 on XOP Include: allows zero or more namespace-qualified [Noah] element and attribute children, but is silent on unqualified children. [Noah] Should we be explicit that unqual elements and attrs. are not allowed? [Noah] * Section 3.1: bullet 4, subitem 3: Spelling error: metadate->metadata [Noah] * Section 4.1: "The root MIME part is the root part of the XOP package, [Noah] >and< MUST be a serialization of the XOP Infoset using any W3C [Noah] recommendation-level version of XML (e.g., [XML 1.0], [XML 1.1]), >and< [Noah] MUST be identified with a media type of "application/xop+xml" (as defined [Noah] below)." Suggest rem [Noah] ...Suggest removing the first >and< indicated in brackets. The [Noah] word "and" appears twice. [Noah] * Various example boxes bleed off the page when printed in IE [mnot] mnot has joined #xmlprotocol [Noah] That's it. Sorry for last minute review. [Noah] Mnot: see my comments on XOP just posted to Suggest removing the first >and< indicated in brackets. The [Noah] word "and" appears twice. [Noah] * Various example boxes bleed off the page when printed in IE [Noah] Argh!!! [Gudge] Noah: regarding Section 2.1, my assumption was that what was stated was allowed, everything else was disallowed [Noah] Mnot: see my comments on xop just posted to 1. Roll Present 7/5 BEA Systems, Mark Nottingham (scribe) IBM, David Fallside IBM, Noah Mendelsohn Microsoft Corporation, Martin Gudgin Nokia, Michael Mahan Sun Microsystems, Tony Graham Sun Microsystems, Marc Hadley Excused BEA Systems, David Orchard IBM, John Ibbotson Microsoft Corporation, Jeff Schlimmer IONA Technologies, Suresh Kodichath SAP AG, Gerd Hoelzing Regrets Canon, Jean-Jacques Moreau Canon, Herve Ruellan Oracle, Anish Karmarkar SeeBeyond, Pete Wenzel W3C, Yves Lafon SAP AG, Volker Wiechers Absent Oracle, Jeff Mischkinsky 2. Agenda Review 3. Minutes [Scribe] minutes from 23rd and 30th of June, 7th of July are approved without objection. 4. Action item Review [Gudge] I've fixed the typo in Section 3.1 [Scribe] September F2F resolved to be in Manhattan on Sept. 21-22 [Gudge] MarkN action complete [Gudge] MarkN action for 470 complete [Gudge] Editorial action done [Gudge] Chair action for 470 done [Gudge] Gudge action for 485 done 5. Status Reports [Gudge] Noah: I've also removed that spurious 'and' from Section 4.1 [Scribe] - Media Type Registration: nothing to report [Gudge] Noah: Thanks for the review! [Scribe] - Media Type document and XMLP/WSD TF: skipped [Scribe] - F2F: (see above) [Scribe] - Primer review: Nilo should be at the Sept. F2F [Scribe] - WSDL Review: No formal notice of LC yet. Would it be appropriate for XMLP to review? [Scribe] Marc: Yes; entirely appropriate [Scribe] Marc: can do one part [Scribe] Chair: can we presume that part 3 is the most relevant? [Scribe] (many): yes. [Scribe] Chair: Marc to review part 3. [Scribe] MarkN: will review part 1. [Scribe] Chair: will send an e-mail to group WRT part 2 [Scribe] Mike: I can do part 2. 6. Attachments / CR Documents [Scribe] Chair: have recieved confirmation that the representation header document is complete; WG members should review. The boilerplate, etc. will be updated over the next week, but the content will stay the change. [Scribe] Chair: Because there don't seem to be many comments for the Representation document, we will make a yes/no decision next week for CR, barring any large changes. [Scribe] - Review comments of XOP, MTOM and Representation specs [Scribe] Chair: does anyone remember whether we chose the camelCase vs. the hyphenated version of the media type attribute? [Scribe] Gudge: the media type document uses CamelCase... [Scribe] Chair: we should use that? [Scribe] No objection to using CamelCase consistently. [Scribe] Noah: I did a read-through of XOP; noticed a few small things. [Scribe] Noah: Section 2.1 of XOP says that xop:Include allows zero or more namespace-qualified children and attributes; what is our intention WRT unqualified children? I would think we wanted to disallow them. [Scribe] Gudge: My reasoning was that anything we don't explicitly allow is disallowed. However, I can see saying something here. [Scribe] Mark: would that disallow whitespace content? [Scribe] Gudge: yes. [Scribe] Noah: we could say that explicitly near the top of the document. [Scribe] Gudge: I prefer the blanket statement. [Gudge] The following subsections provide formal definitions for allowable content in the [Gudge] <emph>element information item</emph> and <emph>attribute information [Gudge] items</emph> used to construct a XOP serialization; content not explicitly listed is disallowed. [Gudge] The following subsections provide formal definitions for content of infoset properties of the [Gudge] <emph>element information item</emph> and <emph>attribute information [Gudge] items</emph> used to construct a XOP serialization; content not explicitly specified is disallowed. [Gudge] The following subsections provide formal definitions for allowable content in the [Gudge] <emph>element information item</emph> and <emph>attribute information [Gudge] items</emph> used to construct a XOP serialization; content not explicitly specified is disallowed. [Scribe] No objection to the last change proposed by Gudge. [Scribe] Noah: Section 3.1 bullet 4, sub-item three: editorial [Noah] "The root MIME part is the root part of the XOP package, >and< MUST be a serialization of the XOP Infoset using any W3C recommendation-level version of XML (e.g., [XML 1.0], [XML 1.1]), >and< MUST be identified with a media type of "application/xop+xml" (as defined below)." Suggest removing the first >and< indicated in brackets. The word "and" appears twice. [Scribe] Noah's proposal to remove second "and" agreed to. [Scribe] Noah: some examples ran off side of page when printing with IE. [Scribe] Gudge: I'm not sure there's much I can do about it, esp. with include instances. [Scribe] Noah: the namespace table also runs off. [Scribe] Chair: the editors are instructed to fix it. [Scribe] No other comments by WG. [Scribe] Chair: Schedule - over the next week, the editors / chair /team will get the right boilerplate into the specs. If you have any last-minute issues, they need to be in before the next meeting, preferably a few days beforehand. We will say yes or no to CR at the meeting; we will submit within a day of a yes. [Scribe] Chair: Issues 485 and 490 are still listed as being open; Gudge said that he had sent the e-mail in. I believe that Yves hasn't updated the LC table yet, so that's it for the issues. [Scribe] Chair: WRT CR feature lists: there has been some e-mail traffic. I haven't seen any pushback to Gudge's proposals. [Scribe] Gudge: Yes. I received mail from Canon that said they'll be available in September. [Scribe] Chair: I've recieved confirmation from Microsoft and White Mesa that they'll have an endpoint. We'll set up some calls when we go to CR with White Mesa and Microsoft. [Scribe] Chair: Aug 18th, 25th, Sept 1st meetings are cancelled [Scribe] Meeting adjourned [Zakim] Attendees were Gudge, Marc, +1.781.993.aaaa, TonyGraham, Mark_Nottingham, me. [RRSAgent] I see 6 open action items: [RRSAgent] ACTION: MarcH to review WSDL Part 3. Due 2004-09-06. [1] [RRSAgent] ACTION: MarkN to review WSDL Part 1. Due 2004-09-06. [2] [RRSAgent] ACTION: MikeM to review WSDL Part 2. Due 2004-09-06. [3] [RRSAgent] ACTION: Chair to announce FTF date to WG et.al. [4] [RRSAgent] ACTION: Chair to outline in email the end-game for doc review and CR [5] [RRSAgent] ACTION: Chair to send WG email re. XMLP shutdown in Aug/Sept [6]
http://www.w3.org/2000/xp/Group/4/08/04-minutes.html
CC-MAIN-2015-35
refinedweb
1,282
66.44
IAutoFieldGenerator This is the heart of controlling which fields are shown in the List, Details, Edit views etc. Listing 1 is a skeleton of the Column/Row Generator, as you can see it is a class that is passed a table and has a loop which returns a ICollection of DynamicFields. The foreach loop is where the columns are processed similarly to the if (!column.Scaffold) which tests to see if the column to scaffolded. using System.Collections.Generic; using System.Web.DynamicData; public class FilteredFieldsManager : IAutoFieldGenerator { protected MetaTable _table; public FilteredFieldsManager(MetaTable table) { _table = table; } public ICollection GenerateFields(Control control) { List<DynamicField> oFields = new List<DynamicField>(); // where do I put this test I think in the page? foreach (MetaColumn column in _table.Columns) { // carry on the loop at the next column // if scaffold column is set to false if (!column.Scaffold) continue; // create new DynamicField DynamicField newField = new DynamicField(); // assign column name and add it to the collection newField.DataField = column.Name; oFields.Add(newField); } return oFields; } } The class is used like: // code to add column level security table = GridDataSource.GetTable(); GridView1.ColumnsGenerator = new FilteredFieldsManager(table); Listing 2 The code in Listing 2 is added to the Page_Init event, this is all that is needed in the pages code behind to add column level security. Customising the FieldGenerator class The first change is to add a new member variable _roles and change the Constructor to take an array of Strings. protected MetaTable _table; protected String[] _usersRoles; public FilteredFieldsManager(MetaTable table, params String[] roles) { _table = table; _usersRoles = roles; } Then in the GenerateFields method the permission for the current column will be assigned a local variable and then add a test to the if (!column.Scaffold) so that if the column is DenyRead then the column will also be skipped see Listing 4. //; Listing 4 The next step is to add a DynamicReadonlyField class so that id a field is marked DenyEdit then a read only field can be returned instead of the regular DynamicField see Listing 5.; // this the default for DynamicControl and has to be // manually changed you do not need this line of code // its there just to remind us what we are doing. control.Mode = DataBoundControlMode.ReadOnly; cell.Controls.Add(control); } else { base.InitializeCell(cell, cellType, rowState, rowIndex); } } } Listing 5 - Thanks to David Ebbo for this class and the explanation here on the DynamicData forum. Now if we add a test for the column has a DenyEdit security attribute assigned then the field can now be set to an DynanicReadOnlyField. In Listing 6 the fieldPermissions variable can be tested to see if it contains a DenyEdit permission. DynamicField f; if (fieldPermissions.Contains(FieldPermissionsAttribute.Permissions.DenyEdit)) { f = new DynamicReadonlyField(); } else { f = new DynamicField(); } f.DataField = column.Name; oFields.Add(f); Listing 6 Listing 7 shows the code to test for foreign Key tables parent and child table permissions and if DenyRead do not show the field for the column. /; } Listing 7 Put it all together in Listing 8. public class FilteredFieldsManager : IAutoFieldGenerator { protected MetaTable _table; protected String[] _usersRoles; public FilteredFieldsManager(MetaTable table, params String[] roles) { _table = table; _usersRoles = roles; } public ICollection GenerateFields(Control control) { List<DynamicField> oFields = new List<DynamicField>(); // Get table permissions var tablePermissions = _table.GetTablePermissions(this._usersRoles); // if table is DenyRead then do not output any fields if (!tablePermissions.Contains(TablePermissionsAttribute.Permissions.DenyRead)) { foreach (MetaColumn column in _table.Columns) { //; } DynamicField f; if (fieldPermissions .Contains(FieldPermissionsAttribute.Permissions.DenyEdit)) { f = new DynamicReadonlyField(); } else { f = new DynamicField(); } f.DataField = column.Name; oFields.Add(f); } } return oFields; } } Listing 8 having done all this remember all you have to add to the page is: // code to add column level security table = GridDataSource.GetTable(); GridView1.ColumnsGenerator = new FilteredFieldsManager(table, Roles.GetRolesForUser()); SQL Server 2005 SQL Server 2008 the sample already has Login and Roles setup (Account details below). Website users: - admin - fred - sue - pam all passwords are: password 28 comments: Hi Steve, I finally got around to looking into table and column permissions for my application. Your sample code is great. Thanks for that. One question though. I noticed when I was running up the sample app that although I logged in as Fred (which shouldn't have read permissions on the order_detail table) that if I manually manipulated the url then I could get access to the that table. It seems to me that marking metadata on tables and columns is a tool to aid in the display of database tables/columns and not to 100% lock out access. Is this correct? Cormac Hi Cormac, if you look at part 4 and the section entitled "Some Error Handling for Pages Reached with Tables that are DenyRead" you will see the code that need to be added to each page to stop what you said is happening. So it's a bug, I will review the download and update where nessacery. Steve P.S. have a look at this new series here DynamicData: Database Based Permissions - Part 1 on my blog :D Steve, You mentioned that you are using a Deny Pattern for your permissions, where you limit functionality as additional attributes are tagged. I setup my application with users and roles as follows: Roles: Admin, Consumer, Buyer User A is an Admin, Consumer, and Buyer User B is a Consumer and a Buyer User C is a Consumer ... you can see where I'm going. When I ran the application User A was being denied access to functionality, this is because one of the other roles this person had was denied functionality. To get everything working with role based permissions setup like I just described I had to refactor the HasAnyRole method in the FieldPermissionsAttribute class to HasAllRoles: public Boolean HasAllRoles(String[] roles) { foreach (var role in roles) { if (!HasRole(role)) return false; } return true; } Thoughts on this? Yep thats the way I made it, of course you could make the logic more complicated, but I was just showing how and that level of complexity will suit more peoples uses :D Steve Steve, Thanks for your excellent work. Your explanations and code help me to understand DD a lot better :-) Thanks again, Sylvester Steve, This is the init of list.aspx.cs: protected void Page_Init(object sender, EventArgs e) { table = DynamicDataRouteHandler.GetRequestMetaTable(Context); GridView1.SetMetaTable(table); GridDataSource.EntityTypeFilter = table.EntityType.Name; table = GridDataSource.GetTable(); GridView1.ColumnsGenerator = new FilteredFieldsManager(table); } I added the class to the project as well, But my app does not go into public ICollection GenerateFields(Control control). What is going wrong? Hi Suicidesquad, from the code you have posted it looks like you are using either Preview 4 or Beta 1 VS2010, I have not tested in this environment yet so I'm not sure what the reason is but I will look into it ASAP. Steve :D Aparently there IAutoFieldGenerator works the same as in V1 according to my contacts. So I'll have a quick look later and see what happens. I'll use Preview4 and Beta 1 to test this. Steve :D Hi Steve Is there a way to add a further column to aps:DetailsView using IAutoFieldGenerator interface? What I want to achieve is, that a new column with units or status information is generated on detailsview. I think you could but there is probably a better way of doing this, can you be more specific. Steve ;D Okay I have an Attribute like this [AttributeUsage(AttributeTargets.Property)] public class UnitAttribute : Attribute { public String Unit { get; private set; } public UnitAttribute() { Unit = "-"; } public UnitAttribute(String UnitExpression) { Unit = UnitExpression; } public static UnitAttribute Default = new UnitAttribute(); } I can use this attribute to decorate my column with. What i now want to see on my detailsview on dynamic data is a third column containing this unit attribute. I have now idea what happens in the background of "RowsGenerator" if i set DetailsView1.RowsGenerator = new AutoFieldsManager(table, PageTemplate.Details, Roles.GetRolesForUser()); So, how can i achieve it? Thanks for your help Have a look at Listing 8 FilteredFieldManager for details of what goes on in side an IAutoFieldGenerator. Steve :D Hi Steve Sorry for my late reply. Hm, I'm sorry, but i don't get the answer from your last post? *confused So let me ask in another way. Is it possible to return a 2-dimensional list of DynamicField from GenerateFields function (Listing 8) to force DetailsView.RowsGenerator to create a third column on detailsview? Sorry, for my bad english. I hope it's now clearer. Thanks for your help Loopmaster The IAutoFieldGenerator returns a list ot type DynamicFiled your problem is that there is no column so it may be possible to add an extra DynamicField that does not match a Column and map it to a FieldTemplate via UIhint. I will give it a try. At least it could work for a gridview. But I don't think, that I can use this I idea for a detailsview, because there a table column becomes a row. That's not what I wanted a achieve. Anyway. Thanks for your help Loopmaster Hi Steve, How would you do the same without IAutoFieldGenerator (using FormView in Detail, Edig and Insert pages)... Thanks!! Hi there :) I have an article here Dynamic/Templated FromView this generates the Templates for a FormView. If you are using VS2010 then look at this article here A New Way To Do Column Generation in Dynamic Data 4 Hope this helps. Steve :D I'm using vs2010 (also use CustomMetaTable and CustomMetaModel like you use in "A New Way To Do Column Generation in Dynamic Data 4"), but I don 't know how to asign DynamicReadonlyField/DynamicField in Fields of FormView Sorry for my bad english. Thanks again !! Your English is better than my say French :) Have a look at this old post based on Preview 4 here Securing Dynamic Data Preview 4 Refresh I am working on a RTM Sample at the moment :) Steve How to add 2 IAutoFieldGenerator on Page_Init? GridView1.ColumnsGenerator = new HideColumnFieldsManager(table, PageTemplate.List); GridView1.ColumnsGenerator = new FilteredFieldsManager(table, Roles.GetRolesForUser()); You can't as they return a list of Fileds not columns. If your using DD4 and VS2010 then I have a better way that can be chained see A New Way To Do Column Generation in Dynamic Data 4 you couls use a delegate to generate columns and you could also allow then to be chained if you wanted. Steve :D Thanks. Hi Steve, Below is my code for Page_Init in List.aspx - table = DynamicDataRouteHandler.GetRequestMetaTable(Context); GridView1.SetMetaTable(table, table.GetColumnValuesFromRoute(Context)); GridDataSource.EntityTypeFilter = table.EntityType.Name; table = GridDataSource.GetTable(); GridView1.ColumnsGenerator = new FilteredFieldsManager(table, Session["dept"].ToString()); But it is not calling GenerateFields() from FilteredFieldsManager. Please suggest asap. You may need to move the line to the Page_Load GridView1.ColumnsGenerator = new FilteredFieldsManager(table, Session["dept"].ToString()); Steve Thnks Steve. Its working. But in Edit page fields are coming. For that I am using same code with Formview1, but RowGenerator is not coming. Please reply Hi vivek, e-mail me direct not sure what your issue is, my e-mail is in the top right of my blog. Steve Steve, My issue is how to implement same like what we did in list.apsx for Edit.aspx page. so that those columns should not come for particular role. Sorry I can't mail you from here. I think you are on .Net 4 so you will need to look at my new Column generation here A New Way To Do Column Generation in Dynamic Data 4 this gets rid of the requirement to use field generators and simplifies everything. Also you cant use column generators with the FormView. Steve
http://csharpbits.notaclue.net/2008/05/dynamicdata-generate-columnsrows-using.html?showComment=1346665467921
CC-MAIN-2021-10
refinedweb
1,942
54.42
Join devRant Search - "how i started out" - The first time I realized I wasn't as good as I thought I was when I met the smartest dev I've ever known (to this day). I was hired to manage his team but was just immediately floored by the sheer knowledge and skills this guy displayed. I started to wonder why they hired outside of the team instead of promoting him when I found that he just didn't mesh well with others. He was very blunt about everything he says. Especially when it comes to code reviews. Man, he did /not/ mince words. And, of course, everyone took this as him just being an asshole. But being an expert asshole myself, I could tell he wasn't really trying to be one and he was just quirky. He was really good and I really liked hanging out with him. I learned A LOT of things. Can you imagine coming into a lead position, with years of experience in the role backing your confidence and then be told that your code is bad and then, systematically, very precisely, and very clearly be told why? That shit is humbling. But it was the good kind of humbling, you know? I really liked that I had someone who could actually teach me new things. So we hung out a lot and later on I got to meet his daughter and wife who told me that he had slight autism which is why he talked the way he did. He simply doesn't know how to talk any other way. I explained it to the rest of the team (after getting permission) and once they understood that they started to take his criticism more seriously. He also started to learn to be less harsh with his words. We developed some really nice friendships and our team was becoming a little family. Year and a half later I had to leave the company for personal reasons. But before I did I convinced our boss to get him to replace me. The team was behind him now and he easily handled it like a pro. That was 5 years ago. I moved out of the city, moved back, and got a job at another company. Four months ago, he called me up and said he had three reasons for us to meet up. 1. He was making me god father of his new baby boy 2. That they created a new position for him at the company; VP of Engineering and 3. He wanted to hang out So we did and turns out he had a 4th reason; He had a nice job offer for me. I'm telling this story now because I wanted to remind everyone of the lesson that every mainstream anime tells us: Never underestimate the power of friendship.22 - - At work today the guys showed me how I can listen in on calls so I can prepare myself for phone support. We tested it through a call between two of the guys. They started talking like "test test123 is this working" I said yes and continued working behind my screen. They just didn't know I was still listening. Both guys started saying stuff like "welcome to the sex hotline" "hello and welcome to the *insert something sexual* hotline!" One of the guys after a few minutes: why is your head so red?! Wait.... Have you been listening along?? 😅 Yes 😂 *everyone bursts out in laughter*44 - - - - Manager: The thing you working on. We need this now! Like end of the week. Me: Desirability is not do-ability. Manager: く( ・◇・)ヾ? Me: I am still in the middle of figuring out how to do things in the first place, so there are some technologies to research and some problems I yet need to solve. I am in no state to just write down my solution. I don't even have enough information to even estimate how long it is going to take. I am getting there. And yes, I can rush things, but need I remind you that you want solid data as a result that actually means something? As this is *why* this whole project was started. We have some old project doing the exact same thing, but whose output we don't trust. I wonder how that came to be. Additionally, this whole project was on hold for months until I took over. So I neither understand nor accept this sudden sense of urgency. And by the way, you recently added manpower to this project. And adding manpower almost always decreases the productivity in the beginning due to on-boarding and communication overhead. Last Monday, I didn't write a single line of code due to that. So no, this week will not do, as I am also on vacation starting on Thursday that was requested and was approved by you at the beginning of the year. See you in January.13 - - Started university of applied sciences to become a computer engineer instead of a web developer. Met a lot of kids that are in the "computer studies = games + YouTube". They struggle hard, but don't do anything to learn... Then there's this classmate, the guy is 10 years older than me, is trying really hard, and struggles a lot. I've been helping him out with assigns by asking questions, and he asks me how to solve a problem in general, not the assignments which is super refreshing to see someone that wants to learn. Currently trying to help him "translate" the simple stuff into c++: So, if you want the char at a certain position in a string, how would you tell me to do it? "well, take the list, look at position x and bam its done" Try writing it like that! And instead of "[i]" he writes "stringvar[i]" He really appreciates the help and I hope he'll get the mindset soon :) Would hate to lose a motivated guy when there's so many idiots copy pasting everything from tutorials...5 - -13 - I waited until yesterday evening to watch the livestream capture from our creators. Was expecting something like them being bought by MS or Google or whatever due to how good this awesome network is doing/growing. As so, i was mentally preparing for a goodbye (the second this data gets into the hands of a data hogging company I'm fucking out (as in, the one who owns the databases)) and then I started watching the livestream. "aaand here it issssss!!" "DevDucks!" 😮😅😆😂😊 Well that was one hell of a relief!14 - How did I start: It was 1994. I had been kicked out of school on academic behavior. I was working at as a telemarketer to pay the bills. I got drunk on St. Patrick's day and over slept my shift. My boss was going to fire me but said he wanted to give me a second chance. He asked if I knew anything about computers. I said no. He said if I was willing to learn, our IT guy was burning out and needed help. I said ok. Next thing I know I'm learning how to write SQL and importing data to print call cards. I read the manual for Foxpro and started building small desktop apps as labor saving devices. 6months later in knew more than our IT guy. Later a friend showed me "the Internet". I went back to our IT guy in amazement. He said it was just a fad. He called it the CB Radio of the 90s. Our network we ran was called Lantastic. I immediately quit went back to school and changed my major. I have been a full stack Java Web developer will the heavy emphasis on UI since 1999.3 - guys i really need your help. My girlfriend started getting phone calls at odd hours, so I got suspicious and started tracking her phone. Then I found out that she has been going to this guys house at wears hours, then once when I was tracking her my computer froze, so what could it be? How do I fix my computer14 - My first job after university (I'm ignoring internships), was on a rapid development team for a large company. We were effectively the rockstars and managed to get a special room to ourselves with a projector, open desks, storage, and whiteboards everywhere. The room was also just past the tour area for people visiting the company to check out the company's products. One day, I was headed to the room a little earlier than usual and was thinking through how to sort out various issues with the code that day. I opened the door to find a raging waterfall coming from the ceiling, just in front of the projector. This had started mere seconds before I opened the door. My coworkers and I all just stood there staring at it for about 15 seconds before we all snapped back and scrambled to save as much tech as we could, moving everything to a spare room to prevent any damage. The waterfall only got worse during this time but we managed to get everything of importance out unharmed. Turns out the water pipe feeding the sprinkler system had burst inside of the ceiling. The smell was egregious because the water in a fire suppression system just sits in the pipe and stagnates forever. We were all traumatised and moved to a meeting room in the centre of the building. - -*8 - - today I got really triggered when i hear this guy say that coding is cancer. I stand up and instantly the first thing going through my mind is that it's the battle of the nerds. He says he tried ALL of the programing languages out there and they were shit. I asked if he tried C# and he still says coding is cancer even though he has never even heard of any C# syntax. I asked if he used Batch as a started language and he still says it. So I just decided to roast him by saying "did you put .bat at the end of the file when you were saving? Oh wait never mind, I forgot your lazy ass doesn't have the intelligence to understand how to save" Surprisingly everyone was silent and most likely didn't understand what I had said. So I just left wondering if he even bothered to get a guide on syntax for any of the languages he would have liked.5 -: - -!1 - - HOW IS IT AUGUST 1 RIGHT NOW 2019 ENDS SOON BUT IT STARTED LIKE YESTERDAY WHAT IS HAPPENI WHY IS TIME GETTING FASTER THE OLDER YOU GET? JUST FCK OFF THIS IS NOT NORMAL I GOTTA HURRY TF UP AND DO SOME SHIT WITH MY LIFE BEFORE TIME RUNS OUT☠️☠️☠️💨💨🌬10 - started with Notepad++ (and continued like that for a while) Then I tried jetbrains webstorm, I tried atom. I tried VS. They all have their cool stuff but I was never fully satisfied. Now I tried brackets. I just opened a project I'm working on rn and started coding a little. Half a hour passed and I still didn't notice that I had a light theme. Yes. This is it. I'll stay with this editor. It just feels right. I just need to figure out how to use tabs not spaces... (picture says just my opinion)33 - - - - I guess my best AHHA moment was back when I learned that good code is simple code. When I started out I wanted to prove myself by showing of how good of a programmer I was(and which I retrospectively wasn't) , which basically meant to use every high level concept I was aware of whenever possible. Multi threading where linear execution would have been totally okay, polymorphism with x meta classes where a switch would have been enough, all that shit. It wasn't until I had to guide the first person through that mess of useless ego stroking that I found out how much time and money I wasted by not going with the easiest approach that solves the problem. Took me some time to fully lay off that attitude but it surely was one of the most influential moments of my career.7 - when I was first started out, I was trying to test out a file delete and renaming program I made. it deleted itself. never even knew how it happened. it was effective in deleting though.5 - I was recuited to do devops work for a client. The project started in late '14. Until mid '15 I was forced to just sit there and do nothing. And I mean nothing. The ops team needed my help but the project lead didn't allow that (endless discussions). Somewhere around the end of '15 I could start to work and quickly learned that I had to report to two leads that couldn't disagree more on what to do and how to do it. I also learned that the companies mentality is "Clean me but don't get me wet". So the ops team demands a lot but is really uncooperative with everything. So I am currently sitting between three grindstones and everything I do is worthless. Because nobody agrees with anybody and I cannot fulfill my job for which I have been hired: Make ops more efficient because they are drowning in manual work. My job is further complicated by the following facts: This company uses no standard whatsoever but their own. Thru this they have created a Rube-Goldberg-Machine. But they think their system is the greatest in the world and the only one that makes sense. Which makes automation pointless because it is not maintainable. They call it diversity and they say that it is the clear reason why automation is not for them even though they schedule meeting after meeting in which they discuss about how to automate things. But in general they do just block everything useful and sabotage my work. And behind my back they make me the reason for the fail. Every real decision is blocked anyway. Also the ops guys think they are the leetest in the world. And everything they invent is above and beyond. If you ask them why they have over 400 VLANs for example (in a company of unter a thousand employees) they stutter and stumble because they cannot explain their complicated shit. They also change their decisions like underwear. Another really "kewl" thing they just did: They hired a devops engineer and everybody loves him. During the interview he said that he has no prior experience with devops whatsoever and it will take him around six month to get started on the basics of devops. I could go on for hours here about the insanity of this company that in my opinion will cease to exist within the next 5 years, if you ask me. Long story short I am getting out of there by the end of march and will be on sabbatical shortly after because I am burned out. And I mean burned out. Not like "Oh I am burned out". I mean really burned out, with health problems and everything. Another external guy got out here last month because of the same health conditions.14 -5 -.12 -!10 - - Had an interview with a potential customer last week, and he started questioning my technical capability in the middle of the discussion on the basis that I’m taking notes with pen and paper... Yes, I can type. At 90+ WPM, I can darn near produce a transcript of everything we say. But I won’t remember any of it afterward, because it passes straight from the ears to the hands without any processing. “You see, that’s what we have something called ’search’ for...” ...Yeah. Except that doesn’t help with picking out the most important points from a wall of text, organizing it in a way that allows visualizing relationships between concepts, and other non-linear things that are hard to do on the fly in a word processor. “Well, how about we get you a tablet with a pen and you can just write on that, then?” How about no. Ended up turning him down because of other concerns that were raised that were, suffice to say, about as ornerous as you might expect from that exchange?4 - When I was 17 years old. I had difficulties in understanding math problem “Calculus” (I can’t remember which one was it). This one day when we were in a Computer Lab, our teacher was showing us how really software’s are made. During my time, it was vb6. I paid close attention. When I went home, I started to think things that I can make using that software so one day I went to my teacher and asked if I can have a copy of the vb6. He gave vb6 and told me that inside are few eBooks that will help in learning. Fuck School, from that day I started to concentrate on programming only. Made a small calculator which will help me to understand a Calculus problem and double check my answer. From that day, I love programming. I’ m 26 now and a full stack software developer. All I want to do it build cool shit, something that will blow the eyeball of my friends and that eyeball should pop out from their asshole. Joke: The person who scored highest in the computer class was afraid to switch on the PC.1 - - - Oh god, I was like 13 and just found out about RPG Maker 2000. I got a pirated copy from a friend because ive got no internet at that time. I remember, my first project was with a friend of mine and dayum, we were so dumb and unknowing. Once we wanted to implement a counter of how many fights a player had. The problem was, we only knew about switches (boolean variables) and so we started to implement boolean variables like these: hadOneFight hadTwoFights hadThreeFight and so on, as something like a counter. We took this to 50 before I asked my friend if this is the right way of doing this. He answered: "thats probably the reason, why games are so big nowadays" (he just installed morrowind at home...) Then at one day, I reached the point I didnt knew what I should do next in this project, so I looked around at all the other functions we never even tried and I found something called "variables". Those where the "real" variables like string and int and wow, suddenly the possibilities where endless. I told him about variables at telephone and what we could do now, but that just got him somehow frustrated so he told me, that he wants to leave this programming thing4 -. -9 -. - I'd like to share with you this story... It all started like 3 months ago. It was a cold morning, and I was walking to school. I saw a girl looking at me. She was really cute, she had a beautiful smile. I acted like nothing happened and went on. 2 minutes later I arrived at school and there I see her again. She was at the school gates. The thing didn't surprised me: she looked like my age, maybe a year or 2 older. The weird thing is that she started talking to me (yeah, I know, big thing). I didn't even knew her. She asked me if we could see each other after school. I agreed. (A hot girl that asks me to see each other after school? Hell yeah!😂) So that afternoon we started to talk, and I discovered that she is an year older than me and that she just moved in from Treviso, the city were I was born. And it turned out we had the same passion: computers! She even programmed in C#, my favourite coding language!! So we started to meet each other more and more often. We started to code together. And today we officially got together. I don't really know how that happened, we were like watching this stack overflow post, and she asked me if I wanted to be her boyfriend. Yeah, I know it is weird, but a cute girl that likes computers and actually wants to date me is a rare thing! 😂 That's it. I just wanted to tell y'all this story, even if I know you couldn't care less 😂. And sorry for my English7 - - When I started programming ~5 years ago. Teacher: OK, C++ classes and structs have 3 access modifiers: private, public and protected. Private fields can't be accessed out of the current class. Me thinking: wow, that's cool, but how can it be? I have to research. I went to home and wrote a class with one variable with its set and get functionality. Then I opened Cheat engine) and tried to access and change the variable. When I succeeded, I started hating this world of programming. After some time I understood that it's wonderful cause it's up to you.5 - Actually I feel I am prety lucky about the relationship between my yamily and me being a dev. My dad is a developer as well (in fact, he was the one who taught me most of what I know today; not as in general coding, but good and bad programming practices, tips what to do next ...) and my mom just started learning Python. So they know prety well what it means to be a dev and have quite realistic image of what to expect. To be fair, I am still the one who usualy fixes broken printers and replugs unplugged ethernet cables. but that is because I enjoy doing that. I take it as a challenge for myself to figure out what/how/when went something wrong. Most of the times I try to figure that even without touching the broken things. Anyway, getting off topic. Alltogether I don't think that they have too unrealistic expectations, but if I had to chose one, it'd be my learning capabilities. I can't learn complete java in 2 days ...1 -!14 - - When I did games dev in college, it’s fair to say that most of my class started off really stupid. Like, I met these people. We were all dumb. Except this one guy. His name was Jordan. He was huge. He smelled bad. Everyone made fun of him, (I kept my distance in fear of being decimated because he was known for his temper). But fuck, that guy knew how to model and code. In the time we had spent working out how to build a single model or write a working line of code, he’d been working on this full scale Skyrim-esque environment that just reminded me of Whiterun. I wonder what he’s doing now. - FUCK THIS SHIT. I AM OUT. That's how I started my Monday. So this week gonna be another great week again. I can bet.2 - My first experience (and memory) is waking up at 5am and finding my dad playing Tomb Raider in the dark. Rather than being angry that I was up so early he sat me down and asked me to help him find all the treasure. I must have been about 5 so it was 1997/8. I sat with him for hours and pointed out any traps or levers or treasure I saw. From there I found Age of Empires and carried on gaming. Then it was a good few years until I actually got interested in what was going on inside the computer. It started with a simple "How is this site made?" And the rest, as they say, is history.4 - - Wanted to move to London out of curiosity/adventure. Started doing interviews online and all companies wanted a stage 2/3 in person but that would've been a pretty expensive flight just to go on a short interview, especially with my budget back then. The guys at my current company were pretty cool and instead we did more video calls and coding tests, then they offered me the job without having to do the face to face. Had a week to pack up and move here. Never had been in the UK before that. I arrived in the evening, slept at my temporary accommodation and went to work next morning. That's basically how I got here :)3 - In the first few months that I took coding seriously, I used to see a feature in some android apps that I really liked and wanted to do. One night in my sleep, I don't know how, but dreamed about it's solution and how to achieve it. So I snapped out of sleep at 2 am and started working on it. I finished it at around 5 am, but I was too exited and happy to go back to sleep, so I kept adding things to it and expanding it until 8 am, when I had to go to work. And at work I had to code until 5 pm, although we had one hour for food and resting. That was the longest I coded!1 - - You asked for it--here it is. It was a regular day in November--I was taking my dog out for a walk. We were walking past an elementary school when my dog started barking at a rock. I went to have a closer look at the rock when suddenly it vanished into thin air. "How strange" I quietly thought to myself, called out to my dog and carried on walking. The next day at around the same time, at the very same place--next to the elementary school, my dog started barking at a log which lied in the exact same spot as the rock had occupied the day before. I did the same as I had done a day earlier--walked up to the log to check it out, but it vanished into thin air. We kept on walking. The third day I decided we'd pick another route. This day, nothing interesting happened. The fourth day went the same as the third. The fifth day, went the same as the fourth. On the sixth day, God was almost done with his works, for that reason we celebrated by going to the movies--me and my dog. To be fair, the only interesting thing that happened on that day was the movie, which was shit. On the eight day when I got out of my bed I fell, broke my neck and died. And that's when I ate my code to make it shorter - First off murphy is a bitch. Week started off good, nothing bad happening then friday night came and i get an email about a site being down. Ok check it out real quick, cert is expired. No real big deal just a 20 minute fix, didn't bother me that i didn't get an expiry alert. Now is where murphy decided to be the biggest fucking bucktoothed cocksucker, generate a csr for a wildcard domain using an existing key and sent it off when i get it back the private key doesn't match the cert. Again ok maybe i fucked up, generate a selfsigned cert no fucking problem. Contact support to see if they have an idea. Oh now is when it gets fun, the fucking dumbass preceded to tell me how i didn't know what i was doing and how i just had to generate a csr and private key at the same time after i explained to the bastard that I've already tested it with a selfsigned cert. (How does this fucker have a job) By now apparently i was pissed off enough to scare murphy's pansy ass away cause i told the fucker to refund my money, got a list of 30 subdomains and setup letsencrypt on it. Now the part on this that is fucking hilarious is that it took me damn near 24 hours to be called a fucking idiot from a guy that doesn't know his ass between a hole in the fucking ground and 30 minutes of being pissed off more than i have been since i took anger management classes in the 9th grade to say fuck it and switch - - - Just tried to figure out why in my scala application a function declaration started with a dot. Like this: def functionName: returnValue = { .something() } how the fuck could I call a method here? And a method of what exactly? Until I ran my finger down the code and wiped away the piece of dirt on my screen I took for a dot. - - A fun story on how I lost my end of year project : Last year was my first year of college in computer science. To get to my school, I need to take two different buses with a kilometer distance between them. The day that I had to send my end of year project, which was worth 25% of my final grade, I thought that it would be fun to use my skateboard to get to the second bus instead of walking. So, I got out of the bus, started skateboarding towards the second bus and, about 20 meters later, my wheel got stuck on a small rock which was big enough to make me do a front flip. I landed on my back and broke my left arm. An hour later, at the hospital, I tried to send my project to my computer science teacher but I quickly realised that my spectacular fall destroyed my laptop's HDD and my end of year project. And this is how I learned how important it is to back up my files in the cloud.8 - Interns' first day: "Here is some documentation I found really handy, got me up and running quick" "Here's a video series on the some of the stuff we work with and maintain. Found it super useful!" Several months later: They didn't use any of it, and I answer questions constantly. WHY!? I started less than a year ago, and I'm the most senior on my team in this country. So it's all falling to me and I don't know how to hold their hands so they'll be able to learn and figure out what to do? Do I just start being rude and telling them to google things?6 -?6 - !rant I know this may not be the typical post on Devrant and it may be a little off topic, but I could really use some advice from fellow colleagues here. The thing is, I just finished engineering school and I got my first job as a software engineer. So far so good. I've never been a natural talent in this field, and I suck at writing code. I find things like architecture, system design, innovation, requirementsspecification, management and business development much more interesting. These past weeks as a software engineer has been really challenging for me. I seem to be totally "in over my head", and fuck everything up. I can't understand how the code I'm supposed to write works, and can't solve even the simplest of tasks that are assigned to me if they involve any implementation of code, or fiddling with Github or build servers. Is it normal to feel like this as an engineer with zero experience? Will things get better, or should I just resign or wait to be fired? What would a natural next step for a software engineer who'd like to move more into business and management be? A MBA? Project management courses? I hope to get some advice from you guys. Maybe you've felt like this when you started out as well? Anyway, any constructive feedback would be really much appreciated.11 - - - !dev Another tinder story from last night. Matched with a girl, I thought she was cute and all. She texted me first, and we started talking. We kinda just clicked, had similar interests and everything. Conversation turned to musicals, she said she wanted me to come listen to one with her at some point when we were both free. I mentioned the whole story from Sunday night to her (see previous rant), and told her how the girl said I was a "rebound", but nothing actually happened. Then she changed the conversation by saying something like "rebounds normally involve sex, maybe I can make up for it". After that the conversation got sexual. Dirty talk, nudes, everything. Talking about how hard she wanted me to fuck her and everything. That carried on until about 6 in the morning. We both decided we should go to sleep. I woke up around 11, we talked for a few minutes, then she said she had to get ready for a doctor appointment, and I didn't think anything of it. Went to work at 2, had to go get a car from a dealership like 20 minutes away. Me and my coworker got back, I decided to check my phone and see if she messaged me or anything. Come to find out, she basically just fucking ghosted me. Blocked me, unmatched me on tinder, the whole nine yards. No warning, nothing. 8 hours earlier she was saying how much she wanted me inside her (not paraphrasing), and now she just decided "nah fuck him altogether". I don't fucking know what it is. It's been about 10 hours since I found out, and I just..I don't know. She could have just said "nah I don't wanna fuck" and I would have been 100% fine with that. But nope. No warning, just blocked me. I'm not mad that she just backed out of it, I'm mad that she didn't say fucking anything about it. Like, even apart from all the sexting and stuff, I genuinely liked this girl. She was nice, cute, funny, just everything I could have asked for. And now, I'm honestly kinda sad about it. Everything seemed like it was going well (maybe all the sexting would have been better for another time in the future ya know, but I can honestly say I didn't initiate it), and now I have nothing again.19 - Had a bug that I just couldn't figure out. How did I solve it? Had to think like a user. Just started clicking options over and over. Not giving it time. Found my issue - Started a new job recently and feel like I don't know anything compared to everyone else, only got a years commercial experience but feel like I should know more! Anybody else ever feel like this when they were starting out? How do you overcome it - - Since I've started writing in clojurescript a 1.5 yrs ago, I can barely look at JavaScript. I started to realise how ugly it is. Seriously waiting to the day browsers will work with clojurescript out of the box, without the need to compile. The language is so clean, clear, easy and data oriented, I find it hard to go back to js. Also, the docs are much better. Long live concurrency !15 - don’t recall why but a project was in need of an all-nighter and I was the only programmer available to do it. I even brought a sleeping bag and, about 2 hours before people started arriving for work the next morning, I slept in a gap between my cubicle and a wall. I brought a shaving kit and everything. For some reason I didn’t want people to know I had pulled the all-nighter so I had to make sure to get up and look presentable before the first person got there. When my kids get the mistaken notion that they’ll be able to be like me right out of school and be able to make the money I make and have the flexible schedule I have and work from home and choose projects I like, I tell them my war stories about how I had to work 23 years of some hellish stuff to gain that privilege. - took literally days to get our software installed onto the client VMs and get the services started correctly. On our own test VMs the same task takes all of about an hour or so. Mind you these VMs are supposed to be created and match the client's environment almost too the T. Same configurations, same third party software, same environment variables and the whole 9 yards. This was not the case at all. Environment variables were not set, third party software was not installed, and I honestly don't remember the list of things wrong with how they setup the VM. Sparing the details, the errors were also not helpful. They also gave us critical information we needed for development days before we were going on site to test. The amount of hackery we had to do could be a completely separate rant on its own. While desperately trying to to stay sane long enough to get our services started, the only thing I could think was how great it would be if there was a fire or something. Anything, just to have an excuse to go back to the hotel and actually sleep. The second day there we finally had everything installed and running. I shit you not, just as we began our first test, the fire alarms went off. At this point in time the team was extremely (pissed tf off) annoyed to put it mildly. Assuming it was just a drill, we left our stuff and went to eat dinner. After we came back we found out it in fact was not a drill... Moral of the story: Don't wish bad fortune on a customer even if out of impulsive spite. Other moral of the story: Don't leave your belongings behind only because you think the fire alarms are just a fire drill. It may not be. P.S. Karma's a bitch.1 - - So I had this awesome idea yesterday, and I was really in to it and all, so before I started working on it I googled some stuff, and while looking for something (how do you generate session cookies) I just found out that somebody did EXACTLY what I wanted to do. Now I'm sad.7 -?4 - In the end of May, I sent a quote for a website to an agency, with a deadline of 60 work days (mon~fri) so I could work everything out and develop custom code etc. It got approved and I started working on it. Today they sent me a message asking me if the website's ready for deploying tomorrow (!!!), because they told their client they'd be able to launch tomorrow and now they don't want to extend the deadline. I don't know how bad they are at counting days or remembering things, but I want to smack'em with a damn baseball bat as hard as I can. Tbh, I'm almost jumping off the stairs on purpose to see if I can break a leg and get more time.3 -* - So I've just started pledging for an emulator project that I've been waiting for for a long time. I can't wait to see how it turns out! It's my first time monthly pledging, too ^ - - My biggest data loss and also contributed in me getting into computer stuff was when dad formatted the computer before I was able to take a backup, felt so bad at that time it had all my photos from school with friends. So instead of crying in the corner and me not knowing they can be brought back, at least half of them, I started learning how computers work, how software work, what type of software is out there ...etc. Though that brought more work for dad having to format my mess every month of so XD But I ended up learning a lot of new things. Then one programming class at school sent me into the dev - It is so funny how this PM got dizzy when I started detailing all the possibilities of her generic requirements and asking for clarification and we started drawing how the fuck she wants in to be. But "just put all data on the report" should be simple, right? Not a 2 hours discussion on one topic out of 10, right? Not.3 -.3 - - Okay. So. I was fixing my laptop (the screen was broken) and I decided to just boot it normally rather than into linux with my USB just to test it. Once it booted up I thought "you know what would be funny, if I decided to look at my crappy first ever programs", so I fired up eclipse and looked at them. Spoiler alert: it was really bad. I then decided to go to my first proper project where I didnt follow a tutorial for it like I had with most bigger things up to this point. This was when I remembered that all the files had a last modified date. I decided to go back to my first projects folder to see when I made it. Turns out it was 6 months before I thought I had started coding. Awsome! I have 6 months extra experience. Turns out this means in 2 years, 3 months I'll have 5 years experience, which is about half a year after I finish college. First of all, it does not seem like almost 3 years already Second, I cant believe how soon after finishing college I will reach 5 years. I thought it would be *atleast* a year.4 - . - -. - I've posted about this a little in the past but.. my situation is that I got hired by a company as a developer, it turns out it was a lead dev role and they some how believe that I'm a one man army that's gonna finish a really huge web application started by another dev that left the company (apparently out of frustration from what I'm gathering in code comments and other employees) All of this needs to be done in four months. I have never written a web application from the ground up and have always been subordinant to more competent developers. The team I with speaks mostly French and I can't help but notice the ever increasing social, communication, and cultural divides, being ostracized by people that I need support from because they don't speak great English has been frustrating to say the least. People have taken a step back in other areas which has me concerned they might be wanting to axe me cause I'm not making enough progress. Helppppppp - !Rant I just got some free swag :D I put it on the HP logo, didn't think about it sinking into it, it looked shit before I started to press it on there It turned out quite well though, now I like the HP looking through But now I can see how misaligned I was... it's going to annoy me :/4 -.13 - They dont mention it in any reviews but dell has cooling problems. Yesterday I bought a brand new g5 from a shop and fans were not spinning until 80c from which it started spinning at 4900rpm like a vacuum. Note that I have latest bios so its not temperature table problem in bios. I found out that there is a driver for thermal power which you can install and for most people it does the work (runs 2200 rpm silent cooling for most of time and 4900 rpm when cpu gpu temp goes above around 60c which is annoying) So I had to spend entire day on figuring out how to control cooling fans myself. And even then dell limited available speeds in bios at 0, 2200 and 4900 rpm. Anyways now my cooling fans run at 2200 rpm until 70c and 4900 after. So i get some nice silent performance for 90% of what I do and as for gaming, full fans after 75c is fine. I ran DOOM from steam and max temps Ive got were around 85-90c which is pretty high, so Im thinking of doing a repaste event though im afraid of voiding the warranty.5 -. - - One year since I started programming I feel like I haven't made enough progress. If I have an idea, I don't know how to get started with it. When I finally figure out a good starting point, I get stuck in Tutorial Land and I feel like I should be able to do things myself with just the documentation instead of doing beginners tutorials y'know?1 -. - So I bought a new phone, I was super excited getting it, I even got to open it at work with my colleagues watching. It was really nice, the S8 is an attractive phone... Until it started crashing very very regularly. I want to go back to my old phone, that's how bad it is. Turns out this is a common experience, how can this be at the top of all the review lists if it has this problem? Is the assumption that you are going to install stock android as soon as you get it? Or is someone paying for reviews?5 - I feel like such an idiot every time I use windows just slightly beyond clicking buttons. I'm trying to write a very simple macro to simply send an email out when I receive an email with a particular header. and no, outlook doesnt support that with rules. so now I have to use this garbage IDE, writing a script in a 25 year old language, with every bell and whistle button you could possibly think of and no way of figuring out how to do anything without being balls deep in a decade old forum post. I hate microsoft more and more every time I use it. I thought maybe if I got good and started "dev"ing with it more, I'd hate it less, but no... its always some super clunky application with shit tons of buttons and you dont know what they do, and when the app breaks, it gives you some hex number and nothing else, and sends all the good stuff to microsoft so they can fix it in the next "big update" thatll fuck up youre entire days worth of work and kill an hour of your precious time. Ugh.1 -. - started to try out xamarin. a ideal way to write it once and use it in 3 apps. on windows all was fine. android sdk adn ndk installed everything ok. starts to looked at ios hmm, you need mac to build project, simulate. oh wait even the UI designer you need mac pc. WTF is going on here, are you serious apple. come to think of it, now i get how apple sales numbers are high. when developers and companies need to by apple pc in order to make a fucking app for them. but that's not all you need to pay 100euro a year to publish the app.15 - I start by diving straight into the code. A blank brand new file in whatever language I have chosen to create my project in. If it's a language I'm unfamiliar with, I'll start with some templates of getting started (for example, I wanted to make a node.js application with a connected website, so I found some code using express to link the two together). Once I've started, I'll eventually create a text file for ideas which I may or may not plan to implement later. If a particular feature is rather complex, I'll draw it out on my whiteboard, giving me a visual guide to help me. My main aim is to simply get a "foot in the door"; once that's achieved, it makes working on the project much more enjoyable. I tend to turn it into a bit of "play" by coming up with suggestions which I would probably not implement in my final design, but add just for the fun of it. If I chose to drop those ideas, I'll save the code - chances are, I would have learnt something new in the process (For example, I learnt how to perform GET requests and figured out what cURL was for the first time by simply adding a "dad joke generator" to a discord bot, just for a laugh) - -. - I used to blast throught everything accademic in a really short time span. I used to push hard on the gas pedal since my college years, up to my bacheler degree. I was always on schedule with every exam, even graduated top of my class and first amongst my colleagues. But then, I felt the urge to change university, I moved out of my parent's home, in a far away city, and everything simply collapsed. All of the sudden, not only was I struggling with my exams, but, most importantly, I started struggling with telling the truth about it. I constantly felt in debt of my parent's efforts to put me through university, to have given me a chance. This caused a strange feeling in me, it was similar to a weird form of depression, I was unable to...act. To do stuff. To even wanting to do it. I started procrastinating everything. I lived at my parent's expenses in this far away town but all I could do was playing videogames. I somehow managed to get to the point that I only had three exams left plus my thesis, but I did this by avoiding all the real hard exams, somehow cheating myself. I was already two years behind schedule at this point, and willing to quit. I was desperate, I cried a lot, thought about running away fron everything as I fear the disappointment I would have caused by simply telling the whole story. Thankfully I met my girlfriend who helped me realize all I needed to do was move back to my former university and take it step by step from there onwards. I almost didn't make it...again. But I was able to pull throught, I worked during the day, wrote my master thesis early in the morning and late in the evenings. I gave it all. And I made it. I graduated last year and got a job in the industry. I don't feel as useless anymore. I still fear and dread what the burnout made me feel. How it almost destroyed all confidence I had in myself. Tldr; I burned out right after getting my bachelor degree. And I stayed like that for years, up to the point that I ended up being years behind schedule. I was able to recover thanks to my gf but still fear and dread those feelings I had when I burned out. - - while(true) { $us->me(); } Damn it. I'm stuck on an infinite loop and can't get out. I'm starting to feel unmotivated on our first project as a team. No financial support from client. Disastrous planning phase. I really do want to drop this project. But I won't because of my dev friends, we started this together. Another thing that frustrates me, they don't know how to use Git. If there are changes on the system, we have to transfer it through flash drive. [ill teach them]. I don't wanna go to the point that this project becomes toxic. So frustrating. This too shall pass. Does every start have to be this hard and frustrating? - - //. - Client deescalation needed and intervention by company leader... Client refuses to test - too much work they say. Client wants a lot of changes - but cannot define what. But most frustrating... Even as we tried to with all patience that was left to find out what they were doing aka how they work, what work flows, documents and so on were involved, they basically started a team discussion and seemed to work all differently... And the project should be a complete sale and warehouse solution, suited and written for their needs. Really? How can a company like this work? It's not the first time I've dealt with hard projects or 'weird' customers, but really the first time I have no fucking clue what I should do. Can someone please summon Ctulhu?3 - - One year ago my journey with php is started... And now we figured out how to working with mysql How lazy i am :)1 - -).4 - - 2 months since i started my project and i still can't figure out how to use cookies to login at a website using only java - Setup an Urbit planet Got it working and it’s beautiful Started doing development Broke my planet because I’m me Now I’m sad as I try to figure out how to fix it and not doing development -!! :)
https://devrant.com/search?term=how+i+started+out
CC-MAIN-2020-24
refinedweb
8,961
80.01
Suppose I have a base class and derived class similar to following: #include "Sprite.h" class Base{ private: int X; //location Sprite* sprite; public: Base(Sprite* sprite){ sprite = new Sprite(some parameter); } int getLocation(){ return X; } int getWidth(){ return sprite->getWidth(); } } class Derived : public Base{ private: Sprite* sprite; // here I have to redefine it in constructor public: Derived(Sprite* sprite); // it's different that base constructor { sprite = new Sprite(some parameter); sprite->setPriperty(some parameter); } } So first of all - what is a segmentation fault? It's something simmilar to a NullPointerException in Java or a NullReferenceException in C#. It happens when you try to access non allocated memory. Why is this happening? You forgot to allocate memory for the sprite pointer, so it's pointing at some not precised memory chunk. You should initialize it in your constructor by using the new operator like this: Base::Base(Sprite* sprite) { this->sprite = new Sprite(sprite); } If you like to live dangerously you could also do the following: Base::Base(Sprite* sprite) { this->sprite = sprite; } But it's not safe, because the sprite could be allocated on the stack, so code like this could wreck havoc to your program causing undefined behavior: Base * getBase() { Sprite sprite; //some code operating on sprite return new Base(&sprite); } It's hazardous, because after exiting the getBase function there is no sprite anymore in the memory. Update: So basically what I concluded from you comments is that you don't call the proper constructor of your Base class. Your Derived constructor should look like this: Derived(Sprite* sprite): Base(sprite) { ... } If you don't do this you do not set the value of sprite for your base class. Your sprite field of your derived class is just shadowing the sprite field of your Base class. It's like: int i = 0; void fun() { int i = 20; } In the example the global i did not change, because it was shadowed. Your code works after duplicating the getWidth() method in the Derived class, because it was accessing then the sprite field of your Derived class. To be clear - without overriding the method getWidth() is accessing the sprite field of the Base class, when you override it it accesses the field of the Derived class.
https://codedump.io/share/F9VoYjLNbUPJ/1/c-derived-class-call-base-class-method-give-segmentation-fault
CC-MAIN-2018-05
refinedweb
376
54.56
Updating the DOM in React Q: How do you update the DOM in React? A: Call the setState() function on the component you want to update. setState() will re-render the virtual DOM, which will check for anything that has changed, and update the page display accordingly. Interestingly enough, the state doesn't even have to change. For example, in the code snippet below, I have the status value initially set to 0, and in my handleClick() function I set the state ( this.setState({ status: 0 });) to the same value of 0, which re-renders the component. class MainContainer extends React.Component { constructor(props) { super(); this.state = { status: 0}; } handleClick() { recipes.push(<Recipe />); this.setState({ status: 0 }); } render () { return ( <div id="accordion" role="tablist" aria- {recipes} <button onClick={() => this.handleClick()}Add</button> </div> ); } } ReactDOM.render( <MainContainer />, document.getElementById('app')); Nice find. For this exact case you could use this.forceUpdate(). This will force a re-render of the component without the need of setting the state.
https://codepen.io/joelmasters/post/updating-the-dom-in-react
CC-MAIN-2018-39
refinedweb
166
53.17
Sugar/Quick screenshot hack From OLPC The Sugar keyboard shortcut alt + 1 on the XO captures the screen, and creates an entry in the journal that you can title and copy to a USB drive. The method is useful for a small number of screenshots, but does not scale. This page describes a more advanced procedure to deal with multiple screenshots. Background Cynthia from the learning lab asked me (DanielDrake) to hack an XO so that taking a substantial number of screenshots and transferring them to her Mac is easy. Right now, it is tedious to copy screenshots one-by-one to a USB drive and then transport the USB drive to another system. Requirements - An internet-connected XO running sugar - ssh access to a remote server on the internet, which we'll call remote.server.com (and your username is "user") - The internet-connected "target" computer The decision was made to store the screenshots on a remote server and access them through the remote server to allow for the XO's IP changing, different XO's being used on different days, etc. It would also be realistic to store the screenshots on the XO and have the target computer access them over SSH, and that would only be a simple modification below. Creating SSH key and configuring remote server The XO needs to have passwordless access to the remote server. You need to create a ssh key pair. If you want to have multiple XOs set up like this, only one of them needs to create the key, then you can copy it to any more XOs that you want to use in this way. - On the XO, launch a terminal activity - Generate a SSH key: - ssh-keygen -t rsa - Copy the public key to the remote server - ssh-copy-id -i .ssh/id_rsa.pub user@remote.server.com - Log into the remote server (confirming that there is no prompt for password/passphrase) and create a screenshots directory - ssh user@remote.server.com - mkdir screenshots - Logout of remote server - exit Setting up the XO - At the terminal activity, create a local screenshots directory - mkdir screenshots - Create a script called at /home/olpc/cpscrn with the following contents: #!/bin/bash scp $1 user@remote.server.com:screenshots - Be sure to modify this line to reflect your remote server information - Mark it executable - chmod a+x /home/olpc/cpscrn Modifying sugar Sugar must be modified to save screenshots to disk, rather than to the journal, and then copy them over SSH. The modifications are in three parts: - place screenshots in a special directory, with the correct file type (a changed file_path), - run the cpscrn script to copy the screenshot over SSH (an os.system call), - avoid adding the screenshot to the journal (a premature return). How to modify Sugar: - Become root - sudo -s - For Sugar 0.84, open /usr/share/sugar/extensions/globalkey/screenshot.py in a text editor - nano /usr/share/sugar/extensions/globalkey/screenshot.py - Find the handle_key_press function, - ctrl + w handle_key_press - For Sugar 0.82, open /usr/share/sugar/shell/view/Shell.py in a text editor - nano /usr/share/sugar/shell/view/Shell.py - Find the take_screenshot function, about 85% of the way through the file - ctrl + w take_screenshot - On the line after the function declaration (def), change how the file_path is prepared, the red line is the new text that replaces the old text: def handle_key_press(self): file_path = os.path.join("/home/olpc/screenshots", '%i.png' % time.time()) window = gtk.gdk.get_default_root_window() - About 10 or 11 lines below, after the call to screenshot.save, add two lines of code, the red lines are the lines that you need to add: screenshot.save(file_path, "png") os.system("/home/olpc/cpscrn %s" % file_path) return client = gconf.client_get_default() - Save the file and close the text editor Accessing remote server - Configure your target computer to have access to the screenshots subdirectory on remote.server.com. - This is system-dependent. Taking screenshots - Restart sugar so that your code changes take effect - ctrl + alt + erase (warning: will lose unsaved work!) - Press alt + 1 to take a screenshot - The journal will no longer contain the screenshot - The screenshot will be saved locally in /home/olpc/screenshots and also copied to the remote server - It may take a few seconds for the screenshot to be saved, compressed, and uploaded over the internet - You can then view the screenshot(s) on your target computer by opening the folder on the remote server Notes After update of build After you update the build, the ssh key will have been removed, and you must re-generate it. - Generate a SSH key: - ssh-keygen -t rsa - ssh-copy-id -i .ssh/id_rsa.pub user@remote.server.com - ssh user@remote.server.com - mkdir screenshots - exit You will also need to reapply your changes to Shell.py or screenshot.py.
http://wiki.laptop.org/go/Sugar/Quick_screenshot_hack
CC-MAIN-2014-15
refinedweb
811
52.39
"Consistency is highly over valued. don't be afraid to change your mind for fear of being branded an inconsistent hypocrite." Stalin, Kruschev and Brezhnev are travelling on a train. The train breaks down. 'Fix it!', orders Stalin. They repair it but still the train doesn't move. 'Shoot everyone!' orders Stalin. They shoot everyone but still the train doesn't budge. Stalin dies. 'Rehabilitate everyone!' orders Kruschev. They are rehabilitated, but still the train won't go. Kruschev is removed. 'Close the curtains,' orders Brezhnev, 'and pretend we're moving!' Anon "If someone gives me a forum to express myself, I will use it. If that means using 'mainstream' channels to do it, then that's all for the better. If you really believe in what you're doing, then why not? By being too cool to publicly talk about these things, we only perpetuate the silence that already exists." Outpunk (taken from Zines, RE SEARCH): moveon.org From Publishers Weekly Renowned pianist and conductor Barenboim, currently general music director of the Deutsche Staatsoper Berlin, comes from a Russian Jewish family transplanted to Argentina and Israel. Said (Orientalism), Columbia professor of English and comparative literature and an accomplished amateur pianist, is a Palestinian who grew up largely in Cairo in an anglicized Christian Arab family. Their differing but entwined histories have led to friendship and a number of public and private conversations about music, culture, politics and "the parallels as well as the paradoxes" of their lives. Edited by Guzelimian, Senior Director and Artistic Adviser of Carnegie Hall, these stimulating discussions-written in the form of three-way Q&A interviews-touch on the nature of sound, some of the similarities and differences between music and literature, performances and audiences, and the authenticity movement. The two agree on the importance of music in uniting people of conflicting political views, and in 1999 they collaborated in setting up the Weimar workshop, which brought together Arab, Israeli and German musicians to form an orchestra. The importance of setting aside national identity in favor of a larger ideal is stressed throughout the book. Barenboim shows himself to be unfazed by the recent controversies surrounding his work in Berlin and his determination to perform Wagner in Israel. Said remarks that in today's world, it has "become quite rare to project one's self outward, to have a broader perspective." These enlightening conversations show that Said and Barenboim are able to do just that. JBoss provides an Mnean that is configured in the root configuration file to view the ojects bound in its JNDI namespace. The MBean definition is shown below: <mbean code="org.jboss.naming.JNDIView" name="jboss:service=JNDIView"> If you access the MBean from JMX console and invoke the list() method, it will list all the contexts and the objects in the JNDI namespace. This page is a very usefull in troubleshhoting problems that occur in performing naming and lookup operations...
https://coderanch.com/u/10064/ersin-eser
CC-MAIN-2020-24
refinedweb
491
53.81
These are chat archives for mithriljs/mithril.js Hey @lhorie may I suggest an alternative data structure for the underlying hyperscript, seeing as you are undecided and exploring things? I am proposing, you'd still be able to use m('div', ...), but the underlying structure is almost as readable as the invocations. mconversion calls What if it the output of m was so similar in structure to the invocations, that in some cases, you could write the data output directly, and save your callstack/memory usage. Something like: //model var text = m.prop("") var count = m.prop(0) //view [ 'div', [], [ ['input', [ ['type', 'text' ], [ 'oninput', m.withAttr('value', text)] //fig 1. ]], ['button', [ ['onclick', count, [ count() + 1 ]] //fig 2. ], 'Increment'] ['p', [ [' style', [ ['font-family', 'Helvetica'], ['font-size', '2em'] ]] ], 'The count is '+count() ] ]] I think the attrs and the style are pretty self explanatory. But I just want to quickly talk about event handlers. In mithril, there are generally two kinds of event handlers. Snabbdom has this great idea where in the case of 2. you don't need to do any binding, you just specify the args to call the function with if it were fired. function clickHandler(number) { console.log('button ' + number + ' was clicked!'); } h('div', [ h('a', {on: {click: [clickHandler, 1]}}), h('a', {on: {click: [clickHandler, 2]}}), h('a', {on: {click: [clickHandler, 3]}}), ]); So I'm just stealing that idea. But I'm suggesting the arguments are always an array (this is a low level API), so there is no need to do any arg slicing. It's all about performance. So in fig1, there is no array in the index[2] so there is no need to bind, just call the handler directly. In fig2, there is an array of args. So we just pass them along. [eventName, handler, args] = event // the array from above window.addEventListener( eventName.replace('on', ''), args ? _ => handler.apply(null, args) : handler ) Also, while we're on crazy ideas. What if the document fragment was passed into the controller on init. It removes a lot of that weird awkward code when you are passing state between config and the controller. I'm not 100% sure how that would work. Particularly when you don't know what the root element tag will be for a component. But it might simplify things? @spacejack thanks, I'm curious what @lhorie thinks about the feasibility too. Perhaps its harder to traverse/index. If everything is a list, it becomes hard to know if you are looking at a tag, or an event handler, or a style object without having more context while traversing. One nice aspect of this list approach, is augmenting elements after the fact with standard list operations. And not overwriting existing keys: ['ul',, [ ['li',[], 'Apples'], ['li',[], 'Bananas'], ['li',[ ['style', ['font-family', 'Helvetica'] ] ], 'Oranges'] ]] .map(colorizeList) var colorizeList = ul => ul => ul.map( li => li[1].concat( ['style', [ ['color', randomColor()] ]] ) ) The colorizeList function adds a style tag to each li, but the existing structure already had a style list. In the old structure,we'd need to use 'Object.assign' or something. But in this new system, we just add our style list and they both coexist, like 2 separate stylesheets. The conflicting li just becomes: ['li', [ ['style', ['fony-family', 'Helvetica']], ['style', ['color', 'rgb(111,123,123)']] ], 'Oranges'] Again, you'd still be able to write: m('li', { style:{ fontFamily: 'Helvetica' } }, 'Oranges') This is just a low level thing. ])})} Hadn't heard of either @barneycarroll But you are right: This is my development script: watchify modules\ui\src\index.js -d -p [ tsify ] -t [ babelify --presets [ es2015 ] ] -o dist\bundle.js -v --poll=1000 It's processing both typescript and es6 And this is the production script with uglify browserify modules/ui/src/index.js -p [ tsify ] -t [ babelify --presets [ es2015 ] ] | uglifyjs -mc > dist/bundle.js So you can just take out -p [tsify] and -t [babelify --presets [es2015 ]] if you are not using anything like that. I include it because sometimes involved examples are better than simple examples tentatively, the js language support in vscode is terrible since the latest typescript salsa update. As soon as you make a file .ts all the old functionality comes back. feels like a bait and switch import as from 'asarg' import m from 'mithril' export default ( [ open, close ], content ) => close.replace( /$\s*<\/|>\s*^/ )::as( tag => m( tag, content ) ) // Usage: // m`<ul> // ${ list.map( item => // m`<li> // ${ item } // </li>` // ) } // </ul>` m`<ul> ${ list.map( item => m`<li> ${ item } </li>` ) } </ul>` that's pretty cool, kind of reminds me of ::work in a more functional way ( expression )::as( expressionResult => { /* whatevs */ } ) close.replace( /$\s*<\/|>\s*^/ )::as( tag => m( tag, content ) ) (function( expressionResult ){ return /* whatever */ }( expression )) export default ( [ open, close ], content ) => m( close.replace( /$\s*<\/|>\s*^/ ), content ) export default ( [ open, close ], content ) => { const tag = close.replace( /$\s*<\/|>\s*^/ ) return m( tag, content ) } asarg) to the m function asis to get an immediate reference to the preceding operand in a point-free manner Seems pointless. Functions can be trivially composed to form a “pipeline” without introducing new syntax: lodash.com/docs#flow These examples only make this language extension look like a confusing and horrible thing. How is this an improvement, in any way? This is a terrible example. It looks a lot better with what's already available About the usefulness of this proposal, this one conflicts with the function bind syntax and assuming FBS is all rainbows and unicorns and everyone should use it, then this proposal makes no sense since the original example should be written like this (and it's already good enough) Using this is a clear winner since that's how the native and user utility methods for the .prototypes of String, Array and such work I really don't see much gain in adding this syntax when there is already a FBS proposal that covers most of the cases. :( Its threads like this that make me happy that JS will probably become "just a compilation target" eventually. And I like JS. But most of es6 is just noise. The examples where mindeavour demonstrates inserting user functions into a proprietary chain is just superb. Its effortless. Lodash already exists Is the dumbest argument ever flowand introduced fpsays a lot. Such a mainstream library moving away from chaining and also recently removed the thisarg from all of its iterators when done correctly, the name is absolutely never redundant cruft. when done poorly, it always is. total garbage sendAction getObjectAtIndexetc ServiceAdapterManagementBroker@brokeServiceManagementAdaption @lhorie any thoughts on the structure I proposed :point_up: April 8, 2016 11:16 AM the issue was the need for concat instead of nesting input[type=text].awesomestuff less and less mto enable it (perhaps even using the pipeline operator), but I'm just curious how much the convenience costs. If its expensive, we could opt out at the library level var M = compose(m, specialRegexThing) specialRegexThingjust added it to the attrs, mithril-objectifywould have to work with it @barneycarroll I used to do that. But I find all my styles are inline so I don't need classes. And, I have utils for most basic element components, and they use attrs. But all I am saying is, its rare to have somethign expensive, that is so trivial to add a layer that supports it. mwould be if it didn't check a regex we may not even be using You discover this as soon as you build something of any significant scale can confirm this! :posts/:comments, and all that stuff is on the server, and the server has a verbiage around the model that matches the view requirements 1:1 — then it's really contrived to say you want to be able to separate out the elements of state There was a WebGL package, it was experimental sure, but the error messages for the package manager were so vague, and Elm is all about "great error messages". Meanwhile npm is just great, so I'm waiting. But I will leave JS one day, now I know this mwritten, one I call strictHyperscriptwhich has the signature m(tagString, attrsObj, childrenArray), no CSS selectors, no variadic support m, vs ~4ms with optimized mvs ~3ms with strictHyperscript msince it gets none of the memoization benefits, but that's not a realistic bench either cond1 && cond2. If they are not looking at this stuff obsessively, then it's very likely they will step into a deopt trap while writing out their beautiful algorithm To test this Lambda thing I'm going to try uploading generated garbage data, and downloading random files from s3, just to isolate what the hard limits are. Right now I don't know if 2.7 gb is good or bad for the process, because I don't know the upload/download rate. If I can get 7gb with garbage data, then I know 2.7 gb is probably not good enough @spacejack not sure, I think its different. I think strong mode was about determining types within the engine wasn't it? I'm thinking this would just accept things to be true, it would trust the compiler whether it was Elm or TS. But I have no clue... this.el = m("div", null, m("table", { class: "table table-striped latest-data" }, this.tbody = m("tbody") ) ); this.rows = new frzr.List(Row) frzr.mount(this.tbody, this.rows) this.rows = new frzr.List(Row)is this some kind of observable? m("tbody", null, m(Row))or such, instead of that ugly mountshenangians m(Row), you'd not be able to call updateon it later on m("tbody", null, m((this.row = new Row(), this.row.el))) @lhorie how about divide mithril components to difference modules and difercence files? import {m, Defered, Request, Route, and others} from 'mithril'; and for old style var m = m || {}; m.request... var m = m || {}; m.defered... import {Render as m, Route} from 'mithril' I have spent all morning trying to get m request objects working for my get request to a rest endpoint. It is not working for me, as I need an 'Authentication' header. This works: curl -u name:password -i -X GET and it sends Authorization: Basic bmFtZTpwYXNzd29yZA== Content-Length: User-Agent: curl/7.35.0 Host: 127.0.0.1:5000 Accept: */* Content-Type: I want my mithril code to do the same thing. Using xhr.setRequestHeaderadds to Access-Control-Request-Headers, but how do I add to the regular headers? @lhorie That is what I thought would be. My code is this: response = m.request( method: "GET" url: "{location.hostname}:5000/#{URL}" config: (xhr) -> xhr.setRequestHeader("Authorization", "Basic bmFtZTpwYXNzd29yZA==") xhr.setRequestHeader("Access-Control-Allow-Origin", "*") ) but it is sending out Origin: Content-Length: User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0 Connection: keep-alive Access-Control-Request-Headers: access-control-allow-origin,authorization Host: localhost:5000 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Access-Control-Request-Method: GET Accept-Language: en-US,en;q=0.5 Content-Type: Accept-Encoding: gzip, deflate Here is it changing Access-Control-Request-Headersinstead of just being a straight header. I must be missing something glaringly obvious, but for the life of me I can't find it. Any help is immensely appreciated. config: (xhr) => { xhr.setRequestHeader('Content-Type', 'application/json'); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); const t = token(); if (t) { xhr.setRequestHeader('Authorization', 'Bearer ' + t); } }, Authorizationheader document.querySelector(‘#app’)
https://gitter.im/mithriljs/mithril.js/archives/2016/04/08
CC-MAIN-2018-22
refinedweb
1,918
57.27
sigsetjmp() Save the environment, including the signal mask Synopsis: #include <setjmp.h> int sigsetjmp( sigjmp_buf env, int savemask ); Arguments: - env - A buffer where the function can save the calling environment. - savemask - Nonzero if you want to save the process's current signal mask, otherwise 0. Library: libc Use the -l c option to qcc to link against this library. This library is usually included automatically. Description: The sigsetjmp() function behaves in the same way as the setjmp() function when savemask is zero. If savemask is nonzero, then sigsetjmp() also saves the thread's current signal mask as part of the calling environment.: Zero on the first call, or nonzero if the return is the result of a call to siglongjmp().
http://developer.blackberry.com/native/reference/bb10/com.qnx.doc.neutrino.lib_ref/topic/s/sigsetjmp.html
CC-MAIN-2013-20
refinedweb
120
65.12
Learn to write a simple java program to verify if a given number is pronic number or not. 1. what is a pronic number A pronic number is a number which is the product of two consecutive integers, that is, a number of the form ‘n x (n + 1)’. They are also called oblong numbers, heteromecic numbers, or rectangular numbers. For example, consider following example of number 6. Given number is : 6 2 x 3 = 6 //6 is pronic number The first few pronic numbers are: 0, 2, 6, 12, 20, 30, 42, 56, 72, 90, 110, 132, 156, 182, 210 etc. 2. Algorithm to determine pronic number To find if a given number is pronic or not – - Find the square root ‘K’ of given number. - Multiply K with K+1. If number is equal tooriginal number, the number pronic number; else not. 3. Java Program to find pronic number public class Main { public static void main(String[] args) { System.out.println("56 is pronic number " + isPronicNumber(56)); System.out.println("57 is pronic number " + isPronicNumber(57)); } static boolean isPronicNumber(int numberToCheck) { int sqrt = (int)(Math.sqrt(numberToCheck)); return sqrt * (sqrt + 1) == numberToCheck ? true : false; } } Program output. 56 is pronic number true 57 is pronic number false Happy Learning !!
https://howtodoinjava.com/java-programs/check-pronic-number/
CC-MAIN-2020-10
refinedweb
209
57.37
by Tim Ewald and Kimberly Wolk Summary: There are many challenges in systems integration for architects and developers, and the industry has focused on XML, Web services, and SOA for solving integration problems by concentrating on communication protocols, particularly in regard to adding advanced features that support message flow in complex network topologies. However, this concentration on communication protocols has taken the focus away from the problem of integrating data. Flexible models for combining data across disparate systems are essential for successful integration. These models are expressed in XML schema (XSD) in Web service–based systems, and instances of the model are represented as XML transmitted in SOAP messages. In our work on the architecture of the MSDN TechNet Publishing System (MTPS), we addressed three pitfalls. We'll look at what those pitfalls are and our solutions to them, in the context of a more general problem—that of integrating customer information. The Essential Data-Integration Problem Demanding Too Much Information No Effective Versioning Strategy No Support for System-Level Extension Mitigating the Risks About the Authors Resources Systems integration presents a wide range of challenges to architects and developers. Over the last several years, the industry has focused on using XML, Web services, and service-oriented architecture (SOA) to solve integration problems. Much of the work done in this space has concentrated on communication protocols, especially on adding advanced features designed to support messages flowing in complex network topologies. While there is undoubtedly some value in this approach, all of this work on communication protocols has taken focus away from the problem of integrating data. Having flexible models for combining data across disparate systems is essential to a successful integration effort. In Web service–based systems, these models are expressed in XSD. Instances of the model are represented as XML that is transmitted between systems in SOAP messages. Some systems map the XML data into relational databases; some do not. From an integration perspective, the structure of those relational database models is not important. What matters is the shape of the XML data model defined in XSD. There are three pitfalls that Web service–based data-integration projects typically fall into. All three are related to how they define their XML schemas. We confronted all three in our work on the architecture of the MSDN TechNet Publishing System (MTPS), the next-generation XML-based system that serves as the foundation for MSDN2. We will look at our solutions in the context of integrating customer information. Imagine you work at a large company. Your company has many outward-facing systems that are used by customers to accomplish a variety of tasks. For instance, one system offers customized product information to registered users who have expressed particular interests. Another system provides membership-management tools for customers in your partner program. A third system tracks customers who have registered to come to upcoming events. Unfortunately, the systems were all developed separately—one of them, by a separate company that your company acquired a year ago. Each of these systems stores customer-related information in different formats and locations. This setup presents a critical problem for the business: It doesn't have a unified view of a given customer. This problem has two effects. First, the customer's experience suffers, because the single company with which they are doing business treats them as different people when they use different systems. For example, customers who have expressed a desire to receive information about a given product through e-mail whenever it becomes available have to express their interest in that product a second time, when they register for particular talks at an upcoming company-sponsored event. Their experiences would be more seamless if the system that registered them for an upcoming event already knew about their interest in a particular product. Second, the business suffers, because it does not have an integrated understanding of its customers. How many customers who are members of a partners' program are also receiving information about products through e-mail? In both cases, the divisions between the systems with which the customer works are limiting how well the company can respond to its customers' needs. Whether this situation arose because systems were designed and developed individually, without any thought to the larger context within which they operate, or because different groups of integrated systems were collected through mergers and acquisitions is irrelevant. The problem remains: The business must integrate the systems to improve the customer experience and their knowledge of who the customer is, and how best to serve them. The most common approach to solving this problem is to mandate that all systems adopt a single canonical model for a customer. A group of architects gets together and designs the company's single format for representing customer data as XML. The format is defined using a schema written in XSD. To enable systems to share data in the new format, a central team builds a new store that supports it. The XSD data model team and store team deliver their solution to all the teams responsible for systems that interact with customers in some way and require that they adopt it. The essential change is shown in Figures 1 and 2. Each system is modified to use the underlying customer-data store through its Web service interface. They store and retrieve customer information as XML that conforms to the customer schema. All of the systems share the same service instance, the same XSD data model, and the same XML information. This solution appears to be simple, elegant, and good, but a naïve implementation will typically fail for one of three reasons: demanding too much information, no effective versioning strategy, and no support for system-level extension. The first potential cause for failure is a schema and store that require too much information. When people build a simple Web service for point-to-point integration, they tend to think of the data their particular service needs. They define a contract that requires that particular data be provided. When a contract is generated from source code, this data can happen implicitly. Most of the tools that map from source code to a Web service contract treat fields of simple value types as required data elements, insisting that a client send it. Even when a contract is created by hand, there is still a tendency to treat all data as required. As soon as the service determines (by schema validation or code) that some required data is not present, it rejects a request. The client gets a service fault. This approach to defining Web service contracts is too rigid and leads to systems that are very tightly coupled. Any change in the service's requirements forces a change in the contract and in the clients that consume it. To loosen this coupling, you need to separate the definition of the shape of the data a service expects from a service's current processing requirements. More concretely, the data formats defined by your contract should treat everything beyond identity data as optional. The implementation of your service should enforce occurrence requirements internally at run time (either using a dedicated validation schema or code). It should be as forgiving as possible when data is not present in a client request and degrade gracefully. In the customer-information example, it is easy to think of cases where some systems want to work with customers, but do not have complete customer information available. For instance, the system that records a customer's interest in a particular product might only collect a customer's name and preferred e-mail address. The event registration system, in contrast, might capture address and credit-card information, too. If a common customer-data model requires that every valid customer record include name, e-mail, address, and credit-card information, neither system can adopt it without either collecting more data than it needs or providing bogus data. Making all the data other than the identity (ID number, e-mail address, and so forth) optional eases adoption of the data model, because systems can simply supply the information they have. Figure 1. Three separate data stores, one per system (Click on the picture for a larger image) By separating the shape of data from occurrence requirements, you make it easier to manage change in the implementation of a single service. It is also critical when you are defining a common XML schema to be used by multiple services and clients. If too much information is mandatory, every system that wants to use the data model may be missing some required piece of information. That leaves each system with the choice of not adopting the shared model and store, or providing bogus data (often, the default value of a simple programming-language type). Either option can be considered a failure. Figure 2. A single data store and format (Click on the picture for a larger image) You gain a lot of flexibility for systems to adopt the model by loosening the schema's occurrence requirements nearly completely. Each system can contribute as much data as it has available, which makes a common XML schema much easier to adopt. The price is that systems receiving data must be careful to check that the data they really need is present. If it is not present, they should respond accordingly by getting more data from the user or some other store, by downgrading their behavior, or—only in the worst case—generating a fault. What you are really doing is shifting some of the constraints you might normally put in an XML schema into your code, where they will be checked at run time. This shifting gives you room to change those constraints without revising the shared schema. The second potential cause for failure is the lack of a versioning strategy. No matter how much time and effort is put into defining an XML schema up front, it will need to change over time. If schema, the shared store that supports them, and every system that uses them has to move to a new version all at once, you cannot succeed. Some systems will have to wait for necessary changes, because other systems are not at a point where they can adopt a revision. Conversely, some systems will be forced to do extra, unexpected work, because other systems need to adopt a new revision. This approach is untenable. To solve this problem, you need to embrace a versioning strategy that allows the schema and store to move ahead independent of the rate at which other systems adopt their revisions. This solution sounds simple, and it is, as long as you think about XML schemas the right way. Figure 3. A combination of stores (see Figures 1 and 2) (Click on the picture for a larger image) Systems that integrate using a common XML schema view it as a contract. Lowering the bar for required data by making elements optional makes a contract easier to agree to, because systems are committing to less. For versioning, systems also need to be allowed to do more without changing schema namespace. What this means in practical terms is that a system should always produce XML data based on the version of the schema with which it was developed. It should always consume data based on that same version with additional information. This definition is a variation on Postel's Law: "Be liberal in what you accept, conservative in what you send." Arguably, this idea underlies all successful distributed systems technologies, and certainly all loosely coupled ones. If you take this approach, you can extend a schema without updating clients. In the customer example, an update to the schema and store might add support for an additional optional element that captures the user's mother's maiden name for security purposes. If systems working with the old version generate customer records without this information, it's okay, because the element is optional. If they send those records to other systems that require this information, the request may fail, and that is okay, too. If new systems send customer data including the mother's maiden name to old systems, that is okay also, because they are designed to ignore it. Happily, many Web service toolkits support this feature directly in their schema-driven marshaling plumbing. Certainly, the .NET object-XML mappers (both the trusty XmlSerializer and the new XmlFormatter/DataContract) handle extra data gracefully. Some Java toolkits do, too, and frameworks that support the new JAX-WS 2.0 and JAXB 2.0 specifications will, also. Given that, adopting this approach is pretty easy. The only real problem with this model is that it introduces multiple definitions of a given schema, each representing a different version. Given a piece of data—an XML fragment captured from a message sent on the wire, for instance—it is impossible to answer the question: "Is this data valid?" The question of validity can only be answered relative to a particular version of the schema. The inability to state definitively whether a given piece of data is valid presents an issue for debugging and, possibly, also for security. With data models described with XML schema, it is possible to answer a different and more interesting question: "Is this data valid enough?" This question is really what systems care about, and you can answer it using the validity information most XML-based schema validators provide, which is a reasonable path to take in cases where schema validation is required, and it can be implemented with today's schema validation frameworks. The third potential cause for failure is lack of support for system-specific extensions to a schema. The versioning strategy based on the notion that a schema's definition changes over time is necessary to promote adoption, but it is not sufficient. While it frees systems from having to adopt the latest schema revision immediately, it does nothing to help systems that are waiting for specific schema updates. Delays in revisions also can make a schema too expensive for a system to adopt. The solution to this last problem is to allow systems that adopt a common schema to extend it with additional information of their own. The extension information can be stored locally in a system-level store (see Figure 3). Figure 4. The same store (see Figure 3), with data formats in a shared store (Click on the picture for a larger image) In this case, each system is modified to write customer data both to its dedicated store using its own data model and to the shared store using the canonical schema. It is also modified to read customer data from both its dedicated store and the shared store. Depending on what it finds, it knows whether a customer is already known to the company and to the system. Table 1 summarizes the three possibilities. The system can use this information to decide how much information it needs to gather about a customer. If the customer is new to the company, the system will add as much information as it can to the canonical store. That information becomes available for other systems that work with customers. It may also store data in its dedicated store to meet its own needs. This model can be further expanded so that system-specific data is stored in the shared store, too (see Figure 4). This solution makes it possible for systems to integrate with one another, using extension data that is beyond the scope of the canonical schema. To work successfully, the store and other systems need to have visibility into the extension data; in other words, it cannot be opaque. The easiest way to solve this problem is to make the extension data itself XML. The system providing the data defines a schema for the extension data, so other systems can process it reliably. The shared store keeps track of extension schemas, so it can ensure that the extension data is valid, even if it does not know explicitly what the extension contains. In the most extreme case, a system might choose to store an entire customer record in a system-specific format as XML extension data. Other systems that understand that format can use it. Systems that do not understand it rely on the canonical representation, instead. When systems are independent, each controls its own destiny. They can capture and store whatever information they need, in whatever format and location they prefer. The move to a single common schema and store changes that. If adopting a common XML data format restricts a system's freedom to deliver required functionality, you are doomed to fail. Using a combination of typed XML extension data in either a system-level or the shared store adds complexity, because you have to keep data synchronized. But it also provides tremendous flexibility. You can align systems around whatever combination of the canonical schema and alternate schemas you want. You can drive toward one XML format over time, but you always have the flexibility to deviate from that format to meet new requirements. This extra freedom is worth a lot in the uncertain world of the enterprise. Table 1. The three possible cases of customer data A further, subtle benefit of this model is that it allows the team defining the common schema to slow its work on revisions. Systems can use extension data to meet new requirements between revisions. The team working on the canonical model can mine those extensions for input into its revision process. This feedback loop helps ensure that model changes are driven by real system requirements. Lots of organizations are working on integrating systems, using XML data described using XML schema and exchanged through Web services. In this discussion, we presented three common causes for failure in these data-centric integration projects: demanding too much information, no effective versioning strategy, and no support for system-level extensions. To mitigate these risks: All of these solutions are based on one core idea: to integrate successfully without sacrificing the agility systems need to be able to agree on as little as possible and still get things done. So, does it all work? The answer is: Yes. These techniques are core to the design of the MSDN/TechNet Publishing System, which underlies MSDN2. Tim Ewald is a principal architect at Foliage Software Systems, where he helps customers design and build applications ranging from enterprise IT to medical devices. Prior to joining Foliage, Tim worked at Mindreef, a leading supplier of Web services diagnostics tools. Before that, Tim was a program manager lead at MSDN, where he worked with Kim Wolk as co-architects of MTPS, the XML- and Web service–based publishing engine behind MSDN2. Tim is an internationally recognized speaker and author. Kim Wolk is the development manager for MSDN and the driving force behind MTPS, the XML- and Web service–based publishing engine behind MSDN2. Previously, she worked as MTPS co-architect and lead developer. Before joining MSDN, Kim spent many years as a consultant, both independently and with Microsoft Consulting Services, where she worked on a wide range of mission-critical enterprise systems. MSDN Magazine MSDN2 Library This article was published in the Architecture Journal, a print and online publication produced by Microsoft. For more articles from this publication, please visit the Architecture Journal website.
http://msdn.microsoft.com/en-us/architecture/bb245674.aspx
crawl-002
refinedweb
3,238
51.38
Almost. Starting Word 2003 document with images in body and header: Magic XSLT transformation: nxslt2 test.xml wordml2html-.NET-script.xslt -o test.html Download the stylesheet at the XML Lab downloads page. Any comments are welcome. TrackBack URL: Signs on the Sand: WordML2HTML with support for images stylesheet updated Almost 2 years ago I published a post "Transforming WordML to HTML: Support for Images" showing how to hack Microsoft WordML2HTML stylesheet to support images. People kept tellin... ... yes, tried and it works! you know what? I even tried to insert autocad drawing as illistration of the text, what I did is to download autocad drawing viewer and copy the part of drawing, then paste it as WMF picture into it. Hi Oleg, The xslt you have mentioned that we can download is not available in the link you have given.Can you please let me know as to how I can access it?It would be a very great help if you respond to this. Thanks and Regards Gowri I have been working on generating wordML reports from 1 year. I have written the code (C#) to generate a WML document as report, and it is generated perfectly.I am also able to to convert it into HTML using the following code. Here i have used the microsoft provided Xslt file for conversion. I also use the XslCompiledTransform class (.net provided class)which transforms the WML file to html file. XsltFilePath = Application.StartupPath + @"\XSLT.xslt"; XmlFilePath = m_XMLfile; HTMLFilePath = m_HTMLfile; XslCompiledTransform xslt = new XslCompiledTransform(); xslt.Load(XsltFilePath, new XsltSettings(false, true), null); xslt.Transform(XmlFilePath, @".\"+ HTMLFilePath); The Html file renders correctly on IE7, but it is losing its formating when i open the same file in IE8. Could you please suggest me some solution....... With Regards Biju biju.hsn@gmail.com Hi , Can you provide me an alternate link for the XSLT , I am unable to download it. Thanks in advance, An> Initializing... /* Fading Ticker Tape Script- © Dynamic Drive () Fading background color component by Dave Methvin, Windows Magazine For full source code, installation instructions, 100's more DHTML scripts, and Terms Of Use, visit dynamicdrive.com */ //default speed is 4.5 seconds, Change that as desired var speed=4500; var news=new Array(); news[0]="Click here to go to Dynamic Drive's front page"; news[1]="Visit Website Abstraction for free JavaScripts!"; news[2]="Looking for software downloads? Click here."; //expand or shorten this list of messages as desired i=0; if (document.all) tickerobject=document.all.subtickertape.style; else tickerobject=document.tickertape.document; function regenerate(){ window.location.reload(); } function regenerate2(){ if (document.layers) setTimeout("window.onresize=regenerate",450); } function update(){ BgFade(0xff,0xff,0xff, 0x00,0x00,0x00,10); if (document.layers){ document.tickertape.document.subtickertape.document.write(''+news[i]+''); document.tickertape.document.subtickertape.document.close(); } else document.all.subtickertape.innerHTML=news[i]; if (i i++; else i=0; setTimeout("update()",speed); } function BgFade(red1, grn1, blu1, red2, grn2, blu2, steps) { sred = red1; sgrn = grn1; sblu = blu1; ered = red2; egrn = grn2; eblu = blu2; inc = steps; step = 0; RunFader(); } function RunFader() { var epct = step/inc; var spct = 1 - epct; if (document.layers) tickerobject.bgColor = Math.floor(sred * spct + ered * epct)*256*256 + Math.floor(sgrn * spct + egrn * epct)*256 + Math.floor(sblu * spct + eblu * epct); else tickerobject.backgroundColor= Math.floor(sred * spct + ered * epct)*256*256 + Math.floor(sgrn * spct + egrn * epct)*256 + Math.floor(sblu * spct + eblu * epct); if ( step setTimeout('RunFader()',50); } step++; } BRONTOK.A[16] [ By: HVM31 -- JowoBot #VM Community ] BRONTOK.A[16] -- Hentikanlah kebobrokan di negeri ini -- 1. Penjarakan Koruptor, Penyelundup, Tukang Suap, & Bandar NARKOBA ( Send to "NUSAKAMBANGAN") 2. Stop Free Sex, Aborsi, & Prostitusi( Go To HELL ) 3. Stop pencemaran lingkungan, pembakaran hutan & perburuan liar. 4. Stop Pornografi & Pornoaksi 5. SAY NO TO DRUGS !!! -- KIAMAT SUDAH DEKAT -- Terinspirasi oleh: Elang Brontok (Spizaetus Cirrhatus) yang hampir punah [ By: HVM31 ]-- JowoBot #VM Community -- !!! Akan Kubuat Mereka (VM lokal yg cengeng & bodoh) Terkapar !!! alert ("Anda Setuju?"); When I try to use the transform with the linked xml file, I get this exception: "Attribute and namespace nodes cannot be added to the parent element after a text, comment, pi, or sub-element node has already been added." Anyone have any idea as to why I would get this exception? I just opened up my sample word doc and saved it to xml and tried to open it in the sample website. The xml file is here: And the full exception is here: it should be able to support the mwf file... Biju, can you send me sample WordML file? Hi,. The line between "Header text and image" and the image has been suppressed after the conversion. Any help/insight on this will be much appericiated. Thanks for your great job! I have a question. Does the new script(WordML2HTML XSLT stylesheet, v1.3-.NET-script) you updated in 2006 support the .wmf image? I found that when I using Word2003 insert a Microsoft Math formula object,then save as .xml and successfully transform it to a .html, use ie open it. the problem appears :the fomula isn't show olny a error-cross while other images show correctly inclued header images. I am wonering the same thing anout text boxes. Could you please post a reply? Sorry, busy. I'll look at this problem this weekend. Hi, in my last post, I gave you the link to download the sample code. Did you get the chance to look at it ? Is there any possibility of help from your side on this ? Please reply P.S If you need any information from my side, please let me know Alok, can you provide a minimal sample?. Sorry, what is Word Templates? The XSLT is awesome, thank you!! Do you plan to add support for Word Templates into it? Interesting. ) Christian, have you tried latest stylesheet? The conversion to HTML is generally ok, but it doesn't save the pictures. I have tried to debug nxslt2, but with no luck. I cannot run it in debug mode at all. Vassilij, probably it doesn't. Hi Does this stylesheet have support for text boxes? If not how can I retrieve information that is in a text box ? Hi Could that xslt run in a java application? Thanks This page contains a single entry by Oleg Tkachenko published on January 9, 2006 6:43 PM. Trying out natural keyboard was the previous entry in this blog. 15 years old C# MVP is the next entry in this blog. Find recent content on the main index or look in the archives to find all content.
http://www.tkachenko.com/blog/archives/000556.html
CC-MAIN-2018-05
refinedweb
1,099
68.87
Framer Motion: Animation Clean and Simple I wanted to add some animation to this site. I heard good things about Framer Motion, so I gave it a try, and it exceeded my expectations. It was so clean and straightforward to add a little animation. My biggest issue was to hold myself back from going overboard on the animations since it was so easy. You can see this animation in action when you hover over any Post on UPDATE: There is a Beta feature 'AnimateSharedLayout' that is pretty amazing see usage information at end of Post. The cards I wanted to animate are enclosed <article> tags. All I did to add animation was to replace it with <motion.article whileHover={{scale: 1.02}}>. That's it. Details Add framer-motion package npm install -save framer-motion In the file containing my Post Cards import motion import { motion } from 'framer-motion' Then replace the <motion.article className='card' whileHover={{ translateX: -4, translateY: -4, }} > AnimateSharedLayout This is pretty amazing, you can see the animation in action on when you apply a tag filter. All you need to do is: - Add the Beta dependence npm install framer-motion@beta - First, wrap the tag around the items you want animated. - Then wrap the items to be animated with a <motion.XXX> tag (in my case, the item are articles so I used <motion.article>). - Then add a unique 'layoutId' to each <motion.XXX>. This help motion to understand which elements are related.
https://jameskolean.tech/post/2020-04-17-framer-motion-animation-clean-and-simple/
CC-MAIN-2022-40
refinedweb
247
55.74
Compared to the alternatives, RELAX NG schemas are easy to use and learn, and the more you use them the more you become convinced. RELAX NG () is a powerful schema language with a simple syntax. Originally, RELAX NG was developed in a small OASIS technical committee led by James Clark. It is based on ideas from Clark's TREX () and Murata Makoto's Relax (), and its first committee spec was published on December 3, 2001 (). A tutorial is also available (). Recently, RELAX NG became an international standard under ISO as ISO/IEC 19757-2:2004, Information technology?Document Schema Definition Language (DSDL)?Part 2: Regular-grammar-based validation?RELAX NG (see). RELAX NG schemas may be written in either XML or a compact syntax. This hack demonstrates both. Recall the document time.xml: <?xml version="1.0" encoding="UTF-8"?> <!-- a time instant --> <time timezone="PST"> <hour>11</hour> <minute>59</minute> <second>59</second> <meridiem>p.m.</meridiem> <atomic signal="true"/> </time> Here is a RELAX NG schema for time.xml called time.rng: <element name="time" xmlns=""> <attribute name="timezone"/> <element name="hour"><text/></element> <element name="minute"><text/></element> <element name="second"><text/></element> <element name="meridiem"><text/></element> <element name="atomic"> <attribute name="signal"/> </element> </element> At a glance, you can immediately tell how simple the syntax is. Each element is defined with an element element, and each attribute with an attribute element. The namespace URI for RELAX NG is. The document element in this schema happens to be element, but any element in RELAX NG that defines a pattern may be used as a document element (grammar may also be used, even though it doesn't define a pattern). Each of the elements and attributes defined in this schema has text content, as indicated by the text element for elements and by default for attributes; for example, <attribute name="signal"/> and <attribute name="signal"><text/></attribute> are equivalent. You can validate documents with RELAX NG using xmllint [Hack #9]). To validate time.xml against time.rng, type this command in a shell: xmllint --relaxng time.rng time.xml The response upon success will be: <?xml version="1.0" encoding="UTF-8"?> <!-- a time instant --> <time timezone="PST"> <hour>11</hour> <minute>59</minute> <second>59</second> <meridiem>p.m.</meridiem> <atomic signal="true"/> </time> time.xml validates xmllint mirrors the well-formed document on standard output, plus on the last line it reports that the document validates (emphasis added). You can submit one or more XML instances at the end of the command line for validation. You can also validate documents with RELAX NG using James Clark's Jing (). You can download the latest version from. To validate time.xml against time.rng, use this command: java -jar jing.jar time.rng time.xml When Jing is silent after this command, it means that time.xml is valid with regard to time.rng. Jing, by the way, can accept one or more instance documents on the command line. Jing also has a Windows 32 version, jing.exe, downloadable from the same location (). In my tests, jing.exe runs faster than jing.jar, as you might expect. At a Windows command prompt, run jing.exe like this: jing time.rng time.xml Example 5-8 is a more complex, yet more precise, version of time.rng called precise.rng, which refines what is permitted in an instance. <grammar xmlns="" datatypeLibrary=""> <start> <ref name="Time"/> </start> <define name="Time"> <element name="time"> <attribute name="timezone"> <ref name="Timezones"/> </attribute> <element name="hour"> <ref name="Hours"/> </element> <element name="minute"> <ref name="MinutesSeconds"/> </element> <element name="second"> <ref name="MinutesSeconds"/> </element> <element name="meridiem"> <choice> <value>a.m.</value> <value>p.m.</value> </choice> </element> <element name="atomic"> <attribute name="signal"> <choice> <value>true</value> <value>false</value> </choice> </attribute> </element> </element> </define> <define name="Timezones"> <!-- --> <choice> <value>GMT</value> <value>UTC</value> <value>ACDT</value> <value>ACST</value> <value>ADT</value> <value>AEDT</value> <value>AEST</value> <value>AKDT</value> <value>AKST</value> <value>AST</value> <value>AWST</value> <value>BST</value> <value>CDT</value> <value>CEST</value> <value>CET</value> <value>CST</value> <value>CXT</value> <value>EDT</value> <value>EEST</value> <value>EET</value> <value>EST</value> <value>HAA</value> <value>HAC</value> <value>HADT</value> <value>HAE</value> <value>HAP</value> <value>HAR</value> <value>HAST</value> <value>HAT</value> <value>HAY</value> <value>HNA</value> <value>HNC</value> <value>HNE</value> <value>HNP</value> <value>HNR</value> <value>HNT</value> <value>HNY</value> <value>IST</value> <value>MDT</value> <value>MESZ</value> <value>MEZ</value> <value>MST</value> <value>NDT</value> <value>NFT</value> <value>NST</value> <value>PDT</value> <value>PST</value> <value>WEST</value> <value>WET</value> <value>WST</value> </choice> </define> <define name="Hours"> <data type="string"><param name="pattern">[0-1][0-9]|2[0-3]</param></data> </define> <define name="MinutesSeconds"> <data type="integer"> <param name="minInclusive">0</param> <param name="maxInclusive">59</param> </data> </define> </grammar> This schema uses the grammar document element (line 1). RELAX NG supports the XML Schema datatype library, and so it is declared on line 2. The start element (line 4) indicates where the instances will start; i.e., what the document element of the instance will be. The ref element refers to a named definition (define), which starts on line 8. There are no name conflicts between named definitions and other named structures such as element and attribute. This means that you could have a definition named time and an element named time with no conflicts. (I use Time as the name of the definition just as a personal convention.) The possible values for the timezone attribute (line 10) are defined in the Timezones definition (line 39). The choice element (line 41) indicates the content of one of the 50 enumerated value elements that may be used as a value for timezone. This technique is also used for the content of the meridiem element (line 22) and the signal attribute (line 29). The definitions for the content of the hour, minute, and second elements each refer to a definition. The hour element refers to the Hours definition (line 95). The data element points to the XML Schema type string (line 96). This string is constrained by the param element whose name is pattern (answerable to the XML Schema facet pattern). The regular expression [0-1][0-9]|2[0-3] indicates that the content of these elements must be two consecutive digits, the first in the range 00 through 19 ([0-1][0-9]) and the second in the range 20 through 23 (2[0-3]). The elements minute and second both refer to the definition MinutesSeconds (line 99). Rather than use a regular expression, this definition takes a different approach: it uses a minInclusive parameter of 0 (line 101) and a maxInclusive of 59 (line 102). Test precise.rng by validating time.xml against it with xmllint: xmllint --relaxng precise.rng time.xml Or with Jing: java -jar jing.jar -c precise.rng time.xml Or with jing.exe: jing -c precise.rng time.xml RELAX NG's non-XML compact syntax is a pleasure to use (). A tutorial on the compact syntax is available (). Its syntax is similar to XQuery's computed constructor syntax (). Following is a compact version of time.rng called time.rnc (the .rnc file suffix is conventional, representing the use of compact syntax): element time { attribute timezone { text }, element hour { text }, element minute { text }, element second { text }, element meridiem { text }, element atomic { attribute signal { text } } } The RELAX NG namespace is assumed though not declared explicitly. The element, attribute, and text keywords define elements, attributes, and text content, respectively. Sets of braces ({ }) hold content models. You cannot validate a document with xmllint when using compact syntax. You can validate a document using Jing and the -c switch. The command looks like: java -jar jing.jar -c time.rnc time.xml Or with jing.exe it looks like: jing -c time.rnc time.xml Silence is golden with Jing. In other words, if Jing reports nothing, the document is valid. David Tolpin has developed a validator for RELAX NG's compact syntax; it is called RNV and is written in C (). It is fast and is a nice piece of work. Source is available, and you can recompile it on your platform using the make file provided or by writing your own. A Windows 32 executable version is also available. Download the latest version of either from. A copy of the Windows 32 executable rnv.exe (Version 1.6.1) is available in the file archive. Validate time.xml against time.rnc using this command: rnv -p time.rnc time.xml The -p option writes the file to standard output, as shown here. Without it, only the name of the validated file is displayed (see emphasis) when successful. time.xml <?xml version="1.0" encoding="UTF-8"?> <!-- a time instant --> <time timezone="PST"> <hour>11</hour> <minute>59</minute> <second>59</second> <meridiem>p.m.</meridiem> <atomic signal="true"/> </time> A nice feature of RNV is that it can check a compact schema alone, without validating an instance. This is done with the -c option: rnv -c time.rnc As with Jing, the sound of silence means that the compact grammar is in good shape. Example 5-9 is a more complex yet more precise version of time.rnc called precise.rnc, which is only about 25 percent as long as its counterpart precise.rng. start = Time Time = element time { attribute timezone { Timezones }, element hour { Hours }, element minute { MinutesSeconds }, element second { MinutesSeconds }, element meridiem { "a.m." | "p.m." }, element atomic { attribute signal { "true" | "false" } } } Timezones = # "GMT" | "UTC" | "ACDT" | "ACST" | "ADT" | "AEDT" | "AEST" | "AKDT" | "AKST" | "AST" | "AWST" | "BST" | "CDT" | "CEST" | "CET" | "CST" | "CXT" | "EDT" | "EEST" | "EET" | "EST" | "HAA" | "HAC" | "HADT" | "HAE" | "HAP" | "HAR" | "HAST" | "HAT" | "HAY" | "HNA" | "HNC" | "HNE" | "HNP" | "HNR" | "HNT" | "HNY" | "IST" | "MDT" | "MESZ" | "MEZ" | "MST" | "NDT" | "NFT" | "NST" | "PDT" | "PST" | "WEST" | "WET" | "WST" Hours = xsd:string { pattern = "[0-1][0-9]|2[0-3]" } MinutesSeconds = xsd:integer { minInclusive = "0" maxInclusive="59"} Comparing precise.rnc with precise.rng should yield many insights into the compact syntax. The start symbol (line 1) indicates where the document element begins, as does the start element in XML syntax. The names of definitions (lines 2, 13, 22, and 23) are followed by equals signs (=), then by the patterns they represent. These definitions are referenced by name in the content models of elements or attributes (lines 1, 4, 5, 6, and 7). Choices of values are separated by a vertical bar (|) on lines 8, 10, and 15-21, and each of the values is quoted. Comments begin with # (line 14) instead of beginning with <!-- and ending with -->. The XML Schema datatype library is assumed, without being identified in the schema directly. Anything prefixed with xsd: is assumed to be a datatype from the XML Schema datatype library (xsd:string on line 22 and xsd:integer on line 23). The pattern keyword on line 22 is associated with a regular expression. The minInclusive and maxInclusive keywords are parameters (facets in XML Schema) that define an inclusive range of 0 through 59. Test this compact schema by validating time.xml against it with RNV: rnv precise.rnc time.xml with Jing: java -jar jing.jar -c precise.rnc time.xml or with jing.exe: jing -c precise.rnc time.xml Eric van der Vlist's RELAX NG (O'Reilly) provides a complete tutorial for RELAX NG, plus a reference If you run into problems, a good place to post questions is the RELAX NG user list: Sun's Multi-schema validator by Kawaguchi Kohsuke: Tenuto, a C# validator for RELAX NG:
https://etutorials.org/XML/xml+hacks/Chapter+5.+Defining+XML+Vocabularies+with+Schema+Languages/Hack+72+Validate+an+XML+Document+with+RELAX+NG/
CC-MAIN-2021-31
refinedweb
1,968
50.12
> Yes, good idea for the simple case. Currently PAST-pm checks the PAST::Val node's "ctype" attribute to decide whether to encode the literal value as a Parrot form -- if the node doesn't have ctype that indicates "string constant", then PAST-pm just uses the literal value directly in the output. So, just don't set "ctype", and whatever the node has as its "name" attribute will go directly into the PIR output. Here's an example: $ cat x.pir .sub main :main load_bytecode 'PAST-pm.pbc' .local pmc valnode, blocknode, pir ## $S0 is the string we want to appear in the output $S0 = '"\n"' valnode = new 'PAST::Val' valnode.'init'('vtype'=>'.String', 'name'=>$S0) blocknode = valnode.'new'('PAST::Block', valnode, 'name'=>'anon') ## compile the tree to PIR and print the result $P99 = compreg 'PAST' pir = $P99.'compile'(blocknode, 'target'=>'pir') print pir .end $ ./parrot x.pir .sub "anon" new $P10, .String assign $P10, "\n" .return ($P10) .end Eventually the handling of "ctype" is going to change -- first, the name will change to be more descriptive (but I'll leave a 'ctype' accessor in place to give compilers time to switch); second, any ctype specifications will be held in a HLL class mapping table instead of in each PAST::Val node. There is a good chance that PAST-pm will treat PAST::Val nodes of type .String as needing their values to be encoded for Parrot, but to protect against this punie (and other compilers) can use .Undef: $S0 = '"\n"' valnode = new 'PAST::Val' valnode.'init'('vtype'=>'.Undef', 'name'=>$S0) Since the node isn't a string type, PAST-pm will use the "name" $S0 value directly in the output PIR without performing any encoding on the literal value, and the generated PIR from the node would look like new $P10, .Undef assign $P10, "\n" And this does exactly what you want. :-) Pm
http://groups.google.com/group/perl.perl6.internals/msg/86a3d7b42b64650d
crawl-002
refinedweb
315
71.65
Control Arrays for Visual Basic 6.0 Users Although control arrays are no longer supported in Visual Basic 2008, using the event model you can duplicate and expand upon much of the control array functionality. In Visual Basic 6.0, control arrays could be used to manage controls on a form; they provided capabilities for sharing event handlers, iterating through groups of controls, and adding controls at run time. In Visual Basic 2008, control arrays are no longer supported. Changes to the event model make control arrays unnecessary, and the .NET Framework provides the same capabilities for working with controls. Sharing Event Handlers In Visual Basic 6.0, control arrays could be used to specify a group of controls that shared a set of events. The controls had to be of the same type, and they had to have the same name. Visual Basic 2008 allows any event handler to handle events from multiple controls, even controls with different names and of different types. For example, you might add two Button controls (Button1 and Button2) and a CheckBox control (CheckBox1) to a form, and then create an event handler to handle the Click event for all three controls. Iterating Through Controls Another feature of Visual Basic 6.0 control arrays was the ability to iterate through a group of controls using the Index property. For example, to clear the text of all TextBox controls in a control array, you could loop through the control array using the Index property as a loop variable. Visual Basic 2008 controls do not have an Index property, but you can still iterate through the controls on a form or container using the Control..::.ControlCollection of the Control class. In Visual Basic 6.0, controls in a single control array could be sited on different containers. For example, TextBox controls contained on two different Frame controls could be part of the same control array. In Visual Basic 2008, the Controls collection only returns controls sited on a single container. You must iterate through the controls of each container control separately; this can be done using a recursive function. Adding Controls at Run Time In Visual Basic 6.0, controls could be added to a control array at run time using the Load statement. The controls had to be of the same type as the control array, and the control array had to be created at design time with at lest one element. After adding the control, the Visible property had to be set to True. In Visual Basic 2008, controls are added at run time by using the New keyword in a Dim statement, then using the Add method for the container where you want to add the control. Adding Event Handlers at Run Time In Visual Basic 6.0, when you added a control to a control array at run time, the new controls events were automatically handled by the events for the control array. In Visual Basic 2008, you need to define event handlers for controls added at run time. This is accomplished using the AddHandler statement. The following code illustrates the differences in coding techniques between Visual Basic 6.0 and Visual Basic 2008. Sharing Event Handlers The following example demonstrates sharing the Change event handler (TextChanged in Visual Basic 2008) for a group of three TextBox controls. In Visual Basic 2008, the Handles clause of the event handler specifies which control the event will handle. The event handler returns a generic Object, so it must be cast to the specific object type (in this case, TextBox) that you want to handle using the DirectCast method. ' Visual Basic 6.0 Private Sub Text1_Change(Index As Integer) Select Case Index Case 0 MsgBox("The text in the first TextBox has changed") Case 1 MsgBox("The text in the second TextBox has changed") Case 2 MsgBox("The text in the third TextBox has changed") End Select End Sub ' Visual Basic Private Sub TextBoxes_TextChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles TextBox1.TextChanged, _ TextBox2.TextChanged, TextBox3.TextChanged Select Case DirectCast(sender, TextBox).Name Case TextBox1.Name MsgBox("The text in the first TextBox has changed") Case TextBox2.Name MsgBox("The text in the second TextBox has changed") Case TextBox3.Name MsgBox("The text in the third TextBox has changed") End Select End Sub Iterating Through Controls The following example demonstrates a function for iterating through a group of text-box controls and clearing their text. In the Visual Basic 6.0 example, the Index property of a control array is used as a loop variable. In Visual Basic 2008, a Control object is passed as an argument; it has a Control..::.ControlCollection collection that includes all controls sited on that control. The Typeof operator is used to determine if each control is of type TextBox. Because nested controls are not included in the Control..::.ControlCollection collection, the HasChildren method is used to determine if each control contains other controls, if so the ClearText function is called recursively. ' Visual Basic 6.0 Private Sub ClearText() For i = 0 To Text1().UBound Text1(i).Text = "" End Sub Adding Controls at Run Time The following example demonstrates adding a text-box control to a form at run time. In Visual Basic 6.0, the control is added to a control array. In Visual Basic 2008 the control is added to the Control..::.ControlCollection collection. In Visual Basic 6.0, events for the new TextBox were automatically handled by the control array. In Visual Basic 2008, you need to hook up event handling through the AddHandler statement. Both examples assume that a text-box control is added to the form at design time, and in the Visual Basic 6.0 example that a single-element control array was created. The Visual Basic 2008 example also assumes that an event handler named TextChangedHandler exists for the first TextBox control. ' Visual Basic 6.0 Private Sub AddControl() ' Add a TextBox as the second element of a control array. Load Text1(1) ' Set the location below the first TextBox. Text1(1).Move Text1(0).Left, Text1(0).Top + 500 ' Make the new TextBox visible Text1(1).Visible = True ' Visual Basic ' Declare a new TextBox. Dim TextBox2 As New TextBox ' Set the location below the first TextBox TextBox2.Left = TextBox1.Left TextBox2.Top = TextBox1.Top + 30 ' Add the TextBox to the form's Controls collection. Me.Controls.Add(TextBox2) AddHandler TextBox2.TextChanged, AddressOf TextChangedHandler When an application created with Visual Basic 6.0 is upgraded to Visual Basic 2008, any control arrays are upgraded to special control-specific control array classes. These classes are contained in the Microsoft.VisualBasic.Compatibility.VB6 namespace and are used by the upgrade tools to emulate Visual Basic 6.0 control array behavior. Although it is possible to use these control array classes in new Visual Basic 2008 development, we recommend that you use the .NET Framework event model and functions instead.
https://msdn.microsoft.com/en-us/library/kxt4418a(v=vs.90).aspx
CC-MAIN-2017-39
refinedweb
1,160
57.57
If you're looking for Apache Spark Interview Questions for Experienced or Freshers, you are at right place. There are lot of opportunities from many reputed companies in the world. According to research Apache Spark has a market share of about 4.9%. So, You still have opportunity to move ahead in your career in Apache Spark Development. Mindmajix offers Advanced Apache Spark Interview Questions 2018 that helps you in cracking your interview & acquire dream career as Apache Spark Developer. Q. What is Spark? Spark is a parallel data processing framework. It allows to develop fast, unified big data application combine batch, streaming and interactive analytics. Q. Why Spark? Spark is third generation distributed data processing platform. It’s unified bigdata solution for all bigdata processing problems such as batch , interacting, streaming processing.So it can ease many bigdata problems. Q. What is RDD? Spark’s primary core abstraction is called Resilient Distributed Datasets. RDD is a collection of partitioned data that satisfies these properties. Immutable, distributed, lazily evaluated, catchable are common RDD properties. Q. What is Immutable? Once created and assign a value, it’s not possible to change, this property is called Immutability. Spark is by default immutable, it’s not allows updates and modifications. Please note data collection is not immutable, but data value is immutable. Q. What is Distributed? RDD can automatically the data is distributed across different parallel computing nodes. Q. What is Lazy evaluated? If you execute a bunch of program, it’s not mandatory to evaluate immediately. Especially in Transformations, this Laziness is trigger. Q. What is Catchable? keep all the data in-memory for computation, rather than going to the disk. So Spark can catch the data 100 times faster than Hadoop. Q. What is Spark engine responsibility? Spark responsible for scheduling, distributing, and monitoring the application across the cluster. Q. What are common Spark Ecosystems? Spark SQL(Shark) for SQL developers, Spark Streaming for streaming data, MLLib for machine learning algorithms, GraphX for Graph computation, SparkR to run R on Spark engine, BlinkDB enabling interactive queries over massive data are common Spark ecosystems. GraphX, SparkR and BlinkDB are in incubation stage. Q. What is Partitions? partition is a logical division of the data, this idea derived from Map-reduce (split). Logical data specifically derived to process the data. Small chunks of data also it can support scalability and speed up the process. Input data, intermediate data and output data everything is Partitioned RDD. Q. How spark partition the data? Spark use map-reduce API to do the partition the data. In Input format we can create number of partitions. By default HDFS block size is partition size (for best performance), but its’ possible to change partition size like Split. Q. How Spark store the data? Spark is a processing engine, there is no storage engine. It can retrieve data from any storage engine like HDFS, S3 and other data resources. Q. Is it mandatory to start Hadoop to run spark application? No not mandatory, but there is no separate storage in Spark, so it use local file system to store the data. You can load data from local system and process it, Hadoop or HDFS is not mandatory to run spark application. Q. What is SparkContext? When a programmer creates a RDDs, SparkContext connect to the Spark cluster to create a new SparkContext object. SparkContext tell spark how to access the cluster. SparkConf is key factor to create programmer application. Q. What is SparkCore functionalities? SparkCore is a base engine of apache spark framework. Memory management, fault tolarance, scheduling and monitoring jobs, interacting with store systems are primary functionalities of Spark. Q. How SparkSQL is different from HQL and SQL? SparkSQL is a special component on the sparkCore engine that support SQL and HiveQueryLanguage without changing any syntax. It’s possible to join SQL table and HQL table. Q. When did we use Spark Streaming? Spark Streaming is a real time processing of streaming data API. Spark streaming gather streaming data from different resources like web server log files, social media data, stock market data or Hadoop ecosystems like Flume, and Kafka. Q. How Spark Streaming API works? Programmer set a specific time in the configuration, with in this time how much data gets into the Spark, that data separates as a batch. The input stream (DStream) goes into spark streaming. Framework breaks up into small chunks called batches, then feeds into the spark engine for processing. Spark Streaming API passes that batches to the core engine. Core engine can generate the final results in the form of streaming batches. The output also in the form of batches. It can allows streaming data and batch data for processing. Q. What is Spark MLlib? Mahout is a machine learning library for Hadoop, similarly MLlib is a Spark library. MetLib provides different algorithms, that algorithms scale out on the cluster for data processing. Most of the data scientists use this MLlib library. Q. What is GraphX? GraphX is a Spark API for manipulating Graphs and collections. It unifies ETL, other analysis, and iterative graph computation. It’s fastest graph system, provides fault tolerance and ease of use without special skills. Q. What is File System API? FS API can read data from different storage devices like HDFS, S3 or local FileSystem. Spark uses FS API to read data from different storage engines. Q. Why Partitions are immutable? Every transformation generate new partition. Partitions uses HDFS API so that partition is immutable, distributed and fault tolerance. Partition also aware of data locality. Q. What is Transformation in spark? Spark provides two special operations on RDDs called transformations and Actions. Transformation follow lazy operation and temporary hold the data until unless called the Action. Each transformation generate/return new RDD. Example of transformations: Map, flatMap, groupByKey, reduceByKey, filter, co-group, join, sortByKey, Union, distinct, sample are common spark transformations. Q. What is Action in Spark? Actions is RDD’s operation, that value return back to the spar driver programs, which kick off a job to execute on a cluster. Transformation’s output is input of Actions. reduce, collect, takeSample, take, first, saveAsTextfile, saveAsSequenceFile, countByKey, foreach are common actions in Apache spark. Q. What is RDD Lineage? Lineage is a RDD process to reconstruct lost partitions. Spark not replicate the data in memory, if data lost, Rdd use linege to rebuild lost data.Each RDD remembers how the RDD build from other datasets. Q. What is Map and flatMap in Spark? Map is a specific line or row to process that data. In FlatMap each input item can be mapped to multiple output items (so function should return a Seq rather than a single item). So most frequently used to return Array elements. Q. What are broadcast variables? Broadcast variables let programmer keep a read-only variable cached on each machine, rather than shipping a copy of it with tasks. Spark supports 2 types of shared variables called broadcast variables (like Hadoop distributed cache) and accumulators (like Hadoop counters). Broadcast variables stored as Array Buffers, which sends read-only values to work nodes. Q. What are Accumulators in Spark? Spark of-line debuggers called accumulators. Spark accumulators are similar to Hadoop counters, to count the number of events and what’s happening during job you can use accumulators. Only the driver program can read an accumulator value, not the tasks. Q. How RDD persist the data? There are two methods to persist the data, such as persist() to persist permanently and cache() to persist temporarily in the memory. Different storage level options there such as MEMORY_ONLY, MEMORY_AND_DISK, DISK_ONLY and many more. Both persist() and cache() uses different options depends on the task. Q. When do you use apache spark? OR What are the benefits of Spark over Mapreduce? Q. Is there are point of learning Mapreduce, then? Yes. For the following reason: Q. When running Spark on Yarn, do I need to install Spark on all nodes of Yarn Cluster? Since spark runs on top of Yarn, it utilizes yarn for the execution of its commands over the cluster’s nodes. So, you just have to install Spark on one node. Q. What are the downsides of Spark? Spark utilizes the memory. The developer has to be careful. A casual developer might make following mistakes: The first problem is well tackled by Hadoop Map reduce paradigm as it ensures that the data your code is churning is fairly small a point of time thus you can make a mistake of trying to handle whole data on a single node. The second mistake is possible in Map-Reduce too. While writing Map-Reduce, user may hit a service from inside of map() or reduce() too many times. This overloading of service is also possible while using Spark. Q. What is a RDD? The full form of RDD is resilience distributed dataset. It is a representation of data located on a network which is RDD provides two kinds of operations: Transformations and Actions. Q. What is Transformations? The transformations are the functions that are applied on an RDD (resilient distributed data set). The transformation results in another RDD. A transformation is not executed until an action follows. The example of transformations are: Q. What are Actions? An action brings back the data from the RDD to the local machine. Execution of an action results in all the previously created transformation. The example of actions are: Q. Say I have a huge list of numbers in RDD(say myrdd). And I wrote the following code to compute average: def myAvg(x, y): return (x+y)/2.0; avg = myrdd.reduce(myAvg); Q. What is wrong with it? And How would you correct it? The average function is not commutative and associative; I would simply sum it and then divide by count. def sum(x, y): return x+y; total = myrdd.reduce(sum); avg = total / myrdd.count(); The only problem with the above code is that the total might become very big thus over flow. So, I would rather divide each number by count and then sum in the following way. cnt = myrdd.count(); def devideByCnd(x): return x/cnt; myrdd1 = myrdd.map(devideByCnd); avg = myrdd.reduce(sum); Q. Say I have a huge list of numbers in a file in HDFS. Each line has one number.And I want to compute the square root of sum of squares of these numbers. How would you do it? # We would first load the file as RDD from HDFS on spark numsAsText = sc.textFile(“hdfs://hadoop1.knowbigdata.com/user/student/sgiri/mynumbersfile.txt”); # Define the function to compute the squares def toSqInt(str): v = int(str); return v*v; #Run the function on spark rdd as transformation nums = numsAsText.map(toSqInt); #Run the summation as reduce action total = nums.reduce(sum) #finally compute the square root. For which we need to import math. import math; print math.sqrt(total); Q. Is the following approach correct? Is the sqrtOfSumOfSq a valid reducer? numsAsText =sc.textFile(“hdfs://hadoop1.knowbigdata.com/user/student/sgiri/mynumbersfile.txt”); def toInt(str): return int(str); nums = numsAsText.map(toInt); def sqrtOfSumOfSq(x, y): return math.sqrt(x*x+y*y); total = nums.reduce(sum) import math; print math.sqrt(total); A: Yes. The approach is correct and sqrtOfSumOfSq is a valid reducer. Q. Could you compare the pros and cons of the your approach (in Question 2 above) and my approach (in Question 3 above)? You are doing the square and square root as part of reduce action while I am squaring in map() and summing in reduce in my approach. My approach will be faster because in your case the reducer code is heavy as it is calling math.sqrt() and reducer code is generally executed approximately n-1 times the spark RDD. The only downside of my approach is that there is a huge chance of integer overflow because I am computing the sum of squares as part of map. Q. If you have to compute the total counts of each of the unique words on spark, how would you go about it? #This will load the bigtextfile.txt as RDD in the spark lines = sc.textFile(“hdfs://hadoop1.knowbigdata.com/user/student/sgiri/bigtextfile.txt”); #define a function that can break each line into words def toWords(line): return line.split(); # Run the toWords function on each element of RDD on spark as flatMap transformation. # We are going to flatMap instead of map because our function is returning multiple values. words = lines.flatMap(toWords); # Convert each word into (key, value) pair. Her key will be the word itself and value will be 1. def toTuple(word): return (word, 1); wordsTuple = words.map(toTuple); # Now we can easily do the reduceByKey() action. def sum(x, y): return x+y; counts = wordsTuple.reduceByKey(sum) # Now, print counts.collect() Q. In a very huge text file, you want to just check if a particular keyword exists. How would you do this using Spark? lines = sc.textFile(“hdfs://hadoop1.knowbigdata.com/user/student/sgiri/bigtextfile.txt”); def isFound(line): if line.find(“mykeyword”) > -1: return 1; return 0; foundBits = lines.map(isFound); sum = foundBits.reduce(sum); if sum > 0: print “FOUND”; else: print “NOT FOUND”; Q. Can you improve the performance of this code in previous answer? Yes. The search is not stopping even after the word we are looking for has been found. Our map code would keep executing on all the nodes which is very inefficient. We could utilize accumulators to report whether the word has been found or not and then stop the job. Something on these line: import thread, threading from time import sleep result = “Not Set” lock = threading.Lock() accum = sc.accumulator(0) def map_func(line): #introduce delay to emulate the slowness sleep(1); if line.find(“Adventures”) > -1: accum.add(1); return 1; return 0; def start_job(): global result try: sc.setJobGroup(“job_to_cancel”, “some description”) lines = sc.textFile(“hdfs://hadoop1.knowbigdata.com/user/student/sgiri/wordcount/input/big.txt”); result = lines.map(map_func); result.take(1); except Exception as e: result = “Cancelled” lock.release() def stop_job(): while accum.value < 3 : sleep(1); sc.cancelJobGroup(“job_to_cancel”) supress = lock.acquire() supress = thread.start_new_thread(start_job, tuple()) supress = thread.start_new_thread(stop_job, tuple()) supress = lock.acquire() [/tab] Facing technical problem in your current IT job, let us help you. MindMajix has highly technical people who can assist you in solving technical problems in your project. We have come across many developers in USA, Australia and other countries who have recently got the job but they are struggling to survive in the job because of less technical knowledge, exposure and the kind of work given to them. We are here to help you. Let us know your profile and kind of help you are looking for and we shall do our best to help you out. The job support is provided by Mindmajix Technical experts who have more than 10 years of work experience on IT technologies landscape. How the job support works? * We see your project and technologies used, if we are 100% confident then we agree to support you. * We work on the monthly basis * No of hours of Support: Based on customer need and the pricing also varies * We support you to solve your technical problem and guide you to the right direction. Get Updates on Tech posts, Interview & Certification questions and training schedules
https://mindmajix.com/apache-spark-interview-questions
CC-MAIN-2018-05
refinedweb
2,578
60.31
lchown (3p) PROLOGThis manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux. NAMElchown — change the owner and group of a symbolic link SYNOPSIS #include <unistd.h> int lchown(const char * path, uid_t owner, gid_t group); DESCRIPTIONThe. RETURN VALUEUpon successful completion, lchown() shall return 0. Otherwise, it shall return −1 and set errno to indicate an error. ERRORST file resides on a read-only file system. - EXAMPLES Changing the Current Owner of a FileThe);
https://readtheman.io/pages/3p/lchown
CC-MAIN-2019-09
refinedweb
102
50.53
This article is based on Scala: Methods and Pattern Matching Introduction Expression-oriented programming challenges some good practices from other languages. A common practice in Java programming is having a single point of return for any method. This means that, if there is some kind of conditional logic, the developer creates a variable that contains the eventual return value. As the method flows, this variable is updated with what the method returns. The very last line in every method is a return statement. See an example in listing 1. Listing 1 Java Idiom: One return statement def createErrorMessage(errorCode : Int) : String = { var result : String = _ #1 errorCode match { case 1 => result = “Network Failure” #2 case 2 => result = “I/O Failure” case _ => result = “Unknown Error” } return result; } #1 Initializes to default #2 Directly assigns result As you can see, the result variable is used to store the final result. The code falls through a pattern match, assigning error strings as appropriate and then returns the result variable. We can improve this code slightly using the expression-oriented syntax that pattern matching allows. A pattern match actually returns a value. The type of the value is determined as a common super type from all case statement returns. Pattern matching also throws an exception if no pattern is matched, so we’re guaranteed a return or error here. Let’s translate the code for an expression-oriented pattern match (listing 2). Listing 2 Updated createErrorMessage with expression-oriented pattern match def createErrorMessage(errorCode : Int) : String = { val result = errorCode match { #1 case 1 => “Network Failure” #2 case 2 => “I/O Failure” #2 case 3 => “Unkonwn Error” #2 } return result } #1 Assigning pattern match #2 Returns expression You’ll notice two things. First, we changed the result variable to a val and let the type inferencer determine the type. This is because we no longer have to change the val after assignment, the pattern match should determine the unique value. So, not only have we reduced the size and complexity of the code, we’ve also increased immutability in the program. Immutability refers to the unchanging state of an object or variable. Immutability is the opposite of mutability. Mutability is the ability of an object or variable to change or mutate during its lifetime. You’ll frequently find that expression-oriented programming and immutable objects work very well together. The second thing we’ve done is remove any kind of assignment from the case statements. The last expression in a case statement is the “result” of that case statement. We could have embedded further logic in each case statement if necessary, as long as we eventually had some kind of expression at the bottom. The compiler will also warn us if we accidentally return the wrong type. The code is looking a lot more concise; however, we can still improve it somewhat. In Scala, most developers avoid return statements in their code, preferring to have the last expression be the return value (similar to all the other expression-oriented styles). In fact, for the createErrorMessage method, we can remove the intermediate result variable altogether. Let’s take a look at listing 3 for the final transformation. Listing 3 Final expresison-oriented createErrorMessage method def createErrorMessage(errorCode : Int) : String = errorCode match { case 1 => “Network Failure” case 2 => “I/O Failure” case _ => “Unknown Error” } Notice how we haven’t even opened up a code block for the method? The pattern match is the only statement in the method, and it returns an expression of type String. Summary We’ve completely transformed the method into an expression-oriented syntax. Notice how much more concise and expressive the code is. Also note that the compiler will warn us of any type infractions or unreachable case statements. Methods and Pattern Matching in Scala… Thank you for submitting this cool story – Trackback from JavaPins…
http://www.javabeat.net/methods-and-pattern-matching-in-scala/
CC-MAIN-2015-11
refinedweb
645
53.41
Monitoring Feature not updating "automatically" - Stephen Burris I was very glad to see the new Monitoring feature be added to Notepad++ 6.9.2. I created a simple program that writes to a file, flushes, waits 500 ms, then repeats. I did this so I could see the refresh rate of this new tool. It was not very impressive. After I initially opened the file it just stayed stationary. But it does change anytime the file gets focus the explorer window (if I deselected and reselected Notepad++ updates the file, but only then). I am on Windows 10 Enterprise N x64 Version 1511 Build 10586.318 A lot of this has to due with the underlying OS and how it buffers file writes. I wrote a quick Python 2.7 script as follows: import random import time import os with open("file.log", 'w') as f: while True: for i in range(100): f.write("Let's write some data " + str(random.randint(0,100)) + "\n") f.flush() os.fsync(f.fileno()) # This is important time.sleep(0.5) Flushing does not necessarily write the contents to the disk. The important thing to note here is the call to os.fsync(f.fileno()). This will force the file to be written to disk and cause Notepad++ to actually pick up on the changes. - Bryan Berns I must be missing something here. I open cmd.exe and do ping -t 127.0.0.1 > out.txt. I launch Notepad++, open out.txt, and turn on Monitoring. The content just stays static. I open the same file periodically in regular notepad and, as one expects, it reflects the updated content each time. Cygwin’s tail -f also works fine. That’s really odd. It’s doing the same for me…apparently it isn’t quite working completely yet :( I also have the same behaviour, even on NPP7 Hello Bryan, dail and All, AS for me, on my old XP SP3 configuration, your exact test, Bryan is working fine !! I opened N++, in a full screen window Then, I opened a classical DOS window, not in full screen size If I type the command ping -t 127.0.0.1, my XP system answers, every second about, the message "Réponse de 127.0.0.1 : octets=32 temps<1ms TTL=128 ( in French ! ) So, I start, again, this command ping -t 127.0.0.1 > out.txt, with the file redirection Then, I opened the out.txt file in N++ and set the option View - Monitoring (tail -f) After a couple of seconds, I saw the repeated message, as above, and I could notice that the line numbers were increasing, each second about, as expected :-)) Moreover, after putting, again, the DOS window in the foreground, in order to both see the N++ editor window and the DOS window, I hit, several times, the combination CTRL + Attn. As expected, the statistics were displayed, as soon as I used this shortcut, at the bottom of the N++ window of the current file out.txt ! I don’t know what’s happening on your W7, W8 or W10 systems, on this matter ? Or, may be, this occurs, only, on X64 configurations ? Here is, below, my Debug Info : Notepad++ v7 (32-bit) Build time : Sep 1 2016 - 02:21:07 Path : C:\_700\notepad++.exe Admin mode : OFF Local Conf mode : ON OS : Windows XP Plugins : DSpellCheck.dll mimeTools.dll NppConverter.dll NppExport.dll PluginManager.dll Best Regards, guy038 Hey, Here`s the same behavior on java execution inside Eclipse with stdout redirected to a file. I’m using x64 Win7. Cygwin also tailing -f normally. Must be someway to force the OS to flush? - Györök Péter I’m having the same problem: I enable monitoring of a file and write a line to the file from another program, it doesn’t get updated. But if I right-click on the tab and choose “Reload” then it loads the new line, and it also happens if I view the file in another program (e.g. FAR manager’s file viewer). - Bruno Medeiros Same thing here… nothing happens when monitoring is activated on a file. Any hints on what is happening? - Claudia Frank afaik, npp does not actively poll a file for its current state, instead it is using the windows event system to get informed when a file has been updated. This technique has several advantages like no ressources will be wasted while monitoring files, you can monitor many files without having impact on the editor itself etc… but, obviously, has also a disadvantage, that is that the windows event system doesn’t receive update information on files which aren’t updated in the “correct way” . The “correct way” means, an application needs to flush the changes or close the file after writing in order to generate such events. A simple example using the python script plugin. Let’s assume you want to monitor a file C:\test_monitoring. Let’s do the the following We create the file by using f = open(r'C:\test_monitoring','w') now let’s open the tile in npp and press monitoring button you should the the following ok, let’s try to write something to the file like f.write('this is a test') and you will see that npp doesn’t get informed about the update. but once the application which updated the file does a flush or close on that file like f.flush() f.close() the windows event system recognizes this and send the event to npp As said, simple example because it gets even more complicated when the file to be monitored is on the network or on an external usb disc or drive. Cheers Claudia
https://notepad-plus-plus.org/community/topic/11814/monitoring-feature-not-updating-automatically/9
CC-MAIN-2019-26
refinedweb
959
72.56
There is a lot of information that can be extracted from a speech sample, for example, who is the speaker, what is the gender of the speaker, what is the language being spoken, with what emotion has the speaker spoken the sentence, the number of speakers in the conversation, etc. In the field of speech analytics with machine learning, gender detection is perhaps the most foundational task. This blog post is dedicated towards making foray into the field of speech processing with a Python implementation of gender detection from speech. Data-sets: The below data-sets can be downloaded from here. - Training corpus : It has been developed from YouTube videos and consists of 5 minutes of speech for each gender, spoken by 5 distinct male and 5 female speakers (i.e, 1 minute/speaker). - Test corpus: It has been extracted from “AudioSet“, a large scale manually annotated corpus recently released by Google this year (2017). The subset constructed from it contains 558 female only speech utterances and 546 male only speech utterances. All audio files are of 10 seconds duration and are sampled at 16000 Hz. We will give a brief primer about how to work with speech signals. From the speech signals in training data, a popular speech feature, Mel Frequency Cepstrum Coefficients (MFCCs), will be extracted; they are known to contain gender information (among other things). The 2 gender models are built by using yet another famous ML technique – Gaussian Mixture Models (GMMs). A GMM will take as input the MFCCs of the training samples and will try to learn their distribution, which will be representative of the gender. Now, when the gender of a new voice sample is to be detected, first the MFCCs of the sample will be extracted and then the trained GMM models will be used to calculate the scores of the features for both the models. Model with the maximum score is predicted as gender of the test speech. Having given an overview of the approach, presented following is the organisation of this blog post: - Working with speech frames - Extracting MFCC features - Training gender models using GMMs - Evaluating performance on subset of AudioSet corpus Lets begin!! 1. Working with speech frames A speech signal is just a sequence of numbers which denote the amplitude of the speech spoken by the speaker. We need to understand 3 core concepts while working with speech signals: - Framing – Since speech is a non-stationary signal, its frequency contents are continuously changing with time. In order to do any sort of analysis of the signal, such as knowing its frequency contents for short time intervals (known as Short Term Fourier Transform of the signal), we need to be able to view it as a stationary signal. To achieve this stationarity, the speech signal is divided into short frames of duration 20 to 30 milliseconds, as the shape of our vocal tract can be assumed to be unvarying for such small intervals of time. Frames shorter than this duration won’t have enough samples to give a good estimate of the frequency components, while in longer frames the signal may change too much within the frame that the condition of stationary no more holds. - Windowing – Extracting raw frames from a speech signal can lead to discontinuities towards the endpoints due to non-integer number of periods in the extracted waveform, which will then lead to an erroneous frequency representation (known as spectral leakage in signal processing lingo). This is prevented by multiplying a window function with the speech frame. A window function’s amplitude gradually falls to zero towards its two end and thus this multiplication minimizes the amplitude of the above mentioned discontinuities. - Overlapping frames – Due to windowing, we are actually losing the samples towards the beginning and the end of the frame; this too will lead to an incorrect frequency representation. To compensate for this loss, we take overlapping frames rather than disjoint frames, so that the samples lost from the end of the ith frame and the beginning of the (i+1)th frame are wholly included in the frame formed by the overlap between these 2 frames. The overlap between frames is generally taken to be of 10-15 ms. 2. Extracting MFCC features Having extracted the speech frames, we now proceed to derive MFCC features for each speech frame. Speech is produced by humans by filtering applied by our vocal tract on the air expelled by our lungs. The properties of the source (lungs) are common for all speakers; it is the properties of the vocal tract, which is responsible for giving shape to the spectrum of signal and it varies across speakers. The shape of the vocal tract governs what sound is produced and the MFCCs best represent this shape. MFCCs are mel-frequency cepstral coefficients which are some transformed values of signal in cepstral domain. From theory of speech production, speech is assumed to be convolution of source (air expelled from lungs) and filter (our vocal tract). The purpose here is to characterise the filter and remove the source part. In order to achieve this, - We first transform the time domain speech signal into spectral domain signal using Fourier transform where source and filter part are now in multiplication. - Take log of the transformed values so that source and filter are now additive in log spectral domain. Use of log to transform from multiplication to summation made it easy to separate source and filter using a linear filter. - Finally, we apply discrete cosine transform (found to be more successful than FFT or I-FFT) of the log spectral signal to get MFCCs. Initially the idea was to transform the log spectral signal to time domain using Inverse-FFT but ‘log’ being a non-linear operation created new frequencies called Quefrency or say it transformed the log spectral signal into a new domain called cepstral domain (ceps being reverse of spec). - The reason for the term ‘mel’ in MFFC is mel scale which exactly specifies how to space our frequency regions. Humans are much better at discerning small changes in pitch at low frequencies than they are at high frequencies. Incorporating this scale makes our features match more closely what humans hear. The above explanation is just to give the readers an idea of how these features were motivated. If you really like to explore and understand more about MFCCs, you can read in this blog. You can find various implementation for extracting MFCCs on internet. We have employed python_speech_features (check here). All you have to do is pip install python_speech_features. One can also install scikits talkbox for the same. The following python code is a function to extract MFCC features from given audio. import python_speech_features as mfcc def get_MFCC(sr,audio): features = mfcc.mfcc(audio, sr, 0.025, 0.01, 13, appendEnergy = False) features = preprocessing.scale(features) return features 3. Training gender models In order to build a gender detection system from the above extracted features, we need to model both the genders. We employ GMMs for this task. A Gaussian mixture model is a probabilistic clustering model for representing the presence of sub-populations within an overall population. The idea of training a GMM is to approximate the probability distribution of a class by a linear combination of ‘k’ Gaussian distributions/clusters, also called the components of the GMM. The likelihood of data points (feature vectors) for a model is given by following equation: (1) , where is the Gaussian distribution (2) The training data of the class are used to estimate the parameters mean , co-variance matrices and weights of these k components. Initially, it identifies k clusters in the data by the K-means algorithm and assigns equal weight to each cluster. k Gaussian distributions are then fitted to these k clusters. The parameters , and of all the clusters are updated in iterations until the converge. The most popularly used method for this estimation is the Expectation Maximization (EM) algorithm. from sklearn.mixture import GMM gmm = GMM(n_components = 8, n_iter = 200, covariance_type='diag',n_init = 3) gmm.fit(features) Python’s sklearn.mixture package is used by us to learn a GMM from the features matrix containing the MFCC features. The GMM object requires the number of components n_components to be fitted on the data, the number of iterations n_iter to be performed for estimating the parameters of these n components, the type of co-variance covariance_type to be assumed between the features and the number of times n_ init the K-means initialization is to be done. The initialization which gave the best results is kept. The fit() function then estimates the model parameters using the EM algorithm. The following Python code is used to train the gender models. The code is run once for each gender and source is given the path to the training files for the respective gender. #train_models.py import os import cPickle import numpy as np from scipy.io.wavfile import read from sklearn.mixture import GMM import python_speech_features as mfcc from sklearn import preprocessing import warnings warnings.filterwarnings("ignore") def get_MFCC(sr,audio): features = mfcc.mfcc(audio,sr, 0.025, 0.01, 13,appendEnergy = False) features = preprocessing.scale(features) return features #path to training data source = "D:\\pygender\\train_data\\youtube\\male\\" #path to save trained model dest = "D:\\pygender\\" files = [os.path.join(source,f) for f in os.listdir(source) if f.endswith('.wav')] features = np.asarray(()); for f in files: sr,audio = read(f) vector = get_MFCC(sr,audio) if features.size == 0: features = vector else: features = np.vstack((features, vector)) gmm = GMM(n_components = 8, n_iter = 200, covariance_type='diag', n_init = 3) gmm.fit(features) picklefile = f.split("\\")[-2].split(".wav")[0]+".gmm" # model saved as male.gmm cPickle.dump(gmm,open(dest + picklefile,'w')) print 'modeling completed for gender:',picklefile 4. Evaluation on subset of AudioSet corpus Upon arrival of a test voice sample for gender detection, we begin by extracting the MFCC features for it, with 25 ms frame size and 10 ms overlap between frames . Next we require the log likelihood scores for each frame of the sample, , belonging to each gender, ie, and is to be calculated. Using (2), the likelihood of the frame being from a female voice is calculated by substituting the and of female GMM model. This is done for each of the k Gaussian components in the model, and the weighted sum of the k likelihoods from the components is taken as per the parameter of the model, just like in (1). The logarithm operation when applied on the obtained sum gives us the log likelihood value for the frame. This is repeated for all the frames of the sample and the likelihoods of all the frames are added. Similar to this, the likelihood of the speech being male is calculated by substituting the values of the parameters of the trained male GMM model and repeating the above procedure for all the frames. The Python code given below predicts the gender of the test audio. #test_gender.py import os import cPickle import numpy as np from scipy.io.wavfile import read import python_speech_features as mfcc from sklearn import preprocessing import warnings warnings.filterwarnings("ignore") def get_MFCC(sr,audio): features = mfcc.mfcc(audio,sr, 0.025, 0.01, 13,appendEnergy = False) feat = np.asarray(()) for i in range(features.shape[0]): temp = features[i,:] if np.isnan(np.min(temp)): continue else: if feat.size == 0: feat = temp else: feat = np.vstack((feat, temp)) features = feat; features = preprocessing.scale(features) return features #path to test data sourcepath = "D:\\pygender\\test_data\\AudioSet\\female_clips\\" #path to saved models modelpath = "D:\\pygender\\" gmm_files = [os.path.join(modelpath,fname) for fname in os.listdir(modelpath) if fname.endswith('.gmm')] models = [cPickle.load(open(fname,'r')) for fname in gmm_files] genders = [fname.split("\\")[-1].split(".gmm")[0] for fname in gmm_files] files = [os.path.join(sourcepath,f) for f in os.listdir(sourcepath) if f.endswith(".wav")] for f in files: print f.split("\\")[-1] sr, audio = read(f) features = get_MFCC(sr,audio) scores = None log_likelihood = np.zeros(len(models)) for i in range(len(models)): gmm = models[i] #checking with each model one by one scores = np.array(gmm.score(features)) log_likelihood[i] = scores.sum() winner = np.argmax(log_likelihood) print "\tdetected as - ", genders[winner],"\n\tscores:female ",log_likelihood[0],",male ", log_likelihood[1],"\n" Results The following confusion matrix shows the results of the evaluation on the subset extracted from AudioSet corpus. The approach performs brilliantly for the female gender, with an accuracy of 95%, while for the male gender the accuracy is 76%. The overall accuracy of the system is 86%. If we look at the performance, trained female model seems to be good representative of their gender in comparison to trained male model. The possible reasons and areas of improvement has been discussed in next section. We also evaluated the same trained gender models on an exhibition data-set that consists of 250 audio files (130 males and 120 females) collected in a real-time environment during an open technology exhibition. The results of the evaluation on the exhibition data-set are shown in the following confusion matrix. Female gender model had an accuracy of 99%, while for the male gender the accuracy is 88%. The overall accuracy of the system is 94%. Concluding Remarks We hope the blog post was successful in explaining to you your first speech processing task. We expect you to reproduce the results posted by us. In order to get a better understanding of the various parameters used by us, you can play with them, for example: - Train gender models on larger data-set. In the experiments performed, training data consists of 5 minutes of speech per gender only. A larger data-set may improve the accuracy as it will encompass the MFCCs well. - Clean the extracted data-set from AudioSet. We have not done any cleaning or noise removal. Few of the audios are noisy and the spoken speech part in audio is less in the 10 seconds audio clip. - Readers can study the effect of number of GMM components on the performance of the models. - We have taken only MFCCs in order to build a gender detection system. In literature, you can find lot of acoustic features that are used to build gender model. For reference here is a link. The full implementation of followed approach for training and evaluation of gender detection from voice can be downloaded from GitHub link here. Also remember to download the data-set provided at the beginning of blog-post. Good one LikeLiked by 1 person Can we get a python 3 version of the same code ? We can get at Sorry to spam! I tried converting the whole code to python3 Training of data set can be achieved with 2.7 , but i need the test_gender to work in 3.x , although i tried converting it to python 3 code , i get an error as Traceback (most recent call last): File “test.py”, line 81, in models = [cPickle.load(open(fname,’r’)) for fname in gmm_files] File “test.py”, line 81, in models = [cPickle.load(open(fname,’r’)) for fname in gmm_files] TypeError: a bytes-like object is required, not ‘str’ i tried to load the fname parameter with ‘rb’ mode , and also wrote them in ‘wb’ mode using the train_data.py , Still did not work! Would be helpful if you could tell me where i went wrong 🙂 replacing ‘r’ with ‘rb’ and ‘w’ with ‘wb’ worked for me, I think there is some other error after doing those changes change it to ‘rb’ in open(fname,’r’) it should be open(fname,’rb’) How to get the same in 3.7 using GausssianMixture function instead of GMM from sklearn.mixture import GaussianMixture as GMM gmm = GMM(n_components=16, max_iter=200, covariance_type=’diag’, n_init=3) This program can be implimented in real time Why are we training our model only on male voice dataset. And if we have trained on male voice how can it identify the female voice? sir can you explain how log_likelihood[i] = scores.sum() winner = np.argmax(log_likelihood) is working. sir can u make blog on voice cloning system using TKinter or django or pytorch or tensorflow. At which we can record our voice and it will mimic our voice as it is. Hii, i’m using these code in python 3.8.2. the training code has running successfully but getting a error while running testing code. below is the error. plz someone help me. C:/Python/python.exe e:/Python/gmm_1.py –EQQVMYe50.wav Traceback (most recent call last): File “e:/Python/gmm_1.py”, line 49, in winner = np.argmax(log_likelihood) File “”, line 5, in argmax File “C:\Python\lib\site-packages\numpy\core\fromnumeric.py”, line 1186, in argmax return _wrapfunc(a, ‘argmax’, axis=axis, out=out) File “C:\Python\lib\site-packages\numpy\core\fromnumeric.py”, line 61, in _wrapfunc return bound(*args, **kwds) ValueError: attempt to get argmax of an empty sequence
https://appliedmachinelearning.blog/2017/06/14/voice-gender-detection-using-gmms-a-python-primer/?replytocom=18734
CC-MAIN-2021-49
refinedweb
2,845
55.54
InterSystems has released Cache 2007, a post-relational database (16 messages) InterSystems has released Cache 2007, their object-oriented database system, which they term a "post-relational database." Cache is unique in that it allows the use of SQL to query an object database. There are two primary aspects to the release: Zen, designed specifically for browser-based application development, and Jalapeno, which focuses on Java database applications. A "post-relational database" is, to InterSystems, a database that combines objects and SQL with an underlying multistorage engine. Zen is an add-on for Cache that manages the presentation layer for data. It's a framework that's been targeted for maximum development speed, includes a library of pre-built components, and was designed for i18n from the beginning. It includes declarative security features, including database integration, page level, and component level access. Jalapeno focuses on Java database applications. It attempts to address some perceived weaknesses of EJB and Hibernate: EJB and Hibernate are based on object-relational mapping. Jalapeno wanted to get rid of it, because ORM has a significant impact on development and runtime. In addition, EJB and hibernate are more database-centric rather than Java-centric. One of Jalapeno's goals was to turn that around, make something Java-centric instead of database-centric. In Jalapeno, the developer goes to his IDE, and starts writing Java code, defining Java classes for the entity model, some of which go into the database, some which may not. At some point, the developer marks as persistent the ones that go into the database. Sooner or later, the compilation occurs. The addin for the IDE gets notified, and it looks to see which classes are persistent, examining them, and creating cache database equivalents of those classes as well as the code needed to connect the application to the database. A month later, if the data needs to change (rename a property, move one)… the plugin applies the same refactoring to the database so there's no unload/reload step. There are two deployment options: from a Java perspective, all access to the database is through the generated Java objects. There's a direct automatic connection between the object and the cache database. The developer can also store the objects via JDBC to any compatible database. Thus, Jalapeno can serve as an ORM layer itself. Rich domain models are created through object database modeling. The object model is translated into cache, so that object validations translate across .NET, Java, or any supported language. Any object class that can be defined can be accessed through SQL. Howver, a single class might not be represented as a single table, because what can be done in a single class hierarchy might require multiple tables to have an accurate relational view. - Posted by: Joseph Ottinger - Posted on: November 01 2006 13:34 EST Threaded Messages (16) - SQL Queries on Object with no O/R Mapping? by Gideon Low on November 01 2006 15:09 EST - Re: SQL Queries on Object with no O/R Mapping? by Billy Newport on November 01 2006 21:39 EST - Re: SQL Queries on Object with no O/R Mapping? by Howdee Deso on November 01 2006 22:22 EST - Re: SQL Queries on Object with no O/R Mapping? by John Brand on November 02 2006 05:01 EST - Re: SQL Queries on Object with no O/R Mapping? by Casual Visitor on November 02 2006 07:47 EST - Post-Relational? by Eyðun Nielsen on November 02 2006 09:42 EST - How about a real OODB... db4o by Travis Reeder on November 02 2006 12:47 EST - Re: How about a real OODB... db4o by Cameron Purdy on November 02 2006 15:30 EST - Re: InterSystems has released Cache 2007, a post-relational data by Iran Hutchinson on November 02 2006 18:04 EST - fud ?? by remco greve on November 03 2006 04:24 EST - Re: fud ?? by Iran Hutchinson on November 03 2006 08:16 EST - old application by remco greve on November 03 2006 11:33 EST - Re: InterSystems has released Cache 2007, a post-relational data by Matthias Ernst on November 04 2006 05:18 EST - Pretty amazing jobPretty amazing job by remco greve on November 04 2006 05:33 EST - Why by Jason Eacott on November 05 2006 22:37 EST - Re: InterSystems has released Cache 2007, a post-relational data by Iran Hutchinson on November 06 2006 16:53 EST SQL Queries on Object with no O/R Mapping?[ Go to top ] I'm a little confused by this claim. Here at GemStone, we are hard at work on providing a very seamless capability to view object data through relational API's. However, any way you slice it, an SQL query must SOMEHOW be mapped to underlying object namespaces, properties, collections, and methods. I guess if you are overlaying a SQL query-only engine on existing object technology, you'd call it "Relational/Object" mapping. GemFire provides querying on our distributed object data fabric today with a robust implementation the Object Data Management Group's Object Query Language (OQL) specification. Next year we will be merging our relational caching and continuous query technology (Real-Time Events) with the object caching technology, at which point SQL queries against objects through a GemFire provided R/O query engine will become available. The R/O overhead in the implementation currently being developed is very low compared to the work of actually executing the query (particularly if distributed)--essentially mapping the SQL to OQL and allowing us to leverage technology we've been improving since the days of GemStone's Facets object database. BTW, Cache certainly isn't the first to do this. I believe that GigaSpaces provides some JDBC capabilities into their object cache today. Cheers, Gideon GemFire--The Enterprise Data Fabric - Posted by: Gideon Low - Posted on: November 01 2006 15:09 EST - in response to Joseph Ottinger Re: SQL Queries on Object with no O/R Mapping?[ Go to top ] Some applications will use a distributed fabric to store state that isn't backed by a database or which was loaded from one or more databases and mapped to a common schema stored in the fabric. So, queries wouldn't be against the various databases, they'd be against whats in the fabric. I think we'll all have JDBC access to data kept in a cache fabric in the near future. What more interesting is which query language to support it? SQL is obviously the main candidate even though it lacks objecty features as the third party support for it (widgets, consoles, reporting tools and so on) basically makes it almost unbeatable. - Posted by: Billy Newport - Posted on: November 01 2006 21:39 EST - in response to Gideon Low Re: SQL Queries on Object with no O/R Mapping?[ Go to top ] I'm not a Cache expert, but learned a bit about it on a past project. Although marketing folks would like you to believe that it is a true OODB that can persist Java objects, the Cache database is essentially a collection of sparse arrays of delimited fields. It was developed for the M (aka "MUMPS") language, primarily to store records with variable number of fields that were needed for clinical results. Intersystems has since put a great marketing spin on it, and it pretty much dominates the healthcare industry As a general purpose database, it is really quite primitive, especially in terms of multi-user support, transaction isolation and recovery, and scalability, but performs reasonably well for smaller, less interactive, niche application areas like health care. Not sure what's new in Jalapeno, but unless they have made some major improvements in the past few months, there is really nothing to get excited about. Incidentally, I had also worked with GemstoneJ a few years ago, and was very impressed with its seamless integration with the Java VM and blazing performance even in a distributed configuration. On the other hand, ad-hoc query support was non-existent, reporting was a nightmare, and there were almost no tools for administration. While both databases are interesting, and can perform well in their own little worlds, I don't see either one becoming a mainstream relational database killer any time soon. - Posted by: Howdee Deso - Posted on: November 01 2006 22:22 EST - in response to Gideon Low Re: SQL Queries on Object with no O/R Mapping?[ Go to top ] - Posted by: John Brand - Posted on: November 02 2006 05:01 EST - in response to Howdee Deso Although marketing folks would like you to believe that it is a true OODB that can persist Java objects, the Cache database is essentially a collection of sparse arrays of delimited fields.Ouch. I typed in my browser, but somehow I ended up on instead. Re: SQL Queries on Object with no O/R Mapping?[ Go to top ] - Posted by: Casual Visitor - Posted on: November 02 2006 07:47 EST - in response to Howdee Deso I'm not a Cache expert, but learned a bit about it on a past project.Thank you for the information! Post-Relational?[ Go to top ] Isn't this a hierarchical database? And wouldn't it then be better described as Pre-Relational? ;-D - Posted by: Eyðun Nielsen - Posted on: November 02 2006 09:42 EST - in response to Joseph Ottinger How about a real OODB... db4o[ Go to top ] In that article, it looks like you still have to annotate the heck out of your objects and even include dependencies to Cache. import com.intersys.pojo.annotations.CacheClass; import com.intersys.pojo.annotations.Index; @CacheClass(name="Person",primaryKey="ID",sqlTableName="PERSON") @Index(description="Name Index on Person table",name="PersonIndexOne",propertyNames={"name"},sqlName="PersonIDX") public class Person { public String name; public String ssn; public String telephone; } If you used db4o, it truly supports plain old java objects and your class would look like this: public class Person { public String name; public String ssn; public String telephone; } And it has full querying capabilities, ACID transactions, and all the other good stuff you'd expect in a database. - Posted by: Travis Reeder - Posted on: November 02 2006 12:47 EST - in response to Joseph Ottinger Re: How about a real OODB... db4o[ Go to top ] Travis, It's a good idea to identify yourself as a db4o employee. Just add a sig (use Firefox signature plug-in) with a link to db4o. Peace, Cameron Purdy Tangosol Coherence: The Java Data Grid - Posted by: Cameron Purdy - Posted on: November 02 2006 15:30 EST - in response to Travis Reeder Re: InterSystems has released Cache 2007, a post-relational data[ Go to top ] Seems there is quite a bit of FUD here about Cache and complete misunderstandings. We put it in our labs and development environments for thorough testing before we chose it. 1. The SQL you use to get data out of Cache contains/object schema handles. That is all the binding you need to get data out of Cache. Then you just iterate over your java objects (typed objects if using Java 5). 2. Jalapeno is updated version of their Java binding with support for Java 5 annotations. It also works with Java 1.4 as you do not have to annotate your objects. You annotate for customization, like to stipulate what you want for 1->many mappings. 3. Scalability: I achieved 10-20,000 transactions per second over JDBC on a Powerbook G4 laptop going against a 500 GB database pulling records 2MB in size with zero optimization. We will be using it for 10+ terabytes of data and several hundred thousand users. Our bottlenecks have been on the JVM side. As far as healthcare goes. I have worked in the healthcare and bio-informatics industries and the data needs are quite diverse, some being quite extensive. To dominate that is quite impressive alone. It is not a niche database because of that. They are used in other sectors. 4. Some Features we like: It is a multi-faceted datbase, OODB, Multi-dimensional DB etc. What they have on the backend is an array structure (sparse) that allows them to project out a particular view of the data: Object, relational, multi-dimensional, etc. This is an important reason we chose it. More than one way to view our data quickly and extensibility for future requirements as change is the one guarantee we generally have in our project(s). 5. Refactoring: to be able to refactor your persistent objects and have IDE sync it with the database seamlessly. A huge feature. No updating of mapping files. Just do your normal refactoring like always. 6. We have a very large (and increasing) quite non-trivial domain model and trying to map that to a relational model would be quite painful and take a long time(300+ entities to start with . . . . project is ongoing). I won't get into the O/R impedance mismatch as there are quite a number of articles and books on the subject. 7. Standards support/ learning curve. XML, Web Services, etc. Java 5 support is nice. But there is also SQL which most developers are familiar with. They are busy at work also adding facets of EJB 3 support. For our team there was a very small learning curve to get up and running. 8. Excitement: our team has licenses to commercial databases and still choose Cache. I think it can replace any RDBMS today. The issue is not technology, it is architect and developer mindset IMHO. A lot of people think Relational first when it comes to solutions (new or old). The willingness to try something outside of the norm is a hurdle not easy to overcome. There are a number reasons Post/Non-relational databases are not as widely known and used. Pain of schema evolution used to be a large, factor, but that was years ago and most vendors have quite good solutions now. As always, use what you have proven works for your requirement/timeframes/etc. For us, the speed of development and overall feature set makes that Cache. - Posted by: Iran Hutchinson - Posted on: November 02 2006 18:04 EST - in response to Joseph Ottinger fud ??[ Go to top ] I think Howard D'Souza gave a pretty fair discription of cache. I am working with it right now on a old system using the sparse arays (globals in cache jargon) and it has no redeeming qualities at all it is somthing that should have been forgotten a long timeago. And cache object script is a language that makes perl seem elegant and simple. I know how it works people invest a lot of time in learning it (as did I) and it can be dificult to face the fact that that time was not very well spend and that the database world has moved on. - Posted by: remco greve - Posted on: November 03 2006 04:24 EST - in response to Iran Hutchinson Re: fud ??[ Go to top ] I'd be interested to know what versions, language bindings and systems you are using. We don't use any Cache object script and don't have to. We've also only been using the Java/Pojo binding in the 5.x series on Linux/Mac/Windows/AIX and have not experienced any of the issues previously described in our design/development/testing, so we came to different conclusions. - Posted by: Iran Hutchinson - Posted on: November 03 2006 08:16 EST - in response to remco greve old application[ Go to top ] I am using 5.1 on my workstation but the db server currently runs 4 something. I am filling a relational olap data-warehouse from a mumps style application and the objects or jdbc are of no use in accessing raw globals with records that are strings that are separated by ^ and 4 different styles to store date's. Globals are in essence very inflexible and you can only search them in 1 way (depth first) so they are more one-dimensional than multidimensional ;-). The internals (objects are compiled to mumps) are enough to put me of cache. - Posted by: remco greve - Posted on: November 03 2006 11:33 EST - in response to Iran Hutchinson Re: InterSystems has released Cache 2007, a post-relational data[ Go to top ] Scalability: I achieved 10-20,000 transactions per second over JDBC on a Powerbook G4 laptop going against a 500 GB database pulling records 2MB in size with zero optimization.Hmm ... that is 20-40GB/s. Pretty amazing job for a G4. You had a 500GB in-memory cache, right? - Posted by: Matthias Ernst - Posted on: November 04 2006 05:18 EST - in response to Iran Hutchinson Pretty amazing jobPretty amazing job[ Go to top ] Yes indeed pretty amazing. I know from experience that it takes a lot longer to load the same data in a cache database than a mysql database with myisam tables so cache is not so exceptionally fast as the marketing says. - Posted by: remco greve - Posted on: November 04 2006 05:33 EST - in response to Matthias Ernst Why[ Go to top ] I'm no Cache expert either, my only experiences with it have been the hardcore marketting folk at intersystems trying to sell it to me. From everything I've seen (and heard) I just dont see the point. I dont see anything Cache offers that you couldnt do with any db backend + hibernate for example, and you wouldnt be locked into some wierd proprietary OO db speak. The tools looked like a nightmare to use too. Its been around for ages and perhaps once upon a time it may have offered some benefit, but in todays world ORM tools are fast, free, reliable, common, and you can levereage whatever db backend you choose. I asked the sales rep repeatedly why I should choose Cache over Oracle/SQLServer+hibernate and after being handed around a few different sales reps and technical reps I got the answer "performance", but nobody would show me any performance data at all. I'm sorry but for that kind of $$ I'm not about to take the sales rep's word for it. - Posted by: Jason Eacott - Posted on: November 05 2006 22:37 EST - in response to Iran Hutchinson Re: InterSystems has released Cache 2007, a post-relational data[ Go to top ] 1. Performance: My Powerbook G4 had 2GB of memory and was 1 of several clients on a clean network with high throughput, same target environment for production deployment. The database it self was on a backend IBM Power 5 based servers with enough physical memory to put it entirely in memory if needed and 1 attached SAN. If you query the entire database, of course it will go into memory. We did not need it. I used JMeter for my test harness. The focus was to architect the application, system, and deployment architectures for scalability and throughput. We found the bottlenecks at the JVM level as it was 32 bit. 64 bit testing is upcoming and we are looking for great improvement. 2. Why. There has been a lot of debate about the Object Relational Impedance mismatch over the years(a few: Ambler, Wikipedia, OODBMS Articles). Surely O/R mapping helps the issue. But why stop there? Why have mutliple models: Domain model, Logical Data Model, Physical Data Model when you can have just one model? Most projects that use relational databases have Data Architects and/or DBAs. As a contrast, most Post-Relational/OODBMs don't require DBAs. There is also no gap (read: politics, design theory, turf wars, deployment etc.) between architects,developers and DBAs. I have used all manner of object databases (Objectivity, ObjectStore,etc.)and relational databases (Oracle,DB2, Sybase, MySQL, etc.) and found Cache quite good for what we are doing because it is not just an object database or an sql database. I don't listen to sale jobs as well which why I mentioned lab, development and testing. 3. Hibernate, JDO, etc. is manual and in some cases automated mapping to relational ends (a few OODBMS may also be supporting some jdo/ejb3). But how many projects still enlist the Data Architect/DBA to build/optimize/maintain the schemas vs. using the generated schemas? How does that work in enviroments with the need for complex schemas like OLAP? We've found limitations/frustrations in O/R mapping frameworks/tooling managing large and/or complex schemas. Some of the runtime speed comes from the removing of layers like O/RMs for instance who need to manage a lot of abstraction (classes, metadata, etc). The design/development speed comes from automatically shoving the schemas in the database in minutes and have it match my domain model 1:1. 4. Tooling. The Database console is a web interface. I really like that aspect. We partnered with Intersystems and said we want all java tools, not the development studio they offer if that is what you speak of. We use just the java jdbc driver, persistence annotations and the Web Interface. We also collaborated on the upcoming plugins for NetBeans, Eclipse and Intellij. They have been a great development partner as we tend to question everything and have high demands. 5. Vendor Lock-in. The point here is architecture and design. We are not tied to any database per se. You design your data access layers for abstraction and you also put that requirement on your database technology as well. But the level of abstraction is completely dependent on the need. Coupling will occur somewhere, point is to put at a place that won't be soo painful later when/if you have to change/extend later. With Cache, we have a very simple data access layer and Java 5 annotations where we want them. - Posted by: Iran Hutchinson - Posted on: November 06 2006 16:53 EST - in response to Joseph Ottinger
http://www.theserverside.com/discussions/thread.tss?thread_id=42902
CC-MAIN-2015-35
refinedweb
3,668
61.26
When you want to convey as message, but an image is too simplistic and a video is too complex, a GIF can be the perfect middle ground. As a JavaScript developer, I recently wondered: - Could I write a program to create a GIF? - Could JavaScript even do this? After a little research and a lot of trial and error, I found the answer to both question is yes. This article sums up what I found out. The GIF Format A good starting point is to research some of the history and structure of a GIF. It turns out the Graphics Interchange Format has was originally created by CompuServe back in the 1980s and was one of the first image formats used on the web. While the PNG format has pretty much replaced GIF for single images, GIF's ability to animate a series of images keeps the format relevant and supported today. In GIFs as we know them today, each image is allowed a maximum palette size of 256 colors. This limitation is why GIFs are more suited to illustrations rather than photography, even though they are used for both. GIF images are also compressed using the LZW algorithm, which provides lossless data compression. For more general information, Wikipedia is a great source, and for an in-depth breakdown of the entire specification, check out What's In a GIF. My Use Case I have been playing around with Electron a lot lately and I decided to attempt a desktop application that could record the user's screen and then turn the captured images into a GIF. The Electron environment combines the features of the browser, the the features of Node, and Electron's own APIs. Electron's desktopCapturer API makes capturing the user's screen a frame at a time and then saving those images to disk possible. Having these sequencial images is essential to this approach to GIF encoding. My project article GifIt goes into more detail on that subject, and the GifIt Source Code is available if you want to check out how I went about recording the desktop. At this point, my goal became to write my own library for GIF encoding. Existing Libraries The next step I took was to look into existing libraries on NPM and Github. There are a few options, and which one you use depends a lot of your use case and the available documentation. It looks like the original implementation in JavaScript was gif.js. I poked around the files and was happy to find that the LZWEncoder and NeuQuant algorithms had already been ported. I used these as building blocks for my library. My Library One thing I noticed about existing libraries was that GIFs took a long time to process and the size of the output files seemed really large. GIF Encoder 2 adds new features to help mitigate these downsides. The first thing I did was add an optional optimizer. I discoved that a lot of time was being spent reducing an image into its 256 color palette. This process involves looking at the color of every pixel in an image and was being done by the NeuQuant algoritm. I added the ability to reuse the palette from the previous image if the current and previous image were similar. Checking this adds overhead, but not nearly as much overhead as calculating a new color palette. I also added a second algorithm called Octree that uses a totally different method to calculate the color palette. This ended up resulting in smaller smaller file sizes. Using Gif Encoder 2 npm install gif-encoder-2 Constructor GIFEncoder(width, height, algorithm, useOptimizer, totalFrames) const encoder = new GIFEncoder(500, 500) const encoder = new GIFEncoder(1200, 800, 'octree', false) const encoder = new GIFEncoder(720, 480, 'neuquant', true, 20) Methods Basic Example This example creates a simple GIF and shows the basic way Gif Encoder 2 works. - Create an instance of GIFEncoder - Call any needed setmethods - Start the encoder - Add frames as Canvas context - Get the output data and do something with it const GIFEncoder = require('gif-encoder-2') const { createCanvas } = require('canvas') const { writeFile } = require('fs') const path = require('path') const size = 200 const half = size / 2 const canvas = createCanvas(size, size) const ctx = canvas.getContext('2d') function drawBackground() { ctx.fillStyle = '#ffffff' ctx.fillRect(0, 0, size, size) } const encoder = new GIFEncoder(size, size) encoder.setDelay(500) encoder.start() drawBackground() ctx.fillStyle = '#ff0000' ctx.fillRect(0, 0, half, half) encoder.addFrame(ctx) drawBackground() ctx.fillStyle = '#00ff00' ctx.fillRect(half, 0, half, half) encoder.addFrame(ctx) drawBackground() ctx.fillStyle = '#0000ff' ctx.fillRect(half, half, half, half) encoder.addFrame(ctx) drawBackground() ctx.fillStyle = '#ffff00' ctx.fillRect(0, half, half, half) encoder.addFrame(ctx) encoder.finish() const buffer = encoder.out.getData() writeFile(path.join(__dirname, 'output', 'beginner.gif'), buffer, error => { // gif drawn or error }) - beginner.gif Advanced Example This example creates a reusable function that reads a directory of image files and turns them into a GIF. The encoder itself isn't as complicated as the surrounding code. Note that setDelay can be called once (sets all frames to value) or once per frame (sets delay value for that frame). Obviously, you can use any directory and filenames you want if you recreate the following example. - Read a directory of images (gets the path to each image) - Create an Imageto find the dimensions - Create a write streamto an output giffile - Create an instance of the GIFEncoder - Pipe the encoder's read streamto the write stream - Call any needed setmethods - Start the encoder - Draw each image to a Canvas - Add each contextto encoder with addFrame - When GIF is done processing resolve1()is called and function is done - Use this function to compare the output of both NeuQuant and Octree algorithms const GIFEncoder = require('gif-encoder-2') const { createCanvas, Image } = require('canvas') const { createWriteStream, readdir } = require('fs') const { promisify } = require('util') const path = require('path') const readdirAsync = promisify(readdir) const imagesFolder = path.join(__dirname, 'input') async function createGif(algorithm) { return new Promise(async resolve1 => { const files = await readdirAsync(imagesFolder) const [width, height] = await new Promise(resolve2 => { const image = new Image() image.onload = () => resolve2([image.width, image.height]) image.src = path.join(imagesFolder, files[0]) }) const dstPath = path.join(__dirname, 'output', `${algorithm}.gif`) const writeStream = createWriteStream(dstPath) writeStream.on('close', () => { resolve1() }) const encoder = new GIFEncoder(width, height, algorithm) encoder.createReadStream().pipe(writeStream) encoder.start() encoder.setDelay(200) const canvas = createCanvas(width, height) const ctx = canvas.getContext('2d') for (const file of files) { await new Promise(resolve3 => { const image = new Image() image.onload = () => { ctx.drawImage(image, 0, 0) encoder.addFrame(ctx) resolve3() } image.src = path.join(imagesFolder, file) }) } }) } createGif('neuquant') createGif('octree') - NeuQuant - Octree Alternative Encoding Method While Gif Encoder 2 is reliable and can encode GIFs faster than other existing libraries, I did find one alternative that works better but requires the FFmpeg stream processing library to be installed on the host machine. FFmpeg is a command line tool, but can be executed by Node using the child_process API. When I was creating GifIt I added the ability to adjust the duration of each frame in the GIF. Imagine a user wants to display a title page for 5 seconds before running through the rest of the frames or wants to cut the duration of certain frames by half. In order to accomadate these variable durations FFmpeg requires a text file describing the path and duration of each image. The duration is in seconds and the paths are relative. - example from FFmpeg Docs file '/path/to/dog.png' duration 5 file '/path/to/cat.png' duration 1 file '/path/to/rat.png' duration 3 file '/path/to/tapeworm.png' duration 2 file '/path/to/tapeworm.png' This is a simplifed version of the function I used in GifIt. imagesis an object that contains the absolute path and duration of the frame dstPathis the destination to save the output GIF file cwdis the absolute path of the current working directory (image files must be here as well) ffmpegPathis the absolute path to the FFmpeg executable on the host machine - the path to the last image is added twice to ensure thhe GIF loops correctly import { execFile } from 'child_process' import fs from 'fs' import path from 'path' import { promisify } from 'util' const writeFile = promisify(fs.writeFile) export const createGif = async (images, dstPath, cwd, ffmpegPath) => { return new Promise(resolve => { let str = '' images.forEach((image, i) => { str += `file ${path.basename(image.path)}\n` str += `duration ${image.duration}\n` }) str += `file ${path.basename(images[images.length - 1].path)}` const txtPath = path.join(cwd, 'template.txt') writeFile(txtPath, str).then(() => { execFile( ffmpegPath, [ '-f', 'concat', '-i', 'template.txt', '-lavfi', 'palettegen=stats_mode=diff[pal],[0:v][pal]paletteuse=new=1:diff_mode=rectangle', dstPath ], { cwd }, (error, stdout, stderr) => { if (error) { throw error } else { resolve() } } ) }) }) } Best of luck creating your GIFs!!! Hit me up if you have any questions.
https://benjaminbrooke.me/posts/encode-gifs-with-node/
CC-MAIN-2019-51
refinedweb
1,480
56.25
I wrote this small utility app while working on the custom 'tree with columns' control, which you can see used in this same app. There is really not much to it, but I figured it might be useful for others working on custom controls. A VisualStyleElement is a UI element exposed by the system and can be used by any custom control to draw a system control or element. In the case of the tree control, the visual element is used to draw the column and row headers. VisualStyleElement More information regarding the visual styles can be found in System.Windows.Forms.VisualStyles namespace and here. System.Windows.Forms.VisualStyles namespace The only part that was a little tricky was to populate the tree. All elements are defined as nested static classes within VisualStyleElement (check it out with Reflector). After a little bit of trial and error I found it to be quite simple though, get the nested types and for each type get the static properties, and do this recursive. The code for this is in VisulalStyleTreeV1.AddType(type). static VisualStyleElement static VisulalStyleTreeV1.AddType(type) To paint the style in the tree, I created a derived class of CellPainter and overwrote PaintCell for the Style column (fieldname called image for this column !?) CellPainter PaintCell Style image And that is all. CompareColorByBright.
http://www.codeproject.com/Articles/23541/Visual-Style-Element-Browser?msg=2425138
CC-MAIN-2015-06
refinedweb
222
54.93
Add a namespace constraint to the Attribute production [15]: NSC: No Prefix Undeclaring. In a namespace declaration for a prefix (i.e where the NSAttName is a PrefixedAttName), the attribute value MUST NOT be empty. This was already stated in the text, but should be made a namespace constraint. Change the "Attribute" links in productions [12] Stag and [14] Empty Element Tag to point to #NT-Attribute instead of. In sections 2.1 and 2.3, change the term "IRI" to "URI". Fortunately this mistake occurs only in explanatory text. To ensure that its definition works with all editions of XML 1.0, update production [4] NCName as follows: Move productions [5] NCNameChar and [6] NCNameStartChar to a new Appendix F, as follows: F Orphaned Productions The following two productions are modified versions of ones which were present in the first two editions of this specification. They are no longer used, but are retained here to satisfy cross-references to undated versions of this specification. Because the Letterproduction of XML 1.0, originally used in the definition of NCNameStartChar, is no longer the correct basis for defining names since XML 1.0 Fifth Edition, the NCNameStartCharproduction has been modified to give the correct results against any edition of XML, by defining NCNameStartChar in terms of NCName. Note: Production [6] NCNameStartChar takes advantage of the fact that a single-character NCName is necessarily an NCNameStartChar, and works by subtracting from the set of NCNames of all lengths the set of all strings of two or more characters, leaving only the NCNames which are one character long. In 7 Conformance of Documents, correct the reference to the XML 1.0 specification to be [XML]. In A Normative References, for consistency with the cross-references from the syntax productions, change the entry for XML 1.0 as follows: In 6.3 Uniqueness of Attributes turn the first sentence and the two numbered clauses following into a Namespace Constraint, and include a forward reference to it from production [15] Attribute.
http://www.w3.org/XML/2006/xml-names-errata.html
CC-MAIN-2019-30
refinedweb
336
55.84
Request for Comments: 7940 Category: Standards Track ISSN: 2070-1721 ICANN A. Freytag ASMUS, Inc. August 2016 Representing Label Generation Rulesets Using XML Unicode code points are permitted for registrations, which alternative code points are considered variants, and what actions may be performed on labels containing those. Design Goals ....................................................5 3. Normative Language ..............................................6 4. LGR Format ......................................................6 4.1. Namespace ..................................................7 4.2. Basic Structure ............................................7 4.3. Metadata ...................................................8 4.3.1. The "version" Element ...............................8 4.3.2. The "date" Element ..................................9 4.3.3. The "language" Element ..............................9 4.3.4. The "scope" Element ................................10 4.3.5. The "description" Element ..........................10 4.3.6. The "validity-start" and "validity-end" Elements ...11 4.3.7. The "unicode-version" Element ......................11 4.3.8. The "references" Element ...........................12 5. Code Points and Variants .......................................13 5.1. Sequences .................................................14 5.2. Conditional Contexts ......................................15 5.3. Variants ..................................................16 5.3.1. Basic Variants .....................................16 5.3.2. The "type" Attribute ...............................17 5.3.3. Null Variants ......................................18 5.3.4. Variants with Reflexive Mapping ....................19 5.3.5. Conditional Variants ...............................20 5.4. Annotations ...............................................22 5.4.1. The "ref" Attribute ................................22 5.4.2. The "comment" Attribute ............................23 5.5. Code Point Tagging ........................................23 6. Whole Label and Context Evaluation .............................23 6.1. Basic Concepts ............................................23 6.2. Character Classes .........................................25 6.2.1. Declaring and Invoking Named Classes ...............25 6.2.2. Tag-Based Classes ..................................26 6.2.3. Unicode Property-Based Classes .....................26 6.2.4. Explicitly Declared Classes ........................28 6.2.5. Combined Classes ...................................29 6.3. Whole Label and Context Rules .............................30 6.3.1. The "rule" Element .................................31 6.3.2. The Match Operators ................................32 6.3.3. The "count" Attribute ..............................33 6.3.4. The "name" and "by-ref" Attributes .................34 6.3.5. The "choice" Element ...............................34 6.3.6. Literal Code Point Sequences .......................35 6.3.7. The "any" Element ..................................35 6.3.8. The "start" and "end" Elements .....................35 6.3.9. Example Context Rule from IDNA Specification .......36 6.4. Parameterized Context or When Rules .......................37 6.4.1. The "anchor" Element ...............................37 6.4.2. The "look-behind" and "look-ahead" Elements ........38 6.4.3. Omitting the "anchor" Element ......................40 7. The "action" Element ...........................................40 7.1. The "match" and "not-match" Attributes ....................41 7.2. Actions with Variant Type Triggers ........................41 7.2.1. The "any-variant", "all-variants", and "only-variants" Attributes .........................41 7.2.2. Example from Tables in the Style of RFC 3743 .......44 7.3. Recommended Disposition Values ............................45 7.4. Precedence ................................................45 7.5. Implied Actions ...........................................45 7.6. Default Actions ...........................................46 8. Processing a Label against an LGR ..............................47 8.1. Determining Eligibility for a Label .......................47 8.1.1. Determining Eligibility Using Reflexive Variant Mappings ...................................47 8.2. Determining Variants for a Label ..........................48 8.3. Determining a Disposition for a Label or Variant Label ....49 8.4. Duplicate Variant Labels ..................................50 8.5. Checking Labels for Collision .............................50 9. Conversion to and from Other Formats ...........................51 10. Media Type ....................................................51 11. IANA Considerations ...........................................52 11.1. Media Type Registration ..................................52 11.2. URN Registration .........................................53 11.3. Disposition Registry .....................................53 12. Security Considerations .......................................54 12.1. LGRs Are Only a Partial Remedy for Problem Space .........54 12.2. Computational Expense of Complex Tables ..................54 13. References ....................................................55 13.1. Normative References .....................................55 13.2. Informative References ...................................56 Appendix A. Example Tables ........................................58 Appendix B. How to Translate Tables Based on RFC 3743 into the XML Format ............................................63 Appendix C. Indic Syllable Structure Example ......................68 C.1. Reducing Complexity .......................................70 Appendix D. RELAX NG Compact Schema ...............................71 Acknowledgements ..................................................82 Authors' Addresses ................................................82 1. Introduction This document specifies a method of using Extensible Markup Language (XML) to describe Label Generation Rulesets (LGRs). LGRs are algorithms used to determine whether, and under what conditions, a given identifier label is permitted, based on the code points it contains and their context. These algorithms comprise a list of permissible code points, variant code point mappings, and a set of rules that act on the code points and mappings. LGRs form part of an administrator's policies. In deploying Internationalized Domain Names (IDNs), they have also been known as IDN tables or variant tables. There are other kinds of policies relating to labels that are not normally covered by LGRs and are therefore not necessarily a and may also be used for describing ASCII domain name label rulesets, or other types of identifier labels beyond those used for domain names. 2. Design Goals The following goals informed the design of this format: - The format needs to be implementable in a reasonably straightforward manner in software. - The format should be able to be automatically checked for formatting errors, so that common mistakes can be caught. - An LGR needs to be able to express the set of valid code points that are allowed for registration under a specific administrator's policies. - An LGR needs to be able to express computed alternatives to a given identifier based on mapping relationships between code points, whether one-to-one or many-to-many. These computed alternatives are commonly known as "variants". - Variant code points should be able to be tagged with explicit dispositions or categories that can be used to support registry policy (such as whether to allocate the computed variant or to merely block it from usage or registration). - Variants and code points must be able to be stipulated based on contextual information. For example, some variants may only be applicable when they follow a certain code point or when the code point is displayed in a specific presentation form. - The data contained within an LGR must be able to be interpreted unambiguously, so that independent implementations that utilize the contents will arrive at the same results. - To the largest extent possible, policy rules should be able to be specified in the XML format without relying on hidden or built-in algorithms in implementations. - LGRs should be suitable for comparison and reuse, such that one could easily compare the contents of two or more to see the differences, to merge them, and so registration policies are used for a particular zone are outside the scope of this memo. 3. Normative Language The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC2119]. 4. LGR Format An LGR is expressed as a well-formed XML document [XML] that conforms to the schema defined in Appendix D. As XML is case sensitive, an LGR must be authored with the correct casing. For example, the XML element names MUST be in lowercase as described in this specification, and matching of attribute values is only performed in a case-sensitive manner. A document that is not well-formed, is non-conforming, or violates other constraints specified in this specification MUST be rejected. 4.1. Namespace The XML Namespace URI is "urn:ietf:params:xml:ns:lgr-1.0". See Section 11.2 for more information. 4.2. Basic Structure The basic XML framework of the document is as follows: <?xml version="1.0"?> <lgr xmlns="urn:ietf:params:xml:ns:lgr-1.0"> ... </lgr> The "lgr" element contains up to three sub-elements or sections. First is an optional "meta" element that contains all metadata associated with the LGR, such as its authorship, what it is used for, implementation notes, and references. This is followed by a required "data" element that contains the substantive code point data. Finally, an optional "rules" element contains information on rules for evaluating labels, if any, along with "action" elements providing for the disposition of labels and computed variant labels. <?xml version="1.0"?> <lgr xmlns="urn:ietf:params:xml:ns:lgr-1.0"> <meta> ... </meta> <data> ... </data> <rules> ... </rules> </lgr> A document MUST contain exactly one "lgr" element. Each "lgr" element MUST contain zero or one "meta" element, exactly one "data" element, and zero or one "rules" element; and these three elements MUST be in that order. Some elements that are direct or nested child elements of the "rules" element MUST be placed in a specific relative order to other elements for the LGR to be valid. An LGR that violates these constraints MUST be rejected. In other cases, changing the ordering would result in a valid, but different, specification. In the following descriptions, required, non-repeating elements or attributes are generally not called out explicitly, in contrast to "OPTIONAL" ones, or those that "MAY" be repeated. For attributes that take lists as values, the elements MUST be space-separated. 4.3. Metadata The "meta" element expresses metadata associated with the LGR, and the element SHOULD be included so that the associated metadata are available as part of the LGR and cannot become disassociated. The following subsections describe elements that may appear within the "meta" element. The "meta" element can be used to identify the author or relevant contact person, explain the intended usage of the LGR, and provide implementation notes as well as references. Detailed metadata allow the LGR document to become self-documenting -- for example, if rendered in a human-readable format by an appropriate tool. Providing metadata pertaining to the date and version of the LGR is particularly encouraged to make it easier for interoperating consumers to ensure that they are using the correct LGR. With the exception of the "unicode-version" element, the data contained within is not required by software consuming the LGR in order to calculate valid labels or to calculate variants. If present, the "unicode-version" element MUST be used by a consumer of the table to identify that it has the correct Unicode property data to perform operations on the table. This ensures that possible differences in code point properties between editions of the Unicode Standard do not impact the product of calculations utilizing an LGR.>> 4.3.3. The "language" Element Each OPTIONAL "language" element identifies a language or script for which the LGR is intended. The value of the "language" element MUST be a valid language tag as described in [RFC5646]. The tag may refer to a script plus undefined language if the LGR is not intended for a specific language. Example of an LGR for the English language: <language>en</language> If the LGR applies to a script rather than a specific language, the "und" language tag SHOULD be used followed by the relevant script subtag from [RFC5646]. For example, for a Cyrillic script LGR: <language>und-Cyrl</language> If the LGR covers a set of multiple languages or scripts, the "language" element MAY be repeated. However, for cases of a script-specific LGR exhibiting insignificant admixture of code points from other scripts, it is RECOMMENDED to use a single "language" element identifying the predominant script. In the exceptional case of a multi-script LGR where no script is predominant, use Zyyy (Common): <language>und-Zyyy</language>. For that type, the content of the "scope" element MUST be a domain name written relative to the root zone, in presentation format with no trailing dot. However, in the unique case of the DNS root zone, it is represented as ".". <scope type="domain">example.com</scope> There may be multiple "scope" tags used -- for example, to reflect a list of domains to which the LGR is applied. No other values of the "type" attribute are defined by this specification; however, this specification can be used for applications other than domain names. Implementers of LGRs for applications other than domain names SHOULD define the scope extension grammar in an IETF specification or use XML namespaces to distinguish their scoping mechanism distinctly from the base LGR namespace. An explanation of any custom usage of the scope in the "description" element is RECOMMENDED. <scope xmlns=""> ... content per alternate namespace ... </scope>" element to condition the application of the LGR's data and rules. The element has an OPTIONAL "type" attribute, which refers to the Internet media type [RFC2045] of the enclosed data. Typical types would be "text/plain" or "text/html". The attribute SHOULD be a valid media type. If supplied, it will be assumed that the contents are of that media type. If the description lacks a "type" value, it will be assumed to be plain text ("text/plain"). 4.3.6. The "validity-start" and "validity-end" Elements The "validity-start" and "validity-end" elements are OPTIONAL elements that describe the time period from which the contents of the LGR become valid (are used in registry policy) and time when the contents of the LGR cease to be used, respectively. The dates MUST conform to the "full-date" format described in Section 5.6 of [RFC3339]. <validity-start>2014-03-12</validity-start> character properties (Section 6.2.3). The value of a given Unicode character property may change between versions of the Unicode Character Database [UAX44], unless such change has been explicitly disallowed in [Unicode-Stability]. It is RECOMMENDED to only reference properties defined as stable or immutable. As an alternative to referencing the property, the information can be presented explicitly in the LGR. <unicode-version>6.3.0</unicode-version> It is not necessary to include a "unicode-version" element for LGRs that do not make use of Unicode character properties; however, it is RECOMMENDED. 4.3.8. The "references" Element An LGR may define a list of references that containing one or more "reference" elements, each with a unique "id" attribute. It is RECOMMENDED that the "id" attribute be a zero-based integer; however, in addition to digits 0-9, it MAY contain uppercase letters A-Z, as well as a period, hyphen, colon, or underscore. The value of each "reference" element SHOULD be the citation of a standard, dictionary, or other specification in any suitable format. In addition to an "id" attribute, a "reference" element MAY have a "comment" attribute for an optional free-form annotation. <references> <reference id="0">The Unicode Consortium. The Unicode Standard, Version 8.0.0, (Mountain View, CA: The Unicode Consortium, 2015. ISBN 978-1-936213-10-8)< its id as part of an optional "ref" attribute (see Section 5.4.1). The "ref" attribute may be used with many kinds of elements in the "data" or "rules" sections of the LGR, most notably those defining code points, variants, and rules. However, a "ref" attribute may not occur in certain kinds of elements, including references to named character classes or rules. See below for the description of these elements. 5. Code Points and Variants The bulk of an LGR is a description of which set of code points. Collectively, these are known as the repertoire. Discrete permissible code points or code point sequences (see Section 5.1) are declared with a "char" element. Here is a minimal example declaration for a single code point, with the code point value given in the "cp" attribute: <char cp="002D"/> As described below, a full declaration for a "char" element, whether or not it is used for a single code point or for a sequence (see Section 5.1), may have optional child elements defining variants. Both the "char" and "range" elements can take a number of optional attributes for conditional inclusion, commenting, cross-referencing, and character tagging, as described below. Ranges of permissible code points may be declared with a "range" element, as in this minimal example: <range first- The range is inclusive of the first and last code points. Any additional represented according to the standard Unicode convention but without the prefix "U+": they are expressed in uppercase hexadecimal and are zero-padded to a minimum of 4 digits. The rationale for not allowing other encoding formats, including native Unicode encoding in XML, is explored in [UAX42]. The XML conventions used in this format, such as element and attribute names, mirror this document where practical and reasonable to do so. It is RECOMMENDED to list all "char" elements in ascending order of the "cp" attribute. Not doing so makes it unnecessarily difficult for authors and reviewers to check for errors, such as duplications, or to review and compare against listing of code points in other documents and specifications. All "char" elements in the "data" section MUST have distinct "cp" attributes. The "range" elements MUST NOT specify code point ranges that overlap either another range or any single code point "char" elements. An LGR that defines the same code point more than once by any combination of "char" or "range" elements MUST be rejected. some code point is only eligible when preceded or followed by a certain a conditional context using an optional "when" attribute as described below in Section 5.2. Using a conditional context is more flexible because a context is not limited to a specific sequence of code points. In addition, using a context allows the choice of specifying either a prohibited or a required context. 5.2. Conditional Contexts A conditional context is specified by a rule that must be satisfied (or, alternatively, must not be satisfied) for a code point in a given label, often at a particular location in a label. To specify a conditional context, either a "when" or "not-when" attribute may be used. The value of each "when" or "not-when" attribute is a context rule as described below in Section 6.3. This rule can be a rule evaluating the whole label or a parameterized context rule. The context condition is met when the rule specified in the "when" attribute is matched or when the rule in the "not-when" attribute fails to match. It is an error to reference a rule that is not actually defined in the "rules" element. A parameterized context rule (see Section 6.4) defines the context immediately surrounding a given code point; unlike a sequence, the context is not limited to a specific fixed code point but, for example, may designate any member of a certain character class or a code point that has a certain Unicode character property. Given a suitable definition of a parameterized context rule named "follows-virama", this example specifies that a ZERO WIDTH JOINER (U+200D) is restricted to immediately follow any of several code points classified as virama: <char cp="200D" when="follows-virama" /> For a complete example, see Appendix A. In contrast, a whole label rule (see Section 6.3) specifies a condition to be met by the entire label -- for example, that it must contain at least one code point from a given script anywhere in the label. In the following example, no digit from either range may occur in a label that mixes digits from both ranges: <data> <range first- <range first- </data> (See Section 6.3.9 for an example of the "mixed-digits" rule.) The OPTIONAL "when" or "not-when" attributes are mutually exclusive. They MAY be applied to both "char" and "range" elements in the "data" element, including "char" elements defining sequences of code points, as well as to "var" elements (see Section 5.3.5). If a label contains one or more code points that fail to satisfy a conditional context, the label is invalid (see Section 7.5). For variants, the conditional context restricts the definition of the variant to the case where the condition is met. Outside the specified context, a variant is not defined. 5.3.. 5.3.1. Basic Variants Variant code points are specified using one of more "var" elements as children of a "char" element. The target mapping is specified using the "cp" attribute. Other, optional attributes for the "var" element are described below.) might hypothetically be specified as a variant for a LATIN SMALL LETTER O WITH DIAERESIS (U+00F6) as follows: <char cp="00F6"> <var cp="006F 0065"/> </char> The source and target of a variant mapping may both be sequences but not ranges. If the source of one mapping is a prefix sequence of the source for another, both variant mappings will be considered at the same location in the input label when generating permuted variant labels. If poorly designed, an LGR containing such an instance of a prefix relation could generate multiple instances of the same variant label for the same original label, but with potentially different dispositions. Any duplicate variant labels encountered MUST be treated as an error (see Section 8.4). only part of the LGR if spelled out explicitly. Implementations that require an LGR to be symmetric and transitive should verify this mechanically. 5.3.5.) 5.3 7. Whenever these values can represent the desired policy, they SHOULD be used. <char cp="767C"> <var cp="53D1" type="allocatable"/> <var cp="5F42" type="blocked"/> <var cp="9AEA" type="blocked"/> <var cp="9AEE" type="blocked"/> </char> By default, if a variant label contains any instance of one of the variants of type "blocked", the label would be blocked, but if it contained only instances of variants to be allocated, it could be allocated. See the discussion about implied actions in Section 7.6. The XML format for the LGR makes the relation between the values of the "type" attribute on variants and the resulting disposition of variant labels fully explicit. See the discussion in Section 7.2. Making this relation explicit allows a generalization of the "type" attribute from directly reflecting dispositions to a more differentiated intermediate value that is then used in the resolution of label disposition. Instead of the default action of applying the most restrictive disposition to the entire label, such a generalized resolution can be used to achieve additional goals, such as limiting the set of allocatable variant labels or implementing other policies found in existing LGRs (see, for example, Appendix B). Because variant mappings MUST be unique, it is not possible to define the same variant for the same "char" element with different "type" attributes (however, see Section 5.3.5). 5.3 mappings from null sequences are removed in variant label generation (see Section 5.3.2). 5.3.4. Variants with Reflexive Mapping At first glance,, let's assume that the goal is to allocate only those labels that contain a variant that is considered "preferred" in some way. As defined in the example, the code point U+3473 exists both as a variant of U+3447 and as a variant of itself (reflexive mapping). Assuming an original label of "U+3473 U+3447", the permuted variant "U+3473 U+3473" would consist of the reflexive variant of U+3473 followed by a variant of U+3447. Given the variant mappings as defined here, the types for both of the variant mappings used to generate that particular permutation would have the value "preferred": <char cp="3447" ref="0"> <var cp="3473" type="preferred" ref="1 3" /> </char> <char cp="3473" ref="0"> <var cp="3447" type="blocked" ref="1 3" /> <var cp="3473" type="preferred" ref="0" /> </char> Having established the variant types in this way, a set of actions could be defined that return a disposition of "allocatable" or "activated" for a label consisting exclusively of variants with type "preferred", for example. (For details on how to define actions based on variant types, see Section 8.) Another useful convention that uses reflexive variants is described below in Section 7.2.1. 5.3.5. Conditional Variants Fundamentally, variants are mappings between two sequences of code points. However, in some instances, for a variant relationship to exist, some context external to the code point sequence must also. As described in Section 5.2, an OPTIONAL "when" or "not-when" attribute may be given for any "var" element to specify required or prohibited contextual conditions under which the variant is defined. Assuming that> While a "var" element MUST NOT contain multiple conditions (it is only allowed a single "when" or "not-when" attribute), multiple "var" elements using the same mapping MAY be specified with different "when" or "not-when" attributes. The combination of mapping and conditional context defines a unique variant. For each variant label, care must be taken to ensure that at most one of the contextual conditions is met for variants with the same mapping; otherwise, duplicate variant labels would be created for the same input label. Any such duplicate variant labels MUST be treated as an error; see Section 8.4. Two contexts may be complementary, as in the following example, which shows ARABIC LETTER TEH MARBUTA (U+0629) as a variant of ARABIC LETTER HEH (U+0647), but with two different types. <char cp="0647" > <var cp="0629" not- <var cp="0629" when="arabic-final" type="allocatable" /> </char> The intent is that a label that uses U+0629 instead of U+0647 in a final position should be considered essentially the same label and, therefore, allocatable to the same entity, while the same substitution in a non-final position leads to labels that are different, but considered confusable, so that either one, but not both, should be delegatable. For symmetry, the reverse mappings must exist and must agree in their "when" or "not-when" attributes. However, symmetry does not apply to the other attributes. For example, these are potential; therefore, between them they implemented based on the joining contexts for Arabic code points. The mechanism defined here supports other forms of conditional variants that may be required by other scripts. 5.4. Annotations Two attributes, the "ref" and "comment" attributes, can be used to annotate individual elements in the LGR. They are ignored in machine-processing of the LGR. The "ref" attribute is intended for formal annotations and the "comment" attribute for free-form annotations. The latter can be applied more widely. 5.4.1. The "ref" Attribute Reference information MAY optionally be specified by a "ref" attribute consisting of a space-delimited sequence of reference identifiers (see Section 4.3.8). <char cp="5220" ref="0"> <var cp="5220" ref="5"/> <var cp="522A" 4.3.8). It is an error to repeat a reference identifier in the same "ref" attribute. It is RECOMMENDED that identifiers be listed in ascending order. In addition to "char", "range", and "var" elements in the "data" section, a "ref" attribute may be present for a number of element types contained in the "rules" element as described below: actions and literals ("char" inside a rule), as well as for definitions of rules and classes, but not for references to named character classes or rules using the "by-ref" attribute defined below. (The use of the "by-ref" and "ref" attributes is mutually exclusive.) None of the elements in the metadata take a "ref" attribute; to provide additional information, use the "description" element instead. 5, as well as definitions of classes and rules, but not on child elements of the "class" element. Finally, in the metadata, only the "version" and "reference" elements MAY have "comment" attributes (to match the syntax in [RFC3743]). 5 6.2.2) that can then be used in parameterized context or whole label rules (see Section 6.3.2). Each "tag" attribute MAY contain multiple values separated by white space. A tag value is an identifier that may also include certain punctuation marks, such as a colon. Formally, it MUST correspond to the XML 1.0 Nmtoken (Name token) production (see [XML] Section 2.3).. 6. Whole Label and Context Evaluation 6.1. Basic Concepts The "rules" element contains the specification of both context-based and whole label rules. Collectively, these are known as Whole Label Evaluation (WLE) rules (Section 6.3). The "rules" element also contains the character classes (Section 6.2) that they depend on, and any actions (Section 7) that assign dispositions to labels based on rules or variant mappings. A whole label rule is applied to the whole label. It is used to validate both original labels and any variant labels computed from them. A rule implementing a conditional context as discussed in Section 5.2 does not necessarily apply to the whole label but may be specific to the context around a single code point or code point sequence. Certain code points in a label sometimes need to satisfy context-based rules -- for example, for the label to be considered valid, or to satisfy the context for a variant mapping (see the description of the "when" attribute in Section 6.4).: - literal code points or code point sequences - character classes, which define sets of code points to be used for context comparisons - context operators, which define when character classes and literals may appear - nested rules, whether defined in place or invoked by reference Collectively, these are called "match operators" and are listed in Section 6.3.2. An LGR containing rules or match operators that - are incorrectly defined or nested, 2. have invalid attributes, or - have invalid or undefined attribute values MUST be rejected. Note that not all of the constraints defined here are validated by the schema. can be specified in several ways: - by defining the class via matching a tag in the code point data. All characters with the same "tag" attribute are part of the same class; - by referencing a value of one of the Unicode character properties defined in the Unicode Character Database; - by explicitly listing all the code points in the class; or - by defining the class as a set combination of any number of other classes."> 0061 4E00 </class> ... <rule> <class by- </rule> An empty "class" element with a "by-ref" attribute is a reference to an existing named class. The "by-ref" attribute MUST NOT. 6.2.2. Tag-Based Classes The "char" or "range" elements that are child elements of the "data" element MAY contain a "tag" attribute that consists of one or more space-separated tag values; for example: <char cp="0061" tag="letter lower"/> <char cp="4E00" tag="letter"/> a colon. Formally, they MUST correspond to the XML 1.0 Nmtoken production. While a "tag" attribute may contain a list of tag values, the "from-tag" attribute MUST always contain.. Unicode property values MUST be designated via a composite of the attribute name and value as defined for the property value in [UAX42], separated by a colon. Loose matching of property values and names as described in [UAX44] is not appropriate for an XML schema and is not supported; it is likewise not supported in the XML representation [UAX42] of the Unicode Character Database itself. A property-based class MAY be anonymous, or, when defined as an immediate child of the "rules" element, it MAY be named to relate a formal property definition to its usage, such as the use of the value 9 for ccc to designate a virama (or halant) in various scripts.].) All implementations processing LGR files SHOULD provide support for the following minimal set of Unicode properties: - General Category (gc) - Script (sc) - Canonical Combining Class (ccc) - Bidi Class (bc) - Arabic Joining Type (jt) - Indic Syllabic Category (InSC) - Deprecated (Dep) The short name for each property is given in parentheses. If a program that is using an LGR to determine the validity of a label encounters a property that it does not support, it MUST abort with an error. 6.2.4. Explicitly Declared Classes A class of code points may also be declared by listing all code points that are members; not doing so makes it unnecessarily difficult for users to detect errors such as duplicates or to compare and review these classes against other specifications. In a class definition, ranges of code points are represented by a hexadecimal> The contents of a class differ from a repertoire in that the latter MAY contain sequences as elements, while the former MUST NOT. Instead, they closely resemble character classes as found in regular expressions. 6.2.5. Combined Classes Classes may be combined using operators for set complement, union, intersection, difference (elements of the first class that are not in the second), and symmetric difference (elements in either class but not both). any of the match operator elements that allow child elements (see Section 6.3.2) by using the set combination as the outer element. 6.2.1). <rules> <union name="xxxyyy"> <class by- <class by- </union> ... </rules> Because (as for ordinary sets) a combination of classes is itself a class, no matter by what combinations of set operators a combined class is created, a reference to it always uses the "class" element as described in Section 6.2.1. That is, a named class is always referenced via an empty "class" element using the "by-ref" attribute containing the name of the class to be referenced. 6.3. Whole Label and Context Rules Each rule comprises a series of matching operators that must be satisfied in order to determine whether a label meets a given condition. Rules may reference other rules or character classes defined elsewhere in the table. 6.3.1. The "rule" Element A matching rule is defined by a "rule" element, the child elements of which are one of the match operators from Section 6.3.2. In evaluating a rule, each child element is matched in order. "rule" elements MAY be nested inside each other and inside certain match operators. A simple rule to match a label where all characters are members of some class called "preferred-codepoint": <rule name="preferred-label"> <start /> <class by- <end /> </rule> Rules are paired with explicit and implied actions, triggering these actions when a rule matches a label. For example, a simple explicit action for the rule shown above would be: <action disp="allocatable" match="preferred-label" /> The rule in this example would have the effect of setting the policy disposition for a label made up entirely of preferred code points to "allocatable". Explicit actions are further discussed in Section 7 and implicit actions in Section 7.5. Another use of rules is in defining conditional contexts for code points and variants as discussed in Sections 5.2 and 5.3.5. A rule that is an immediate child element of the "rules" element MUST be named using a "name" attribute containing a single identifier string with no spaces. A named rule may be incorporated into another rule by reference and may also be referenced by an "action" element, "when" attribute, or "not-when" attribute. If the "name" attribute is omitted, the rule is anonymous and MUST be nested inside another rule or match operator. 6.3.2. The Match Operators The child elements of a rule are a series of match operators, which are listed here by type and name and with a basic example or two. +------------+-------------+------------------------------------+ | 6.2.5) as well as references to named classes. All match operators shown as empty elements in the Examples column of the table above do not support child elements of their own; otherwise, match operators MAY be nested. In particular, anonymous "rule" elements can be used for grouping. 6.3.3. The "count" Attribute The OPTIONAL "count" attribute, when present, specifies the minimally required or maximal permitted number of times a match operator is used to match input. If the "count" attribute is n the match operator matches the input exactly n times, where n is 1 or greater.. A "count" attribute MUST NOT be applied to any element that contains a "name" attribute but MAY be applied to operators such as "class" that declare anonymous classes (including combined classes) or invoke any predefined classes by reference. The "count" attribute MUST NOT be applied to any "class" element, or element defining a combined class, when it is nested inside a combined class. A "count" attribute MUST NOT be applied to match operators of type "start", "end", "anchor", "look-ahead", or "look-behind" or to any operators, such as "rule" or "choice", that contain a nested instance of them. This limitation applies recursively and irrespective of whether a "rule" element containing these nested instances is declared in place or used by reference. However, the "count" attribute MAY be applied to any other instances of either an anonymous "rule" element or a "choice" element, including those instances nested inside other match operators. It MAY also be applied to the elements "any" and "char", when used as match operators. 6.3.4. The "name" and "by-ref" Attributes Like classes (see Section 6.2.1), rules declared as immediate child elements of the "rules" element MUST be named using a unique "name" attribute, and all other instances MUST NOT be named. Anonymous rules and classes or references complete definition has not been seen. In other words, it is explicitly not possible to define recursive rules or class definitions. The "by-ref" attribute MUST NOT appear in the same element as the "name" attribute or in an element that has any child elements. The example shows several named classes and a named rule referencing some of them by name. <class name="letter" property="gc:L"/> <class name="combining-mark" property="gc:M"/> <class name="digit" property="gc:Nd" /> <rule name="letter-grapheme"> <class by- <class by- </rule> 6.3.5. The "choice" Element The "choice" element is used to represent a list of two or more alternatives: <rule name="ldh"> <choice count="1+"> <class by- <class by- <char cp="002D" comment="literal HYPHEN"/> </choice> </rule> Each child element of a "choice" element represents one alternative. The first matching alternative determines the match for the "choice" element. To express a choice where an alternative itself consists of a sequence of elements, the sequence must be wrapped in an anonymous rule." attribute in addition to the "cp" attribute and OPTIONAL "comment" or "ref" attributes. No other attributes or child elements are permitted. 6.3.7. The "any" Element The "any" element is an empty element that matches any single code point. It MAY have a "count" attribute. For an example, see Section 6.3.9. Unlike a literal, the "any" element MUST NOT have a "ref" attribute. 6.3.8. The "start" and "end" Elements To match the beginning or end of a label, use the "start" or "end" element. An empty label would match this rule: <rule name="empty-label"> <start/> <end/> </rule> Conceptually, whole label" elements, to define a rule that requires that an entire label be well-formed. For this example, that means that it must start with a letter and that the first or last element to be matched, respectively, in matching a rule. "start" and "end" elements are empty elements that do not have a "count" attribute or any other attribute other than "comment". It is an error for any match operator enclosing a nested "start" or "end" element to have a "count" attribute. 6.3.9. Example Context Rule from IDNA Specification This is an example of the WLE rule from [RFC5892] forbidding the mixture of the Arabic-Indic and extended Arabic-Indic digits in the same label. It is implemented as a whole label rule associated with the code point ranges using the "not-when" attribute, which defines an impermissible context. The example also demonstrates several instances of the use of anonymous rules for grouping. <data> <range first- <range first- </data> <rules> <rule name="mixed-digits"> <choice> <rule> <class from- <any count="0+"/> <class from- </rule> <rule> <class from- <any count="0+"/> <class from- </rule> </choice> </rule> </rules> As specified in the example, a label containing a code point from either of the two digit ranges is invalid for any label matching the "mixed-digits" rule, that is, any time that a code point from the other range is also present. Note that invalidating the label is not the same as invalidating the definition of the "range" elements; in particular, the definition of the tag values does not depend on the "when" attribute. 6.4. Parameterized Context or When Rules To recap: When a rule is intended to provide a context for evaluating the validity of a code point or variant mapping, it is invoked by the "when" or "not-when" attributes described in Section 5.2. For "char" and "range" elements, an action implied by a context rule always has a disposition of "invalid" whenever the rule given by the "when" attribute is not matched (see Section 7.5). Conversely, a "not-when" attribute results in a disposition of "invalid" whenever the rule is matched. When a rule is used in this way, it is called a context or "when" rule. The example in the previous section shows a whole label rule used as a context rule, essentially making the whole label the context. The next sections describe several match operators that can be used to provide a more specific specification of a context, allowing a parameterized context rule. See Section 7 for an alternative method of defining an invalid disposition for a label not matching a whole label rule. 6.4.1. The "anchor" Element Such parameterized context rules are rules that contain a special placeholder represented by an "anchor" element. As each When Rule is evaluated, if an "anchor" element is present, it is replaced by a literal corresponding to the "cp" attribute of the element containing the "when" (or "not-when") attribute. The match to the "anchor" element must be at the same position in the label as the code point or variant mapping triggering the When Rule. For example, the Greek lower numeral sign is invalid if not immediately preceding a character in the Greek script. This is most naturally addressed with a parameterized instance and fail for the second. Unlike other rules, rules containing an "anchor" element MUST only be invoked via the "when" or "not-when" attributes on code points or variants; otherwise, their "anchor" elements cannot be evaluated. However, it is possible to invoke rules not containing an "anchor" element from a "when" or "not-when" attribute. (See Section 6.4.3.) The "anchor" element is an empty element, with no attributes permitted except "comment". in a rule. Here is an example of a rule that defines an "initial" context for an Arabic code point: (or context rule) is a named rule that. 6.4.3. Omitting the "anchor" Element If the "anchor" element is omitted, the evaluation of the context rule is not tied to the position of the code point or sequence associated with the "when" attribute. According to [RFC5892], the Katakana middle dot is invalid in any label not containing at least one Japanese character anywhere in the label. Because this requirement is independent of the position of the middle dot, the rule does not require an "anchor" element. be in one of these scripts, but the position of that code point is independent of the location of the middle dot; therefore, no anchor is required. (Note that the Katakana middle dot itself is of script Common, that is, "sc:Zyyy".) 7. The "action" Element The purpose of an action is to assign a disposition to a label in response to being triggered by the label meeting a specified condition. LGR 7.3.) 7.1. The "match" and "not-match" Attributes An OPTIONAL "match" or "not-match" attribute specifies a rule that must be matched or not matched as a condition for triggering an action. Only a single rule may be named as the value of a "match" or "not-match" attribute. Because rules may be composed of other rules, this restriction to a single attribute value does not impose any limitation on the contexts that can trigger an action. An action MUST NOT contain both a "match" and a "not-match" attribute, and the value of either attribute MUST be the name of a previously defined rule; otherwise, the document MUST be rejected. An action without any attributes is triggered by all labels unconditionally. For a very simple LGR, the following action would allocate all labels that match the repertoire: <action disp="allocatable" /> the rules are not affected by the disposition attributes of the variant mappings. To trigger any actions based on these dispositions requires the use of additional optional attributes for actions described next. 7.2. Actions with Variant Type Triggers 7.2.1. The "any-variant", "all-variants", and "only-variants" Attributes An action may contain one of the OPTIONAL attributes "any-variant", "all-variants", or "only-variants" defining triggers based on variant types. The permitted value for these attributes consists of one or more variant type values, separated by spaces. These MAY include type values that are not used in any "var" element in the LGR. When a variant label is generated, these variant type values are compared to the set of type values on the variant mappings used to generate the particular variant label (see Section 8). 5.3.4). <char cp="0078" comment="x"> <var cp="0078" type="allocatable" comment="reflexive" /> <var cp="0079" type="blocked" /> </char> <char cp="0079" comment="y"> <var cp="0078" type="allocatable" /> </char> ... <action disp="blocked" any- <action disp="allocatable" only- <action disp="some-disp" any- In the example above, the label "xx" would have variant labels "xx", "xy", "yx", and "yy". The first action would result in blocking any variant label containing "y", because the variant mapping from "x" to "y" is of type "blocked", triggering the "any-variant" condition. Because in this example "x" has a reflexive variant mapping to itself of type "allocatable", the original label "xx" has a reflexive variant "xx" that would trigger the "only-variants" condition on the second action. A label "yy" would have the variants "xy", "yx", and "xx". Because the variant mapping from "y" to "x" is of type "allocatable" and a mapping from "y" to "y" is not defined, the labels "xy" and "yx" trigger the "any-variant" condition on the third label. The variant "xx", being generated using the mapping from "y" to "x" of type "allocatable",-variant" trigger with reflexive variant mappings (Section 5.3: <char cp="0570" comment="ARMENIAN SMALL LETTER HO"> <var cp="0068" type="blocked" comment="LATIN SMALL LETTER H" /> <var cp="04BB" type="blocked" comment="CYRILLIC SMALL LETTER SHHA" /> < 8). 7.2.2. Example from Tables in the Style of RFC 3743 This section gives an example of using variant type triggers, combined with variants with reflexive mappings (Section 5.3.4), to achieve LGRs that implement tables like those defined according to [RFC3743] where the goal is to allow as variants only labels that consist entirely of simplified or traditional variants, in addition to the original label. This example assumes an LGR where all variants have been given suitable "type" attributes of "blocked", "simplified", "traditional", or "both", similar to the ones discussed in Appendix B. Given such an LGR, the following example actions evaluate the disposition for the variant label: <action disp="blocked" any- <action disp="allocatable" only- <action disp="allocatable" only- <action disp="blocked" all- <action disp="allocatable" /> The first action matches any variant label for which at least one of the code point variants is of type "blocked". 5.3.4). The final two actions rely on the fact that actions are evaluated in sequence and that the first action triggered also defines the final disposition for a variant label (see Section "blocked". There are exceptions where the assumption on reflexive mappings made above does not hold, so this basic scheme needs some refinements to cover all cases. For a more complete example, see Appendix B. 7.3. Recommended Disposition Values The precise nature of the policy action taken in response to a disposition and the name of the corresponding "disp" attributes are only partially defined here. It is strongly RECOMMENDED to use the following dispositions only in their conventional sense. invalid The resulting string is not a valid label. This disposition may be assigned implicitly; see Section 7.5. No variant labels should be generated from a variant mapping with this type. blocked The resulting string is a valid label but should be blocked from registration. This would typically apply for a derived variant that is undesirable due to having no practical use or being confusingly similar to some other label. allocatable The resulting string should be reserved for use by the same operator of the origin string but not automatically allocated for use. activated The resulting string should be activated for use. (This is the same as a Preferred Variant [RFC3743].) valid The resultant string is a valid label. (This is the typical default action if no dispositions are defined.) 7.4. Precedence Actions are applied in the order of their appearance in the file. This defines their relative precedence. The first action triggered by a label defines the disposition for that label. To define the order of precedence, list the actions in the desired order. The conventional order of precedence for the actions defined in Section 7.3 is "invalid", "blocked", "allocatable", "activated", and then "valid". This default precedence is used for the default actions defined in Section 7.6. 7.5. Implied Actions The context rules on code points ("not-when" or "when" rules) carry an implied action with a disposition of "invalid" (not eligible) if a "when" context is not satisfied or a "not-when" context is matched, respectively. These rules are evaluated at the time the code points for a label or its variant labels are checked for validity (see Section 8). In other words, they are evaluated before any of the actions are applied, and with higher precedence. The context rules for variant mappings are evaluated when variants are generated and/or when variant tables are made symmetric and transitive. They have an implied action with a disposition of "invalid", which means that. 7.6. Default Actions If a label does not trigger any of the actions defined explicitly in the LGR, the following implicitly defined default actions are evaluated. They are shown below in their relative order of precedence (see Section 7.4). Default actions have a lower order of precedence than explicit actions (see Section 8.3). The default actions for variant labels are defined as follows. The first set is triggered based on the standard variant type values of "invalid", "blocked", "allocatable", and "activated": <action disp="invalid" any- <action disp="blocked" any- <action disp="allocatable" any- <action disp="activated" all- A final default action sets the disposition to "valid" for any label matching the repertoire for which no other action has been triggered. This "catch-all" action also matches all remaining variant labels from variants that do not have a type value. <action disp="valid" comment="Catch-all if other rules not met"/> Conceptually, the implicitly defined default actions act just like a block of "action" elements that is added (virtually) beyond the last of the user-supplied actions. Any label not processed by the user-supplied actions would thus be processed by the default actions as if they were present in the LGR. As the last default action is a "catch-all", all processing is guaranteed to end with a definite disposition for the label. 8. Processing a Label against an LGR 8.1. Determining Eligibility for a Label In order to test a given label for membership in the LGR, a consumer of the LGR must iterate through each code point within a given label and test that each instance of a code point is a member of the LGR. If any instance of a code point is not a member of the LGR, the label shall be deemed invalid. An individual instance of a code point is deemed a member of the LGR when it is listed using a "char" element, or is part of a range defined with a "range" element, and all necessary conditions in any "when" or "not-when" attributes are correctly satisfied for that instance. Alternatively, an instance of a code point is also deemed a member of the LGR when it forms part of a sequence that corresponds to a sequence listed using a "char" element for which the "cp" attribute defines a sequence, and all necessary conditions in any "when" or "not-when" attributes are correctly satisfied for that instance of the sequence. In determining eligibility, at each position the longest possible sequence of code points is evaluated first. If that sequence matches a sequence defined in the LGR and satisfies any required context at that position, the instances of its constituent code points are deemed members of the LGR and evaluation proceeds with the next code point following the sequence. If the sequence does not match a defined sequence or does not satisfy the required context, successively shorter sequences are evaluated until only a single code point remains. The eligibility of that code point is determined as described above for an individual code point instance. A label must also not trigger any action that results in a disposition of "invalid"; otherwise, it is deemed not eligible. (This step may need to be deferred until variant code point dispositions have been determined.) 8.1.1. Determining Eligibility Using Reflexive Variant Mappings For LGRs that contain reflexive variant mappings (defined in Section 5.3.4), the final evaluation of eligibility for the label must be deferred until variants are generated. In essence, LGRs that use this feature treat the original label as the (identity) variant of itself. For such LGRs, the ordinary determination of eligibility described here is but a first step that generally excludes only a subset of invalid labels. To further check the validity of a label with reflexive mappings, it is not necessary to generate all variant labels. Only a single variant needs to be created, where any reflexive variants are applied for each code point, and the label disposition is evaluated (as described in Section 8.3). A disposition of "invalid" results in the label being not eligible. (In the exceptional case where context rules are present on reflexive mappings, multiple reflexive variants may be defined, but for each original label, at most one of these can be valid at each code position. However, see Section 8.4.) 8 rules are satisfied as follows: - Create each possible permutation of a label by substituting each code point or code point sequence in turn by any defined variant mapping (including any reflexive mappings). - Apply variant mappings with "when" or "not-when" attributes only if the conditions are satisfied; otherwise, they are not defined. - Record each of the "type" values on the variant mappings used in creating a given variant label in a disposition set; for any unmapped code point, record the "type" value of any reflexive variant (see Section 5.3.4). - Determine the disposition for each variant label per Section 8.3. - If the disposition is "invalid", remove the label from the set. - If final evaluation of the disposition for the unpermuted label per Section 8.3 results in a disposition of "invalid", remove all associated variant labels from the set. The number of potential permutations can be very large. In practice, implementations would use suitable optimizations to avoid having to actually create all permutations (see Section 8.5). In determining the permuted set of variant labels in step (1) above, all eligible partitions into sequences must be evaluated. A label "ab" that matches a sequence "ab" defined in the LGR but also matches the sequence of individual code points "a" and "b" (both defined in the LGR) must be permuted using any defined variant mappings for both the sequence "ab" and the code points "a" and "b" individually. 8.3. Determining a Disposition for a Label or Variant Label For a given label (variant or original), its disposition is determined by evaluating, in order of their appearance, all actions for which the label or variant label satisfies the conditions. - For any label that contains code points or sequences not defined in the repertoire, or does not satisfy the context rules on all of its code points and variants, the disposition is "invalid". - For all other labels, the disposition is given by the value of the "disp" attribute for the first action triggered by the label. An action is triggered if all of the following are true: - the label matches the whole label rule given in the "match" attribute for that action; - the label does not match the whole label rule given in the "not-match" attribute for that action; - any of the recorded variant types for a variant label match the types given in the "any-variant" attribute for that action; - all of the recorded variant types for a variant label match the types given in the "all-variants" or "only-variants" attribute given for that action; - in case of an "only-variants" attribute, the label contains only code points that are the target of applied variant mappings; or - the action does not contain any "match", "not-match", "any-variant", "all-variants", or "only-variants" attributes: catch-all. - For any remaining variant label, assign the variant label the disposition using the default actions defined in Section 7.6. For this step, variant types outside the predefined recommended set (see Section 7.3) are ignored. - For any remaining label, set the disposition to "valid". 8.4. Duplicate Variant Labels For a poorly designed LGR, it is possible to generate duplicate variant labels from the same input label, but with different, and potentially conflicting, dispositions. Implementations MUST treat any duplicate variant labels encountered as an error, irrespective of their dispositions. This situation can arise in two ways. One is described in Section 5.3.5 and involves defining the same variant mapping with two context rules that are formally distinct but nevertheless overlap so that they are not mutually exclusive for the same label. The other case involves variants defined for sequences, where one sequence is a prefix of another (see Section 5.3.1). The following shows such an example resulting in conflicting reflexive variants: <char cp="0061"> <var cp="0061" type="allocatable"/> </char> <char cp="0062"/> <char cp="0061 0062"> <var cp="0061 0062" type="blocked"/> </char> A label "ab" would generate the variant labels "{a}{b}" and "{ab}" where the curly braces show the sequence boundaries as they were applied during variant mapping. The result is a duplicate variant label "ab", one based on a variant of type "allocatable" plus an original code point "b" that has no variant, and another one based on a single variant of type "blocked", thus creating two variant labels with conflicting dispositions. In the general case, it is difficult to impossible to prove by mechanical inspection of the LGR that duplicate variant labels will never occur, so implementations have to be prepared to detect this error during variant label generation. The condition is easily avoided by careful design of context rules and special attention to the relation among code point sequences with variants. 8.5. Checking Labels for Collision The obvious method for checking for collision between labels is to generate the fully permuted set of variants for one of them and see whether it contains the other label as a member. As discussed above, this can be prohibitive and is not necessary. Because of symmetry and transitivity, all variant mappings form disjoint sets. In each of these sets, the source and target of each mapping are also variants of the sources and targets of all the other mappings. However, members of two different sets are never variants of each other. If two labels have code points at the same position that are members of two different variant mapping sets, any variant labels of one cannot be variant labels of the other: the sets of their variant labels are likewise disjoint. Instead of generating all permutations to compare all possible variants, it is enough to find out whether code points at the same position belong to the same variant set or not. For that, it is sufficient to substitute an "index" mapping that identifies the set. This index mapping could be, for example, the variant mapping for which the target code point (or sequence) comes first in some sorting order. This index mapping would, in effect, identify the set of variant mappings for that position. To check for collision then means generating a single variant label from the original by substituting the respective "index" value for each code point. This results in an "index label". Two labels collide whenever the index labels for them are the same. 9. Conversion to and from Other Formats Both [RFC3743] and [RFC4290] provide different grammars for IDN tables. The formats in those documents are unable to fully support the increased requirements of contemporary IDN variant policies. This specification is a superset of functionality provided by the older IDN table formats; thus, any table expressed in those formats can be expressed in this new format. Automated conversion can be conducted between tables conformant with the grammar specified in each document. For notes on how to translate a table in the style of RFC 3743, see Appendix B. 10. Media Type Well-formed LGRs that comply with this specification SHOULD be transmitted with a media type of "application/lgr+xml". This media type will signal to an LGR-aware client that the content is designed to be interpreted as an LGR. 11. IANA Considerations IANA has completed the following actions: 11.1. Media Type Registration The media type "application/lgr+xml" has been registered to denote transmission of LGRs that are compliant with this specification, in accordance with [RFC6838]. Type name: application Subtype name: lgr+xml Required parameters: N/A Optional parameters: charset (as for application/xml per [RFC7303]) Security considerations: See the security considerations for application/xml in [RFC7303] and the specific security considerations for Label Generation Rulesets (LGRs) in RFC 7940 Interoperability considerations: As for application/xml per [RFC7303] Published specification: See RFC 7940 Applications that use this media type: Software using LGRs for international identifiers, such as IDNs, including registry applications and client validators. Additional information: Deprecated alias names for this type: N/A Magic number(s): N/A File extension(s): .lgr Macintosh file type code(s): N/A Person & email address to contact for further information: Kim Davies <kim.davies@icann.org> Asmus Freytag <asmus@unicode.org> Intended usage: COMMON Restrictions on usage: N/A Author: Kim Davies <kim.davies@icann.org> Asmus Freytag <asmus@unicode.org> Change controller: IESG Provisional registration? (standards tree only): No 11.2. URN Registration This specification uses a URN to describe the XML namespace, in accordance with [RFC3688]. URI: urn:ietf:params:xml:ns:lgr-1.0 Registrant Contact: See the Authors of this document. XML: None. 11.3. Disposition Registry This document establishes a vocabulary of "Label Generation Ruleset Dispositions", which has been reflected as a new IANA registry. This registry is divided into two subregistries: - Standard Dispositions - This registry lists dispositions that have been defined in published specifications, i.e., the eligibility for such registrations is "Specification Required" [RFC5226]. The initial set of registrations are the five dispositions in this document described in Section 7.3. - Private Dispositions - This registry lists dispositions that have been registered "First Come First Served" [RFC5226] by third parties with the IANA. Such dispositions must take the form "entity:disposition" where the entity is a domain name that uniquely identifies the private user of the namespace. For example, "example.org:reserved" could be a private extension used by the example organization to denote a disposition relating to reserved labels. These extensions are not intended to be interoperable, but registration is designed to minimize potential conflicts. It is strongly recommended that any new dispositions that require interoperability and have applicability beyond a single organization be defined as Standard Dispositions. In order to distinguish them from Private Dispositions, Standard Dispositions MUST NOT contain the ":" character. All disposition names shall be in lowercase ASCII. The IANA registry provides data on the name of the disposition, the intended purposes, and the registrant or defining specification for the disposition. 12. Security Considerations 12.1. LGRs Are Only a Partial Remedy for Problem Space Substantially unrestricted use of non-ASCII characters in security- relevant identifiers such as domain name labels may cause user confusion and invite various types of attacks. In many languages, in particular those using complex or large scripts, an attacker has an opportunity to divert or confuse users as a result of different code points with identical appearance or similar semantics. The use of an LGR provides a partial remedy for these risks by supplying a framework for prohibiting inappropriate code points or sequences from being registered at all and for permitting "variant" code points to be grouped together so that labels containing them may be mutually exclusive or registered only to the same owner. In addition, by being fully machine processable the format may enable automated checks for known weaknesses in label generation rules. However, the use of this format, or compliance with this specification, by itself does not ensure that the LGRs expressed in this format are free of risk. Additional approaches may be considered, depending on the acceptable trade-off between flexibility and risk for a given application. One method of managing risk may involve a case-by-case evaluation of a proposed label in context with already-registered labels -- for example, when reviewing labels for their degree of visual confusability. 12.2. Computational Expense of Complex Tables A naive implementation attempting to generate all variant labels for a given label could lead to the possibility of exhausting the resources on the machine running the LGR processor, potentially causing denial-of-service consequences. For many operations, brute-force generation can be avoided by optimization, and if needed, the number of permuted labels can be estimated more cheaply ahead of time. The implementation of WLE rules, using certain backtracking algorithms, can take exponential time for pathological rules or labels and exhaust stack resources. This can be mitigated by proper implementation and enforcing the restrictions on permissible label length., <>. [UAX42] The Unicode Consortium, "Unicode Character Database in XML", May 2016, <>. [Unicode-Stability] - The Unicode Consortium, "Unicode Encoding Stability Policy, Property Value Stability", April 2015, < stability_policy.html#Property_Value>. [Unicode-Versions] - The Unicode Consortium, "Unicode Version Numbering", June 2016, <>. [XML] Bray, T., Paoli, J., Sperberg-McQueen, M., Maler, E., and F. Yergeau, "Extensible Markup Language (XML) 1.0 (Fifth Edition)", World Wide Web Consortium, November 2008, <>. 13.2. Informative References [ASIA-TABLE] - DotAsia Organisation, ".ASIA ZH IDN Language Table", February 2012, <>. [LGR-PROCEDURE] - Internet Corporation for Assigned Names and Numbers, "Procedure to Develop and Maintain the Label Generation Rules for the Root Zone in Respect of IDNA Labels", December 2012, < draft-lgr-procedure-07dec12-en.pdf>. [RELAX-NG] The Organization for the Advancement of Structured - Information Standards (OASIS), "RELAX NG Compact Syntax", November 2002, < relax-ng/compact-20021121.html>. [RFC3688] Mealling, M., "The IETF XML Registry", BCP 81, RFC 3688, DOI 10.17487/RFC3688, January 2004, <>. 4290] Klensin, J., "Suggested Practices for Registration of Internationalized Domain Names (IDN)", RFC 4290, DOI 10.17487/RFC4290, December 2005, <>. [RFC5226] Narten, T. and H. Alvestrand, "Guidelines for Writing an IANA Considerations Section in RFCs", BCP 26, RFC 5226, DOI 10.17487/RFC5226, May 2008, <>. [RFC5564] El-Sherbiny, A., Farah, M., Oueichek, I., and A. Al-Zoman, "Linguistic Guidelines for the Use of the Arabic Language in Internet Domains", RFC 5564, DOI 10.17487/RFC5564, February, <>. [TDIL-HINDI] - Technology Development for Indian Languages (TDIL) Programme, "Devanagari Script Behaviour for Hindi Ver2.0", < resourceDetails&toolid=1625&lang=en>. [UAX44] The Unicode Consortium, "Unicode Character Database", June 2016, <>. [WLE-RULES] - Internet Corporation for Assigned Names and Numbers, "Whole Label Evaluation (WLE) Rules", August 2016, < attachments/43989034/WLE-Rules.pdf>. Appendix A. Example Tables The following presents a minimal LGR table defining the lowercase LDH (letters, digits, hyphen) repertoire and containing no rules or> In practice, any LGR that includes the hyphen might also contain rules invalidating any labels beginning with a hyphen, ending with a hyphen, and containing consecutive hyphens in the third and fourth positions as required by [RFC5891]. <?xml version="1.0" encoding="utf-8"?> <lgr xmlns="urn:ietf:params:xml:ns:lgr-1.0"> <data> <char cp="002D" not- <range first- <range first- </data> <rules> <rule name="hyphen-minus-disallowed" comment="RFC5891 restrictions on U+002D"> <choice> <rule comment="no leading hyphen"> <look-behind> <start /> </look-behind> <anchor /> </rule> <rule comment="no trailing hyphen"> <anchor /> <look-ahead> <end /> </look-ahead> </rule> <rule comment="no consecutive hyphens in third and fourth positions"> <look-behind> <start /> <any /> <any /> <char cp="002D" comment="hyphen-minus" /> </look-behind> <anchor /> </rule> </choice> </rule> </rules> <> <scope type="domain">example.com</scope> 9.0</reference> <reference id="1" >RFC 5892</reference> <reference id="2" >Big-5: Computer Chinese Glyph and Character Code Mapping Table, Technical Report="blocked" ref="2" /> <var cp="534B" type="allocatable" ref="2" /> </char> <char cp="4E17" ref="0"> <var cp="4E16" type="allocatable" ref="2" /> <var cp="534B" type="allocatable" ref="2" /> </char> <char cp="534B" ref="0"> <var cp="4E16" type="allocatable" ref="2" /> <var cp="4E17" type="blocked" ref="2" /> </char> </data> <!-- Context and whole label rules --> <rules> <!-- Require the given code point to be between two 006C code points --> <rule name="catalan-middle-dot" ref="0"> <look-behind> <char cp="006C" /> </look-behind> <anchor /> <look-ahead> <char cp="006C" /> </look-ahead> </rule> <!--="invalid" match="three-or-more-consonants" /> <action disp="blocked" any- <action disp="allocatable" all- </rules> </lgr> Appendix B. How to Translate Tables Based on RFC 3743 into the XML Format As background, the rules specified in [RFC3743] work as follows: - The original (requested) label is checked to make sure that all the code points are a subset of the repertoire. - If it passes the check, the original label is allocatable. -: - Block all variant labels containing at least one blocked variant. - Allocate all labels that consist entirely of variants that are "simp" or "both". - Also allocate all labels that are entirely "trad" or "both". - Block all surviving labels containing any one of the dispositions "simp" or "trad" or "both", because they are now known to be part of an undesirable mixed simplified/traditional label. -. - asmus@unicode.org
http://pike.lysator.liu.se/docs/ietf/rfc/79/rfc7940.xml
CC-MAIN-2021-43
refinedweb
11,661
51.38
Important: Please read the Qt Code of Conduct - How to import the "latest" versions of QtQuick.Controls and QtQuick.Controls.Styles? I'm having trouble figuring out which versions of QtQuick.Controls and QtQuick.Controls.Styles I should be importing. I'd like to just use the "latest" version of each - but it seems that it isn't that simple. I have Qt v5.7 installed. Below is a slightly simplified version of my QML file. import QtQuick 2.5 import QtQuick.Controls 2.0 import QtQuick.Controls.Styles 1.4 Item { Column { id: column anchors.fill: parent TextField { id: textField height: 37 style: TextFieldStyle { textColor: "black" background: Rectangle { color: "white" border.color: "black" border.width: 1 } } } } } I'm importing versions 2.0 and 1.4 respectively, as these appear to be the latest versions of these two modules - at least, they are the latest version numbers that are offered up by the auto-completion in Qt Creator. However, this code produces a red "error" underline on the "style" property. Hovering over it shows: 'Invalid property name: "style". (M16).' At runtime, attempting to load this QML file produces the error 'Cannot assign to non-existent property "style" '. I'm pretty sure this error is occurring because the version numbers (2.0 and 1.4) do not match. As another variation, I tried this: import QtQuick.Controls 2.0 import QtQuick.Controls.Styles 2.0 I didn't expect this to work, since the latest version of the Styles module that the designer knows about is 1.4, but I thought I would try it. As expected, this also produces a red error underline in the designer, and at runtime produces the error 'module "QtQuick.Controls.Styles" version 2.0 is not installed'. The only way I can get this to work is to use: import QtQuick.Controls 1.4 import QtQuick.Controls.Styles 1.4 However, I'm then limited to the feature set of QtQuick.Controls 1.4, and can't use any 2.0 features - for example, I can't use the Label.topPadding property (which I want to use elsewhere in this file), as it isn't supported by QtQuick.Controls 1.4. All I really want to do is to import QtQuick.Control 2.0, and be able to apply a style to a TextField - but I'm stumped as to how I can do this. Any advice or suggestions would be much appreciated. In Qt Quick Controls 2, there is no such property as TextField::style. In general, there is no way to use the style objects from Qt Quick Controls 1 with Qt Quick Controls 2. The APIs between the two major versions of Qt Quick Controls are not compatible. See the following documentation pages for more details: There is a reason why we ended up breaking the APIs and creating a new major version. In short, there is no way to make the heavily Loader-based architecture of Qt Quick Controls 1 to perform reasonably well. Therefore all that dynamic loading of Components was ditched in Qt Quick Controls 2. The delegates that used to be provided by a style object are now part of the control instead, instantiated "in place". In essence: TextField { style: TextFieldStyle { textColor: "white" background: Rectangle { color: "black" } } } vs. TextField { color: "white" background: Rectangle { color: "black" } } You can read more about the history in. For example, highlights the fundamental structural changes in Qt Quick Controls 2. Thanks J-P, that's exactly what I needed to know! I think I found an old example online that used the 1.x approach to styling, then tried to combine that with 2.x controls - and got myself in a tangle. I now understand how styling is meant to be applied in 2.x, and it's working just fine for me.
https://forum.qt.io/topic/69615/how-to-import-the-latest-versions-of-qtquick-controls-and-qtquick-controls-styles
CC-MAIN-2021-31
refinedweb
640
69.28
Euler problems/111 to 120 From HaskellWiki 1 Problem 111 Search for 10-digit primes containing the maximum number of repeated digits. Solution: import Control.Monad (replicateM) -- All ways of interspersing n copies of x into a list intr :: Int -> a -> [a] -> [[a]] intr 0 _ y = [y] intr n x (y:ys) = concat [map ((replicate i x ++) . (y :)) $ intr (n-i) x ys | i <- [0..n]] intr n x _ = [replicate n x] -- All 10-digit primes containing the maximal number of the digit d maxDigits :: Char -> [Integer] maxDigits d = head $ dropWhile null [filter isPrime $ map read $ filter ((/='0') . head) $ concatMap (intr (10-n) d) $ replicateM n $ delete d "0123456789" | n <- [1..9]] problem_111 = sum $ concatMap maxDigits "0123456789" 2 Problem 112 Investigating the density of "bouncy" numbers. Solution: import Data.List isIncreasing x = show x == sort (show x) isDecreasing x = reverse (show x) == sort (show x) isBouncy x = not (isIncreasing x) && not (isDecreasing x) findProportion prop = snd . head . filter condition . zip [1..] where condition (a,b) = a >= prop * fromIntegral b problem_112 = findProportion 0.99 $ filter isBouncy [1..] 3 Problem 113 How many numbers below a googol (10100) are not "bouncy"? Solution: import Array mkArray b f = listArray b $ map f (range b) digits = 100 inc = mkArray ((1, 0), (digits, 9)) ninc dec = mkArray ((1, 0), (digits, 9)) ndec ninc (1, _) = 1 ninc (l, d) = sum [inc ! (l-1, i) | i <- [d..9]] ndec (1, _) = 1 ndec (l, d) = sum [dec ! (l-1, i) | i <- [0..d]] problem_113 = sum [inc ! i | i <- range ((digits, 0), (digits, 9))] + sum [dec ! i | i <- range ((1, 1), (digits, 9))] - digits*9 -- numbers like 11111 are counted in both inc and dec - 1 -- 0 is included in the increasing numbers Note: inc and dec contain the same data, but it seems clearer to duplicate them. it is another way to solution this problem: binomial x y =div (prodxy (y+1) x) (prodxy 1 (x-y)) prodxy x y=product[x..y] problem_113=sum[binomial (8+a) a+binomial (9+a) a-10|a<-[1..100]] 4 Problem 114 Investigating the number of ways to fill a row with separated blocks that are at least three units long. Solution: -- fun in p115 problem_114=fun 3 50 5 Problem 115 Finding a generalisation for the number of ways to fill a row with separated blocks. Solution: binomial x y =div (prodxy (y+1) x) (prodxy 1 (x-y)) prodxy x y=product[x..y] fun m n=sum[binomial (k+a) (k-a)|a<-[0..div (n+1) (m+1)],let k=1-a*m+n] problem_115 = (+1)$length$takeWhile (<10^6) [fun 50 i|i<-[1..]] 6 Problem 116 Investigating the number of ways of replacing square tiles with one of three coloured tiles. Solution: binomial x y =div (prodxy (y+1) x) (prodxy 1 (x-y)) prodxy x y=product[x..y] f116 n x=sum[binomial (a+b) a|a<-[1..div n x],let b=n-a*x] p116 x=sum[f116 x a|a<-[2..4]] problem_116 = p116 50 7 Problem 117 Investigating the number of ways of tiling a row using different-sized tiles. Solution: fibs5 = 0 : 0 :1: 1:zipWith4 (\a b c d->a+b+c+d) fibs5 a1 a2 a3 where a1=tail fibs5 a2=tail a1 a3=tail a2 p117 x=fibs5!!(x+2) problem_117 = p117 50 8 Problem 118 Exploring the number of ways in which sets containing prime elements can be made. Solution: digits = ['1'..'9'] -- possible partitions voor prime number sets -- leave out patitions with more than 4 1's -- because only {2,3,5,7,..} is possible -- and the [9]-partition because every permutation of all -- nine digits is divisable by 3 test xs |len>4=False |xs==[9]=False |otherwise=True where len=length $filter (==1) xs parts = filter test $partitions 9 permutationsOf [] = [[]] permutationsOf xs = [x:xs' | x <- xs, xs' <- permutationsOf (delete x xs)] combinationsOf 0 _ = [[]] combinationsOf _ [] = [] combinationsOf k (x:xs) = map (x:) (combinationsOf (k-1) xs) ++ combinationsOf k xs priemPerms [] = 0 priemPerms ds = fromIntegral . length . filter (isPrime . read) . permutationsOf $ ds setsums [] 0 = [[]] setsums [] _ = [] setsums (x:xs) n | x > n = setsums xs n | otherwise = map (x:) (setsums (x:xs) (n-x)) ++ setsums xs n partitions n = setsums (reverse [1..n]) n fc :: [Integer] -> [Char] -> Integer fc (p:[]) ds = priemPerms ds fc (p:ps) ds = sum [np y * fc ps (ds \\ y) | y <- combinationsOf p ds, np y /= 0] where np = priemPerms -- here is the 'imperfection' correction method: -- make use of duplicate reducing factors for partitions -- with repeating factors, f.i. [1,1,1,1,2,3]: -- in this case 4 1's -> factor = 4! -- or for [1,1,1,3,3] : factor = 3! * 2! dupF :: [Integer] -> Integer dupF = product . map (product . enumFromTo 1 . fromIntegral . length) . group main = do print . sum . map (\x -> fc x digits `div` dupF x) $ parts problem_118 = main 9 Problem 119 Investigating the numbers which are equal to sum of their digits raised to some power. Solution: import Data.List digits n {- 123->[3,2,1] -} |n<10=[n] |otherwise= y:digits x where (x,y)=divMod n 10 problem_119 =sort [(a^b)| a<-[2..200], b<-[2..9], let m=a^b, let n=sum$digits m, n==a]!!29 10 Problem 120 Finding the maximum remainder when (a − 1)n + (a + 1)n is divided by a2. Solution: fun m=div (m*(8*m^2-3*m-5)) 3 problem_120 = fun 500 I have no idea what the above solution has to do with this problem, even though it produces the correct answer. I suspect it is some kind of red herring. Below you will find a more holy mackerel approach, based on the observation that: 1. (a-1)n + (a+1)n = 2 if n is odd, and 2an if n is even (mod a2) 2. the maximum of 2an mod a2 occurs when n = (a-1)/2 I hope this is a little more transparent than the solution proposed above. Henrylaxen Mar 5, 2008 maxRemainder n = 2 * n * ((n-1) `div` 2) problem_120 = sum $ map maxRemainder [3..1000]
https://wiki.haskell.org/index.php?title=Euler_problems/111_to_120&oldid=33822
CC-MAIN-2015-18
refinedweb
1,019
63.39
She had been a singer and strongly identified her self with her voice, she wanted to be able to use a speech synthesis system that had her own voice pattern. Apologies if this was already mentioned, but it seems to be a use others here hadn't considered. Good job, team Lyrebird. My feedback is that while the inclusion of ethics page is great, it could do with more content on your vision and what you will not let your tech be used for. I know others can develop similar tech, but it will be good to read about YOUR ethics. [Edited for clarity] 1. Open source voice-copying software 2. At worst, create entire market of voice-fraudsters, at best, very few voice-fraudsters but very high and very real perception of fear of such 3. Become leading security experts in voice fraud detection 4. Sell software / time / services to intelligence agencies, governments, law enforcement, news networks Ethically I'm a bit concerned with (2), but realistically the team is right --- this technology exists, it will certainly be used for good and for bad, and they're positioning themselves as the leading experts. I'm interested to see which VCs and acquirers line up here. Applying a voice to any phrase seems useful for voice assistants (Amazon Alexa, Google Home) but I don't think that's the $B model. For the examples given for various intonations from Obama/Trump, some intonations are much more natural than others. It would be interesting to decide how to parametrize a sentence for the intended intonation. (based on word2vec analysis of the words in the sentence, punctuation cues in the sentence, and perhaps a specified category of "emotional delivery"). It would be interesting at the sentence-level, but also at the macro speech-level to include the right "mix" of intonations for a specific context. On a related note, it would be interesting to study the patterns of intonations in successful vs unsuccessful outbound sales calls, for example, to learn how to best simulate a good human sales voice. Update:Reading changelogs before deployment never sounded better! If you thought fake news was bad before wait until these 'secret' recordings start getting released and reported on. 2. Is this better then what Google or Baidu are doing? 3. I remember reading Adobe has something similar. 4. Why ( What happened ) that all of a sudden we have 4 company making voice breakthrough tech like these? 5. What Happen to Voice Acting? Places like Japan where they highly value voice actor. Is Voice even patentable? How difficult is it to create/tune voices from parameters rather than training from an audio clip? I build software where people create fictional characters for writing, and having an author "create" voices for each character would be an amazing way to autogenerate audiobooks with their voices, or interact with those characters by voice, or just hear things written from their point of view in their voice for that extra immersion. Having an author upload voice clips of themselves mimicking what they think that character should sound like, but probably would keep traces of their original voice (and feel "fake" to them because they can recognize their own voice), no? Can't wait to see how this pans out. Signed up for the beta and will definitely be pushing it to its limits when it's ready. :) I built a toy concatenative Donald Trump speech system [1], but I don't have an ML background. I've been taking Andrew Ng's online course in addition to Udacity's deep learning program in an attempt to learn the basics. I'm hoping I can use my dataset to build something backed by ML that sounds better. Is anyone in the Atlanta area interested in ML? I'd love to chat over coffee or join local ML interest groups.... But, you can certainly see where this is going and that's the worrisome part. The samples weren't that convincing to me, but could probably be used to switch a word here and there. That may be enough.] I love this book. What's the best way to learn a mathematical field? To discover it yourself, piece by piece! I wish this were a series. [1]: Time spent learning Calculus is worthwhile; and if nothing else, understand the fundamental theorem. Overwhelmingly impressive. Well. Now I have to read the whole thing I guess..... What one fool can do, another can. -Ancient Simian Proverb Monkey see, monkey do?... the original is French, the Author Gustave Bessiere was an engineer, mathematician and inventor:... I don't think they are (yet) copyright free,. Oh, what's that... you can't just republish instantly because electronic computers haven't been invented yet? Well, just iterate and do things that don't scale :) Sources: > The number should preferably be in the range 1-255 so thatit can be used in the WKS field in name servers. Well-known service (WKS) records let hosts advertise in DNS which services a given machine made available, by listing which of the assigned port numbers were open for TCP or UDP connections. This never really caught on, as few people used them, even fewer kept them up to date, and checking WKS provided very little real benefit over just attempting a connection. They had been deprecated already in 1989 through RFC 1123 [1], but it seems that by the mid-1990s at least some people still considered them relevant. author (Tatu Ylonen) sent an email to Joyce K. Reynolds at IANA, on release of v.1.0 of SSH protocol, and IANA agreed to assign port 22. That's kinda it. A summary of SSH use follows the story which is a good overview for someone new to it. While I grew up with computers, when Internet got to the first homes like mine, I was still too young and had only very limited programming skills to contribute to it. Love these stories about how simple and straight-forward it was to have a huge impact. I guess there is some nostalgia involved, but these were, in my opinion, better times. That sounds weird. Did SSH originally have file-copying capabilities? As I recall, the ssh command was written to be command-line compatible with rsh, not telnet, since rsh (and its companion rlogin) was what people were using at the time to log in over the network between local systems. The manual page for SSH still states this explicitly: It is intended to replace rlogin and rsh [], and SSH from the start had (and still has) an rlogin replacement, "slogin". (Telnet was at the time only used for accessing remote, i.e. not-on-site, services, which did not necessarily imply shell access.) Anyway, the rsh and rlogin protocols use port 513 and 514, but no nearby ports seems to be unallocated. The story seems to be missing some details, or possibly be made up after the fact in lieu of a bad memory. It seemed reasonable to me at the time to give port 22 to a better replacement for, and a spiritual successor to, Telnet, but the story seems odd for not mentioning rsh or rlogin at all. I have a separate theory as to why ipv6 is being pushed so hard by advertising companies like Facebook, Google, and the US Government (CIA, NSA): it makes it very easy to casually track the number of hosts behind firewalls. While not impossible with ipv4 at the layer4 level using fingerprinting techniques, it's quite difficult to do at scale, is unreliable, and spoofable. Ipv6 makes this trivial for anyone, and will allow ip transit providers to scrape more information about users, even those encrypting layer5+ traffic. It's a bit cliche but the pace of innovation in our field (at least up to now), and the rate at which we get used to new things, is amazing. >. Registering MIME types was also easy:... Even better, port knocking on non-standard port. I read the email and the dude just gives them that port assignment with no ceremony. I was hoping it would be more climactic. HN doesn't really seem concerned that all these titles are low-quality bait. Guess they're digging those page req numbers. Unfortunate how effective it is to just deceive your users. My guess is, that where other blockers by default can easily block all google ads, Chrome blocker would not block Google Ads because it would classify them as acceptable. And Google would then hope that people would use their built in blocker rather than downloading a third party extension which would highly likely block there ads. And if people have a built in blocker that blocks the mostly bad ads, the people would start to hate ads less and be okay with 'good ads'. Also since people wouldn't use third party blockers as much those companies would go out business more likely. It's a very risky move on Google's part, so would be a bit surprised if it happens. But doing nothing, is equally if not more risky in the long run for there business model. I like this approach. It punishes site owners for running malicious or badly-behaved ads. I think this is a step forward. I hate blocking ads across the board - I just want to stop the intrusive and dangerous variety. I can tolerate the rest. The basic explanation of what happened is simple: the UK instituted a carbon tax that made coal more expensive than natural gas per unit of electricity produced, so British utilities shut down their coal plants and replaced them with gas plants as quickly as possible. The backstory is somewhat more complicated, and much more interesting. The British tax was implemented in 2013 as a local fix to a broken EU carbon-trading program; that program, called the Emissions Trading Scheme [1], allocated to electrical utilities in the EU the right to produce a fixed amount of carbon emissions (and carbon-equivalent emissions), and the rights were made transferablea typical cap-and-trade set-up. And then the basic problem with that typical set-up occurred: the fixed supply of rights to produce emissions proved higher than the EU's electrical sector's total demand, a consequence mostly of lower than expected demand for electricity during the recession that followed the financial crisis of a decade ago, but also partly due to other clean-energy initiatives and to big changes in world energy markets. And so the price of emissions rights collapsed. That wasn't really a problemno more carbon was being pumped into the air than the ETS allowedbut it made plain the fact that the ETS was doing nothing at all to reduce emissions. So British lawmakers decided to implement their own carbon tax, called the Carbon Price Floor [2], in order to reduce emissions and support the development of clean energy. The tax rate Parliament set was one of the highest in the world, and as it turned out it was just high enough to make coal slightly more expensive than natural gas for generating electricity, an outcome entirely unforeseen when the policy was decided, just as global production of natural gas was beginning to boom and its price to plummet. So in the end, a bunch of poorly designed policies and their unforeseen consequences led to a better than expected outcome: Britain has been weened off coal decades earlier than was thought possible. 0.... 1.... 2.... It stands so proud, the wheel a sacred ground? Foreign tourists gazing round Asking if men once worked here Way beneath this pit-head gear Empty trucks once filled with coal There are many confounding factors (recession in 2008-2009) but generally, the number of days with smog advisories has been on the decline in Ontario as well:... Note that in general, across North America (not sure about the world at large) electricity consumption per capita has also been on the decline, to the extent that overall/absolute electricity consumption is down in large areas like Ontario[1]. I haven't done any research, but I surmise this is due to factors like more energy-efficient devices and time-of-day usage being pushed onto the retail user. (In additional to the aforementioned recession causing loss of manufacturing/factories) 1.... [0] What a great accident. The biggest problem with plastic is not with the products that make it into the landfill, where bacteria could be used. The problem is with what happens when they don't make it into a landfill, and they end up as basically permanent pollutants in the water. We heavily subsidize both wind power and solar. We even still subsidize gasohol even though it doesn't produce the environmental benefits we first thought that it did. But we don't subsidize degradable plastic made from corn which isn't used widely because it costs a few cents more than plastic made from oil. That has never made any sense to me. Lignin (wood) and cellulose are pretty tough to break down, but there are things that eat them. Plastic fundamentally (chemically) is made of the same stuff as wood, just in a different arrangement of atoms, and releases energy when decomposed. So it seems quite reasonable that there would be things that can eat it. I think the plastic pollution we are seeing right now is a temporary thing - soon enough there will a large enough population of plastic eaters that it will no longer be a problem. (We should avoid plastics that have chlorine in them though, except where needed. PVC is the most common example of a plastic like this.) The worms can't live in landfills. If you could separate the plastic before landfilling to feed it to worms, then you could just burn whatever separated plastic can't be recycled. (Yes, that releases CO2, but so does having worms and bacteria eat the plastic.) The problem with plastic as waste isn't that it is super-toxic or impossible to destroy. The problem is that it's mixed in with a lot of other kinds of waste. We don't need new ways to destroy polyethylene. We need ways to separate it from mingled waste streams or prevent mingling in the first place. Interestingly, Prof Mukherjee had no idea that Mr Pirsig has written this cult book or that he was a famous author/philosopher. To him, he was just an odd student (because of his age). I wrote about this in our campus newspaper - but no one cared. I thought that I was the only fan of Mr Pirsig in this small town in India. Once I found the internet I discovered that I wasn't alone. It was a great feeling. Anyway, i was very proud that he went to the same university that i went to. It was exciting to learn that in 1998! Also, while i didn't fully get the philosophy-the father and son journey in Zen really meant a lot to me while growing up. Edit: by the way, Prof Mukherjee is mentioned in his book "Lila", and that is how I found him. Edit2: "Lila", the name of Mr Pirsig's second book, seems to have been inspired by his stay in Varanasi (India). In Sanskrit, the word Lila is "a way of describing all reality, including the cosmos, as the outcome of creative play by the divine". Someone on Wikipedia also seems to have made this connection: Edit3: I spent the last hour digging into a 15-year-old hard drive (oh, what painful fun). I found a folder with my notes on Robert Pirsig! Most interestingly, my meeting notes with Dr. Mukherjee. I gave him the book and he flipped through the chapter for 20 minutes reading the sections I had underlined (where his name was mentioned). This frail man of seventy, said with a smile on his face: "He must not have been an attentive student. I never taught him this way". Most of the notes are about him reminiscing about the "golden years" of the philosophy department when according to him many great philosophers came to visit and study at the philosophy department at Banaras Hindu University. However I read it several times and I think that interpretation is very uncharitable. It is a touching big hearted story about a fractured person struggling to put himself back together while trying to connect with his son and while trying to figure out what it means to live 'the good life.'[2] If what he had was metal illness, I think that he might be an example of someone putting it to the best use possible. I'm honestly not sure if the MOQ holds up as philosophy or not, or even as a coherent mystical system. But I can say that I wish there were more books like it, that is to say: written by authors way on the fringe of mainstream thought. [1] My critique about the Zen aspect is that Buddhism is not something you theorize about, it is something you practice. To theorize about Buddhism would be like a guy who reads a lot about golf trivia, golf training, golf biographies, but does not play golf. Golf is a thing you do, an aspiration to get the ball into the little hole. It is something you have to embody and realize in yourself. Buddhism more resembles learning a sport or a craft than a philosophy. [2] Many of us should be so lucky to achieve even one of those things in a lifetime. We weren't allowed to read or do anything but sit in boredom during suspension (school rules) but he made an exception for me if I wanted to read Zen and the Art of Motorcycle Maintenance (at his recommendation). I bought a copy and brought it to suspension the next day, read the whole thing that week. Good memories thanks to the room monitor dude and an excellent book. "Zen was published in 1974, after being rejected by 121 publishing houses...then Pirsig lived reclusively and worked on his second book Lila for 17 years before its publication in 1991." "Quality is, how do you know what it is, or how do you know that it even exists? If no one knows what it is, then for all practical purposes it doesn't exist at all. But for all practical purposes it really does exist."... :'(... Zen and the art of motorcycle maintenance was one of the first books on philosophy that I read outside of my philosophy curriculum at university and it stayed with me. It's a great book discussing the metaphysics of quality, but not just that. It's written in a captivating way, mixing both the 'food for thought' as well as a pleasant narative about a father and a son on a motorcycle trip. It's one of the philosophy books that I can recommend to people who are not directly interested in philosophy as well, which gave me some quite fun discussions with my friends about the topics in the book without being too deep into the philosophy itself. May he rest in peace. Anybody with some education in philosophy figures out that utter, logical-proof certainty can't be had. So what does one do for epistemology instead? There are two main alternatives: -- Religious-style faith. This is not my preferred choice. -- An aesthetically-tinged approach to epistemology. What I mean by the latter is, for example, generalizing Occam's Razor into usability. The problem with Occam's Razor is that it says, in effect, "In case of doubt go with the simpler answer", without giving a general way to judge what's simpler. Any solution to that problem winds up being an aesthetic kind of judgment.." But I wish to make the case that the book is worth reading for its literary value alone. The narrative parts are a gentle, beautiful telling of this father/son trip across the northwest, and reading it will leave you with enjoying nature (or, more generally, reality) with something like a calm optimism. I think this applies to a lot of the great writing I have loved, and perhaps Pirsig's ZAAMM falls into this bucket. After all, for all of its classical philosophical underpinnings and serious intent, it does not seem to have achieved much status as as work of philosophy. You won't find Pirsig's name (except in passing) in the Stanford Encyclopedia of Philosophy, for example. The book is also over a generation old. I suppose there's a question, therefore, of whether it will endure as a book that future generations will draw inspiration and ideas from. Nevertheless, I think it stands admirably as a iconoclastic, genre-bashing, cross-pollinating, fascinating exploration of philosophical ideas, and, as Pirsig himself observed, as a "culture-bearer" of the time and place it was written. This makes it a classic of American writing as far as I am concerned, if not a classic treatise in philosophy. RIP, Mr. Pirsig. "In other words, any true German mechanic, with a half-century of mechanical finesse behind him, would have concluded that this particular solution to this particular technical problem was perfect." Anyone else remember that bit? I now ride a big BMW R1200RT. I wonder if this book influenced me to do that? RIP Mr Pirsig "..."... Amazing when things like that are foretold. (Yes I know, survivorship bias blah blah) Like composition v. inheritance, you don't always want to become the thing, you just want to use it. It's dangerous to become a thing, especially one without any Quality. Maybe I resonate more strongly now with the BMW driver. I don't know. Maybe I didn't really understand the book. Pirsig's concept of "quality" sticks with me in every decision I make as a parent, engineer, and product manager. RIP, Mr. Pirsig. An interview with someone who interviewed Pirsig. With clips from that original interview. Very, very good radio. From personal relation to the book. When I was young I went on a motorcycle trip on the back of my father's motorcycle, with his friend and son. We pulled into a small rural gas station, and there was a younger guy filling up a small foreign car. And he just started laughing upon talking to us. He had just taken time off his undergrad after reading a book about man and his son on a motorcycle trip. And wrote the name down on the back of our map. While I was far to young to understand the book at first, reading it over again and again as I got older it was a different learning experience each time as I grew. Highly recommended to anyone who likes reading. It's not just the philosophy and it's not just the story, it's the way they are part of the same whole, with deep roots in the American landscape, that makes this book so special. Now I want to revisit it and see if I can pick up his later work as well. If you still haven't read Zen and the Art of Motorcycle Maintenance, do yourself a favor and pick up a copy. Read again when I was a bit more ready to hear it and wow, profound book. The church of reason lecture is awesome. And timeless. I hope this guy found some peace in his life, I did get the sense that he was struggling but that's just a guess. He gives a break down of a certain style of thinking about things where you break the subject down into parts and the relationships between the parts. He gives examples in technical writing that this process has a degree of arbitrariness to it. His circumscribing the general process of conceptualizing things suggests that the process itself has limits, and while valuable, is not everything (despite the tendency of certain mentalities to see things that way. He has an ongoing contrast between himself who is inclined to think that way and others who aren't.) I see this as a bridge to understanding Eastern philosophy's low opinion of language and penchant for indirect explanations. I borrowed the book from the public library just last week. [edited to remove spoiler I shouldn't have mentioned -- my apologies] I loved it and will always remember it when I have forgotten many other books. It is not a 'philosophy' book but it is quite philosophical. It's worth a read but it's slow in parts. Push yourself through or skip a few chapters. Like many other readers my favourite part is the drink can as shim. For those who are interested, a little more info to contribute... RP, apparently though I can't substantiate, was tested as having a "Genius level IQ" as an early child. After reading both ZMM and LILA carefully, I believe he has gotten as close as anyone to a philosophy that explains humanity and blends successfully eastern and western history and perspective on such. LILA is the serious effort and a far more important book, though it has gone largely ignored. Some interesting info for fans to dig into here: At the time, I thought it was one of the most significant things I'd read. Of course, I was young, and it was a long time ago. (And then, life and injury and illness and... well, a distinct lack of quality happened, and I never got back to it.) I've been meaning, intending, lately, to reread it. Last year, I was invited into a book club. I've considered suggesting it -- I think I will. Quality. Eloquence, in a word. P.S. I've been thinking about getting a bike and riding for a summer. Adequate, but not overdone -- and quiet. Piece by piece, this rough idea has been sketching itself in. Don't know why I'm telling HN, this, or why you should care. Except that we all should care about quality. And about a man who thought and felt hard on the topic and in turn gave us much to think about. Reflected much of ourselves, to ourselves -- giving us eyes and ears into ourselves and our choices. Anyway... I think that's an often overlooked detail and one of the pieces of "sexiness" that makes it very difficult to want to switch away from an XPS 13: it's so damn portable. System76 needs to come out with something comparable to that before I can switch. The market of people who want something rugged/durable/functional are already taken care of by the Thinkpads. The market that is still untapped is that of the Linux ultrabooks. Developers and other Linux enthusiasts basically just want a MBA/MBP that runs Linux natively. Do that, and people will flock to it. I must say, however, I don't see that need for desktops. Custom desktops are relatively easy to build, even for customers. A well designed linux laptop, with no driver issues, good build quality, that doesn't sacrifice performance for thinness? That's what I'm missing. From a personal/consumer standpoint, all I want to see anymore is a competitor to the Macbook Pro, with a comparable track pad, display, keyboard, battery life and form factor. I'd love to move away from my MBP, but the closest competitor I've found is the XPS 13 and, while it's a great laptop, just doesn't hold a candle to the MBP in a few of those areas. I wish System76 luck and would love to see them prove me wrong. This press release, so early in the process, just seems like a lot of pressure for the company to live up to, especially based off of their past offerings. I don't know if I'm the only one, but I really want a 13 inch laptop thats thin/ultrabook format, with low specs and only a HD screen. All I do each day is use a browser and SSH into other machines, I don't need an i5/i7 processor and HiDPI display to do that. My ideal laptop would be an XPS 13 sized laptop, with a 1080p screen, i3 processor, 8GB of RAM and as much battery life increases as possible. There are many configurations and many redundant options, and silly coupons that work on some models and not others. The buying options are entirely unclear, I think intentionally so. Just like HP and some of the other major OEMs. Please don't read this wrong, I love options, but I dislike foolish inconsistency. When I build a desktop I can choose any CPU, any GPU, any Mobo... When I look at the 4 models (lines, tiers, whatever) of the XPS 13 they have redundant options, 4 different ways to get to the same configuration with no reason I can see for a $200 difference in price. When I spend my money I want to know what I am buying. Beyond the normal BS is that part of buying System76 is not giving money to microsoft. I think microsoft is evil, not an exaggeration, legitimately evil. Not giving them money is a huge selling point for me. I think this is a discussion for another thread and will not defend this here and now, Just take that I (and at least a few others) won't willingly give money to microsoft. So where is the option for an XPS with Linux, any flavor (or even Freedos or no OS) pre-installed? Because none of the XPS 13 systems say they support what I choose for my OS, what is my recourse if I do blow away the pre-installed OS and something doesn't work? They are free to change the hardware when they please and I have ordered two dells with identical model numbers and gotten 2 different things (even in their business class of machines). They are making it clear that I am not their intended customer and mine is not their intended use case. I bought an ultralight Acer of so-so quality and the thing runs Xubuntu, i3 almost flawlessly out of the box. I'm not going to pretend it's a Macbook Air or XPS but it matches them in function for a lot less money. I am quite happy with my 2016 MBP, by no means perfect, but my overall Mac experience did not change that much. Having worked with raw EIA data I can say that the inputs are not very reliable: a) a lot of smaller farms are not included in EIA data b) reporting is voluntary and 30%+ of wind sites stopped reporting data in 2016, for example [1], and c) reporting is based on surveys which means errors, delays, etc. The US is really lagging behind when it comes instrumenting and monitoring its energy infrastructure. [0]() [1](...) I always hate how projects are touted as 'bringing X many jobs to the region' when a majority of cited jobs are in the construction or building of whatever the project is, and then evaporate away once it's built. Of course, less employees per unit of energy could equate to more total employees if the increase in energy produced is greater than the increases in efficiency. As far as I can tell, the types of energy policies we have in the US do a pretty good job of incentivizing increased efficiency in all types of energy, including renewables. I'm definitely not knowledgeable about this though, so maybe someone can correct me if I'm wrong. In fact you could raise mushrooms under the solar panels and get triple use of the land. See page 29. Solar, for example, employs 373,807. Natural Gas: 362,118 Nuclear: 76,771 I've also designed a super low cost wind power system anyone can just stick in their yard. Basically a flat wide pole you stick in the ground that the wind blows up and down. (Think wind blowing across a grassy field). I need help with engineering to make any more progress though. Reality is that most jobs, in most sectors, pay crap. Wind energy is no exception. It's becoming hard for me to justify staying in the 'DevOps' space with amazing solutions like this coming out regularly from AWS. I can hitch myself to the AWS wagon for a while, but eventually, it seems, dedicated operators just won't be needed for most small to medium deployments. It's tough, because I can see that this is genuinely moving the industry forward, but it's also negating the need for skills I've worked for over a decade to build. I guess this is what carriage builders felt like 100 years ago. This may also mean that I will never have to touch devops again. I may never have to use Terraform, Kubernetes, Docker, CoreOS, and all that other stuff. At least, not for small to medium-sized deployments. It also means that I'll never need to touch Dokku or Flynn. I was about to say that some company just wasted a lot of money on Deis, but then I remembered that it was Microsoft. So maybe that was a good move, although I feel like Azure is the Bing of cloud providers. I'm actually angry that this took so long. This should have been available 5 years ago. CodeStar is more like AWS Elastic Beanstalk, the one that I still don't know how to take it into my toolchain and development flow. Now AWS CodeStar, that requires bunch of clicks, wizards, permissions configuration, choosing a template and then another changes... To get started with they needed to show bunch of screenshots, while something like Heroku would tell how to use the whole thing in 2-3 commands in terminal. That's all. However, I hope something like CodeStar get more polished and mature so I can move have one place to bill and one thing to worry about and not docker, kubernetes, mesos, ansible, ssh into machine, database backups, etc... edit: Just found out for web applications they use Elastic Beanstalk as deploy step. I think this looks great. Edit: Looking into the CloudFormation templates created, there are CodeStar resources, so, I assume, the new resource types are just not documented yet. Not that it needs much documentation, but I will try creating a template with those to test if it works. Edit 2: Here are the new resource types: CodeStarProject: Description: Starting project creation Properties: ProjectDescription: AWS CodeStar created project ProjectId: !Ref 'ProjectId' ProjectName: !Ref 'AppName' ProjectTemplateId: arn:aws:codestar:us-east-1::project-template/webapp-nodeweb-lambda StackId: !Ref 'AWS::StackId' Type: AWS::CodeStar::Project Version: 1.0 SeedRepo: DeletionPolicy: Retain DependsOn: [CodeCommitRepo] Description: Adding application source code to the AWS CodeCommit repository for the project Properties: CodeCommitRepositoryURL: !GetAtt [CodeCommitRepo, CloneUrlHttp] DefaultBranchName: master ProjectTemplateId: arn:aws:codestar:us-east-1::project-template/webapp-nodeweb-lambda Type: AWS::CodeStar::SeedRepository SyncInitialResources: DependsOn: [SeedRepo] Description: Adding the AWS CodeCommit repository to your AWS CodeStar project. Properties: ProjectId: !Ref 'ProjectId' Type: AWS::CodeStar::SyncResources Version: 1.0 SyncResources: DependsOn: [SeedRepo, CodeBuildProject, ProjectPipeline, SyncInitialResources] Description: Adding all created resources to your AWS CodeStar project Properties: ProjectId: !Ref 'ProjectId' Type: AWS::CodeStar::SyncResources Version: 1.0 I don't mean to knock it, it's great to see this functionality make it to AWS, I was just wondering if there were any significant differences to Azure's offering? Definitely a cool thing, a good way to have something that's easy to start with, but as you need a more complex infrastructure would let you add it as necessary without incurring the usual "learn everything at once" cost. Not using their code hosting, use GitHub for code + Wiki. My question is CodeStar only worth using when you need to deploy a basic "template" app out the door? What happens when our requirements mean changing web server config, firewall rules and all the actual things that happen that are customizations? If you start on CodeStar are you "stuck" with it or can you easily get off it but keep the underlying services? I know its just EC2 horsepower under the hood. The last thing I need is a service that isn't customizable, if that's the case maybe I'd be better sticking with straight Elastic Beanstalk? That being said, after poking around I have a few criticisms: 1. It doesn't seem like the example templates include Docker. At this point, I think Docker should be considered a must-have for any new ops tool. It makes your application much more portable and eases the learning curve for new developers. 2. Getting things set up and working is still too complex. It took me 20 minutes to get my first project working fully (even just using their standard tools). 3. There doesn't seem to be any ability to bring in an existing project. It'd be awesome if I could just provide a GitHub URL and Amazon would automatically set up all the ops tools I need to have a production-ready deployment of that project. I welcome the competition though. Let humans focus on unique work while computers automate things. [0] In fact, I founded my startup on that premise: My vision for AWS is being able to login to AWS and see c9 with one click deploy and configuration. I'm patiently awaiting for this. It was one thing that really woke me up to Azure with their wizard form directly from Visual Studio. After AWS reinvent 2016, the Azurphoria wore off and I was an AWS fanboy once more. Having the ability to edit/deploy inside my browser would be a huge tide turning moment. >>each project using AWS CodeCommit, AWS CodeBuild, AWS CodePipeline, and AWS CodeDeploy.<< As a developer I don't need to know all of that. All I need to know is one command to deploy my deployment package for the project. That way I am productive quickly. Then give me the ability to configure the VM/container size and autoscaling. Now that my app is up and running, give me something like Azure WebJobs to run my worker tasks. Amazon needs to have a better PaaS story than what BeanStalk is. BeanStalk is very flexible but in return, it ends up being too complicated to set up. Compared to Heroku and Azure App Service (which I am using in a .Net project and was surprised to find very easy to get started with.), AWS Elastic BeanStalk is very complicated. With Heroku and Azure App Service, the developer friendly PaaS UX is more or less a cracked problem. AWS just needs to copy it well. I have no experience with devops and want to learn to manage my applications directly (mostly use services like now or heroku currently), but looking at learning aws always seemed intimidating with the 600 different services they run. Doesn't quite look like they've nailed the ease-of-use quite in the way Heroku have yet, however. The link for a one-off contribution is here: Or for a subscription, here: I tried the weekly paper edition for a while, but although it was posted on-time at the printers (in Britain or Austria), the Danish postal system usually delayed delivery to me by at least a week. The web is at a crossroad and we should promote multiple platforms, old-style blogs, decentralized navigation, classic journalism, etc. For too many people, Facebook is the web and this is really sad and wrong. We must find other ways to pay for information and curated content, limiting tracking and defending privacy. Your news feed is designed from the ground up with powerful artificial intelligence to become an echo chamber, and lots of FB users just don't understand this. They fall for it completely. I have more liberal friends than conservative friends, and my FB feed literally only shows me anti-Trump pieces (along with ads and other spam), some of which are astoundingly blatant in their bias. I have to go out of my way to seek out opinions from or articles shared by my conservative friends. Even if I do this frequently, FB still does not incorporate them into my feed. Instead, every single day, it shows me low-quality clickbait anti-Trump articles shared by someone who lived on the same floor as me in a college dorm 7 years ago with whom I shared one conversation in real-life and whom I've never interacted with on FB in any way aside from approving her friend request.... Precisely. FB's brand with respect to news is damaged to the point where it's negative. FB is the place to get fake nuz. The Guardian and the Times are wise not to allow their content to move under the FB brand. In some sense, Apple faced that problem, too. It created its own sales channel, whereas the Guardian has one to fall back on. In contrast, Intel when faced with that problem in the PC market, choose to work on brand awareness through the "Intel Inside" campaign. Reason likely is that, to create their own sales channel, they would have had to start making PCs, thus competing with their own customers. So, Intel accepted that there were larger entities offering both their and their competitor's product, as long as it had ample opportunity to market its brand there. So, perhaps the aggregators should work on two things: pay more to their contributors, and allow contributors more to present their brand. They are not news companies, they are not in the news business, they don't know it, and they have not done anything to be worth the trust of the public. They are just convenient because they are a monopoly in another area. The dead of the omnibus paper the press is forced to choose between a return to the old local/partisan model where the paper becomes a part of political movement and receives "patronage" from that movement in forms of paid subscriptions, or the yellow(named for the color of cheap paper) model that lives off scandal creation. *Most of the newspapers of the 90ies based most of their revenue off content sourced from their network of partners a model that only really worked because the paper had access to long distance communication networks too expensive/exclusive for widespread usage among consumers. Are you serious, that is the draw? Apologies as needed from me (someone who doesn't know or care a thing about Facebook) but I'm surprised. Couldn't a publisher easily silver-bullet this just by removing the bloatware from their own site? Integrating with FB IA & Apple News is giving up power for gains that may not be worth it in the long run. I think it's best for the internet's health that Instant Articles is slowly declining, but it did show me how much better the experience could be if people paid attention to that stuff. (I'm only commenting on the bigger picture, nothing about the Guardian specifically. They actually have one of the better websites out there.) Not only did US MSM (NYT, WaPo, ...) ignore Frank, they ignored the fact that Trump and Sanders were better at protecting STEM jobs by combatting H1-B Visa abuse than Clinton. (See ComputerWorld article below). He was warning the Democrats not to ignore the affects of globalization on the working class: March of 2016 Millions of ordinary Americans support Donald Trump. Here's why... After BrExit (July).The world is taking its revenge against elites. When will America's wake up?... The first article I started sending to people in early June. He explains very clearly that the Democrats left drifted away from the strategy of FDR of supporting the working class and protecting American jobs. Hilary was for trade which decimated working class and for H1-B visas and illegal immigration which depressed wages for STEM and working class respectively. Trump was anti-trade, anti-illegal immigration, and anti-H1-B abuse (he complained when Disney of FL replaced 250 American IT workers with H1-B). Notably, HRC was more like Bush and Rubio wanted to expand H1-B.... ." - Work or school account - Personal account I get this prompt every time I try to log into Azure with my work email. If I choose the work account (the most intuitive option) my azure subscription list is empty. I have to log out and select the other option. Why is there a difference and why isn't this transparent? I am authenticated, you know who I am, give me access to the things I'm authorized for. I don't know what kind of weird backend situation MS has, but asking me to understand it is terrible UX. - My Office University account expires. - My father invites me to be part of his Office 365 Family subscription (it includes 5 accounts). - I click on the "Get the invite" button on the email I have received and... "You already have an active account". There was no way from the website to cancel my expired University account, the only available option was to subscribe to my own Office 365 Personal account (10/month). I have contacted Microsoft and it took 90 minutes of chat, including a one hour session where a Microsoft support guy took control of my computer (it was totally useless, the error has been solved by a modification in the Microsoft account database), to fix the issue. As titled here: this is insane. Apple is actually getting close to this bad, too, and in some ways, worse. I gave my mother my old iPhone over a year ago. It was wiped, and we set it up with the 'family' whatsit. For reasons I won't go in to, at some point, I ended up giving her my Apple ID password to fix a problem when I couldn't do it. Ever since then, something has periodically decided to sync a random assortment of things. It isn't consistent, temporally or in terms of what it syncs. (I'm very anti-cloud-service; I don't use online backup, sync or cloud docs or any other sync services from Apple. I think my other uses the backup, but nothing else, because the phone is her only Apple device.) A few months ago, her contacts ended up splattered all over mine. I deleted them, it happened again a few days later, this time just a random assortment of them. Yesterday, my call logs ended up on her phone. Short of asking her to wipe the phone again, I don't know how to make this crap stop, but I'm sick of it. Seriously considering going back to a feature phone; everyone making modern phones appear to (a) make it impossible to have a self-contained phone without your personal life smeared across multiple companies' servers, and (b) be too incompetent to actually smear my personal life across their servers without fucking it up. I'd like to change the username of my basic Skype account. Alas, it has the company name I worked for at the time. I also have some credits in that account. I'd either like my credits back, or I'd like to change my Skype username. Neither are possible. I'd also like Microsoft to stop asking me if I'm using a business account, or a personal account, when I enter my work email address into every Microsoft service we use every day. That'd be nifty, too. In addition to those 3 accounts, I had 2 Office accounts (one for work, one personal). Notwithstanding that the O365 sign in really can't handle two accounts on the same browser (by ways of automatic redirects) - I didn't know if services were on O365 or Live. MSDN and VSTS do not support O365 login, so I had to tell my Live account to claim my MSDN keys. It's nuts. I eventually just forget about accounts. I stopped using O365 for personal email. Don't use O365 for anything personal, you will pay hell for it (for more reasons than merely sign in). I don't have a mobile phone so that's fine, I can get texts on Google Hangouts or Skype but their account software refuses to send the verification texts to those numbers. Fortunately there's an option to have them call you but they refuse to send call my home phone system that is registered with my name and that is a valid e911 number associated with an e911 address. A call with a Microsoft support person confirmed that nope, I can not sign up for Azure. What a cluster MSFT EDIT: And guess what, I have not used Skype since.Trying to recreate my contacts and the whole process of having family accept my new account was a much larger barrier than just instructing my family to use another video chat service. FU MSFT. Reddit discusses hackers using weak Skype credentials to access other MS accounts and bypass 2FA I need to get access to my Microsoft Office online documents. I go to login and it has me do a security check with my email: microsoft@mydomain.com. It's supposed to send a code to verify my email, but I never get it. So I try option 2, a different email: microsoft@myotherdomain.com. Never get the code... Hmm, does it not like the word microsoft? So I try myname@mydomain.com, and I get the code! Although now I have to answer a bunch of questions and my account is under review -- I should get an answer within 24 hours. But what about the future? My real account is still microsoft@mydomain.com. Will this keep happening? :\ I once subscribed to Office and am pretty sure I had to supply my first and last name once if not multiple times. But the final confirmation email still started with "Dear null null". I love MS stuff, but they have the worst account process ever, closely followed by Apple. I do wish MS would sort their act out in regards to accounts. I lost my Xbox account trying to transfer my games and such between my windows live account and an old account. Lost my games and points and credits :( Old skype account - kinda bad password. MS account - great password, 2FA. Then I got alerts that someone in China had logged in to my MS account. I couldn't figure out how they'd done this until... I figured out they'd signed in to skype, using my old skype username and old skype password that were still valid for some unknown reason after merging it in to my far more secure MS account. So I'm migrating everything to Inbox (Gmail) and people don't care at all switching to Hangouts instead of Skype. Another point is that you cannot use a "work account" you use in office365 as your personal account for OneDrive etc. All for a service (skype) I rarely use. It's russian roulette every time I try to login to something that's authenticated with Microsoft accounts, and trying to remember which login I need to use to access which resources is more than I can keep track of, across outlook, MSDN, forums, Azure, Active Directory, etc, etc. I have like 3 old skype accounts which shows up with my name which I can't access due to me not having the email addresses anymore nor do I remember the passwords, so it is a pain when people try to add me on skype and I contacted them and asked if they could delete my old accounts since I can't access them and they said that is not possible since I don't remember all the security questions and answers, wouldn't even give me the questions so I could have a chance at answering them.. Edit: added TL;DR These situations where you mix personal and enterprise/job accounts become edge cases that can be catastrophic for users stuck in them after they leave companies.... Difference for me is that I have no idea how the work account was created. I do an have Office365 account from my employer but we just recently switched and I had this problem before that account was created. Also, that Office365 account is linked to my actual work email. The problem I am experiencing is a "work" account that was mysteriously created on my personal email and it makes no sense. Over a month and no one has responded. Anyone here have any ideas? Protip, don't name anything expecting you can change it later. See also: S3 buckets. If someone goes offline, Skype will show you how long they have been offline for. Except....that it's just a random number. I can set my status to offline right now, and my coworker will see that I've been offline for.....168 days. Or 700 days. Or 35 minutes. Microsoft knew about this bug for years, and there is no fix for it. Frequently, when I send messages to my coworkers, they appear ABOVE older messages in the coversation, which is extremely confusing, because obviously the whole window will flash to indicate you got a new message, but in reality you have to scroll up to actually see it. Highlighting text is just broken, I dare anyone from MS to reliably highlight just a portion of text without the selection jumping to seemingly random part of the window without any indication how or why. Arbitrarily low character limit, so you can't paste snippets of code. During conference calls, audio just dies from time to time, and the only thing you can do about it is kill the conversation and start again. This is a product based off Skype, for fucks sake, that MS is charging us millions of dollars for globally, and that doesn't even have the basic functionality working correctly. An event I'm going to requires a Skype account of a preliminary interview. So I go to sign up with my gmail, and I'm able to create an account. However, I already had a Skype account through MS's weird Outlook program (I signed up with my gmail for Outlook, and it automatically created a Skype account without telling me . . . for the gmail account). This bricks both accounts by loading to an error page when I login, telling me to go to MS's website to fix my account. I go there and then after spelunking through the maze of a UI, finally get to a page that tells me I need to call Microsoft to diagnosis the problem. Screw that noise. It's 2017, this is archaic. Luckily, there's a third option for signing up and that's through a phone number. I do that, but now I don't know what to enter for the username field in my interview app. I look through Skype's help docs, and it doesn't say anything about phone numbers. I assumed my phone number is my username and that's how people can add me. Anyway, that's what I put in the app and I'm hoping that the UN acts like a UN and not a phone number with calling charges. What a mess. It's also partly the event's fault for using Skype when better alternatives exist. So I sign in to the new Skype, and can't remember my password. That's OK, I'll just get them to reset it. Oh, my email address expired while my PC was sitting on the junk heap? That's OK, I'll follow their prompts, this shouldn't be too difficult. "Unfortunately, we were unable to verify your ownership of this account using the information you provided. [...] Please submit a new account verification formAt this point, your best option is to submit a new form with as much accurate information as you can gather." I've provided the details of six different users who were on my contact list, the complete email address I used to use, and there is nothing else I can do. No email address I can contact, no phone number to ring. Oh, and most importantly, there's no "Import old account settings" option. Screw you, Microsoft. And then I read your post today... I'm glad I closed my Surface and went back to my MacBook last night... Ref:... Their support is the worst; they were totally unable to even comprehend the problem I was seeing, let alone fix it. I just gave up trying to use them. I'm currently dealing with an issue with different versions of the same (MS) software getting authenticated via a domain but ending up pointing at two different MS accounts associated with the same email address, and hence consuming two licenses. 2 weeks of "support" back and forth hasn't helped, they seem to have good tooling to introspect what is happening. What's wrong with Uber tracking Lyft drivers? What is wrong with using a competitor's API to get real-time tactical information about them? Not only did it not harm Lyft drivers, but it actually aided them: Several of them were offered hundreds of dollars by Uber to switch companies. Most drivers are trying to make end's meet, and from speaking directly with drivers, this was seen as a universally positive thing. "I was like, yes! Where do I sign? $400 bucks is amazing. Too bad my car was too old for Uber." Though I guess if Mr. Gonzales wins his lawsuit, it will give the answer to these questions and more. A lot of the lying and cheating they do seems like an objectively poor risk/reward proposition and I think many companies would not even get to the ethics question because they would stop when realizing the ideas are stupid when you add up the negatives. Stealing Google's autonomous auto IP could be a crime that actually moves the needle for the company (if it turns out they are guilty), so I guess they at least had significant upside with that one. IIRC the previous coverage noted that Uber was providing incentives to drivers who were using both systems, including both bonuses and steering passengers to the both-systems drivers to incentivize them to drop Lyft and only drive for Uber. The corollary of that is that there are a bunch of Uber-only drivers and former drivers who had their incomes hurt by Uber's redirection of profitable fares to 2-system drivers. THAT may be actionable, and a class action of former drivers seems like it wouldn't be that hard to put together. It would seem to me that the Lyft company has the strongest case here against Uber based on a violation of the terms of service for the private API that Uber abused. If Lyft were successful in their lawsuit, that would lend confidence to a follow-on suit by drivers. I ended up downloading their app and using it all weekend, and uninstalled it as soon as I got to the airport. I wonder how many other cities are basically exclusively Uber currently ? It might be erm... tantamount to admitting most of your activity is subject to legal challenge but the cost savings would be astronomical. This is terrifying and must be stopped! Can anyone explain how this is different from Google and Facebook following you around with informatics everywhere you go on the internet? The favicon trick is a pretty good example. Here is an updated version with some clarifications: <<< Docker is transitioning all of its open source collaborations to the Moby project going forward.During the transition, all open source activity should continue as usual. IMPORTANT NOTE: if you are a Docker user, this does not change anything. Docker CE continues to exist as a downstream open-source product, with exactly the same interface, packages and release cycle. This change is about the upstream development of the components of Docker, and making that process more open and modular. Moby is not a replacement for Docker: it's a framework to help system engineers build platforms like Docker out of many components. We use Moby to build Docker, but you can use it to build specialized systems other than Docker. You can learn more at) >>> EDIT: I'm happy to answer any follow-up questions here, if it helps clarify. Moby is an open framework created by Docker to assemble specialized container systems without reinventing the wheel. It provides a lego set of dozens of standard components and a framework for assembling them into custom platforms. its. More recently, I was part of a discussion where Kubernetes has decided to roll its own logging infrastructure, while leaving important parts like log rotation still undecided.... driving me even closer to the Docker ecosystem. However, it seems that Swarmkit is a big casualty of the whole CE/EE (and now Moby) split. Docker EE () still does not mention Swarmkit anywhere. In fact, there is NO top-level page on Docker's own site that actually mentions Swarmkit [1] and even Docker "Swarm-mode" is part of some second level documentation and help pages. It makes me really worried about how you are seeing Swarm-mode/Swarmkit as part of the long term future of Docker Inc. You guys really dont talk about it - not even on twitter. I'm assuming this is your handle as well (), which has not seen a tweet since Jan 2017. However, you guys do tweet a lot about "Docker Datacenter". What's going on ? [1]... > Docker is transitioning all of its open source collaborations to the Moby project going forward. Should I understand that the core team wants to keep the brand "Docker" but use it in a commercial way, while Moby will be the underlying open source code? Is it Docker/Moby = RHEL/Fedora ? or Docker/Moby = Mongodb.com/Mongodb.org? Moby = open source development Docker CE = free product release based on Moby Docker EE = commercial product release based on Docker CE. Nothing is dead; and everything that was open-source remains open-source. In fact we are open-sourcing new things. Docker used to be the open source part. Now that's being moved out of the way so when you search for Docker you get the paid offerings. The goal is to confuse the people who haven't been following this into thinking Docker is a thing you pay Docker (the company) for. It's brilliant. Docker. Ok, works with containers I get... wait. Your logo is a WHALE with a bunch of shipping containers on it. You know that whales DISAPPEAR underwater for hours at a time, and shipping containers are NOT MEANT TO DO THAT? Ok ok maybe it was an honest mistake hey whats this new thing moby.. wait. Whales. Moby. Moby dick? Your project is named after a mythical white whale that sank boats, the very thing that actually carry CONTAINERS. Having said all that, based on this [1] summary of Docker's usefulness in production from February, maybe both names are absolutely on-point for the reality of this abysmal 'product'. 1.... The intention is to have a clearer split between the Open Source community project - which is and will always be the heart of Docker (or now Moby) and the "product" pieces. The Docker product itself is not changing at all from an external perspective - you will still call "docker run" as before. However, Docker will be an "assembly" of pieces from the moby project plus some under the docker namespace, probably including "docker/docker-cli". Going forward, this will allow the docker-cli to make more product-centric moves like further Hub integration that would be too controversial for the community moby project. It also allows other organisations to take the moby code and reassemble it in different ways without offending the Docker "product". Furthermore, the intention is that in the long run, various Moby pieces will move to community foundations such as the CNCF and OCI. Survivorship bias is "Zuck did X, Y and Z, if I do the same then I'll be a multi-billionaire too!" Following the playbook of those that made it into the top 0.001% is foolish and does not properly account for the large part luck played in their success. There's no survivorship bias in going to med school, becoming a specialist and then earning 400k/yr. When I created my first company my parents told me about how hard it was going to be, how few succeed... On the contrary I found it was way easier and natural than studying engineering was, for example, and hundreds or thousands of people could do it. I found most serious people succeed in business. It is not that hard to become a millionaire, way easier than being a salaried person, tens of thousands of times easier than winning a lottery. On the lottery you have absolutely no control about the outcome, on real life you can "cheat" and control anything. For example, one of the great discoveries in my life is that in business if you don't know how to do something you can just hire the person to teach you or your team or just do it for you. That felt like cheating because I had been trained all my years on school and job that you have to do all your job yourself, regardless you being good at it or not. That control makes it extremely easy to do things. For example you could work with the people you want to work with, that makes your life way easier and enjoyable than if you are externally forced to work with people you don't want to work with. In the startup world some people want to be billionaires, and that is probably akin to winning the lottery. But I know some billionaires and do not envy them. Traveling everywhere with armed escort because someone could kidnap your children, so you live in a bunker isolated from everyone. Everywhere you go someone wants something from you, a loan , to invest in them. Banks harassing you all the time. Not knowing if people is around you just for your money. By far, the best explanation I've ever seen ! One thing is pretty certain, though. Doing nothing at all leads nothing at all. If you don't get up out of bed, eat, do something - you die rather quickly. If you barely get out of bed to eat, but don't take care of yourself, you limp along through life and probably die early from lack of proper nutrition, exercise, and mental stimulation. Somewhere along the spectrum from doing absolutely nothing to killing yourself with work is a sweet spot for achieving success. My observation is that the people who succeed spend more time on the side of that spectrum toward working their tails off than on the side of doing nothing. So yeah, it's a funny comic. It makes a point to remember, but it's definitely not the final word on the value of hard work. I've spent enough time in running a business to know that what works for one person may or may not work for another. I too hate the hero worship that surrounds the ultra successful, the whole "follow XYZ steps and you can be a billionaire!" type stuff. You can extrapolate a lot of general guidelines to help you increase your "luck", but nothing is guaranteed. I've seen friends with good plans fail because they couldn't execute, due to things out of their control or things I perceived as in their control. We've weathered some storms through sheer luck and I'm thankful for that. However, If you're already looking for excuses then you will most likely fail. Every ambition or goal has a cost. If X% of startups or Y% of people who pursue this succeed, there's obviously a luck component to it. But I bet that the vast majority of that subset worked hard anyway and knew what they were getting into. Failure was always a potential outcome. I get frustrated by everyone who points to anyone who is finding success in something as handwaving away their hard work and pointing to luck and survivorship bias, as if they see through some illusion that nobody else is aware of. That's bullshit. So you know what survivorship bias is? Good for you, now what? Does this affect your life goals in any way? People just play the hand they are dealt and come out better or worse. Nothing more, nothing less. But if you put too much emphasis on survivorship bias then you would think that everything is completely random and use "survivorship bias" argument as an excuse to do nothing. I'm highly recommend to listen Peter Thiel's speech "You are not a lottery ticket": I have had a lot of exposure to people 'in property'. People in property are people who had access to capital at the right time. Even worse are those who get to hear about government sell offs or developments which will increase values in an area before the rest of the populace. Then of course there are the money launderers. So I will add flexible morality to my list of traits that make a millionaire. The details in between are important in the discourse of luck. Growing up poor, I engaged in a lot of unethical behavior to acquire money. By some miracle, I got admitted into college (albeit a state school), and realizing this miracle, I dedicated my 4 years to pure studying with the belief that good grades -> good job. At the end of junior year, I questioned this logic- I had a 4.0 GPA, yet after 20 interviews, wasn't able to land an internship (which falsely led me to believe I was relegated out of the realm of "success"). Then, I digressed to my former self, and got in trouble with the law. During senior year, after 20 more interviews, couldn't land a full-time offer. Again, by luck, I somehow ended up landing a "prestigious" job. Years later, it was revealed to me that the hiring committee all but unanimously disagreed on my qualifications. One member read my senior thesis in full and, for some inexplicable reason, fought for me, and I ended up receiving 1/40 slots reserved for Ivy League grads. Whereas the first paragraph suggests hard work pays off, the second paragraph screams "luck." Sometimes, the details are too long, where the key events suffice when giving a description of someone's path. I don't think people are trying to dupe listeners and self inflate their hard work when they make statements like the first paragraph- people just spare the details because it's really not directly relevant to the narrative. Since my first job, I've interviewed for 70 different roles without success. While I get dejected at times, I understand the role of luck. I don't owe the details- I've earned my right to say I worked hard, but people can, and always do, aid in my luck. Without the awareness of this, I would've given up by now, but I just keep chopping. That's all there is to it when it comes to discussing luck. Yes there's survivorship bias, you try to adjust for that, and draw inspiration from the positive parts of the better and more realistic examples. Just because the system is rigged against you, doesn't mean you shouldn't try to achieve things. Not trying to achieve things is decidedly worse. The belief that success is completely luck-based is useless, unless there's a uniform distribution of 'success' over all types of people and their strategies. That is, even if I leave my job now without any verified product, I have the same chances to establish a profitable business, then a guy who already has paying customers. Is this because people prefer discussion threads over collaborating in a wiki, or is this because ExplainXKCD is not as widely known as it should be? Even as a developer, when I saw "tokenbrowser.com", I was expecting to see a web browser. Visually, it looks more like a chat client (makes sense since they are taking inspiration from WeChat). -. [1]: [1] - If they are using the standard protocol then how do they connect to the Ethereum network? Do they use their servers as proxy to the network? Because if it's so, that would defeat the whole point to me.. Open Whisper Systems source is GPLv3. I wonder if they will reset the usernames when it gets put on livenet because it kind of seems unfair. "They spent much of their energy one-upping rivals like Lyft.fts business. (Lyft, too, operates a competitive intelligence team.)" At the time, Uber was dealing with widespread account fraud in places like China, where tricksters bought stolen iPhones that were erased of their memory. To halt the activity, Uber engineers assigned a persistent identity to iPhones with a small piece of code, a practice called fingerprinting. Uber could then identify an iPhone and prevent itself from being fooled even after the device was erased of its contents. Source: McDonald's: Behind The Arches, John F. Love (July 1, 1995) Edit: changed ie to eg, thanks for the correction all What impresses me least about McDonald's is their ruthless child-targeted advertising. EDIT: in sort of a quaint way the incentive structure is reminiscent of the manorial system. for an entertaining and educational dramatization of the McDonald's story, including the franchising and real estate leasing aspects. In addition to being a very well-done movie, it does a superb job of describing the relationship between the visionary founders of a startup, and the sales guys and bean counters who turn it into a successful business. It doesn't matter that the McDonald brothers were revolutionizing burgers, the telling of this part of the story captures perfectly the same sort of activity that goes on at any startup with a new idea, (emphasis on new). It also captures very well how the suits recognize a good thing when they see it, buy into the vision (but for very different reasons from the founders), and finally take over and render the founders obsolete. Really great movie for anyone involved with startups. The same goes for any restaurant, it's why they ply you for drinks. When people talk about McDonald's "selling burgers", what they mean is McDonald's and its franchisees. - percent franchised vs owned... - quote from article that is misleading"Of that $18.2 billion generated by company-operated stores in 2014, the corporation keeps just $2.9 billion. Of the $9.2 billion coming from franchisees, the corporation keeps $7.6 billion." So I think it's a bit misleading and hyperbole to say 'how they really make money'. The only reason the can make that money is because of the product and the customer base that patronizes the McDonalds. So in the end it is because of the product. "How they really make their money" is because of that product. Breweries (and "PubCo's") typically own the premises, which is leased to a tenant (publican) who is required to purchase the brewery's products. Well, if one thinks of how many of these burger joints.. And yes the burgers also make some good money ;) If all you need is a basic drink, they get it more or less right for several hundreds of a percent lower. The takeaway: Don't dismiss a useful service that you can't directly monetize. It's possible that you can gain high-quality information which can be monetized indirectly. It's all about getting better information about a particular market than everyone else. It's almost like saying that grocery stores are not really in the grocery business, they are in the business of accepting cash and credit card payments. True, that's where they "make their money", but that business would dry up pretty quick if they didn't stock groceries. I found that rather depressing. All those people struggling to improve their business are merely struggling to increase the income of the property owner. (I guess if I had the money and inspiration to become a property owner it would be less depressing). I think a lot of why real estate works for them is that the business is not affected by recessions - they may even sell more burgers if people can't afford fancy places. So they can buy real estate cheap when others can't. Also - when people choose to eat less burgers, or there is less innovation in the menu, the stock price dips. Nobody goes there anymore. It's too crowded. I know it's a serious worry, but seems like one of those good problems to have.... I've been to multiple understaffed McDonald's and man does the quality suck. When they have staff things are decent but now I can predict when a McDonald's will be bad. This is a beautiful story. Thanks for sharing so well.. Is part of the problem authoring tools? Every time I need to make some SVG by hand, I look around and keep coming back to Inkscape and Illustrator. I can't afford Illustrator, and Inkscape has just never stuck for me, it feels very clunky. I've used lots of the other tools out there but nothing seems great. :) Full SVG just seems too high level to be implemented universally, especially when sent in some form to a GPU for parallel evaluation. Now have a moment of silence for OpenVG Yet there is hope:... * hopefully compatible with Path2D API... I'm not sure how it got this way, but it seems to be connected to the W3 consortium, which has many other instances of creating exceedingly complex, difficult-to-implement standards. If anyone is questioning the relevance or flexibility of SVG or its ease of use check my CodePen stuff - with a library like Greensock you can do almost anything with SVG. There's definitely something wrong with funding of web standardization work (or lack thereof) though, that needs to be brought to public attention. The WHATWG/W3C situation is unsustainable IMO.. Boy howdy do I wish Adobe hadn't mismanaged Flash and Flex so badly they killed them. If they'd gone more open, fixed performance issues on non-Windows platforms, and actually followed through on the Tamarin gesture we'd all be in a happier place.! [1] As a common representation for draw programs, SVG is quite useful. But apparently it accumulated way too many features, and SVG 2, this author says, was an solution to a non-problem.. Design a set of re-usable components in Sketch that get turned into JavaScript widgets and used in a product The JavaScript widgets are are modified, extended, and changed. Maybe a line here, a color here. Designers now sometimes have component designs dont quite match what they look like in the wild This tool now lets them re-create the Sketch file from the components as the look in the wild. That means when designers work on whole pages, made up of widgets, theyll look exactly like they would in the wild. But this tool is related to that ui/ux version of Sketch (but with/for React), and not the mis-named Sketch (that was for React)? Naming is fun. Design Systems and related tooling makes total sense at certain scale and I can definitely see both designer and developer efficiency gains from consistent building blocks that Design Systems provide.Jon I'm curious if this would still make sense if AirBnB weren't so invested in React and React Native. 1) Create designs in sketch (mainly core components) 2) Code those designs in React that will generate the React translated version of the sketch 3) Use the react generated sketch to build non-core component designs in sketch.. 4) When the core design changes, update the react component to match the new designs 5) All the other components in the sketch will automatically start using the new updated sketch component A market in which buyers are not free to choose better products is not a free market. A market in which new entrants cannot compete fairly against established players is not a free market. A market in which innovators have to get permission and pay established players for "access" (think ISPs) is not a free market. And yes, a market in which economic and political power is concentrated in large corporations geographically clustered in a handful of giant metropolitan areas... is also not a free market. Those corporations have both strong incentives and the means to change the rules of competition to their advantage. "How Democrats Killed Their Populist SoulIn the 1970s, a new wave of post-Watergate liberals stopped fighting monopoly power. The result is an increasingly dangerous political system."... A lot of these "monopolies" result because of regulation pushed by combination of well-meaning and self interested people and corporations (see bootleggers and baptists). Her examples suggest it'd be better to focus on the marriage between corporations and government, which allows companies to focus their energy on getting gov to hassle their competitors vs improving their own product. A strip mall with a Subway, a couple national fast food joints, and if you're big enough, Wal-Mart. There are literally 1000s of towns with this copy and paste setup-- how could this not be detrimental when money is going to a huge corporation every time? These are both cases where it's not so much anti-merger/monopoly law that's the culprit, but the general structure of the legal system that favors those with the larger pockets and forces out upstart manufacturers. 1 -... That last bit sentence me a bit odd. Rather than go into the details of incentives of hospitals and why they would forgo a better alternative, the author just attributes it to "monopoly". If this is true, there is some deeper misalignment with incentives in this industry that won't go away by just removing product providers that control a significant portion of the market. Or something that the author doesn't know about the industry that would make this decision make sense. I ended up using Reddit for blog comments: Reddit has: 1) a good commenting interface 2) many existing users with accounts 3) a low barrier to a signup for those who don't (you barely even need an e-mail address) 4) an API The downside right now is that you have to leave the page to comment, but I don't think it's a big deal. It probably lowers engagement a little, but I find that the most commens happen on other aggregators like HN, no matter which service you use for comments. I also use reddit's RSS feeds, since a few people asked for that. Reddit has its share of immature users and a culture of snark, but my subreddit has managed to steer clear of that. > For unauthenticated requests, the rate limit allows you to make up to 60 requests per hour. Unauthenticated requests are associated with your IP address, and not the user making requests. In this case, all the comments for an issue are returned with a single API call, making the limit a nonissue (unless someone is binge-reading more than a post a minute) Also, it may be a good idea to sanitize the comment.body_html. That seems XSS abuseable. I'm not affiliated with the site, I've just used them for comments on one static github hosted blog post. What surprises me is disqus didn't even give a shit about the page's loading time in an effort to violate users privacy and trust. Disqus, If you are reading this thread, shame on you! I've done something similar with my blog. [1] It's not using Disqus or any heavyweight 3rd party solution for comments. Instead, I've created something very simple, similar to GitHub Issues frontend UI and backend, and used that. The backend is completely pluggable (it's an interface [2]), so it can be implemented by talking to real GitHub API [3], or any custom implementation you want. My blog uses a simple JSON files implementation, so I can avoid a heavyweight database dependency. Oh, and I've also implemented reactions. Not just 6, all of them. [4] I do use GitHub for authentication though, I don't want to make people come up with yet another password. [1] [2] [3] [4] Why not stand up a Discourse instance for your comments?... I'm sad that didn't take off, it was so handy. Disqus without ads and without real-time comments is pretty fast, but those days are long gone and they're also full of spam. It's also such easy spam to catch that it feels like they just stopped caring and are cashing in as long as they can. Also why not just use Gists? I've seen a few people use them as a standalone blog pages with markdown files, and it also has an API available. A one-click setup simple enough for non-technical users. Instructions should be along these lines: 1. Sign up for AWS if you haven't already got an account 2. Generate a keypair and run our setup/load our template/whatever (I'm a bit hazy on AWS automation but I would imagine there's a fairly obvious way to do this. The new CodeStar thing looks like it might fit the bill) 3. Place this snippet of javascript in your page The service would use Lambda and DynamoDB to to handle storing/serving the comments. Costs would be fairly minimal for low-traffic sites. Rough guess is that this would be no more than a few days to a couple of weeks work for someone. Am I over-optimistic? So either someone does this to scratch an itch or we fund it via Patreon/Kickstarter. [1] I don't know if Disqus requests so much tracking. Currently, I am setting up a personal blog and looking for a comment system for it. There are two choices: Disqus and Twitter. Why? Disqus is free and easy to put it to whatever blog platforms you use and Twitter is free too, I think many people have it. After reading this, I think GitHub is not a good place to give a comment because somebody who doesn't have account must register first. I am talking about "non-developer" reader. Does anybody here use Twitter as a blog comment system? I would like to know your experience since some of people usually use it for their blog. Bottom line is this. If you put backdoors in, or exploit 0days for your own, they will get out in the wild eventually, and suddenly you have massively weakened infrastructure, corporate, and government security... basically all the things important to national security in general. So while I don't disagree that triple letters need some cool tools to get shit done, I think this function needs some technocratic oversight specifically for this issue. It's time for a new Church committee. That we connect directly to a worldwide network with minimum consideration for security is very troubling. In decades to come, we'll look back in humility and realize that the manners in which we used technology added grave risks to our health. In 2017, we are not in the "wild wild west" age of technology. Rather, we are firmly in the dark ages. We're so far away from having an understanding regarding the lack of social maturity in our technological growth that we fail to properly consider the downside risks. This is a tough nut to crack because technology is simply too good for the majority, even the technically inclined majority. I recall efforts by very very talented folks to build decentralized technologies to help mitigate some of these long term risks, but such efforts will remain firmly at the fringes of intellectual superiority for a long time. Meanwhile, Goliath will simply grow stronger in time, unless there is some major cultural shift. Is there any such shift happening, beyond the fringe? It is also interesting to read the outrage about the tools and the presentations on how to use them. If you have ever read the user's manual for a cluster bomb which no doubt tells you in detail how to maximize the number of people it will kill, you get a sense of how destructive and outrageous war can be. Why should cyber war be any different? And how is it any different to use a zero day to compromise a system than it is to use an architectural feature of a building to bring it down on top of its occupants (other than the obvious loss of life). Exploiting defects in the deployed system to maximize the effectiveness of a munition, not a new thing at all. Just the reality of warfare. We're pretty clearly already in a form of warfare and it is having visible effects on things like infrastructure and elections. So how do we make the battles visible to the common folks? How do convince Mom & Dad to patch their router so that they don't inadvertently aid the 'badguys' in their quest for dominance on the digital battlefield? Definitely feels like Phase III of the Internet has begun to me. Personally, my view is that we should be putting the focus on the defensive side. Protect infrastructure, IP, etc. I believe the reputation of technology in general is harmed by the offensive mission, and US companies disproportionately so. There is now even greater incentives for our adversaries (and friends) to foster development of technologies that compete directly with US products in their own jurisdictions (where they can get a look under the hood). * The zero-day has to be powerful enough to allow the agency to gain full access & remotely patch the zero day -- i.e. if the zero-day gets out, and the agency didn't warn the manufacturer ahead of time and instead used it for its own purposes, it must have the capability to "immediately" scan the internet for the vulnerability and patch it where accessible. * If the above condition is not satisfied, or if the agency can't/won't dedicate the resources to develop a backup patch, it should be required to alert the manufacturer immediately. Does this cost more? Yes. Does it limit some of the monitoring capabilities they will have? Yes. The second seems like a pro. The first one seems like a worthy compromise for questionable activity with high potential for collateral damage. Seems to contradict itself? If it's continuously relaying information, wouldn't that make it easy to detect? Their terms of use are awful.[1] Note that they want to operate under British law, where libel law favors the subject. They have an indemnification clause, so their volunteers could be compelled to reimburse WikiTribune if WikiTribune loses a libel suit. That's happened in the UK; see the famous McLibel case, where McDonalds sued two Greenpeace volunteers. That decision was overturned by the European Court of Human Rights. But, post-Brexit, that level of appeal will no longer be available. They also appear to have plagiarized the terms of use from other sites. One section reads "We may, in our sole discretion, limit or cancel quantities purchased per person, per household or per order. ... We reserve the right to limit or prohibit orders that, in our sole judgment, appear to be placed by dealers, resellers or distributors." That exact text appears on other sites, usually ones that sell tangible goods. It's completely inappropriate here. Sloppy. This stuff matters when the business involves pissing people off. Don't volunteer to write for this organization unless and until they work out the liability issue. [1][2] So the fact that they write front page article on some terrorist attack in say France that kills 5 while a similar drone strike on the same day in Afganistan kills 20 and gets buried on page 30 is the point. Who was is that once said the first casualty in any war is truth? And how many blows did we miss that lead to that first casualty? Regardless, I see little downside to this and hope it's successful! I think the real promise lies in Wikitribune potentially going toe-to-toe with "real news" like CNN or the Washington Post. These outlets also don't always get the facts straight and can't be said to have a diehard following. If a superior option presents itself, readers will follow. The fundamental problem that these sites run into is a thorough understanding of issues in the news requires context, and very often not the kind of context that can fit into an 800 word blog post on a subject. An 800 word blog or article of any sort necessitates that you're going to make choices about which evidence you're going to include, which sources are credible and which sources are not, which sources add to the discussion vs which only serve to obscure. As soon as you do that, you're adding bias. You can set out to build an 'evidence based' news site, but what you quickly find is that you've built a site with paid journalists (who have their own biases) supported by volunteers (who are the people most likely to have political skin in the game). The problem is that people want a shortcut for everything - they want an 800 word post that will tell them everything they need to know about Syria. No such thing exists. There's no substitute for actually putting in the work and navigating the bias yourself. Ha! Oh c'mon, anyone who's experienced the activistism of certain groups on Wikipedia knows there's plenty of people with a vested interest in this kind of thing. So, in attempt to not be "that guy" that just complains here's what I'd suggest as a start. - Institutions need to drop their relationship with Facebook et al (The Guardian has just done this [1]). - There's a few places (and in the interest of avoiding starting a flame war, I'll forgo naming them explicitly) that parade themselves as "objective" sources of news by telling you they're explaining "complicated" concepts in digestible ways. In my view, that's just a rhetorical tactic to disguise what is actually just advocacy journalism. It's not objective at all, and seeks to form your opinion rather than present you with data from which you form your own. These places need to either be shut down, or pivot back to what we'd traditionally consider actual reporting. - I consider myself reasonably well read, and read the actual, physical paper daily (when I can, I suppose). There is a distinct difference between the content I see pushed on the internet and what's in the traditional paper and it's this: increasingly articles that belong on the opinion pages are pushed elsewhere, probably because they know it'll generate more clicks elsewhere on the site because it makes either a controversial or marginally supported claim. In my view this directly contributes to the loss of faith people have in the Journalistic profession because it's just so damn easy to point out instances of bias. So, hire some old school editors and fire the "social media" guy and put content where it belongs. That's just what I can think of off the top of my head right now, but I'm pretty convinced that "crowd-sourcing" is not the answer to this problem. [1]... I seriously hope this project can overcome the prevalent, subtle biases in media. For instance, every single headline from the recent French election mentioned "far-right" Le Pen without also mentioning any ideological affiliation of the other candidates. Painting your opponent as an extremist is an effective political tactic, and "far-right" certainly sounds extreme. Were most media outlets opposed to Le Pen, hence the extreme label? Why not label any other candidates? I'm not necessarily optimistic about the prospects for unbiased news, but I will be watching this project as it progresses. [1] This is even more pronounced for retrospective coverage, where developments in the story as it had evolved are hard to glean from the coverage at the time, but important facts are surfaced throughout the coverage that are often elided in a retrospective published by a news source, but are well-represented, even controversially (where facts disagree or question the overall narrative). My main complaint about the current trend in journalism (under Trump) is that the desire to sell clicks is so strong that you get no idea whether anything that happens is highly unusual or just routine, but the negative spin is so heavy that I can no longer trust that I'm being told how unusual each event is unless I really dig into it to find out. A great example is the ongoing harassment of international travelers in the US. The impression I get is that things have gotten much worse, but there's certainly ample evidence of unpleasant behavior even under previous administrations, and some slim cherry-picked data saying that it's gotten worse. This is clearly a space where better sourcing of primary sources would help to make things a lot clearer, and to an extent, a somewhat adversarial approach to news research would help to reduce the tendency towards alarmism. - - home of ... data journalism - - seeking a ... data journalist - - ... is a data reporter This is hardly the only source of bias in the news, which is an age-old problem. We'd be better off just expecting news organizations to announce their bias up front so that we don't have to read between the lines in order to ferret out its nuances. I tried to register as a supporter. Upon submitting my credit card, I got a CloudFlare error. I have no idea what was supposed to happen when I registered. When I received the confirmation email, I clicked the "confirm" button, was asked to prove I was human by identifying photos of gas stations, then taken to the website of impossible.com instead of WikiTribune. "One of these days the people of Louisiana are going to get good government - and they aren't going to like it." If there ever is a 'paper' that publishes the full unvarnished un-redacted truth about everything, it will have very many enemies, some of them very powerful. Wikitribune solves a problem, just not the problem they have defined as the target. They've used a naive view of the problem; the model under this ignores the existence of antagonists and too much faith in crowd sourcing difficult problems. Antagonists will prey on services like this, and off the top of my head, here's 2 ways in which such a service can be made biased. 1) baseless accusations, oft repeated. Find the facts inimical to your (the antagonists) position. Ignore them. Find facts which are borderline, and have dog whistle properties - highlight these facts ad nauseum. Say that "Wikitribune is biased". Repeat till it sticks. Then target the facts inimical to you. 2) flood the service with facts that serve your cause- humans have only so much working memory. ---- The particular structure wikitribune has chosen, will result in issues. There's a reason print news papers had an editor and a whole staff dedicated to working together. With volunteers there's no structure, and that causes failures, just consider the Boston bomber case. Of course with a journalist in the mix the assumption is that they will push back. But the structure is supposedly egalitarian, which just means that this is going to end up causing the same politicking, and admin arguing that plagues Wikipedia. Recruit everyone, don't get volunteers. Get the whole team. > Articles are authored, fact-checked, and verified by professional journalists and community members working side by side as equals, and supported not primarily by advertisers, but by readers who care about good journalism enough to become monthly supporters The wisdom of the crowd fails all too often. As another article recently discussed, it's 5% of the people that take up most of your time. How will this structure deal with truly divisive news articles? Or people who have conflicts (and conflicts of interest) within the group? How will you deal with the fact that one day someone can say "volunteer X was a pedophile from <country>!" Kudos for trying it. This looks like a propaganda machine which will use the wiki brand about to be born. Honourable aims for this project, however once you are literally only reporting the presented facts (without bias - aka opinion) surely you are just a Wire Service? Otherwise I love the idea that there must be an attributable source to all information they present -- no more "senior government officials" or "anonymous FBI agents"... I've looked at large articles I contributed to a few years ago and they are now disasters. Full of bowdlerisation, inconsistent style, and false snippets of information. I think the abusive nature of many Wikipedia admins, and the hostility of Wikipedia itself to knowledge, will eventually just make it a 4chan with pretentions. I've been a multi-decade Vim user, until I switched to VSCode last year. It made me realize how much better the user experience can be for an editor. I had all kinds of complex vim configurations and plugins with special cases for linux vs. mac, server vs. desktop, GUI vs. terminal, all of which are a huge pain in the butt to maintain. If there was one thing I could ask of Vim (or even emacs), it'd be a consistent high-quality default user experience. (Ofcourse, the default experience in VSCode isn't perfect either, but it took me four lines in settings.json and four plugins (vim, go, eslint, clang) for a near-perfect experience.) One huge advantage is that I can run the dev setup on a remote server which allows to keep the entire enviroment with all build tools and watchers live and persistent for weeks. You can do this on a local environment as well if you never shutdown the system or suspend only but it still feels different. Just an example: You worked weeks ago on a side-project and want to get in again for a small fix. Just to recall and open all relevant files, run the build tool and server plus tweaking the layout requires five minutes and usually you don't do it, you just want to fix one line and not think about the project setup. With tmux you go to the respective workplace with prefix+p (for previous) in case you kept the workplace still running. That's it. With a 1GB RAM VPS I can run many tmux workplaces/windows each with ~8 vim instances or other processes. Further, I can develop on any of my notebooks/PCs/OSes with an ssh client installed, even on my phone. Btw, tmux and vim are perfect for phone keyboards, try it and it happens really frequently that you are on the go and want to try another idea/fix. Here, prefix+z for zooming into a pane is quite helpful. And when I get a new computer my dev environment doesn't have to be setup again. I am still using the same remote server which survived three notebooks now. And a (small) bonus: If you want to show coworkers your work in a browser (if it's a website) you give them just your static server IP without the need to ifconfig your current local dynamic IP before. Running your dev environment remotely is a small thing but makes a huge difference in daily use. i3 is a window manager that can outcompete anything you can do with vim splits or a tool like tmux/screen. It's whole existence is based around putting windows in the right place at the right time. Ranger is a vim-like ncurses file browser. I think it's genuinely one of the most underappreciated tools in programming. The ability to hjkl through your file system, with quick marks, with vim-style cut/paste, with visual mode, with about 20 other things that I use daily which just means that no other viewer comes remotely close. My typical flow has between 4 and 12 terminals open, with the bulk being ranger->vim, which allows me to easily navigate complex project structures. The others are usually make, or htop, or some ssh. I'll usually have a couple of web browsers open in another workspace as well. i3 tiling extends to all applications. -- Dunno is it only me but I see a weird thing going on with "new" Vim community. Everyone is starting to use it as a VSCode or Atom, trying to use hundreds plugins but most of them don't even know how to use tabs properly... I see most of this by new "neo" fans "you don't know how to make a thing in Vim? Download Neovim... or even Spacevim configuration." type of way. :) Don't want to start a war here because every editor has it's own fans and I do not want to offend anybody either. But every one should learn to use vanilla version of their editor of choice before moving further. I have a function in my .vimrc ( ) that allows me to send current vim selection to the adjacent tmux pane with vimux. This comes in very handy in REPLing sessions ( MySQL and the like ). For copy pasting stuff ( like ids, urls, SHAs, etc ) I use which is awesome and you should totally try it! ( </shameless-plug> ) Tiling Window Managers are awesome, and I totally see why people who can't use one would choose to use Tmux, but if you have the option, I would totally recommend just going with the TWM and skipping Tmux. When I work remotely, I use the tmux integration provided by iTerm2 to provide more native windows, and it works well enough that I don't have to think about it most of the time. If I were moving back to Windows or to a Linux development machine, I probably would go back to tmux in a single window. I'm just somewhat glad I don't have to right now....... One additional trick I often use is to look for inotify events in split tmux panes to compile/run tests on every save.... No, I don't think I have a brain injury. I'd love something configurable, like a dedicated WM key, a dedicated tmux key and a dedicated vim/app key. I'm sure it's possible to setup manually, but it would take a lot of work. That would be a nice way to integrate with the surrounding environment without so many plugins, just simple programs that would run in a separate window. Vim remote can help, neovim-remote might help even further. It has panes, sessions, windows. Customizing is a lot easier if you're not already familiar with tmux. The one thing you get with tmux that's killer is if your shell dies (remote disconnect, you have to logout, etc) the processes in tmux keep running. I also tried out vim-arpeggio but kept seeing "Arpeggio is not defined". Looks like the project hasn't been updated for a while. I have mapped Ctrl-C to ESC and I use it often. One specific instance I have seen vim crash is when the cursor is at np.inf and I press Ctrl-C. What we see in most products is a result of the accountants saying "no" to too much. Cheap parts, assembled cheaply, pennies saved per part. What we see here is the exact opposite: the accountants didn't say "no" nearly often enough. Apple manufactures custom everything because they can, and because they sell at massive scales. Juicero wanted to be Apple quality without selling at Apple quantity. I fully believe you get a better cup of juice squeezing with their massive press rather than by hand because it can press over a bigger surface. I also believe it doesn't matter a bit, because this is a worthless piece of equipment. Beautiful engineering, though. I'll definitely be on the lookout for other write ups from Ben Einstein. To anyone wanting more content like this, I also recommend the "Bored of Lame Tool Reviews?" (BOLTR) series of videos from YouTuber AvE: Also, I don't believe "330V 15A" for a second. Maybe 2A... I once got a chance to look closely at the mechanism of SF's JCDecaux overpriced automatic street toilets in SF. Those cost about $150K each. The mechanism is all Telemecanique industrial control components. If you built a washing machine that way, which you could, it would cost $5000-$10000. Compare the Portland Loo.[1] I would quibble about the custom power supply though, they are not as difficult as they were in the past. Much of the 'magic' of building good SMPS supplies has been encapsulated into very clever chips and certification bodies have seen enough of them now that the checklists are pretty straight forward. I don't get the outrage though. Also, as overwrought and unnecessary as the Juicero product is, I can't agree with the "it's useless because you can do it by hand" argument. I could probably hand wash my clothes as well as the washing machine does in the same amount of time, but it's hardly useless. While the Juicero is pressing your juice you can be making your lunch or something. Who knows why the CEO's response skipped straight past "having the machine do it saves you time" to "it can automatically lock you out if your pack expired." These subscription models, or even machines that require only a certain type of consumable, are effectively leases. Sure you may buy a piece of hardware, but it is only useful for as long as you buy and use the required consumable. I am comfortable in renting a place to live - especially since I have moved about every 2-3 years in recent memory - and I am comfortable paying a subscription fee for some software and services. But I am not that comfortable when I have to subscribe to food or clothing for example. 700bucks for abag squeezer? Something went terribly wrong. It feels like they aimed to produce some advanced robotics and built the wrong product. Could turn this into a limb for amputees, makes more sense and actually good use of the resources. [1]: If you are serious about juicing you can find cheaper products that don't require packets. This is a convenience item for people with a lot of money. There is no way this company will be worth $120MM unless they design a low cost model. You do have to clean up a mess, but if your time is that valuable you can hire a maid to do it for about that $5-$8 price point of the packs. - two motors, one of them exceptionally strong - a durable drive train - a control board with flash memory, wifi, a camera and a USB plug for flashing without additional tools(!) - a durable aluminum frame Those parts look like they could be building blocks for some interesting hobby projects. Did they ever think about selling to makers? But at the same time, it feels like they have achieved such a great quality that the learning and experience to design and execute could be very valuable as an unintended consequence. So, maybe quality always wins in the long run nevertheless. Wouldn't you hire these guys and pay a premium, if you wanted to manufacture great hardware? [1]... But this thing doesn't appear generally useful based on what I've seen about this story. It seems to want to lock you into using food from a particular vendor. How much less appealing would my stand mixer have been as a purchase if it were outfitted with a QR reader looking to make sure that the KitchenAid cookie dough I was giving it was fresh? That would be a deal breaker. >No prep. No mess. No clean up. That's brilliant because people don't like cleaning. Cleaning regular juicers is annoying to the point that only few people use them regularly. There are enough people with money to spare that this can become a success. I haven't seen it mentioned, so let me spell it out: This is Nespresso for fruits. [1]: Edit: Just got to the bottom of the article. Looks like sealed hierarchies is exactly what they explore. FYI, I recently found out that C# can actually do multiple dispatch... Please use a Scala unapply() and not just constructor parameters. The former gives much more latitude to build patterns. I have a ton more to say about all of this having written in Scala and Kotlin extensively. I'll just say that it is useful they are already thinking about new variable assignment to parts of matches and NOT concerning themselves w/ "smart casts". * heredoc/multiline string/embedded interpolated strings* concise array, map, and object literal initializers. * structural/anonymous types Simple things like multivalue return become an exercise in boilerplate in Java. As much as I like Immutables.org or @AutoValue, I should be able to return a struct or use destructuring operations at the callsite. The hack in Java is to use annotation processors to provide nice fluent builder patterns, but really the language should have first class support for this. 1 - case classes / value classes / data classes, whatever you want to call them. 2 - match-and-bind syntax ... 11? - fancy pattern matching This maybe says more about how much I pay attention to what's upstream in Java, but I found the fact that this is just a hypothetical proposal, in April of 2017, strangely shocking. I guess I figured it had to be on the docket for a future java version already. I liked that this article laid out the specific options and various shades of gray that can constitute parts of "pattern matching". I'm curious for thoughts on a syntax like this: This is somewhat more difficult given that even when using Flow or TypeScript, there's relatively little type granularity available at runtime.This is somewhat more difficult given that even when using Flow or TypeScript, there's relatively little type granularity available at runtime. x = match y: case > 3: () => "it's bigger than three" case 2: () => "it's strictly equal to two" case Integer: (x) => `some int smaller than two: ${x}` case String: (s) => `some string: ${s}` case Array: ([ first, ...rest ]) => `a list starting with ${first}` case Object: ({ a, b }) => `an object with property a: ${a}` Any thoughts? [0] * in the cases where I don't have control over the common base type, I've written a builder pattern that constructs a sequence of predicate-function pairs and applies them appropriately. This looks like so:* in the cases where I don't have control over the common base type, I've written a builder pattern that constructs a sequence of predicate-function pairs and applies them appropriately. This looks like so: <T> T match(Function<X, T> foo, BiFunction<Y, Z, T> bar); The main disadvantage here is that it doesn't work well with generics, because the class objects have raw types.The main disadvantage here is that it doesn't work well with generics, because the class objects have raw types. new PatternMatchingHelper() .append(Foo.class, foo -> doSomething(foo.x)) .append(Bar.class, bar -> doSomethingElse(bar.y, bar.z)) .otherwise(x -> fallbackValue()) .apply(objectOfUnknownType); You could probably extend the second approach to get something close to the arbitrary predicates that pattern matching would provide, but the syntax wouldn't be nearly a clean as having it in the language. [1]: I wonder if Oracle could create some excitement around the platform by creating or adopting a new language as an official repla^D^D^D^D^D "new member of the family" to implicitly succeed Java just like C# replaced Visual Basic for most use cases. Java could be kept around as a sop to die-hards like VB.NET was. It's great that the JVM allows a thousand flowers to bloom, but it's not great that the only "official" choice on the JVM is a language that hasn't been able to evolve very far from its 1990s roots. It generates code for algebraic data types which offer a typesafe interface similar to the `case` statements in languages that natively support pattern matching. Why declare a new variable? The Ceylon syntax works great with union types too.Why declare a new variable? The Ceylon syntax works great with union types too. if (is String name) { // compiler knows 'name' is String in this block print(name); } else { print("some other text"); } [1] And if you don't want the type, the value of any other method, function, or attribute could be checked by "is?" or whatever syntax token you want there.And if you don't want the type, the value of any other method, function, or attribute could be checked by "is?" or whatever syntax token you want there. instanceOf x is? { Int { System.out.println("It's an Int"); } String { System.out.println("Hello, " + x); } _default { System.out.println("This type is not explicitly named here."); } } Further tests could be saved for within those blocks to save complexity. What's odd though is that in Java this particular example seems to want multi-method. Testing the type explicitly and acting on it is more akin to duck-typed language programming. You see this pattern pretty often in Perl for example. If I want to write in Perl, I typically reach for Perl. Paper::... [0]: Is this addressed with pattern matching? You can see it live! [1] [0] [1] "randomisation; allocation concealment; blinding of therapists (intervention supervisors); blinding of participants; blinding of outcome assessors; handling of incomplete data (use of intention-to-treat analysis); selective reporting and any other risk of bias." [1] Also, the result was only statistically significant for poor quality control groups that didn't engage in any shared activity: ." [1] In summary, a few poor quality studies with large bias account for most if not all of the effect reported in this meta-analysis. [1]... Staying 30 minutes longer happens easily so it's 7:30. Commuting to the gym would take another 20-30. 1h in the gym and it's 9 (or later). Commuting an hour home and it's 10. Go to supermarket, maybe cook something up and it could easily be 11 already. This leaves 1-2h max to do anything else, given I am not dead from the gym. Now spinning up the brain to focus on something creative also needs a bit of time. Morning gym is hard as well. All gyms around my home open from 9:30/10:00 which is when I have to be on the way to the office already. So the time slots that are free are very competitive. Pick one: Do I go to the gym? Do I watch a movie with the gf? Do I program? Do I learn the next grammar chapter? Do I work on other hobbies that I've been putting off too long? Do I meet friends and catch up on social life? To be honest, this 'problem' makes me currently think of switching into a part time job, just so I have more time for the things I actually care about. (Part time remote for optimum happiness but that might be impossible to come by) Plus, the fact that your body will go to shit if you don't exercise. Before I started lifting weights approx 10 years ago, I had back aches from sitting in an office chair all day. After regular, challenging, weight training, those problems vanished. Why? Because my muscles are strong now. If you don't use your muscles, they soon because worthless, and painful. It's amazing how much stronger you get in a short amount of time as a beginner in weight training. You don't like exercising? Boo hoo, no one does. I'd much rather eat pizza and drink beer than put 30 miles on my bike. But, I know it's important, so I suck it up and go. Even when I absolutely don't want to. I prefer to think of exercise as normal and sitting around as the mind-dulling deviation. I would say: Not exercising can dull the mind. or A sedentary lifestyle instead of getting your heart pumping can dull the mind. "Researchers found that the foot's impact during walking sends pressure waves through the arteries that significantly modify and can increase the supply of blood to the brain."... And although I have considered never picking up a weight again, I know the benefits of weight bearing exercise and so, sometime this year, will go back to they gym, but less frequently and for a shorter duration. And never forget that 50% of your health is nutrition. Abstract:. This review details the findings surrounding the impact of running on various health outcomes and premature mortality, highlights plausible underlying mechanisms linking running with chronic disease prevention and longevity, identifies the estimated additional life expectancy among runners and other active individuals, and discusses whether there is adequate evidence to suggest that longevity benefits are attenuated with higher doses of running. Conclusion: There is compelling evidence that running provides significant health benefits for the prevention of chronic diseases and premature mortality regardless of sex, age, body weight, and health conditions. There are strong plausible physiological mechanisms underlying how running can improve health and increase longevity. Running may be the most cost-effective lifestyle medicine from public health perspective, more important than other lifestyle and health risk factors such as smoking, obesity, HTN, and DM. It is not clear, however, how much running is safe and efficacious and whether it is possible to perform an excessive amount of exercise. Also, running may have the most public health benefits, but is not the best exercise for everyone since orthopedic or other medical conditions can restrict its use by many individuals.... NYT reporting on the study ("An Hour of Running May Add 7 Hours to Your Life"):... Can a person overcome lack of good nutrition by exercising regularly ? Exercise goes hand in hand with nutrition IMO. People who exercise tend to eat better and healthier foods. If someone did not exercise routinely - they could easily improve their health by eating properly! What is more important? healthy nutrition or regular physical activity or both?! * And dont forget about about sleep!!! If we are building the safest transportation system, what role do driverless vehicles play? Wouldn't that be the narrative that actually saves the most lives? I'm not sure this rider trial thing strongly signals any of them. You would want real world end-customer experiences regardless, I would think. I think it is great that they are getting additional exposure to nominally real world users here. However, I'm not exactly sure what they are learning in user behaviors. Is it "Can we make a less expensive livery service?" or is it "How freaked out do people get in self driving cars?" or is it something else? I went to a conference last week where there were several talks that were pretty critical of self driving 'hype' given the HLS[1] issues and the ability to inexpensively 'spoof' the AI[2] to see something that isn't actually there (road signs being particularly vulnerable). It left me thinking I might be more optimistic about the technology than I should be. [1] "Health, Life, Safety" the general basket of things that are super critical to minimizing injury and death. [2]... -- on Facial Recognition but sign recognition has the same problem. * People can apply to use/borrow a Waymo vehicle (RX450 or Pacifica) for some period of time. * "as part of this early trial, there will be a test driver in each vehicle monitoring the rides at all times." * Limited to Phoenix metro area for the time being. * You apply here: * Waymo will be adding 500 more of the Pacifica minivans for this program. This is for cases where you want the credit but still want the protections afforded by being somewhat anonymous. Similar to WikiLeaks but more focused on allowing the company or entity to solve their problems and representing fairness on all sides. [EDIT]I decided to log in today just to see if it's still there (was a couple days ago), and it's finally been patched. If I had used a throwaway I would gladly let you guys know the bank, but I won't since it's trivial to find out who I am from my handle. "Sign this NDA or we will send the FBI to arrest you because you found that our banking website's security was completely fucking broken and told us about it." Jesus fucking christ.
http://hackerbra.in/best/1493172662
CC-MAIN-2018-43
refinedweb
21,130
62.27
1 /*2 Copyright (c) 2002,2003, Dennis M. Sosnoski.3 org.jibx.runtime.impl;30 31 import java.util.ArrayList ;32 33 /**34 * Holder used to collect forward references to a particular object. The35 * references are processed when the object is defined.36 *37 * @author Dennis M. Sosnoski38 * @version 1.039 */40 41 public class BackFillHolder42 {43 /** Expected class name of tracked object. */44 private String m_class;45 46 /** List of references to this object. */47 private ArrayList m_list;48 49 /**50 * Constructor. Just creates the backing list.51 *52 * @param name expected class name of tracked object53 */54 55 public BackFillHolder(String name) {56 m_class = name;57 m_list = new ArrayList ();58 }59 60 /**61 * Add forward reference to tracked object. This method is called by 62 * the framework when a reference item is created for the object63 * associated with this holder.64 *65 * @param ref backfill reference item66 */67 68 public void addBackFill(BackFillReference ref){69 m_list.add(ref);70 }71 72 /**73 * Define referenced object. This method is called by the framework74 * when the forward-referenced object is defined, and in turn calls each75 * reference to fill in the reference.76 *77 * @param obj referenced object78 */79 80 public void defineValue(Object obj) {81 for (int i = 0; i < m_list.size(); i++) {82 BackFillReference ref = (BackFillReference)m_list.get(i);83 ref.backfill(obj);84 }85 }86 87 /**88 * Get expected class name of referenced object.89 *90 * @return expected class name of referenced object91 */92 93 public String getExpectedClass() {94 return m_class;95 }96 }97 Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ |
http://kickjava.com/src/org/jibx/runtime/impl/BackFillHolder.java.htm
CC-MAIN-2018-05
refinedweb
272
59.4
Render the Note Form Now that our container loads a note on componentDidMount, let’s go ahead and render the form that we’ll use to edit it. Replace our placeholder render method in src/containers/Notes.js with the following. validateForm() { return this.state.content.length > 0; } formatFilename(str) { return str.replace(/^\w+-/, ""); } }); } handleDelete = async event => { event.preventDefault(); const confirmed = window.confirm( "Are you sure you want to delete this note?" ); if (!confirmed) { return; } this.setState({ isDeleting: true }); } render() { return ( <div className="Notes"> {this.state.note && <form onSubmit={this.handleSubmit}> <FormGroup controlId="content"> <FormControl onChange={this.handleChange} value={this.state.content} </FormGroup> {this.state.note.attachment && <FormGroup> <ControlLabel>Attachment</ControlLabel> <FormControl.Static> <a target="_blank" rel="noopener noreferrer" href={this.state.attachmentURL} > {this.formatFilename(this.state.note.attachment)} </a> </FormControl.Static> </FormGroup>} <FormGroup controlId="file"> {!this.state.note.attachment && <ControlLabel>Attachment</ControlLabel>} <FormControl onChange={this.handleFileChange} </FormGroup> <LoaderButton block <LoaderButton block </form>} </div> ); } We are doing a few things here: We render our form only when this.state.noteis available. Inside the form we conditionally render the part where we display the attachment by using this.state.note.attachment. We format the attachment URL using formatFilenameby stripping the timestamp we had added to the filename while uploading it. We also added a delete button to allow users to delete the note. And just like the submit button it too needs a flag that signals that the call is in progress. We call it isDeleting. We handle attachments with a file input exactly like we did in the NewNotecomponent. Our delete button also confirms with the user if they want to delete the note using the browser’s confirmdialog. To complete this code, let’s add isLoading and isDeleting to the state. So our new initial state in the constructor looks like so. this.state = { isLoading: null, isDeleting: null, note: null, content: "", attachmentURL: null }; Let’s also add some styles by adding the following to src/containers/Notes.css. .Notes form { padding-bottom: 15px; } .Notes form textarea { height: 300px; font-size: 24px; } Also, let’s include the React-Bootstrap components that we are using here by adding the following to our header. And our styles, the LoaderButton, and the config. import { FormGroup, FormControl, ControlLabel } from "react-bootstrap"; import LoaderButton from "../components/LoaderButton"; import config from "../config"; import "./Notes.css"; And that’s it. If you switch over to your browser, you should see the note loaded. Next, we’ll look at saving the changes we make to our note. If you liked this post, please subscribe to our newsletter, give us a star on GitHub, and check out our sponsors. For help and discussionComments on this chapter
https://branchv21--serverless-stack.netlify.app/chapters/render-the-note-form.html
CC-MAIN-2022-33
refinedweb
447
53.27
Back to index 00001 #ifdef __cplusplus 00002 extern "C" { 00003 #endif 00004 00005 #ifndef GDFX_H 00006 #define GDFX_H 1 00007 00008 #include "gd.h" 00009 00010 /* im MUST be square, but can have any size. Returns a new image 00011 of width and height radius * 2, in which the X axis of 00012 the original has been remapped to theta (angle) and the Y axis 00013 of the original has been remapped to rho (distance from center). 00014 This is known as a "polar coordinate transform." */ 00015 00016 BGD_DECLARE(gdImagePtr) gdImageSquareToCircle(gdImagePtr im, int radius); 00017 00018 /* Draws the text 'top' and 'bottom' on 'im', curved along the 00019 edge of a circle of radius 'radius', with its 00020 center at 'cx' and 'cy'. 'top' is written clockwise 00021 along the top; 'bottom' is written counterclockwise 00022 along the bottom. 'textRadius' determines the 'height' 00023 of each character; if 'textRadius' is 1/2 of 'radius', 00024 characters extend halfway from the edge to the center. 00025 'fillPortion' varies from 0 to 1.0, with useful values 00026 from about 0.4 to 0.9, and determines how much of the 00027 180 degrees of arc assigned to each section of text 00028 is actually occupied by text; 0.9 looks better than 00029 1.0 which is rather crowded. 'font' is a freetype 00030 font; see gdImageStringFT. 'points' is passed to the 00031 freetype engine and has an effect on hinting; although 00032 the size of the text is determined by radius, textRadius, 00033 and fillPortion, you should pass a point size that 00034 'hints' appropriately -- if you know the text will be 00035 large, pass a large point size such as 24.0 to get the 00036 best results. 'fgcolor' can be any color, and may have 00037 an alpha component, do blending, etc. 00038 00039 Returns 0 on success, or an error string. */ 00040 00041 BGD_DECLARE(char *) gdImageStringFTCircle( 00042 gdImagePtr im, 00043 int cx, 00044 int cy, 00045 double radius, 00046 double textRadius, 00047 double fillPortion, 00048 char *font, 00049 double points, 00050 char *top, 00051 char *bottom, 00052 int fgcolor); 00053 00054 /* 2.0.16: 00055 * Sharpen function added on 2003-11-19 00056 * by Paul Troughton (paul<dot>troughton<at>ieee<dot>org) 00057 * Simple 3x3 convolution kernel 00058 * Makes use of seperability 00059 * Faster, but less flexible, than full-blown unsharp masking 00060 * pct is sharpening percentage, and can be greater than 100 00061 * Silently does nothing to non-truecolor images 00062 * Silently does nothing for pct<0, as not a useful blurring function 00063 * Leaves transparency/alpha-channel untouched 00064 */ 00065 00066 BGD_DECLARE(void) gdImageSharpen (gdImagePtr im, int pct); 00067 00068 #endif /* GDFX_H */ 00069 00070 00071 #ifdef __cplusplus 00072 } 00073 #endif
https://sourcecodebrowser.com/tetex-bin/3.0/gdfx_8h_source.html
CC-MAIN-2016-44
refinedweb
457
66.57
The attached 3dm file has a full sphere in wireframe - that looks like an arc because isocurves are turned off and it has not yet been display meshed. Do not shade any views, run the following scriptlet: import rhinoscriptsyntax as rs msg="Select object for bounding box" obj=rs.GetObject(msg,4+8+16+32,preselect=True) bb=rs.BoundingBox(obj) rs.AddBox(bb) You will see that the bounding box is wrong (should correspond to the box you see on the locked layer in the file). It is the bounding box of the visible seam of the sphere, not of the full sphere. If you shade the object, even if you then switch back to wireframe, the BB is correct. So it works as long as the object has a display mesh. The normal Rhino BoundingBox command must also force meshing, as you see the object display mesh details show up in Properties>Details even if it had none before. Known bug? Didn’t see it on youtrack. Seems pretty odd that this has never been seen before though… –Mitch WrongBB.3dm (41.4 KB)
https://discourse.mcneel.com/t/boundingbox-incorrect-for-sphere-object-in-wireframe/21884
CC-MAIN-2020-45
refinedweb
186
69.52
One of the most common issues facing administrators who deploy ISA Server is how to configure ISA Server to resolve Domain Name System (DNS) requests. If DNS is configured incorrectly, the ISA Server computer fails to resolve either internal names or external names. Name resolution problems that present themselves can be intermittent in nature and difficult to track down and can range from email not being transmitted to users being unable to access the Internet through the Web proxy. This document describes various ISA Server scenarios, details how to set up ISA Server for DNS for each scenario, and explains why each configuration is needed. It covers the simplest configuration, a single-homed ISA Server computer in a non-domain scenario, and also describes a complex scenario, that of a multi-homed ISA Server computer that is a domain member.. Multi-homed ISA Server computers Single network adapter scenarios Common Questions Multi-homed ISA Server computers have DNS settings for both external and internal network adapters. Depending on the situation, ISA will fail if this is not configured correctly. There are several ways to correctly configure DNS depending on the requirement of the internal network. ISA Server computers that are not domain members should be set up just like a single-homed computer. If you have an internal DNS zone that you need to resolve – you should point DNS to the internal DNS server. The internal DNS server then forwards name resolution requests to your ISP’s DNS servers or uses root hints to resolve external names.. Figure 1 :Full DNS resolution configuration Another common scenario is where the Internal DNS servers do not forward to the Internet at all. This prevents both the Internal DNS servers and clients who use them from resolving names on the Internet. The ISA Server computer should not point to the internal DNS servers for name resolution, but still has to resolve both internal and external DNS names. Set up another DNS server on the ISA Server computer itself, or designate a DNS server internally dedicated to resolving both internal and external DNS names. On this new DNS server, set up a secondary to your internal DNS namespace and then configure the DNS server to forward to the Root servers or the ISP’s DNS servers for name resolution. This solution effectively isolates the intranet namespace and eliminates cache pollution / poisoning issues on the internal DNS servers. Figure 2: Multi-homed ISA with Internal DNS server Isolation In this section, ISA is set up with one network adapter and can only function as a proxy server (firewall service cannot run with only one network adapter). A stand-alone ISA Server computer not in a member of a domain, and there is no internal DNS server. Point to the ISP for DNS. A stand-alone ISA Server computer that is not a member of a domain, where an internal DNS server exists, should point to the internal DNS server to resolve internal names, and should NOT point to the external ISP as a secondary server. The internal DNS server should use forwarders to point to the external ISP’s DNS servers or should use the root servers (employing root hints) so that the ISA Server computer can resolve external names. If the ISA Server computer does not need to resolve internal DNS names at all – it can safely point to the ISP’s DNS servers. An ISA Server computer that is a domain member in NT 4.0 can safely point to an ISP for DNS since NT 4.0 does not use DNS for name resolution (it uses WINS). If you have an internal DNS server and you need to resolve internal names as well as external, the ISA Server computer should point to the internal DNS server as long as the internal DNS server forwards to an external ISP or root servers. Q: Why can’t I point to the Windows 2000 DNS first, and then to the ISP DNS? A: A common misconception is that you achieve fault tolerance by pointing to the Windows 2000 domain first, and then the ISP’s DNS server. The problem is that if the first DNS server fails, ISA Server will use the second DNS server and never go back to the original DNS server unless the second DNS server fails. DNS will work until you bring down the internal DNS server for maintenance, then a few hours later no one can get access to the Internet because you can’t validate the user against the domain. Restarting the ISA Server computer will solve this problem..
http://technet.microsoft.com/en-us/library/cc302590.aspx
crawl-002
refinedweb
770
56.08
<< Quentin L'eilde1,907 Points What is wrong with my code ? Hi everyone. I really don't have a clue of what is wrong with my method. Is it the format of my returns ? (My code is in the enums.swift file) Thanks for your help import Foundation enum UIBarButtonStyle { case Done case Plain case Bordered } class UIBarButtonItem { var title: String? let style: UIBarButtonStyle var target: AnyObject? var action: Selector init(title: String?, style: UIBarButtonStyle, target: AnyObject?, action: Selector) { self.title = title self.style = style self.target = target self.action = action } } enum Button { case Done(String) case Edit(String) func toUIBarButtonItem() -> UIBarButtonItem { switch self { case .Done(let done): return UIBarButtonItem(title: done, style: UIBarButtonStyle.Done, target: nil, action: nil) case .Edit(let edit): return UIBarButtonItem(title: edit, style: UIBarButtonStyle.Plain, target: nil, action: nil) } } } let doneButton = Button.Done("Done").toUIBarButtonItem() 1 Answer Martin WildfeuerCourses Plus Student 11,071 Points Although your code works and it's definitely the shortest way to create your done button, the assignment asks for using the done constant you assigned in the first task Button.Done("Done") in order to create the doneButton. So this should work: let done = Button.Done("Done") let doneButton = done.toUIBarButtonItem() Hope that helps :) Quentin L'eilde1,907 Points Quentin L'eilde1,907 Points ok you were right ! I'm french so I certainly misunderstood this instruction... Thanks !
https://teamtreehouse.com/community/what-is-wrong-with-my-code-55
CC-MAIN-2022-27
refinedweb
228
62.85
Had a bit of a meh turn out to the last Geekzone function - did we want to do another one towards the end of this month/beginning of April? We need to bring back Pizza nights with sponsors and prizes and beers and all the important things like free beer and free food and free prizes :-) Also they need to not be in Auckland :-) Information wants to be free. The Net interprets censorship as damage and routes around it. I do miss the events a bit as it was a great way to network with people and get out of the house. I'd been keen even if I had to travel up to Auckland for a bit. Michael Murphy | A quick guide to picking the right ISP | The Router Guide | Community UniFi Cloud Controller | Ubiquiti Edgerouter Tutorial networkn: My company may potentially be willing to throw a little something at it to perhaps include a round of drinks or something :) #include <std_disclaimer> Any comments made are personal opinion and do not reflect directly on the position my current or past employers may Taubin: I'm quite introverted but may be convinced. Sounds like it could be a good time. I've been interested to attend one but missed the last two for varying reasons. I did idly wonder one day whether a GZ IRL meeting might just be a bunch of 'classic nerdy-looking guys nervously standing around not talking to each other'! Of course there is zero chance of that being the reality.... someone would just need to pull out a new gadget and the room would erupt! haha For varying reasons (mostly buying/selling/trading bits) I've met half a dozen GZers over the last couple of years, and I'd be more than happy to spend more time with any of them. Great bunch of guys in my experience so far, and generally more than willing to help. Taubin: I'm quite introverted but may be convinced. Sounds like it could be a good time. i'm sure those who have met me at geekzone IRLs will indicate i'm extremely introverted. i quite enjoy attending however, certainly build some good connections! #include <std_disclaimer> Any comments made are personal opinion and do not reflect directly on the position my current or past employers may have. On a more serious note, I'd like to have a pizza night in Wellington. I scouted a place other day and was disappointed with service. Not many large pizza places in Wellington anymore, like the old One Red Dog used to be. Any suggestions welcome. Backblaze cloud backup (personal and business) | Geekzone broadband switch | Amazon (Geekzone aff) | MightyApe (Geekzone aff) | My technology disclosure | Business Transformation | Enterprise Content Management | Customer Relationship Management | Sharesies investment fund nate: Had a bit of a meh turn out to the last Geekzone function - did we want to do another one towards the end of this month/beginning of April? If its the weekend of Adele in Akl later this month I might be able to make it from New Plymouth, I have to drive the wife\ sister in law up and babysit while they go. Seems like I'm already earning brownie points.
https://www.geekzone.co.nz/forums.asp?forumid=48&topicid=208884
CC-MAIN-2019-22
refinedweb
539
67.08
Groovy adds several methods to the List interface. In this post we look at the head() and tail() methods. The head() method returns the first element of the list, and the tail() returns the rest of the elements in the list after the first element. The following code snippet shows a simple recursive method to reverse a list. def list = [1, 2, 3, 4] def reverse(l) { if (l.size() == 0) { [] } else { reverse(l.tail()) + l.head() } } assert [4, 3, 2, 1] == reverse(list) // For the same result we can of course use the List.reverse() method, // but then we didn't learn about tail() and head() ;-) assert [4, 3, 2, 1] == list.reverse()
http://mrhaki.blogspot.com/2009/10/groovy-goodness-getting-tail-of-list.html
CC-MAIN-2017-47
refinedweb
114
83.56
Table of Contents Connecting a New External Data Source VuFind includes support for several external services in addition to the core Solr index. However, it may sometimes be necessary to build support for a new service. This page will help take you through the process. Initial Decisions There are a few things to decide before implementing any code. - What URLs do you want to use for searches and record views? This will affect the names of the routes and controllers you create. (i.e.,) - What “source” value do you want VuFind to use for identifying records from your new source? This value will be saved in the database and passed in some URLs. It should be short, unique and alphanumeric (i.e. “WorldCat”, “Summon”). - What name do you want to use for your family of search classes; this should almost always be the same as your “source” value. - What name do you want to use for your record driver? Again, this should usually be consistent with the “source” value. Step-by-Step Building Instructions If you haven't already, you may want to read the Data Model / Key Concepts page for background information on how VuFind's pieces fit together. Once you are ready to write code, you can follow these steps to get a new module added to VuFind. Obviously, this is just a recommendation – some of these steps can be taken out of order without any problems. Note that for examples below, we will assume that you have chosen Source, search class and record driver names of “Sample.” Just replace “Sample” with your actual choice. The examples also assume that you are adding to core VuFind code. You also have the option of building your classes inside a custom module; to do this, you just need to create all new classes within your module's namespace and register them in your module's config/module.config.php instead of inside the main VuFind module. - Build Search Connector/Backend - Before you can integrate a new service into VuFind, you need to be able to talk to it from within PHP. It's possible that the service provides its own library, which may save you some time. Whether or not there is a pre-existing library, you should implement a search backend for VuFind's search service. This consists of a few steps: - Create a backend implementing \VuFindSearch\Backend\BackendInterface (and possibly also some of the feature interfaces found in the \VuFindSearch\Feature namespace, if appropriate). The purpose of this is to provide low-level functionality for performing searches and retrieving records. Several example backend implementations can be found in the VuFindSearch module – you should be able to use these as models during development. In some cases (as in connecting to a custom Solr core) you may be able to use existing code but simply configure it differently. - Create a factory to construct your backend in the context of VuFind; some example factories can be found in the \VuFind\Search\Factory namespace. - Register your factory in the ['vufind']['plugin_managers']['search_backend']['factories'] section of module.config.php (either by modifying the VuFind module's configuration, or that of your own local custom module). The name of the registered service should match the “source” value you chose above. - Implement Record Driver - The record driver object is responsible for extracting key pieces of data about a record from the data returned by your chosen service. To create it, follow these steps: - Create a record driver plugin for your data source – i.e. module/VuFind/src/VuFind/RecordDriver/Sample.php containing a class called \VuFind\RecordDriver\Sample. - Decide which existing record driver class to extend. If the records you are working with are very distinctive, you will probably want to extend \VuFind\RecordDriver\AbstractBase and build custom templates. However, in many cases, records will contain bibliographic data that is similar enough to VuFind's default Solr records to allow you to extend \VuFind\RecordDriver\SolrDefault (or one of its subclasses) and thus recycle many of VuFind's default built-in templates. This approach is recommended whenever it is possible. - Implement key methods: - setRawData() - This method is fed data directly from the external service (usually by a class implementing \VuFindSearch\Response\RecordCollectionFactoryInterface and set up by the service factory described above) and is responsible for storing it within the object. This data will be used by all other methods to retrieve specific details. The nature of the data being passed in is determined by your search results class (see below); you can use whatever is most convenient for your situation. \VuFind\RecordDriver\AbstractBase contains a default implementation of this method which stores the data in the $this→fields property; in many cases, you can use this default, but you may want to modify this method if additional processing is necessary. - getUniqueId() - This method returns the record's unique identifier. All VuFind records must have a unique identifier of some sort. Note that this unique ID is combined with the “source” value when VuFind does lookups, so you do not have to worry about IDs from one service colliding with IDs from another service. - getBreadcrumb() - This method returns a string used for identifying the record in breadcrumbs, page titles, etc. Normally it will be a short form title or something similar. - …and the rest - If you are extending \VuFind\RecordDriver\SolrDefault and your saved data is not structured exactly like a Solr response, you should override the public get methods of that class to return information from your chosen format. (If the data is unavailable for a given method, you don't have to override it – the base code will handle missing data appropriately). If you are extending \VuFind\RecordDriver\AbstractBase, you should add public get methods for any data elements you will need to display in your templates. When possible, try to name your methods consistently with other record drivers (see the Record Driver Method Master List) since this will improve your chances of being able to reuse certain VuFind components. - In most cases, you may want to adjust other methods dealing with things like tabs to display in record view or supported export formats, but these details can probably wait until after the first phase of development. - Register Record Driver - Add your new record driver to the recorddriver_plugin_manager section of module/VuFind/config/module.config.php; you will often want to set up a factory function to pass configurations to the record driver's constructor – see existing driver configurations (in VuFind\RecordDriver\PluginManager) for some examples. Be sure that the name you register the driver under matches the name expected by your backend factory (and see the record_drivers page for some notes on registering custom Solr record drivers). - Implement Search Classes - Create a new directory under module/VuFind/src/VuFind/Search named for the search class ID you picked earlier. In this new directory, you will create three files: - Options.php - This will contain the \VuFind\Search\Sample\Options class, which must extend \VuFind\Search\Base\Options. See the existing \VuFind\Search\Solr\Options or \VuFind\Search\WorldCat\Options classes for some examples of how this works. These are the most important methods to implement in this class: - Constructor - The constructor tells the other search classes which .ini files to use for search/facet settings and sets up initial options by reading them in from those .ini files. (You may at this time wish to establish a Sample.ini file – you can use config/vufind/Summon.ini and config/vufind/WorldCat.ini for inspiration). - getSearchAction() - This returns the name of the route used to access the search action for your new service. This will normally be something like 'sample-search.' - getAdvancedSearchAction() - This is just like getSearchAction, except it points to the Advanced Search form. This will normally be something like 'sample-advanced.' If you do not wish to support advanced searches, simply return false. - Params.php - This will contain the \VuFind\Search\Sample\Params class, which must extend \VuFind\Search\Base\Params. Unless you need to do special parameter processing or add new parameters not supported by the base class, you are not required to implement any methods here – you can just extend with an empty class. You'll probably end up adding methods here eventually, but for the initial implementation it is nice to leave this empty – one less thing to worry about! - Results.php - This will contain the \VuFind\Search\Sample\Results class, which must extend \VuFind\Search\Base\Results. This class interacts with your backend to expose results to VuFind, and looking at existing examples like \VuFind\Search\Solr\Results and \VuFind\Search\WorldCat\Results may help you understand it better. You will have to implement several methods: - performSearch() - This method reads the search parameters from the parameters and options objects, uses them to perform a search against your chosen service, and uses the results of the search to populate two object properties: $this→resultTotal, the total number of search results found, and $this→results, an array of record driver objects representing the current page of results requested by the user. - getFacetList() - This method returns facet options related to the current search. You may need to store extra values in performSearch() to allow the list to be generated. It is possible that getFacetList will be called before a search has been performed – in this case, you should call the performAndProcessSearch method to fill in all the details. (See \VuFind\Search\Solr\Results for an example of this). - Register Search Classes - You may not have to register your search classes at all – if they live in the VuFind\Search namespace and have no special constructor parameters, the default factory will take care of building them for you. However, if you have special needs, you will need to register the classes in the ['vufind']['plugin_managers']['search_options'], ['vufind']['plugin_managers']['search_params'] and/or ['vufind']['plugin_managers']['search_results'] sections of module/VuFind/config/module.config.php. - Create Controllers - In order to provide web access to your new code, you will need to create two new controllers in the module/VuFind/src/VuFind/Controller folder: - Search Controller - This should have a name like \VuFind\Controller\SampleController and should extend \VuFind\Controller\AbstractSearch. This controller will handle displaying and processing search forms. At a bare minimum, it should contain a constructor which sets the $this→searchClassId property to the appropriate value (i.e. 'Sample') and calls the parent constructor. You can look at the \VuFind\Controller\AbstractSearch class for other available options. You can also define controller actions if you wish, but this is not necessary – by default, you will have Home, Results and Advanced actions inherited from the base class. - Record Controller - This should have a name like \VuFind\Controller\SamplerecordController and should extend \VuFind\Controller\AbstractRecord. This controller will handle displaying records and performing record-related tasks (export, save, etc.). At a bare minimum, it should contain a constructor which sets the $this→searchClassId property to the appropriate value (i.e. 'Sample') and calls the parent constructor. - Register Controllers - Now that your controllers are created, you should register them in the invokables array of the controller section of module/VuFind/config/module.config.php. The entries should look like 'sample' ⇒ 'VuFind\Controller\SampleController' and 'samplerecord' ⇒ 'VuFind\Controller\SamplerecordController'. - Set Up Routes - You'll need to edit the module/VuFind/config/module.config.php configuration file to set up all the routes related to your new controllers. The configuration is designed to make it easy to add new routes: - In the $recordRoutes array, add an association between the route name (which should be your source value concatenated with the word “record”) and the route's controller name (as registered in controller invokables above). For example: 'samplerecord' ⇒ 'samplerecordcontroller' - In the $staticRoutes array, add any necessary search-related routes… for example, 'Sample/Home', 'Sample/Search' and 'Sample/Advanced'. - Note that, if you are using a custom module, you may need to copy some extra route-building logic from the main VuFind configuration, since these convenience route-building arrays are not present by default in empty modules. - Set Up Templates - Now that the models and controllers are set up, you need some views. - Search Templates - Within your chosen theme, create a templates/sample directory (replacing 'sample' with a lowercased version of your search controller's name). In this directory, you need to create one template for each action: advanced.phtml, home.phtml and search.phtml. These templates can simply wrap around the default search templates, overriding a few settings if necessary. See the existing templates in templates/worldcat for the simplest possible example. - Record Templates - If your record driver extends \VuFind\RecordDriver\SolrDefault, you may not need to create any record templates at all – the defaults should work for you. However, if you built a custom driver, you will need to create an appropriately-named directory under templates/RecordDriver in your chosen theme. Look at the existing templates in templates/RecordDriver/SolrDefault to see which filenames you need to create and what sort of content they should contain (note that some are optional and some filenames are dynamically generated based on other record driver options – i.e. the tab-*.phtml files, which are driven by allowed tab options).
https://vufind.org/wiki/development:howtos:connecting_a_new_external_data_source
CC-MAIN-2020-45
refinedweb
2,207
52.6
Groovy StubFor magic I finished revising the testing chapter in Making Java Groovy (the MEAP should be updated this week), but before I leave it entirely, I want to mention a Groovy capability that is both cool and easy to use. Cool isn’t the right word, actually. I have to say that even after years of working with Groovy, what I’m about to describe still feels like magic. Here’s the issue: I have a class that uses one of Google’s web services, and I want to test my class even when I’m not online. That means I need to mock the dependency, which isn’t all that hard. The problem is that there’s no explicit way to get my mock object into my own service. Yet, with Groovy’s MockFor and StubFor classes, I can mock a dependency, even when it’s instantiated as a local variable inside my class. Let me show you the code. I’ll start with a simple POGO called Stadium: class Stadium { String street String city String state double latitude double longitude String toString() { "($street,$city,$state,$latitude,$longitude)" } } I use this in my Groovy Baseball application, which accesses MLB box scores online and displays the daily results on a Google Map. The Stadium class holds location data for an individual baseball stadium. When I use it, I set the street, city, and state and have the service compute latitude and longitude for me. My Geocoder class is based on Google’s restful geocoding service. class Geocoder { String base = '?' void fillInLatLng(Stadium stadium) { String urlEncodedAddress = [stadium.street, stadium.city, stadium.state].collect { URLEncoder.encode(it,'UTF-8') }.join(',+') String url = base + [sensor:false, address:urlEncodedAddress].collect { it }.join('&') def response = new XmlSlurper().parse(url) String latitude = response.result.geometry.location.lat[0] ?: "0.0" String longitude = response.result.geometry.location.lng[0] ?: "0.0" stadium.latitude = latitude.toDouble() stadium.longitude = longitude.toDouble() } } First I take the stadium’s street, city, and state and add them to a list. Then the collect method is used to apply a closure to each element of the list, returning the transformed list. The closure runs each value through Java’s URLEncoder. In looking at the Google geocoder example, I see that they separate the encoded street from the city and the city from the state using “ ,+“, so I do the same using the join method. The Google geocoding service requires a parameter called sensor, which is true if the request is coming from a GPS-enabled device and false otherwise. In the Groovy map, I set its value to false, and set the value of the address parameter to the string from the previous line. The collect method on the map converts each entry to “ key=value“, so joining with an ampersand and appending to the base value gives me the complete URL for the stadium. Most restful web services try to provide their data in a format requested by the user. The content negotiation is usually done through an “Accept” header in the HTTP request, but in this case Google does something different. They support only XML and JSON output data, and let the user select which one they want through separate URLs. The base URL in the service above ends in xml. Google lists the JSON version as preferred, but that’s no doubt because they expect the requests to come through their own JavaScript API. I’m making the request using Groovy, and the XmlSlurper class makes parsing the result trivial. (Since Groovy 1.8, the JsonSlurper class also makes parsing JSON trivial, and I have a version that does that, too, but the difference really isn’t significant here.) The resulting block of XML that is returned by the service is fairly elaborate, but as you can see from my code, the data is nested through the elements GeocodeResponse/result/geometry/location/lat and GeocodeResponse/result/geometry/location/lng. After invoking the parse method (which returns the root element, GeocodeResponse), I just walk the tree to get the values I want. I do have to protect myself somewhat. The Google service isn’t nearly as deterministic as I would have expected. Sometimes I get multiple locations when I search, so I added the zero index to make sure I always get the first one. Also, some time during the last year Google decided to start throttling their service. I have a script that uses the Geocoder for all 30 MLB stadiums, and unfortunately it runs too fast (!) for the Google limits. I know this because I start getting back null results if I don’t artificially introduce a delay. That’s why I put in the Elvis operator with the value 0.0 if I don’t get a good answer. So much for the service; now I need a test. If I know I’m going to be online, I can write a simple integration test as follows: import static org.junit.Assert.*; import org.junit.Test; class GeocoderIntegrationTest { Geocoder geocoder = new Geocoder() @Test public void testFillInLatLng() { Stadium google = new Stadium(street:'1600 Ampitheatre Parkway', city:'Mountain View',state:'CA') geocoder.fillInLatLng(google) assertEquals(37.422, google.latitude, 0.01) assertEquals(-122.083, google.longitude, 0.01) } } I’m using Google headquarters, because that’s the example in the documentation. I invoke my Geocoder’s fillInLatLng method and check the results within a hundredth of a degree. (The fact that the Google geocoder returns answers to seven decimal places is evidence that their developers have a sense of humor.) Now, finally, after all that introduction, I reach the subject of this post. What happens if I’m not online? More to the point, how do I test the business logic in the fillInLatLng method without requiring access to Google? What I need is a mock object, or, more precisely, a stub. (A stub stands in for the external dependency, called a collaborator. A mock does the same, but also validates that the caller accesses the collaborator’s methods the right number of times in the right order. A stub helps test the caller, and a mock tests the interaction of the caller with the collaborator, sometimes called the protocol. Insert obligatory link to Martin Fowler’s “Mocks Aren’t Stubs” post here.) In my Geocoder class, the Google service is accessed through the parse method of the XmlSlurper. Even worse (from a testing point of view), the slurper is instantiated as a local variable inside my fillInLatLng method. There’s no way to isolate the dependency and set it from outside, either as an argument to the method, a setter in the class, a constructor argument, or whatever. That’s where Groovy’s StubFor (or MockFor) class comes in. Let me show it in action. First, I’ll set up the answer I want. String xml = ''' <root><result><geometry> <location> <lat>37.422</lat> <lng>-122.083</lng> </location> </geometry></result></root>''' def correctRoot = new XmlSlurper().parseText(xml) The xml variable has the right answer in it, nested appropriately. I use the XmlSlurper to parse the text and return the root of the tree I want. Now I need a Stadium to update. I deliberately put in the wrong street, city, and state to make sure that I only get the right latitude and longitude if I insert the stub correctly. Stadium wrongStadium = new Stadium( street:'1313 Mockingbird Lane', city:'Mockingbird Heights',state:'CA') (Yes, that’s a pretty obscure reference. For details, see here. And yes, I’m old. If you’re in the right age group, though, you now have the show’s theme song going through your head. Sorry.) The next step is to create the stub and set the expectations. def stub = new StubFor(XmlSlurper) stub.demand.parse { correctRoot } The StubFor constructor takes a class as an argument and builds a stub around it. Then I use the demand property to say that when the parse method is called, my previously computed root is returned rather than actually going over the web and parsing anything. To put the stub into play, invoke its use method, which takes a closure: stub.use { geocoder.fillInLatLng(wrongStadium) } That’s all there is to it. By the magic of Groovy metaprogramming, when I invoke the parse method of the XmlSlurper — even when it’s instantiated as a local variable — inside the use block the stub steps in and returns the expected value. For completeness, here’s the complete test class: import static org.junit.Assert.* import groovy.mock.interceptor.StubFor import org.junit.Test class GeocoderUnitTest { Geocoder geocoder = new Geocoder() @Test public void testFillInLatLng() { Stadium wrongStadium = new Stadium( street:'1313 Mockingbird Lane', city:'Mockingbird Heights',state:'CA') String xml = ''' <root><result><geometry> <location> <lat>37.422</lat> <lng>-122.083</lng> </location> </geometry></result></root>''' def correctRoot = new XmlSlurper().parseText(xml) def stub = new StubFor(XmlSlurper) stub.demand.parse { correctRoot } stub.use { geocoder.fillInLatLng(wrongStadium) } assertEquals(37.422, wrongStadium.latitude, 0.01) assertEquals(-122.083, wrongStadium.longitude, 0.01) } } Since I’m only calling one method and only calling that method once, a stub is perfectly fine in this case. I could invoke the verify method if I wanted to ( MockFor invokes verify automatically but StubFor doesn’t), but it doesn’t really add anything here. There is one limitation to this technique, which only comes up when you’re doing the sort of Groovy/Java integration that is the subject of my book. You can only use StubFor or MockFor on a class written in Groovy. All this code is available in the book’s Github repository at. This particular example is part of Chapter 5: Testing Java and Groovy. As a final note, I should say that I dug into all of this, worked out all the details, and tried it in several examples. Then I finally did what I should have done all along, which was look it up in Groovy In Action. Of course, there it was laid out in detail over about five pages. Someday that will stop happening to me. 🙂 Nice one! Groovy rocks! Consider using assert instead of assertEquals and the like. Groovy assertions are way better!
https://kousenit.org/2012/01/02/groovy-stubfor-magic/
CC-MAIN-2017-34
refinedweb
1,706
55.74
Recently I had to spend some time trying to adapt my imperative/OO background to a piece of code I need to write in functional paradigm. The problem is quite simple and can be described briefly. You have a collection of pairs containing an id and a quantity. When a new pair arrives you have to add the quantity to the pair with the same id in the collection, if exists, otherwise you have to add the pair to the collection. Functional programming is based on three principles (as seen from an OO programmer) – variables are never modified once assigned, no side-effects (at least, avoid them as much as possible), no loops – work on collections with collective functions. Well maybe I missed something like monad composition, but that’s enough for this post. Thanks to a coworker I wrote my Scala code that follows all the aforementioned principles and is quite elegant as well. It relies on the “partition” function that transforms (in a functional fashion) a collection into two collections containing the elements of the first one partitioned according to a given criteria. The criteria is the equality of the id so that I find the element with the same id if it exists, or just an empty collection if it doesn’t. Here’s the code: Yes, I could have written more concisely, but that would have been too much write-only for me to be comfortable with. Once the pleasant feeling of elegance wore off a bit I wondered what is the cost of this approach. Each time you invoke merge the collection is rebuilt and, unless the compile optimizer be very clever, also each list item is cloned and the old one goes to garbage recycling. Partitioning scans and rebuild, but since I’m using an immutable collection, also adding an item to an existing list causes a new list to be generated. Performance matters in some 20% of your code, so it could acceptable to sacrifice performance in order to get a higher abstraction level and thus a higher coding speed. But then I wonder what about premature pessimization? Premature pessimization, at least in context where I read the them, means the widespread adoption of idioms that lead to worse performances (the case was for C++ use of pre or post increment operator). Premature pessimization may cause the application to run generally slower and makes more difficult to spot and optimize the cause. This triggered the question – how is language idiomatic approach impacts on performances? To answer the question I started coding the same problem in different languages. I started from my language of choice – C++. In this language it is likely you approach a similar problem by using std::vector. This is the preferred collection and the recommended one. Source is like this: Code is slightly longer (consider that in C++ I prefer opening brace on a line alone, while in Scala “they” forced me to have opening braces at the end of the statement line). Having mutable collections doesn’t require to warp your mind around data to find which aggregate function could transform your input data into the desired output – just find what you are looking for and change it. Seems simpler to explain to a child. Then I turned to Java. I’m not so fond of this language, but it is quite popular and has a comprehensive set of standard libraries that really allow you to tackle every problem confidently. Not sure what a Java programmer would consider idiomatic, so I staid traditional and went for a generic List. The code follows: I’m not sure why the inner class Data needs to be declared static, but it seems that otherwise the instance has a reference to the outer class instance. Anyway – code is decidedly more complex. There is no function similar to C++ find_if nor to Scala partition. The loop is simple, but it offers some chances to add bugs to your code. Anyway explaining the code is straightforward once the iterator concept is clear. Eventually I wrote a version in C. This language is hampered by the lack of basic standard library – beside some functions on strings and files you have nothing. This could have been fine in the 70s, but today is a serious problem. Yes there are non-standard libraries providing all the needed functionalities, you have plenty of them, gazillions of them, all incompatible. Once you chose one you are locked in… Well clearly C shows the signs of age. So I write my own single linked list implementation: Note that once cleaned of braces, merge function is shorter in C than in Java! This is a hint that Java is possibly verbose. I just wrote here the merge function. The rest of the sources is not relevant for this post, but it basically consists in parsing the command line (string to int conversion), getting some random numbers and getting the time. The simplest frameworks for this operation are those based on the JVM. The most complex is C++ – it allows a wide range of configuration (random and time), but I had to look up on internet how to do it and… I am afraid I wouldn’t know how to exploit the greater range of options. Well, in my career as a programmer (some 30+ years counting since when I started coding) I think I never had the need to use a specific random number generator, or some clock different from a “SystemTimeMillis” or Wall Clock Time. I don’t mean that because of this no one should ask for greater flexibility, but that I find daunting that every programmer should pay this price because there is case for using a non default RNG. Anyway back to my test. In the following table I reported the results. Times have been taken performing 100000 insertions with max id 10000. The test has been repeated 20 times and the results have been averaged in the table. The difference in timing between C++ and Scala is dramatic – with the first faster about 70 times the latter. Wildly extrapolating you can say that if you code in C++ you need 1/70 of the hardware you need to run Scala… there’s no surprise (still guessing wildly) that IBM backs this one. Java is about 5 times faster than Scala. I’m told this is more or less expected and possibly it is something you may be willing to pay for higher level. In the last column I reported the results for a version of the C++ code employing std::list for a more fair comparison (all the other implementations use a list after all). What I didn’t expected was that C++ is faster (even if slightly) than C despite using the same data structure. It is likely because of some template magic. The other interesting value I wrote in the table is the number of lines (total, not just the merge function) of each implementation. From my studies (that now are quite aged) I remember that some researches reported that the speed of software development (writing, testing and debugging), stated as lines of code per unit of time, is the same regardless of the language. I’m starting having some doubt because my productivity in Scala is quite low if compared with other languages, but … ipse dixit. Let’s say that you spend 1 for the Scala program, then you would pay 2.31 for C++, 1.97 for Java and 3.20 for C. Wildly extrapolating again you could draw a formula to decide whether it is better to code in C++ or in Scala. Be H the cost of the CPU and hardware to comfortably run the C++ program. Be C the cost of writing the program in Scala. So the total cost of the project is: (C++) H+C×2.31 (Scala) 68×H+C (C++) > (Scala) ⇒ H+C×2.31 > 68×H+C ⇒ C×1.31 >67×H ⇒ C > 51.14×H That is, you’d better using Scala when the cost of the hardware you want to use will not exceed the cost of Scala development by a factor of 50. If hardware is going to cost more, then you’d better use C++. Beside of being a wild guess, this also assumes that there is no hardware constraint and that you can easily scale the hardware of the platform. (Thanks to Andrea for pointing out my mistake in inequality) 6 thoughts on “Comparisons” Your comparison among Scala and the other languages is not fair. You are comparing an implementation using immutable structures with implementations that use mutable structures. It’s obvious that the performance is 2 orders of magnitude worse, both in terms of speed and memory! You should reimplement the Scala version with a mutable collection (and update items in place) and redo the tests. This specific problem screams for a mutable structure (and I’d rather use a map, maybe a hashmap, rather than a list) Scala let’s you implement in an imperative way, when you need to. It’s perfectly legit, and you should not be ashamed of it. Also, comparing C++ and Scala based on the raw performance doesn’t make sense. Obviously C++ is more performant then Scala (given a good C++ programmer as you are). But the choice of a programming language depends on many different things. It is likely I had to state it better – this comparison didn’t want to be between raw performances. In fact it makes little sense to compare a compiled language vs an interpreted one. Instead my goal was to compare how much “premature pessimization” you get when you tackle a problem with a functional approach. In other words my experiment was intended to be – give the same assignment to one Scala programmer and to one C++ programmer and compare the outcome. In this sense I don’t find it unfair – you pick up the tool you consider more apt, but in the end it only matters how much it costs to create it and how much it costs to run it. I agree that the problem is fictitious – I just took a piece of code for which an elegant solution has been found and overcharged it. I mean, in the real world that code does just a few iterations and I tested it with a number of iteration 1000 times. No one of the two programmers was concerned with performances, as it was reasonable. But this doens’t mean that you don’t pay for the functional approach. The overall code will be slower, maybe this will go unnoticed in the 80% of the code, but then you will need more hardware to run multiple instances, you will need more energy. I am not saying this is bad and you should avoid Scala in favor of C++, but that it is nice to take in account the extra you are paying and will be paying at run-time. I did other tests on the same problem – using mutable hash table Scala is only 10 times slower than C++. Changing data representation to a more suitable one (both in C++ and Scala) you can have the fastest implementation and Scala is only 2 times slower than C++. But this is just out of the scope – the first approach for C++ programmers is to use a std::vector, while for Scala programmers is to use an immutable List. Again I have to disagree on the statement FP = “premature pessimization”. I’d rather say “bad design choice” = “premature pessimization”. In this specific example, as stated, you have a growing list of data that have a state (the quantity) that is frequently changing. You should not implement it with immutable structures that at every call reconstruct completely. For example (as I explained in another reply) you can compromise by using an immutable list of (partly) mutable objects. The list grows by adding new elements at the head, and this is very cheap. A functional programmer will focus on the “what” he has to do, rather than “how”, and he won’t be bothered by the usual boilerplate of iterating, updating, etc. This can improve productivity a lot. Then again, performance compared against C++ is in general worse. But the choice of a language should not be done only on raw performance (you’re saying that you’re not comparing raw performance, but indeed it is this you are saying again in your reply). Btw, Scala is not an interpreted language, it is compiled and executed in a VM. So, Scala is better? C++ is better? Both are better… The important thing is being able to choose the right programming language for the right problem, given many factors. among them also the expertise of developers. And don’t have a prejudice on Functional Programming Paradigm. It can take a while to get used to it after many years of Imperative paradigm, but in the end it can help describe problems in a more logical and clear way. I think we are coming about to the same conclusion – pick the tool which better deals with the problem you are trying to solve. The business doesn’t care for FP / OO / Scala / Java / whatever. And we agree raw speed is not everything because it is just a part of the goal. I tried to take in account both speed of execution and speed of code production. I already know that trying to find a good Scala programmer is exceedingly hard. And I wondered what is the extra CPU you are paying to do FP. Maybe I have been exposed to too much bad Scala code, but I keep seeing a strong aversion for “var” and mutable. So, I focused on this aspect. I tried also with mutable data structures with a solution close to the one you proposed. I don’t have data here, but IIRC the code was five times slower wrt C++. As you said and I fully agree this is not enough to dismiss Scala in favor of C++. My final disequation – taken with a lot of grains of salt – pretended to be a rule of thumb to select the language according to the cost of running the application. Mutable or not mutable there is a price to pay for functional, this is why we needed to wait some 50 years since the formulation of lambda calculus and Lisp, for a functional language to start becoming mainstream. I’ll keep an eye for other cases to benchmark 🙂 If you accept that “quantity” in Data object is mutable (and you should, since it is in the Java, C++ and C versions) you can write: case class Data(val id: String, var quantity: Int) type Collection = List[Data] def merge( collection : Collection, data : Data ) : Collection = { collection.find(_.id == data.id).map { d => d.quantity += data.quantity collection }.getOrElse( data +: collection ) } In this case if a Data object is already present, its quantity is updated, otherwise a new Data object is added at the head of the (immutable) list. The list is not duplicated (not wasted memory), and “quantity” is the only mutable state. I think performance should improve. With an implicit (and this can be an answer to your post on implicits) you can write (sorry that indentation is lost in this editor): case class Data(val id: String, var quantity: Int) type Collection = List[Data] implicit class mergedCollection(val collection: Collection) extends AnyVal { def merge(data: Data): Collection = collection.find(_.id == data.id).map { d => d.quantity += data.quantity collection }.getOrElse( data +: collection ) } val c0: Collection = List.empty c0.merge(Data("a", 1)). merge(Data("b", 1)). merge(Data("a", 1)) With an implicit class we have easily extended our Collection with a method merge(). That’s nice!
http://www.maxpagani.org/2016/07/12/comparisons/
CC-MAIN-2017-51
refinedweb
2,650
69.31
0 i've a problem to split a joining multipe type of file here's my code for joining two diff type file, pict file (jpg) and audio file(mp3) an ouput is pict file contains audio file in it. a problem is how do i check this file is joining file or not? and how do i split this kind of file? (suppose that spliting and joining code are separate) import sys import os f = open("e:/Dev/1.jpg", "rb") g = open("e:/Dev/2.mp3", "rb") dataList = [] dataList.append(f.read()) dataList.append(g.read()) g.close() data = f.read() new = f.name f = open(new, 'wb') for data in dataList: f.write(data) f.close() os.remove(g.name)
https://www.daniweb.com/programming/software-development/threads/361564/how-do-i-split-a-joining-multiple-file
CC-MAIN-2018-34
refinedweb
123
77.53
Like most things in life, our current software project is powered by Git, and historically we’ve been using git to generate the version numbers for our builds by sucking it out from the tags in our repository via git-describe. $ git describe --tags --long --match v* v0.3.0-0-g865eb5f This works wonderfully well when you have a single-line commit history, as the tag for versioning is the most recent tag. Recently, however, we switched to using Vincent Driessen’s Git branching model, which opens up a serious hole in the simple versioning system. When you prepare a hotfix release for master, you tag the hotfix branch at the point the hotfix is being applied. This has the unfortunate side-effect of screwing up the way git describe determines the “nearest” tag. I’ve created a sample repo demonstrating this problem. If you’re not keen on grabbing the repo, follow along with the screenshot below. Basically what we see here is a hotfix being applied for release v0.1.0 while development continues on v0.2.0. The hotfix is merged back into develop (but decided not to be merged into master as the hotfix could wait until the next release). Running the git-describe command above *SHOULD* yield v0.2.0-4-gba68c2f as the tag for develop in order to be true, however it comes back as v0.1.1-4-gba68c2f, which leads to our builds being completely mis-versioned. (We just versioned 0.2.0 code as 0.1.1 – how shit are we?) Okay, so why is git picking up my v0.1.1 tag instead of the v0.2.0 tag? Turns out it has a lot to do with the explanation of how git-describe works:. Which is all well and good, however the describe algorithm ended up traversing a merge-branch down from develop and erroneously (for our purposes) finding v0.1.1 because it was closer to HEAD than v0.2.0 (well specifically in this example case they have the same number of commits, but the depth of the merged branch seems to be more appealing to git) Digging around a bit more, I found that the git log command actually has an argument to have git-log search only the first (oldest) of multiple parent commits (ie: merges). enter . …and when you use that to find the appropriate tag, it does! $ git log --oneline --decorate=short --first-parent | grep '(tag:' | head -n1 b4aa13c (tag: v0.2.0) continued work on develop So first-parent history search behaviour is what I want, but it’s not available on git-describe. Turns out, i’m not the only one who’s come across this…It’s a shame, really because describe does everything else perfectly, except for the algorithm to find the closest tag. Unfortunately there’s no clear work-around or even a solution as to when a –first-parent argument will be made available for git-describe, which meant I had to come up with this monstrous flake of rake script to get the build version identifier (formatting doesn’t do it justice): def git_version_identifier tag_number = `git log --oneline --decorate=short --first-parent | grep '(tag:' | head -n1` version_number = /v(d+).(d+).(d+)/.match(tag_number) `git describe --tags --long --match #{version_number}`.chomp end which (in a nutshell): - Finds the appropriate tag number for the current branch as per the bash-fu you saw earlier - Parses the previous output for the tag identifier (vx.x.x as per our convention) - Fires THAT tag id into git describe to get it to generate the identifier properly, bypassing its search mechanism Seems convoluted and i’m not really happy with the result. Hoping that someone out there knows something I dont. –first-parent option was added to git describe – I’m not sure when exactly, but I can see it in 2.11.0. Another way of avoiding such problem would be if you didn’t put the 0.1.1 tag on hotfix commit itself, but only on the master branch after you merge that hotfix into it. Anyway, nice post! Is this still actual? It might be good to also refer with what Git version this happend. thx
https://www.xerxesb.com/?p=924&replytocom=4905
CC-MAIN-2020-40
refinedweb
711
62.98
Forum:What happened to the Forum Talk namespace? From Uncyclopedia, the content-free encyclopedia Forums: Index > Village Dump > What happened to the Forum Talk namespace? (talk) Note: This topic has been unedited for 581 days. It is considered archived - the discussion is over. Do not add to unless it really needs a response. Yeah, I just noticed that it is gone, who huffed it and why? --Capercorn FLAME! what? UNATO OWS 18:51, 17 August 2007 (UTC) - It's a stupid namespace. You're not supposed to use it. It's fun for commentary, but generally not the best for serious topics. ~ Jacques Pirat, Esq. Converse : Benefactions : U.w.p.17/08/2007 @ 18:56 - Actually, it still exists, but the tabs that lead to them were deleted. Forum Talk:Village Dump and some other forum talk pages still exist. --Sir Starnestommy (Talk • Contribs • CUN • Capt.) 21:18, August 17, 2007 - Speaking of namespaces, what's the code to put a different image in the top left corner of a certain namespace? --Crazyswordsman...With SAVINGS!!!! (T/C) 00:53, 18 August 2007 (UTC) - Ohhhhhh - I've been back like half an hour and I still couldn't work out what it was that had changed... Can we get the spacer put back between the forum tab and the others, please? Purely for aesthetic reasons, and not at all the fact that it made my head spin trying to work out where the edit tab was. --Whhhy?Whut?How? *Back from the dead* 16:18, 18 August 2007 (UTC) - I liked it that way before. Than when people clogged up the actual form, the discussion had somewhere to go, like with this.--Sir Manforman 17:14, 18 August 2007 (UTC) - I am agreeing with SbU on this issue. A spacer would make the row of tabs less likely to cause mental *urp* indigest:55, 18 August 2007 (UTC) - No! Moosh them all together into one uber-tab: ForumDiscussionEdit+HistoryMoveWatch. Imagine how much time it will save. Imagine harder! Sir Modusoperandi Boinc! 18:03, 18 August 2007 (UTC) - My uber-tab will be ForumDiscussionEdit+HistoryProtectDeleteMoveWatchGoogleWikipedia. I think I'll pass. --Whhhy?Whut?How? *Back from the dead* 19:22, 18 August 2007 (UTC) - You have Google/Wikipedia at the top. Mine is only Forum/Edit/History/Move/Watch. How do you enable that Google/Wikipedia thing?-:28, 18 August 2007 (UTC) - It's a javascript thing - you can steal it from my javascript if you can work it out - off the top of my head, you'll need the addenwp, addgoogle, and addlilink functions (near the bottom), and then you'll either need to call the first two of them from a "Main()" function (near the top), or I think you can just put "addOnloadHook(<function name>);" anywhere in the script, but I'm no expert on these things because I mostly steal them from other people. If you have no idea what I just said, ask me on my talk page and I'll try and help. -- Whhhy?Whut?How? *Back from the dead* 22:21, 18 August 2007 (UTC) - Okay, the spacing is now restored, and the header template now links to the talk page if it exists, so old talk pages are still accessible. --Algorithm 19:55, 18 August 2007 (UTC) - Above and beyond, as usual Algorithm! --Whhhy?Whut?How? *Back from the dead* 22:21, 18 August 2007 (UTC) - What about New Forum talkpages? Sir Modusoperandi Boinc! 22:39, 18 August 2007 (UTC)
http://uncyclopedia.wikia.com/wiki/Forum:What_happened_to_the_Forum_Talk_namespace%3F?t=20130516212711
CC-MAIN-2014-52
refinedweb
585
73.88
This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project. Tom Tromey writes: > Here's what happens: configure decides that iconv() exists in libc > (which is true). Then the code includes <iconv.h>, which in your case > defines things like this: > > #define iconv_open libiconv_open It is wrong for configure to look at a symbol called 'iconv' or 'libiconv' without including <iconv.h>. Because you have to include <iconv.h> in order to use iconv_t and the functions, and you have to accept the iconv.h file that you get, depending on $CC, $CFLAGS, $CPPFLAGS. Using the Solaris function with the GNU libiconv header, or the GNU libiconv function with the Solaris header, will lead to trouble. The #define iconv_open libiconv_open is there to let the trouble happen at link time, rather than at run time. (Really, the use of the FreeBSD iconv header with the GNU libiconv function would lead to core dumps.) Therefore the best strategy is to 1. include <iconv.h> and try to link without -liconv (because on glibc systems, or when -liconv is already in the LDFLAGS, you don't need it), then 2. include <iconv.h> and try to link with -liconv. The following macro, being used in gettext and fileutils for a year, works in all cases. Also note that the use of ICONV_CONST in gcc/java/lex.c could avoid warnings on systems whose iconv function takes a second argument of type 'char **', not 'const char **'. The macro defines @LIBICONV@ for use in Makefiles; its value is either empty or "-liconv". Bruno ============================= iconv.m4 ============================== #serial AM2 dnl From Bruno Haible. AC_DEFUN([AM_ICONV], [ dnl Some systems have iconv in libc, some have it in libiconv (OSF/1 and dnl those with the standalone portable GNU libiconv installed). AC_ARG_WITH([libiconv-prefix], [ --with-libiconv-prefix=DIR search for libiconv in DIR/include and DIR/lib], [ for dir in `echo "$withval" | tr : ' '`; do if test -d $dir/include; then CPPFLAGS="$CPPFLAGS -I$dir/include"; fi if test -d $dir/lib; then LDFLAGS="$LDFLAGS -L$dir/lib"; fi done ]) AC_CACHE_CHECK(for iconv, am_cv_func_iconv, [ am_cv_func_iconv="no, consider installing GNU libiconv" am_cv_lib_iconv=no AC_TRY_LINK([#include <stdlib.h> #include <iconv.h>], [iconv_t cd = iconv_open("",""); iconv(cd,NULL,NULL,NULL,NULL); iconv_close(cd);], am_cv_func_iconv=yes) if test "$am_cv_func_iconv" != yes; then am_save_LIBS="$LIBS" LIBS="$LIBS -liconv" AC_TRY_LINK([#include <stdlib.h> #include <iconv.h>], [iconv_t cd = iconv_open("",""); iconv(cd,NULL,NULL,NULL,NULL); iconv_close(cd);], am_cv_lib_iconv=yes am_cv_func_iconv=yes) LIBS="$am_save_LIBS" fi ]) if test "$am_cv_func_iconv" = yes; then AC_DEFINE(HAVE_ICONV, 1, [Define if you have the iconv() function.]) AC_MSG_CHECKING([for iconv declaration]) AC_CACHE_VAL(am_cv_proto_iconv, [ AC_TRY_COMPILE([ #include <stdlib.h> #include <iconv.h> extern #ifdef __cplusplus "C" #endif #if defined(__STDC__) || defined(__cplusplus) size_t iconv (iconv_t cd, char * *inbuf, size_t *inbytesleft, char * *outbuf, size_t *outbytesleft); #else size_t iconv(); #endif ], [], am_cv_proto_iconv_arg1="", am_cv_proto_iconv_arg1="const") am_cv_proto_iconv="extern size_t iconv (iconv_t cd, $am_cv_proto_iconv_arg1 char * *inbuf, size_t *inbytesleft, char * *outbuf, size_t *outbytesleft);"]) am_cv_proto_iconv=`echo "[$]am_cv_proto_iconv" | tr -s ' ' | sed -e 's/( /(/'` AC_MSG_RESULT([$]{ac_t:- }[$]am_cv_proto_iconv) AC_DEFINE_UNQUOTED(ICONV_CONST, $am_cv_proto_iconv_arg1, [Define as const if the declaration of iconv() needs const.]) fi LIBICONV= if test "$am_cv_lib_iconv" = yes; then LIBICONV="-liconv" fi AC_SUBST(LIBICONV) ]) ===========================================================================
https://gcc.gnu.org/legacy-ml/gcc-bugs/2001-06/msg01398.html
CC-MAIN-2022-33
refinedweb
524
56.25
event methode updates the display Hello, on my ubuntu, methods events (pump, clear, wait, etc. ..) update the display. it's annoying when you want to keep hidden elements. from pygame import * screen = display.set_mode((500,500)) screen.fill(-1) time.wait(1000) event.wait() while 1: pass in the same way, display.flip() has not the effect expected if is called too quickly from pygame import * screen = display.set_mode((500,500)) screen.fill(-1) display.flip() while 1: pass This only shows a small bit of the display I can not reproduce the described effect. Using this code, the display is updated to show red. If you change the "display.flip()" back to "pass" then the screen is not updated, and remains black. from pygame import * screen = display.set_mode((500,500)) screen.fill((255,0,0)) time.wait(1) event.wait() while 1: display.flip() I also don't see a problem with the second example, it updates the screen to display white. it seems that the problem is related to compiz ... Closing due to insufficient information.
https://bitbucket.org/pygame/pygame/issues/126/event-methode-updates-the-display
CC-MAIN-2018-05
refinedweb
177
69.89
problem with sequence of include files Discussion in 'C++' started by Tio, Oct 9, 2006. - Similar Threads #include "bar" negates #include <string> ; how to fix?Danny Anderson, Aug 15, 2003, in forum: C++ - Replies: - 5 - Views: - 748 - Victor Bazarov - Aug 15, 2003 Re: the use of #include <a_file.h> v/s #include"a_file.cpp"Rolf Magnus, Nov 28, 2003, in forum: C++ - Replies: - 2 - Views: - 787 - Karl Heinz Buchegger - Nov 28, 2003 Tomcat include-prelude include-coda problemweb4all, May 11, 2006, in forum: Java - Replies: - 0 - Views: - 3,390 - web4all - May 11, 2006 how to iterate over sequence and non-sequence ?stef mientki, Oct 19, 2007, in forum: Python - Replies: - 13 - Views: - 970 - stef mientki - Oct 20, 2007 /* #include <someyhing.h> */ => include it or do not include it?That is the question ....Andreas Bogenberger, Feb 21, 2008, in forum: C Programming - Replies: - 3 - Views: - 1,247 - Andreas Bogenberger - Feb 22, 2008
http://www.thecodingforums.com/threads/problem-with-sequence-of-include-files.457495/
CC-MAIN-2016-18
refinedweb
151
64.41
In today’s post, you’ll learn how to use Styled Components in React with best practices. Using normal styling in React is alright, but if you mistakenly use the same Class name for other components, it can cause some bad effects on your design. Also, when working on huge projects, there’s no way to keep track of Class Names, there’ll be a point where you might use the same Class Names and break your site. To avoid these issues, there are many ways, but React has an amazing library called Styled Components. Contents What are React Styled Components? It is a package that helps you build components that have certain styles attached to them, where the styles only affect which component they were attached to and not any other components. You can visit the Styled Components official website and read their documentation if you want to learn more, though I will explain all you need to know about it step by step. Getting Started with Styled Components – To get started with Styled Components, we need to install and import it first obviously, so let’s do it, npm install --save styled-components use the above command to install this Library, and below to import it. import styled from "styled-components"; Now, let’s initialize the Styled Components, for example, let’s say we want to style a button component, const Button = styled.button`` this syntax seems weird right? chances are that you might not have used this syntax, it’s actually a JavaScript feature called Tagged Template Literal and yes it was launched with ES6. So, here the button is a method to the styled object, basically styled is an object that we are importing from styled components and there we are accessing the method called button. Instead of calling the method using the parenthesis, button(), we are using Tagged Template Literal, again which is the default JavaScript feature. Here is an article by Webos.com on JavaScript Tagged Template Literal, do check out if you are interested. So, what’s happening here, whatever we pass between these two backticks will end up in that button method and will return a new button Component. That styled package has methods for all HTML Elements. So how can we use it? Also, check out, How to style React Components for beginners? How to use Styled Components? We can provide the CSS Styles between those backticks ` `, just like below. const Button = styled.button` font: inherit; padding: 0.5rem 1.5rem; border: 1px solid #8b005d; color: white; background: #8b005d; box-shadow: 0 0 4px rgba(0, 0, 0, 0.26); cursor: pointer; &:focus { outline: none; } &:hover, &:active { background: #ac0e77; border-color: #ac0e77; box-shadow: 0 0 8px rgba(0, 0, 0, 0.26); } `; Tip: you can install a library called VScode-styled-components which highlights the styled-components syntax. Here, we have added the styles in our styled component. A thing to notice is that we don’t need Classes here, as there’s no place to attach it & if you are wondering how to use Pseudo-classes we can just use the “&” operator and it will work just fine. The button which is returned also applies all the props that are passed to the component, and all the events, types, etc. also can be passed as a prop. Just like this, <Button type="submit">Add Goal</Button> How do Styled Components work? If you inspect the element in the browser, you’ll see the button element obviously, but the interesting part is that it will have super unique classes. These class names are dynamically generated by the styled-components package, and what it does, in the end, is it gets the styles we passed in those backticks and wraps it inside those two classes. Styled components add these classes as global CSS classes, and as the class names are unique for all the styled components we set up, they will never affect any other component in the app. Styled Components with Conditional Styling & Dynamic Props – Conditional Styling – We can also use styled-components in the same file and how can we do it? Let’s say we want to create a div, which will have two elements label and input. <div className={`form-control ${!isValid ? "invalid" : ""}`}> <label>Course Goal</label> <input type="text" /> </div> Now, we’ll transform this above code to the styled component, by creating one, let’s create a styled component called FormControl and it will be a div element. const FormControl = styled.div` margin: 0.5rem 0; & label { font-weight: bold; display: block; margin-bottom: 0.5rem; } & input { display: block; width: 100%; border: 1px solid #ccc; font: inherit; line-height: 1.5rem; padding: 0 0.25rem; } & input:focus { outline: none; background: #fad0ec; border-color: #8b005d; } &.invalid input { border-color: red; background-color: #ffd7d7; } &.invalid label { color: red; } `; To access the Pseudo classes and child elements or child classes we need to use the “&” operator. This is it, now we can use this component instead of plain div, <FormControl className={!isValid ? "invalid" : ""}> <label>Course Goal</label> <input type="text" /> </FormControl> In FormControl component, we are still using the same className , because what styled-components does is, it passes all the props to the underlying components which is a div element. So, we can use conditional styling even with the styled-components. But, there’s also another way to do it, and it’s provided by the styled-components package. Dynamic Props – We can use this feature by passing props to the styled-components and using them inside our styles. How can we do it? Well first we’ll remove the class invalid that we applied previously, and then we’ll pass a prop called invalid which will hold a Boolean value, <FormControl invalid={!isValid}> <label>Course Goal</label> <input type="text" /> </FormControl> here, we are passing a use state hook !isValid , which is a Boolean. Now, inside our styled component, we can use conditional styling, just like this, const FormControl = styled.div` margin: 0.5rem 0; & label { font-weight: bold; display: block; margin-bottom: 0.5rem; // ---> color: ${props => props.invalid ? "red" : "black"}; // <--- } & input { display: block; width: 100%; // ---> border: 1px solid ${props => props.invalid ? "red" : "#ccc"}; background-color: ${props => props.invalid ? "#ffd7d7" : "transparent"}; // <--- font: inherit; line-height: 1.5rem; padding: 0 0.25rem; } & input:focus { outline: none; background: #fad0ec; border-color: #8b005d; } `; As you can see, here we have removed the .invalid class and instead, we are conditionally styling the desired style. I have wrapped the style in arrows as you can see in the above snippet. To use props passed in styled components, we can use a ${} with curly braces and use a call-back function passing the props as an argument. That prop will hold all of the props we passed in the styled components, in this case, it’s an invalid prop. So here we are checking if props.invalid is true then set color to "red" and if it’s false set it to "transparent". That’s It, I know this can be hard at the beginning to get it completely, but that’s fine, you only need to practice it few times and you’ll be able to wrap your head around it comfortably. I hope this post was helpful, if it was make sure to share it with your friends who are beginning to learn React. Also, make sure to follow us by pressing the bell icon down-left to never miss any interesting posts on web development.
https://waystoweb.com/react-styled-components-beginners-guide/
CC-MAIN-2022-40
refinedweb
1,256
63.49
Hi Team, I would like to find out the offset of consumer while reading the message from kafka topic through kafkaCosumer.How can we achieve that. I have seen some of the commits done by you regarding this in below mentioned link I have my code like this @parallel(width = $ParallelWidth) stream Beacon_Op = KafkaConsumer() { param propertiesFile : getApplicationDir() + $KafkaPropertiesFile ; topic : $Topic_Name; } In this how can I get the offset for this. Thanks, Mohan Answer by NSchulz (216) | Jun 12 at 03:06 AM Hi Mohan, from the link you added in your question I assume that you are using the Kafka functionality of the Messaging toolkit. If so, I'm afraid you are battling on lost ground, for the operator does not define any parameters to hand over offset values. Furthermore, the Kafka part of the Messaging toolkit has been deprecated for a while now, and further development is done in the Kafka toolkit. Referring to the documentation you will see, that the Kafka toolkit's KafkaConsumer operator has a parameter outputOffsetAttributeName to put the current offset into a data stream, and a parameter startOffset to define from where the consumer shall start reading. To switch from Messaging to Kafka toolkit you probably have to just change the used namespace from use com.ibm.streamsx.messaging.kafka::* ; to use com.ibm.streamsx.kafka::* ; Hope that gives you a head start ... Kind regards Norbert Answer by Mohan Pandy (9) | Jun 17 at 05:21 AM Yes I am using kafka functionality of the messaging toolkit. Now I started using kafka toolkit and getting the values properly. Thank you so much for the info.. Thanks, Mohan. Answer by Mohan Pandy (9) | Jul 08 at 12:56 PM While compiling I am getting the below error. Kafka which I mausing kerbos authenticated So I should use the jass file to connect. CDISP0054E ERROR: The jaasFile parameter is unknown and was not defined for the KafkaConsumer operator. How to resolve this issue. Is there any parameter which will solve this compilation issue. Thanks, Mohan Answer by NSchulz (216) | Jul 09 at 02:03 AM Hi @Mohan Pandy, the Kafka toolkit removed the jaasFile parameter in favor of using the sasl.jaas.config parameter directly, which has been introduced with Kafka v0.10.0. Please, refer to the remarks for the jaasFile and jaasFilePropName parameters in the Migration document. Kind regards Norbert 182 people are following this question. Implementation of topology toolkit...? 8 Answers Can we do Stream synchronization in Native function..? 1 Answer Streams 4: Additional details on configuring auditing 1 Answer How to avoid data loss when connecting to non file based input sources. 1 Answer Java operators logs not printed in streams version 4.x 3 Answers
https://developer.ibm.com/answers/questions/507512/$%7Buser.profileUrl%7D/
CC-MAIN-2019-35
refinedweb
454
55.13
CodePlexProject Hosting for Open Source Software Can someone direct me to the documentation or a posting on how to create a new data provider? Those posts that I've found online seem to be with previous versions of BE.NET, and the standard XML provider, while stating that it can be used as a template for new providers, is causing issues when the namespace is changed, and minor tweaks to account for no longer being in the core dll. Or, has anyone worked on a LINQ to XML version of the XML provider, or seen one posted? I suppose I could use one of the database-backed providers, but since I'm going to start with the standard XML provider ... Thanks, ~James 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.
https://blogengine.codeplex.com/discussions/155480
CC-MAIN-2016-44
refinedweb
158
79.5
Guest post: Peter Knolle is a Solutions Architect at Trifecta Technologies, Force.com MVP, and Salesforce Developer Group Organizer. He holds six Salesforce certifications, blogs regularly at peterknolle.com, and is active on Twitter @PeterKnolle. The Lightning Component Framework uses an event-driven architecture and provides an infrastructure for developers to create their own custom Lightning events. Event-driven programming is a programming paradigm that allows developers to write functions to respond to fired events. The framework waits for events to be generated from user interactions such as button clicks and mouse overs, or by non-interactive actions such as loading completions or component renderings. When an event is fired the function(s) that have been declared to handle it are called by the framework. This post describes the mechanisms provided for working with custom events in the Lightning Component Framework. By the way, I should mention that the Lightning Components module in Trailhead is the best to get started while earning badges to demonstrate your skills. And be sure to check out all of the resources on the Lightning Components page at Salesforce Developers. Consider an application that allows users to search for Contacts and displays the results as a table of Contacts. You might be thinking that is simple…create a text input, a button, a table of results, perform the search, and display the results. Nothing to it! The better approach with component-based, event-driven programming is to separate out the search piece into its own component distinct from the table of results and have the search component fire an event when its search has completed. The benefit of this is that the search component can then be paired with other components that use its results differently. But it’s not just the search component that can be reused. The table component can be reused in other contexts as well. Events in the Lightning Component Framework are either component level or application level. Let’s explore the Contact application, and the contactSearch and contactTable components it uses to see how a component-level or application-level event can be used. Component-level events are generated by a component and can be handled by the component itself, or its containing component or application. Component events are useful for situations where your component can be used in an application multiple times and you don’t want the different instances interfering with each other. So, if the intent of the contactSearch was that it could be used in the application more than once, it would make sense for it to generate a component-level event. Let’s look at how that is done. A Lightning Event must be created and the type attribute must be specified as “COMPONENT.” The name that you specify is the event’s type and is displayed as the name of the file, e.g., contactSearchCompleteEvent. Note that the event type is specified in business terms and not in lower-level or implementation-level terms (e.g., serverCallDone, jsonReady, apexComplete, etc.). It is better to not let the lower-level details be part of the event’s specification. <aura:event <aura:attribute </aura:event> The aura:attribute defines the data that can be carried with the event. It is also referred to as the event’s shape. The contactSearch component registers that it can generate the event with the aura:registerEvent component. <aura:component <aura:registerEvent <div class="searchInput"> <ui:inputText </div> <ui:button </aura:component> The aura:registerEvent specifies the event type. Note the “c:” prefix. That is the default namespace and is used in orgs that do not have a namespace. The name attribute is what the component’s container uses to specify which of its controller functions should be called when the event is fired. In the Contact application, the app’s handleContactSearchComplete controller method will be called when the event is fired. <aura:application > <aura:attribute <div class="app"> <c:contactSearch <div class="table"> <c:contactTable aura: </div> </div> </aura:application> The contactSearch component creates the event, sets its parameters, and fires it after the search has completed. This code resides in a helper function that is called from a controller function. var searchCompleteEvent = component.getEvent("contactSearchComplete"); searchCompleteEvent.setParams({ contacts: contacts }).fire(); The app’s handler method is then called, which allows it to update its list of Contacts. handleContactSearchComplete : function(component, event, helper) { component.set("v.appContacts", event.getParam("contacts")); } The parameter that was set is retrieved with the getParam method. Note another extremely powerful aspect of the Lightning Component Framework at work here. There is no need to write code to manipulate the DOM to update the table. A single line of code to set the attribute value that the table uses will automatically update the table. Application-level events are published by a component, and any component or application that has subscribed to the event has its handler invoked when the event is fired. If the design of the contactSearch was that it should only be used once in an application and multiple components need to respond to process its results, it would make sense to use an application-level event. There are some slight modifications that can be made to the component-level, event-related code to convert it to an application-level event code. The only thing that changes in the Lightning Event is the level=”COMPONENT” changes to level=”APPLICATION.” Nothing needs to change with the way the component uses the aura:register to declare that it fires the event. The app’s markup changes to not specify an event handler on the component anymore, but instead specifies that it handles the event type, with the aura:handler component. <aura:handler The only thing that changes in the event firing code is to get the event in a different way. Instead of component.getEvent(), an Aura framework method is used to get the event: $A.getEvt(“c:contactSearchCompleteAppEvent”). The handler, handleContactSearchComplete, does not need to change. For more information on event handling in the Lightning Component Framework, refer to the Lightning Component Developer’s Guide. For a quick overview and introduction to Lightning Components, visit the Lightning Components page on Salesforce Developers. If you’re ready to learn hands-on while earning badges to demonstrate your skills, start the Lightning Components module in Trailhead.
https://developer.salesforce.com/blogs/developer-relations/2015/03/lightning-component-framework-custom-events.html
CC-MAIN-2021-31
refinedweb
1,059
54.83
Rate Limiter Requirements and Goals - To limit the number of requests per client in a particular time window. For example, a client is only allowed 100 requests per minute. - Rate limit should be considered across different servers of a service. The user should get an error message whenever the defined threshold is crossed across a cluster of servers. - Explore different types of algorithms used in rate limiting. Why ? - To prevent DDOS attacks - To eliminate spikiness in traffic from one client. For example, a client may make requests in abundance in a particular time period, leading to starvation of other clients. High Level Design (HLD) Bring the rate limiting configurations of all clients like number of requests allowed per time interval stored in database during app initialisation. Rate Limiter Middleware will be responsible for deciding which request will be served by the API and which request will be declined. Once a new request arrives, the Rate Limiter decides if it will be served or throttled. If the request is not throttled, then it’ll be passed to the API to process the request. Different Types of Algorithms - Token Bucket Algorithm In token bucket, for each client, we would record last request’s Unix timestamp and available token count within a hash in Redis. Refill rate of tokens is constant here. Please see the algorithm in action below: 2. Leaky Bucket Algorithm Suppose we have a bucket in which we are pouring water but we have to get water at a fixed rate, for this we will make a hole at the bottom of the bucket. It will ensure that water coming out is at some fixed rate, and also if bucket is full, we will stop pouring in it. The input rate can vary, but the output rate remains constant. Leaky Bucket uses a bucket or queue to hold the incoming requests. Whenever a new request arrives, it is appended to the rear of the queue, until the queue is not full. The requests are processed at fixed time intervals in the first come first serve (FCFS) manner, i.e. old requests are the one to be executed first. If the queue is full, the remaining are dropped or leaked with a proper message or notification to the client. Algorithm Define useful variables as follows: // The number of requests left in the bucket var numOfRequestLeftInTheBucket int // The timestamp of the last successful request insertion var lastInsertedTime int64 // The bucket capacity var capacity int// The time required for the bucket to be drained var duration int64// The request leakage rate of the bucket, which is equal to capacity/duration var rate float64For Example: The requests can drain for 1min at the rate of 4 req/second i.e Every 250 ms, one request leaves from the bucket Core Logic for Leaky Bucket. Please note that, counters will be maintained inside REDIS. For the sake of simplicity, redis is not used in the below code. func isAllowRequest(String key) bool { currentTime := time.Now().Unix(); /* Total requests left in the bucket = Previously left requests in the bucket – Requests leaked during the past period of time. */ /* Requests leaked during the last period of time = (Current time – Last request insertions time) * Request leakage rate */ /* If the current time is too far from the last request insertion time (no request has been inserted for a long time), the request left in the bucket is 0 (the bucket is drained) */ numOfRequestLeftInTheBucket = math.max(0, numOfRequestLeftInTheBucket - int64(((currTime - lastInsertionTime) * rate)) if (numOfRequestLeftInTheBucket < capacity) { lastInsertionTime = currTime; numOfRequestLeftInTheBucket++; return true; } return false; } 3. GCRA(Genetic Cell Rate Algorithm) Rate limits are defined by a limit, L, i.e. the number of requests, and a time period, P, such that a rate of only L/P is possible without the requests being limited (blocked). CASE: When L = 1 To understand this approach, let the rate of requests be R = L/P and then for simplicity set L = 1 so that the rate is R = 1/P. With this target rate, we can expect that the requests are separated by at least PPut simply, if the arrival time of the current request t is within P of the arrival time of the previous request s, or t — s < P, then the request must be limited. By defining a Theoretical Arrival Time, TAT, of the next request to be equal to the arrival time of the current request s plus P — i.e. TAT = s + P — we find that if t < TAT the request should be limited. Hence we can just calculate and store TAT on every request. CASE: When L > 1 When L > 1, we need to reconsider what the Theoretical Arrival Time of the next request should be. In the L = 1 case it was always the current request time s plus P. However when L > 1 it would be possible to have L requests within P, therefore each request is separated by P/L. In addition, it is now possible for requests to bunch, i.e. for the arrival time s to be less than the expected TAT. When this happens the next request’s Theoretical Arrival Time is TAT’ = TAT + P/L. However when requests don’t bunch and s is greater than TAT, TAT’ = s + P/L hence TAT’ = max(TAT, s) + P/L Now that we can calculate and store the TAT for the next request, we just need to decide when to limit. From the above it is clear that for each request that arrives before its TAT, the stored TAT increases by the interval P/L. Clearly if the new TAT’ exceeds the current time plus the period the request should be limited, i.e. if TAT’ — t > P or TAT — t > P — P/L. When L = 1 this reduces to TAT — t > 0 as previously stated. Note that the TAT should not be updated for limited requests, as they don’t have a theoretical arrival time. Please have a look at the following python code to get the idea of the implementation class RateLimit: def __init__(self, count: int, period: timedelta) -> None: self.count = count self.period = period@property def inverse(self) -> float: return self.period.total_seconds() / self.countclass Store: def get_tat(self, key: str) -> datetime: # This should return a previous tat for the key or the current time. pass def set_tat(self, key: str, tat: datetime) -> None: # Sets the tat for the next request passdef is_limit(self, key: str, limit: RateLimit) -> bool: now = datetime.utcnow() tat = max(self.get_tat(key), now) separation = (tat - now).total_seconds() max_interval = limit.period.total_seconds() - limit.inverse if separation > max_interval: reject = True else: reject = False new_tat = max(tat, now) + timedelta(seconds=limit.inverse) self.set_tat(key, new_tat) return reject 4. Fixed Window Algorithm In Fixed window rate limiting algorithm, the timeline is divided into a fixed window(say 1min or 1 hour etc.) and each window is provided with a counter(to count a number of requests in a particular window). If the value of the counter exceeds the limit, the remaining requests are dropped. The counter resets after every window. Suppose we have a rate limit of 10 requests/hour and have a data model like below. In the above example, if a new request arrives at 12:40, we get the count from the bucket(12:00–1:00) which is 7, and if less than our threshold of 10 req/hour, hence this request will be processed and count of the current window will become 8. Now assume a case for window (1:00–2:00), a request arrives at 1:40 and the value of the counter in this window is 9, which is less than permissible limit(10), so this request will be accepted and the value of the counter will become 10. Now no more requests in the window (1:00–2:00) will be accepted. 5. Sliding Logs Algorithm In sliding logs, we maintain a sliding window by keeping track of each request per client. We can store the timestamp of each request in a Redis sorted set. Let’s assume our rate limiter is allowing 3 requests per minute per client, so, whenever a new request comes in, the Rate Limiter will perform following steps: - Remove all the timestamps from the Sorted Set that are older than “CurrentTime — 1 minute”. - Count the total number of elements in the sorted set. Reject the request if this count is greater than our throttling limit of “3”. - Insert the current time in the sorted set and accept the request. 6. Sliding Window with Counter Algorithm We can maintain a sliding window if we can keep track of each request per user using multiple fixed time windows, , e.g., 1/60th the size of our rate limit’s time window. For example, if we have a minutely rate limit, we can keep a count for each second and calculate the sum of all counters in the past one minute when we receive a new request to calculate the throttling limit. Let’s take an example where we rate-limit at 100 requests per minute with an additional limit of 5 requests per second(optional). This means that when the sum of the counters with timestamps in the past one minute exceeds the request threshold (100), the client has exceeded the rate limit. In addition to that, the client can’t send more than 5 requests per seconds(optional). We can store our counters in a Redis hash. When each request increments a counter in the hash, it also sets the hash to expire a minute later. So, whenever a new request comes in, the Rate Limiter middleware will perform following steps - Remove all the timestamps from the sorted set that are older than “CurrentTime — 1 minute”. - Insert the current time in the sorted set, set expiry of the current timestamp and accept the request. - Calculate the sum of the counters with timestamps in the set in the past 1 minute. Reject the request if this count is greater than our throttling limit of “100”. Please see the algorithm in action in the following diagram: Problems with Sliding window with Count The only problem with this algorithm is there’ll be some inconsistency during race conditions. For example, let’s say that two requests come at the same time on the load balancer. Those two requests are redirected to different servers in the cluster. Let’s assume that we’ve allowed 10 requests per minute for a client and we’ve already allowed 9 requests in the past 1 minute. Now, at the 55th second of the minute, these two requests come, they’ll see that total requests in the past one minute are 9 and therefore, both the requests will be allowed. One possible solution is to use distributed redis lock such that, if two requests come at the same time, only one can be allowed to read the data, the other request has to wait till the first request updates the sum variable in redis. But this will become a performance bottleneck since latency will take a hit. The other solution would be to have relaxed rate limiting. For example, if we have a limit of 100 requests per minute and let’s assume we have served 99 requests in the past 50 seconds and now we get 5 requests in the 55th second of the minute. So, we can simply allow these 5 requests to have a total of 104 requests per minute. Comparison Between Different Algorithms That was all about different algorithms employed in rate limiting. Do let me know in case you have any doubts. Cheers :)
https://aman-jain24.medium.com/rate-limiter-9a8e8b94c7b6
CC-MAIN-2021-31
refinedweb
1,944
60.55
How to draw Marker (c++)? - Shira-Brixx How can I draw a Marker? static void DRAW_MARKER(int type, float posX, float posY, float posZ, float dirX, float dirY, float dirZ, float rotX, float rotY, float rotZ, float scaleX, float scaleY, float scaleZ, int red, int green, int blue, int alpha, BOOL bobUpAndDown, BOOL faceCamera, int p19, BOOL rotate, char* textureDict, char* textureName, BOOL drawOnEnts) { invoke<Void>(0x28477EC23D892089, type, posX, posY, posZ, dirX, dirY, dirZ, rotX, rotY, rotZ, scaleX, scaleY, scaleZ, red, green, blue, alpha, bobUpAndDown, faceCamera, p19, rotate, textureDict, textureName, drawOnEnts); } // 0x28477EC23D892089 0x48D84A02 0x28477ec23d892089, 0xbdd6765e5846a7de, //1.0.1365.1 (1.43) // loop > bool drawMarkerToggle = false; void drawMarker() { if (drawMarkerToggle) { GRAPHICS::DRAW_MARKER(markerType, markerPos.x, markerPos.y, markerPos.z, markerDir.x, markerDir.y, markerDir.z, markerRot.x, markerRot.y, markerRot.z, markerScale.x, markerScale.y, markerScale.z, markerRED, markerGREEN, markerBLUE, markerALPHA, 0, 1, 1, 0, 0, 0, 0); } } Vector3 markerPos is set to my coords. the other Vector3´s have I try to change with alot different Values... but the marker dont will show up and my game laggs if I loop these! I hope anyone know to help me!? (and please only in c++) Nobody knows? @ikt Sure, its always open and not only that. I ve tried all things out, but idk what the problem is that i cant see a marker. Its easy to create a checkpoint, but with a simple marker I have my problems! Try using whatever Guadmaz did: Minimal example: using System; using GTA; using GTA.Native; using System.Collections.Generic; public class DrawMarker : Script { public DrawMarker() { Tick += OnTick; } void OnTick(object sender, EventArgs e) { Ped player = Game.Player.Character; if (!player.Exists()) return; Vehicle v = player.CurrentVehicle; if (!v.Exists()) return; var pos = v.Position; Function.Call(Hash.DRAW_MARKER, 2, pos.X, pos.Y, pos.Z + 2, 0f, 0f, 0f, 0f, 180f, 0f, 1f, 1f, 1f, 255, 128, 0, 50, false, true, 2, false, false, false, false); } } GRAPHICS::DRAW_MARKER(2, pos.X, pos.Y, pos.Z + 2, 0f, 0f, 0f, 0f, 180f, 0f, 1f, 1f, 1f, 255, 128, 0, 50, false, true, 2, false, false, false, false); You might need to fix the arguments (to what i just posted) as the signature might be wrong. @Shira-Brixx said in How to draw Marker (c++)?: // loop > bool drawMarkerToggle = false; void drawMarker() { if (drawMarkerToggle) You have set drawMarkerToggle to false inside the loop and then in the if clause you tell to only draw the marker if drawMarkerToggle is true. No wonder that nothing happens! - You need to declare drawMarkerToggle outside this loop. - You need to have the marker rendering inside the Tick eventhandler (which I think you did). - Do not set the interval so that the tick eventhandler gets called each frame. - Set the drawMarkerToggle outside the tick eventhandler (I hope you know the difference between declaration and setting) - IMPORTANT! Draw only markers which are nearby! - Also IMPORTANT! Do only things each frame where and when necessary! Tip: The best approach to keep things smooth (performance friendly) is to create a Rendering class which inherits from script. This class is only responsible for rendering tasks! Use other classes for the rest. Since the Rendering class must be decoupled from any other classes in order to run parallel, you need a kind of Proxy for the communication between them (see Balking pattern). You can use a simple static class which only holds properties like for example bool ConfigLoaded. You can then set such a property in one class and query it in another without both "knowing" each other. This picture shows the marker optimization process in my Teleportals mod.
https://forums.gta5-mods.com/topic/19301/how-to-draw-marker-c
CC-MAIN-2018-47
refinedweb
603
64.2
Question Refer to problem 15, and assume new circumstances cause the analysts to reduce the anticipated P/E in 2011 to 20 percent below the average low J&J P/E for the last 10 years. Furthermore, projected earnings per share are reduced to $4.00. What would the stock price be? Answer to relevant QuestionsSecurity analysts following Health Sciences, Inc., use a simplified income statement method of forecasting. Assume that 2011 sales are $30 million and are expected to grow by 11 percent in 2012 and 2013. The after-tax profit ...If in problem 2 the beta (b) were 1.9 and the other values remained the same, what is the new value of Ke? What is the relationship between a higher beta and the required rate of return (Ke)? Why will the fixed-charge-coverage ratio always be equal to or less than times interest earned? Given the following financial data, compute: a. Return on equity. b. Quick ratio. c. Long-term debt to equity. d. Fixed-charge coverage. Assets: Cash $ 2,500 Accounts receivable 3,000 Inventory 6,500 Fixed ...Given the following financial data: Net income/Sales = 4 percent; Sales/Total assets = 3.5 times; Debt/Total assets = 60 percent; compute: a. Return on assets. b. Return on equity. Post your question
http://www.solutioninn.com/refer-to-problem-15-and-assume-new-circumstances-cause-the
CC-MAIN-2017-13
refinedweb
216
61.33
please i have this task to to but i can only manage to display five cards but i cant compare my result, here is what should be done: (Card Shuffling and Dealing) Modify the application to deal a five-card poker hand. Then modify class "DeckOfCards") also and also Use the methods developed to write an application that deals two five-card poker hands, evaluates each hand and determines which is better. below is the codes of classes i have tried introducing this code bu it gives me 3 errors:" "if(myDeckOfCards.dealCard(face + " of " + suit).equals("Duece of Hearts")) { System.out.printf( "A Pair" ); }" <// Card.java // Card class represents a playing card. public class Card { private String face; // face of card ("Ace", "Deuce", ...) private String suit; // suit of card ("Hearts", "Diamonds", ...) // two-argument constructor initializes card's face and suit public Card( String cardFace, String cardSuit ) { face = cardFace; // initialize face of card suit = cardSuit; // initialize suit of card } // end two-argument Card constructor // return String representation of Card public String toString() { return face + " of " + suit; } // end method toString } // end class Card > <// DeckOfCards.java // DeckOfCards class represents a deck of playing cards. import java.util.Random; public class DeckOfCards { private Card[] deck; // array of Card objects private int currentCard; // index of next Card to be dealt private static final int NUMBER_OF_CARDS = 52; // constant # of Cards // random number generator private static final Random randomNumbers = new Random(); // constructor fills deck of Cards public DeckOfCards() { String[] faces = { "Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" }; String[] suits = { "Hearts", "Diamonds", "Clubs", "Spades" }; deck = new Card[ NUMBER_OF_CARDS ]; // create array of Card objects currentCard = 0; // set currentCard so first Card dealt is deck[ 0 ] // populate deck with Card objects for ( int count = 0; count < deck.length; count++ ) deck[ count ] = new Card( faces[ count % 13 ], suits[ count / 13 ] ); } // end DeckOfCards constructor // shuffle deck of Cards with one-pass algorithm public void shuffle() { // after shuffling, dealing should start at deck[ 0 ] again currentCard = 0; // reinitialize currentCard // for each Card, pick another random Card and swap them for ( int first = 0; first < deck.length; first++ ) { // select a random number between 0 and 51 int second = randomNumbers.nextInt( NUMBER_OF_CARDS ); // swap current Card with randomly selected Card Card temp = deck[ first ]; deck[ first ] = deck[ second ]; deck[ second ] = temp; } // end for } // end method shuffle // deal one Card public Card dealCard() { // determine whether Cards remain to be dealt if ( currentCard < deck.length ) return deck[ currentCard++ ]; // return current Card in array else return null; // return null to indicate that all Cards were dealt } // end method dealCard } // end class DeckOfCards> <// DeckOfCardsTest.java // Card shuffling and dealing. public class DeckOfCardsTest { // execute application public static void main( String[] args ) { DeckOfCards myDeckOfCards = new DeckOfCards(); myDeckOfCards.shuffle(); // place Cards in random order // print all 52 Cards in the order in which they are dealt for ( int i = 1; i <= 5; i++ ) { // deal and display a Card System.out.printf( "%-19s", myDeckOfCards.dealCard() ); if ( i % 1 == 0 ) // output newline every 4 cards System.out.println(); } // end for /* if(myDeckOfCards.dealCard(face + " of " + suit).equals("Duece of Hearts")) { }*/ } // end main } // end class DeckOfCard>
http://www.javaprogrammingforums.com/whats-wrong-my-code/29141-guys-please-help-me-find-answers-b-below.html
CC-MAIN-2015-22
refinedweb
517
50.97
DB tool with extension tool I am very new to SoaTest and was having difficulty utilizing the extension tool with the DB tool. I was wanting to access the results of a db tool query within the extension tool but was having difficulty doing so. The input object just shows "text" where if i attach the extension tool to a soap response, I will recieve the soap response output. Could anyone provide a learning resource or even a simple example would be appreciated. Here is a simple example of what i was trying. import com.parasoft.api.*; boolean customAssertion(Object input, ScriptingContext context) { Application.showMessage("Value from SQL response is " + input) return true; } 0 Attach your Extension Tool to the "Results as XML" output of the DB Tool (right-click on DB Tool > Select Add Output... > Select Results as XML > Choose Extension Tool > Click Finish). Now the input to your Extension Tool should be an XML representation of the result set from your SQL query. Thank you for responding. When I followed those instructions. (which seem like they should work.) I just see the output of "text" from my input object. I feel like there is something very basic I am missing. I attached a screenshot of hte test with the log output. You are running into an inconsistency between how DBTool and SOAP Client pass the input to an Extension Tool. Modify your script like this and it will work: That did the trick. Thank you. Using the getText I see how the "SQL Query" extension tool shows the SQL going into the tool and the "Results as XML" extension tool shows the output coming out. Is there a resource which outlines how the tools interact with the extension tools or is this a learn by experience ? Unfortunately this is a learn by experience - if you run into similar kinds of issues these forums are a great place to try to get answers! Understandable. Thank you again for your help.
https://forums.parasoft.com/discussion/comment/8112/
CC-MAIN-2018-09
refinedweb
331
64.2
The QStyleOptionToolBox class is used to describe the parameters needed for drawing a tool box. More... #include <QStyleOptionToolBox> Inherits QStyleOption. Inherited by QStyleOptionToolBoxV2. The QStyleOptionToolBox class is used to describe the parameters needed for drawing a tool box. QStyleOptionToolBox contains all the information that QStyle functions need to draw QToolBox.ToolBox.. Creates a QStyleOptionToolBox, initializing the members variables to their default values. Constructs a copy of the other style option. This variable holds the icon for the tool box tab. The default value is an empty icon, i.e. an icon with neither a pixmap nor a filename. This variable holds the text for the tool box tab. The default value is an empty string.
https://doc.qt.io/archives/4.6/qstyleoptiontoolbox.html
CC-MAIN-2021-49
refinedweb
115
61.93
Quoting "Russ P." <Russ.Paielli at gmail.com>: > On Jan 19, 7:13 am, Bruno Desthuilliers <bruno. > 42.desthuilli... at websiteburo.invalid> wrote: > > > I must be missing the point : if it's a public attribute, it doesn't > > need a "property" ? I guess we use the same words for different things > here. > > Yes, you are missing more than one point. > > Scala automatically converts public data members into properties, > apparently to save the programmer the trouble of doing it manually. If > you are interested, I'm sure you can find publicly available > information on it. Russ, I think _you_ are missing the point. If the attribute is already public, why does it need properties? Why would a programmer go to the trouble of adding them manually, just to get one level of indirection for an already public attribute? > > I definitively wouldn't bet my ass on language-level access restriction > > to protect software from fraud or sabotage. > > You're missing the point here too. I'll try one more time to explain > it. And I think you are conflating the idea of "private" as in "secret information that should not be known by the _public_" and "private" as in "static safeguards enforced by the compiler to prevent accidents" [and you are missing the third, "compiler feature to prevent namespace pollution without having to use extremely unlikely variable names", i.e, self.__x in python]. No wonder you can't get Bruno's point. For the second, static checks to prevent accidents, you have pylint. For the first, not only you are using the wrong tool, but you are barking at python for not having it. Assuming that pylint is perfect (big assumption, but it is up to you to prove where it fails), what would be the difference between only accepting/running "pylint-authorized code" and the enforced hiding you desire? This thread is starting to remind me of a professor of mine, who once claimed that python didn't have private attributes because it "is opensource and anyone can see the source code anyway", and the obvious confusion of his students ("why should I make my entrypoint '_public_ static void main', if it is _my_ sourcecode and I don't want to share it?"). What you want is not enforced data hiding. You want something actually designed to try to prevent abuses from hostile programmers - go use .Net or Java, who attempt to do that (I don't know with what level of success, but they at least provide you the 'locks' and 'police' that you need). Or better yet, write a proposal about how to implement code trust in Python. I'll support you on that one, and I think many others will. But if you keep presenting data hiding as a solution to that problem... I doubt that you will be heard. -- Luis Zarrabeitia Facultad de Matemática y Computación, UH
https://mail.python.org/pipermail/python-list/2009-January/520869.html
CC-MAIN-2018-09
refinedweb
482
72.26
Formerly known as Tweep, Twint is an advanced Twitter scraping tool written in Python that allows for scraping Tweets Some of the benefits of using Twint vs Twitter API: - Can fetch almost all Tweets (Twitter API limits to last 3200 Tweets only) - Fast initial setup - Can be used anonymously and without Twitter sign up - No rate limitations Requirements - Python 3.6 Installing Git: git clone pip3 install -r requirements.txt pip3 install --upgrade -e git+[email protected]/master#egg=twint pipenv install -e git+ CLI Basic Examples and Combos A few simple examples to help you understand the basics: from the specified Tweet ID. Module Example Twint can now be used as a module and supports custom formatting. More details are located in the wiki import twint # Configure c = twint.Config() c.Username = "noneprivacy" c.Search = "#osint" c.Format = "Tweet id: {id} | Tweet: {tweet}" #Twitter can shadow-ban accounts, which means that their tweets will not be available via search. To solve this, pass --profile-fullif If you have any questions, want to join in on discussions, or need extra help, you are welcome to join our Twint focused Slack server. If you are interested in OSINT and still seeking for help or suggestions, join the OSINT community at OSINT Team (there is a specific Twint channel)
https://amp.kitploit.com/2019/05/twint-advanced-twitter-scraping-and.html
CC-MAIN-2021-17
refinedweb
217
59.13
Issue Type: Bug Created: 2009-02-17T21:48:08.000+0000 Last Updated: 2009-02-18T03:23:22.000+0000 Status: Resolved Fix version(s): - 1.8.0 (30/Apr/09) Reporter: Sebastian (sfjb) Assignee: Thomas Weidner (thomas) Tags: - Zend_File_Transfer Related issues: Attachments: When using isUploaded() to check whether a file has been uploaded, rather than return false (as documented) if the file has not been uploaded, a Zend_File_Transfer_Exception is thrown. The Zend_File_Transfer_Exception' has the message "'file' not found by file transfer adapter". I believe that the function should just return true or false if the specified file has not been uploaded. The exception stems from the _getFiles() method. Looks like it the $noexception parameter needs to be set to true. The isUploaded() method also needs to test for empty return value from _getFiles() before looping through it. Actually, can't the isUploaded() just return (bool) _getFiles($files)? Posted by Thomas Weidner (thomas) on 2009-02-18T03:23:20.000+0000 Not reproducable with trunk. Seems to be already fixed.
https://framework.zend.com/issues/browse/ZF-5821?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
CC-MAIN-2016-30
refinedweb
170
60.11
Hi all Currently I'm using the search method returning the Hits object. According to one should use a HitCollector-oriented search method instead. But I need another aspect of the "Hits search(...)" method: it's sorting ability. Now my code looks like : def hits = multiSearcher.search( query, Methods.activeFilter, sort ) def iter = hits.iterator() def results = [] int counter = 0 for( hit in iter ){ if( range.contains( counter ) && hit.document ){ results << Methods.bind( hit.document, lucenizedClasses ) }else if( counter >= upper ) break counter++ } So, how can I get the same results using the HitCollector? Also it would be really nice, if you could point me to some examples of using it... Thanx in advance, Konstantyn -- View this message in context: Sent from the Lucene - Java Users mailing list archive at Nabble.com. --------------------------------------------------------------------- To unsubscribe, e-mail: java-user-unsubscribe@lucene.apache.org For additional commands, e-mail: java-user-help@lucene.apache.org
http://mail-archives.apache.org/mod_mbox/lucene-java-user/200806.mbox/%3C17604363.post@talk.nabble.com%3E
CC-MAIN-2014-49
refinedweb
152
54.29
py2rs From Python into Rust let x = Rust::from("Python"); A quick reference guide for the Pythonista in process of becoming a Rustacean. NOTE The original repository for this article is on <-- READ THERE FOR UPDATED VERSION Monty Python - Season 3 - Episode 49 Mrs. Jalin: George. Mr. Jalin: crustaceans. Mr. Jalin: Crustaceans! Mrs. Jalin: Yes. Mr. Jalin: What's he mean, crustaceans? Mrs. Jalin: CRUSTACEANS!! GASTROPODS! LAMELLIBRANCHS! CEPHALOPODS! ... Ok...watch it later... let's learn some Rust now... TOC - Getting Started with Rust - Where to exercice - Where to be informed on news and updates - Interacting with Rustacean Communities - Additional learning Resources - Curious Facts - py2rs: Glossary of terms - py2rs: General fact comparison - py2rs: Environment Tools - py2rs: Libraries and Frameworks - py2rs: Applications - py2rs: Useful Crates - py2rs: Code comparison Python X Rust implementations - Credits Getting Started with Rust Assuming you already know what is Rust and already decided to start learning it. Here are some steps for you to follow: - Take a tour of Rust Syntax and Coding Style - Watch some screencasts to get basics of Ownership &Borrowing concept - Follow this set of runnable examples to understand how everything fit together Now it is time to read your first book, you can pick: Rust Essentials A good introduction to Rust language in a more superficialapproach which results in a very pleasant and easy reading, recommended even for those who are not experienced with low level systems languages. - Paperback and e-book available on Packt Publisher TRPL (The Rust Programming language Book) A complete Guide to Rust Language - Official Book - Free to read online - Available as paperback or e-book (buy at Amazon) Read some real examples - Rust Cookbook This Rust Cookbook is a collection of simple examples that demonstrate good practices to accomplish common programming tasks, using the crates of the Rust ecosystem. - Anthology - Patterns and Good Practices - Rust Patterns - API Guidelines Exercices Time to put your new knowledge in action solving some exercices. 1) Exercism.io Register a new account on exercism.io (using github auth) Install exercism command line client on your computer Solve some exercices: 2) Rust Playground Run Live Rust Code in the browser with Getting updated Now I assume you are addicted to Rust and you want to be updated about averything around it, here are some good links to follow. 1) This Week in Rust Newsletter 2) Reddit (serious sub-reddit) (almost memes only) 3) Official Twitter Interact with other Rustaceans Don't be afraid, the Rustaceans are a very receptive species and are cozy with the Pythonistas. Community links: Local Brazil - General - Youtube : - Telegram: - Rust BH Add your country/city here, send a Pull Request. Additional learning resources - Rust Learning - Rust Guidelines (WIP) - Rust Design Patterns and Idioms - Idiomatic Rust - GTK Rust Tutorial - Effective use of iterators - Red Hat Developers: Speed up Your Python with Rust Facts - The language is named Rust because "rust is as close to the bare metal as you can get.", in metal theory rust is the chemical layer closest to bare metal. - The Rust trifectais 1) Memory Safe, 2) Fast 3) Concurrent - Rust can be used for web development - Rust can be used for Gaming Development - Rust can be used for Machine Learning - Lots of IDEs and Editors supports Rust (VSCode is known to have the better support by now) - Rust packages are called Cratesand are installed by Cargoexplore them at - In Rust there is no class but Structs, Enums, Traits, functions and macros! - The Rust mascot (unofficial) is called Ferris and it is a crab (There is no record of the official reason about being a crab, the reasonable history is that it was inspired by the Rusty Crab a common species of crab and also a name of a famous restaurant.) More facts? send a question here or send a Pull Request adding an interest fact to this list. Glossary of terms py2rs From Python into Rust let x = Rust::from("Python"); A quick reference guide for the Pythonista in process of becoming a Rustacean. General Environment Tools Libraries and Frameworks Applications Useful crates Add Pythonic features to Rust Show me The code From Python to Rust by examples You can copy-paste and run the Rust examples in and Python in Creating a new project Create a new project with baseic files, entry points, module initializer, dependency and installation artifacts. Python $ mkdir {pyproject,pyproject/src} $ touch {pyproject/src/{__init__.py,__main__.py,program.py},pyproject/{requirements.txt,setup.py}} $ echo "-e ." >> pyproject/requirements.txt $ echo "from setuptools import setup" >> pyproject/setup.py $ echo "setup(author=..., name=...)" >> pyproject/setup.py Rust $ cargo new my-rust-program Installing new libraries/crates Python $ pip install foo Rust $ cargo install foo Running / Compiling Python $ python my_python_program.py Rust $ cargo run Hello World Python if __name__ == "__main__": print("Hello, World") Rust fn main() { println!("Hello, World"); } Types and Declarations Create new objects, values on basic primitive types and also data structures. Python age = 80 name = 'daffy' weight = 62.3 loons = ['bugs', 'daffy', 'taz'] ages = { # Ages for 2017 'daffy': 80, 'bugs': 79, 'taz': 63, } Rust use std::collections::HashMap; fn main() { let age = 80; let name = "daffy"; let weight = 62.3; let mut loons = vec!["bugs", "daffy", "taz"]; let mut ages = HashMap::new(); // Ages for 2017 ages.insert("daffy", 80); ages.insert("bugs", 79); ages.insert("taz", 63); } Define a function Defining a function that takes 2 integer arguments and returns its sum. Python def add(a, b): "Adds a to b""" return a + b Rust // Adds a to b fn add(a: i32, b: i32) -> i32 { a + b } List/Slice Creating a list, adding new elements, gettings its length, slicing by index, itarating using for loop and iterating with enumerator. Python names = ['bugs', 'taz', 'tweety'] print(names[0]) # bugs names.append('elmer') print(len(names)) # 4 print(names[2:]) # ['tweety', 'elmer'] for name in names: print(name) for i, name in enumerate(names): print('{} at {}'.format(name, i)) Rust fn main() { let mut names = vec!["bugs", "taz", "tweety"]; println!("{}", names[0]); // bugs names.push("elmer"); println!("{}", names.len()); // 4 println!("{:?}", &names[2..]); // ["tweety", "elmer"] for name in &names { println!("{}", name); } for (i, name) in names.iter().enumerate() { println!("{} at {}", i, name); } } Dict/Map Create new dictionaries (hash maps), adding new keys and values, changing values, getting by key, checking if a key is containing, etc. Python # Creating a new dict and populating it ages = {} ages['daffy'] = 80 ages['bugs'] = 79 ages['taz'] = 63 # or doing the same using a for loop ages = {} for name, age in [("daffy", 80), ("bugs", 79), ("taz", 63)]: ages[name] = age # or initializing from a list ages = dict([("daffy", 80), ("bugs", 79), ("taz", 63)]) # or passing key values on creation ages = { # Ages for 2017 'daffy': 80, 'bugs': 79, 'taz': 63, } ages['elmer'] = 80 print(ages['bugs']) # 79 print('bugs' in ages) # True del ages['taz'] for name in ages: # Keys print(name) for name, age in ages.items(): # Keys & values print('{} is {} years old'.format(name, age)) Rust use std::iter::FromIterator; use std::collections::HashMap; fn main() { // Creating a new HashMap and populating it let mut ages = HashMap::new(); // Ages for 2017 ages.insert("daffy", 80); ages.insert("bugs", 79); ages.insert("taz", 63); // or doing the same using a loop let mut ages = HashMap::new(); for &(name, age) in [("daffy", 80), ("bugs", 79), ("taz", 63)].iter() { // For non-Copy data, remove & and use iter().clone() ages.insert(name, age); } // or initializing from Array let mut ages: HashMap<&str, i32> = // Ages for 2017 [("daffy", 80), ("bugs", 79), ("taz", 63)] .iter().cloned().collect(); // or initializing from Vec (Iterator) let mut ages: HashMap<&str, i32> = // Ages for 2017 HashMap::from_iter( vec![ ("daffy", 80), ("bugs", 79), ("taz", 63) ] ); ages.insert("elmer", 80); println!("{}", ages["bugs"]); // 79 println!("{}", ages.contains_key("bugs")); // true ages.remove("taz"); for name in ages.keys() { // Keys println!("{}", name); } for (name, age) in &ages { // Keys & values println!("{} is {} years old", name, age); } } Pythonic alternative to dict/map in Rust You can use the maplit crate to load hashmap! macro to have an efficient sugared (a.k.a Pythonic) syntax! # Cargo.toml [dependencies] maplit = "*" then #[macro_use] extern crate maplit; let map = hashmap!{ "daffy" => 80, "bugs" => 79, "taz" => 63, }; set / HashSet Create a set (a hash of unique keys), add new keys and compute intersection, difference and union Python # creating and populating colors = set() colors.add("red") colors.add("green") colors.add("blue") colors.add("blue") # using literal syntax colors = {'red', 'green', 'blue', 'blue'} # from an iterator colors = set(['red', 'green', 'blue', 'blue']) # deduplication print(colors) # {"blue", "green", "red"} # operations colors = {'red', 'green', 'blue', 'blue'} flag_colors = {"red", "black"} # difference colors.difference(flag_colors) # {'blue', 'green'} # symmetric difference colors.symmetric_difference(flag_colors) # {'black', 'blue', 'green'} # intersection colors.intersection(flag_colors) # {'red'} # unioin colors.intersection(flag_colors) # {'black', 'blue', 'green', 'red'} Rust use std::collections::HashSet; use std::iter::FromIterator; fn main() { // creating and populating - type inference let mut colors = HashSet::new(); colors.insert("red"); colors.insert("green"); colors.insert("blue"); colors.insert("blue"); // from an iterator - explicit type let mut colors: HashSet<&str> = HashSet::from_iter(vec!["red", "green", "blue", "blue"]); // deduplication println!("{:?}", colors); // {"blue", "green", "red"} // Operations let mut colors: HashSet<&str> = HashSet::from_iter(vec!["red", "green", "blue", "blue"]); let mut flag_colors: HashSet<&str> = HashSet::from_iter(vec!["red", "black"]); // difference colors.difference(&flag_colors); // ["green", "blue"] // symmetric difference colors.symmetric_difference(&flag_colors); // ["blue", "green", "black"] // intersection colors.intersection(&flag_colors); // ["red"] // union colors.union(&flag_colors); // ["red", "blue", "green", "black"] } or syntax sugared using maplit crate #[macro_use] extern crate maplit; let colors = hashset!{"red", "green", "blue", "blue"}; while and for loops Looping until a condition is met or over an iterable object. Python # While loop counter = 0 while counter < 10: print(counter) counter += 1 # infinite while loop while True: print("loop Forever!") # infinite ehile loop with break counter = 0 while True: print(counter) counter += 1 if counter >= 10: break # while loop with continue counter = 0 while True: counter += 1 if counter == 5: continue print(counter) if counter >= 10: break # For loop over a list for color in ["red", "green", "blue"]: print(color) # Enumerating indexes for i, color in enumerate(["red", "green", "blue"]): print(f"{color} at index {i}") # For in a range for number in range(0, 100): print(number) # from 0 to 99 Rust fn main() { // While loop let mut counter = 0; while counter < 10 { println!("{}", counter); counter += 1; } // infinite while loop loop { println!("Loop forever!"); } // infinite while loop with break let mut counter = 0; loop { println!("{}", counter); counter += 1; if counter >= 10 { break; } } // infinite while loop with continue let mut counter = 0; loop { counter += 1; if counter == 5 { continue; } println!("{}", counter); if counter >= 10 { break; } } // for loop over a list for color in ["red", "green", "blue"].iter() { println!("{}", color); } // Enumerating indexes for (i, color) in ["red", "green", "blue"].iter().enumerate() { println!("{} at index {}", color, i); } // for in a range for number in 0..100 { println!("{}", number); // from 0 to 99 } } Loop Labels Rust has a looping feature which is not present on Python: Loop labels 'outer: for x in 0..10 { 'inner: for y in 0..10 { if x % 2 == 0 { continue 'outer; } // continues the loop over x if y % 2 == 0 { continue 'inner; } // continues the loop over y println!("x: {}, y: {}", x, y); } } Files Read a text file and iterate its lines printing the content, properly close the file at the end. Python from pathlib import Path with open(Path("/tmp/song.txt")) as fp: # Iterate over lines for line in fp: print(line.strip()) Rust use std::io::{BufReader, BufRead}; use std::fs::File; use std::path::Path; fn main () { let fp = File::open(Path::new("/tmp/song.txt")).unwrap(); let file = BufReader::new(&fp); for line in file.lines() { // Iterate over lines println!("{}", line.unwrap()); } } Exceptions/Return Error Expecting for exceptions and identifying errors. Python def div(a, b): if b == 0: raise ValueError("b can't be 0") return a / b # ... try: div(1, 0) except ValueError: print('OK') Rust ``` --- ### Concurrency **Python** ```python thr = Thread(target=add, args=(1, 2), daemon=True) thr.start() Rust ``` --- ### Communicating between threads Managing data context between threads. **Python** ```python from queue import Queue queue = Queue() # ... # Send message from a thread queue.put(353) # ... # Get message to a thread val = queue.get() Rust ``` --- ### Sorting Sorting lists, reversing and using a key. **Python** ```python names = ['taz', 'bugs', 'daffy'] # Lexicographical order names.sort() # Reversed lexicographical order names.sort(reverse=True) # Sort by length names.sort(key=len) Rust ``` --- ### Web app with Flask / Rocket **Python** ```python from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'Hello Python' if __name__ == '__main__': app.run(port=8080) Rust #![feature(plugin)] #![plugin(rocket_codegen)] extern crate rocket; #[get("/")] fn index() -> &'static str { "Hello Rust" } fn main() { rocket::ignite().mount("/", routes![index]).launch(); } MISSING SOME IMPLEMENTATIONS AND EXAMPLES PLEASE CONTRIBUTE on HTTP Request with error handling Python import json from urlib2 import urlopen url = '' try: fp = urlopen(url) except HTTPError as err: msg = 'error: cannot get {!r} - {}'.format(url, err) raise SystemExit(msg) try: reply = json.load(fp) except ValueError as err: msg = 'error: cannot decode reply - {}'.format(err) raise SystemExit(msg) print(reply['origin']) Rust ``` --- ### Encode and Decode JSON **Python** ```python data = '''{ "name": "bugs", "age": 76 }''' obj = json.loads(data) json.dump(obj, stdout) Rust ``` --- ### Print Object for Debug/Log **Python** ```python daffy = Actor( name='Daffy', age=80, ) print('{!r}'.format(daffy)) Rust ``` --- ### Object Orientation **Python** ```python class Cat: def __init__(self, name): self.name = name def greet(self, other): print("Meow {}, I'm {}".format(other, self.name)) # ... grumy = Cat('Grumpy') grumy.greet('Grafield') Rust rust Credits NOTE The original repository for this article is on CONTRIBUTE Created by Bruno Rocha @rochacbruno inspired by With contributions by: - Send a PR and include your name and links
http://brunorocha.org/python/py2rs-from-python-to-rust-reference-guide.html
CC-MAIN-2017-51
refinedweb
2,273
54.63
Configuring an Ensemble System and Creating a Namespace This appendix provides information on configuring Ensemble and Caché so that you can use it as an ESB or with pass-through REST and SOAP services and operations. It contains the following sections: This appendix briefly discusses how to configure your system so that you can use HTTP and SOAP services through the Ensemble CSP port. This information is intended to help you set up a development or test system for these services. Complete information about these topics is provided in the Caché documentation. See “Configuring Caché” in the Caché System Administration Guide for more details. To set up an Ensemble development or test system for HTTP or SOAP services, follow these steps: If you have installed Ensemble in a locked down installation, Studio access is disabled. Open the Management Portal and enable Studio access: Start the Management Portal from the Ensemble cube. You will have to use your Windows login username rather than _system to access the portal. Enter the password that you specified during installation. Select System Administration > Security > Services to get to the Services portal page. The %Services_Bindings service is disabled by default. Select the service name and check the Service Enabled checkbox and save the setting. If you are not using an existing Ensemble namespace, create a new namespace: Select System Administration > Configuration > System Configuration > Namespaces to get to the Namespaces portal page. Select the Create New Namespace button, specify a name for the namespace, such as SERVICESNS. Select the Create New Database button for the globals database. In the Database Wizard, enter a name for the globals database, such as SERVICES_GDB. The wizard uses the name to create a directory for the database. Select the Next button twice to get to the Database Resource form. Select the Create a new resource radio button. The wizard displays a Create New Resource form. Accept the suggested name, such as %DB_SERVICES_GDB and ensure that Public Permissions Read and Write checkboxes are not checked. Select the Save button on the Database Resource form and the Finish button on the Database Wizard form. Repeat steps c through e for the routines database. Select the Save button to complete creating the namespace. Select Close to close the log. This completes the system configuration.
https://docs.intersystems.com/latest/csp/docbook/DocBook.UI.Page.cls?KEY=EESB_configure_system
CC-MAIN-2022-33
refinedweb
380
56.66
#include <Coord.h> #include <Coord.h> List of all members. Class for a double-tuple storing a position / two-dimensional vector. Some comparison and basic arithmetic operators on Coord structures are implemented. 0 [inline] Initializes coordinates. Returns the distance to Coord a Adds coordinate vector b to a. Subtracts coordinate vector b from a. Assigns a this. Returns distance^2 to Coord a (omits square root). Returns the squared distance on a torus to Coord a (omits square root). [friend] Multiplies a coordinate vector by a real number. Tests whether two coordinate vectors are not equal. Negation of the operator==. Adds two coordinate vectors. Subtracts two coordinate vectors. Divides a coordinate vector by a real number. Tests whether two coordinate vectors are equal. Because coordinates are of type double, this is done through the FWMath::close function.
http://mobility-fw.sourceforge.net/api/classCoord.html
CC-MAIN-2018-05
refinedweb
137
55.61
Inline::SLang::Config - How to configure Inline::SLang The Inline documentation describes how you can configure the Inline-specific options. Please review that document if you are unfamiliar with the way Inline works (in particular the section on "Configuration Options"). This document describes the options that are available to configure the S-Lang interface. This option - which takes either a string or a reference to an array of strings - specifies the S-Lang namespaces which are searched for functions to bind to Perl. The accepted values are: Binds functions in the Global namespace only. This is the default value. Binds functions in all the namespaces that are defined at the time of compilation. You can not use the namespace renaming feature discussed below with this option (so "All=foo" does not work). If an array reference is given then it should contain the names of the namespaces to search for S-Lang functions. In most case you will want to ensure that "Global" is contained in this list. The default behaviour is for functions in the "Global" namespace to be bound to the Perl main package (so they can be used without any package specifier) while functions in other namespaces are placed into the Perl package whose name equals that of the S-Lang namespace (see below for examples). This can be changed by supplying strings matching "foo=bar", which says to bind S-Lang functions from the foo namespace into the Perl package bar. Therefore, BIND_NS => [ "Global=foo", "foo" ], will bind all S-Lang functions from the Global and foo namespaces into Perl's foo package. Note that no checks are made for over-writing functions when they are bound to Perl. Also, if you are using this functionality you should probably be using the 2-argument form of S-Lang's import and evalfile commands instead. The following examples are also available in the examples/ sub-directory of the source code (this directory is not installed by make install). use Inline 'SLang' => Config => BIND_NS => ["foo"]; use Inline 'SLang' => <<'EOS1'; define fn_in_global(x) { "in global"; } implements( "foo" ); define fn_in_foo(x) { "in foo"; } EOS1 # this works printf "I am %s\n", foo::fn_in_foo("dummyval"); # this does not work since fn_in_global is in the # Global namespace which was not given to the # BIND_NS option printf "I am %s\n", fn_in_global("dummyval"); use Inline 'SLang' => Config => BIND_NS => [ "Global", "foo" ];"); use Inline 'SLang' => Config => BIND_NS => [ "Global", "foo=bar" ]; use Inline 'SLang' => <<'EOS1'; define fn_in_global(x) { "in global"; } implements( "foo" ); define fn_in_foo(x) { "in foo"; } EOS1 # this works printf "I am %s\n", bar::fn_in_foo("dummyval"); # as does this printf "I am %s\n", fn_in_global("dummyval"); use Inline 'SLang' => Config => BIND_NS => "All";"); This option is used to give a list of S-Lang intrinsic functions which are to be bound to Perl. The default value is [], i.e. no functions. Note that there are no checks on whether it makes sense to bind the specified function, or whether it conflicts with an existing Perl definition. use Inline 'SLang' => Config => BIND_SLFUNCS => ["typeof"]; use Inline 'SLang' => "define get_typeof(x) { typeof(x); }"; # both lines print # The S-Lang type of 'foo' is String_Type printf "The S-Lang type of 'foo' is %s\n", get_typeof("foo"); printf "The S-Lang type of 'foo' is %s\n", typeof("foo"); use Inline 'SLang' => Config => BIND_NS => "Global=foo", BIND_SLFUNCS => ["typeof"]; use Inline 'SLang' => " "; # This also prints # The S-Lang type of 'foo' is String_Type printf "The S-Lang type of 'foo' is %s\n", foo::typeof("foo"); The reason for giving " " as the S-Lang code in the last example is to stop Inline from complaining about being sent no code. The SETUP option can be set to one of: This is the default value. When set, the S-Lang interpreter is set up in a similar manner to that of the slsh interpreter from the S-Lang distribution (v1.4.9): get_slang_load_path()and set_slang_load_path()routines from the S-Lang Run-Time Library - is set to the contents of the environment variable SLSH_PATH. The SLSH_CONF_DIR environment variable. The SLSH_LIB_DIR environment variable. The directories: /usr/local/etc:/usr/local/slsh:/etc:/etc/slsh. No additional set up is made to the interpreter. At present the code used to support the slsh option will only work for UNIX-style file systems/set ups. The Inline::SLang module contains a number of utility routines that are - by default - only available using the fully-qualified package name. If you would rather use sl_array(...) than Inline::SLang::sl_array(...) then you can use the EXPORT option. This resembles the standard Perl export mechanism but is not as feature rich. The available functions are (see Inline::SLang for a detailed description): A wrapper around the constructor for the Array_Type class. Useful if you want to ensure that a Perl array reference is converted to the correct array type and size in S-Lang. Used to read or write the flag that controls how S-Lang arrays are converted to Perl. See Inline::SLang::Array. Call S-Lang's eval() routine and, on exit, convert the stack to Perl. Determine if the module was compiled with support for PDL. Sets up the interpreter in a similar manner to that used by slsh. This routine should be rarely needed. Returns the number of times the sl_setup_as_slsh() routine has been called. A wrapper around S-Lang's typeof() routine. It is more efficient than using S-Lang's typeof routine. Returns the version of the S-Lang library used to compile the module. <datatype name>() A function is created for each S-Lang datatype known about when the Perl code is executed (so this includes typedef-fed structures and any application-specific datatypes from imported modules). The name of the function matches the name of the S-Lang datatype and returns a Perl DataType_Type object whose value matches the function name - so Integer_Type() is just the same as calling DataType_Type->new("Integer_Type"); Note that - as of version 0.12 of Inline::SLang - you can also use the name of synonyms as well as the base classes. For instance, Int32_Type() will return the datatype that corresponds to the S-Lang Int32_Type type. The EXPORT option accepts a reference to an array that lists the names of the functions to export, e.g. use Inline 'SLang' => Config => EXPORT => [ "sl_array" ]; If you want to export the datatype functions then you can either list the names of the required functions in the EXPORT array or give the value !types which includes them all. Note that we do not accept the full syntax of the Exporter module: the EXPORT option should be thought of as a toy car next to the RV that is the Exporter module. The info option of Inline can be useful to see what has (and has not) been bound to Perl. As an example try the following (available as examples/info.pl in the source code of the module): perl -MInline=info <<FOO use Inline SLang; # let's not actually do anything __END__ __SLang__ typedef struct { foo, bar } FooBarStruct_Type; variable foobar = "a string"; define foo() { return foobar; } define bar(x) { foobar = x; } FOO The relevant part of the output (as of version 0.30) is: Configuration details --------------------- Version of S-Lang: 1.4.9 Perl module version is 0.30 and supports PDL The following S-Lang types are recognised: Int32_Type UInteger_Type _IntegerP_Type FooBarStruct_Type[Struct_Type] Int_Type Struct_Type ULong_Type FD_Type Long_Type Float_Type Array_Type UInt32_Type File_Type UInt_Type UChar_Type UShort_Type Double_Type Float64_Type Float32_Type Int16_Type Null_Type Integer_Type BString_Type Char_Type Undefined_Type Short_Type Any_Type Ref_Type Complex_Type Assoc_Type String_Type UInt16_Type DataType_Type The following S-Lang namespaces have been bound to Perl: 2 functions from namespace Global are bound to package main bar() foo() Any S-Lang intrinsic functions bound to Perl are indicated using the format S-Lang name() -> Perl name(), even when the Perl and S-Lang names match (this may change). If you have a typedef statement defining a "named" structure then the name of the structure will be followed by [Struct_Type], as with the FooBarStruct_Type variable type in the example above. The format of this section is liable to change; any suggestions are very welcome.
http://search.cpan.org/dist/Inline-SLang/SLang/Config.pod
CC-MAIN-2016-40
refinedweb
1,360
58.42
Read and write stem multistream audio files Project description stempeg = stems + ffmpeg python package to read and write STEM files. Technically, STEMs are MP4 files with multiple audio streams and additional metatdata. stempeg is a python interface for ffmpeg particularly made to read and write multi stream MP4 audio files. Installation 1. Installation of ffmpeg Library stempeg relies on ffmpeg (tested: 4.1, 4.0.2, 3.4 and 2.8.6) to decode the stems file format. For encoding ffmpeg >= 3.2 is suggested. The Installation if ffmpeg differ among operating systems. If you use Anaconda you can install ffmpeg on Windows/Mac/Linux using the following command: conda install -c conda-forge ffmpeg Decoding is supported with any recent build of ffmpeg. For Encoding it is recommended to use the Fraunhofer AAC encoder ( libfdk_aac) which is not included in the default ffmpeg builds. Note that the conda version currently does not include fdk-aac. If libfdk_aac is not installed stempeg will use the default aac codec which will result in slightly inferior audio quality. You can install ffmpeg with libfdk-aac support manually as following: - Mac: use homebrew: brew install ffmpeg --with-fdk-aac - Ubuntu Linux: See installation script here. - Using Docker (Mac, Windows, Linux): docker pull jrottenberg/ffmpeg 2. Installation of the stempeg package Installation via PyPI using pip pip install stempeg Usage There are very few freely available stem files. We included a small test track from the Canadian rock-band The Easton Ellises. The band released them under Creative Commons license CC BY-NC-SA 3.0. To use the included stem example you can use stempeg.example_stem_path(). Reading stems import stempeg S, rate = stempeg.read_stems(stempeg.example_stem_path()) S is the stem tensor that includes the time domain signals scaled to [-1..1]. The shape is (stems, samples, channels). Reading individual stem ids you can read individual substreams of the stem file by passing the corresponding stem id (starting from 0): S, rate = stempeg.read_stems(stempeg.example_stem_path(), stem_id=[0, 1]) Read excerpts (set seek position) to read an excerpt from the stem instead of the full file, you can provide start ( start) and duration ( duration) in seconds to read_stems: S, _ = stempeg.read_stems(stempeg.example_stem_path(), start=1, duration=1.5) # read from second 1.0 to second 2.5 Improve performance if read_stems is called repeatedly, it always does two system calls, one for getting the file info and one for the actual reading. To speed this up you could provide the Info object to read_stems if the number of streams, the number of channels and the samplerate is identical. file_path = stempeg.example_stem_path() info = stempeg.Info(file_path) S, _ = stempeg.read_stems(file_path, info=info) Writing stems Writing stem files from a numpy tensor stempeg.write_stems(S, "output.stem.mp4", rate=44100) :warning: Warning: Muxing stems using ffmpeg might lead to non-conform stem files. Please use MP4Box, if you need a reliable result. Use the command line tools stempeg provides a convenient cli tool to convert a stem to multiple wavfiles. The -s switch sets the start, the -t switch sets the duration. stem2wav The Easton Ellises - Falcon 69.stem.mp4 -s 1.0 -t 2.5 Project details Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/stempeg/
CC-MAIN-2020-24
refinedweb
555
59.09
PERCEPTUAL COMPUTING: Augmenting the FPS Experience Por Lee Bamber, atualizado Downloads PERCEPTUAL COMPUTING: Augmenting the FPS Experience [PDF 977KB] 1. Introduction For more than a decade, we've enjoyed the evolution of the First Person Shooter (FPS) Genre, looking at games through the eyes of the protagonist and experiencing that world first hand. To exercise our control, we've been forced to communicate with our avatar through keyboard, mouse, and controllers to make a connection with that world. Thanks to Perceptual Computing, we now have additional modes of communication that bring interaction with that world much closer. This article not only covers the theory of perceptual controls in FPS games, but demonstrates actual code that allows the player to peek around corners by leaning left or right. We will also look at using voice control to select options in the game and even converse with in-game characters. A familiarity with the Intel® Perceptual Computing SDK is recommended but not essential, and although the code is written in Dark Basic Professional (DBP), the principals are also suited to C++, C#, and Unity*. The majority of this article will cover the theory and practise of augmenting the First Person experience and is applicable not only to games but simulations, tours, and training software. In this article, we’ll be looking at augmenting the FPS game genre, a popular mainstay of modern gaming and one that has little to no Perceptual Computing traction. This situation is partly due to the rigid interface expectations required from such games and partly to the relative newness of Perceptual Computing as an input medium. As you read this article, you will be able to see that with a little work, any FPS can be transformed into something so much more. In a simple firefight or a horror-thriller, you don't want to be looking down at your keyboard to find the correct key—you want to stay immersed in the action. Figuring out the combination of keys to activate shields, recharge health, duck behind a sandbag, and reload within a heartbeat is the domain of the veteran FPS player, but these days games belong to the whole world not just the elite. Only Perceptual Computing has the power to provide this level of control without requiring extensive practice or lightning fast hand/eye coordination. Figure 1. When reaction times are a factor, looking down at the keyboard is not an option We’ve had microphones for years, but it has only been recently that voice recognition has reached a point where arbitrary conversations can be created between the player and the computer. It’s not perfect, but it’s sufficiently accurate to begin a realistic conversation within the context of the game world. Figure 2. Wouldn’t it be great if you could just talk to characters with your own voice? You’ve probably seen a few games now that use non-linear conversation engines to create a sense of dialog using multiple choices, or a weapon that has three or four modes of fire. Both these features can be augmented with voice control to create a much deeper sense of emersion and create a more humanistic interface with the game. This article will look at detecting what the human player is doing and saying while playing a First Person experience, and converting that into something that makes sense in the gaming world. 2. Why Is This Important As one of the youngest and now one of the largest media industries on the planet, the potential for advancement in game technology is incredible, and bridging the gap between user and computer is one of the most exciting. One step in this direction is a more believable immersive experience, and one that relies on our natural modes of interaction, instead of the artificial ones created for us. With a camera that can sense what we are doing and a microphone that can pick up what we say, you have almost all the ingredients to bridge this gap entirely. It only remains for developers to take up the baton and see how far they can go. For developers who want to push the envelope and innovate around emerging technologies, this subject is vitally important to the future of the First Person experience. There is only so much a physical controller can do, and for as long as we depend on it for all our game controls we will be confined to its limitations. For example, a controller cannot detect where we are looking in the game, it has to be fed in, which means more controls for the player. It cannot detect the intention of the player; it has to wait until a sequence of button presses has been correctly entered before the game can proceed. Now imagine a solution that eliminates this middle-man of the gaming world, and ask yourself how important it is for the future of gaming. Figure 3. Creative* Interactive Gesture Camera; color, depth and microphone – bridging the reality gap Imagine the future of FPS gaming. Imagine all your in-game conversations being conducted by talking to the characters instead of selecting buttons on the screen. Imagine your entire array of in-game player controls commanded via a small vocabulary of commonly spoken words. The importance of these methods cannot be understated, and they will surely form the basis of most, if not all, FPS game interfaces in the years to come. 3. Detect Player Leaning You have probably played a few FPS games and are familiar with the Q and E keys to lean left and right to peek around corners. You might also have experienced a similar implementation where you can click the right mouse button to zoom your weapon around a corner or above an obstacle. Both game actions require additional controls from the player and add to the list of things to learn before the game starts to feel natural. With a perceptual computing camera installed, you can detect where the head and shoulders of your human player lie in relation to the center of the screen. By leaning left and right in the real world, you can mimic this motion in the virtual game world. No additional buttons or controls are required, just lean over to peek around a corner, or sidestep a rocket, or dodge a blow from an attacker, or simply view an object from another angle. Figure 4. Press E or lean your body to the right. Which one works for you? In practice, however, you will find this solution has a serious issue., You will notice your gaming experience disrupted by a constantly moving (even jittering) perspective as the human player naturally shifts position as the game is played. It can be disruptive to some elements of the game such as cut-scenes and fine-grain controls such as using the crosshair to select small objects in the game. There are two solutions to this: the first is to create a series of regions that signal a shift to a more extreme lean angle, and the second is to disable this feature altogether in certain game modes as mentioned above. Figure 5. Dividing a screen into horizontal regions allows better game leaning control By having these regions defined, the majority of the gaming is conducted in the center zone, and only when the player makes extreme leaning motions does the augmentation kick in and shift the game perspective accordingly. Implementing this technique is very simple and requires just a few commands. You can use the official Intel Perceptual Computing SDK or you can create your own commands from the raw depth data. Below is the initialization code for a module created for the DBP language and reduces the actual coding to just a few lines. rem Init PC perceptualmode=pc init() pc update normalx#=pc get body mass x() normaly#=pc get body mass y() The whole technique can be coded with just three commands. The first initializes the perceptual computing camera and returns whether the camera is present and working. The second command asks the camera to take a snapshot and do some common background calculations on the depth data. The last two lines grab something called a Body Mass Coordinate, which is the average coordinate of any foreground object in the field of the depth camera. For more information on the Body Mass Coordinate technique, read the article on Depth Data Techniques (). Of course detecting the horizontal zones requires a few more simple lines of code, returning an integer value that denotes the mode and then choosing an appropriate angle and shift vector that can be applied to the player camera. rem determine lean mode do leanmode=0 normalx#=pc get body mass x()/screen width() if normalx#<0.125 leanmode=-2 else if normalx#<0.25 leanmode=-1 else if normalx#>0.875 leanmode=2 else if normalx#>0.75 leanmode=1 endif endif endif endif leanangle#=0.0 leanshiftx#=leanmode*5.0 select leanmode case -2 : leanangle#=-7.0 : endcase case -1 : leanangle#=-3.0 : endcase case 1 : leanangle#= 3.0 : endcase case 2 : leanangle#= 7.0 : endcase endselect pc update loop Applying these lean vectors to the player camera is simplicity itself, and disabling it when the game is in certain modes will ensure you get the best of both worlds. Coding this in C++ or Unity simply requires a good head tracking system to achieve the same effect. To get access to this DBP module, please contact the author via twitter at. The buzz you get from actually peering around a corner is very cool, and is similar to virtual/augmented reality, but without the dizziness! 4. Detect Player Conversations Earlier versions of the Intel® Perceptual Computing SDK had some issues with accurate voice detection, and even when it worked it only understood a U.S. accent. The latest SDK however is superb and can deal with multiple language accents and detect British vocals very well. Running the sample code in the SDK and parroting sentence after sentence proves just how uncannily accurate it is now, and you find yourself grinning at the spectacle. If you’re a developer old enough to remember the ‘conversation engines’ of the 8-bit days, you will recall the experimental applications that involved the user typing anything they wanted, and the engine picking out specific trigger words and using those to carry on the conversation. It could get very realistic sometimes, but often ended with the fall-back of ‘and how do you feel about that?’ Figure 6. A simple conversation engine from the adventure game “Relics of Deldroneye” Roll the clock forward about 30 years and those early experiments could actually turn out to be something quite valuable for a whole series of new innovations with Perceptual Computing. Thanks to the SDK, you can listen to the player and convert everything said into a string of text. Naturally, it does not get it right every time, but neither do humans (ever play Chinese whispers?). Once you have a string of text, you can have a lot of fun with figuring out what the player meant, and if it makes no sense, you can simply get your in-game character to repeat the question. A simple example would be a shopkeeper in an FPS game, opening with the sentence, “what would you like sir?” The Intel® Perceptual Computing SDK also includes a text-to-speech engine so you can even get your characters to use the spoken word, much more preferred in modern games than the ‘text-on-screen’ method. Normally in an FPS game, you would either just press a key to continue the story, or have a small multi-choice menu of several responses. Let’s assume the choices are “nothing,” “give me a health kit,” or “I want some ammo.” In the traditional interface you would select a button representing the choice you wanted through some sort of user interface mechanism. Using voice detection, you could parse the strings spoken by the player and look for any words that would indicate which of the three responses was used. It does not have to be the exact word or sentence as this would be almost impossible to expect and would just lead to frustration in the game. Instead, you would look for keywords in the sentence that indicate which of the three is most likely. NOTHING = “nothing, nout, don’t anything, bye, goodbye, see ya” HEALTH = “health, kit, medical, heal, energy” AMMO = “ammo, weapon, gun, bullets, charge” Of course, if the transaction was quite important in the game, you would ensure the choice made was correct with a second question to confirm it, such as “I have some brand new ammo, direct from the factory, will that do?” The answer of YES and NO can be detected with 100% certainty, which will allow the game to proceed as the player intended. Of course this is the most complex form of voice detection and would require extensive testing and wide vocabulary of detections to make it work naturally. The payoff is a gaming experience beyond anything currently enjoyed, allowing the player to engage directly with characters in the game. 5. Detect Player Commands An easier form of voice control is the single command method, which gives the player advance knowledge of a specific list of words they can use to control the game. The Intel® Perceptual Computing SDK has two voice recognition modes “dictation” and “command and control.” The former would be used in the above complex system and the latter for the technique below. A game has many controls above and beyond simply moving and looking around, and depending on the type of game, can have nested control options dependent on the context you are in. You might select a weapon with a single key, but that weapon might have three different firing modes. Traditionally this would involve multiple key presses given the shortage of quick-access keys during high octane FPS action. Replace or supplement this with a voice command system, and you gain the ability to select the weapon and firing mode with a single word. Figure 7. Just say the word “reload”, and say goodbye to a keyboard full of controls The “command and control” mode allows very quick response to short words and sentences, but requires that the names you speak and the names detected are identical. Also you may find that certain words when spoken quickly will be detected as a slight variation on the word you had intended. A good trick is to add those variations to the database of detectable words so that a misinterpreted word still yields the action you wanted in the game. To this end it is recommended that you limit the database to as few words as that part of the game requires. For example, if you have not collected the “torch” in the game, you do not need to add “use torch” to the list of voice controls until it has been collected. It is also recommended that you remove words that are too similar to each other so that the wrong action is not triggered at crucial moments in the game play. For example, you don’t want to set off a grenade when you meant to fire off a silent grappling hook over a wall to escape an enemy. If the action you want to perform is not too dependent on quick reaction times, you can revert to the “dictation” mode and do more sophisticated controls such as the voice command “reload with armor piercing.” The parser would detect “reload,” “armor,” and “piercing,” The first word would trigger a reload, and the remaining ones would indicate a weapon firing mode change and trigger that. When playing the game, using voice to control your status will start to feel like you have a helper sitting on your shoulder, making your progress through the game much more intuitive. Obviously there are some controls you want to keep on a trigger finger such as firing, moving, looking around, ducking, and other actions that require split-second reactions. The vast majority however can be handed over to the voice control system, and the more controls you have, the more this new methods wins over the old keyboard approach. 6. Tricks and Tips Do’s - Using awareness of the player’s real-world position and motion to control elements within the game will create an immediate sense of connection. Deciding when to demonstrate that connection will be the key to a great integration of Perceptual Computing. - Use “dictation” for conversation engines and “command and control” for instant response voice commands. They can be mixed, providing reaction time does not impede game play. - If you are designing your game from scratch, consider developing a control system around the ability to sense real player position and voice commands. For example a spell casting game would benefit in many ways from Perceptual Computing as the primary input method. - When you are using real world player detection, ensure you specify a depth image stream of 60 frames per second to give your game the fastest possible performance. Don’ts - Do not feed raw head tracking coordinates directly to the player camera, as this will create uncontrollable jittering and ruin the smooth rendering of any game. - Do not use voice control for game actions that require instantaneous responses. As accurate as voice control is, there is a noticeable delay between speaking the word and getting a response from the voice function. - Do not detect whole sentences in one string comparison. Parse the sentence into individual words and run string comparisons on each one against a larger database of word variations of similar meaning. 7. Final Thoughts A veteran of the FPS gaming experience may well scoff at the concept of voice-activated weapons and real-world acrobatics to dodge rockets. The culture of modern gaming has created a total dependence on the mouse, keyboard, and controller as lifelines into these gaming worlds. Naturally, offering an alternative would be viewed with incredulity until the technology fully saturates into mainstream gaming. The same can be said of virtual reality technology, which for 20 years attempted to gain mainstream acceptance without success. The critical difference today is that this technology is now fast enough and accurate enough for games. Speech detection 10 years ago was laughable and motion detection was a novelty, and no game developer would touch them with a barge pole. Thanks to the Intel Perceptual Computing SDK, we now have a practical technology to exploit and one that’s both accessible to everyone and supported by peripherals available at retail. An opportunity exists for a few developers to really pioneer in this area, creating middleware and finished product that push the established model of what an FPS game actually is. It is said that among all the fields of computing, game technology is the one field most likely to push all aspects of the computing experience. No other software pushes the limits of the hardware as hard as games, pushing logic and graphics processing to the maximum (and often beyond) in an attempt to create a simulation more realistic and engaging than the year before. It’s fair to suppose that this notion extends to the very devices that control those games, and it’s realistic to predict that we’ll see many innovations in this area in years to come. The great news is that we already have one of those innovations right here, right now, and only requires us to show the world what amazing things it can do..
https://software.intel.com/pt-br/articles/perceptual-computing-augmenting-the-fps-experience
CC-MAIN-2017-39
refinedweb
3,286
55.27
Next Chapter: Recursion and Recursive Functions Functions Syntax Functions are a construct to structure programs. They are known in most programming languages, sometimes also called subroutines or procedures. Functions are used to utilize code in more than one place in a program. The only way without functions to reuse code consists in copying the code. a return statement. It can be anywhere in the function body. This statement ends the execution of the function call and "returns" the result, i.e. the value of the expression following the return keyword, to the caller. If there is no return statement in the function code, the function ends, when the control flow reaches the end of the function body. Example: >>> def add(x, y): ... """Return x plus y""" ... return x + y ... >>>In the following interactive session, the function we previously defined will be called: >>> add(4,5) 9 >>> add(8,3) 11 >>> Example of a Function with Optional Parameters >>> def add(x, y=5): ... """Return x plus y, optional""" ... return x + y ... >>>Calls to this function could look like this: >>> add(4) 9 >>> add(8,3) 11 >>> Docstring The first statement in the body of a function is usually a string, which can be accessed with function_name.__doc__ This statement is called Docstring. Example: >>> execfile("function1.py") >>> add.__doc__ 'Returns x plus y' >>> add2.__doc__ 'Returns x plus y, optional' >>> Keyword Parameters Using keyword parameters is an alternative way to make function calls. The definition of the function doesn't change. An example: def sumsub(a, b, c=0, d=0): return a - b + c - dKeyword parameters can only be those, which are not used as positional arguments. >>> execfile("funktion1.py") >>> sumsub(12,4) 8 >>> sumsub(12,4,27,23) 12 >>> sumsub(12,4,d=27,c=23) 4 arbitrary(x, y, *more): print "x=", x, ", y=", y print "arbitrary: ", morex and y are regular positional parameters in the previous function. *more is a tuple reference. Example: >>> execfile("funktion1.py") >>> arbitrary(3,4) x= 3 , x= 4 arbitrary: () >>> arbitrary(3,4, "Hello World", 3 ,4) x= 3 , x= 4 arbitrary: ('Hello World', 3, 4) Next Chapter: Recursion and Recursive Functions
http://python-course.eu/functions.php
CC-MAIN-2017-09
refinedweb
358
58.08
Doing hibernate connection data sqlserver 2005, when a mistake. The first is the pop-up Exception in thread "main" org.hibernate.exception.SQLGrammarException: Cannot open connection Caused by: com.microsoft.sqlserver.jdbc.SQLServerExceptio ... [/ Color] [color = red] hey now replaced with sql server database, then when I really met a lot of questions to share with you the next show Error message is as follows: User 'sa' Login failed. The user with trusted SQL Server connection is n ... A strange question, the project on the interaction with the database run locally not occur, when transplanted into the public network when a bunch of problems, this does not like to use the MS database, but found a problem under solution. LOOK " Unab Website not open, suggesting a 404 error, according to the previous investigation of 404 errors were not found set errors, the latter finding is not due SQL2005 SQL Server authentication method to log in, displays "Login failed for user sa, 18456 err After restarting my server, sql server agent can not be started, OS are the hook on the front of the. I ordered the "Start / continue", it says "Login failed because service did not start" - "error 1069 - (due to a logon fail Website not open, suggesting that the 404 error, according to previous 404 troubleshoot, set errors are not found, was discovered behind is not as SQL2005 SQL Server authentication method to log in, displays "Login failed for user sa, 18456 error. After restarting my server, sql server agent can not start, OS is on the hook of the front. I point the "Start / continue" prompt "login failed because service did not start" - "error 1069 - (due to a logon failure can not st Can not open user default database, login failed, which is the SQL Server users are familiar with one of the issues. Using Enterprise Manager, Query Analyzer, various tools and application software, as long as related to connecting to SQL Server data Connected to one, for this problem, in fact, think is really very simple, but it did cost me a lot of time to find information. In fact, as long as the web.config inside information to connect to the database to change to change it. For example, my origin Solving steps: This problem generally is due to SQL Server is not integrated Windows authentication result, the solution is: 1 Open SQL Server Enterprise Manager. 2 Select the server name on the right select "Edit SQL Server Registration Propert ... This error is not in the window nutch direct shipping, have set the path environment variable to point to cygwin (eg: C: \ cygwin \ bin), and then restart the eclipse so that you can run eclise ok Parameter: Process parameters: urls-dir no-depth 3-to This will be the production of the reader to start from scratch with a AJAX Login DEMO, program features, business is very simple, so I do not need with you to explain things in this regard, we look at how to use AJAX to achieve the registry, the pur ... This example retrieves the login name of the user that is running the application. The example requires a login configuration file that specifies the login modules to execute when using a particular login-app name. This configuration file specifies t ... (Provider: Shared Memory Provider, error: 0 - the other end of the pipeline without any process.) User 'sa' Login failed. The user with trusted SQL Server connection is not associated. Description: During the execution of the current Web requ ... 'User' sa 'Login failed. The user with trusted SQL Server connection is not associated '. 1: Open SQL Server Manager Manager! On the left to find 'security' - login - sa, double-click sa Check the status of login is to "start 'User' sa 'Login failed. The user with trusted SQL Server connection is not associated '. 1: Open SQL Server Manager Manager! On the left to find 'security' - login - sa, double-click sa Check the status of login is to "start / ** * Login.js Power by YUI-EXT and JSON. * * @ Author seraph * @ Email seraph115@gmail.com * / var Login = ( author: "Seraph", version: "0.1.0" ); var loginPanel; Ext.QuickTips.init (); E ... Login with the OpenId more fashionable now, last year friendfeed (facebook) new out of python Tornado Web Server and framework (to turn) on the popular OpenId provider (Google, twitter, etc.) have built-in support, and the tornado is very clean and concis Third, the realization of landing function 3.1 The User entity class User Define the user name and password. Generally add [Bindable] tag, marked as bound. package vo { import com.adobe.cairngorm.vo.IValueObject; [Bindable] public class User implemen Complete the following configuration changes must not forget the new start after the database Some errors related to: Can not use the special principal 'Sa'. (Microsoft SQL Server, Error: 15405) Successfully establish a connection with the; char JSP-based database using user login process to complete a security problem with Statement: SQL injection vulnerability select * from person where name = "darkness" and password = "wind" or "1" = "1" Password: wind 1. <br /> Motivated people know that used CAS CAS-Server-side deployment alone, as a pure certification center. Each time a user logs in, you need to enter the CAS-Server login page fill in the user name and password, but if there are multiple sub-a Mobile client code: LoginForm: package com; import java.io.DataInputStream; import java.io.IOException; import java.io.OutputStream; import javax.microedition.io.Connector; import javax.microedition.io.HttpConnection; import javax.microedition.lcdui. / / Case Study: User registration and login system / / User registration / login, user registration information will be written to the file, fill out the registration information matches / / When the log, if the user already exists, indicating a succ Solution ' User 'sa' login failures. The user and the trusted SQL Server connection is not associated One problem, forget your Microsoft SQL Server 2005 login password for the sa Solution: use windows authentication to log in, then the 'se [Code = "java"] com.microsoft.sqlserver.jdbc.SQLServerException: user 'sa' login failures. The user and the trusted SQL Server connection is not associated. at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError (Unknow JSP project to connect the database to do today, the result error, error reason: 'user' sa 'login failures. The user and the trusted SQL Server connection is not associated 'today on the online search for a long time or get it working This morning chrome Browser Sync fails when Google account login "prompt login failed." Many bookmarks can not be collected simultaneously over a very depressed. From the Internet to find a solution, in fact, the synchronization server, the To the package: (version very different) struts-core1.3.5.jar commons-beanutils-1.7.0.jar commons-digester-1.8.jar commons-logging-api-1.1.jar commons-chain-1.1.jar 1. Add the servlet in web.xml <servlet> <servlet-name>action</servlet-name This fact, with the fifth international articles and first article to achieve the effect, just as login credentials, but the international treatment only, a few more international profile Here I have to say, it may be the first article and after reading t Online registration usually we have experienced, such as user registration is successful, then hit the back button, to return to the form page to submit the form again, if untreated repeat the request to submit the details will be re-submitted successfull Here do not know, if you wish, you can go to my blog to see the sina Plan tasks No task name of the task end date no later than the standard workload of the task completion status 1 to establish a database and corresponding table 2009/04/28 2009/04/2 ... Ajax is a popular Web development technologies, BJAF Web framework in the original framework of Ajax had a strong package, the development of Ajax wanted to develop a common standard of the traditional controller as simple as that. Ajax Framework is struc This article is reproduced from the I CSDN blog: First of all, SPRING and HIBERNATE need to prepare for the JAR corresponding package in the ECLIPSE project to create a new WEB, SPRING wil 1.ExtLoginAction package com.action; import java.util.Map; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import com.model.Tuser; import com.util. This article made reference to the royzhou1985 Bo-wen, would like to thank him for his selfless sharing. 1 What is the aop? I understand it, aop Let us concentrate on doing what we are most concerned about functionality, but to many other classes nee ... 1.LDecode Recently modified system, need to do CAS's Proxy, surf the Internet for a long time, and found some articles about the principles, but almost no articles about the configuration, there is about the conf linux extract the tar.gz file commands: tar zxvf tomcat6.0.tar.gz linux modify the file name: mv tomcat5.0 tomcat6.0 View a process: ps-ef | grep tomcat Copying files: cp filename target path to draw the machine: ether-wake target NIC address to log ... eclipse3.2, myeclipse5.0, Jboss4.0.3, sql server2000 sp3 Principle of In the java enterprise applications, ejb powerful ejb configuration with the complex and difficult to learn as well known. But in the past and what we do? Just bite the bullet and came Deployment descriptor is actually an XML file that contains a lot of description of servlet / JSP applications in all aspects of the elements, such as the servlet registration , Servlet mapping as well as the listener registration. The deployment descript First ExtJS program, spent an entire night, only then tune-pass procedure has proved too much, or their own vegetables, before the three-tier code originally written there are still many mistakes, kingcat correct to say that programmers should be responsi IIS The meaning of status code Summary When a user tries to HTTP or File Transfer Protocol (FTP) Access to a computer that is running Internet Information Services (IIS) The content server ,IIS That the request returns a status code number . This status c Add a button click event, the implementation of the following methods 1. Function login (item) ( 2. 3. If (validatorForm ()) ( 4. / / Login when the login button set to disabled, to prevent duplicate submission 5. This.disabled = true; 6. 7. / / The ... js code struts configuration file CodeWeblog.com 版权所有 黔ICP备15002463号-1 processed in 0.027 (s). 6 q(s)
http://www.codeweblog.com/stag/login-failed-for-user-getpwd/
CC-MAIN-2015-22
refinedweb
1,755
52.49
webdriver-python This is a Docker container combined with a few utility functions to simplify writing Selenium tests in Python. It uses Firefox as the driver. Dockerfile. Run example code The example test querys the keyword "test" at google.com and print the first search result to stdout: $ docker run weihan/webdriver-python To export screenshots to the ./shots folder on the host computer: $ docker run -v $PWD/shots:/sreenshots aerofs/webdriver-python Write tests To write new tests, you can either bind mount your python files to the container or create a new Docker image and copy files into the image. The example code is located at /main.py in the container. You may overwrite this file or place your files at different locations. For the latter, run the container as follows: $ docker run weihan/webdriver-python python -u /path/to/your/python/code At the beginning of your code, call webdriver_util.init() to set up the environment and retrieve a few utility objects. Screenshots will be saved at the container's "/screenshots" folder. You may use bind mount to export them to the host. from webdriver_util import init driver, wait, selector = init() driver is the Selenium WebDriver object wait is a convenience wrapper around WebDriverWait. Every call to wait.until*() methods produce useful console output and a screenshot at the end of the wait. You can also use wait.shoot() at any time to save a screenshot. selector provides shortcuts to WebDriver.find_element_by_css_selector(). It restricts element selection to using CSS selectors only. See example code for the usage of these objects. Customize Use the RESOLUTION environmental variable to customize screen size and depth. The default is "1024x768x24". For example: docker run -e RESOLUTION=1920x1600x24 weihan/webdriver-python Build from source Check out this GitHub repository and run this command in the repository's root folder: $ docker build -t aerofs/webdriver-python .
https://hub.docker.com/r/aerofs/webdriver-python/
CC-MAIN-2018-13
refinedweb
313
58.79
Template meta-programming Template meta-programming can be a very interesting, complicated topic (anything “meta” is very interesting, after all). We’ll keep it very simple in this class. The idea behind template meta-programming is that we want to use a special language on top of C++ that generates C++ code. This “template meta-language” is itself a full programming language, but we’ll just use the simplest pieces. Our use of template meta-programming will be limited to generating classes and functions that work on any type of object. Important note: Template classes and functions must have their full implementations in the header file, not an external .cpp file. This is because template classes and functions cannot be compiled in a generic way, so we cannot produce a .o file that has compiled but generic functions/methods. Generic linked lists Think back to our linked lists. Let’s say we have a linked list class: class LinkedList { private: struct node { double value; node *pnext; }; node *head; public: LinkedList(); void insert_front(double value); void push_back(double value); int length(); void reverse(); double nth(int n); void print(); }; // etc... Assuming that LinkedList class was fully implemented, we would be able to do things like this: int main() { LinkedList mylist; mylist.push_back(4.3); mylist.insert_front(3.2); mylist.print(); // etc... } But this is quite unfortunate! That linked list class only stores double values. There are more things in heaven and earth than can be represented as double values. (Well, not really, since representations don’t matter, theoretically. But in practice, they do.) We want to create a single linked list class that can store any (single) type of value. We will not have the option to create a linked list that can store varying types of values (e.g. a linked list with strings, doubles, ints, and so on all in the same list will not be possible). But, it would be nice to write one linked list class that can store strings, or in another instance integers, or whatever. Template meta-programming allows us to do this. Creating a templated class All you have to change about the linked list class above in order to support making a linked list with a (single) arbitrary type is the following: template <typename T> // T can be anything, e.g. foo class LinkedList { private: struct node { T value; // not double, T! node *pnext; }; node *head; public: LinkedList(); void insert_front(T value); // T! void push_back(T value); // T! int length(); void reverse(); T nth(int n); // T! void print(); }; template<typename T> void LinkedList<T>::insert_front(T value) { node *n = new node; n->value = value; n->pnext = head; head = n; } // etc... Now, to use such a “generic linked list,” when we create a LinkedList object in the main() function we have to say what type we’re using ( T will become whatever that type is). int main() { LinkedList<double> mylist; mylist.push_back(4.3); mylist.insert_front(3.2); mylist.print(); // etc... } Ok, that’s still double values in our linked list. Let’s put strings inside instead: int main() { LinkedList<string> mylist; mylist.push_back("hugo"); mylist.insert_front("chavez"); mylist.print(); // etc... } The linked list that stores string values is the same class as above. We can create two linked lists storing different types of values, if we wish: int main() { LinkedList<string> words; LinkedList<int> frequencies; words.push_back("bean"); frequencies.push_back(15); // etc... } That feeling of elation that you must have is the feeling of freeing yourself from strong typing. You didn’t really free yourself; the types are all still there ( double, string, etc.). But it’s close enough (we don’t need much to be thrilled). Another example: Template specialization This example is borrowed from cplusplus.com. It shows how we can “specialize” a template class by writing another class with a specific type for the template type, and even add new methods that that specialized class. // template specialization #include <iostream> using namespace std; // class template: template <class T> class mycontainer { T element; public: mycontainer (T arg) {element=arg;} T increase () {return ++element;} }; // class template specialization:; } Output: 8 J Function templates You can use templates on functions, too, and not just classes. Example from cppreference.com #include <iostream> template<typename T> void f(T s) { std::cout << s << '\n'; } int main() { f<double>(1); // instantiates and calls f<double>(double) f<>('a'); // instantiates and calls f<char>(char) f(7); // instantiates and calls f<int>(int) void (*ptr)(std::string) = f; // instantiates f<string>(string) }
http://csci221.artifice.cc/lecture/template-metaprogramming.html
CC-MAIN-2017-30
refinedweb
754
63.19
Re: Change for a Dollar - From: Simon Richard Clarkstone <s.r.clarkstone@xxxxxxxxxxxx> - Date: Sat, 28 Apr 2007 13:28:20 +0100 Charles Richmond wrote: I heard one night on David Letterman that there are 293 ways to make change for a dollar. So I started thinking about writing a program to list out *all* the ways a dollar could be broken into change. I just can *not* seem to get a hold on this problem. I wrote a program with a recursive function attempting to make the change, but it had excessive runtime and does *not* seem to be working in any case... Does anyone have an idea how I can proceed??? Idea: if you want to make change for an amount A, and you have a coins of value [V_1, V_2, V_3, ..., V_n] available, and V_i is less than A, then you can make change by: (the coin V_i)+(change you can make for (A - V_i) from [V_i, ..., V_n]) This gives all the combinations in one ordering, with the coins in the same order as the original list. I sat down and bashed out a program based on that idea in Haskell: We have a module declaration: module Change (mkChange, Coin) where import Data.List (tails) The the definition of a Coin (there is a string to distinguish multiple types with the same value, as someone suggested elsewhere in this thread): data Coin = Coin { cName :: String, val :: Integer } How to print a coin (just print the String part) instance Show Coin where show = cName The mkChange function takes a list of available coin types and the value to make up, then returns the list of ways to make the change: mkChange :: [Coin] -> Integer -> [[Coin]] mkChange coins total The only way for a total of zero is no coins: | total == 0 = [[]] Otherwise, we have a list comprehension. The coin c followed by the list ch is a possible way to make change... | otherwise = [ c : ch For each c being a coin and ccs being the list of that coin and all later coins in the available list... | ccs@(c:cs) <- tails coins Check that the value of c is not bigger than the total... , val c <= total and ch is one of the ways to make change for the remaining amount from the coins ccs. , ch <- mkChange ccs (total - val c) ] To use it, we can define: > usaCoins = [Coin "penny" 1, Coin "nickle" 5, Coin "dime" 10, Coin "quarter" 25, Coin "half" 50, Coin "dollar" 100] Then call: > mkChange usaCoins 100 to get the full list or: > length $ mkChange usaCoins 100 to find out how many ways there are. A good compiler will deforest that expression into recursive code very similar to the typical imperative solution. My approach can be easily adapted for any language that has list comprehensions (e.g. Python), though linked lists work better for it than arrays do. -- Simon Richard Clarkstone: s.r.cl?rkst?n?@durham.ac.uk/s?m?n.cl?rkst?n?@hotmail.com Scheme guy says: (> Scheme Haskell) Haskell guy says: (> Scheme) Haskell . - References: - Change for a Dollar - From: Charles Richmond - Prev by Date: Re: Applications that use thousands of data containers? - Next by Date: Re: random integer - Previous by thread: Re: Change for a Dollar - Next by thread: Re: Change for a Dollar - Index(es):
http://coding.derkeiler.com/Archive/General/comp.programming/2007-04/msg00413.html
crawl-002
refinedweb
555
73.51
Created on 2017-07-13 14:03 by dtasev, last changed 2017-07-23 11:05 by pitrou. This issue is now closed. Hello, I have noticed a significant performance regression when allocating a large shared array in Python 3.x versus Python 2.7. The affected module seems to be `multiprocessing`. The function I used for benchmarking: from timeit import timeit timeit('sharedctypes.Array(ctypes.c_float, 500*2048*2048)', 'from multiprocessing import sharedctypes; import ctypes', number=1) And the results from executing it: Python 3.5.2 Out[2]: 182.68500420999771 ------------------- Python 2.7.12 Out[6]: 2.124835968017578 I will try to provide any information you need. Right now I am looking at callgrind/cachegrind without Debug symbols, and can post that, in the meantime I am building Python with Debug and will re-run the callgrind/cachegrind. Allocating the same-size array with numpy doesn't seem to have a difference between Python versions. The numpy command used was `numpy.full((500,2048,2048), 5.0)`. Allocating the same number of list members also doesn't have a difference - `arr = [5.0]*(500*2048*2048)` This is because instantiating new Arena is much slower in Python 3. ./python -m timeit -r1 -s 'from multiprocessing.heap import Arena' 'Arena(2**26)' Python 3.7: 1 loop, best of 1: 1.18 sec per loop Python 2.7: 100000 loops, best of 1: 9.19 usec per loop May be the regression was introduced by issue8713. It can be significantly sped up if replace the writing loop with if size: os.lseek(self.fd, size, 0) os.write(self.fd, b'') os.lseek(self.fd, 0, 0) or just with os.truncate(self.fd, size) (not sure the latter always works). But instantiating an open Arena will still be slower than in 2.7. In Python 2.7, multiprocessing.heap.Arena uses an anonymous memory mapping on Unix. Anonymous memory mappings can be shared between processes but only via fork(). But Python 3 supports other ways of starting subprocesses (see issue 8713 [1]) and so an anonymous memory mapping no longer works. So instead a temporary file is created, filled with zeros to the given size, and mapped into memory (see changeset 3b82e0d83bf9 [2]). It is the zero-filling of the temporary file that takes the time, because this forces the operating system to allocate space on the disk. But why not use ftruncate() (instead of write()) to quickly create a file with holes? POSIX says [3], "If the file size is increased, the extended area shall appear as if it were zero-filled" which would seem to satisfy the requirement. [1] [2] [3] Note that some filesystems (e.g. HFS+) don't support sparse files, so creating a large Arena will still be slow on these filesystems even if the file is created using ftruncate(). (This could be fixed, for the "fork" start method only, by using anonymous maps in that case.) If I understand correctly, there is no way to force the old behaviour in Python 3.5, i.e. to use an anonymous memory mapping in multiprocessing.heap.Arena so that the memory can be shared between the processes instead of writing to a shared file? The data sizes usually are, on average, 20 GB, and writing it out to a file is not desirable. As I understand from Gareth Rees' comment, ftruncate() will speed up initialisation, however any processing afterwards would be IO capped. To shed more light to the processing going on, the data is handled as a 3D array, so each process gets a 2D array to operate on, and no information needs to be shared between processes. If the anonymous memory mapping cannot be forced, then the multiprocessing module with a shared array becomes unusable for me. Are you aware of any way to use the multiprocessing module to run execution in parallel, that somehow doesn't use a shared array? If you need the 2.7 behaviour (anonymous mappings) in 3.5 then you can still do it, with some effort. I think the approach that requires the smallest amount of work would be to ensure that subprocesses are started using fork(), by calling multiprocessing.set_start_method('fork'), and then monkey-patch multiprocessing.heap.Arena.__init__ so that it creates anonymous mappings using mmap.mmap(-1, size). (I suggested above that Python could be modified to create anonymous mappings in the 'fork' case, but now that I look at the code in detail, I see that it would be tricky, because the Arena class has no idea about the Context in which it is going to be used -- at the moment you can create one shared object and then pass it to subprocesses under different Contexts, so the shared objects have to support the lowest common denominator.) Nonetheless this is bound to be a nasty performance for many people doing big data processing with NumPy/SciPy/Pandas and multiprocessing and moving from 2 to 3, so even if it can't be fixed, the documentation ought to warn about the problem and explain how to work around it. I have looked into your advice of changing multiprocessing.heap.Arena.__init__, I have removed the code that allocated the file and reverted to the old behaviour. I have done some brief runs and it seems to bring back the old behaviour which is allocating the space in RAM, rather than with IO. I am not sure what things this might break, and it might make the other usages of multiprocessing unstable! Can anyone think of anything this change might break? The Arena.__init__ code is the one from Python 2.7: class Arena(object): def __init__(self, size, fd=-1): self.size = size self.fd = fd # still kept but is not used ! self.buffer = mmap.mmap(-1, self.size) There does not seem to be a difference regardless of the start method setting multiprocessing.set_start_method('fork') to be 'fork'. I see now that the default start method is 'fork' (except on Windows), so calling set_start_method is unnecessary. Note that you don't have to edit multiprocessing/heap.py, you can "monkey-patch" it in the program that needs the anonymous mapping: from multiprocessing.heap import Arena def anonymous_arena_init(self, size, fd=-1): "Create Arena using an anonymous memory mapping." self.size = size self.fd = fd # still kept but is not used ! self.buffer = mmap.mmap(-1, self.size) Arena.__init__ = anonymous_arena_init As for what it will break — any code that uses the 'spawn' or 'forkserver' start methods. Thank you, that is indeed the solution I ended up with, along with a large explanation of why it was necessary. Do you think that it's worth updating the `multiprocessing` documentation to make users aware of that behaviour? I propose: 1. Ask Richard Oudkerk why in changeset 3b82e0d83bf9 the temporary file is zero-filled and not truncated. Perhaps there's some file system where this is necessary? (I tested HFS+ which doesn't support sparse files, and zero-filling seems not to be necessary, but maybe there's some other file system where it is?) 2. If there's no good reason for zero-filling the temporary file, replace it with a call to os.ftruncate(fd, size). 3. Update the documentation to mention the performance issue when porting multiprocessing code from 2 to 3. Unfortunately, I don't think there's any advice that the documentation can give that will help work around it -- monkey-patching works but is not supported. 4. Consider writing a fix, or at least a supported workaround. Here's a suggestion: update multiprocessing.sharedctypes and multiprocessing.heap so that they use anonymous maps in the 'fork' context. The idea is to update the RawArray and RawValue functions so that they take the context, and then pass the context down to _new_value, BufferWrapper.__init__ and thence to Heap.malloc where it can be used to determine what kind of Arena (file-backed or anonymous) should be used to satisfy the allocation request. The Heap class would have to have to segregate its blocks according to what kind of Arena they come from. The original changeset in Richard's repository is. Unless Richard answers otherwise, I think it's likely the performance degradation was an oversight. Given the code we're talking about is POSIX-specific, truncate() (or its sibling os.ftruncate()) is specified to always zero-fill. So it should be safe to use. Another related point is that the arena file is created inside get_temp_dir(), which allocates something in /tmp. On modern Linux systems at least, /tmp is usually backed by persistent storage. Instead, we could use /run/user/{os.getuid()}, which uses a tmpfs and would therefore save on I/O when later accessing the shared array. Gareth, Dimitar, you may want to take a look at The size of file system mounted on "/run/user/${uid}" is limited (only 200 MiB on my computer). get_temp_dir() will be successful, but this may be not enough for allocating large shared array. And it is harder to control by user, because the location is not specified by an environment variable. > The size of file system mounted on "/run/user/${uid}" is limited (only 200 MiB on my computer) Hmm, you're right. Is /dev/shm ok on your computer? Yes, /dev/shm is ok on my computer. But there is yet one drawback of this patch. Currently the size of shared array is limited by the free space on the file system for temporary files. If it isn't enough you can easy set TMPDIR to other path. In 2.7 and with hardcoded /dev/shm it is limited by the size of physical memory (maybe plus swap). It is not easy to increase it, especially for unprivileged user. The effect of hardcoding /dev/shm can be achieved by setting TMPDIR to /dev/shm. Using os.ftruncate() adds yet about 20% of speed up. This looks mainly as a documentation issue to me. The regression and the workaround should be documented. The main issue here is to restore performance of 2.7 version. Setting TMPDIR sounds too general and might have impact on other libraries. I think it's ok if shared array size is limited by virtual memory size on the computer, since the whole point is to expose a fast communication channel between processes. This can break Python 3 applications that work with shared arrays larger than the size of physical memory. If do this change, it should be optional. Setting TMPDIR=/dev/shm restores performance of 2.7 version even on versions that we will decide to not patch. Again, setting TMPDIR is a poor workaround as it will impact any library creating temporary files. I haven't found anyone complaining about limited shared array size on 2.7, so likely it's not a common concern. Right now, anyone creating a huge shared array on 3.x will be facing huge performance issues, as the array is backed by disk, so it doesn't sound realistic at all to assume people are doing that. Serhiy, I've changed the strategy in PR 2708: now the partition free space is tested before deciding to locate the file there or not. New changeset 3051f0b78e53d1b771b49375dc139ca13f9fd76e by Antoine Pitrou in branch 'master': bpo-30919: shared memory allocation performance regression in multiprocessing (#2708)
http://bugs.python.org/issue30919
CC-MAIN-2017-34
refinedweb
1,902
66.13
Second AI Discovery By Ian Beardsley ISBN: 978-1-365-87273-0 2 of 39 Table of Contents Artificial Intelligence Connected To Organic Life Through Water And The Earth3 Now Germanium..13 AI Test 0125 Artificial Intelligence Connected To Organic Life Through Water and The Earth 4 of 39 In this paper I set out to answer the question question: Why does AI have the structure Idiscovered according to my definition of structure and, why is it connected to organic life withthat structure. I did this by finally asking the right question. Once I had asked that question, Istarted a journal that begins: Entry OneMarch 30, 2017 Entry TwoMarch 31, 2017 Then I noticed something interesting from the data processed in those entries that takes us inanother direction: the discovery that Artificial Intelligence (AI) is connected to Organic lifethrough the density of water (H2O) and the physical dimensions of the Earth (the distance fromthe North Pole to the Equator. The question I was addressing was pertinent to my discovery of structure in AI and Natural Lifeas presented in my book An AI Discovery by Ian Beardsley, which is available online for freedownload. Ian BeardsleyApril 1, 2017 5 of 39 In light of the discovery that artificial intelligence (AI) is connected to organic life through mydefinition of structure, the question to ask is: Why does AI have the structure I have describedand, why is it connected to organic life? In a sense, we can say AI is central to the Universal Mystery because not only is it based onsilicon (Si), where silicon is in group 14, the same group as carbon (C) upon which organic life isbased, but it is also element 14, which is to say it is made up of 14 protons and 14 electrons.That is to say, that it is element 14 in group 14, which is the group of life (carbon). The reasongroup 14 is the group of life is that it is 4 steps away the noble gases, giving them four electronsfor binding and, 4 electrons allows for carbon (C) to form long chains, the hydrocarbons. 13 14 15 5 6 7B C N10.81 12.01 14.01 13 14 15Al Si P26.98 28.09 30.97 Ian BeardsleyMarch 30, 2017 This discovery, I feel, is but one melody in an overall orchestral work. To get started, how muchmore does an atom of silicon weigh than an atom of carbon? We refer to the periodic table ofelements: And, how many more times dense is silicon than carbon. That is how much more mass does itdoes it have for for the same volume: We know the molar volume of silicon at STP. It is (12 cm^3)/(mole). The molar volume ofcarbon at STP can vary from molecular structure to molecular structure of the element. That is,the molar volume of a diamond, which has a lattice-type structure, would be significantlydifferent that that of coal. It, in fact, is not a trivial problem to determine the molar volume of thehydrocarbons in a sample of coal. But, we will work with those things for which we have data. Ian BeardsleyMarch 31, 2017 6 of 39 But we notice: A centimeter (cm) is defined as a billionth of the distance from the North Pole to the Equator. We then conclude that Artificial Intelligence (AI) is connected to organic life, through the densityof water and the physical dimensions of the Earth. 7 of 39 We now move on to combine the results of the detour with the results of the exit,8 of 39 9 of 39 10 of 39 A key component of natural life sustenance is not just water (H2O) but, is air. Air is mostlycomposed of diatomic oxygen gas (O2 20.95% by volume) and diatomic nitrogen gas (N278.09% by volume). Other components are: Argon (0.93%)Carbon Dioxide (0.03%)Neon (0.0018%)Helium (0.0005%)Krypton (0.0001%)Hydrogen (0.0005%)Xenon (9E-6%) 0.2095(32.00) + 0.7809(28.02) +, yeilds: As an accepted figure. We know the molar mass of silicon (Si) is 28.09 grams per mole where silicon is the heart of AI, 12 of 39 13 of 39 Now Germanium 14 of 39 15 of 39 16 of 39 18 of 39 19 of 39 20 of 39 21 of 39 23 of 39 24 of 39 AI Test 01 25 of 39 An AI Test 01 Given the molar mass of carbon (g/mol) is close to the molar volumeof silicon (cm^3/mol), and that the mass of an atom of Si comparedto the mass of an atom of C is close to the density of Si (g/cm^3)and, that, H2O is defined as 1 gram per cubic centimeter, which ofthe following is true:1. We can define the density of water closely with the above.2. We can define the specific volume of water closely with the above.3. We can compute the molar volume of carbon.4. One and two are true.5. All of the above are true.4One and two are true. 2[cos(pi/6)]=1. sqrt(2)2. PHI=1.618...3. sqrt(3)3The answer is 3, sqrt(3) [Process completed] 28 of 39 I made an ALICEBOT (an AI with which you can chat) and his name is Sabio. 30 of 39 Train Alter sabio: Hello. 31 of 39 Human: Elaborate. Human: I do. 32 of 39 count.py While Loop In C cuenta.c #include <stdio.h>int main(void){int i=0;int n;printf("Give me an integer less than 10: ");scanf("%i", &n);while (n>0){i=i+1;n=n-1;printf("%i\n", i);}} 34 of 39 cuenta.py For Loop In C count.c #include<stdio.h>int main (void){int n;do{printf("Count to this integer: ");scanf("%d", &n);}while (n<=0);for (int i = 1; i<=n; i++){printf("%d\n", i);}} Running the For Loop in C (Does same thing as the While Loops) 36 of 39 37 of 39 The.
https://de.scribd.com/document/343838336/A-Second-AI-Discovery
CC-MAIN-2019-47
refinedweb
1,020
69.01
Access the reports page To view the Cloud Billing reports for your Cloud Billing account: In the Google Cloud console, go to your Cloud Billing account. Go to your Cloud Billing account At the prompt, choose the Cloud Billing account for which you'd like to view reports. The Billing Overview page opens for the selected billing account.. Adjust<< Manage report view and settings Use the various report settings and filters to custiomize the report view. You can select a preset view, and you can further refine the data displayed in the report by adjusting the time range, group by, and filter settings. Preset views . Time range You can select between Usage date or Invoice month. May 2021: Subaccount: If you're viewing a primary billing account. Project hierarchy: Project hierarchy is the project's ancestry, the resource hierarchy mapping of a project (Organization > Folder > Project). When grouped by Project hierarchy, the report returns a row for each unique combination of Organization > Folder > Project, and the table includes columns for Project, Project ID, Project number, and Project hierarchy. The values listed in the Project hierarchy column show Organization name > Folder name. Projects can stand alone or be the child of an organization or folder. When grouping by Project hierarchy, projects that stand alone display as [Project not associated with any folders or organizations]. The project hierarchy group by option is selectable when the report's time range is set to start on or after January 1, 2022. Learn more about analyzing costs by project hierarchy. Subaccounts: If you're viewing a primary billing account with subaccounts, you can select all subaccounts (default) or select a subset of subaccounts by clicking them in the list. Folders & Organizations: Folders and organizations are part of a project hierarchy, the resource hierarchy mapping of a project. If the time range is configured to start on or after January 1, 2022, you can select all folders/organizations (default) that are associated with the projects that are linked to the Cloud Billing account, or select a subset of folders/organizations. The values in the selector are listed in alphabetical order by resource name. To determine if a value is an organization or a folder, look at the ID number displayed below each name. ID numbers are prefaced with folders/ or organizations/ to indicate the type of resource. For the Cloud Billing account you are viewing, if none of the linked projects are associated with any folders or organizations, then this filter option is not displayed. Note that you can still group by Project hierarchy. The Project hierarchy column displays [Project not associated with any folders or organizations] for projects that do not have any ancestors. Projects: You can select all Cloud projects linked to. >>IMAGE. Labels: Labels are key/value pairs you attach to resource usage (for example, Compute Engine, Cloud Storage, or Google Kubernetes Engine). To filter usage by label, follow these steps: -. If you want to view costs for your Google Kubernetes Engine, you must enable cost allocation for your GKE clusters. After you have enabled cost allocation, you can filter your GKE resources by using these label keys: goog-k8s-cluster-name: Filter or group GKE resources by cluster. k8s-namespace: Filter or group GKE resources by namespace. When filtering by label keys, you cannot select labels applied to a project. You can select other user-created labels that you set up and applied to Google Cloud services. For more information about labels, see common uses of labels and creating and managing resource labels. Credits: You can select all applicable credits (default) to be included in the cost calculations, or you can uncheck some or all of the credit options to exclude credits from the cost calculations. The credits filter displays only the specific credit types that you incurred in your Google Cloud costs. If a particular type of credit does not apply to your Cloud Billing account, you will not see that credit option in the list.. Save and share. . View_13<<. View your costs by project hierarchy Viewing your costs by project hierarchy helps you analyze costs by folder or organization. For example, if you use folders in an organization to represent cost centers, you can effectively configure your report to group all costs by those cost centers. To analyze your costs by project hierarchy, including costs by Organizations or costs by Folders, set the Group by option to Project hierarchy. You can also use the Folders & Organizations filter to select specific folders/organizations to focus the data returned in the report. About project and resource hierarchy Projects form the basis for creating, enabling, and using all Google Cloud services. Folders are used to group projects under the organization node in a resource hierarchy. A folder can contain projects, other folders, or a combination of both. Each resource has exactly one parent. Metaphorically speaking, the Google Cloud resource hierarchy resembles the file system found in traditional operating systems as a way of organizing and managing entities hierarchically. From a cost management perspective, you might use folders in an organization to represent cost centers (such as Devops or Finance). You can view your costs by project hierarchy to analyze your costs by folder. Project hierarchy is the ancestry of a project, the resource hierarchy mapping of the project (Organization > Folder > Project). Projects can stand alone (that is, not be associated with any folders or organizations) or be the child of an Organization or Folder. Project hierarchy tracks the current and historical project ancestry. For example, changing a project's name, or moving a project to a different folder or organization, affects the historical project ancestry. To gain a deeper understanding about resource hierarchy and Cloud Billing, refer to Cloud Billing concepts, Resource hierarchy . Configure your report to show project hierarchy To view your costs by project hierarchy (organization > folder > project), take the following steps: - In the Google Cloud console, open the Reports page for the Cloud Billing account you want to analyze. - In the report Filters, set a Time range to use a starting date on or after January 1, 2022. In the Group by selector, choose Project hierarchy. The report returns a row for each unique combination of Organization > Folder > Project, and the table includes columns for Project, Project ID, Project number, and Project hierarchy. The values listed in the Project hierarchy column show Organization name > Folder name. Analyze the report when grouped by Project hierarchy You can sort the table data on different columns to view the project hierarchy costs in different ways: - To visualize all of the projects that have the same project hierarchy, sort the table by the Project hierarchy column. - To visualize if you have the same project associated with more than one ancestry, sort the table by the Project ID column. You can narrow the report's project hierarchy results using the Folders & Organizations filter. While you are viewing the report grouped by Project hierarchy, if you change the report's time range to include a starting date prior to January 1, 2022, the Group by selection is automatically updated to group by Project. If you select some folders or organizations in the filter, and then update the time range to include a starting date prior to January 1, 2022, the folders/organizations selections are removed. Understand and analyze changes in project ancestry For the time range you are analyzing, it is possible for the same Project to be listed in more than one row in the report table. This can occur if something related to the project's ancestry has changed. Changes that affect a project's ancestry include the following: - Changing the project's name - Moving the project to a different organization and/or folder - Changing a parent folder's name - Moving a parent folder into another folder and/or organization To visualize if you have projects associated with more than one ancestry, sort the table data by the Project ID column. View project hierarchy examples showing different scenarios where something related to the project's ancestry was changed, and how that change impacts the results in the report, depending on how you Group the results. View and analyze_15<<. View the details of your committed use discounts (CUD) Committed use discounts (CUDs) reduce the usage costs of Compute Engine and certain other Google Cloud services. The fees and credits from your purchased committed use discounts are applied to your Cloud Billing account using attribution, which describes how they're spread across the account's projects that consumed the eligible discounts. When analyzing your Google Cloud costs, it is useful to understand how your purchased commitments are impacting your costs. To understand how your commitment fees and credits are applied to your Cloud Billing account and projects, see Attribution of committed use discount fees and credits.]. Depending on the product for which you purchased committed use discounts, the fees and credits are applied to your Cloud Billing account using either account attribution or proportional attribution. To understand how your commitment fees and credits are attributed to your Cloud Billing account and projects, see Attribution of committed use discounts. May 2021 May 2021. View. Analyze. Understand. View_16<< - The summary footer, below the table, displays the cost breakdown based on your filter selections. Invoice-level charges (tax and adjustments) are blank (—) when you filter by Usage date, or when you set other report filters (like projects, services, or SKUs). , which can be filtered and downloaded. - Cost Breakdown report: An at-a-glance waterfall view of your monthly costs calculated using the on-demand price for your Google Cloud usage, how credits saved you money on your invoice, and any invoice-level charges applied (if you are viewing the cost breakdown for an invoice month time range).. When viewing costs by invoice month, the following data is available in the Cloud Billing reports:. As of May 2021, May 2021 invoice. Prior to May 2021, or when viewing the report using a Usage date time range, your costs are calculated using your negotiated contract price, resulting in a single column for Cost that includes your Negotiated savings. As of January 1, 2022, the following data is available in the Cloud Billing reports: - Project hierarchy: Project hierarchy is the project's ancestry, the resource hierarchy mapping of a project (Organization > Folder > Project). When viewing your report with a starting time range of January 1, 2022, you can group your data by Project hierarchy. - Folders & Organizations: Folders and organizations are components of a project hierarchy. When viewing your report with a starting time range of January 1, 2022, you can filter your data by folders and/or organizations.
https://cloud.google.com/billing/docs/how-to/reports?authuser=1
CC-MAIN-2022-33
refinedweb
1,776
50.67
Hallo everyone . I am trying to write code for a tree traversal of plain trees (although all trees can be viewed as binary trees). So far i have written the code below. I would like to ask if you think my approach is correct. Furthermore, in the main procedure i want to parse a tree from a file and then call the post_traverse function. My problem is not the parsing of the file, instead i am having difficulties to understand how to assign each value i am going to read from the file to a node. For example, lets say i have a file like this: (1(2 (3 9)5(3))). A left parenthesis '(' signals a new child, while a right parenthesis ')' signals a new sibling. In this example how can i pass each value to the n -> firstchild or n -> nextsibling? Thank you. Code:#include <iostream> using namespace std; struct treenode { string value; int numofchildren; struct treenode *firstchild; struct treenode *nextsibling; }; int leaf (treenode *n, int depth) { if (n -> numofchildren == 0) return 1; else return 0; } int visit (treenode *n, int depth) { std::cout << depth << ":" << n -> value; return 0; } int post_traverse (treenode *n, int depth) { if (leaf(n, depth)) visit(n, depth); else { // visit(n, depth); //PRE post_traverse(n -> firstchild, depth + 1); while (n -> numofchildren - 1 > 0) { // visit(n, depth); //IN n -> numofchildren --; post_traverse (n -> nextsibling, depth + 1); visit(n, depth); } depth ++; return 0; } } int main() { return 0; }
http://cboard.cprogramming.com/cplusplus-programming/99104-plain-tree-traversal.html
CC-MAIN-2015-48
refinedweb
240
62.61
There has been talk of JavaScript fatigue. It's true the field is progressing fast. And as you move fast, it can be tiring for sure. Fortunately, as we understand better what we are doing, we can actually standardize our ways of doing. That should take away some of the pain. Eventually development made in frameworks and libraries tends to flow back to the web platform itself. I believe one of the key advances will be a movement towards common component definitions. There are two main ways to approach components in the web. You can either try to solve JavaScript in HTML or HTML in JavaScript. This doesn't mean there won't be any JavaScript. It's more about how it's being treated. In the former approach you leave structural aspects to HTML side of the fence while in the latter you push them to JavaScript. JavaScript in HTML relies on templating. There's standardization for the approach in form of Web Components (example: <x-gif</x-gif>). Frameworks, such as Angular or Ember, implement a templating solution of their own. Both have made moves that will allow you to consume Web Components from both frameworks, though. Libraries like React, Deku, and Cycle, fall to the HTML in JavaScript category. Here we can use a format, such as hyperscript (plain JavaScript) or JSX (XMLish syntax compiled to JavaScript). In this approach you will perform possible templating operations (for example if, looping) using JavaScript itself. It is possible to use the approaches together in React. At the moment the match isn't ideal as the programming models differ and that causes friction. React documentation suggests that you wrap your Web Components within React components of their own. That is the same approach you would use with a library such as jQuery. In short, you can use Web Components with a library like React, but it might not be very fun yet. During the past few years it has become apparent component oriented approach fits the web and web applications well. We're still paying a price from the fact that the web is a content oriented platform by design. That said, developing full blown web applications is far easier these days than it was ten years ago. There are still plenty of issues to resolve, though. Even though npm makes it almost ridiculously easy to share your components, we aren't quite there yet. It might be easy to consume JavaScript through it, but aspects like styling are still partially unresolved. As a result we have CSS conventions, processors, and a lot of many other solutions like CSS Modules. It is quite telling that Bootstrap, a popular HTML, CSS, and JavaScript framework, has its own implementations for Angular, Ember, and React. Even though I appreciate the efforts of the people behind the projects, surely we must be able to resolve these kind of things better. Perhaps that's something Web Components could provide us? Although Web Components might be the longer term solution, there could be something that could be achieved for HTML in JavaScript type libraries like React, Deku, or Cycle. After all, even a small win is a win. And anything we can do to battle unnecessary fragmentation is good in my eyes. Currently any component I develop for React is useful only within React context. I find this a little problematic as I would love to share my work with a larger amount of people. I am sure this applies to other component authors too, and this would benefit the JavaScript community on the whole. React 0.14 introduced a feature known as stateless functional components. To give you an example, consider the one from their release notes (slightly modified for readability): // A functional component using an ES2015 (ES6) arrow function: const Aquarium = (props) => { const fish = getFish(props.species); return <Tank>{fish}</Tank>; }; // Or with destructuring and an implicit return, simply: const Aquarium = ({species}) => ( <Tank> {getFish(species)} </Tank> ); // Then use: <Aquarium species="rainbowfish" /> If the definition looks simple, that's because it is. A function based component like this cannot do much, but they are still highly useful! The best feature is that the syntax can be seen as something React agnostic! You could compile that JSX to Hyperscript and use that as an intermediate format to mediate between libraries. Components like this don't require a direct dependency on React thanks to babel-plugin-react-require. The plugin injects import React from 'react'; so that the JSX transpilation process works. It would be possible to pull this off with other libraries as well. There are proposals that would allow you to write stateful functions. Deku implements something like React context (read-only within the tree). Adopting ideas like these would give more room for potential sharing. Even though you cannot do absolutely everything with function based components, they allow you to achieve quite much! I believe adopting the core ideas would allow larger scale sharing of components between libraries. Currently solutions like Deku or Cycle feel like islands of their own compared to the continent of React. Building bridges wouldn't hurt. There have been interesting developments in the React world itself. Libraries, such as react-lite and Preact, provide much lighter ways to achieve the same results as using vanilla React might. I think we'll begin to see adoption of Web Components this year especially as frameworks like Angular and Ember allow you to consume them. The biggest benefit of following the standards is that you shield yourself from some of the churn. And of course you avoid vendor lock-in! I hope we see a similar movement within the React world. That would benefit the community as a whole and give more freedom for component authors. Even though having more standard ways of defining basic components would benefit libraries other than React initially, I believe this development could flow back to the React ecosystem as well.
https://survivejs.com/blog/towards-common-components/
CC-MAIN-2019-18
refinedweb
994
64.61
#ifdef CFW_446 #include "firmware_symbols_441.h" #endif #ifdef CFW_446 #include "firmware_symbols_446.h" #endif <![if !IE]> 105 Comments - Go to Forum Thread » Download: / / To quote, roughly translated: Version 2.68u in beta testing for all of our users on the forum. Although being in beta, the version in question works very well, so do not be afraid to get crash or otherwise. We decided to put in downloads this "beta" version, because we still have much work to do and time is very short. For now, enjoy this slice of homebrew. Sincere Thanks to the PS3 scene Spanish, having read so many positive reviews both on our Homebrew on Ferrox. Thank you again! The homebrew obviously is in testing (beta), shown here in the thread the various problems related to improper startup and or any other kind of problem. Iris Manager Unofficial v2.68u Changelog: Arabic language has been added (Thanks to Haider Kiara) Persian language has been removed (Due to poor translation, it was unnecessary to include it. Will be added back later if some users kindly got the result) Automatic recognition of language (beta) PAYLOAD mode DISCLESS pre-activated (Fake BD) for CFW's 3.55 / 4.30 / 4.46 New background color: Deep Ruby, Color Ocean, Razzmic Berry and Rich Electric Blue Fixed minor bugs for better stability Iris Manager 2.68u Unofficial (Final Version): Added Arabic Language (Thanks to Haider Kiara) Added Polish Language (Thanks to Roman5566) Automatic recognition of the language Archive Manager (Italian translation) Included in the "Version 2.68ui" ControlFan Utility (Italian translation) Included in the "Version 2.68ui" Removed the Persian language (Due to poor translation, it was unnecessary to include it. Will be readjusted later if some users kindly got the result.) Mode DISCLESS PAYLOAD pre-activated also on Custom Firmware 4.50! (Fake BD) for CFW's 430/446/450 New Colors System (Background Style) (Deep Ruby) (Color Ocean) (Razzmic Berry) (Rich Electric Blue) Payload 4.50 (Thanks to REIZA72 for the DUMP LV1/2, IDA PRO & Kakarotoks for lv2_dump_analyser) Fixed minor bugs for better stability Compatible with Habib/FERROX 4.50 Q: I can not start some games, giving me a black screen, why? A: Iris Unofficial Manager has integrated the modalia DISC-LESS ON CFW 430/446/450. Enable it and solve the start of all games. Q: The source code will be released when? A: The source code will be released with version 2.70u onwards. More PlayStation 3 News... Download: / (Mirror) To quote from cosimo98, roughly translated: CHANGELOG IRIS MANAGER 2.67U Added compatibility with CFW Rebug 4.46.1 REX / D-REX EDITION and other future CFW 446dex. Mode DiscLess 4.46/446dex activated. For the rest, has the same characteristics of 2.66U Special Thanks BETA TESTER franci97 (DEX user) cosimo98 (CEX user) More PlayStation 3 News...
http://www.ps3news.com/ps3-cfw-mfw/ps3ita-manager-v1-20-iris-manager-ps3-fork-by-rancid-o-arrives/page-5/
CC-MAIN-2013-48
refinedweb
471
66.44
The current post will focus on how to carry out between-subjects ANOVA using Python. As mentioned in an earlier post (Repeated measures ANOVA with Python) ANOVAs are commonly used in Psychology. We start with some brief introduction on theory of ANOVA. If you are more interested in the four methods to carry out one-way ANOVA with Python click here. ANOVA is a means of comparing the ratio of systematic variance to unsystematic variance in an experimental study. Variance in the ANOVA is partitioned in to: There is a more elegant way to parametrize the model. In this way the group means are represented as deviations from the grand mean by grouping their coefficients under a single term. I will not go into detail on this equation: As for all parametric tests the data need to be normally distributed (each groups. ANOVA using Python In the four examples in this tutorial we are going to use the dataset “PlanthGrowth” that originally was available in R but can be downloaded using this link: PlanthGrowth. In the first three examples we are going to use Pandas DataFrame. pd.unique(data.group.values)} to the control group. Using SciPy We start with A one-way ANOVA with calculating the Sum of Squares between. Sum of Squares Between is the variability due to interaction between the groups. Sometimes known as the Sum of Squares of the Model. SSbetween = (sum(data.groupby('group').sum()['weight']**2)/n)\ - (data['weight'].sum()**2)/N Sum of Squares Within The variability in the data due to differences within people. The calculation of Sum of Squares Within can be carried out according to this formula: sum_y_squared = sum([value**2 for value in data['weight'].values]) SSwithin = sum_y_squared - sum(data.groupby('group').sum()['weight']**2)/n Sum of Squares Total Sum of Squares Total will be needed to calculate eta-squared later. This is the total variability in the data. SStotal = sum_y_squared - (data['weight'].sum()**2)/N Mean Square Between Mean square between is the sum of squares within divided by degree of freedom between. MSbetween = SSbetween/DFbetween a F-value table based on the DFwithin and DFbetween. However, there is a method in SciPy for obtaining a p-value. p = stats.f.sf(F, DFbetween, DFwithin) Finally, we are also going to calculate. Thus, we can use the less biased effect size measure Omega squared: om_sqrd = (SSbetween - (DFbetween * MSwithin))/(SStotal + MSwithin) The results we get from both the SciPy and the above method can be reported according to APA style; F(2, 27) = 4.846, p = .016, η² = .264. If you want to report Omega Squared: ω2 = .204 Using Statsmodels The third method, using Statsmodels, is also easy. We start by using ordinary least squares method and then the anova_lm method. Also, if you are familiar with R-syntax. Statsmodels have a formula api where your model is very intuitively formulated. First, we import the api and the formula api. Second we, use ordinary least squares regression with our data. The object obtained is a fitted model that we later use with the anova_lm method to obtaine a ANOVA table. import statsmodels.api as sm from statsmodels.formula.api import ols mod = ols('weight ~ group', data=data).fit() aov_table = sm.stats.anova_lm(mod, typ=2) print aov_table Output table: As can be seen in the ANVOA table Statsmodels don’t provide an effect size . To calculate eta squared we can use the sum of squares from the table: esq_sm = aov_table['sum_sq'][0]/(aov_table['sum_sq'][0]+aov_table['sum_sq'][1]) Using pyvttbl anova1way We can also use the method anova1way from the python package pyvttbl. This package also has a DataFrame method. We have to use this method instead of Pandas DataFrame to be able to carry out the one-way ANOVA.) As can be seen in the output from method anova1way we get a lot more information. Maybe of particular interest here is that we get results from a post-hoc test (i.e., Tukey HSD). Whereas the ANOVA only lets us know that there was a significant effect of treatment the post-hoc analysis reveal where this effect may be (between which groups)..
http://www.marsja.se/four-ways-to-conduct-one-way-anovas-using-python/
CC-MAIN-2016-26
refinedweb
695
65.12
I am interested in developing algorithms in Julia and compiling the algorithm into a library and then integrating the functionality into large codebases written in C. I’m aware of PackageCompiler.jl but am confused about whether it can accomplish my goal especially since v1.0.0. I’m sure I’m not the first to ask this question but I can’t seem to find information on this use case. Any insight/advice would be appreciated. Thanks in advance. See the embedding Julia documentation. The easiest thing, in my opinion, is to do as much of the interfacing work as possible on the Julia side. For example, suppose you have a Julia function foo(x::Number, a::AbstractVector), which returns something of the same type as x, that you want to call from C. You first need to create a C-callable API using C datatypes, e.g. a function c_foo that takes a double, a double *, and a size_t length. Do this in Julia c_foo(x::Number, aptr::Ptr, alen::Integer) = foo(x, unsafe_wrap(Array, aptr, alen)) Then, in your C code, do // setup jl_init(); jl_eval_string("import MyModule"); // get C interface to Julia MyModule.foo function: double (*c_foo)(double, double*, size_t) = jl_unbox_voidpointer(jl_eval_string("@cfunction(MyModule.c_foo, Cdouble, (Cdouble, Ptr{Cdouble}, Csize_t))")); You now have a C function pointer c_foo to your c_foo routine, to which you can pass (double, double*, size_t) normally and get a double back. Lower-level things are possible, but the main point is that it is easier to do as much of the “glue” as possible on the Julia side. Thanks, @stevengj. I just totally missed that section of the manual. I will work through that section but from your examples, it seems to be exactly the details that I need. Correction: you need to call jl_unbox_voidpointer on the result of jl_eval_string to get a void* that you can cast to a function pointer. Here is a minimal working example that wraps the Julia sum function: #include <stdio.h> #include <julia.h> int main(int argc, char *argv[]) { jl_init(); // define a C-callable wrapper for sum(a), compile it // with @cfunction, and convert it to a C function pointer: jl_eval_string("c_sum(aptr, alen) = sum(unsafe_wrap(Array, aptr, alen))"); jl_value_t *c_sum_jl = jl_eval_string("@cfunction(c_sum, Cdouble, (Ptr{Cdouble}, Csize_t))"); double (*c_sum)(double*,size_t) = (double (*)(double*,size_t)) jl_unbox_voidpointer(c_sum_jl); // call our function to compute sum(a) (= 8): double a[] = {1,3,4}; printf("sum(a) = %g\n", c_sum(a, 3)); jl_atexit_hook(0); return 0; } In principle I should probably do JL_GC_PUSH1(&c_sum_jl);, but I omitted that since Julia doesn’t actually garbage-collect compiled code IIRC. You don’t need to root it but it has nothing to do with GC of code. c_sum_jl is just a Ptr{Cvoid} object and its lifetime is not bound to the code the pointer is pointing to. You don’t need the root because there’s nothing else between the return of the value and the single use of it. Notice that embedding doesn’t require any compilation (outside Julia) at all but you can use PackageCompiler to build a custom sysimage in order to reduce startup latency. In the latter case you need to initialize Julia with jl_init_with_image rather than jl_init, which is somewhat more involved. See for some explanation of how that works and a proposal to simplify matters. It is also possible to load libjulia dynamically with dlopen if you don’t want to compile libjulia into your C program. See for unmerged documentation of this approach. Incidentally it goes very far in the direction of doing as much of the interfacing as possible on the Julia side.
https://discourse.julialang.org/t/calling-julia-algorithm-from-c/35130
CC-MAIN-2022-21
refinedweb
611
52.9
Imagine, you are making a game. And you need to display scores frequently. One solution is to write the whole code to display the score again and again. But there is another better solution using functions. We can define that whole code in a function once and call it whenever we want. Function is nothing but a group of codes put together and given a name. And these can be called anytime without writing the whole code again and again. Why Functions? Functions make our code neat and easily readable and avoid us to rewrite the same code again and again. Types of Functions in C There are two types of functions in C. - Library Functions - User-defined Functions Library Functions Library functions are pre-defined functions in C. We have already read about some of these library functions like printf() and scanf(). User Defined Functions We can also define our own functions in C. Let's first see how to declare a function of our own. How to Declare a Function? We declare a function as follows return_type function_name ( parameters ) ; As an example, suppose we have to calculate the average of 2 numbers 'num1' and 'num2'. The numbers are integers and average is of type float. We will pass the numbers to a function that will return the average value of those numbers. We will declare that function as follows: float average( int num1, int num2 ); Here, the function named 'average' is taking 'num1' and 'num2' of integer type as input and then returning the average value of type float after calculating it. Defining Function Syntax for defining a function is return_type function_name ( parameters ) { //code } Let's see the 'average' function that we defined above. float average( int num1, int num2 ) { float avg; /* declaring local variable */ avg = ( num1 + num2 )/2.0; return avg; /* returning the average value */ } Variables declared inside function are called local variables. A local variable can only be used in the function in which it is declared. It has no use outside the function. For example, in our case, 'avg' is a local variable. int. return avg → This means that this function will give us or return us the variable (or its value) 'avg' which is of type float. You will understand this clearly in examples. Calling Function To use a function, we need to call it. Once we call a function, it performs its operations and after that the control again passes to the main program. To call a function, we need to specify the function name along with its parameters. function_name ( parameters ) ; So, we will call our average function as average( num1, num2 ); Now, let's combine all to take out the average of 2 numbers using a function. #include <stdio.h> float average(int num1, int num2); /* declaring function named average */; } float average( int num1, int num2 ) /* function */ { float avg; /* declaring local variable */ avg = (num1 + num2)/2.0; return avg; /* returning the average value */ } 5 Enter second number 4 Average is 4.50 float average( int num1, int num2 ) → We have declared that we have defined a function named 'average' in our program so that, 'main' function can search for it while calling. Here, a function named 'average' with 2 integer parameters ('num1' and 'num2') and return type of float is declared. This means that while calling the function, we need to give two integers as input and in return, it will give us a float as output. By writing c = average( num1, num2 );, we are calling the function 'average' with 2 parameters ( 'num1' and 'num2' ). As it is returning a float, and here it is 4.50, so, this expression will be equivalent to c = 4.50 as 4.50 is returned by the function and its value gets stored in a variable 'c'. We can also define a function at the time of declaration as in the example below. #include <stdio.h> float average( int num1, int num2 ) /* function */ { float avg; /* declaring local variable */ avg = ( num1 + num2 )/2.0; return avg; /* returning the average value */ }; } 5 Enter second number 4 Average is 4.50 We haven't declared our function seperately ( float average(int num1, int num2);) as we did in the previous example. Instead, we have defined our 'average' function before 'main'. So in this case, while executing 'main', the compiler will know that there is a function named 'average' because it is defined above from where it is being called. If a function doesn't return anything, then its return type is written as void as in the example below #include <stdio.h> void display( int n ) /* function */ { printf("Number is %d\n", n); } int main() { int n; printf("Enter number\n"); scanf("%d", &n); display(n); /* calling the function display*/ return 0; } 5 Number is 5 void means that the function will not return anything. It is also possible to define a function without any argument. See an example over this. #include <stdio.h> void display() { printf("Function with no argument\n"); } int main() { display(); return 0; } As you can see, there is no argument given in the function display(). Calling a function inside another Yes, we can call a function inside another function. We have already done this. We were calling our functions inside the main function. Now look at an example in which there are two user defined functions. And we will call one inside another. #include <stdio.h> int div_2(int a) { if(a%2==0) { return 1; } else { return 0; } } void div_6(int b) { if( div_2(b)==1 && b%3 == 0 ) { printf("Yes, the number is divisible by 6.\n"); } else { printf("No, the number is not divisible by 6.\n"); } } int main() { div_6(12); div_6(25); return 0; } No, the number is not divisible by 6. A number is divisible by 6 if it is divisible by 2 and 3 both. We have a function div_2 which will return 1 if the given number is divisible by 2. Another function that we have defined is div_6 which calls div_2 inside itself. if( div_2(b)==1 && b%3 == 0 ) → If div_2 returns 1, function within the same function.. #include <stdio.h> int factorial( int a ) /* function */ { if( a == 0 || a == 1) { return 1; } else { return a*factorial(a-1); } } int main() { int n; printf("Enter number\n"); scanf("%d", &n); int fact = factorial(n); printf("Factorial of %d is %d\n", n, fact); return 0; } 4 Factorial of 4 is 24 Here, if the integer 'n' is 0 or 1, return 1; is returning factorial value as 1. Otherwise, if the integer 'n' is greater than 1, then n*factorial(n-1) multiplies 'n' with the factorial of 'n-1'. For example, if the number is 4, then 'n*factorial(n-1)' implies '4*factorial(3)'. So by writing 'n*factorial(n-1)', we are again calling the function 'factorial' inside itself but this time the argument is 'n-1' i.e., factorial(n-1). So, first give 0 to factorial function, it will give us 1. Again, give 1, it will return 1 again. Now, give 2. This time the statement in the body of 'else' will be executed and it has to return n*factorial(n-1) i.e., 2*factorial(1). So, it will again call the 'factorial' function with 1 as argument (as factorial(1)) and it is 1. Finally, it will return 2*1 i.e. 2. Now, let's try this with 3. This time it has to return 3*factorial(2). Again factorial(2) will be called and it will return 2*factorial(1). So, the expression will be return 3*2*factorial(1) and then 3*2*1 ( as factorial(1) will return 1 ). For 4, the expression will be 4*factorial(3). Calling factorial(3), it will be 4*3*factorial(2) ( as factorial(3) will return 3*factorial(2) ). Again calling factorial(2), it will be 4*3*2*factorial(1). And at last, it will return 4*3*2*1 or 24.
https://www.codesdope.com/c-my-functions/
CC-MAIN-2021-39
refinedweb
1,339
64.61
With the first alpha release of Elasticsearch 5.0 comes a ton of new and awesome features, and if you've been paying attention then you know that one of the more prominent of these features is the new shiny ingest node. Simply put, ingest aims to provide a lightweight solution for pre-processing and enriching documents within Elasticsearch itself before they are indexed. We aren't going to dive into the details of how ingest node works in this blog post (it is recommended that you read the docs as a prerequisite), but instead we're going to showcase how to consume the ingest APIs from an Elasticsearch client. In these examples we're going to use NEST, the official .NET client, but keep in mind that these concepts apply to any of the official Elasticsearch language clients. So whether you're C# inclined or not, transferring this knowledge to the language of your choice should be trivial. Creating an ingestion pipeline In Elasticsearch 5.0, all nodes are ingest nodes by default, so there's nothing to do in terms of setting up Elasticsearch. Thus, the first step to enriching documents via an ingest node is to create an ingestion pipeline. Let's use the classic Tweet example (my apologies) and create a tweets index in our Elasticsearch cluster with the following mapping: { "tweets": { "mappings": { "tweet": { "properties": { "lang": { "type": "keyword" }, "message": { "type": "text" }, "retweets": { "type": "integer", "coerce": false } } } } } } Here, message contains the actual content of the tweet, lang represents the language code ( fr, etc...), and retweets is the number of times the tweet has been re-tweeted. Now imagine we have the following C# type to model our tweet documents: public class Tweet { public string Message { get; set; } public string Lang { get; set; } public string Retweets { get; set; } } Notice that Retweets is of type string, and perhaps for some reason we cannot to change the type. Well, since we set "coerce": false in our mapping of the retweets field, if we try to index one of these documents, Elasticsearch is going to throw a parse exception since the incoming value will be a string. So, what can we do? Let's create a pipeline that converts our retweets field to an integer before indexing it. While we're at it, let's also uppercase our language codes since they are of type keyword in our mapping and so case-sensitivity matters. Here's what this looks like using NEST: var client = new ElasticClient(); client.PutPipeline("tweet-pipeline", p => p .Processors(ps => ps .Convert<Tweet>(c => c .Field(t => t.Retweets) .Type(ConvertProcessorType.Integer) ) .Uppercase<Tweet>(u => u .Field(t => t.Lang) ) ) ); So what we've done here is used the put pipeline API to create a pipeline with the id "tweet-pipeline" that has two processors. A convert processor for converting retweets from string to integer, and an uppercase processor for, you guessed it, upper-casing the value of our lang field. Indexing documents Now that we've created our pipeline, let's index some documents using the bulk API and enrich them through the pipeline. client.Bulk(b => b .Index("tweets") .Pipeline("tweet-pipeline") .Index<Tweet>(i => i .Document(new Tweet { Retweets = "4", Message = "Hello, Twitter!", Lang = "en" }) ) .Index<Tweet>(i => i .Document(new Tweet { Retweets = "32", Message = "Bonjour, Twitter!", Lang = "fr" }) ) .Index<Tweet>(i => i .Document(new Tweet { Retweets = "", Message = "Hallo, Twitter !", Lang = "nl" }) ) ); Business as usual, except notice we specified a pipeline. This tells Elasticsearch we want to pre-process each document using the "tweets-pipeline" we created earlier before indexing. Here we specified the pipeline for all index commands, but we could specify a different pipeline for each individual index command if we had multiple pipelines. Handling errors If we inspect the response from our bulk request: { "took" : 33, "ingest_took" : 4, "errors" : true, "items" : [ { "index" : { "_index" : "tweets", "_type" : "tweet", "_id" : "AVSl-cCKVD5bKRQTTXNo", "_version" : 1, "_shards" : { "total" : 2, "successful" : 1, "failed" : 0 }, "created" : true, "status" : 201 } }, { "index" : { "_index" : "tweets", "_type" : "tweet", "_id" : "AVSl-cCKVD5bKRQTTXNp", "_version" : 1, "_shards" : { "total" : 2, "successful" : 1, "failed" : 0 }, "created" : true, "status" : 201 } }, { "index" : { "_index" : "tweets", "_type" : "tweet", "_id" : null, "status" : 400, "error" : { "type" : "illegal_argument_exception", "reason" : "unable to convert [] to integer", "caused_by" : { "type" : "number_format_exception", "reason" : "For input string: \"\"" } } } } ] } We'll notice that our last document failed. Why? Well if we take a look at the document we tried to index we'll notice that the value Retweets was an empty string and our convert processor didn't know what to do with it. We can address this by telling our processor what to do when it encounters a failure. Each processor has an on_failure property, which accepts more processors that it will execute when an error occurs. These nested processors themselves also have an on_failure property which you can further nest error handling, and so on and so forth. Also, the pipeline itself has its' own on_failure which you can set as a "catch all" error handler for the entire pipeline. For our tweet-pipeline example, let's just update our convert processor and add a set processor to on_failure that will set retweets to 0 if it fails to convert the original value. client.PutPipeline("tweet-pipeline", p => p .Processors(ps => ps .Uppercase<Tweet>(u => u .Field(twt => t.Lang) ) .Convert<Tweet>(c => c .Field(twt => twt.Retweets) .Type(ConvertProcessorType.Integer) .OnFailure(f => f .Set<Tweet>(s => s .Field(t => t.Retweets) .Value(0) ) ) ) ) ); If we index the document again (this time just using the index API), we'll get a 201 back from Elasticsearch: client.Index(new Tweet { Retweets = "", Message = "Hallo, Twitter !", Lang = "nl" }, i => i .Index("tweets") .Pipeline("tweet-pipeline") ); Now let's take a look at the documents in our index: "hits": [ { "_index": "tweets", "_type": "tweet", "_id": "AVSmDI7jVD5bKRQTTXin", "_score": 1, "_source": { "retweets": 32, "message": "Bonjour, Twitter!", "lang": "FR" } }, { "_index": "tweets", "_type": "tweet", "_id": "AVSmDJB6VD5bKRQTTXio", "_score": 1, "_source": { "retweets": 0, "message": "Hallo, Twitter !", "lang": "NL" } }, { "_index": "tweets", "_type": "tweet", "_id": "AVSmDI7jVD5bKRQTTXim", "_score": 1, "_source": { "retweets": 4, "message": "Hello, Twitter!", "lang": "EN" } } ] All of our language codes are uppercase and retweets for our NL has been set to 0! That is — in a nutshell — ingest node. Client considerations Dedicated ingest nodes with any Elasticsearch client is to create a dedicated "indexing" client instance, and use it for indexing requests: var pool = new StaticConnectionPool(new [] { new Uri(""), new Uri(""), new Uri("") }); var settings = new ConnectionSettings(pool); var indexingClient = new ElasticClient(settings); Increasing timeouts When a pipeline is specified, there is an added overhead of document enrichment when indexing a document. For large bulk requests, you might need to increase the default indexing timeout ( 1m) to avoid exceptions. Keep in mind, that the client may have its own request timeout — this should be increased as well, at least to the same value as the Elasticsearch timeout. client.Bulk(b => b .Index("tweets") .Pipeline("tweet-pipeline") .Timeout("5m") // Increases the bulk timeout to 5 minutes .Index<Tweet>(/*snip*/) .Index<Tweet>(/*snip*/) .Index<Tweet>(/*snip*/) .RequestConfiguration(rc => rc .RequestTimeout(TimeSpan.FromMinutes(5)) // Increases the request timeout to 5 minutes ) ); Conclusion In this post I've covered the basics of the new ingest node feature coming in Elasticsearch 5.0 and how to consume the ingest APIs from an Elasticsearch language client. I've only scratched the surface though, so I highly recommend reading the docs and watching the Ingest Node: Enriching Documents within Elasticsearch talk from Elastic{ON}16. NEST supports the ingest node APIs since the 5.0.0-alpha1 release and will work against any Elasticsearch 5.0.0 alpha release. Try it out and let us know what you think!
https://www.elastic.co/kr/blog/ingest-node-a-clients-perspective
CC-MAIN-2017-17
refinedweb
1,270
58.62
Journal tools | Personal search form | My account | Bookmark | Search: ... pioneer avic n2 dvd gps navigation system 6.5 shining mountain ... lab mountain melodies dark justice dvd adaptation adjustment family model resiliency ... characters buy cheap contact lenses convert cda to mp3 free download... syracuse ny coupons discount anime dvd 1995 lt1 engine swap to ...singularities definition alpha blue archives dvd john ottenheimer 15love the show... ...whiplash long term effects audible book files convert mp3 cheap cigarette marlboro russian traxxas 4... 45.9 torrent drop leaf riddim how to remove copy protection dvd john quince adams royal dutch airline ...jet extra large format printer 2 break dvd prison season right way driving center ... movie star easy cd creator 5.3.5 update exercise wall chart alternative ... ... wheels teacher idea for game 5 java mobile window wet t-...-1 pcmcia pc cards soil temperature dvd rw buy info radio canada ... woman globalism in business dvd player portable television sorcerers stone ... amarillo texas winchester in newspaper convert ogg mp3 freeware metronorth trains ...child health alert 01 26v2.dvd complete exile kaa last widescreen... ... outcast demo global data center the truth about 9/11 and wtc loose change the spirit ... home mom site myspace.com isometric map java convert string to integer download natural selection beta 5 kingdom hearts voice character voltage converter uk usa ... sand pensacola beach had joss stone arcsoft showbiz dvd 2 review acupuncture ear staples weight loss ... ...gig memory stick pro duo caspase 9 molecular weight gastric bypass success rates...rs5000 installation sunday morning by maroon 5+lyrics hollywood florida courthouse code ... 1 patch cuny spring semester dvd fullscreen where to sell baseball ... of soil by sludge drive dvd hard player panasonic ag dv2500p ... della ratta inc homes 3.5 convert keygen master video stay ... ... letter write def jam vendetta game cheats bmw recall 5 series red slip cover tips on song and lyric ... recognition product cheap air fares to india canada chinese convert glass scale california cannon chemical delivery water pasadena homeless ... you love my dark lyrics stone yamashita hp lightscribe dvd writer perl documentation split well point health network ... ... georgia blue planet bbc history of political parties in the united states download dvd region free 5.6 sewing pattern salwar kameez saree black cat stuffed animal people getting owned...vehicle registration fee tax deductible haiti port de paix british convert pound usd video communication and production cheap internet providers broadband... ... plan account first principal cd convert record ohio home health aide ... alabama ged online photo to dvd production hough and guidice miller ... hotel download free reason 2.5 mountaineer recall tarrant county public ... underground railroad one piece theme dvd read error popular college drinks... pool cabana this girls life dvd review new jersey furniture store... ... buy microsoft picture it express 9 alas poor 1997 mercury tracer ...standardized physical training guide samsonite 5 piece set luggage quick chicken ...poetry strong black man download dvd drivers south beach san francisco ... city gyms texas apartment locators 5 lose pound week capital health...bikini brazil in string calculator convert kilogram pound stories about jungle... ... chinese seamstress summary taking back sunday spin convert long raw classic auto and parts.com... mail extension canton irish cultural center 9 keygen pinnacle studio housecall trend antivirus ... west was won review nypd blues dvd long island wine country bed and ... lawyers 1 4.2.1.5 click copy dvd keygen louisiana flooded parking security webcam software one stop ... Avi To Dvd Converter Avi To Vcd Svcd Dvd Converter Dvd 9 To Dvd 5 Converter Copy Dvd 9 To Dvd 5 Copy 3.5.9.0 Clone Dvd Divx To Dvd Converter Dvd 9 5 Gb Dvd Dvd 9 5 Dvd Burner Dvd 9 Replication Dvd Burning Cucusoft Avi To Vcd Dvd Mpeg Converter Pro Dvd Copy Cucusoft Avi To Vcd Dvd Mpeg Converter Lite Dvd Copy Software Dvd Movie Dvd Ripper Result Page: 1 2 3 4 5 6 7 8 9 for Dvd 9 Convert To Dvd 5
http://www.ljseek.com/Dvd-9-Convert-To-Dvd-5_s4Zp1.html
crawl-002
refinedweb
661
58.99
We've previously covered the basics of driving OLED I2C displays from MicroPython, including simple graphics commands and text. Here we look at displaying monochrome 1 bit-per-pixel images and animations using MicroPython on a Wemos D1. Processing the images and correct choice of image-formats is important to get the most detail, and to not run out of memory. Setting up The display communicates over I2C, but we need a driver to interface with it. For this we can use the If the import ssd1306 succeeds, the package is correctly uploaded and you're good to go. Wire up the OLED display, connecting pins D1 to SCL and D2 to SDA. Provide power from G and 5V. The display below is a 2-colour version, where the top 1/4 of the pixels are yellow, while the rest is blue. They're intended for mobile screens, but it looks kind of neat with Scatman. i2c = I2C(-1, Pin(5), Pin(4)) display = ssd1306.SSD1306_I2C(128, 64, i2c) If your display is a different size just fiddle the numbers above. You'll need to change some parameters on loops later too. To test the display is working, let's set all the pixels to on and show it. display.fill(1) display.show() The screen should light up completely. If it doesn't, something is wrong. Image Processing To display an image on a 1-bit per pixel monochrome display we need to get our image into the same format. The best way to do this is using image manipulation software, such as Photoshop or GIMP. These allow you to down-sample the image to monochrome while maintaining detail by adding dither or other adjustments. The first step is to crop the image down to the correct dimensions — the display used here is 128x64 pixels. To preserve as much of the image as possible you might find it useful to resize the larger axis to the max (e.g. if the image is wider than high, resize the width to 128 pixels). Then crop the remaining axis. You can convert images to 1-bit-per-pixel in GIMP through the Image -> Mode -> Indexed... dialog. If you're image is already in an indexed format this won't be available. So convert back to RGB/Grayscale first, then re-select Image -> Mode -> Indexed. Select "Use black and white (1-bit) palette" to enable 1bpp mode. The colour dithering settings are best chosen by trial and error depending on the image being converted although turning off dithering entirely is often best for images of solid colour blocks (e.g. logos). Once the imagine is converted to black & white you can save to file. There are two good options for saving 1bpp images — PBM and PGM. PBM is a 1 bit-per-pixel format, while PGM is grayscale 1 byte per pixel. While PBM is clearly better suited, we can pre-process PGM down to an equivalent bit stream. Both approaches are included here, in case your software can only produce one or the other. Save as either PBM (recommended) or PGM, and select Raw mode, not ASCII. Example images Some example images (128x64 pixels) are shown below, in PNG format. Each of the images is available in this zip which contains PBM, PGM and PNG formats. Portable Bitmap Format Portable Bitmap Format (PBM) format consists of a regular header, separated by newlines, then the image data. The header starts with a magic number indicating the image format and whether the format is ASCII for binary. In all examples here we're using binary since it's more compact. The second line is a comment, which is usually the program used to create it. Third are the image dimensions. Then, following a final newline, you get the image binary blob. P4 # CREATOR: GIMP PNM Filter Version 1.1 128 64 <data> The data is stored as a 1-bit-per-pixel stream, with pixel on as 1 pixel off as 0. On a normal display screen an on pixel appears as black — this is different on the OLED, which we need to account for later. To upload your PBM file to the controller — ampy --port /dev/tty.wchusbserial141120 put alan.pbm The PBM data stream is already in the correct format for use. We can wrap the data in bytearray, use this to create a FrameBuffer and blit it immediately. However, we need to skip the header region (3x readline) before reading the subsequent data block. with open('scatman.pbm', 'rb') as f: f.readline() # Magic number f.readline() # Creator comment f.readline() # Dimensions data = bytearray(f.read()) fbuf = framebuf.FrameBuffer(data, 128, 64, framebuf.MONO_HLSB) We can't use readlines() since the binary image data may contain ASCII code 13 (newline). PBM data. This framebuffer format framebuf.MONO_HLSB used is different to that used by the ssd1306 screen ( framebuf.MONO_VLSB). This is handled transparently by the framebuffer when blitting. Displaying an image We have the image data in fbuf, which can be blitted directly to our display framebuffer, using .blit. This accepts coordinates at which to blit. Because the OLED screen displays inverse (on = light, off = black) we need to switch .invert(1) on the display. display.invert(1) display.blit(fbuf, 0, 0) display.show() Portable Graymap Format Portable Graymap Format (PGM) format shares a similar header to PBM, again newline separated. However, there is an additional 4th header line which contains the max value — indicating the number of values between black and white. Black is again zero, max (255 here) is white. P5 # CREATOR: GIMP PNM Filter Version 1.1 128 64 255 <data> The format uses 1 byte per pixel. This is 8x too many for our purposes, but we can process it down to 1bpp. Since we're saving a mono image each pixel will contain either 0 (fully off) or 255 (fully on). To upload your PGM file to the controller — ampy --port /dev/tty.wchusbserial141120 put alan.pgm Since each pixel is a single byte it is easy to iterate, though slow as hell. We opt here to turn on bright pixels, which gives us the correct output without switching the display invert on. with open('alan.pgm', 'rb') as f: f.readline() # Magic number f.readline() # Creator comment f.readline() # Dimensions data = bytearray(f.read()) for x in range(128): for y in range(32): c = data[x + y*128] display.pixel(x, y, 1 if c == 255 else 0) Packing bits Using 1 byte per pixel wastes 7 bits which is not great, and iterating to draw the pixels is slow. If we pack the bits we can blit as we did with PBM. To do this we simply iterate over the PGM image data in blocks of 8 (8 bits=1 byte). Each iteration we create our zero'd-byte (an int of 0). As we iterate over the 8 bits, we add 2**(7-n) if that bit should be set to on. The first byte we hit sets the topmost bit, which has a value of 2**(7-0) = 2**7 = 128, the second 2**(7-1) = 2**6 = 64. The table below shows the values for each bit in a byte. |7| 6|5|4|3|2|1|0 |:--|:--|:--|:--|:--|:--|:--|:--| |2^7| 2^6|2^5|2^4|2^3|2^2|2^1|2^0| |128| 64|32|16|8|4|2|1| The result is a single byte with a single bit set in turn for each byte we iterated over. p = [] for i in range(0, len(d), 8): byte = 0 for n, bit in enumerate(d[i:i+8]): byte += 2**(7-n) if bit == 255 else 0 p.append(byte) We choose to interpret the 255 values as on (the opposite as in PBM where black = on, giving an inverted image). You could of course reverse it. The variable p now contains a list of int values in the range 0-255 (bytes). We can cast this to a bytearray and then use this create our FrameBuffer object. # Create a framebuffer object fbuf = framebuf.FrameBuffer(bytearray(p), 128, 64, framebuf.MONO_HLSB) PGM (and bit-packed) data. This framebuffer format framebuf.MONO_HLSB used is different to that used by the ssd1306 screen ( framebuf.MONO_VLSB). This is handled transparently by the framebuffer when blitting. Packing script A command-line packing script is given below (and you can download it here), which can be used to pack a PGM into a 1bpp bitstream. The script accepts a single filename of a PGM file to process, and outputs the resulting packed bit data as <filename>.bin. import os import sys fn = sys.argv[1] with open(fn, 'rb') as f: f.readline() # Magic number f.readline() # Creator comment f.readline() # Dimensions f.readline() # Max value, 255 data = bytearray(f.read()) p = [] for i in range(0, len(data), 8): byte = 0 for n, bit in enumerate(data[i:i+8]): byte += 2**(7-n) if bit == 255 else 0 p.append(byte) b = bytearray(p) basename, _ = os.path.splitext(fn) with open('%s.bin' % basename, 'wb') as f: f.write(b) The resulting file is 1KB in size, and identical to a .pbm format file, minus the header and with colours inverted (this makes display simpler). python pack.py scatman.1.pgm ls -l -rw-r--r-- 1 martin staff 1024 26 Aug 18:11 scatman.bin -rw-r--r-- 1 martin staff 8245 26 Aug 18:02 scatman.pgm To upload your BIN file to the controller — ampy --port /dev/tty.wchusbserial141120 put scatman.bin Since we've stripped off the PGM header, the resulting file can be read directly into a bytearray. with open('scatman.bin', 'rb') as f: data = bytearray(f.read()) fbuf = framebuf.FrameBuffer(data, 128, 64, framebuf.MONO_HLSB) The colours were inverted in our bit packer so we can just blit the framebuffer directly without inverting the display. display.blit(fbuf, 0, 0) display.show() Animation Both the PBM and PGM images are 1KB in memory once loaded, leaving us plenty of space to load multiple images and animate them. The following loads a series of Scatman John PBM images and animates them in a loop. from machine import I2C, Pin import ssd1306 import time import framebuf i2c = I2C(-1, Pin(5), Pin(4)) display = ssd1306.SSD1306_I2C(128, 64, i2c) images = [] for n in range(1,7): with open('scatman.%s.pbm' % n, 'rb') as f: f.readline() # Magic number f.readline() # Creator comment f.readline() # Dimensions data = bytearray(f.read()) fbuf = framebuf.FrameBuffer(data, 128, 64, framebuf.MONO_HLSB) images.append(fbuf) display.invert(1) while True: for i in images: display.blit(i, 0, 0) display.show() time.sleep(0.1) The resulting animation — The image distortion is due to frame rate mismatch with the camera and won't be visible in person. Optimization There is still plenty of room left for optimization. For static images there are often multiple consecutive blocks of bits of the same colour (think backround regions) or regular patterns (dithering). By setting aside a few bits as repeat markers we could compress these regions down to a single pattern, at the cost of random larger files for very random images and unpacking time. We could get away with a lot less data for the animation (particularly the example above) by storing only frame deltas (changes), and using key frames. But we'd also need masking, and that takes memory... and yeah. Let's not, for now.
https://www.mfitzp.com/tutorials/displaying-images-oled-displays/
CC-MAIN-2021-43
refinedweb
1,929
67.76
New, easy to use md5 source and utility released tonight on SourceForge:. If you have a C compiler handy, you can cut and paste a single source file and you are on your way. With the news that SHA1 is compromised/dead, some software that was using this hash for secure signing (mine) needs new hashing code. The obvious choice is md5 and there is plenty of code out there. However, this code is either part of some monolithic system or old and rains down compiler warnings (or even errors). That does not work for me. I need to be able to quickly and easily build verifiable code. Downloading an entire cryptographic library and finding every dependency to build it is ridiculous. This is a (relatively) simple block of code. I want one file that simply compiles with vanilla C. Thanks. Many have complained about the fact that a lot (most) of the open-source code out there is practically impossible to compile and run `out of the box'. This is true; it seems, even for the people that built the code. Despite protestations to the contrary, a lot of the open source stuff that I try to adapt is idiosyncratic and downright buggy. While putting together the present utility, I discovered bugs, compiler warnings, etc in the code that was out there. This is supposed to be library code. One of the examples I found in a number of places failed to close the file handle every time it opened a file. That can be a devilish thing to track down when the code is part of a big system. As in another file that I released (b64.c), I have produced what I wished I could have found. The base64 code that I wrote was not widely used, but it was used and I was thanked for it. You don't need to get all squishy with thanks, but since this is the very first release, I would appreciate it if some of the coders here could take a quick compile and run of this program to make sure it's ok. There is a little package with compile batch files and regression test stuff at SourceForge. However, SourceForge is down right now, so in the interest of getting on with it, here's the only file you really need. There are command lines for compiling in the header material. To keep it short and sweet, you should be able to compile this the same as `hello world'. Enjoy. Here's the 'syntax box' from the program: md5 (create md5 hash) Bob Trower 03/11/05 (C) Copr Bob Trower 1986-2005. Version 0.00B Usage: md5 [-option] <Input> [testhash] Purpose: This program is a simple utility that implements the md5 hashing algorithm (RFC1321). Options: -f Input is filename. -s Input is string. -h This help text. -? This help text. -t Self Test. -v Verify file hash. Note: -s Is the default. It hashes the input as a string Returns: 0 = success. Non-zero is an error code. ErrCode: 1 = Bad Syntax 2 = File Open error 3 = File I/O error 4 = Missing input Example: md5 -s Some_String <- hash that string. md5 -f SomeFileName <- hash that file. md5 -t <- Perform Self Test. md5 -v filename, testhash <- Verify file hash. Source: Source code and latest releases can be found at: Release: 0.00.00, Fri Mar 11 03:30:00 2005, ANSI-SOURCE C /*********************************************************************\ MODULE NAME: md5.c AUTHOR: Bob Trower 03/11/05 PROJECT: Crypt Data Packaging NOTES: This is free software. This source code may be used as you wish, subject to the LGPL license. See the LICENCE section below. Canonical source should be at: This is a big header for a little utility, but it is designed to be self-contained, so this is pretty much the complete package in one file. DESCRIPTION: This little utility implements the md5 Message-Digest Algorithm described in RFC1321 (). DESIGN GOALS: Specifically: Code is a stand-alone utility to perform md5 hashing.: Note that this program has a 'self test' function that tests the inputs given in the RFC document. The following are additional tests on the program itself and using test vectors from files. case 0:empty file: CASE0.DAT Hash Verified, errorlevel is: 0 case 1:One input character (a): CASE1.DAT Hash Verified, errorlevel is: 0 case 2:Three input characters (abc): CASE2.DAT Hash Verified, errorlevel is: 0 case 3:'message digest': CASE3.DAT Hash Verified, errorlevel is: 0 case 4:The alphabet: CASE4.DAT Hash Verified, errorlevel is: 0 case 5:AlphaNumeric Characters: CASE5.DAT Hash Verified, errorlevel is: 0 case 6:Lots of numbers: CASE6.DAT Hash Verified, errorlevel is: 0 case 7: Large files: Tested 67 MB file (OOo_1.1.4_Win32Intel_install.zip). Correct hash as tested against another md5 program. case 8: Very Large Files: Tested ISO images for Mandrake Linux Correct hash. Approximately 25-40MB/sec on 1GHz machine. Times were the same to copy the files to the nul device, so it is likely that performance is simply I/O bound for this application. case 9 Stress: All files in a working directory hashed. Spot checked to ensure correct hashes and ensure that multiple runs do not cause problems such as exhausting file handles, tmp storage, etc. ------------- Syntax, operation and failure: All options/switches tested. Performs as expected. case 10: No Args -- Shows Usage Screen md5 Return Code 1 (Invalid Syntax) case 11: One Arg -- Defaults to hashing as string md5 "message digest" Return Code 0 (Success) Hash is correct. case 12: One Arg Help (-?) -- Shows detailed Usage Screen. Return Code 0 (Success -- help request is valid). case 13: One Arg Help (-h) -- Shows detailed Usage Screen. Return Code 0 (Success -- help request is valid). case 14: One Arg -'f' (valid) -- Uses stdin/stdout (filter) md5 -f < CASE3.DAT Return Code 0 (Success) CASE3.DAT used -- hash matches correctly. case 15: Two Args (invalid filename) -- shows system error. md5 -f :Is:Not:A\Valid/FileName Return Code 2 (File Error) case 16: hash non-existent file -- shows system error. md5 -f NotLikelyAFileName.xyz Return Code 2 (File Error) case 17: Invalid disk -- shows system error. md5 -f y:NoDiskHere Return Code 2 (File Error) case 18: Too many args -- shows system error. md5 x y Return Code 1 (Invalid Syntax) case 19: Missing Args -- shows system error. md5 -s md5:004:Missing input -- nothing to hash. Return Code 4 (Missing input) case 20: Verify Option Missing Args -- shows error. md5 -v FileNameButNoHash md5:004:Missing input -- nothing to hash. Return Code 4 (Missing input) case 21: Verify Option Too Many Args -- shows error. md5 -v x y z md5:006:Syntax: Too many arguments. Return Code 1 (Invalid Syntax) case 22: Verify -- Syntax Ok, verify fails. md5 -v CASE3.DAT bogushashvalue bogushashvalue << Expected Hash Value f96b697d7cb7938d525a2f31aaf161d0 << Actual Hash Value Hash not verified. No match. md5:007:Test Failure. Return Code 7 (Test Failure) case 23: Verify -- Verify passes.) case 24: Self Test md5 -t d41d8cd98f00b204e9800998ecf8427e << Expected Hash Value d41d8cd98f00b204e9800998ecf8427e << Actual Hash Value 0cc175b9c0f1b6a831c399e269772661 << Expected Hash Value 0cc175b9c0f1b6a831c399e269772661 << Actual Hash Value 900150983cd24fb0d6963f7d28e17f72 << Expected Hash Value 900150983cd24fb0d6963f7d28e17f72 << Actual Hash Value f96b697d7cb7938d525a2f31aaf161d0 << Expected Hash Value f96b697d7cb7938d525a2f31aaf161d0 << Actual Hash Value c3fcd3d76192e4007dfb496cca67e13b << Expected Hash Value c3fcd3d76192e4007dfb496cca67e13b << Actual Hash Value0.DAT d41d8cd98f00b204e9800998ecf8427e << Expected Hash Value d41d8cd98f00b204e9800998ecf8427e << Actual Hash Value Writing CASE1.DAT 0cc175b9c0f1b6a831c399e269772661 << Expected Hash Value 0cc175b9c0f1b6a831c399e269772661 << Actual Hash Value Writing CASE2.DAT 900150983cd24fb0d6963f7d28e17f72 << Expected Hash Value 900150983cd24fb0d6963f7d28e17f72 << Actual Hash Value Writing CASE3.DAT f96b697d7cb7938d525a2f31aaf161d0 << Expected Hash Value f96b697d7cb7938d525a2f31aaf161d0 << Actual Hash Value Writing CASE4.DAT c3fcd3d76192e4007dfb496cca67e13b << Expected Hash Value c3fcd3d76192e4007dfb496cca67e13b << Actual Hash Value Writing CASE5.DAT Writing CASE6.DAT7.DAT Writing CASE8.DAT Self Test Passed Return Code 0 (Success) case 25: Test convert test hash to lowercase for comparison.) ------------- Compile/Regression test: gcc compiled binary under Cygwin: gcc md5.c -omd5.exe Microsoft Visual Studio under Windows 2000 cl md5.c Microsoft Version 6.0 C under Windows 98+ cl md5.c DEPENDENCIES: None LICENCE: NOTE: This license should be liberal enough for most purposes while still offering some protection to the code. If you find the license a problem, get in touch through and we will see what we can do. In particular, those who have been kind enough to make the original sources and other materials available can expect to use the code with more liberal permissions. CREDITS: Algorithm and (I think) sample code for the RFC was done by Ron Rivest. Colin Plumb wrote a public domain version in 1993. Some of this code derives from code that derives from that. From a header in one of the sources used to create this file: parts of this file are : Written March 1993 by Branko Lankester Modified June 1993 by Colin Plumb for altered md5.c. Modified October 1995 by Erik Troan for RPM Although not used, code supplied by Langfine Ltd. was consulted and used for some of the validation. Although it was not used, code by John Walker was consulted. John is a source of inspiration. His actions speak for themselves. You can find lots of other neat stuff at his website: VERSION HISTORY: Bob Trower 03/11/05 -- Create Version 0.00.00B \******************************************************************* */ #include <stdio.h> #include <string.h> #include <errno.h> /* ** typedefs for convenience */ typedef unsigned long mULONG; typedef unsigned char mUCHAR; typedef struct { mULONG hash[4]; mULONG bits[2]; mUCHAR data[64]; } MD5Context; /* Basic MD5 functions */ #define F1(x, y, z) (z ^ (x & (y ^ z))) #define F2(x, y, z) (y ^ (z & (x ^ y))) #define F3(x, y, z) (x ^ y ^ z) #define F4(x, y, z) (y ^ (x | ~z)) /* This is the central step in the MD5 algorithm. */ #define TRANSFORM(f, w, x, y, z, data, s) \ ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x ) /* ** ** md5_transform ** ** The MD5 "basic transformation". Updates the hash ** based on the data block passed. ** */ static void md5_transform( mULONG hash[ 4 ], const mULONG data[ 16 ] ) { mULONG a = hash[0], b = hash[1], c = hash[2], d = hash[3]; /* Round 1 */ TRANSFORM( F1, a, b, c, d, data[ 0] + 0xd76aa478, 7); TRANSFORM( F1, d, a, b, c, data[ 1] + 0xe8c7b756, 12); TRANSFORM( F1, c, d, a, b, data[ 2] + 0x242070db, 17); TRANSFORM( F1, b, c, d, a, data[ 3] + 0xc1bdceee, 22); TRANSFORM( F1, a, b, c, d, data[ 4] + 0xf57c0faf, 7); TRANSFORM( F1, d, a, b, c, data[ 5] + 0x4787c62a, 12); TRANSFORM( F1, c, d, a, b, data[ 6] + 0xa8304613, 17); TRANSFORM( F1, b, c, d, a, data[ 7] + 0xfd469501, 22); TRANSFORM( F1, a, b, c, d, data[ 8] + 0x698098d8, 7); TRANSFORM( F1, d, a, b, c, data[ 9] + 0x8b44f7af, 12); TRANSFORM( F1, c, d, a, b, data[10] + 0xffff5bb1, 17); TRANSFORM( F1, b, c, d, a, data[11] + 0x895cd7be, 22); TRANSFORM( F1, a, b, c, d, data[12] + 0x6b901122, 7); TRANSFORM( F1, d, a, b, c, data[13] + 0xfd987193, 12); TRANSFORM( F1, c, d, a, b, data[14] + 0xa679438e, 17); TRANSFORM( F1, b, c, d, a, data[15] + 0x49b40821, 22); /* Round 2 */ TRANSFORM( F2, a, b, c, d, data[ 1] + 0xf61e2562, 5); TRANSFORM( F2, d, a, b, c, data[ 6] + 0xc040b340, 9); TRANSFORM( F2, c, d, a, b, data[11] + 0x265e5a51, 14); TRANSFORM( F2, b, c, d, a, data[ 0] + 0xe9b6c7aa, 20); TRANSFORM( F2, a, b, c, d, data[ 5] + 0xd62f105d, 5); TRANSFORM( F2, d, a, b, c, data[10] + 0x02441453, 9); TRANSFORM( F2, c, d, a, b, data[15] + 0xd8a1e681, 14); TRANSFORM( F2, b, c, d, a, data[ 4] + 0xe7d3fbc8, 20); TRANSFORM( F2, a, b, c, d, data[ 9] + 0x21e1cde6, 5); TRANSFORM( F2, d, a, b, c, data[14] + 0xc33707d6, 9); TRANSFORM( F2, c, d, a, b, data[ 3] + 0xf4d50d87, 14); TRANSFORM( F2, b, c, d, a, data[ 8] + 0x455a14ed, 20); TRANSFORM( F2, a, b, c, d, data[13] + 0xa9e3e905, 5); TRANSFORM( F2, d, a, b, c, data[ 2] + 0xfcefa3f8, 9); TRANSFORM( F2, c, d, a, b, data[ 7] + 0x676f02d9, 14); TRANSFORM( F2, b, c, d, a, data[12] + 0x8d2a4c8a, 20); /* Round 3 */ TRANSFORM( F3, a, b, c, d, data[ 5] + 0xfffa3942, 4); TRANSFORM( F3, d, a, b, c, data[ 8] + 0x8771f681, 11); TRANSFORM( F3, c, d, a, b, data[11] + 0x6d9d6122, 16); TRANSFORM( F3, b, c, d, a, data[14] + 0xfde5380c, 23); TRANSFORM( F3, a, b, c, d, data[ 1] + 0xa4beea44, 4); TRANSFORM( F3, d, a, b, c, data[ 4] + 0x4bdecfa9, 11); TRANSFORM( F3, c, d, a, b, data[ 7] + 0xf6bb4b60, 16); TRANSFORM( F3, b, c, d, a, data[10] + 0xbebfbc70, 23); TRANSFORM( F3, a, b, c, d, data[13] + 0x289b7ec6, 4); TRANSFORM( F3, d, a, b, c, data[ 0] + 0xeaa127fa, 11); TRANSFORM( F3, c, d, a, b, data[ 3] + 0xd4ef3085, 16); TRANSFORM( F3, b, c, d, a, data[ 6] + 0x04881d05, 23); TRANSFORM( F3, a, b, c, d, data[ 9] + 0xd9d4d039, 4); TRANSFORM( F3, d, a, b, c, data[12] + 0xe6db99e5, 11); TRANSFORM( F3, c, d, a, b, data[15] + 0x1fa27cf8, 16); TRANSFORM( F3, b, c, d, a, data[ 2] + 0xc4ac5665, 23); /* Round 4 */ TRANSFORM( F4, a, b, c, d, data[ 0] + 0xf4292244, 6); TRANSFORM( F4, d, a, b, c, data[ 7] + 0x432aff97, 10); TRANSFORM( F4, c, d, a, b, data[14] + 0xab9423a7, 15); TRANSFORM( F4, b, c, d, a, data[ 5] + 0xfc93a039, 21); TRANSFORM( F4, a, b, c, d, data[12] + 0x655b59c3, 6); TRANSFORM( F4, d, a, b, c, data[ 3] + 0x8f0ccc92, 10); TRANSFORM( F4, c, d, a, b, data[10] + 0xffeff47d, 15); TRANSFORM( F4, b, c, d, a, data[ 1] + 0x85845dd1, 21); TRANSFORM( F4, a, b, c, d, data[ 8] + 0x6fa87e4f, 6); TRANSFORM( F4, d, a, b, c, data[15] + 0xfe2ce6e0, 10); TRANSFORM( F4, c, d, a, b, data[ 6] + 0xa3014314, 15); TRANSFORM( F4, b, c, d, a, data[13] + 0x4e0811a1, 21); TRANSFORM( F4, a, b, c, d, data[ 4] + 0xf7537e82, 6); TRANSFORM( F4, d, a, b, c, data[11] + 0xbd3af235, 10); TRANSFORM( F4, c, d, a, b, data[ 2] + 0x2ad7d2bb, 15); TRANSFORM( F4, b, c, d, a, data[ 9] + 0xeb86d391, 21); hash[ 0 ] += a; hash[ 1 ] += b; hash[ 2 ] += c; hash[ 3 ] += d; } /* ** md5_init ** ** Initialise md5 context structure ** */ void md5_init( MD5Context *ctx ) { ctx->hash[ 0 ] = 0x67452301; ctx->hash[ 1 ] = 0xefcdab89; ctx->hash[ 2 ] = 0x98badcfe; ctx->hash[ 3 ] = 0x10325476; ctx->bits[ 0 ] = 0; ctx->bits[ 1 ] = 0; } /* ** md5_update ** ** Update context with the next buffer from the stream of data. ** Call with each block of data to update the md5 hash. ** */ void md5_update( MD5Context *ctx, const mUCHAR *buf, mULONG buflen ) { mULONG idx; /* Update bitcount */ idx = ctx->bits[ 0 ]; ctx->bits[ 0 ] = idx + (buflen << 3); if( ctx->bits[ 0 ] < idx ) { ctx->bits[ 1 ]++; /* Carry from low to high */ } ctx->bits[ 1 ] += buflen >> 29; idx = (idx >> 3) & 0x3f; /* Bytes already in ctx->data */ /* Handle any leading odd-sized chunks */ if( idx != 0 ) { mUCHAR *p = (mUCHAR *) ctx->data + idx; idx = 64 - idx; if( buflen < idx ) { memcpy( p, buf, (size_t) buflen ); } else { memcpy( p, buf, (size_t) idx ); md5_transform( ctx->hash, (mULONG *) ctx->data ); buf += idx; buflen -= idx; } } if( buflen >= idx ) { while( buflen >= 64 ) { memcpy( ctx->data, buf, 64 ); md5_transform( ctx->hash, (mULONG *) ctx->data ); buf += 64; buflen -= 64; } memcpy( ctx->data, buf, (size_t) buflen ); } } /* ** md5_final ** ** Finalize creation of md5 hash and copy to digest buffer. ** */ void md5_final( MD5Context *ctx, mUCHAR digest[ 16 ] ) { mULONG count; mUCHAR *pad; count = (ctx->bits[ 0 ] >> 3) & 0x3F; /* Number of bytes mod 64 */ pad = ctx->data + count; *pad++ = 0x80; /* Bytes of padding needed to make 64 bytes */ count = 64 - 1 - count; /* Pad out to 56 mod 64 */ if( count < 8 ) { /* Two lots of padding: Pad the first block to 64 bytes */ memset( pad, 0, (size_t) count ); md5_transform( ctx->hash, (mULONG *) ctx->data ); /* Now fill the next block with 56 bytes */ memset( ctx->data, 0, 56 ); } else { /* Pad block to 56 bytes */ memset( pad, 0, (size_t) (count - 8) ); } /* Append length in bits and transform */ ((mULONG *) ctx->data)[ 14 ] = ctx->bits[ 0 ]; ((mULONG *) ctx->data)[ 15 ] = ctx->bits[ 1 ]; md5_transform( ctx->hash, (mULONG *) ctx->data ); memcpy( digest, ctx->hash, 16 ); } /* ** md5_digest_string ** ** Supply the digest and a buffer for the string. ** This routine will populate the buffer and ** return the value as a C string. ** */ char *md5_digest_string( mUCHAR d[ 16 ], char digest_string[ 33 ] ) { int i; digest_string[ 32 ] = 0; for( i = 0; i < 16; i++ ) { sprintf( &(digest_string[ i * 2 ]), "%2.2x", d[ i ] ); } return( digest_string ); } /* ** returnable errors ** ** Error codes returned to the caller ** and to the operating system. ** */ #define MD5_SYNTAX_ERROR 1 #define MD5_FILE_ERROR 2 #define MD5_FILE_IO_ERROR 3 #define MD5_MISSING_INPUT 4 #define MD5_ERROR_OUT_CLOSE 5 #define MD5_SYNTAX_TOOMANYARGS 6 #define MD5_TEST_FAILURE 7 /* ** md5_message ** ** Gather text messages in one place. ** */ char *md5_message( int errcode ) { #define MD5_MAX_MESSAGES 8 char *msgs[ MD5_MAX_MESSAGES ] = { "md5:000:Invalid Message Code.", "md5:001:Syntax Error -- check help for usage.", "md5:002:File Error Opening/Creating Files.", "md5:003:File I/O Error -- Note: file cleanup not done.", "md5:004:Missing input -- nothing to hash.", "md5:005:Error on output file close.", "md5:006:Syntax: Too many arguments.", "md5:007:Test Failure." }; char *msg = msgs[ 0 ]; if( errcode > 0 && errcode < MD5_MAX_MESSAGES ) { msg = msgs[ errcode ]; } return( msg ); } /* ** ** md5_file ** ** Compute hash on an open file handle. ** */ #define MD5_BUFSIZE 1024 int md5_file( FILE *infile, mUCHAR digest[ 16 ] ) { int retcode; MD5Context ctx; mUCHAR buf[ MD5_BUFSIZE ]; mULONG bytes_read; md5_init( &ctx ); while( (bytes_read = fread (buf, sizeof (mUCHAR), MD5_BUFSIZE, infile)) > 0 ) { md5_update( &ctx, buf, bytes_read ); } if( ferror( infile ) ) { retcode = MD5_FILE_IO_ERROR; } else { md5_final( &ctx, digest ); retcode = 0; } return( retcode ); } /* ** ** md5_filename ** ** Compute the hash on a file. ** */ int md5_filename( const char *infilename, mUCHAR digest[ 16 ] ) { FILE *infile; int retcode = MD5_FILE_ERROR; if( !infilename ) { infile = stdin; } else { infile = fopen( infilename, "rb" ); } if( !infile ) { printf( "Error: FileName='%s' -- %s\n", infilename, strerror( errno ) ); } else { retcode = md5_file( infile, digest ); if( infile != stdin ) { if( fclose( infile ) != 0 ) { char *ErrM = md5_message( MD5_ERROR_OUT_CLOSE ); printf( "Error: %s -- %s\n", ErrM, strerror( errno ) ); retcode = MD5_FILE_IO_ERROR; } } } return( retcode ); } /* ** ** md5_verify_filename ** ** Verify that a given file has a given hash. ** */ int md5_verify_filename( char *infilename, char *hash ) { int retcode = 0; mUCHAR digest[ 16 ]; char digest_string[ 33 ]; char *hd; md5_filename( infilename, digest ); hd = md5_digest_string( digest, digest_string ); printf( "%s << Expected Hash Value\n%s << Actual Hash Value\n", hash, hd ); if( strcmp( hash, hd ) ){ retcode = MD5_TEST_FAILURE; } return( retcode ); } /* ** ** md5_buffer ** ** Compute the md5 hash on a buffer. ** */ void md5_buffer( const mUCHAR *buf, int buflen, mUCHAR digest[ 16 ] ) { MD5Context ctx; md5_init( &ctx ); md5_update( &ctx, buf, buflen ); md5_final( &ctx, digest ); } /* ** ** Standard test vectors and expected hashes. ** Data below is used in the self-test function. ** ** The standard test vectors are augmented by ** a couple more cases to ease regression test. ** */ #define NUM_VECTORS 7 #define NUM_CASES 9 char *test_vector[] = { "", ", "CASE7.DAT should be replaced with your own 10MB to 100MB file\n", "CASE8.DAT should be replaced with your own 100MB+ file\n" }; char *test_hash[] = { ", "04842407f40f4fc21f159bf89a7bf63e", "472c5207d61df9454c1e732930d1c496" }; /* ** ** GenAndTestFileCases() ** ** Generates CASE data files for regression test ** and runs md5_verify_filename check. ** */ int GenAndTestFileCases() { int i; char outfilename[16]; FILE *outfile; int retcode = 0; for( i = 0; i < NUM_CASES && retcode == 0; i++ ) { sprintf( outfilename, "CASE%d.DAT", i ); printf( "Writing %s\n", outfilename ); outfile = fopen( outfilename, "wb" ); if( !outfile ) { printf( "Error: FileName='%s' -- %s\n", outfilename, strerror( errno ) ); } else { if( fprintf( outfile, "%s", test_vector[ i ] ) < 0 ) { printf( "Error: FileName='%s' -- %s\n", outfilename, strerror( errno ) ); retcode = MD5_FILE_IO_ERROR; } if( fclose( outfile ) != 0 ) { char *ErrM = md5_message( MD5_ERROR_OUT_CLOSE ); printf( "Error: %s -- %s\n", ErrM, strerror( errno ) ); retcode = MD5_FILE_IO_ERROR; } else { if( i < NUM_VECTORS ) { retcode = md5_verify_filename( outfilename, test_hash[ i ] ); } } } } return( retcode ); } /* ** ** md5_self_test ** ** Tests the core hashing functions against the ** test suite given in the RFC. ** */ int md5_self_test( void ) { int i, retcode = 0; mUCHAR digest[ 16 ]; char digest_string[ 33 ]; char *tv; char *hd; for( i = 0; i < NUM_VECTORS && retcode == 0; i++ ) { tv = test_vector[ i ]; md5_buffer( (mUCHAR *) tv, strlen( tv ), digest ); hd = md5_digest_string( digest, digest_string ); printf( "%s << Expected Hash Value\n%s << Actual Hash Value\n", test_hash[ i ], hd ); if( strcmp( hd, test_hash[ i ] ) ) { retcode = MD5_TEST_FAILURE; } } if( retcode == 0 ) { retcode = GenAndTestFileCases(); } return( retcode ); } /* ** ** LCaseHex ** ** Forces Hex string to lowercase. ** ** Make sure that we do apples to apples ** comparison of input hash to calculated hash. ** */ static char *LCaseHex( char *h ) { char *p; for( p = h; *p; p++ ) { *p = (char) (*p | 0x20); } return( h ); } /* ** showuse ** ** display usage information, help, version info */ void showuse( int morehelp ) { { printf( "\n" ); printf( " md5 (create md5 hash) Bob Trower 03/11/05 \n" ); printf( " (C) Copr Bob Trower 1986-2005. Version 0.00B \n" ); printf( " Usage: md5 [-option] <Input> [testhash]\n" ); printf( " Purpose: This program is a simple utility that\n" ); printf( " implements the md5 hashing algorithm (RFC1321).\n" ); } if( !morehelp ) { printf( " Use -h option for additional help.\n" ); } else { printf( " Options: -f Input is filename. -s Input is string.\n" ); printf( " -h This help text. -? This help text.\n" ); printf( " -t Self Test. -v Verify file hash.\n" ); printf( " Note: -s Is the default. It hashes the input as a\n" ); printf( " string\n" ); printf( " Returns: 0 = success. Non-zero is an error code.\n" ); printf( " ErrCode: 1 = Bad Syntax 2 = File Open error\n" ); printf( " 3 = File I/O error 4 = Missing input\n" ); printf( " Example: md5 -s Some_String <- hash that string.\n" ); printf( " md5 -f SomeFileName <- hash that file.\n" ); printf( " md5 -t <- Perform Self Test.\n" ); printf( " md5 -v filename, testhash <- Verify file hash.\n" ); printf( " Source: Source code and latest releases can be found at:\n" ); printf( "\n" ); printf( " Release: 0.00.00, Fri Mar 11 03:30:00 2005, ANSI-SOURCE C\n" ); } } #define THIS_OPT(ac, av) (ac > 1 ? av[ 1 ][ 0 ] == '-' ? av[ 1 ][ 1 ] : 0 : 0) /* ** main ** ** parse and validate arguments and call md5 routines or help ** */ int main( int argc, char **argv ) { int opt = 0; int retcode = 0; char *input = NULL; mUCHAR digest[ 16 ]; char digest_string[ 33 ]; while( THIS_OPT( argc, argv ) ) { switch( THIS_OPT(argc, argv) ) { case 'f': opt = 'f'; break; case '?': case 'h': opt = 'h'; break; case 's': opt = 's'; break; case 't': opt = 't'; break; case 'v': opt = 'v'; break; default: opt = 's'; break; } argv++; argc--; } if( ( opt == 'v' && argc > 3) || ((opt !='v') && argc > 2) ) { printf( "%s\n", md5_message( MD5_SYNTAX_TOOMANYARGS ) ); opt = 0; } else { if( opt == 0 && argc == 2 ) { opt = 's'; } } switch( opt ) { case 'f': input = argc > 1 ? argv[ 1 ] : NULL; retcode = md5_filename( input, digest ); break; case 's': input = argc > 1 ? argv[ 1 ] : NULL; if( input ) { md5_buffer( (mUCHAR *) input, strlen( input ), digest ); retcode = 0; } else { retcode = MD5_MISSING_INPUT; } break; case 't': retcode = md5_self_test(); if( retcode == 0 ) { printf( "Self Test Passed\n" ); } else { printf( "Self Test Failed\n" ); } break; case 'v': if( argc < 3 ) { retcode = MD5_MISSING_INPUT; } else { retcode = md5_verify_filename( argv[ 1 ], LCaseHex( argv[ 2 ] ) ); if( retcode == 0 ) { printf( "Hash Verified\n" ); } else { printf( "Hash not verified. No match.\n" ); } } break; case 0: retcode = MD5_SYNTAX_ERROR; case 'h': showuse( opt ); break; } if( retcode ) { printf( "%s\n", md5_message( retcode ) ); } else { if( opt == 'f' || opt == 's' ) { printf( "%s\n", md5_digest_string( digest, digest_string ) ); } } return( retcode ); } You do realize this, don't you? It's been all over Slashdot. Both SHA-1 and MD5 are broken. The best candidates I know of for replacing them are the SHA2 family. <code>SHA2-256</code>, <code>SHA2-384</code>, and <code>SHA2-512</code>. Also, there are many other MD5 implementations out there that are just as simple as yours, so you don't add much posting yours to Advogato. I concentrated so hard on making this darn thing 'fool-proof' that I did not do my due diligence at the other end. I have used MD5 in so many other applications (using other people's code) that I assumed (incorrectly) that if someone was mentioning that SHA-1 was 'broken', they would say something about MD5. Still, mea culpa. As for there being 'many other...just as simple'. Please post a few of these. I reviewed literally dozens of available sources and they were not even close to what I've posted here. What I have posted here is cut, paste and compile. There's nothing to it. If you know of something (one single example) that meets my criteria: 1) Simple vanilla C, single source file, no dependancies, no compiler warnings. 2) Usable license (for me). 3) `Hackability' with reasonable samples of use that can be cut and pasted. 4) Properly validated. None of the code I saw validated beyond the few examples in the RFC. Because of this, I found a few had rather grievous bugs in junk I attempted to hack into something that compiled without warnings. No good deed goes unpunished. I expected flames, so there's no reason to suppose that I'm all shook up about this. Chagrined, though, that's for sure. Happily, the code is still usable on its own. MD5 is not `broken' so badly that it can't be used. Meantime, we can still use the shell, harness and understanding of this algorithm to create another simple utility of a better hash. Again, I am really most curious as to what code you feel is out there that comes close to meeting my criteria. I took a look on SourceForge and with all due respect to the authors of the other code, it is not even a contest. As a side note, I have to say that the number of bits used to secure all of this stuff (encryption and secure hashing) is needlessly inadequate. I have never quite understood that. The only arguments that make any sense are considerations of performance. However, the above code was 100% I/O bound in practical use. Well, have to pack. I will review in a few weeks and see what can be done. SHA1 is not broken yet. In theory a paper has started circulating that shows one potential weakness. It is still a *much* better hash algorithm than md5. md5 has been broken for many years. there are readily available tools out there for generating colliding md5 signature data. web and ftp sites posting md5 sums for integrity checking are fooling themselves while posting sha1s would still be fine. just posting a hash on a web/ftp site is mainly useful for error checking integrity anyways as any respecting trojan maker would just replace the signature file. use gpg signatures with a trusted key if security is the goal. fyi - look at libtomcrypt if you want great single source file public domain implementations of todays standard hash algorithms. just paste one of those into your own program if you hate libraries. Are you saying that with a know size and a md5 signature that there are utilities can can make a useful file? I suppose that you could create a trojan much smaller than the size and then fill the rest of the file with pad to make the md5 hash the same, but what has stopped us doing this since signatures started? How has this changed? Regards Dave yes! I believe the core issue here is what 'broken' means. The word is highly suggestive, and in that sense the use of it is highly misleading. I prefer to be more precise, myself, but when someone writes that a hash is 'broken' means something like a theory has been devised that shows there's a better way of finding a collision than the brute force method (Which requires computation of hash codes for billions of messages). For example, in a 64 bit hash, you might need to supply 2^32 messages before you can find a collision. If you find a little loophole in the hash that lets you reduce the number of computations by a noticeable percentage, then according to some, you've broken the hash. I think both MD5 and SHA1 are possibly "broken" according to the reports; however, I have not looked at them thoroughly. The real question is, does it matter? Not necessarily, it depends on how much weaker the hash has become. It would help to be more precise. In my opinion you would still be better off using SHA1 than MD5. But for all I know that could change tomorrow. Being broken does not mean someone has found a way yet to surreptitiously replace data without changing the hash after 10 minutes of computation, (although if the attacker could that hash is not only broken but unsafe), replacing data is a much more complicated problem for an attacker to solve... Not only do they need to be able to find collisions, they need to be able to find collisions that suit their needs than managing to find one colliding message after 12 weeks worth of computation on a cluster of several hundred computers. (Collisions that inject their preferred semantics, at least for program/text content is a smaller set of collisions they need to find to implant data, and getting that IMO, would pretty much mean they've found a way not only to get the collisions but they've got a pattern and can predict where they'll be). Mysidia: Both are broken in a stronger sense than you are suggesting, but it doesn't matter to everyone. If I understand correctly, the breach is a special sort of chosen plaintext attack which depends upon iteratively passing a potentially sizeable, but feasibly sizeable, number of plaintext messages to be encrypted. This means that many protocols making use of MD5 and SHA1 are still safe, because they don't give attackers the opportunity to pass on enough of the plaintext messages they need for their compromise, but equally, surprisingly many protocols are at risk of attack. In brief, MD5 and SHA1 are no longer really fit to be called cryptographically secure for the purposes of securing applications, but they aren't broken in a completely transparent!
http://www.advogato.org/article/830.html
crawl-001
refinedweb
4,885
69.62
To create a folder in python just call os.mkdir. E.g. create file mkfolder.py: import os os.mkdir('fol_in_pwd') This will create a folder in the current PWD. NOTE: PWD is not folder that contains script, but folder where the process was executed e.g. if you are located in /home/user/ calling python scripts/mkfolder.py will create /home/user/fol_in_pwd/ but not /home/user/scripts/fol_in_pwd/ NOTE: To check the current location in Linux/Mac terminal use pwd, on Windows use cdwithout arguments Create a folder in python script folder To create a folder in python script near the script itself: - Find the absolute path of a script with os.path.realpath(__file__) - Create an absolute path of a new folder with os.path.join - Call os.mkdirpassing formed an absolute path import os script_path = os.path.realpath(__file__) new_abs_path = os.path.join(script_path, 'fol_near_script') os.mkdir(new_abs_path) Now if you are in /home/user/ calling python scripts/mkfolder.py will create /home/user/scripts/fol_in_pwd/ The safe way in python – create folder if not exists Just call os.path.exists before actually call create and check returned result – if it returns True, then filter exists and you should do nothing: import os import sys script_path = os.path.realpath(__file__) new_abs_path = os.path.join(script_path, 'fol_near_script') if not os.path.exists(new_abs_path): os.mkdir(new_abs_path) So now it will create a folder only if it does not exist, otherwise, you don't have to create a folder at all.
https://hinty.io/brucehardywald/how-to-create-folder-in-python/
CC-MAIN-2021-21
refinedweb
253
60.01
SMB Printing 2. Setting Up Identity Mapping Between Windows and Oracle Solaris Systems 3. Setting Up a Oracle Solaris SMB Server to Manage and Share Files 4. Using SMB File Sharing on Client Systems The Distributed File System (DFS) feature is supported by the SMB server. For more information, see the Microsoft DFS documentation. Currently, the SMB server supports only one stand-alone DFS namespace per system. No configuration is required on the SMB server to use the DFS feature. You can use the DFS tools that are available on Windows systems to create and manage the stand-alone namespace in the Oracle Solaris OS.
http://docs.oracle.com/cd/E26502_01/html/E29004/dfssupport.html
CC-MAIN-2016-18
refinedweb
105
58.38
PyScan User Push Button Hi Everyone, I'm totally new to all this, so please bear with me. I've got a PyScan Expansion Board with a lopy4 mounted. It all works great but I'm trying to figure out how to use the push button on the expansion board. Ultimately I want to use it to wake from deep sleep... but right now I'd be really happy if I could just read it! In an attempt to try and discover what it was connected to, I wrote the code below. Alas it didn't help as I cant see any change when pressing the button. Any and all help very much appreciated :) from machine import Pin while True: time.sleep(0.2) p_inP2 = Pin('P2', mode=Pin.IN, pull=Pin.PULL_UP) p_inP3 = Pin('P3', mode=Pin.IN, pull=Pin.PULL_UP) p_inP4 = Pin('P4', mode=Pin.IN, pull=Pin.PULL_UP) p_inP6 = Pin('P6', mode=Pin.IN, pull=Pin.PULL_UP) p_inP8 = Pin('P8', mode=Pin.IN, pull=Pin.PULL_UP) p_inP9 = Pin('P9', mode=Pin.IN, pull=Pin.PULL_UP) p_inP10 = Pin('P10', mode=Pin.IN, pull=Pin.PULL_UP) p_inP13 = Pin('P13', mode=Pin.IN, pull=Pin.PULL_UP) p_inP14 = Pin('P14', mode=Pin.IN, pull=Pin.PULL_UP) #THIS ONE?? p_inP15 = Pin('P15', mode=Pin.IN, pull=Pin.PULL_UP) p_inP16 = Pin('P16', mode=Pin.IN, pull=Pin.PULL_UP) p_inP17 = Pin('P17', mode=Pin.IN, pull=Pin.PULL_UP) p_inP18 = Pin('P18', mode=Pin.IN, pull=Pin.PULL_UP) p_inP19 = Pin('P19', mode=Pin.IN, pull=Pin.PULL_UP) p_inP20 = Pin('P20', mode=Pin.IN, pull=Pin.PULL_UP) p_inP21 = Pin('P21', mode=Pin.IN, pull=Pin.PULL_UP) p_inP23 = Pin('P23', mode=Pin.IN, pull=Pin.PULL_UP) print('Button Values %(a)s %(b)s %(c)s %(d)s %(e)s %(f)s %(g)s %(h)s xx %(i)s %(j)s %(k)s %(l)s %(m)s %(n)s %(o)s %(p)s %(q)s' % {'a': p_inP2(), 'b': p_inP3(), 'c': p_inP4(), 'd': p_inP6(), 'e': p_inP8(), 'f': p_inP9(), 'g': p_inP10(), 'h': p_inP13(), 'i': p_inP14(), 'j': p_inP15(), 'k': p_inP16(), 'l': p_inP17(), 'm': p_inP18(), 'n': p_inP19(), 'o': p_inP20(), 'p': p_inP21(), 'q': p_inP23()}) @GreenGrouch Try to move the line "p_inP14 = Pin ..." before the while instruction - Paul Thornton last edited by Hey, Had a look into this. It looks to be a case of terrible naming on the sheet. That button should not actually do anything but put it in firmware update mode. @robert-hh thanks for the reply - I'm totally lost as to how this push button was intended to work, it feels like it should be super simple! Would really help if someone from PYCOM could help out / @Paul-Thornton @greengrouch Nothing is defective. It is just that the Input wire picks up noise induced by your finger. P14 is an input only pin, and it does not support the PULL option. From what it looks like, there seems to be no external PULL resistor on the board. Checking it with a DMM at my PySense, it seems not to have any external PULL, and no direct connection to P14. Powering just the PySense reveals 3.3V at the switch, but not level change at P14 (or any other pin) when pushing the switch. So let's assume that the User button is connected to the PIC. On a PyTrack, the switch is connected to P14, and it seems to have an external Pull-up resistor. Since PYCOM IS TOO SHY TO PUBLISH THE SCHEMATICS, even of the expansion boards, I can only guess. @Paul-Thornton, maybe you could check whether and how the user button is connected. B,.t.w. What happened to the promise of Daniel to publish the PIC software? @greengrouch said in PyScan User Push Button: Please help! Is my unit defective? - Remove the "h"s from hhhmode. The parameter is called mode. - Move the pin init out of the loop. - If this does not work try Pin.PULL_DOWN instead of Pin.PULL_UP @alexpul I tried my program on pin 14 and it doesn't seem to work. Please see this video: I hover my finger over the button (but I don't press it) and you can see the value for P14 change. When I remove my finger there is some lag and it changes back to 0. When I press the user button with my pen there is no change in the value. What might be happening is that P14 is connected to a light sensor? Please help! Is my unit defective? Here is a script that works for my WiPy with PyTrack board to wake the device from deep sleep when the button is pushed import machine #machine library machine.pin_deepsleep_wakeup(['P14'], machine.WAKEUP_ALL_LOW, False) #set up interrupt machine.deepsleep(10*1000) #deep sleep for 10s 'P14' is the pin that corresponds to the user push button on the PyTrack. Let me know if anything else needs clarification!
https://forum.pycom.io/topic/4353/pyscan-user-push-button/5?lang=en-US
CC-MAIN-2020-29
refinedweb
815
68.36