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
A script for analyzing tournament replay packs Project description Replay Parsing for Tournament Replay Packs This is a script for parsing tournament replay packs. It recursively searches sub-directories for replay files, then parses the replays using the Zephyrus Replay Parser. You can inject a function to analyze output data. Analyzed data is aggregated and stored, then exported as JSON. Information from directory names such as group, BoX and player names can be also be parsed and associated with replay data. Installation and Usage This script is hosted on PyPI and can be installed with pip pip install recursive_parse The recursive_parse function is imported by default import recursive_parse Required Arguments There are 2 required keyword arguments for the function: sub_dir and data_function. sub_dir specifies the relative path of the replays you want to parse from the location of the script dir/ analysis.py <-- recursive_parse called here replays/ ... sub_dir = 'replays' data_function is a function supplied by the user to analyze output data from parsed replays. Returned data is appended to a list which is exported as JSON after all replays have been parsed. You can access all the information available from parsed replay ( players, timeline, stats, metadata) as well as enclosed information in your supplied function via kwargs. This includes default values and any information parsed from directory names. Defaults currently available are ignore_units and merge_units. ignore_units is a list of temporary unit which are usually not wanted. merge_units is a dictionary in the format of <unit name>: <changed name>. It can be used to merge information from different unit modes or to re-name a unit, such as LurkerMP --> Lurker. Optional Arguments recursive_parse takes 2 optional keyword arguments: player_match and identifiers. Both are RegEx patterns that parse information from directory names. player_match is specifically for parsing player names from directories. It takes a list of tuples of RegEx patterns and the type of search to perform. Ex: (<pattern>, <search type>) You can choose between search or split for search type, but the last pattern must be a split to separate the player names. The default patterns are: standard_player_match = [ ('\\w+ +[v,V][s,S]\\.? +\\w+', 'search'), ('.vs\\.?.', 'split'), ] identifiers is for parsing information from directory names. It contains a list of tuples of RegEx patterns and the chosen name of the pattern. It has no default patterns. Ex: (<pattern name>, <pattern>) The list of tuples can be accessed through kwargs['identifier'] in your data_function. Example The hsc_analysis.py file is an example of usage for replay files from HSC XX. The parse_data function loops through each player's units and buildings that were created during the game and records information about the unit/building and game. It also indentifies and stores groups that players were in. Exporting Data Data is exported as JSON to a JSON file by default, but you can use the json_to_csv.py file to create a CSV file from the JSON data. In future there will be an option to define a data schema as an argument for recursive_parse. Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/sc2-tournament-analysis/
CC-MAIN-2021-04
refinedweb
531
56.45
For some reason the ball is still going off the top of the frame. Im not sure why. import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; Type: Posts; User: NathanWick For some reason the ball is still going off the top of the frame. Im not sure why. import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; I am declaring the borderlessDimension before I declare the frame and set it Visible, let me try declaring it after --- Update --- Dude thanks so much! I feal like an idiot now haha So im using the this.getContentPane().getSize(); to set a Dimension variable called borderlessSize (because its supposed to contain the size of the frame excluding the borders) and then im setting an... I understand how to access the Width, Height, X, Y coordinates and everything, however how would I used those in order to test whether or not the two objects are colliding? yeah but how would i do that? I'm making a game where a ball bounces around the screen, and i was wondering how you would test if the ball (just a jlabel with an icon) collides with another square in the middle of the... Thank you so much :D! I made a game where basically, a ball (A JLabel with the icon set to a ball image from my computer) bounces across the screen, and when you click it, the speed increases. When I exported the game, it...
http://www.javaprogrammingforums.com/search.php?s=db2970609243516486bc47db9679e9ba&searchid=837612
CC-MAIN-2014-15
refinedweb
256
75.71
I am having a problem with this error when I am trying to use a function for a button. Everything works fine when I have it on frame 1, but when I add a preloader to frame 1 and put my content on frame two I recieve the #1009 error. When I tested my code with just a simple function I still got the error. the code is below, Any help would be greatly appreciated! ****Code for Preloader(Frame1)******* stop(); loaderInfo.addEventListener(ProgressEvent.PROGRESS, updatePreloader); function updatePreloader(evtObj:ProgressEvent):void { var percent:Number = Math.floor((evtObj.bytesLoaded*100)/evtObj.bytesTotal); preloader_txt.text=percent+"%"; if (percent>=100){ nextFrame(); } } ****Code for Main Content (Frame 2)**** stop(); //Import the necessary files for all of the tweening //-------------------------------------------------------- import fl.transitions.Tween; import fl.transitions.TweenEvent; import fl.transitions.easing.*; //--------------------------------- //Move all of the text off screen and set them invisible //-------------------------------------------------------- featuresText_mc.alpha=0; featuresText_mc.y=-500; viewCottageText_mc.y=-500; rateInfo_mc.alpha=0; rateInfo_mc.y=-500; viewCottageText_mc.alpha=0; contactInfoText_mc.alpha=0; //-------------------------------------------------------- viewCottage_btn.addEventListener(MouseEvent.CLICK, goCottage); function goCottage(evtObj:MouseEvent){ trace("test") } ***Any Help would be greatly Appreciated*** click file/publish settings/flash and tick "permit debugging" and retest to pinpoint your error. the frame and line number that's causing the error will be displayed. I have pinpointed the problem being the function that I am trying to call, but I still do not know why it is giving me a problem. I am assuming that something has not been initiated on stage from what I have read, but I have no clue how to fix it. Thanks. viewCottage_btn.addEventListener(MouseEvent.CLICK, goCottage); function goCottage(evtObj:MouseEvent) { trace("test") } kglad, I believe you have helped billygoatkareoke out before with the exact same problem I am having now(). I think my buttons weren't instantiated when my test first played and the code executed. You were able to solve his problem by looking at/and adjusting his code, unfortunately the code was not posted and the file link on the post is no more so I can not reference it. Is there any way you can help me out? Thanks for your help so far. a function won't give a null object reference error. the line above your function could be causing the error but it should be obvious which line is causing the error because the lines are numbered. which line is referenced in the error message and copy and paste the exact error message. You're right, viewCottage_btn.addEventListener(MouseEvent.CLICK, goCottage); I found a similar post to mine(), you were able to help him, but unfortunately it was through file swapping so I could not reference the solution. Do you think you can help me out? if viewCottage_btn.addEventListener(MouseEvent.CLICK, goCottage); is the line referenced in the error message, viewCottage_btn doesn't exist when that error message occurs. I am begining to understand. How can I go about making it exist when it is reference? that depends how you create that instance. if it's done on the timeline, then you should have that code attached to the first frame where that object first appears and never remove that object for as long as it's needed. I have two scenes, each with one frame. The first scene calls the preloader code, and the second scene has the main content where the problem code is located. That is where the object first appears and that is where the code is but I am still getting an error. I am confused because I do not reference it anywhere else. here is my code if that sheds any light on the subject. rentalsatconesuslakeny.com/cottage_website.zip use a trace() statement to confirm that the error occurs as the playhead enters the frame that contains your button for the first time. if so, you have a typo either in the code or the properties panel. use copy and paste to make sure they match.] is the code that causes the error message and the button in the same frame? if so, you have a typo. Ok, I finally started a new flash file and used more than one frame. Everything seems to be working now. Thanks for your help! you're welcome. Hi kglad, I recently suffered a similar problem and reading your advice here helped me get it working again. Just wanted to let you know your helping us all and we appriciate it THANK YOU!!! p.s. you're a genious North America Europe, Middle East and Africa Asia Pacific South America
http://forums.adobe.com/message/2122905
CC-MAIN-2013-20
refinedweb
762
64.71
What's Happening State Street ( STT ) is on deck to report its third-quarter numbers October 23. Analysts expect the company to post quarterly earnings of $1.61, versus $1.29 during the same period last year, and the stock has appreciated 24.7% on the year. Technical Analysis STT was recently trading at $98.86, down $1.13 from its 12-month high and $30.18 above its 12-month low. Technical indicators for STT are bullish and the stock is in a strong upward trend. The stock has recent support above $95.00 and has recent resistance below $100.00. Of the 14 analysts who cover the stock, four rate it a "strong buy", and 10 rate it a "hold". STT gets a score of 78 from InvestorsObserver's Stock Score Report. Analyst's Thoughts STT has been a solid performer over the last year, as Wall Street has rallied behind the financial sector due to rising interest rates and President Trump's determination to remove restrictions placed on the sector during the financial crisis. STT has risen a hefty 24.7% on the year, and analysts see modest additional upside. The stock is trading at $98.86, with an average price target of $101.75. STT has a P/E of 18.2, is seems more than reasonable considering analysts forecast earnings growth of 20.2%S during the current year, and 12.5% next year. The consensus calls for earnings of $1.61 per share, but the street has a slightly higher whisper of $1.64, suggesting an earnings beat, which would be the eighth straight quarter of stronger than expected profits. It has been a pretty good earnings season so far for the big financials that have already reported, and I expect STT will follow the trend with a strong report of its own. Stock Only Trade Bullish Trade If you want to set up a bullish hedged trade on STT, consider a January 82.50/87.50 bull-put credit spread for a 30-cent credit. That's a potential 6.4% return (25.6% annualized*) and the stock would have to fall 11.2% to cause a problem. Bearish Trade If you want to take a bearish stance on the stock at this time, consider a January 100/115 bear-call credit spread for a 30-cent credit. That's a potential 6.4% return (25.6% annualized*) and the stock would have to rise 11.
https://www.nasdaq.com/articles/state-street-reports-q3-earnings-october-23-2017-10-21
CC-MAIN-2019-47
refinedweb
413
78.14
Modify Axis On 30/12/2016 at 20:56, xxxxxxxx wrote: Hello there, How I can modify the Y Axis to -100% using python as shown in the screenshot below: Thanks On 31/12/2016 at 11:59, xxxxxxxx wrote: Hi, I found the solution below : import c4d def main() : world_pos = op.GetMg().off bBox_pos = op.GetMp() bBox_size = op.GetRad() local_bottom = c4d.Vector(0,bBox_pos.y - bBox_size.y,0) world_bottom = local_bottom + world_pos yPos = c4d.Vector(0,world_bottom.y,0) oldm = op.GetMg() points = op.GetAllPoints() pcount = op.GetPointCount() op.SetAbsPos(yPos) newm = op.GetMg() for p in xrange(pcount) : op.SetPoint(p,~newm*oldm*points[p]) op.Message(c4d.MSG_UPDATE) c4d.EventAdd() if __name__=='__main__': main() On 01/01/2017 at 08:23, xxxxxxxx wrote: Take care of this and using child objects ! Since you modify the original axis and since children use relative position this will affect the position of their. A good way is to store gobal position/scale/rotation (or simply get the global matrix of it) change the axis and then reasign those data On 02/01/2017 at 11:23, xxxxxxxx wrote: Hi, At the outset I wanted to find a solution to dropping an object to a floor, so I wanted to modify the y axis and put it at the bottom of my object then I set the y position to zero. But I find a new solution and it works with all type of object. script : import c4d def main() : if not op: return world_pos = op.GetMg().off bBox_pos = op.GetMp() bBox_size = op.GetRad() local_bottom = c4d.Vector(0,bBox_pos.y - bBox_size.y,0) world_bottom = local_bottom + world_pos op[c4d.ID_BASEOBJECT_REL_POSITION,c4d.VECTOR_Y] += -world_bottom.y c4d.EventAdd() if __name__=='__main__': main() I don't know if can do that differently, and thank you guys for your replies. On 07/08/2017 at 01:52, xxxxxxxx wrote: Thank you for for the nice code example! But it works incorrectly with scaled objects.
https://plugincafe.maxon.net/topic/9875/13300_modify-axis/?page=1
CC-MAIN-2019-30
refinedweb
327
59.5
Java inner class is defined inside the body of another class. Java inner class can be declared private, public, protected, or with default access whereas an outer class can have only public or default access. Java Nested classes are divided into two types. static nested class If the nested class is static, then it’s called a static nested class. Static nested classes can access only static members of the outer class. A static nested class is the same as any other top-level class and is nested for only packaging convenience. A static class object can be created with the following statement. OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass(); java inner class Any non-static nested class is known as inner class in java. Java inner class is associated with the object of the class and they can access all the variables and methods of the outer class. Since inner classes are associated with the instance, we can’t have any static variables in them. The object of java inner class are part of the outer class object and to create an instance of the inner class, we first need to create an instance of outer class. Java inner class can be instantiated like this; Outer: package(); } } We can define a local inner class inside any block too, such as static block, if-else block etc. However, in this case, the scope of the class will be very limited. public class MainClass { static { class Foo { } Foo f = new Foo(); } public void bar() { if(1 < 2) { class Test { } Test t1 = new Test(); } // Below will throw error because of the scope of the class //Test t = new Test(); //Foo f = new Foo(); } } anonymous inner class A local inner class without. It's a bit hard to define how to create an anonymous inner class, we will see it's real-time usage in the test program below. Here is a java class showing how to define java inner class, static nested class, local inner class, and an anonymous inner class. OuterClass.java package; } } Here is the test program showing how to instantiate and use the inner class in java. InnerClassTest.java package com.journaldev.nested; import java.util.Arrays; //nested classes can be used in import for easy instantiation import com.journaldev.nested.OuterClass.InnerClass; import com.journaldev.nested.OuterClass.StaticNestedClass; public class InnerClassTest { public static void main(String[] args) { OuterClass outer = new OuterClass(1,2,3,4); //static nested classes example StaticNestedClass staticNestedClass = new StaticNestedClass(); StaticNestedClass staticNestedClass1 = new StaticNestedClass(); System.out.println(staticNestedClass.getName()); staticNestedClass.d=10; System.out.println(staticNestedClass.d); System.out.println(staticNestedClass1.d); //inner class example InnerClass innerClass = outer.new InnerClass(); System.out.println(innerClass.getName()); System.out.println(innerClass); innerClass.setValues(); System.out.println(innerClass); //calling method using local inner class outer.print("Outer"); //calling method using anonymous inner class System.out.println(Arrays.toString(outer.getFilesInDir("src/com/journaldev/nested", ".java"))); System.out.println(Arrays.toString(outer.getFilesInDir("bin/com/journaldev/nested", ".class"))); } } Here is the output of the above java inner class example program. OuterClass 10 0 OuterClass w=0:x=0:y=0:z=0 w=1:x=2:y=3:z=4 Outer: OuterClass Outer: 1 Outer: 2 Outer: 3 Outer: 4 [NestedClassTest.java, OuterClass.java] [NestedClassTest.class, OuterClass$1.class, OuterClass$1Logger.class, OuterClass$InnerClass.class, OuterClass$StaticNestedClass.class, OuterClass.class] Notice that when OuterClass is compiled, separate class files are created for the inner class, local inner class, and static nested class. Benefits of Java Inner Class - If a class is useful to only one class, it makes sense to keep it nested and together. It helps in the packaging of the classes. - Java inner classes implements encapsulation. Note that inner classes can access outer class private members and at the same time we can hide inner class from outer world. - Keeping the small class within top-level classes places the code closer to where it is used and makes the code more readable and maintainable. That's all for java inner class. I am running my own website Learned alot. from you. great contents. I am visiting your blog. It’s awesome. Dear pankajbhai, I must say thank you for wonderful work. You are skilled gifted by God. Thank you so much for this information. Thank you… Great content! Thanks a lot! It’s more helpful for interview purpose thank you. Hi Pankaj, The inline code is not available for any of your posts. Can you please suggest what needs to be done? Without the code referenced in your text, there is very less meaning to the post. Thank you!! Can you try to clear your cookie cache? Which browser you are facing issue? Thnxx it’s very nyc Mere liye kafi helping resources thnxx The statement about Method Local Inner Classes needs changes. It says “A local inner class can access all the members of the enclosing class and local final variables in the scope it’s defined.”. The correct statement should be “A local inner class can access all the members of the enclosing class and local final variables in the scope it’s defined. Additionally it can also access non final local variable of method in which it is defined, but it cannot modify them. So if you try to print non final local variable’s value it will be allowed but if you try to change its value from inside method local inner class, you will get compile time Error” > Additionally it can also access non final local variable of method in which it is defined, but it cannot modify them. It is known as effectively final Hi Panka, Thanks for your wonderful work. I have referred to many of your excellent materials on this site and would like to make a correction in one of the statement above. “If a class is defined in a method body, it’s known as local inner class.” A local inner class is typically defined in a method but it is not a mandatory condition. The mandatory condition is that it should be defined in a block. We can also define a local inner class inside a for loop, if block etc. Thanks for the additional points, I have included them in the post with code example. You are right, I have added the additional details in the explanation with example code. for local inner class we can access local non-final variable in the scope it’s defined.(java version 8 and above) True…..it can access only. But it cannot modify, thats the thing need to remember by developers. What are the benefits of annonymous inner class? Explain with example. You forgot the magical word “Please”. Since inner classes are associated with instance, we can’t have any static variables in them…. true but If we use ‘static final int mytest=0 ;’ it is allowed! Typo fix: “Java nested classes are defined as class inside the body of another class. A nested class can be declared private, public, protected, or with default access whereas an outer class can have only private or default access.” private should be switched to private Awesome work, Keep it up Thanks for pointing out the typo error, fixed it. Thanks, Pankaj, for sharing another helpful post. But I want to add something to it: In the first paragraph of this post, you have said: “… whereas an outer class can have only private or default access.” It should rather be: “… whereas an outer class can have only PUBLIC or default access.” Do I make a point here? This is obviously an error, the author must have meant to write ‘public’ instead of ‘private’.
https://www.journaldev.com/996/java-inner-class
CC-MAIN-2021-04
refinedweb
1,281
56.55
You must be missing something because when building in a chroot, I get the following fail: ``` ==> Building in chroot for [extra] (x86_64)... ==> Creating clean working copy [miguel]...done ==> Making package: linkchecker 9.4-1 (Thu Jun 29 22:04:10 CEST 2017) ==> Retrieving sources... -> Cloning linkchecker git repo... Cloning into bare repository '/enc/home/miguel/documents/it/archlinux/packages/sources/linkchecker'... remote: Counting objects: 38204, done. remote: Compressing objects: 100% (10/10), done. remote: Total 38204 (delta 3), reused 2 (delta 0), pack-reused 38194 Receiving objects: 100% (38204/38204), 65.86 MiB | 457.00 KiB/s, done. Resolving deltas: 100% (27488/27488), done. ==> Validating source files with sha256sums... linkchecker ... Skipped ==> ERROR: Cannot find the git package needed to handle git sources. ==> ERROR: An unknown error has occurred. Exiting... ==> ERROR: Build failed, check /var/lib/archbuild/extra-x86_64/miguel/build ``` Also, per this commit [0] fixing this issue [1], LinkChecker won't work unless you have `python2-requests<2.15`. [0] [1] Search Criteria Package Details: linkchecker 9.4-1 Dependencies (2) Required by (1) Sources (1) Latest Comments galaux commented on 2017-06-29 20:12 You must be missing something because when building in a chroot, I get the following fail: masser commented on 2017-03-30 13:07 2agrim The project was divided into two parts: 1. linkchecker (Command line version) 2. linkchecker-gui (GUI version) In AUR present both versions. agrim commented on 2017-03-26 12:10 According to this bug the project moved to Any chance to get an updated version? thanks electricprism commented on 2016-12-09 00:08 The Icon listed in the desktop launcher is a bad link, could you add a patch to correct the link? I've noted the problem over here: michalzuber commented on 2016-07-05 06:41 Made a patch for the package Thanks @Sathors for the solution Sathors commented on 2016-06-10 16:29 @e-anima, the bug is resolved in this pull request:. The problem is that it is not yet merged, and it does not seem it will get merged soon. I used the code from the pull request to create a patch, to add to the PKGBUILD, and resolve the problem until the pull request gets merged. Actually the pull request itself is not working as a patch, because of a one character difference (the "if requests.__version__ <" has to be "if requests.__version__ <="). The patch is ``` diff --git a/linkcheck/__init__.py b/linkcheck/__init__.py index 22a0cf5..219e576 100644 --- a/linkcheck/__init__.py +++ b/linkcheck/__init__.py @@ -20,13 +20,14 @@ # version checks import sys +from distutils.version import LooseVersion # Needs Python >= 2.7 because we use dictionary based logging config # Needs Python >= 2.7.2 which fixed if not (hasattr(sys, 'version_info') or sys.version_info < (2, 7, 2, 'final', 0)): raise SystemExit("This program requires Python 2.7.2 or later.") import requests -if requests.__version__ <= '2.2.0': +if LooseVersion(requests.__version__) < LooseVersion('2.2.0'): raise SystemExit("This program requires Python requests 2.2.0 or later.") import os ``` e-anima commented on 2016-05-18 09:45 wehn trying to launch from the console: This program requires Python requests 2.2.0 or later. masser commented on 2014-04-13 04:14 2OliK fixed OliK commented on 2014-04-10 12:59 The gui version (linkchecker-gui) depends on extra/python2-pyqt4. masser commented on 2014-03-27 06:00 2Chrissss Try to install the module python2-requests Chrissss commented on 2014-03-26 14:03 I get this error... $ linkchecker Traceback (most recent call last): File "/usr/bin/linkchecker", line 34, in <module> from linkcheck.cmdline import print_version, print_usage, aggregate_url, \ File "/usr/lib/python2.7/site-packages/linkcheck/cmdline.py", line 23, in <module> from . import checker, fileutil, strformat, plugins File "/usr/lib/python2.7/site-packages/linkcheck/checker/__init__.py", line 24, in <module> from .. import strformat, url as urlutil, log, LOG_CHECK File "/usr/lib/python2.7/site-packages/linkcheck/url.py", line 25, in <module> import requests ImportError: No module named requests lp76 commented on 2012-08-25 13:05 Updated to 7.9 lp76 commented on 2012-05-17 11:44 Updated to 7.8 lp76 commented on 2012-04-09 06:03 Updated to 7.6 qubodup commented on 2012-02-28 16:36 Same problem as selig's here. Had to remove python-dnspython to allow it to install. qubodup commented on 2012-02-28 16:35 Same problem as selig's here. dkorzhevin commented on 2012-01-24 17:21 Doesn't works lp76 commented on 2011-11-23 07:04 Updated to version 0.7.2 lp76 commented on 2011-11-23 07:04 Updated to versione 0.7.2 Anonymous comment on 2011-08-11 15:31 error: failed to commit transaction (conflicting files) linkchecker: /usr/lib/python2.7/site-packages/dns/__init__.py exists in filesystem linkchecker: /usr/lib/python2.7/site-packages/dns/__init__.pyc exists in filesystem linkchecker: /usr/lib/python2.7/site-packages/dns/dnssec.py exists in filesystem linkchecker: /usr/lib/python2.7/site-packages/dns/dnssec.pyc exists in filesystem linkchecker: /usr/lib/python2.7/site-packages/dns/e164.py exists in filesystem linkchecker: /usr/lib/python2.7/site-packages/dns/e164.pyc exists in filesystem linkchecker: /usr/lib/python2.7/site-packages/dns/edns.py exists in filesystem linkchecker: /usr/lib/python2.7/site-packages/dns/edns.pyc exists in filesystem linkchecker: /usr/lib/python2.7/site-packages/dns/entropy.py exists in filesystem linkchecker: /usr/lib/python2.7/site-packages/dns/entropy.pyc exists in filesystem ...... For ex. /usr/lib/python2.7/site-packages/dns/tsig.py is owned by python-dnspython 1.9.2-1 :: namebench: requires python-dnspython lp76 commented on 2011-05-29 05:30 New version 7.0 lp76 commented on 2011-05-22 07:41 Updated to 6.9 Thanks Dragonlord! Dragonlord commented on 2011-05-15 13:30 lp76 commented on 2011-04-25 12:47 New version 6.7 lp76 commented on 2011-04-09 06:09 New version 6.6 Thanks CPUnltd CPUnltd commented on 2011-04-09 03:49 version 6.6 is now out... lp76 commented on 2011-03-13 09:17 New version 6.5 lp76 commented on 2011-03-08 06:53 Updated to 6.4 lp76 commented on 2011-02-02 07:02 Updated to version 6.2 lp76 commented on 2010-11-26 07:10 Updated to 5.5 Thanks mikyter Anonymous comment on 2010-11-22 19:08 And 5.5 is there. You only need to change the version and checksum... lp76 commented on 2010-11-05 06:56 Updated to 5.4 Thanks Mikyter Anonymous comment on 2010-11-02 17:35 5.4 is out... lp76 commented on 2010-10-23 06:36 Updated dependencies lp76 commented on 2010-10-10 06:47 Updated to 5.3 Thank you mikyter Anonymous comment on 2010-10-08 18:03 LinkChecker 5.3 is available! The updated PKGBUILD: lp76 commented on 2010-04-06 05:44 Added x86_64 tag. Thanks to Paterbrown paterbrown commented on 2010-04-05 09:19 Can you add x86_64? I have tested, it works... lp76 commented on 2010-04-05 06:33 Updated to version 5.2
https://aur.archlinux.org/packages/linkchecker/?comments=all
CC-MAIN-2017-43
refinedweb
1,220
62.04
Nova volume-update leaves volumes stuck in attaching/detaching Bug Description There is a problem with the nova command 'volume-update' that leaves cinder volumes in the states 'attaching' and 'deleting'. If the nova command 'volume-update' is used by a non admin user the command fails and the volumes referenced in the command are left in the states 'attaching' and 'deleting'. For example, if a non admin user runs the command $ nova volume-update d39dc7f2- Will result in the two volumes stuck like this: $ cinder list +----- | ID | Status | Display Name | Size | Volume Type | Bootable | Attached to | +----- | 59b0cf66- | f0c3ea8f- +----- And the following in the cinder-api log: 2015-01-21 11:00:03.969 13588 DEBUG keystonemiddlew 2015-01-21 11:00:03.970 13588 DEBUG routes.middleware [req-d08bc456- 2015-01-21 11:00:03.971 13588 DEBUG routes.middleware [req-d08bc456- 2015-01-21 11:00:03.971 13588 DEBUG routes.middleware [req-d08bc456- 2015-01-21 11:00:03.972 13588 INFO cinder. 2015-01-21 11:00:03.972 13588 DEBUG cinder. 2015-01-21 11:00:03.973 13588 INFO cinder. 2015-01-21 11:00:03.975 13588 INFO eventlet. The problem is that the nova policy.json file allows a non admin user to run the command 'volume-update', but the cinder policy.json file requires the admin role to run the action os-migrate_ The operation will complete successfully if it is performed by an admin user, or if it is run by a non admin user after the cinder policy.json file is updated. The simplest fix would be to remove the "rule:admin_api" requirement from the "os-migrate_ Currently 403 doesn't seem to be an expected code? @wsgi. @extensions @validation def update(self, req, server_id, id, body): Duncan, Nova does not clean up if this call fails: https:/ While I agree Nova shouldn't assume this call will succeed as it does today, what I think Loganathan is explaining is we have nova expecting volume migration completion to be ran by a normal end user, not the administrator. Volume migrate was never intended to be used by an end user, which is why by default it's required for the user running it to be within the admin role. In an OpenStack environment, the end user wouldn't know or care about the storage backends, they would just want to consume the resources based on requirements advertised by volume types, that's it. With that in mind, the administrator cares/knows about the backends, so we expose this feature to an admin role only. However, I don't think that's the problem either. Currently in the Nova code it does elevate the context which it talks to Cinder, so I'm not sure why this is happening: https:/ In this case migrate_ If an admin user runs 'nova volume-update ' the operation completes successfully. But if a user that does not have admin privs runs it, the we end up in the state described above. So I think that what is happening is that nova performs all it's operations as the necessary, elevating context as required. Then nova makes a call to the cinder api migrate_ So I think there are three questions here 1. Should the python novaclient command 'volume-update' be a non-admin operation. The nova devs I've spoken to believe that it should be available to non-admin users 2. If volume-admin is available to non-admins then should nova call the os-migrate_ 3. Should nova clean up volume states in the case where an error occurs towards the end of a volume operation. For the moment I'm assuming that cinder should support nova in allowing non-admin users to run update-volume, and I'm assuming cinder should allow the non-admin user to run the os-migrate_ I think the issue of nova cleaning up is an independent bug which could be raised on nova. So, I'm preparing a patch that makes os-migrate_ Please let me know if you think this is the wrong approach. Ollie, this is nothing new with cinder client. There are plenty of things that can be called that are admin only. See this search for 'admin only' in the client code: http:// As explained in my last comment, Nova is elevating the context when making this call, so time should be spent on figuring out why that's not working as expeected: https:/ Mike: I'm aware nova /doesn't/ do any clean-up, I'm suggesting that it should. Context.elevated, like cinder, does not use an admin context for inter-project rest calls, only RPC/db calls. There was a new version of elevate added to cinder recently to use a service (usually admin) user for specific calls, I think nova has a similar concept but does not yet use it for this call. Mike: Duncan is correct, elevating the nova context does not mean that nova will use different credentials when it connects to the cinder API. That's what I was saying in my last post and I've confirmed it with nova developers. Given that, it seems that 'nova volume-update' is working as expected. The user credentials passed with the os-migrate_ Do you agree with that? or is there something else you had in mind? Hi, I have tested this issue on latest master and it is reproducible by admin user as well i.e., volumes are remaining in 'attaching' and 'detaching' states by admin user and normal user after running nova volume-update command. I have found one launchpad issue related to migrate attach volume which is already fixed, https:/ Two different patches were submitted for this issue, but the cinder patch ( https:/ So, volume update works properly on stable/juno because nova patch was not merged. In nova patch, attach and detach calls are moved from swap_volume() method of nova.compute. IMO, while fixing this cinder migrate attach volume issue, nova volume-update was not tested properly. When we migrate volume which is attached to the instance, cinder calls update_ https:/ In swap_volume() of nova.compute, migrate_ https:/ Hence volumes are remaining in 'attaching' and 'detaching' states. FYI, I have added the missing tempest test for nova os-volume- https:/ Putting in incomplete for nova until we sort out what is actually needed on the nova side. It seems unclear if there is an issue on that side. Change abandoned by Mike Perez (<email address hidden>) on branch: master Review: https:/ Reason: Over a month with no update. [Expired for OpenStack Compute (nova) because there has been no activity for 60 days.] Should nova do some tidying up if it gets a permission denied?
https://bugs.launchpad.net/nova/+bug/1413610
CC-MAIN-2018-51
refinedweb
1,133
61.26
DTK_NANOSLEEP(3) Draw Toolkit manual DTK_NANOSLEEP(3) NAME dtk_nanosleep - high-resolution sleep SYNOPSIS #include <dtk_time.h> int dtk_nanosleep(int abs, const struct dtk_timespec* req, struct dtk_timespec* rem); DESCRIPTION The function dtk_nanosleep() allows the caller to sleep for an interval with nanosecond precision. If the argument abs is zero, the speci- fied interval is interpretated as a relative value, otherwise an absolute value. The interval is specified by the req argument which is a pointer to a dtk_timespec structure defined as: struct dtk_timespec { long sec; /* seconds */ long nsec; /* nanoseconds */ }; If interpreted as an absolute value, it represents seconds and nanoseconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC). dtk_nanosleep() suspends the execution of the calling thread until either at least the time specified by req has elapsed, or a signal is delivered that causes a signal handler to be called or that terminates the process. If the call is interrupted by a signal handler, dtk_nanosleep() returns -1, and sets errno to EINTR. In addition, if rem is not NULL, and abs is zero, it returns the remaining unslept time in rem. This value can then be used to call dtk_nanosleep() again and complete a (rela- tive) sleep. RETURN VALUE On successfully sleeping for the requested interval, dtk_nanosleep() returns 0. If the call is interrupted by a signal handler or encoun- ters an error, then it returns -1 and errno is set appropriately. ERRORS dtk_nanosleep() will fail if: EINTR The sleep was interrupted by a signal handler. EINVAL The value in the nsec field was not in the range 0 to 999999999 or sec was negative. NOTE This function is a wrapper to clock_nanosleep(2) if it is provided by the system. Otherwise, it implements the function by using the sleep function with the highest precision available on the system. SEE ALSO dtk_nanosleep(3), clock_nanosleep(2) EPFL 2011 DTK_NANOSLEEP(3)
https://www.unix.com/unix-for-dummies-questions-and-answers/157129-capture-running-process-2-hours-interval-10-sec.html?s=441282753b85e8c8d53d42c43ae989c0
CC-MAIN-2019-39
refinedweb
311
51.28
Many Java programmers use the == operator to compare strings. Nevertheless, if you want to compare the value of two String objects, you need to use a method. The equals() method compares the text of the two String objects. If the text is the same, it will return true. Otherwise, it returns false. So, this snippet works as expected: public class StringEquality { public static void main(String[] args) { String string1 = "abc", string2 = "def"; if((string1 + string2).equals("abcdef")) { System.out.println("Equal"); } } } But why does the == operator work sometimes and at other times not? It is because String objects in Java are immutable and the == operator is comparing object references, not the text of the strings. These two facts work together to make it look as if the == is sometimes correctly comparing string values. Therefore, if you create two strings using this syntax: String string1 = "abc";String string2 = "abc"; Java will not create two String objects with the same value - just a single object containing "abc". So, string1 and string2 will be referencing the same object in memory. This is the reason why: string1 == string2 is true. The == operator checks if both objects reference the same object in memory and in this case this also means that the two strings are equal in value. However if you use the String constructor, a new space in memory will be used for the new String object. That is following: String string1 = "abc"; String string2 = new String("abc"); We have two string objects both holding the same text but now: is false because the two variables reference different object. The same thing happens if you compute a result on the fly or compare a string to a literal. For example: string1 + string2 == "abcdef" is false for two reasons. First string1 and string2 are concatenated as a new object and "abcdef" is yet another string object, and so they cannot be equal as references to an object. You should always use the equals() method if you want to compare the text of two String objects. You might think that it is a disadvantage to be unable to compare String objects with the == operator. But, don't forget that String in Java is not a primitive type; it is a class and hence uses reference semantics not value semantics. Thus, we use == to know if two string objects are actually the same object in memory which also, almost as a side effect, ensures that they have the same text. Introducing Melvin and Bugsy, characters who figure in a series of challlenges from Joe Celko. Sharpen your coding skills with puzzles that will both amuse and torment you.. <ASIN:0132130807> <ASIN:0672330768><ASIN:0136091814> <ASIN:0321356683>
http://www.i-programmer.info/programmer-puzzles/170-java/2939-strings-and-things.html?start=1
CC-MAIN-2018-26
refinedweb
449
70.73
Additional Titles Related Articles Homeschools, Private Schools and System Education January 7, 2004 NewsWithViews.com Two years ago this week, President Bush's much heralded "No Child Left Behind" law went into effect. To mark the anniversary Mr. Bush has been busy visiting schools around the country defending this misguided plan against those who point out this scheme has done nothing but: Since Congress passed this law, which mandates "achievement" standards for "all" students, we are now witnessing what happens when you allow the federal government to be involved in the education of a nation's children. The brightest kids stuck in the government's education camps also known as the public school system are the latest casualties in this failed policy. Schools which don't make steady progress toward reading and math scores by 2014 face penalties, so in an effort to make sure low achievers are brought along to hit certain benchmarks, the talented and gifted kids are being short-changed in their programs. Schools missing the proficiency levels outlined by the feds face penalties which include letting parents transfer their kids out of the school. Schools can also be forced to pay for outside tutors. Rather than deal with those financially devastating penalties schools are opting to siphon money from programs that help the most gifted students. They've decided to focus on the bottom neglecting the top. So, in order to stay out of trouble, schools are shifting resources away from the programs that help bright kids who apply themselves, i.e. the "talented and gifted" or TAG kids (although we're seeing a shift away from any terminology which "labels" a child as such, since it's no longer politically correct to term a child "gifted" just because he or she does well in an academic setting.) The object of federal education policies has, for a long time now, been to discourage excellence and dumb down to a common denominator which currently has the U.S. rated very close to the bottom of countries when it comes to math and science achievement. Does this make any sense? Take the resources available,(even though the cost of government education is much higher than private school per child costs)spread them thinly and deny those who ostensibly have the best chance of succeeding, while at the same time taking finite resources and wasting them on things like bilingual education (sure to keep the non-English speakers from doing well in the classroom and thus in the marketplace�and after all isn't that the point?)). It almost seems like a deliberate attempt to make sure the U.S. stays dumb and gets dumber still. While federal education policies mandate spending gargantuan sums on kids who either can't or don't want to learn they are now penalizing the best and brightest students by trimming their class offerings and thereby stunting their academic growth. Sounds like a plan. State after state has dropped programs for the most promising students while increasing funds for basic reading. No Child Left Behind? No Child Left Alone is more like it. If some kids are going to be dumb, well, by golly ALL kids should be that way, too! So much for the pursuit of excellence. Wall Street Journal reporter Daniel Golden cites a High Point, N.C. elementary school as an example. There, 85% of the students are black or Hispanic and 95% of them come from low-income families. Intensive tutoring has ostensibly raised test scores there overall, except for one group. The academically gifted kids are now doing the worst! Go figure. Schools are devoting resources to developing programs for the poorest students while those who show the slightest aptitude for anything above burger-flipping get aced out. Officials at schools targeted for low test scores have been beating their heads against the wall to get the low-achievers up to a pitiful compliance level and the good students be damned. Maybe that's why we have to import technical workers from India or why the U.S. ranks below Cyprus when it comes to overall academic achievement. Sounds like a plan to "Maybe that's why we have to import technical workers from India or why the U.S. ranks below Cyprus when it comes to overall academic achievement."
http://newswithviews.com/Mary/starrett36.htm
CC-MAIN-2016-44
refinedweb
722
60.35
On Sat, Mar 27, 2004 at 04:17:00PM -0600, Parker, Ron wrote: > > By making these trackers so simple to implement, they have hit upon a > > new concept -- decentralized centralization (!). Sure, there's > > superservers, but there's so many of them, that nobody is in control. > > > > What bittorrent has to teach us is that the problem isn't centralized > > servers. The problem to avoid is having a centralized server > > that is too > > Okay, this is too weird. After asking you about the bandwidth etc. > requirements of the supermirror, I got to thinking about bittorrent as it > might relate to arch, down the road, especially as the supermirror becomes > overloaded. It is an interesting idea for a lot of different reasons. > > As I checked into bittorrent, I discovered that it is really designed for > large files with a fairly concentrated and intense demand period. For it to > > I haven't had time to get back to investigating it and to think about > whether or not their might be a way to adapt what bittorrent does to the > arch environment. Grin. I'm not proposing that arch archives be pushed via bittorrent. That just wouldn't work. :) What I'm attemping to illustrate is that the problem that we're all seeking to avoid, the creation of a monopoly for the namespace, is actually somewhere different than we've been thinking. The problem is not in having an 'arch namespace server (ANS)'. The problem is that any such ANS must be a commodity so that anybody can run one out of their basement. Does this ASN need to be some sort of specialized server? HECK NO. We've learned from both CVS's and subversion's server that specialized servers are the wrong way to go. No, the right answer here is to devise a filesystem protocol that can be served by CFDP[0]. Something like the way that arch works now. For example, what if people could perform the following (I've simplified the scenario. In a more proper solution, things would be a little more complex): 1a. "tla lookup --add" Add to ~/.arch-params/lookupservers 1b . "tla lookup --add" Add to ~/.arch-params/lookupservers 2. "tla register-archive --lookup address@hidden Downloads and conflates & 2a. If only one archive matches, register-archive it. 2b. If more than one archive matches, list all matching archives and tell the user to run register-archive by hand. 3. user creates new archive 4. user registers the archive with a site by visiting a cgi page that updates the list of archives in [0] CFDP or "Common File Distribution Protocols" - An acronym I just made up on the spot that refers to servers such as http, ftp, scp,
https://lists.gnu.org/archive/html/gnu-arch-users/2004-03/msg01125.html
CC-MAIN-2019-47
refinedweb
454
72.26
On 7/3/16, 7:21 AM, "Harbs" <harbs.lists@gmail.com> wrote: >The first “flex” was a typo and it should have been “flash”. I'm not seeing that in the code. Can you be more specific about which lines are doing this? > >I’m not sure my question made sense, but I do have a related question: >Why this? > COMPILE::SWF > public class HTTPServiceBase extends EventDispatcher > { > } > > COMPILE::JS > public class HTTPServiceBase extends HTMLElementWrapper > { > } > >Why is the JS side not extending EventDispatcher as well? IMO, some code somewhere as to abstract the platform differences and do it as thinly as possible for performance reasons, so the inheritance chain for classes don't have to be the same, the API surface they present does. I think there will be more emphasis on Interfaces like IEventDispatcher instead of base classes like EventDispatcher in FlexJS. It should keep us from wasting code trying to make everything look the same under the covers and prevent huge chains of class dependencies that make it hard to have separation of concerns and small applications. Or maybe I'm not understanding your question... -Alex
http://mail-archives.apache.org/mod_mbox/flex-dev/201607.mbox/%3CD39E73B8.6F8A8%25aharui@adobe.com%3E
CC-MAIN-2018-13
refinedweb
188
62.07
Chris SALE, Acting Commissioner, Immigration and Naturalization Service, et al., Petitioners v. HAITIAN CENTERS COUNCIL, INC., et al. 509 "authorizes such forced repatriation to be undertaken only beyond the territorial sea of the United States." Respondents, organizations representing interdicted Haitians and a number of Haitians, sought a temporary restraining order, contending that the Executive Order violates § 243 243(h) are ordinarily advanced. Since the INA nowhere provides. ----, 111 S.Ct. 1227, 113 L.Ed.2d 274,. ____. (b) The history of the Refugee Act of 1980which amended § 243(h)(1) by adding the phrase "or return" and deleting the phrase "within the United States" following "any alien"confirms that § 243. ____. (c) Article 33's textwhich provides that "no . . . State shall expel or return ('refouler') a refugee . . . to . . . territories where his life or freedom would be threatened . . .," Article 33.1, and that "the benefit of the present provision may not . . . be claimed by a refugee whom there are reasonable grounds for regarding as a danger to the security of the country in which he is located," Article 33.2affirmwhich bargainsolidly. § 243(h)(1) of the Immigration and Nationality Act of 1952 (INA or Act). 2 We hold that neither § determined refugee will be returned without his consent." Executive Order 12324, 3 CFR § S.Ct. 1245, 117 L.Ed.2d 477 advisors,." 8 U.S.C.. Although § 243(h)(1) refers only to the Attorney General, the Court of Appeals found it "difficult to believe that the proscription of §. . . ." § §. ----, ---- n. 5, 113 S.Ct. 1178, 1183 n. 122 L.Ed.2d 548 or return" only to make § 243(h)'s protection available in both deportation and exclusion proceedings. Indeed, the history of the 1980 amendment confirms that conclusion. As enacted in 1952, § § 243(h). Leng May Ma v. Barber, 357 U.S. 185, 186, 78 S.Ct. 1072, 1073, 2 L.Ed.2d 1246 (1958). 31 We explained the important distinction between "deportation" or "expulsion," on the one hand, and "exclusion," on the other: , 345 U.S. 206, 212 § 243(h)(1), and they are fully explained by the intent to apply §.leads. § of the moral weight of that argument, both the text and negotiating history of Article 33 affirmatively indicate that it was not intended to have extraterritorial effect..", 78 S.Ct., at 1073 (quoting Shaughnessy v. United States ex rel. Mezei, 345 U.S. 206, 212, 73 S.Ct. 625, 629, 97 L.Ed. 956 (1953)). This suggestionthat "return" has a legal meaning narrower than its common meaning The drafters of the Convention and the parties to the Protocollike the drafters of §: "Mr. ZUTTER (Switzerland) said that the Swiss Federal Government saw no reason why article 28 should not be adopted as it stood; for the article was a necessary one. He thought, however, that its wording word 'return', used in the English text, gave that idea exactly. Yet article 28 implied the existence of two categories of refugee: refugees who were liable to be expelled, and those who were liable to be returned. In any. V" of thousands of Haitiansto, ____.' " (citation omitted). Ibid. Executive Order No. 12,807, 57 Fed.Reg. 23133 (1992)I ____, the majority leads itself astray. The straightforward interpretation of the duty of nonreturn is strongly reinforced by the Convention's use of the French term "refouler. " The ordinary meaning of "refouler, " as the majority concedes, ante, at ____, is "to repulse, . . .; to drive back, to repel." Dictionnaire Larousse ("Les "may not . . . be claimed by a refugee whom there are reasonable grounds for regarding as a danger to the security of the country in which he is, or who, having been convicted by a final judgment of a particularly serious crime, constitutes a danger to the community of that country.". B,)., 54 S.Ct. 735, 742-43, 78 L.Ed. 1298 (1934). There is no evidence that the comment on which the majority relies was ever communicated to the United States' Government or to the Senate in connection with the ratification of the Convention. ). 2364. The majority thus cannot maintain that van Boetzelaer's interpretation prevailed., 102 S.Ct., at 2379, required to overcome the Convention's plain statement: "No Contracting State shall expel or return ('refouler ') a refugee in any manner whatsoever to the frontiers of territories where his life or freedom would be threatened. . . ." II Like the Treaty whose dictates it embodies, § 243(h) is unambiguous. It reads: )(1). . Immigration Act to make mandatory ("shall not deport or return ") what had been a discretionary function ("The Attorney General is authorized to withhold deportation"). The Attorney General may not decline to follow the command of §,)" (emphasis added). The Refugee Act of 1980 explicitly amended this provision in three critical respects. Congress (1) deleted the words "within the United States"; (2) barred the Government from "returning," as well as "deporting," alien refugees; and (3) made the prohibition against return mandatory, thereby eliminating the discretion of the Attorney General over such decisions. The import of these changes is clear. Whether "within the United States" or not, a refugee may not be returned to his persecutors. To read into §, 107 S.Ct., at 1219-1220 , 78 S.Ct. 1072, 2 L.Ed.2d 1246 (1958), this Court decided that aliens paroled into the United States from detention at the border were not "within the United States" for purposes of the former § § 208(a). 15 An examination of the carefully designed provisions of the INAnot an elaborate theory about a 1958 case regarding the rights of aliens in exclusion proceedingsis the proper basis for an analysis of the statute. 16not "common-sense notion" that Congress was looking inwardsperfectly ____, is completely wrong. The presumption that Congress did not intend to legislate extraterritorially has less forceperhaps,. " 'Over. The Charming Betsy, 2 Cranch 64, 117-118, 2 L.Ed. 208 (1804). The majority's improbable construction of § 243(h), which flies in the face of the international obligations imposed by Article 33 of the Convention, violates that established principle. III. This language appears in both Executive Order No. 12324, 3 CFR 181 (1981-1983 Comp.), issued by President Reagan, and Executive Order No. 12807, 57 Fed.Reg. 23133 (1992), issued by President Bush. Title 8 U.S.C. 1253(h) (1988 ed. and Supp. IV), as amended by § 203(e) of the Refugee Act of 1980, Pub.L. 96-212, 94 Stat. 107. Section 243(h)(1) provides: "(h) Withholding of deportation or return. (1) 243(h)(2), 8 U.S.C.. 1253(h) (1976 ed.); see also INS v. Stevic, 467 U.S. 407, 414, n. 6, 104 S.Ct. 2489, 2493, n. 6, 81 L.Ed.2d 321 (1984). Jan. 31, 1967, 19 U.S.T. 6223, T.I.A.S. No. 6577. 8 U.S.C. 1252 (1988 ed. and Supp. IV). 8 U.S.C. 1226. Although such aliens are located within the United States, the INA (in its use of the term exclusion) treats them as though they had never been admitted; §." See INS v. Stevic, 467 U.S., at 423, n. 18, 104 S.Ct., at 2497, n. 18. Id., at 424-425; 426, n. 20, 104 S.Ct., at 2499, n. 20.. advisor to the State Department. See App. 202-230. App. 231. In 1985 the District Court for the District of Columbia upheld the interdiction program, specifically finding that § § § 243(h) [ 8 U.S.C.., but not quite as strict as the standard applicable to a withholding of deportation pursuant to § 243(h)(1). See generally, INS v. Cardoza-Fonseca, 480 U.S. 421, 107 S.Ct. 1207, 94 L.Ed.2d 434 (1987). See App. 244-245. Executive Order No. 12,807 reads in relevant part as follows: : "when. July 28, 1951, 19 U.S.T. 6259, T.I.A.S. No. 6577., 104 S.Ct., at 2494. Because the Convention established Article 33, and the Protocol merely incorporated it, we shall refer throughout this opinion to the Convention, even though it is the Protocol that applies here. .. 1104, 1105, 1153, 1201, and 1202 (1988 ed. and Supp. IV). See 8 U.S.C.). been bound by § 243(h)(1). Respondents challenge a program of interdiction and repatriation established by the President and enforced by the Coast Guard. See, e.g., § 1158(a), quoted in n. 11, supra. 66 Stat. 214; see also n. 2, supra. . , 407 U.S., at 417-418, 104 S.Ct., at 2494-2495. U §." The New Cassell's French Dictionary 440 (1973), gives this translation: "return (I) [ritp, largent rapporte interet; to return good for evil, rendre le bien pour le mal.n. Retour (coming back, going back), m.; rentree (c oming. "refouler [rpfule],. .lawfully or unlawfully"). A more recent work describes the evolution of non-refoulement into the international (and possibly extraterritorial) duty of non-return country pending a decision on his initial request.' " (emphasis added). Handbook on Refugee Status, at 460.").."). The Court seems no more convinced than I am by the Government)..). The majority also cites secondary sources that, it claims, share its reading of the Convention. See ante, at ____, that nations need not admit refugees or grant them asylumquestions); Goodwin-Gill, The Refugee in International Law 87 (. The majority neglects to point out that the current High Commissioner for Refugees acknowledges that the Convention does apply extraterritorially. See Brief for United Nations High Commissioner for Refugees as Amicus Curiae. suspended. . . ." Presidential Proclamation No. 4865, 46 Fed.Reg. 48,107 (1981). Of course the Attorney General's authority is not dependent on its recognition in the Order. " ____. ____. Congress used the words "physically present within the United States" to delimit the reach not just of § 208 but of sections throughout the INA. See, e.g., 8 U.S.C. 1159 (adjustment of refugee status); 1101(a)(27(I) ) (1988 ed., Supp. IV) (requirements for temporary protected status). The majority offers no hypothesis for why Congress would not have done so here as well.are. Indeed, petitioners are hard-pressed to argue that restraints on the Coast Guard infringe upon the Commander-in-Chief power when the President himself has placed that agency under the direct control of the Department of Transportation. See Declaration of Admiral Leahy, App. 233.
http://www.law.cornell.edu/supremecourt/text/509/155
CC-MAIN-2014-49
refinedweb
1,709
68.47
#include <sys/ddi.h> #include <sys/sunddi.h> int ddi_dma_movwin(ddi_dma_handle_t handle, off_t *offp, uint_t *lenp, ddi_dma_cookie_t *cookiep); This interface is obsolete. ddi_dma_getwin(9F) should be used instead. The DMA handle filled in by a call to ddi_dma_setup(9F). A pointer to an offset to set the DMA window to. Upon a successful return, it will be filled in with the new offset from the beginning of the object resources are allocated for. A pointer to a value which must either be the current size of the DMA window (as known from a call to ddi_dma_curwin(9F) or from a previous call to ddi_dma_movwin()). Upon a successful return, it will be filled in with the size, in bytes, of the current window. A pointer to a DMA cookie (see ddi_dma_cookie(9S)). Upon a successful return, cookiep is filled in just as if an implicit ddi_dma_htoc(9F) had been made. The ddi_dma_movwin() function shifts the current DMA window. If a DMA request allows the system to allocate resources for less than the entire object by setting the DDI_DMA_PARTIAL flag in the ddi_dma_req(9S) structure, the current DMA window can be shifted by a call to ddi_dma_movwin(). The caller must first determine the current DMA window size by a call to ddi_dma_curwin(9F). Using the current offset and size of the window thus retrieved, the caller of ddi_dma_movwin() may change the window onto the object by changing the offset by a value which is some multiple of the size of the DMA window. The ddi_dma_movwin() function takes care of underlying resource synchronizations required to shift the window. However, if you want to access the data prior to or after moving the window, further synchronizations using ddi_dma_sync(9F) are required. This function, it returns without invoking another DMA transfer. Otherwise it calls ddi_dma_movwin() to shift the current window and starts another DMA transfer. The ddi_dma_movwin() function returns: The current length and offset are legal and have been set. Otherwise. The ddi_dma_movwin() function can be called from user, interrupt, or kernel context. See attributes(5) for a description of the following attributes: attributes(5), ddi_dma_curwin(9F), ddi_dma_getwin(9F), ddi_dma_htoc(9F), ddi_dma_setup(9F), ddi_dma_sync(9F), ddi_dma_cookie(9S), ddi_dma_req(9S) Writing Device Drivers for Oracle Solaris 11.2 The caller must guarantee that the resources used by the object are inactive prior to calling this function.
http://docs.oracle.com/cd/E36784_01/html/E36886/ddi-dma-movwin-9f.html
CC-MAIN-2016-07
refinedweb
390
54.52
import "go.chromium.org/luci/starlark/typed" Package typed contains implementation of strongly-typed lists and dicts. converter.go dict.go doc.go list.go type Converter interface { // Convert takes a value and either returns it as is (if it already has the // necessary type) or allocates a new value of necessary type and populates // it based on data in 'x'. // // Returns an error if 'x' can't be converted. Convert(x starlark.Value) (starlark.Value, error) // Type returns a name of the type the converter converts to. // // Used only to construct composite type names such as "list<T>". Type() string } Converter can convert values to a some Starlark type or reject them as incompatible. Must be idempotent, i.e. the following must not panic for all 'x': y, err := Convert(x) if err == nil { z, err := Convert(y) if err != nil { panic("converted to an incompatible type") } if z != y { panic("doesn't pass through already converted item") } } Must be stateless. Must not mutate the values being converted. Dict is a Starlark value that looks like a regular dict, but implements type checks and implicit conversions for keys and values when assigning elements. Note that keys(), values() and items() methods return regular lists, not typed ones. Differences from regular dicts: * Not comparable by value to regular dicts, only to other typed dicts. go.starlark.net has no way to express that typed dicts should be comparable to regular dicts. * update() doesn't support keyword arguments. Using keyword arguments implies string keys which make no sense in generic typed Dict interface, since generally strings are not valid keys. This also substantially simplifies the implementation of update(). AsTypedDict allocates a new dict<k,v>, and copies it from 'x'. Returns an error if 'x' is not an iterable mapping or some of its (k, v) pairs can't be converted to requested types. NewDict returns a dict with give preallocated capacity. KeyConverter returns the type converter used for keys of this dict. ValueConverter returns the type converter used for values of this dict. List is a Starlark value that looks like a regular list, but implements type checks and implicit conversions when assigning elements. Differences from regular lists: * Not comparable by value to regular lists, only to other typed lists. go.starlark.net has no way to express that typed lists should be comparable to regular lists. * Only == and != comparison operators are supported. * `l += ...` is same as `l = l + ...`, not `l.extend(...)` AsTypedList allocates a new list<t>, and copies it from 'x'. Returns an error if 'x' is not an iterable or some of its elements can't be converted to 't'. NewList returns a list with given elements, converted to necessary type through 'item' converter. All subsequently added elements will be converter through this converter too. func (l *List) Binary(op syntax.Token, y starlark.Value, side starlark.Side) (starlark.Value, error) Binary implements 'l <op> y' (or 'y <op> l', depending on 'side'). Note that *starlark.List has its binary operators implement natively by the Starlark evaluator, not via HasBinary interface. Converter returns the type converter used by this list. Package typed imports 3 packages (graph) and is imported by 1 packages. Updated 2019-12-06. Refresh now. Tools for package owners.
https://godoc.org/go.chromium.org/luci/starlark/typed
CC-MAIN-2019-51
refinedweb
544
50.53
Hands up. How many of you use 'List<T>' on a regular basis? If the core software you write consists mostly of lines of business apps, then I'm sure like me, quite a lot of you do. But, did you ever stop to thoroughly explore some of the more esoteric types that are available in the .NET collections namespace? It might surprise some that, as well as the more commonly known dictionary and array types, .NET has quite a few classes designed for implementing things like FIFO/LIFO Queues, linked lists, and many other structures that you might never have even realised. Interesting, but if I've Gotten This Far Without Needing Them... Many will proclaim that if they've gotten this far in their career without knowing about the existence of these extra types, why suddenly start using them? Like many tools in the developers' toolbox, it's not about suddenly starting to use them, but more a realisation that you now have an extra tool, and you never know when it's going to come in handy. This is exactly what happened to me, and why it prompted me to write this post about the hidden gems available. On a recent project, I had to research a different way of managing a collection of data in an application I was maintaining. This data, due to its structure, warranted a slight deviation from the norm. As a result, I ended up uncovering some of the collection types I describe below. Bit Array The Bit Array class is, in the true sense of the word, just like a normal Array. Under the hood, however, it harbours some very clever tricks. The idea behind the Bit Array is to store a collection of ones and zeros, represented in individual units as Boolean true/false values. Behind the scenes, however, everything is packed down into bytes/ints as far as possible. This means you can—at least in theory—pack 32 bits of information into the same space that a one-element integer array would occupy. Bit Arrays can be constructed from byte arrays; so, for example, if you did the following: byte[] myBytes = new byte[5] { 255, 255 }; BitArray myBA3 = new BitArray( myBytes ); You would end up with a Bit Array containing 16 Boolean elements all set to true. The actual bit pattern set is derived from the bit pattern produced. If you were to turn the individual values into their binar, representations. This is useful for things like compression systems, or taking parallel data and streaming it serially, perhaps down a serial cable, or in a serial network simulation. You also can take two Bit Arrays and perform useful operations on them, such as 'AND', 'OR', and 'XOR'. This will allow you to perform bit-level operations without having to resort to individual bit twiddling. Queue Queues are used to create FIFO (first in first out) structures. This kind of structure is very useful for sequentially processing a set of messages or commands. For example, if you had an internal message bus in your application, you could use the queue to receive the messages coming in from the bus, and make them ready for a processor to use them. Unlike a normal list, you don't reference items in the queue directly by an index. You add items to the queue by using the following statements: Queue myQueue = new Queue(); myQueue.Enqueue("Message 1"); myQueue.Enqueue("Message 2"); myQueue.Enqueue("Message 3"); This will add the three messages such that the last one added will be the last one out. You get the value at the head by using the reverse of the 'Enqueue' method 'Dequeue', as follows: string msg1 = myQueue.Dequeue(); you can use the 'Peek' method to check if there is anything present without removing it, and like all the classes in the namespace, the queue presents an IEnumerable iteration interface so you can do things such as 'for each' over the collection. Stack Stacks are the opposite of a queue and are used to construct a LIFO (last in first out) structure. The easiest way to picture this is to imagine a stack of plates. As you put one plate on top of another, the stack grows higher. When you need a plate, you take one from the top of the stack. The last plate added to the stack was the next one out. Stacks are often used for temporary lists of things like parameters while a calculation is performed on them. In fact, some mathematical operations performed using methods, such as reverse polish notation, are inherently based around the concept of a stack. To add items to a stack, use the 'Push' method. To get the value at the top of the stack, use 'Pop' (to pop off the top value) as follows: Stack myStack = new Stack(); myStack.Push("Message 1"); myStack.Push("Message 2"); myStack.Push("Message 3"); string msg3 = myStack.Pop(); There are others too, such as an ArrayList, SortedList, and a ReadOnlyCollection. However, the one big thing that many may not realise has been added to the collection's name space are the parallel tasking extensions. Along with the addition of the collections in the PLinq (Parallel Linq) namespaces, most of the structures in the standard system.collections namespace have now been extended to include operations such as 'AsParallel'. What this means is that, when performing Linq queries using these collections, you can apply AsParallel to allow the query to do multiple operations on multiple threads making best use of multi core machines. As well as these extensions, there are a number of interface types, allowing you to build custom data types easily, while using the underlying existing structures to avoid having to re-invent the wheel. If you want to explore the namespace further, the main MSDN page for it can be found at If there's anything you'd like to see covered in this column, please feel free to hunt me down on Twitter where I can be found as @shawty_ds. I also help run a small .NET users group on the Linked-in network, called Lidnug. Please feel free to swing by and say hello, and I'll see what I can do to get your topic included in this column. MrPosted by Gavin on 09/08/2014 07:40am Very nice refresh on that topic. I've personally not come across a reason to use a stack yet, but the Queue has soon some use for some front end scenarios. Nice to be reminded the others are there. RE: MrPosted by Peter Shaw on 09/26/2014 02:45pm Hi Gavin, Glad to hear it was useful to you, please do share your success stories to, I'm always interested in hearing the creative uses developers put these tools to.Reply MDPosted by Jim Reid on 09/01/2014 10:39am In the Bit Array example: byte[] myBytes = new byte[5] { 255, 255 }; BitArray myBA3 = new BitArray( myBytes ); (1): Shouldn't the first line read: byte[] myBytes = new byte[2] { 255, 255 }; The remaining 3 Bytes seem to be redundant. (2): I not sure why the variable name myBA3 has been so chosen. Did you mean myBA2 ? Sorry if I have misunderstood the example, but, if so, I would still be grateful for an explanation. Many thanks Jim Reid RE: MDPosted by Peter Shaw on 09/26/2014 02:49pm Hi Jim, Well spotted, yes that should indeed be only 2 bytes. I think maybe my caffeine level may have been a little low when I typed that. :-) As for BA3, well not quite sure why 'BA3' but the BA was supposed to be short form of 'BitArray' there's a good chance that was a caffine affected type too. Come find me on twitter - @shawty_ds I'll see if I can rustle you up a freebie for something dev related for spotting that one :-) ShawtyReply
https://www.codeguru.com/columns/dotnet/using-lists-and-stacks-in-.net.html
CC-MAIN-2018-43
refinedweb
1,329
69.41
Christopher F Baum Boston College and DIW Berlin 1 / 207 Introduction Introduction In this talk, I will discuss some ways in which you can use Stata more effectively in your work, and present some examples of recent enhancements to Stata that facilitate that goal. I rst discuss the several contexts of what it means to be a Stata programmer. Then, given your role as a user of Stata rather than a developer, we consider your motivation for achieving prociency in each of those contexts, and give examples of how such prociency may be valuable. I hope to convince you that a little bit of Stata programming goes a long way toward making your use of Stata more efcient and enjoyable. 2 / 207 Introduction First, some nomenclature related to programming: You should consider yourself a Stata programmer if you write do-les: sequences of Stata commands which you execute with the do command or by double-clicking on the le. You might also write what Stata formally denes as a program: a set of Stata commands that includes the program statement. A Stata program, stored in an ado-le, denes a new Stata command. As of version 9, you may use Statas new programming language, Mata, to write routines in that language that are called by ado-les. Any of these tasks involve Stata programming. 3 / 207 Introduction With that set of denitions in mind, we must deal with the why: why should you become a Stata programmer? After answering that essential question, we take up some of the aspects of how: how you can become a more efcient user of Stata by making use of programming techniques, be they simple or complex. 4 / 207 Introduction Using any computer program or language is all about efciency: not computational efciency as much as human efciency. You want the computer to do the work that can be routinely automated, allowing you to make more efcient use of your time and reducing human errors. Computers are excellent at performing repetitive tasks; humans are not. One of the strongest rationales for learning how to use programming techniques in Stata is the potential to shift more of the repetitive burden of data management, statistical analysis and the production of graphics to the computer. Lets consider several specic advantages of using Stata programming techniques in the three contexts enumerated above. 5 / 207 Using do-les Using a do-le to automate a specic data management or statistical task leads to reproducible research and the ability to document the empirical research process. This reduces the effort needed to perform a similar task at a later point, or to document the specic steps you followed for your co-workers or supervisor. Ideally, your entire research project should be dened by a set of do-les which execute every step from input of the raw data to production of the nal tables and graphs. As a do-le can call another do-le (and so on), a hierarchy of do-les can be used to handle a quite complex project. 6 / 207 Using do-les The beauty of this approach is exibility: if you nd an error in an earlier stage of the project, you need only modify the code and rerun that do-le and those following to bring the project up to date. For instance, an academic researcher may need to respond to a review of her papersubmitted months ago to an academic journalby revising the specication of variables in a set of estimated models and estimating new statistical results. If all of the steps producing the nal results are documented by a set of do-les, that task becomes straightforward. I argue that all serious users of Stata should gain some facility with do-les and the Stata commands that support repetitive use of commands. A few hours investment should save days of weeks of time over the course of a sizable research project. 7 / 207 Using do-les That advice does not imply that Statas interactive capabilities should be shunned. Stata is a powerful and effective tool for exploratory data analysis and ad hoc queries about your data. But data management tasks and the statistical analyses leading to tabulated results should not be performed with point-and-click tools which leave you without an audit trail of the steps you have taken. Responsible research involves reproducibility, and point-and-click tools do not promote reproducibility. For that reason, I counsel researchers to move their data into Stata (from a spreadsheet environment, for example) as early as possible in the process, and perform all transformations, data cleaning, etc. with Statas do-le language. This can save a great deal of time when mistakes are detected in the raw data, or when they are revised. 8 / 207 You may nd that despite the breadth of Statas ofcial and user-writen commands, there are tasks that you must repeatedly perform that involve variations on the same do-le. You would like Stata to have a command to perform those tasks. At that point, you should consider Statas ado-le programming capabilities. 9 / 207 Stata has great exibility: a Stata command need be no more than a few lines of Stata code, and once dened that command becomes a rst-class citizen." You can easily write a Stata program, stored in an ado-le, that handles all the features of ofcial Stata commands such as if exp, in range and command options. You can (and should) write a help le that documents its operation for your benet and for those with whom you share the code. Although ado-le programming requires that you learn how to use some additional commands used in that context, it may help you become more efcient in performing the data management, statistical or graphical tasks that you face. 10 / 207 My rst response to would-be ado-le programmers: dont! In many cases, standard Stata commands will perform the tasks you need. A better understanding of the capabilities of those commands will often lead to a researcher realizing that a combination of Stata commands will do the job nicely, without the need for custom programming. Those familiar with other statistical packages or computer languages often see the need to write a program to perform a task that can be handled with some of Statas unique constructs: the local macro and the functions available for handling macros and lists. If you become familiar with those tools, as well as the full potential of commands such as merge, you may recognize that your needs can be readily met. 11 / 207 The second bit of advice along those lines: use Statas search features such as findit and the Stata user community (via Statalist) to ensure that the program you envision writing has not already been written. In many cases an ofcial Stata command will do almost what you want, and you can modify (and rename) a copy of that command to add the features you need. In other cases, a user-written program from the Stata Journal or the SSC Archive (help ssc) may be close to what you need. You can either contact its author or modify (and rename) a copy of that command to meet your needs. In either case, the bottom line is the same advice: dont waste your time reinventing the wheel! 12 / 207 If your particular needs are not met by existing Stata commands nor by user-written software, and they involve a general task, you should consider writing your own ado-le. In contrast to many statistical programming languages and software environments, Stata makes it very easy to write new commands which implement all of Statas features and error-checking tools. Some investment in the ado-le language is needed (perhaps by taking a NetCourse on Stata programming) but a good understanding of the features of that languagesuch as the program and syntax statementsis not hard to develop. 13 / 207 A huge benet accrues to the ado-le author: few data management, statistical or graphical tasks are unique. Once you develop an ado-le to perform a particular task, you will probably run across another task that is quite similar. A clone of the ado-le, customized for the new task, will often sufce. In this context, ado-le programming allows you to assemble a workbench of tools where most of the associated cost is learning how to build the rst few tools. 14 / 207 Another rationale for many researchers to develop limited uency in Statas ado-le language: Statas maximum likelihood (ml) capabilities involves the construction of ado-le programs dening the likelihood function. The simulate, bootstrap and jackknife commands may be used with standard Stata commands, but in many cases may require that a command be constructed to produce the needed results for each repetition. Although the nonlinear least squares commands (nl, nlsur) may be used in an interactive mode, it is likely that a Stata program will often be the easiest way to perform any complex NLLS task. 15 / 207 16 / 207 The Mata programming environment is tightly integrated with Stata, allowing interchange of variables, local and global macros and Stata matrices to and from Mata without the necessity to make copies of those objects. A Mata program can easily generate an entire set of new variables (often in one matrix operation), and those variables will be available to Stata when the Mata routine terminates. Matas similarity to the C language makes it very easy to use for anyone with prior knowledge of C. Its handling of matrices is broadly similar to the syntax of other matrix programming languages such as MATLAB, Ox and GAUSS. Translation of existing code for those languages or from lower-level languages such as Fortran or C is usually quite straightforward. Unlike Statas C plugins, code in Mata is platform-independent, and developing code in Mata is easier than in compiled C. 17 / 207 In this section of the talk, I will mention a number of tools and tricks useful for do-le authors. Like any language, the Stata do-le language can be used eloquently or incoherently. Users who bring other languages techniques and try to reproduce them in Stata often nd that their Stata programs resemble Googles automated translation of French to English: possibly comprehensible, but a long way from what a native speaker would say. We present suggestions on how the language may be used most effectively. Although I focus on authoring do-les, these tips are equally useful for ado-le authors: and perhaps even more important in that context, as an ado-le program may be run many times. 18 / 207 20 / 207 21 / 207 The values from the return list and ereturn list may be used in computations: summarize famsize, detail scalar iqr = r(p75) - r(p25) scalar semean = r(sd) / sqrt(r(N)) display "IQR : " iqr display "mean : " r(mean) " s.e. : " semean will compute and display the inter-quartile range and the standard error of the mean of famsize. Here we have used Statas scalars to compute and store numeric values. In Stata, the scalar plays the role of a variable in a traditional programming language. 26 / 207 27 / 207 In many cases, the forvalues command will allow you to substitute explicit statements with a single loop construct. By modifying the range and body of the loop, you can easily rewrite your do-le to handle a different case. The foreach command is even more useful. It denes an iteration over any one of a number of lists: the contents of a varlist (list of existing variables) the contents of a newlist (list of new variables) the contents of a numlist the separate words of a macro the elements of an arbitrary list 29 / 207 For example, we might want to summarize each of these variables: foreach v of varlist price mpg rep78 { summarize v, detail } Or, run a regression on variables for each country, and graph the data and tted line: local eucty DE ES FR IT UK foreach c of local eucty { regress healthexpc incomec twoway (scatter healthexpc incomec) || /// (lfit healthexpc incomec) } 30 / 207 We can now illustrate how a local macro could be constructed by redenition: local eucty DE ES FR IT UK local alleps foreach c of local eucty { regress healthexpc incomec predict double epsc, residual local alleps "alleps epsc" } Within the loop we redene the macro alleps (as a double-quoted string) to contain itself and the name of the residuals from that countrys regression. We could then use the macro alleps to generate a graph of all ve countries residuals: tsline alleps 31 / 207 This technique can be used to automate a recode operation. Say that we had sequential codes for several countries (cc) coded as 14, and we wanted to apply IMF country codes to them: local ctycode 111 112 136 134 local i 0 foreach c of local ctycode { local ++i local rc "rc (i=c)" } display "rc" (1=111) (2=112) (3=136) (4=134) recode cc rc, gen(newcc) (400 differences between cc and newcc) 32 / 207 Introduction I now present a number of recipes for solving common problems in Stata do-le programming. These are taken from my book, An Introduction to Stata Programming, Stata Press, 2009. The concept behind this collection of recipes is that you may have a problem similar to one of those illustrated here. Differing somewhat, perhaps, but with enough similarity to provide guidance for the problems successful solution. Just as you might modify a recipe in the kitchen to deal with ingredients at hand or preferences of the dinner guests, you can modify a do-le recipe to meet your needs. 34 / 207 The problem: considering a number of related variables, you want to determine whether, for each observation, all variables satisfy a logical condition. Alternatively, you might want to know whether any satisfy that condition (for instance, taking on inappropriate values), or you might want to count how many of the variables satisfy the logical condition. 35 / 207 This would seem to be a natural application of egen as that command already contains a number of row-wise functions to perform computations across variables. For instance, the anycount() function counts the number of variables in its varlist whose values for each observation match those of an integer numlist, while the rowmiss() and rownonmiss() functions tabulate the number of missing and non-missing values for each observation, respectively. The three tasks above are all satised by egen functions from Nicholas Coxs egenmore package: rall(), rany() and rcount(), respectively. Why dont you just use those functions, then? 36 / 207 First, recall that egen functions are interpreted code. Unlike the built-in functions accessed by generate, the logic of an egen function must be interpreted each time it is called. For a large dataset, the time penalty can be signicant. Second, to use an egen function, you must remember that there is such a function, and remember its name. In addition to Statas ofcial egen functions, documented in on-line help, there are many user-written egen functions available, but you must track them down. For these reasons, current good programming practice suggests that you should avoid egen function calls in instances where the performance penalty might be an issue. This is particularly important within an ado-le program, but may apply to many do-les as well. In many cases, you can implement the logic of an egen function with a few lines of Stata commands. 37 / 207 Imagine that we have a dataset of household observations, where variables child1. . . child12 contain the current age of each child (or missing values for nonexistent offspring). We would like to determine the number of school-age children. We could compute nschool with a foreach loop: . generate nschool = 0 . foreach v of varlist child1-child12 { . replace nschool = nschool + inrange(v, 6, 18) . } The built-in inrange() function will execute more efciently than the interpreted logic within rcount(). 38 / 207 As a bonus, if we wanted to also compute an indicator variable signaling whether there are any school-age children in the household, we could do so within the same foreach loop: . . . . . . generate nschool = 0 generate anyschool = 0 foreach v of varlist child1-child12 { replace nschool = nschool + inrange(v, 6, 18) replace anyschool = max( anyschool, inrange(v, 6, 18)) } Note that in this case anyschool will remain at 0 for each observation unless one of the childrens ages match the criteria specied in the inrange function. Once it is switched to 1, it will remain so. 39 / 207 An alternative (and more computationally efcient) way of writing this code takes advantage of the fact that generate is much faster than replace, as the latter command must keep track of the number of changes made in the variable. Thus, we could write . . . . . foreach v of varlist child1-child12 { local nschool "nschool + inrange(v, 6, 18)" } generate byte nschool = nschool generate byte anyschool = nschool > 0 In this variation, the local macro is built up to include an inrange() clause for each of the possible 12 children. This version runs considerably faster on a large dataset. 40 / 207 41 / 207 What if you want to juxtapose the summary statistics for each aggregate unit with the individual observations in order to compute one or more variables for each record? For instance, you might have repeated-measures data for a physicans patients measuring their height, weight and blood pressure at the time of each ofce visit. You might want to ag observations where their weight is above their median weight, or when their blood pressure is above the 75th percentile of their repeated measurements. Computations such as these may be done with a judicious use of by-groups. For instance, . by patientid: egen medwt = median(weight) . by patientid: egen bp75 = pctile(bp), p(75) 42 / 207 We stress that you should avoid using variables to store constant values (which would occur if you omitted the by patientid: prex). But in these cases, we are storing a separate constant for each patientid. You may now compute indicators for weight, blood pressure and at-risk status, using the byte datatype for these binary variables: . generate byte highwt = weight > medwt & !missing(weight, medwt) . generate byte highbp = bp > bp75 & !missing(bp, bp75) . generate byte atrisk = highwt & highbp 43 / 207 If you need to calculate a sum for each group (patientid in this case), you can use the total() function for egen. Alternatively, to improve computational efciency, you could use . . . . by patientid: generate atriskvisits = sum(atrisk) by patientid: generate n_atrisk = atriskvisits if _n == _N gsort -n_atrisk list patientid n_atrisk if inrange(n_atrisk, 1, .) This sequence of commands uses the sum() function from generate, which is a running sum. Its value when _n == _N is the total for that patientid. We store that value as n_atrisk and sort it in descending order with gsort. The list command then prints one record per patientid for those patients with at least one instance of atrisk in their repeated measures. 44 / 207 The problem: you have hierarchical data such as observations of individual patient visits to a clinic. In the previous recipe, we described how summary statistics for each patient could be calculated. These include extrema: for instance, the highest weight ever recorded for each patient, or the lowest serum cholesterol reading. What you may need, however, is the record to date for those variables: the maximum (minimum) value observed so far in the sequence. This is a record value in the context of setting a record: for instance, maximum points scored per game, or minimum time recorded for the 100-yard dash. How might you compute these values for hierarchical data? 45 / 207 First, let us consider a single sequence (that is, data for a single patient in our example above). You might be tempted to think that this is a case where looping over observations will be essentialand you would be wrong! We exploit the fact that Statas generate and replace commands respect Statas sort order. We need only record the rst observations value and then use replace to generate the record high: . sort visitdate . generate maxwt = weight in 1 . replace maxwt = max(maxwt[\_n - 1], weight) in 2/l Unusually, you need not worry about missing values, as the max() function is smart enough to ignore them unless it is asked to compare missing with missing. 46 / 207 If we want to calculate a similar measure for each patientid in the dataset, we use the same mechanism: . sort patientid visitdate . by patientid: generate minchol = serumchol if _n == 1 . by patientid: replace minchol = /// min(minchol[_n - 1], serumchol) if _n > 1 With repeated measures data, we cannot refer to observations 1,2, and so on as those are absolute references to the entire dataset. Recall that under the control of a by-group, the _n and _N values are redened to refer to the observations in that by-group, allowing us to refer to _n in the generate command and the prior observation in that by-group with a [_n - 1] subscript. 47 / 207 The problem: you have ordered data (for instance, a time series of measurements) and you would like to examine spells in the data. These might be periods during which a qualitative condition is unchanged, as signaled by an indicator variable. As examples, consider the sequence of periods during which a patients cholesterol remains above the recommended level, or a worker remains unemployed, or a released offender stays clear of the law. Alternatively, they might signal repeated values of a measured variable, such as the number of years that a given team has been ranked rst in its league. Our concern with spells may involve identifying their existence and measuring their duration. 48 / 207 One solution to this problem involves using a ready-made Stata command, tsspell, written by Nicholas J. Cox. This command can handle any aspect of our investigation. It does require that the underlying data be dened as a Stata time series (for instance, with tsset. This makes it less than ideal if your data are ordered but not evenly spaced, such as patient visits to their physician which may be irregularly timed. Another issue arises, though: that raised above with respect to egen. The tsspell program is fairly complicated interpreted code, which may impose a computational penalty when applied to a very large dataset. You may only need one simple feature of the program for your analysis. Thus, you may want to consider analyzing spells in do-le code, perhaps much simpler than the invocation of tsspell. You generally can avoid explicit looping over observations, and will want to do so whenever possible. 49 / 207 Assume that you have a variable denoting the ordering of the data (which might be a Stata date or date-and-time variable, but need not be) and that the data have been sorted on that variable. The variable of interest is employer, which takes on values A,B,C... or missing for periods of unemployment. You want to identify the beginning of each spell with an indicator variable. How do we know that a spell has begun? The condition . generate byte beginspell = employer != employer[_n-1] will sufce to dene the start of each new spell (using the byte datatype to dene this indicator variable). Of course, the data may be left censored in the sense that we do not start observing the employees job history on her date of hire. But the fact that employer[_n-1] is missing for period 1 does not matter, as it will be captured as the start of the rst spell. What about spells of unemployment? If they are coded as a missing value of employer, they will be considered spells as well. Christopher F Baum (BC / DIW) Programming in Stata and Mata Adelaide, June 2010 50 / 207 First consider some ctitious data on an employee. She is rst observed working for rm A in 1987, then is laid off in 1990. After a spell of unemployment, she is hired by rm B in 1992, and so on. . Programming in Stata and Mata 1 Adelaide, June 2010 51 / 207 Notice that beginspell properly ags each change in employment status, including entry into unemployment. If we wanted to ag only spells of unemployment, we could do so with . generate byte beginunemp = missing(employer) & (employer != employer[_n-1]) which would properly identify years in which unemployment spells commenced as 1990, 1999 and 2006. 52 / 207 With an indicator variable agging the start of a spell, we can compute how many changes in employment status this employee has faced, as the count of that indicator variable provides that information. We can also use this notion to tag each spell as separate: . beginu~p 0 0 0 1 0 0 0 0 0 0 0 0 1 0 spellnr 1 1 1 2 2 3 3 3 3 3 4 5 6 6 7 Adelaide, June 2010 53 / 207 What if we now want to calculate the average wage paid by each employer? . sort spellnr . by spellnr: egen meanwage = mean(wage) Or the duration of employment with each employer (length of each employment spell)? . by spellnr: gen length = _N if !missing(employer) Here we are taking advantage of the fact that the time variable is an evenly spaced time series. If we had unequally spaced data, we would want to use Statas date functions to compute the duration of each spell. 54 / 207 This example may seem not all that useful as it refers to a single employees employment history. However, all of the techniques we have illustrated work equally well when applied in the context of panel or longitudinal data as long as they can be placed on a time-series calendar. If we add an id variable to these data and xtset id year, we may reproduce all of the results above by merely employing the by id: prex. In the last three examples, we must sort by both id and spell: for example, . sort id spellnr . bysort id spellnr: egen meanwage = mean(wage) is now required to compute the mean wage for each spell of each employee in a panel context. 55 / 207 A number of additional aspects of spells may be of interest. Returning to the single employees data, we may want to ag only employment spells at least three years long. Using the length variable, we may generate such as indicator as: . sort spellnr . by spellnr: gen length = _N if !missing(employer) (5 missing values generated) . generate byte longspell = (length >= 3 & !missing(length)) . list year employer length longspell, sepby(employer) noobs year 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 B B B B B C employer A A A length 3 3 3 . . 5 5 5 5 5 1 longsp~l 1 1 1 0 0 1 1 1 1 1 Programming in Stata and Mata 56 / 207 Create a text le, clinics.raw, containing two columns: the clinic ID (clinicid) and the SMSA FIPS code (smsa) For instance, 12367 12467 12892 13211 14012 ... 23435 29617 32156 1120 1120 1120 1200 4560 ... 5400 8000 9240 where SMSA codes 1120, 1200, 4560, 5400, 8000 and 9240 refer to the Boston, Brockton, Lowell, New Bedford, Springeld-Chicopee-Holyoke and Worcester, MA SMSAs, respectively. 58 / 207 Read the le into Stata with infile clinicid smsa using clinics, and save the le as Stata dataset clinic_char. Now use the patient le and give the commands . merge n:1 clinicid using clinic_char . tab _merge We use the n:1 form of the merge command to ensure that the clinic_char dataset has a single record per clinic. After the merge is performed you should nd that all patients now have an smsa variable dened. If there are missing values in smsa, list the clinicids for which that variable is missing and verify that they correspond to non-urban locations. When you are satised that the merge has worked properly, type . drop _merge 59 / 207 You have performed a one-to-many merge, attaching the same SMSA identier to all patients who have been treated at clinics in that SMSA. You may now use the smsa variable to attach SMSA-specic information to each patient record with merge. Unlike an approach depending on a long list of conditional statements such as . replace smsa=1120 if inlist(clinicid,12367,12467,12892,...) this approach leads you to create a Stata dataset containing your clinic ID numbers so that you may easily see whether you have a particular code in your list. This approach would be especially useful if you revise the list for a new set of clinics. 60 / 207 As Nicholas Cox has pointed out in a Stata FAQ, the above approach may also be fruitfully applied if you need to work with a subset of observations that satisfy a complicated criterion. This might be best dened in terms of an indicator variable that species the criterion (or its complement). The same approach may be used. Construct a le containing the identiers that dene the criterion (in the example above, the clinic IDs to be included in the analysis). Merge that le with your dataset and examine the _merge variable. That variable will take on values 1, 2 or 3, with a value of 3 indicating that the observation falls in the subset. You may then dene the desired indicator: . generate byte subset1 = _merge == 3 . drop _merge . regress ... if subset1 Using this approach, any number of subsets may be easily constructed and maintained, avoiding the need for complicated conditional statements. Christopher F Baum (BC / DIW) Programming in Stata and Mata Adelaide, June 2010 61 / 207 The problem: For each of a set of variables, you want to perform some steps that involve another group of variables, perhaps creating a third set of variables. These are parallel lists, but the variable names of the other lists may not be deducible from those of the rst list.How can these steps be automated? First, lets consider that we have two arbitrary sets of variable names, and want to name the resulting variables based on the rst sets variable names. For instance, you might have some time series of population data for several counties and cities: 62 / 207 . . . . . . . . local county Suffolk Norfolk Middlesex Worcester Hampden local cseat Boston Dedham Cambridge Worcester Springfield local wc 0 foreach c of local county { local ++wc local sn : word `wc of `cseat generate seatshare`county = `sn / `c } This foreach loop will operate on each pair of elements in the parallel lists, generating a set of new variables seatshareSuffolk, seatshareNorfolk. . . 63 / 207 Another form of this logic would use a set of numbered variables in one of the loops. In that case, you could use a forvalues loop over the values (assuming they were consecutive or otherwise patterned) and the extended macro function word of. . . to access the elements of the other loop. The tokenize command could also be used. Alternatively, you could use a forvalues loop over both lists, employing the word count extended macro function: . local n: word count `county . forvalues i = 1/`n { . local a: word `i of `county . local b: word `i of `cseat . generate seatshare`a = `b/`a . } 64 / 207 You may also nd this logic useful in handling a set of constant values that align with variables. Lets say that you have a cross-sectional dataset of hospital budgets over various years, in the wide structure: that is, separate variables for each year (e.g., exp1994, exp1997,. . . . You would like to apply a health care price deator to each variable to place them in comparable terms. For instance: . . . . . . . . local yr 1994 1997 2001 2003 2005 local defl 87.6 97.4 103.5 110.1 117.4 local n: word count `yr forvalues i = 1/`n { local y: word `i of local yr local pd: word `i of local defl generate rexp`y = exp`y * 100 / `pd } 65 / 207 This loop will generate a set of new variables measuring real expenditures, rexp1994, rexp1997,. . . by scaling each of the original (nominal valued) variables by (100/de) for that years value of the health care price deator. This could also be achieved by using reshape to transform the data into the long format, but that is not really necessary in this context. 66 / 207 The problem: if you have unbalanced panel data, how do you ensure that each unit has at least n observations available? It is straightforward to calculate the number of available observations for each unit. . xtset patient date . by patient: generate nobs = _N . generate want = (nobs >= n) These commands will produce an indicator variable, want, which selects those units which satisfy the condition of having at least n available observations. 67 / 207 This works well if all you care about is the number of observations available, but you may have a more subtle concern: you want to count consecutive observations. You may want to compute statistics based on changes in various measurements using Statas L. or D. time series operators Applying these operators to series with gaps will create missing values. A solution to this problem is provided by Nicholas J. Cox and Vince Wiggins in a Stata FAQ, How do I identify runs of consecutive observations in panel data? The sequence of consecutive observations is often termed a run or a spell. They propose dening the runs in the timeseries for each panel unit: 68 / 207 . . . . generate run = . by patient: replace run = cond(L.run == ., 1, L.run + 1) by patient: egen maxrun = max(run) generate wantn = (maxrun >= n) The second command replaces the missing values of run with either 1 (denoting the start of a run) or the prior value + 1. For observations on consecutive dates, that will produce an integer series 1,. . . ,.len where len is the last observation in the run. When a break in the series occurs, the prior (lagged) value of run will be missing, and run will be reset to 1. The variable maxrun then contains, for each patient, the highest value of run in that units sequence. 69 / 207 Although this identies (with indicator wantn) those patients who do (or do not) have a sequence or spell of n consecutive observations, it does not allow you to immediately identify this spell. You may want to retain only this longest spell, or run of observations, and discard other observations from this patient. To carry out this sort of screening, you should become familiar with Nicholas J. Coxs tsspell program (available from ssc), which provides comprehensive capabilities for spells in time series and panel data. A canned solution to the problem of retaining only the longest spell per patient is also available from my onespell routine, which makes use of tsspell. 70 / 207 The problem: If you have data on individuals that indicate their association with a particular entity, how do you count the number of entities associated with each individual? For instance, we may have a dataset of consumers who purchase items from various Internet vendors. Each observation identies the consumer (pid and the vendor (vid), where 1=amazon.com, 2=llbean.com, 3=overstock.com, and so on. Several solutions were provided by Nicholas J. Cox in a Statalist posting. 71 / 207 . bysort pid vid: generate count = ( _n == 1) . by pid : replace count = sum(count) . by pid : replace count = count(_N) Here, we consider each combination of consumer and vendor and set count = 1 for their rst observation. We then replace count with its sum() for each consumer, keeping in mind that this is a running sum, so that it takes on 1 for the rst vendor, 2 for the second, and so on. Finally, count is replaced with its value in observation _N for each consumer: the maximum number of vendors with whom she deals. 72 / 207 This solution takes advantage of the fact that when (vid) is used on the bysort prex, the data are sorted in order of vid within each pid, even though the pid is the only variable dening the by-group. When the vid changes, another value of 1 is generated and summed. When subsequent transactions pertain to the same vendor, vid != vid[_n-1] evaluates to 0, and those zero values are added to the sum. 73 / 207 This problem is common enough that an ofcial egen function has been developed to tag observations: . egen tag = tag( pid vid ) . egen count = total(tag), by(pid) The tag() function returns 1 for the rst observation of a particular combination of pid vid, and zero otherwise. Thus, its total() for each pid is the number of vids with whom she deals. As a last solution, Coxs egenmore package contains the nvals()egen nvals() function, which allows you to say . egen count = nvals(vid), by(pid) 74 / 207 To solve the problem, we dene a loop over rms. For each rm of the nf rms, we want to calculate the correlations between rm returns and the set of nind index returns, and nd the maximum value among those correlations. The variable hiord takes on values 19, while permno is an integer code assigned to each rm by CRSP. We set up a Stata matrix retcorr to hold the correlations, with nf rows and nind columns. The number of rms and number of indices are computed by the word count extended macro function applied to the local macro produced by levelsof. 76 / 207 . qui levelsof hiord, local(indices) . . . . local nind : word count `indices qui levelsof permno, local(firms) local nf : word count `firms matrix retcorr = J(`nf, `nind, .) We calculate the average return for each rm with summarize, meanonly. In a loop over rms, we use correlate to compute the correlation matrix of each rms returns, ret, with the set of index returns. For rm n, we move the elements of the last row of the matrix corresponding to the correlations with the index returns into the nth row of the retcorr matrix. We also place the mean for the nth rm into that observation of variable meanret. 77 / 207 . . . . . local n 0 qui gen meanret = . qui gen ndays = . local row = `nind + 1 foreach f of local firms { 2. qui correlate index1-index`nind ret if permno == `f 3. matrix sigma = r(C) 4. local ++n 5. forvalues i = 1/`nind { 6. matrix retcorr[`n, `i] = sigma[`row, `i] 7. } 8. summarize ret if permno == `f, meanonly 9. qui replace meanret = r(mean) in `n 10. qui replace ndays = r(N) in `n 11. } We now may use the svmat command to convert the retcorr matrix into a set of variables, retcorr1-retcorr9. The egen function rowmax() computes the maximum value for each rm. We then must determine which of the nine elements is matched by that maximum value. This number is stored in highcorr. Christopher F Baum (BC / DIW) Programming in Stata and Mata Adelaide, June 2010 78 / 207 . . . . svmat double retcorr qui egen double maxretcorr = rowmax(retcorr*) qui generate highcorr = . forvalues i = 1/`nind { 2. qui replace highcorr = `i if maxretcorr == retcorr`i /// > & !missing(maxretcorr) 3. } We now can sort the rm-level data in descending order of meanret, using gsort and list rms and their associated index fund numbers. These values show, for each rm, which index fund their returns most closely resemble. For brevity, we list only the fty best-performing rms. 79 / 207 . gsort -meanret highcorr . label values highcorr ind . list permno meanret ndays highcorr in 1/50, noobs sep(0) permno meanret ndays highcorr 24969 .0080105 53575 .0037981 64186 .0033149 91804 .0028613 86324 .0027118 60090 .0026724 88601 .0025065 73940 .002376 84788 .0023348 22859 .0023073 85753 .0022981 39538 .0021567 15667 .0019581 83674 .0019196 68347 .0019122 81712 .0018903 82686 .0017555 23887 .0017191 75625 .0017182 24360 .0016474 Christopher F Baum (BC / DIW) 68340 .0016361 8 Nu 465 Tau 459 Upsilon 1001 Psi 1259 Chi 1259 Upsilon 1250 Chi 531 Nu 945 Chi 1259 Lambda 489 Chi 1259 Nu 1259 Kappa 941 Chi 85 Kappa 1259 Chi 987 Chi 1259 Lambda 1259 Phi 1259 Lambda Programming in Stata and Mata 1259 Upsilon 80 / 207 The syntax statement will almost always be used to dene the commands format. For instance, a command that accesses one or more variables in the current data set will have a syntax varlist statement. With speciers, you can specify the minimum and maximum number of variables to be accepted; whether they are numeric or string; and whether time-series operators are allowed. Each variable name in the varlist must refer to an existing variable. Alternatively, you could specify a newvarlist, the elements of which must refer to new variables. 82 / 207 One of the most useful features of the syntax statement is that you can specify [if] and [in] arguments, which allow your command to make use of standard if exp and in range syntax to limit the observations to be used. Later in the program, you use marksample touse to create an indicator (dummy) temporary variable identifying those observations, and an if touse qualier on statements such as generate and regress. The syntax statement may also include a using qualier, allowing your command to read or write external les, and a specication of command options. 83 / 207 Option handling includes the ability to make options optional or required; to specify options that change a setting (such as regress, noconstant); that must be integer values; that must be real values; or that must be strings. Options can specify a numlist (such as a list of lags to be included), a varlist (to implement, for instance, a by( varlist) option); a namelist (such as the name of a matrix to be created, or the name of a new variable). Essentially, any feature that you may nd in an ofcial Stata command, you may implement with the appropriate syntax statement. See [P] syntax for full details and examples. 84 / 207 Within your own command, you do not want to reuse the names of existing variables or matrices. You may use the tempvar and tempname commands to create safe names for variables or matrices, respectively, which you then refer to as local macros. That is, tempvar eps1 eps2 will create temporary variable names which you could then use as generate double eps1 = .... These variables and temporary named objects will disappear when your program terminates (just as any local macros dened within the program will become undened upon exit). 85 / 207 So after doing whatever computations or manipulations you need within your program, how do you return its results? You may include display statements in your program to print out the results, but like ofcial Stata commands, your program will be most useful if it also returns those results for further use. Given that your program has been declared rclass, you use the return statement for that purpose. You may return scalars, local macros, or matrices: return return return return scalar teststat = testval local df = N - k local depvar "varname" matrix lambda = lambda These objects may be accessed as r(name) in your do-le: e.g. r(df) will contain the number of degrees of freedom calculated in your program. Christopher F Baum (BC / DIW) Programming in Stata and Mata Adelaide, June 2010 86 / 207 A sample program from help return: program define mysum, rclass version 10.0 syntax varname return local varname varlist tempvar new quietly { count if varlist!=. return scalar N = r(N) gen double new = sum(varlist) return scalar sum = new[_N] return scalar mean = return(sum)/return(N) } end 87 / 207 This program can be executed as mysum varname. It prints nothing, but places three scalars and a macro in the return list. The values r(mean), r(sum), r(N), and r(varname) can now be referred to directly. With minor modications, this program can be enhanced to enable the if exp and in range qualiers. We add those optional features to the syntax command, use the marksample command to delineate the wanted observations by touse, and apply if touse qualiers on two computational statements: 88 / 207 program define mysum2, rclass version 10.0 syntax varname [if] [in] return local varname varlist tempvar new marksample touse quietly { count if varlist!=. & touse return scalar N = r(N) gen double new = sum(varlist) if touse return scalar sum = new[_N] return scalar mean = return(sum)/return(N) } end 89 / 207 estimates the effects of the last four periods values of x on y. We might naturally be interested in the sum of the lag coefcients, as it provides the steady-state effect of x on y. This computation is readily performed with lincom. If this regression is run over a moving window, how might we access the information needed to perform this computation? Christopher F Baum (BC / DIW) Programming in Stata and Mata Adelaide, June 2010 90 / 207 A solution is available in the form of a wrapper program which may then be called by rolling:. We write our own r-class program, myregress, which returns the quantities of interest: the estimated sum of lag coefcients and its standard error. The program takes as arguments the varlist of the regression and two required options: lagvar(), the name of the distributed lag variable, and nlags(), the highest-order lag to be included in the lincom. We build up the appropriate expression for the lincom command and return its results to the calling program. 91 / 207 . type myregress.ado *! myregress v1.0.0 CFBaum 11aug2008 As with any program to be used under the control of a prex operator, it is a good idea to execute the program directly to test it to ensure that its results are those you could calculate directly with lincom. 92 / 207 . use wpi1, clear . qui myregress wpi L(1/4).wpi t, lagvar(wpi) nlags(4) . return list scalars: r(se) = .0082232176260432 r(sum) = .9809968042273991 . lincom L.wpi+L2.wpi+L3.wpi+L4.wpi ( 1) L.wpi + L2.wpi + L3.wpi + L4.wpi = 0 wpi (1) Coef. .9809968 Std. Err. .0082232 t 119.30 P>|t| 0.000 [95% Conf. Interval] .9647067 .9972869 Having validated the wrapper program by comparing its results with those from lincom, we may now invoke it with rolling: 93 / 207 . rolling sum=r(sum) se=r(se) ,window(30) : /// > myregress wpi L(1/4).wpi t, lagvar(wpi) nlags(4) (running myregress on estimation sample) Rolling replications (95) 1 2 3 4 5 .................................................. ............................................. 50 We may graph the resulting series and its approximate 95% standard error bands with twoway rarea and tsline: . tsset end, quarterly time variable: end, 1967q2 to 1990q4 delta: 1 quarter . label var end Endpoint . g lo = sum - 1.96 * se . g hi = sum + 1.96 * se . twoway rarea lo hi end, color(gs12) title("Sum of moving lag coefficients, ap > prox. 95% CI") /// > || tsline sum, legend(off) scheme(s2mono) 94 / 207 1970q1 1 97 5 q1 1 9 8 0q1 E ndpoint 19 8 5 q1 1 9 9 0 q1 95 / 207 96 / 207 We present a solution to this problem here in the context of an ado-le, onespell.ado. Dealing with this problemnding and retaining the single longest spell for each unit within the panelis quite straightforward in the case of a single variable. However, we want to apply this logic listwise, and delete shorter spells if any of the variables in a specied varlist are missing. The program builds upon Nicholas J. Coxs excellent tsspell command, which examines a single variable, optionally given a logical condition that denes a spell and creates three new variables: _spell, indicating distinct spells (taking on successive integer values); _seq, giving the sequence of each observation in the spell (taking on successive integer values); and _end, indicating the end of spells. If applied to panel data rather than a single timeseries, the routine automatically performs these observations for each unit of a panel. 97 / 207 In this rst part of the program, we dene the syntax of the ado-le. The program accepts a varlist of any number of numeric variables, if exp and in range options, and requires that the user provide a lename in the saving() option in which the resulting edited dataset will be stored. Optionally, the user may specify a replace option (which, as is usual in Stata, must be spelled out). The noisily option is provided for debugging purposes. The preserve command allows us to modify the data and return to the original dataset. 98 / 207 The tsset command allows us to retrieve the names of the panel variable and time variable. If the data are not tsset, the program will abort. The tsfill command lls any gaps in the time variable with missing observations. We then use marksample touse to apply any qualiers on the set of observations and dene a number of tempvars. For ease of exposition, I do not list the entire ado-le here. Rather, the rst piece of the code is displayed (as a text le), and the remainder (also as a text le) as a separate listing below a discussion of its workings. 99 / 207 . type onespell_part1.txt *! onespell 1.1.1 CFBaum 13jan2005 * locate units with internal gaps in varlist and zap all but longest spell program onespell, rclass version 10.1 syntax varlist(numeric) [if] [in], Saving(string) [ REPLACE NOIsily] preserve quietly tsset local pv "`r(panelvar)" local tv "`r(timevar)" summarize `pv, meanonly local n1 = r(N) tsfill marksample touse tempvar testgap spell seq end maxspell keepspell wantspell local sss = cond("`noisily" != "", "noisily", "quietly") 100 / 207 The real work is performed in the second half of the program. The temporary variable testgap is generated with the cond() function to dene each observation as either its value of the panel variable (pv) or missing. Coxs tsspell is then invoked on the testgap variable with the logical condition that the variable is non-missing. We explicitly name the three variables created by tsspell as temporary variables spell, seq and end. 101 / 207 In the rst step of pruning the data, we note that any observation for which spell = 0 may be discarded, along with any observations not dened in the touse restrictions. Now, for each panel unit, we consider how many spells exist. If spell > 1, there are gaps in the usable data. The longest spell for each panel unit is stored in temporary variable maxspell, produced by egen max() from the seq counter. Now, for each panel unit, we generate a temporary variable keepspell, identied by the longest observed spell (maxspell) for that unit. We then can calculate temporary variable wantspell with egen max(), which places the keepspell value in each observation of the desired spell. What if there are two (or more) spells of identical length? By convention, the latest spell is chosen by this logic. 102 / 207 We can now apply keep to retain only those observations, for each panel unit, associated with that units longest spell: those for which wantspell equals the spell number. The resulting data are then saved to the le specied in the saving() option, optionally employing replace, and the original data are restored. 103 / 207 . type onespell_part2.txt `sss { * testgap is panelvar if obs is usable, 0 otherwise generate `testgap = cond(`touse, `pv, .) tsspell `testgap if !missing(`testgap), spell(`spell) seq(`s > eq) end(`end) drop if `spell == 0 | `touse == 0 * if `spell > 1 for a unit, there are gaps in usable data * calculate max length spell for each unit and identify * that spell as the one to be retained egen `maxspell = max(`seq), by(`pv) generate `keepspell = cond(`seq==`maxspell, `spell, 0) egen `wantspell = max(`keepspell), by(`pv) * in case of ties, latest spell of max length is selected list `pv `tv `spell `seq `maxspell `keepspell `wantspell > , sepby(`pv) summarize `spell `wantspell keep if `wantspell == `spell summarize `pv, meanonly local n2 = r(N) drop \__* } display _n "Observations removed: " `n1-`n2 save `saving, `replace restore end 104 / 207 To illustrate, we modify the grunfeld dataset. The original dataset is a balanced panel of 20 years observations on 10 rms. We remove observations from different variables in rms 2, 3 and 5, creating two spells in rms 2 and 3 and three spells in rm 5. We then apply onespell: 105 / 207 . webuse grunfeld, clear . quietly replace invest = . in 28 . quietly replace mvalue = . in 55 . quietly replace kstock = . in 87 . quietly replace kstock = . in 94 . onespell invest mvalue kstock, saving(grun1) replace Observations removed: 28 file grun1.dta saved A total of 28 observations are removed. The tabulation shows that rms 2, 3 and 5 now have longest spells of 12, 14 and 6 years, respectively. 106 / 207 Percent 11.63 6.98 8.14 11.63 3.49 11.63 11.63 11.63 11.63 11.63 100.00 Cum. 11.63 18.60 26.74 38.37 41.86 53.49 65.12 76.74 88.37 100.00 Although this routine meets a specialized need, the logic that it employs may be useful in a number of circumstances for data management. 107 / 207 In this section of the talk, I will discuss writing egen functions and routines for use with the nl and nlsur (nonlinear least squares) and gmm (generalized method of moments) commands. 108 / 207 egen functions egen functions The egen (Extended Generate) command is open-ended, in that any Stata user may dene an additional egen function by writing a specialized ado-le program.The name of the program (and of the le in which it resides) must start with _g: that is, _gcrunch.ado will dene the crunch() function for egen. To illustrate egen functions, let us create a function to generate the 9010 percentile range of a variable. The syntax for egen is: egen type newvar = fcn(arguments) if in , options The egen command, like generate, may specify a data type. The syntax command indicates that a newvarname must be provided, followed by an equals sign and an fcn, or function, with arguments. egen functions may also handle if exp and in range qualiers and options. Christopher F Baum (BC / DIW) Programming in Stata and Mata Adelaide, June 2010 109 / 207 egen functions We calculate the percentile range using summarize with the detail option. On the last line of the function, we generate the new variable, of the appropriate type if specied, under the control of the touse temporary indicator variable, limiting the sample as specied. . type _gpct9010.ado *! _gpct9010 v1.0.0 CFBaum 11aug2008 program _gpct9010 version 10.1 syntax newvarname =/exp [if] [in] tempvar touse mark `touse `if `in quietly summarize `exp if `touse, detail quietly generate `typlist `varlist = r(p90) - r(p10) if `touse end 110 / 207 egen functions This function works perfectly well, but it creates a new variable containing a single scalar value. As noted earlier, that is a very proigate use of Statas memory (especially for large _N) and often can be avoided by retrieving the single scalar which is conveniently stored by our pctrange command. To be useful, we would like the egen function to be byable, so that it could compute the appropriate percentile range statistics for a number of groups dened in the data. The changes to the code are relatively minor. We add an options clause to the syntax statement, as egen will pass the by prex variables as a by option to our program. Rather than using summarize, we use egens own pctile()pctile() function, which is documented as allowing the by prex, and pass the options to this function. The revised function reads: 111 / 207 egen functions . type _gpct9010.ado *! _gpct9010 v1.0.1 CFBaum 11aug2008 program _gpct9010 version 10.1 syntax newvarname =/exp [if] [in] [, *] tempvar touse p90 p10 mark `touse `if `in quietly { egen double `p90 = pctile(`exp) if `touse, `options p(90) egen double `p10 = pctile(`exp) if `touse, `options p(10) generate `typlist `varlist = `p90 - `p10 if `touse } end These changes permit the function to produce a separate percentile range for each group of observations dened by the by-list. 112 / 207 egen functions Now, if we want to compute a summary statistic (such as the percentile range) for each observation classied in a particular subset of the sample, we may use the pct9010() function to do so. 113 / 207 You may perform nonlinear least squares estimation for either a single equation (nl) or a set of equations (nlsur). Although these commands may be used interactively or in terms of programmed substitutable expressions," most serious use is likely to involve your writing a function evaluator program. That program will compute the dependent variable(s) as a function of the parameters and variables specied. 114 / 207 The techniques used for a maximum likelihood function evaluator, as described earlier, are quite similar to those used by nl and nlsur function evaluator programs. For instance, we might want to estimate a constant elasticity of substitution (CES) production function 1 ln Qi = 0 ln Ki + (1 )L + i i which relates a rms output Qi to its use of capital, or machinery Ki and labor Li . The parameters in this highly nonlinear relationship are 0 , and . 115 / 207 We store the function evaluator program nlces.ado, as nl requires a program name that starts with the letters nl. As described in nl, the syntax statement must specify a varlist, allow for an if exp, and an option at(name). The parameters to be estimated are passed to your program in the row vector at. In our CES example, the varlist must contain exactly three variables, which are extracted from the varlist by the args command. This command assigns its three arguments to the three variable names provided in the varlist. For ease of reference, we assign tempnames to the three parameters to be estimated. The generate and replace statements make use of the if exp clause. The function evaluator program must replace the observations of the dependent variable: in this case, the rst variable passed to the program, referenced within as logoutput. 116 / 207 . type nlces.ado *! nlces v1.0.0 CFBaum 11aug2008 program nlces version 10.1 syntax varlist(numeric min=3 max=3) if, at(name) args logoutput K L tempname b0 rho delta tempvar kterm lterm scalar `b0 = `at[1, 1] scalar `rho = `at[1, 2] scalar `delta = `at[1, 3] gen double `kterm = `delta * `K^( -(`rho )) `if gen double `lterm = (1 - `delta) *`L^( -(`rho )) `if replace `logoutput = `b0 - 1 / `rho * ln( `kterm + `lterm ) `if end 117 / 207 We invoke the estimation process with the nl command using Statas production dataset. You specify the name of your likelihood function evaluator by including only the unique part of its name (that is, ces, not nlces), followed by @. The order in which the parameters appear in the parameters() and initial() options denes their order in the at vector. The initial() option is not required, but is recommended. 118 / 207 . use production, clear . nl ces @ lnoutput capital labor, parameters(b0 rho delta) /// > initial(b0 0 rho 1 delta 0.5) (obs = 100) Iteration 0: residual SS = 29.38631 Iteration 1: residual SS = 29.36637 Iteration 2: residual SS = 29.36583 Iteration 3: residual SS = 29.36581 Iteration 4: residual SS = 29.36581 Iteration 5: residual SS = 29.36581 Iteration 6: residual SS = 29.36581 Iteration 7: residual SS = 29.36581 Source SS df MS Number of obs Model 91.1449924 2 45.5724962 R-squared Residual 29.3658055 97 .302740263 Adj R-squared Root MSE Total 120.510798 99 1.21728079 Res. dev. lnoutput /b0 /rho /delta Coef. 3.792158 1.386993 .4823616 Std. Err. .099682 .472584 .0519791 t 38.04 2.93 9.28 P>|t| 0.000 0.004 0.000 = = = = = 119 / 207 After execution, you have access to all of Statas postestimation commands. For instance, the elasticity of substitution = 1/(1 + ) of the CES function is not directly estimated, but is rather a nonlinear function of the estimated parameters. We may use Statas nlcom command to generate point and interval estimates of using the delta method: . nlcom (sigma: 1 / ( 1 + [rho]_b[_cons] )) sigma: 1 / ( 1 + [rho]_b[_cons] ) lnoutput sigma Coef. .4189372 Std. Err. .0829424 t 5.05 P>|t| 0.000 [95% Conf. Interval] .2543194 .583555 This value, falling below unity in point and interval form, indicates that in the rms studied the two factors of production (capital and labor) are not very substitutable for one another. 120 / 207 The programming techniques illustrated here for nl carry over to the nlsur command (new in Stata version 10), which allows you to apply nonlinear least squares to a system of non-simultaneous (or seemingly unrelated) equations. Likewise, you could write a wrapper for nlces, as we illustrated before in the case of maximum likelihood, in order to create a new Stata command. 121 / 207 gmm programs gmm programs Like nl, Statas new gmm command may be used with either substitutable expressions or a moment-evaluator program. We focus here on the development of moment-evaluator programs, which are similar to the function-evaluator programs you might develop for maximum likelihood estimation (with ml or nonlinear least squares (nl, nlsur). A GMM moment-evaluator program receives a varlist and replaces its elements with the error part of each moment condition. An abbreviated form of the syntax for the gmm command is: gmm moment_pgm [ if ] [ in ], equations( moment_names ) /// parameters( param_names ) [instruments() options] 122 / 207 gmm programs For instance, say that we wanted to compute linear instrumental variables regression estimates via GMM. This is unnecessary, as ofcial ivregress and BaumSchafferStillman ivreg2 provide this estimator, but let us consider it for pedagogical purposes. We have a dependent variable y , a set of regressors X and an instrument matrix Z which contains the exogenous variables in X as well as additional excluded exogenous variables, or instruments. The moment conditions to be dened are the statements that each variable in Z is assumed to have zero covariance with the error term in the equation. We replace the population error term with its empirical counterpart, the residual e = (y Xb) where b is the vector of estimated parameters in the model. The moment-evaluator program computes this residual vector, while the gmm command species the variables to be included in Z . 123 / 207 gmm programs 124 / 207 gmm programs To invoke the program with the auto dataset, consider a model where mpg is the dependent variable, gear_ratio and turn are the explanatory variables, and we consider turn to be endogenous. The instrument matrix Z contains gear_ratio, length, headroom and a units vector. There is one equation (one vector of residuals) being computed, and three parameters to be estimated. As the gmm command does not have depvar or rhs options, the contents of those options are passed through to our moment-evaluator program. . gmm gmm_ivreg, nequations(1) nparameters(3) /// instruments(gear_ratio length headroom) depvar(mpg) /// rhs(gear_ratio turn) 125 / 207 gmm programs 74 126 / 207 gmm programs The gmm command may be used to estimate models that are not already programmed in Stata, including those containing nonlinear moment conditions, models with multiple equations and panel data models. This illustration merely lays the groundwork for more complex applications of GMM estimation procedures. For instance, we might want to apply Poisson regression in a panel data context. A standard Poisson regression may be written as y = exp(x ) + u If the x variables are strictly exogenous, this gives rise to the moment condition E[x{y exp(x )}] = 0 and we need only compute the residuals from this expression to implement GMM estimation. 127 / 207 gmm programs In a panel context, with an individual heterogeneity term (xed effect) i , we have E(yit |xit , i ) = exp(xit + i ) = it i where it = exp(xit and i = exp(i ). With an additive error term , we have the regression model yit = it i + it 128 / 207 gmm programs With strictly exogenous regressors, the sample moment conditions are xit i t yi yit it i =0 where the bar values are the means of y and for panel i. As i depends on the parameters of the model, it must be recalculated within the residual equation. 129 / 207 gmm programs 130 / 207 gmm programs Using the poisson1 dataset with three exogenous regressors, we estimate the model: . webuse poisson1, clear . gmm gmm_ppois, mylhs(y) myrhs(x1 x2 x3) myidvar(id) /// > nequations(1) parameters(b1 b2 b3) /// > instruments(x1 x2 x3, noconstant) vce(cluster id) /// > onestep nolog Final GMM criterion Q(b) = 5.13e-27 GMM estimation Number of parameters = 3 Number of moments = 3 Initial weight matrix: Unadjusted Number of obs = 409 (Std. Err. adjusted for 45 clusters in id) Robust Std. Err. .1000265 .0923592 .1156561 131 / 207 gmm programs In this estimation, we use our programs mylhs, myrhs and myidvar options to specify the model. The noconstant is used in the instrument list, as a separate intercept cannot be identied in the model, and the covariance matrix is cluster-robust by the id (panel) variable. The one-step GMM estimator is used, as with strictly exogenous regressors, the model is exactly identied, leading to a Hansen J of approximately zero. 132 / 207 Introduction to Mata Introduction to Mata Since the release of version 9, Stata contains a full-edged matrix programming language, Mata, with most of the capabilities of MATLAB, R, Ox or GAUSS. You can use Mata interactively, or you can develop Mata functions to be called from Stata. In this talk, we emphasize the latter use of Mata. Mata functions may be particularly useful where the algorithm you wish to implement already exists in matrix-language form. It is quite straightforward to translate the logic of other matrix languages into Mata: much more so than converting it into Statas matrix language. A large library of mathematical and matrix functions is provided in Mata, including optimization routines, equation solvers, decompositions, eigensystem routines and probability density functions. Mata functions can access Statas variables and can work with virtual matrices (views) of a subset of the data in memory. Mata also supports le input/output. Christopher F Baum (BC / DIW) Programming in Stata and Mata Adelaide, June 2010 133 / 207 Introduction to Mata Introduction to Mata The Mata programming language can sidestep these memory issues by creating matrices with contents that refer directly to Stata variablesno matter how many variables and observations may be referenced. These virtual matrices, or views, have minimal overhead in terms of memory consumption, regardless of their size. Unlike some matrix programming languages, Mata matrices can contain either numeric elements or string elements (but not both). This implies that you can use Mata productively in a list processing environment as well as in a numeric context. For example, a prominent list-handling command, Bill Goulds adoupdate, is written almost entirely in Mata. viewsource adoupdate.ado reveals that only 22 lines of code (out of 1,193 lines) are in the ado-le language. The rest is Mata. 135 / 207 Introduction to Mata Speed advantages Speed advantages Last but by no means least, ado-le code written in the matrix language with explicit subscript references is slow. Even if such a routine avoids explicit subscripting, its performance may be unacceptable. For instance, David Roodmans xtabond2 can run in version 7 or 8 without Mata, or in version 9 or 10 with Mata. The non-Mata version is an order of magnitude slower when applied to reasonably sized estimation problems. In contrast, Mata code is automatically compiled into bytecode, like Java, and can be stored in object form or included in-line in a Stata do-le or ado-le. Mata code runs many times faster than the interpreted ado-le language, providing signicant speed enhancements to many computationally burdensome tasks. 136 / 207 Introduction to Mata In the rest of this talk, I will discuss: Basic elements of Mata syntax Design of a Mata function Matas interface functions Some examples of StataMata routines 138 / 207 Operators Operators To understand Mata syntax, you must be familiar with its operators. The comma is the column-join operator, so : r1 = ( 1, 2, 3 ) creates a three-element row vector. We could also construct this vector using the row range operator (..) as : r1 = (1..3) The backslash is the row-join operator, so c1 = ( 4 \ 5 \ 6 ) creates a three-element column vector. We could also construct this vector using the column range operator (::) as : c1 = (4::6) Christopher F Baum (BC / DIW) Programming in Stata and Mata Adelaide, June 2010 139 / 207 Operators We may combine the column-join and row-join operators: m1 = ( 1, 2, 3 \ 4, 5, 6 \ 7, 8, 9 ) creates a 3 3 matrix. The matrix could also be constructed with the row range operator: m1 = ( 1..3 \ 4..6 \ 7..9 ) 140 / 207 Operators The prime (or apostrophe) is the transpose operator, so r2 = ( 1 \ 2 \ 3 ) is a row vector. The comma and backslash operators can be used on vectors and matrices as well as scalars, so r3 = r1, c1 will produce a six-element row vector, and c2 = r1 \ c1 creates a six-element column vector. Matrix elements can be real or complex, so 2 - 3 i refers to a complex number 2 3 1. Christopher F Baum (BC / DIW) Programming in Stata and Mata Adelaide, June 2010 141 / 207 Operators The standard algebraic operators plus (+), minus () and multiply () work on scalars or matrices: g = r1 + c1 h = r1 * c1 j = c1 * r1 In this example h will be the 1 1 dot product of vectors r1, c1 while j is their 3 3 outer product. 142 / 207 One of Matas most powerful features is the colon operator. Matas algebraic operators, including the forward slash (/) for division, also can be used in element-by-element computations when preceded by a colon: k = r1 :* c1 will produce a three-element column vector, with elements as the product of the respective elements: ki = r 1i c1i , i = 1, . . . , 3. 143 / 207 Matas colon operator is very powerful, in that it will work on nonconformable objects. For example: r4 m2 m3 m4 = = = = ( 1, 2, 3 ) ( 1, 2, 3 \ 4, 5, 6 \ 7, 8, 9 ) r4 :+ m2 m1 :/ r1 adds the row vector r4 to each row of the 3 3 matrix m2 to form m3, and divides the elements of each row of matrix m1 by the corresponding elements of row vector r1 to form m4. Matas scalar functions will also operate on elements of matrices: d = sqrt(c) will take the element-by-element square root, returning missing values where appropriate. Christopher F Baum (BC / DIW) Programming in Stata and Mata Adelaide, June 2010 144 / 207 Logical operators Logical operators As in Stata, the equality logical operators are a == b and a != b. They will work whether or not a and b are conformable or even of the same type: a could be a vector and b a matrix. They return 0 or 1. Unary not ! returns 1 if a scalar equals zero, 0 otherwise, and may be applied in a vector or matrix context, returning a vector or matrix of 0, 1. The remaining logical comparison operators (>, >=, <, <=) can only be used on objects that are conformable and of the same general type (numeric or string). They return 0 or 1. As in Stata, the logical and (&) and or (|) operators may only be applied to real scalars. Christopher F Baum (BC / DIW) Programming in Stata and Mata Adelaide, June 2010 145 / 207 Subscripting Subscripting Subscripts in Mata utilize square brackets, and may appear on either the left or right of an algebraic expression. There are two forms: list subscripts and range subscripts. With list subscripts, you can reference a single element of an array as x[i,j]. But i or j can also be a vector: x[i,jvec], where jvec= (4,6,8) references row i and those three columns of x. Missing values (dots) reference all rows or columns, so x[i,.] or x[i,] extracts row i, and x[.,.] or x[,] references the whole matrix. You may also use range operators to avoid listing each consecutive element: x[(1..4),.] and x[(1::4),.] both reference the rst four rows of x. The double-dot range creates a row vector, while the double-colon range creates a column vector. Either may be used in a subscript expression. Ranges may also decrement, so x[(3::1),.] returns those rows in reverse order. Christopher F Baum (BC / DIW) Programming in Stata and Mata Adelaide, June 2010 146 / 207 Subscripting Range subscripts use the notation [| |]. They can reference single elements of matrices, but are not useful for that. More useful is the ability to say x[| i,j \ m,n |], which creates a submatrix starting at x[i,j] and ending at x[m,n]. The arguments may be specied as missing (dot), so x[| 1,2 \4,. |] species the submatrix ending in the last column and x[| 2,2 \ .,.|] discards the rst row and column of x. They also may be used on the left hand side of an expression, or to extract a submatrix: v = invsym(xx)[| 2,2 \ .,.|] discards the rst row and column of the inverse of xx. You need not use range subscripts, as even the specication of a submatrix can be handled with list subscripts and range operators, but they are more convenient for submatrix extraction and faster in terms of execution time. 147 / 207 Loop constructs Loop constructs Several constructs support loops in Mata. As in any matrix language, explicit loops should not be used where matrix operations can be used. The most common loop construct resembles that of the C language: for (starting_value; ending_value; incr ) { statements } where the three elements dene the starting value, ending value or bound and increment or decrement of the loop. For instance: for (i=1; i<=10; i++) { printf("i=%g \n", i) } prints the integers 1 to 10 on separate lines. If a single statement is to be executed, it may appear on the for statement. Christopher F Baum (BC / DIW) Programming in Stata and Mata Adelaide, June 2010 148 / 207 Loop constructs You may also use do, which follows the syntax do { statements } while (exp) which will execute the statements at least once. Alternatively, you may use while: while(exp) { statements } which could be used, for example, to loop until convergence. 149 / 207 You may also use the conditional a ? b : c, where a is a real scalar. If a evaluates to true (nonzero), the result is set to b, otherwise c. For instance, if (k == 0) else can be written as dof = ( k==0 ? n-1 : n-k ) The increment (++) and decrement () operators can be used to manage counter variables. They may precede or follow the variable. The operator A # B produces the Kronecker or direct product of A and B. dof = n-1 dof = n-k 151 / 207 152 / 207 Element types may be real, complex, numeric, string, pointer, transmorphic. A transmorphic object may be lled with any of the other types. A numeric object may be either real or complex. Unlike Stata, Mata supports complex arithmetic. There are ve organization types: matrix, vector, rowvector, colvector, scalar. Strictly speaking the latter four are just special cases of matrix. In Statas matrix language, all matrices have two subscripts, neither of which can be zero. In Mata, all but the scalar may have zero rows and/or columns. Three- (and higher-) dimension matrices can be implemented by the use of the pointer element type, not to be discussed further in this talk. 153 / 207 Data access Data access If youre using Mata functions in conjunction with Statas ado-le language, one of the most important set of tools are Matas interface functions: the st_ functions. The rst category of these functions provide access to data. Stata and Mata have separate workspaces, and these functions allow you to access and update Statas workspace from inside Mata. For instance, st_nobs(), st_nvar() provide the same information as describe in Stata, which returns r(N), r(k) in its return list. Mata functions st_data(), st_view() allow you to access any rectangular subset of Statas numeric variables, and st_sdata(), st_sview() do the same for string variables. 155 / 207 st_view( ) st_view( ) One of the most useful Mata concepts is the view matrix, which as its name implies is a view of some of Statas variables for specied observations, created by a call to st_view(). Unlike most Mata functions, st_view() does not return a result. It requires three arguments: the name of the view matrix to be created, the observations (rows) that it is to contain, and the variables (columns). An optional fourth argument can specify touse: an indicator variable specifying whether each observation is to be included. st_view(x, ., varname, touse) States that the previously-declared Mata vector x should be created from all the observations (specied by the missing second argument) of varname, as modied by the contents of touse. In the Stata code, the marksample command imposes any if or in conditions by setting the indicator variable touse. Christopher F Baum (BC / DIW) Programming in Stata and Mata Adelaide, June 2010 156 / 207 st_view( ) The Mata statements real matrix Z st_view(Z=., ., .) will create a view matrix of all observations and all variables in Statas memory. The missing value (dot) specication indicates that all observations and all variables are included. The syntax Z=. species that the object is to be created as a void matrix, and then populated with contents. As Z is dened as a real matrix, columns associated with any string variables will contain all missing values. st_sview() creates a view matrix of string variables. 157 / 207 st_view( ) If we want to specify a subset of variables, we must dene a string vector containing their names. For instance, if varlist is a string scalar argument containing Stata variable names, void foo( string scalar varlist ) ... st_view(X=., ., tokens(varlist), touse) creates matrix X containing those variables. 158 / 207 st_data( ) st_data( ) An alternative to view matrices is provided by st_data() and st_sdata(), which copy data from Stata variables into Mata matrices, vectors or scalars: X = st_data(., .) places a copy of all variables in Statas memory into matrix X. However, this operation requires at least twice as much memory as consumed by the Stata variables, as Mata does not have Statas full set of 1-, 2-, and 4-byte data types. Thus, although a view matrix can reference any variables currently in Statas memory with minimal overhead, a matrix created by st_data() will consume considerable memory, just as a matrix in Statas own matrix language does. Similar to st_view(), an optional third argument to st_data() can mark out desired observations. Christopher F Baum (BC / DIW) Programming in Stata and Mata Adelaide, June 2010 159 / 207 160 / 207 A Mata function may take one (or several) existing variables and create a transformed variable (or set of variables). To do that with views, create the new variable(s), pass the name(s) as a newvarlist and set up a view matrix. st_view(Z=., ., tokens(newvarlist), touse) Then compute the new content as: Z[., .] = result of computation It is very important to use the [., .] construct as shown. Z = will cause a new matrix to be created and break the link to the view. 161 / 207 You may also create new variables and ll in their contents by combining these techniques: st_view(Z, ., st_addvar(("int", "float"), /// ("idnr", "bp"))) Z[., .] = result of computation In this example, we create two new Stata variables, of data type int and float, respectively, named idnr and bp. You may also use subviews and, for panel data, panelsubviews. We will not discuss those here. 162 / 207 Along the same lines, functions st_global, st_numscalar and st_strscalar may be used to retrieve the contents, create, or replace the contents of global macros, numeric scalars and string scalars, respectively. Function st_matrix performs these operations on Stata matrices. All of these functions can be used to obtain the contents, create or replace the results in r( ) or e( ): Statas return list and ereturn list. Functions st_rclear and st_eclear can be used to delete all entries in those lists. Read-only access to the c( ) objects is also available. The stata( ) function can execute a Stata command from within Mata. 164 / 207 165 / 207 In the same ado-le, we include the Mata routine, prefaced by the mata: directive. This directive on its own line puts Stata into Mata mode until the end statement is encountered. The Mata routine creates a Mata view of the variable. A view of the variable is merely a reference to its contents, which need not be copied to Matas workspace. Note that the contents have been ltered for missing values and those observations specied in the optional if or in qualiers. That view, labeled as X in the Mata code, is then a matrix (or, in this case, a column vector) which may be used in various Mata functions that compute the vectors descriptive statistics. The computed results are returned to the ado-le with the st_numscalar( ) function calls. 166 / 207 version 11 mata: void m_mysum(string scalar vname, string scalar touse) st_view(X, ., vname, touse) mu = mean(X) st_numscalar("N", rows(X)) st_numscalar("mu", mu) st_numscalar("sum" ,rows(X) * mu) st_numscalar("sigma", sqrt(variance(X))) end 167 / 207 For another example of a Mata function called from an ado-le, imagine that we did not have an easy way of computing the minimum and maximum of the elements of a Stata variable, and wanted to do so with Mata: program varextrema, rclass version 11 syntax varname(numeric) [if] [in] marksample touse mata: calcextrema( "`varlist", "`touse" ) display as txt " min ( `varlist ) = " as res r(min) display as txt " max ( `varlist ) = " as res r(max) return scalar min = r(min) return scalar max = r(max) end 168 / 207 Our ado-language code creates a Stata command, varextrema, which requires the name of a single numeric Stata variable. You may specify if exp or in range conditions. The Mata function calcextrema is called with two arguments: the name of the variable and the name of the touse temporary variable marking out valid observations. As we will see the Mata function returns its results in two numeric scalars: r(min), r(max). Those are returned in turn to the calling program in the varextrema return list. 169 / 207 170 / 207 The Mata code as shown is strict: all objects must be dened. The function is declared void as it does not return a result. A Mata function could return a single result to Mata, but we need to send two results back to Stata. The input arguments are declared as string scalar as they are variable names. We create a view matrix, colvector x, as the subset of varname for which touse==1. Matas colminmax() function computes the extrema of its arguments as a two-element vector, and st_numscalar() returns each of them to Stata as r(min), r(max) respectively. 171 / 207 A multi-variable function A multi-variable function Now lets consider a slightly more ambitious task. Say that you would like to center a number of variables on their means, creating a new set of transformed variables. Surprisingly, ofcial Stata does not have such a command, although Ben Janns center command does so. Accordingly, we write Stata command centervars, employing a Mata function to do the work. 172 / 207 A multi-variable function 173 / 207 A multi-variable function The le centervars.ado contains a Stata command, centervars, that takes a list of numeric variables and a mandatory generate() option. The contents of that option are used to create new variable names, which then are tested for validity with confirm new var, and if valid generated as missing. The list of those new variables is assembled in local macro newvars. The original varlist and the list of newvars is passed to the Mata function centerv() along with touse, the temporary variable that marks out the desired observations. 174 / 207 A multi-variable function 175 / 207 A multi-variable function In the Mata function, tokens( ) extracts the variable names from varlist and places them in a string rowvector, the form needed by st_view . The st_view function then creates a view matrix, X, containing those variables and the observations selected by if and in conditions. The view matrix allows us to both access the variables contents, as stored in Mata matrix X, but also to modify those contents. The colon operator (:-) subtracts the vector of column means of X from the data. Using the Z[,]= notation, the Stata variables themselves are modied. When the Mata function returns to Stata, the contents and descriptive statistics of the variables in varlist will be altered. 176 / 207 A multi-variable function One of the advantages of Mata use is evident here: we need not loop over the variables in order to demean them, as the operation can be written in terms of matrices, and the computation done very efciently even if there are many variables and observations. Also note that performing these calculations in Mata incurs minimal overhead, as the matrix Z is merely a view on the Stata variables in newvars. One caveat: Matas mean() function performs listwise deletion, like Statas correlate command. 177 / 207 Lets consider adding a feature to centervars: the ability to transform variables before centering with one of several mathematical functions (abs(), exp(), log(), sqrt()). The user will provide the name of the desired transformation, which defaults to the identity transformation, and Stata will pass the name of the function (actually, a pointer to the function) to Mata. We call this new command centertrans. 178 / 207 179 / 207 In Mata, we must dene wrapper functions" for the transformations, as we cannot pass a pointer to a built-in function. We dene trivial functions such as function mf_log(x) return(log(x)) which denes the mf_log() scalar function as taking the log of its argument. The Mata function centertrans() receives the function argument as pointer(real scalar function) scalar f To apply the function, we use Z[ ., . ] = (*f)(X) which applies the function referenced by f to the elements of the matrix X. Christopher F Baum (BC / DIW) Programming in Stata and Mata Adelaide, June 2010 180 / 207 181 / 207 A particularly important feature added to Mata in Stata version 10 is the suite of optimize() commands. These commands permit you to dene your own optimization routine in Mata and direct its use. The routine need not be a maximum-likelihood nor nonlinear least squares routine, but rather any well-dened objective function that you wish to minimize or maximise. Just as with ml, you may write a d0, d1 or d2 routine, requiring zero, rst or rst and second analytic derivatives in terms of the gradient vector and Hessian matrix. For ease of use in statistical applications, you may also construct a v0, v1 or v2 routine in terms of the score vector and Hessian matrix. For the rst time, Stata provides a non-classical optimization method, NelderMead simplex, in addition to the classical techniques available elsewhere in Stata. 183 / 207 The hols command takes a dependent variable and a set of regressors. The exog() option may be used to provide the names of additional variables uncorrelated with the error. By default, hols calculates estimates under the assumption of i.i.d. errors. If the robust option is used, the estimates standard errors are robust to arbitrary heteroskedasticity. Following estimation, the estimates post and estimates display commands are used to provide standard Stata estimation output. If the exog option is used, a SarganHansen J test statistic is provided. A signicant value of the J statistic implies rejection of the null hypothesis of orthogonality. 184 / 207 The Mata code makes use of a function to compute the covariance matrix: either the classical, non-robust VCE or the heteroskedasticity-robust VCE. For ease of reuse, this logic is broken out into a standalone function. version 11 mata: real matrix m_myomega(real rowvector beta, real colvector Y, real matrix X, real matrix Z, string scalar robust) { real matrix QZZ, omega real vector e, e2 real scalar N, sigma2 // Calculate residuals from the coefficient estimates N = rows(Z) e = Y - X * beta if (robust=="") { // Compute classical, non-robust covariance matrix QZZ = 1/N * quadcross(Z, Z) sigma2 = 1/N * quadcross(e, e) omega = sigma2 * QZZ } else { // Compute heteroskedasticity-consistent covariance matrix e2 = e:^2 omega = 1/N * quadcross(Z, e2, Z) } _makesymmetric(omega) return (omega) } Christopher F Baum (BC / DIW) Programming in Stata and Mata Adelaide, June 2010 186 / 207 The main Mata code takes as arguments the dependent variable name, the list of regressors, the optional list of additional exogenous variables, the marksample indicator (touse) and the robust ag. The logic for linear GMM can be expressed purely in terms of matrix algebra. 187 / 207 188 / 207 189 / 207 Sargan-Hansen J statistic: 0.000 . hols price mpg headroom, exog(trunk displacement weight) robust Heteroskedastic OLS results Number of obs = 74 Robust Std. Err. 60.375 313.6646 2067.6 190 / 207 As shown, this user-written estimation command can take advantage of all of the features of ofcial estimation commands. There is even greater potential for using Mata with nonlinear estimation problems, as its new optimize() suite of commands allows easy access to an expanded set of optimization routines. For more information, see Austin Nichols talk on GMM estimation in Mata from Summer NASUG 2008 at. 191 / 207 moremata If youre serious about using Mata, you should familiarize yourself with Ben Janns moremata package, available from SSC. The package contains a function library, lmoremata, as well as full documentation of all included routines (in the same style as Matas on-line function descriptions). Routines in moremata currently include kernel functions; statistical functions for quantiles, ranks, frequencies, means, variances and correlations; functions for sampling; density and distribution functions; root nders; matrix utility and manipulation functions; string functions; and input-output functions. Many of these functions provide functionality as yet missing from ofcial Mata, and ease the task of various programming chores. 192 / 207 In summary, then, it should be apparent that gaining some familiarity with Mata will expand your horizons as a Stata programmer. Mata may be used effectively in either its interactive or function mode as an efcient adjunct to Statas traditional command-line interface. We have not illustrated its usefulness for text processing problems (such as developing a concordance of words in a manuscript) but it could be fruitfully applied to such tasks as well. 193 / 207 Although the original example is geographical, the underlying task is found in many disciplines where a control group of observations is to be identied, each of which is the closest match to one of the observations of interest. For instance, in nance, you may have a sample of rms that underwent a takeover. For each rm, you would like to nd a similar rm (based on several characteristics) that did not undergo a takeover. Those pairs of rms are nearest neighbors. In our application, we will compute the Euclidian distance between the standardized values of pairs of observations. 195 / 207 To implement the solution, we rst construct a Stata ado-le dening program nneighbor which takes a varlist of one or more measures that are to be used in the match. In our application, we may use any number of variables as the basis for dening the nearest neighbor. The user must specify y, a response variable; matchobs, a variable to hold the observation numbers of the nearest neighbor; and matchval, a variable to hold the values of y belonging to the nearest neighbor. 196 / 207 After validating any if exp or in range conditions with marksample, the program conrms that the two new variable names are valid, then generates those variables with missing values. The latter step is necessary as we construct view matrices in the Mata function related to those variables, which must already exist. We then call the Mata function, mf_nneighbor(), and compute one statistic from its results: the correlation between the y() variable and the matchvals() variable, measuring the similarity of these y() values between the observations and their nearest neighbors. 197 / 207 . type nneighbor.ado *! nneighbor 1.0.1 CFBaum 11aug2008 program nneighbor version 11 syntax varlist(numeric) [if] [in], /// Y(varname numeric) MATCHOBS(string) MATCHVAL(string) marksample touse qui count if `touse if r(N) == 0 { error 2000 } // validate new variable names confirm new variable `matchobs confirm new variable `matchval qui generate long `matchobs = . qui generate `matchval = . mata: mf_nneighbor("`varlist", "`matchobs", "`y", /// "`matchval", "`touse") summarize `y if `touse, meanonly display _n "Nearest neighbors for `r(N) observations of `y" display "Based on L2-norm of standardized vars: `varlist" display "Matched observation numbers: `matchobs" display "Matched values: `matchval" qui correlate `y `matchval if `touse display "Correlation[ `y, `matchval ] = " %5.4f `r(rho) end 198 / 207 We now construct the Mata function. The function uses a view on the varlist, constructing view matrix X. As the scale of those variables affects the Euclidian distance (L2-norm) calculation, the variables are standardized in matrix Z using Ben Janns mm_meancolvar() function from the moremata package on the SSC Archive. Views are then established for the matchobs variable (C), the response variable (y) and the matchvals variable (ystar). 199 / 207 For each observation and variable in the normalized varlist, the L2-norm of distances between that observation and the entire vector is computed as d. The heart of the function is the call to minindex(). This function is a fast, efcient calculator of the minimum values of a variable. Its fourth argument can deal with ties; for simplicity we do not handle ties here. We request the closest two values, in terms of the distance d, to each observation, recognizing that each observation is its own nearest neighbor. The observation numbers of the two nearest neighbors are stored in vector ind. Therefore, the observation number desired is the second element of the vector, and y[ind[2]] is the value of the nearest neighbors response variable. Those elements are stored in C[i] and ystar[i], respectively. 200 / 207 . type mf_nneighbor.mata mata: mata clear mata: mata set matastrict on version 11 mata: // mf_nneighbor 1.0.0 CFBaum 11aug2008 void function mf_nneighbor(string scalar matchvars, string scalar closest, string scalar response, string scalar match, string scalar touse) { real matrix X, Z, mc, C, y, ystar real colvector ind real colvector w real colvector d real scalar n, k, i, j string rowvector vars, v st_view(X, ., tokens(matchvars), touse) // standardize matchvars with mm_meancolvar from moremata mc = mm_meancolvar(X) Z = ( X :- mc[1, .]) :/ sqrt( mc[2, .]) n = rows(X) k = cols(X) st_view(C, ., closest, touse) st_view(y, ., response, touse) st_view(ystar, ., match, touse) 201 / 207 (continued) // loop over observations for(i = 1; i <= n; i++) { // loop over matchvars d = J(n, 1, 0) for(j = 1; j <= k; j++) { d = d + ( Z[., j] :- Z[i, j] ) :^2 } minindex(d, 2, ind, w) C[i] = ind[2] ystar[i] = y[ind[2]] } } end 202 / 207 We now can try out the routine. We employ the usairquality dataset used in earlier examples. It contains statistics for 41 U.S. cities air quality (so2, or sulphur dioxide concentration) as well as several demographic factors. To test our routine, we rst apply it to a single variable: population (pop). Examining the result, we can see that it is properly selecting the city with the closest population value as the nearest neighbor: 203 / 207 . use usairquality, clear . sort pop . nneighbor pop, y(so2) matchobs(mo1) matchval(mv1) Nearest neighbors for 41 observations of so2 Based on L2-norm of standardized vars: pop Matched observation numbers: mo1 Matched values: mv1 Correlation[ so2, mv1 ] = 0.0700 . list pop mo1 so2 mv1, sep(0) pop mo1 so2 mv1 36 31 13 46 28 94 28 94 8 26 31 26 14 10 14 23 18 23 1. 71 2. 80 3. 116 4. 132 5. 158 6. 176 7. 179 8. 201 9. 244 10. 277 11. 299 12. 308 13. 335 14. 347 15. 361 16. 448 17. 453 Christopher F Baum 18. 463 2 31 1 36 4 46 3 13 6 56 7 28 6 94 7 17 10 11 11 8 12 26 11 31 14 10 13 14 14 9 17 18 16 23 (BC 17 / DIW) 11 204 / 207 We must note, however, that the response variables values are very weakly correlated with those of the matchvar. Matching cities on the basis of one attribute does not seem to imply that they will have similar values of air pollution. We thus exercise the routine on two broader sets of attributes: one adding temp and wind, and the second adding precip and days, where days measures the mean number of days with poor air quality. 205 / 207 . nneighbor pop temp wind, y(so2) matchobs(mo3) matchval(mv3) Nearest neighbors for 41 observations of so2 Based on L2-norm of standardized vars: pop temp wind Matched observation numbers: mo3 Matched values: mv3 Correlation[ so2, mv3 ] = 0.1769 . nneighbor pop temp wind precip days, y(so2) matchobs(mo5) matchval(mv5) Nearest neighbors for 41 observations of so2 Based on L2-norm of standardized vars: pop temp wind precip days Matched observation numbers: mo5 Matched values: mv5 Correlation[ so2, mv5 ] = 0.5286 We see that with the broader set of ve attributes on which matching is based, there is a much higher correlation between the so2 values for each city and those for its nearest neighbor. 206 / 207 In this last session, I encourage each of you to specify a statistical or data management problem for which you need programming assistance. We will develop possible solutions to these problems, emphasizing the use of programming principles discussed in the course. 207 / 207
https://fr.scribd.com/document/79665482/Good-Stata-Programming-Lecture
CC-MAIN-2019-35
refinedweb
16,346
59.64
Store and multiple filters Store and multiple filters Hi, i have a Ext.Store with static data. To filter with one param is no problem, but how can I apply multiple filters? In API Store.filter is defined as (filter,value) so i don't no how to apply more like company:ba,city:be etc. Why not to use Store::filterBy()?Use the force - read the source. - Join Date - Mar 2007 - Location - Notts/Redwood City - 30,498 - Vote Rating - 46 Yes, the documentation is totally clear: 2 params: Parameters: * fn : Function The function to be called, it will receive 2 args (record, id) * scope : Object (optional) The scope of the function (defaults to this) Filter by a function. The specified function will be called with each record in this data source. If the function returns true the record is included, otherwise it is filtered. Where's the problem? - Join Date - Mar 2007 - Location - Notts/Redwood City - 30,498 - Vote Rating - 46 That's a direct quote from the documentation. I'd like to preface this by saying that I am an EXT noob... and have really only been using the library for a few days now. That being said, I am also looking to apply multiple filters, but I was hoping to apply them in stages. ie. User does a search for something and the data is filtered, then the user does a second search on the already filtered data. I was hoping that you could simply do subsequent filterBy calls on the data store, but this appears to not be the case. My second filterBy seemingly searches ALL records [even ones previously filtered out]. Is there a way to do this? Thanks! I would be interested in this too. I would be interested in this too. ThanksSteven Benjamin Senior Coldfusion Developer filterBy not working but filter works!! filterBy not working but filter works!! Following code: var store = Ext.data.StoreManager.get("SampleStore"); store.filterBy(function (record) //scope is optional so I dint use it. { return (record.get("Name") == "Jack"); }); not working but store.filter("Name","Jack"); works!! Please help.
http://www.sencha.com/forum/showthread.php?12185-Store-and-multiple-filters&p=904951&viewfull=1
CC-MAIN-2014-35
refinedweb
351
67.25
article Python API clients with Tapioca Filipe Ximenes • 25 October 2016 In this post I'll present to you Tapioca, a Python library to create powerful API clients with very few lines of code. If you don't want to read through the reasons why I've built it, you may just jump straight to the Tapioca Wrapper section. Why do we need a better way to build API clients Integrating with external services is painful. Here at Vinta, we build and deal with both public and private APIs on the daily basis. Having worked in many of those projects I can safely tell that we are currently in hell when it comes to integrations. There are two ends in this mess: one is the result of poorly designed APIs and the other is the lack of standards and good practices for building API clients. It begins with API design. As we get away from RPC based architectures and move to more REST style systems, there is clearly a lack of well formed practical set of rules or at least a broad misunderstanding of the rules for building APIs. This is actually not a surprise since we were used to RPC and its well defined protocols while REST provides a set of guides, and is actually an architectural style. Luckily there are people trying to solve this problem, the json:api project is a good example of where we should aim for good design and standardization. On the other side there are people trying to use these poorly designed APIs. Most developers doing integrations don't want to deal with the complicated and unique patterns API creators freely chose for their systems. The easiest [and most common] way of trying to stay away from this mess is to use open source available API clients (or API wrappers). Which sounds like a good plan as long as you are doing a simple integration with a single service. As you move to multiple complex integrations you start noticing that the API client spectrum is as messy as the API services. Every single wrapper lib has it own unique way of dealing with authentication, pagination, versioning, throttling and parameter passing. Not to mention the huge amount of duplicated code to perform the exact same set of features among them. While we developers using public APIs do not have control over how they are built, we do have on the API client side. This takes us to Tapioca. Tapioca Wrapper Tapioca is a Python API client maker. It gathers most of the features API clients implement and puts them in an extensible core. Wrappers will then extend this core implementing only the specifics from each service (such as authentication and pagination) and get all the common API client features for free. Tapioca approach also comes in handy because regardless of the service, clients look the same in the way you interact with them. Once you've worked with a Tapioca lib you know how to use them all, no need to learn things from scratch. Here is the tapioca-facebook in action. >>> from tapioca_facebook import Facebook >>> >>> api = Facebook( And now the tapioca-twitter: >>> from tapioca_twitter import Twitter >>> >>> api = Twitter( >>> api_key='{your-api-id}', >>> api_secret='{your-api-secret}', >>> access_token='{your-access-token}', >>> access_token_secret='{your-access-token-secret}') >>> >>> statuses = api.statuses_user_timeline().get() >>> print(statuses[0].text) <TapiocaClient object ('RT @vintasoftware: Our latest blog post was featured in @thedjangoweekly and ' '@importpython newsletters! Go check it out:')> Pagination is also very easy and similar for both services. >>> feed = api.user_feed(id='me').get() >>> for item in feed().pages(): >>> print(item.id) ... Twitter: >>> statuses = api.statuses_user_timeline().get() >>> for item in statuses().pages(): >>> print(item.id) ... There are many other features (e.g.: serialization) you can check here. To give you an idea on how easy it is to build a client with Tapioca, here is the source code for the tapioca-facebook we just played with. See the code in the repository. from tapioca import ( TapiocaAdapter, generate_wrapper_from_adapter, JSONAdapterMixin) from requests_oauthlib import OAuth2 from .resource_mapping import RESOURCE_MAPPING class FacebookClientAdapter(JSONAdapterMixin, TapiocaAdapter): api_root = '' resource_mapping = RESOURCE_MAPPING def get_request_kwargs(self, api_params, *args, **kwargs): params = super(FacebookClientAdapter, self).get_request_kwargs( api_params, *args, **kwargs) params['auth'] = OAuth2( api_params.get('client_id'), token={ 'access_token': api_params.get('access_token'), 'token_type': 'Bearer'}) return params def get_iterator_list(self, response_data): return response_data['data'] def get_iterator_next_request_kwargs(self, iterator_request_kwargs, response_data, response): paging = response_data.get('paging') if not paging: return url = paging.get('next') if url: return {'url': url} Facebook = generate_wrapper_from_adapter(FacebookClientAdapter) That's right, it's a entire client lib from a 37 line file plus the [ridiculously simple] resource mapping. You can benefit from the flavours that were already developed. Or you can create a new Tapioca for a public API or your private service using the Cookiecutter template. Resources: Want read more about APIs? Check out these posts from our blog:
https://www.vinta.com.br/blog/2016/python-api-clients-with-tapioca/
CC-MAIN-2021-04
refinedweb
808
54.93
How to: Learn to read and write to the social feed by using the .NET client object model in SharePoint 2013 Create a console application that reads and writes to the social feed by using the SharePoint 2013 .NET client object model. Last modified: July 01, 2013 Applies to: SharePoint Server 2013 The console application that you’ll create retrieves a target user's feed and prints the root post from each thread in a numbered list. Then, it publishes a simple text reply to the selected thread. The same method (CreatePost) is used to publish both posts and replies to the feed. To create the console application, you'll need the following: SharePoint Server 2013 with My Site configured, with personal sites created for the current user and a target user, and with a few posts written by the target user Visual Studio 2012 Full Control access permissions to the User Profile service application for the logged-on user Core concepts to know about working with SharePoint 2013 social feeds Table 1 contains links to articles that describe core concepts you should know before you get started. On your development computer, open Visual Studio 2012. On the menu bar, choose File, New, Project. In the New Project dialog box, choose .NET Framework 4.5 from the drop-down list at the top of the dialog box. From the Templates list, choose Windows, and then choose the Console Application template. Name the project ReadWriteMySite, and then choose the OK button. Add references to the client assemblies, as follows: In Solution Explorer, open the shortcut menu for the ReadWriteMySite project, and then choose Add Reference. In the Reference Manager dialog box, choose the following assemblies: Microsoft.SharePoint.Client Microsoft.SharePoint.Client.Runtime Microsoft.SharePoint.Client.UserProfiles If you are developing on the computer that is running SharePoint Server 2013, the assemblies are in the Extensions category. Otherwise, browse to the location that has the client assemblies you downloaded (see SharePoint Client Components). In the Program.cs file, add the following using statements. Declare variables for the server URL and target user's account credentials. In the Main method, initialize the SharePoint client context. Create the SocialFeedManager instance. Specify the parameters for the feed content that you want to retrieve. The default options return the first 20 threads in the feed, sorted by last modified date. Get the target user's feed. GetFeedFor returns a ClientResult<T> object that stores the collection of threads in its Value property. The following code iterates through the threads in the feed. It checks whether each thread has the CanReply attribute and then gets the thread identifier and the text of the root post. The code also creates a dictionary to store the thread identifier (which is used to reply to a thread) and writes the text of the root post to the console. Dictionary<int, string> idDictionary = new Dictionary<int, string>(); for (int i = 0; i < feed.Value.Threads.Length; i++) { SocialThread thread = feed.Value.Threads[i]; string postText = thread.RootPost.Text; if (thread.Attributes.HasFlag(SocialThreadAttributes.CanReply)) { idDictionary.Add(i, thread.Id); Console.WriteLine("\t" + (i + 1) + ". " + postText); } } (UI-related only) Get the thread to reply to and prompt for the user's reply. Define the reply. The following code gets the reply’s text from the console application. Publish the reply. The threadToReplyTo parameter represents of the thread's Id property. (UI-related only) Exit the program. To test the console application, on the menu bar, choose Debug, Start Debugging. The following example is the complete code from the Program.cs file. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.Social; namespace ReadWriteMySite { class Program { static void Main(string[] args) { // Replace the following placeholder values with the target server running SharePoint and the // target thread owner. const string serverUrl = ""; const string targetUser = "domainName\\userName"; // Connect to the client context. ClientContext clientContext = new ClientContext(serverUrl); // Get the SocialFeedManager instance. SocialFeedManager feedManager = new SocialFeedManager(clientContext); // Specify the parameters for the feed content that you want to retrieve. SocialFeedOptions feedOptions = new SocialFeedOptions(); feedOptions.MaxThreadCount = 10; // Get the target owner's feed (posts and activities) and then run the request on the server. ClientResult<SocialFeed> feed = feedManager.GetFeedFor(targetUser, feedOptions); clientContext.ExecuteQuery(); // Create a dictionary to store the Id property of each thread. This code example stores // the ID so a user can select a thread to reply to from the console application. Dictionary<int, string> idDictionary = new Dictionary<int, string>(); for (int i = 0; i < feed.Value.Threads.Length; i++) { SocialThread thread = feed.Value.Threads[i]; // Keep only the threads that can be replied to. if (thread.Attributes.HasFlag(SocialThreadAttributes.CanReply)) { idDictionary.Add(i, thread.Id); // Write out the text of the post. Console.WriteLine("\t" + (i + 1) + ". " + thread.RootPost.Text); } } Console.Write("Which post number do you want to reply to? "); string threadToReplyTo = ""; int threadNumber = int.Parse(Console.ReadLine()) - 1; idDictionary.TryGetValue(threadNumber, out threadToReplyTo); Console.Write("Type your reply: "); // Define properties for the reply. SocialPostCreationData postCreationData = new SocialPostCreationData(); postCreationData.ContentText = Console.ReadLine(); // Post the reply and make the changes on the server. feedManager.CreatePost(threadToReplyTo, postCreationData); clientContext.ExecuteQuery(); Console.WriteLine("Your reply was published."); Console.ReadKey(false); // TODO: Add error handling and input validation. } } } To learn how to do more read tasks and write tasks with the social feed by using the .NET client object model, see the following:
https://msdn.microsoft.com/en-us/library/jj163246(d=printer).aspx
CC-MAIN-2015-27
refinedweb
907
52.05
[. Directory Services – the very core of an enterprise network Directory Services are found at the heart of every company’s network, because they provide the management system where all user, computer and other system credentials and rights are stored, as well as managed. In a Windows network this directory service is called Active Directory and requires special servers, called Domain Controllers, which are solely dedicated for this purpose. A new developer API to interact with and maintain these services was created at the time Active Directory replaced the older NT Domain model: ADSI.As the name says, it was created as a scripting interface based on COM technology to give administrators fast and easy access to the directory infrastructure. The ADSI syntax can be compared to WMI scripting, because the two technologies were created roughly in parallel. Here is a simple code snippet that shows how to move the ATL-Users group from the HR organizational unit into the Users container of the same domain: The first line of code binds the action to the Users container of the Fabrikam domain, which acts as the target. Careful, this approach needs some acclimatization when you start writing scripts! The second line then moves the ATL-Users group into the target container. TechNet and MSDN are your friends There are a lot of valuable script samples on the Microsoft TechNet site on how to accomplish day to day scripting tasks using ADSI. I explicitly state Technet, because developers normally turn to MSDN for coding information. Of course, there is a lot of additional information on MSDN, too, about the programmatic use of this API. Be aware that, due to the nature of the underlying COM technology, the effort required to use ADSI with native code (C++) is much higher than the effort required for scripting languages such as VBScript or Jscript. There is a managed wrapper for this API, as well. One needs to set a reference to the System.DirectoryServices.dll in the managed project and add this namespace to the code: After including this, AD is accessible from a managed embedded maintenance application or a custom shell running on e.g. a thin client device. Including ADSI in an embedded image There is one important thing necessary to make these code samples work. The ADSI components need to be added to the image configuration from the infrastructure node, as shown below. As one can see, there are additional providers for other non-Microsoft directory services, as well. This is great, because it enables embedded devices to integrate into 3rd party environments as first class citizens. The footprint impact of ADSI on an embedded image is relatively modest - around 20 MB. The impact of a .NET Framework component is much higher. One should also not forget to include this infrastructure for managed code or the Windows Scripting Technologies in an image. ADSI Tools There are some helpful tools available to make a developer or administrator’s life easier. The ADSI scriptomatic, including some entertainment, comes from the TechNet scripting guys. Really funny folks over there…. ADSIEDIT is part of the Windows support tools. It is a lightweight LDAP editor to manage objects and attributes in a directory. Not only AD! ADSI provides a valuable way to access and maintain the functionality of Internet Information Server (IIS) or Exchange Server, too. While having IIS on an embedded box is not too unrealistic, running Exchange Server certainly will present at least a licensing problem. - Alexander Alexander Wechsler Wechsler Consulting An issue was found with the April Security database update for Windows Embedded Standard 2009. Although database updates are not usually provided in odd-numbered months, the Embedded Windows July Security Update DVD image will include a database update for Windows Embedded Standard 2009 which corrects this issue. There are no database updates for other platforms, and as usual, the July security updates will be rolled into the database updates for all platforms in the even-month Security updates for August. OEM’s who have already deployed Embedded Standard 2009 images built with the April-2009 database update applied, and are experiencing versioning inconsistency, should apply the hotfix, scheduled for release at the end of July to correct these inconsistencies. - Gina **Updated at 5:47pm, 7/1/09: Correction-The June updates included both the componentized updates for applying to the database, as well as the updates in the \DQI folders that can be applied to runtimes. June Security updates include:, - Patrick This. Configure the Virtual Null Modem cable 1. Run the Virtual PC Console on the development machine by selecting Start-All Programs-Microsoft Virtual PC 1. Run the Virtual PC Console on the development machine by selecting Start-All Programs-Microsoft Virtual PC 2. Select your Target VM and click Settings 2. Select your Target VM and click Settings 3. In the Settings dialog click COM1 3. In the Settings dialog click COM1 4. Select Named Pipe and enter “\\.\pipe\mydebugpipe” for the value (without the quotes) 4. Select Named Pipe and enter “\\.\pipe\mydebugpipe” for the value (without the quotes) 5. Click OK 5. Click OK Configure the Target VM for Kernel Debugging. Note that this is one line in the file. Note that this is one line in the file. multi(0)disk(0)rdisk(0)partition(1)\WINDOWS="Microsoft Windows Embedded Standard" /noexecute=optin /fastdetect /DEBUG /DEBUGPORT=COM1 /BAUDRATE=115200 multi(0)disk(0)rdisk(0)partition(1)\WINDOWS="Microsoft Windows Embedded Standard" /noexecute=optin /fastdetect /DEBUG /DEBUGPORT=COM1 /BAUDRATE=115200 7. Shutdown the Target VM 7. Shutdown the Target VM Launch WinDbg We are going to use WinDbg to kernel debug the Target VM. Download and install it now if you do not have it already. 8. On the Development machine, open a Command Prompt 8. On the Development machine, open a Command Prompt 9. Launch WinDbg using the following command 9. Launch WinDbg using the following command <install-path-of-windbg>\windbg -k com:pipe,port=\\.\pipe\mydebugpipe,resets=0,reconnect <install-path-of-windbg>\windbg -k com:pipe,port=\\.\pipe\mydebugpipe,resets=0,reconnect Debug with WinDbg 10. Start the Target VM from the Virtual PC console and select the Microsoft Windows Embedded Standard [debugger enabled] operating system to start 10. Start the Target VM from the Virtual PC console and select the Microsoft Windows Embedded Standard [debugger enabled] operating system to start 11. At this point, WinDbg will connect and start to spew some information to the screen 11. At this point, WinDbg will connect and start to spew some information to the screen 12. In WinDbg, select Debug->Break 12. In WinDbg, select Debug->Break 13. Now select View->Call Stack from the WinDbg menu to see the current call stack of the OS 13. Now select View->Call Stack from the WinDbg menu to see the current call stack of the OS Well, I hope this introduction to kernel mode debugging was interesting and enjoyable. I did spare you the need to have two machines and string a null modem cable between the two. With this new knowledge, I suspect that you will find, or create, a need to do some kernel mode debugging in the near future. - Preston Technorati Tags: XPe,Standard 2009 In my previous screen cast I focused on importing a sound card driver inf into Component Designer in order to automatically generate a component. This video continues with the theme of interpreting and solving warnings that you receive when importing various kinds of driver infs, using a webcam and a printer driver as examples. - Lynda.. As a member of the Windows Embedded team, my business is embedded devices. For fun, I spend way too much time playing video games and following the video game industry. Whenever I can combine the two is always a bonus (this might be a stretch so you will have to bear with me). About this time each year the video game industry gathers in Los Angeles for the Electronics Entertainment Expo (it was June 2-4 this year). I have had the pleasure of attending in person on several occasions, but I always follow the happenings of E3 regardless. One of the major announcements from Microsoft was Project Natal for the Xbox 360. If you watch the video you will quickly see Project Natal promises gaming without controllers. I am very interested in the concept and how it will apply to traditional games, but I’m not so sure about utilizing the wardrobe selection feature (watch the video). If you look at the end of the video you will see the embedded device that provides the Project Natal functionality. I have already spent more than a few minutes staring at the paused video wondering what is inside that device and how it is doing what it is doing. BTW, in my continuing attempt to tie business with pleasure I plan on spending some time checking out the new Direct2D API’s for Windows 7 that replace GDI for programming 2D graphics. Available for download is a new Windows 7 Training Kit for Developers. This kit includes presentations, hands-on labs, and demos designed to help you learn how to build applications that shine on Windows 7 by utilizing key features such as: Want more than the kit and looking to download the Windows 7 Release Candidate? You can get the RC version and a product key for x86 & x64 here from this page. - Andy! . The complete IIS macro component pulls in about 100 MB of required functionality into a Windows Embedded Standard image. IIS therefore is not a good choice when it comes down to optimizing footprint, but if one just chooses the technologies needed for the individual device the impact can be reduced to a certain extent. However, if you need a more lean approach, for example for ASP.NET hosting capabilities, Microsoft’s Cassini web server sample may be worth a look. It comes as a 217k download and the footprint impact to an OS image is negligible. Usage scenarios This brings us to embedded use cases. Why on earth, would one include full-blown IIS in a Windows Embedded image? HTTP/FTP/etc. servers normally are an essential part of data center infrastructure and at first glance it seems strange to leverage this technology on an embedded device. But in fact, it is not. It is better to look at these servers from a different perspective, namely as being access doors for an embedded device to a network or the Internet. The FTP server, for example, can be leveraged to collect log files from a device, push down system updates or even complete OS image updates. The HTTP server is able to provide a web user interface, which can be essential to headless systems that do not provide other means to access them. In this scenario one is able to leverage a lot of different technologies out of the Microsoft web application portfolio. This starts with developing custom ISAPI extensions which trigger functionality based on the information included in a URL. ISAPI is the IIS API, through which developers are able to access the server’s functionality directly. The extensions provide minimal footprint, a high degree of functionality and good security. They normally are implemented as DLLs in native code. User Interfaces Another lean approach for developing a web UI is the use of classic Active Server Pages. This scripting technology leverages VBScript or Jscript, and it dominated dynamic web page creation before ASP.NET arrived. It is infamous for spaghetti code, mixing presentation as well as application logic on an HTML page, but nevertheless it works fine for simple to advanced presentation tasks. <% > The code snippet above shows how a simple database call could look like from an ASP page.ASP is included in the IIS Web server component and requires the Windows Scripting engines, which are about 1MB of additional footprint. If one wants to create state of the art web applications on IIS, ASP.NET can be used to implement compelling user experiences leveraging the full power of a managed environment. But keep in mind that the footprint impact is significant. ASP.NET always requires the full corresponding .NET Framework version. More resources for this technology can be found at the MSDN developer center or the official ASP.NET site. Web Services With ASP.NET the infrastructure to create not only UIs but Web Services is brought to an embedded device, as well. This is a very interesting usage scenario on connected embedded systems, which, with the help of suitable web services, turn into functionality nodes. These nodes then can be used by applications or others nodes to create agile systems and solutions. Security and operations Quite a while ago, IIS was infamous for the number of exploits and hacks targeted at this technology. Due its prominent role in Microsoft’s internet strategy it was, and still is, an interesting target to hackers and all sorts of malware programmers. Microsoft has addressed this very thoroughly by not doing a default install of IIS to all Windows systems as well as numerous security improvements and fixes. Nevertheless, providing a functionality gateway to the Internet always raises certain security issues. But, there is help! A lot of best practices, tools and resource kits are available on TechNet and Microsoft’s IIS site to address these issues. By applying best practices and protection mechanisms, is it not a problem to run embedded or other systems with IIS in a robust, reliable and secure fashion. I’ve recently read a few books on engineering and thought it might be worth sharing what I thought of some of them with our community. So here are my reviews of three books; hopefully you’ll find the reviews useful. The Pencil by Henry Petroski is commonly found on suggested reading lists for engineers, but I feel it is not his best work. I enjoyed much more the other two books I’ve read by Petroski – The Evolution of Useful Things and Success through Failure, the Paradox of Design. In The Pencil, Petroski attempts a detailed study of the history of the design and manufacturing of what was an essential tool for engineers. His purpose is to illustrate that even with a mundane object like a pencil there are genuine and significant engineering problems in its production. He succeeds in making his point. However, an underlying theme is revealed in this effort, but left to the other two books to be explored in greater detail. In The Evolution of Useful Things, Petroski examines the history and development of several ordinary objects to convincingly make the point that the “evolution of form begins with the perception of failure”. By tracing the history of objects like the paper clip, Petroski is able to show how each successive design was an attempt to remedy failings of its own antecedents. This process has culminated in the modern paper clip which, while certainly not the perfect design, has not been supplanted for more than 100 years. In the third book, Success through Failure, Petroski studies both successful and failed designs of large and small objects. By defining failure as an “unacceptable difference between expected and observed performance”, he proceeds to make the case that the most successful designs are ones which are “based on the best and most complete assumptions about failure.” Later, Petroski goes even further to say that: There are two approaches to any engineering or design problem: success-based or failure-based. Paradoxically, the latter is far more likely to succeed. There are two approaches to any engineering or design problem: success-based or failure-based. Paradoxically, the latter is far more likely to succeed. Perhaps it’s because I’ve spent much of my career thinking about how things can fail, but Success through Failure is my favorite of the three books. I particularly liked the discussion of how an unanticipated, shall we say, use case scenario embarrassed a security device company. Read and enjoy. -Jim In my? The first post in the Windows Embedded Installer Testing series discussed a detailed level of the testing process that the installer undergoes. The purpose of this second post is to give a higher-level view of this process by introducing the automation test framework used in testing the installer along with many features of Windows Embedded Tools. Implementing automated tests has many advantages which include: The framework: At Microsoft, there is a test automation framework that is internally developed and heavily used throughout different teams across the company. Much like any other test automation framework, this tool functions as follows: Fig. 1 Fig. 1 gives a visual representation of the process mentioned above. In the case of running test cases for the Windows Embedded installer, the test client machines are usually running the installer specific test cases such as installing/file checking/uninstalling simultaneously and reporting back the result to the test controller PC where the test engineer monitors those test to ensure that the installer’s quality is meeting the expected high quality metrics. Finally, for readers who are interested in learning more about test automation frameworks and to have some hands-on experience in it, I recommend trying out some of the open source automation frameworks. STAF (Software Testing Automation Framework) is one of the many open source frameworks that you can find online. More information about STAF can be found here -Sami Technorati Tags: XPe,Windows Installer,Standard 2009,Testing Trademarks | Privacy Statement
http://blogs.msdn.com/embedded/default.aspx
crawl-002
refinedweb
2,927
53.41
Click on one of the following Links to navigate through the project page: See the project in action: German demonstration: Controlling a VW CAN BUS dashboard of a Polo 6R with an Arduino and a CAN BUS shield using the Telemetry API of Euro Truck Simulator 2 Click on one of the following Links to navigate through the project page: See the project in action: German demonstration: &&...Read more »! Happy Holidays to all of you! The last few days I worked pretty hard on finding new functions of some CAN Commands for the dashboard! New functions I found: Hello Tech-Enthusiasts! I just updated the thumbnails for this project. Therefore I got help in a photo studio to take some better profile pics. I hope you enjoy them! Known CAN Codes so far: For CAN Codes please visit the Sources-Page. Instruction Video: Arduino Source Code: //############################################################################################################## //Volkswagen CAN BUS Gaming //Test Sketch v3.0 //(C) by Leon Bataille 2015-2016 //Hackaday Project Page: //Sketch information #DO NOT REMOVE! String game = "VW Static v3.0"; String vendor = "Leon Bataille"; //END Sketch information //For individual setup scroll down to the section MAIN CONFIGURATION //############################################################################################################## //Libraries #include <mcp_can.h> //CAN Bus Shield Compatibility Library #include <SPI.h> //CAN Bus Shield SPI Pin Library #include <Servo.h> //Library for Controlling Servos #include <Wire.h> //Extension Library for measuring current #include <LiquidCrystal_I2C.h> //Libraries for controlling LC Displays #include <LCD.h> #include <LiquidCrystal.h> //Definition #define lo8(x) ((int)(x)&0xff) #define hi8(x) ((int)(x)>>8) //Variables (Dashboard LEDs) int high_beam = 13; int fog_beam = 12; int park_brake = 11; //Variables (VW Dashboard Adapter) int LEFT_INDICATOR = A0; int RIGHT_INDICATOR = A1; int PARKING_BREAK = A2; int FUEL_WARNING = A3; //Variables (Dashboard Functions) int turning_lights = 3; boolean turning_lights_blinking = true; int turning_lights_counter = 0; int temp_turning_lights = 0; boolean backlight = false; int oilpswitch = 8; int pack_counter = 0; boolean add_distance = false; int drive_mode = 0; int distance_multiplier = 2; boolean oil_pressure_simulation = true; boolean door_open = false; boolean clutch_control = false; int temp_clutch_control = 0; boolean check_lamp = false; int temp_check_lamp = 0; boolean trunklid_open = false; int temp_trunklid_open = 0; boolean battery_warning = false; int temp_battery_warning = 0; boolean keybattery_warning = false; int temp_keybattery_warning = 0; int lightmode = 0; boolean seat_belt = false; int temp_seat_belt = 0; int engine_control = 0; int temp_dpf_warning = 0; boolean dpf_warning = false; boolean light_fog = false; int temp_light_fog = 0; boolean light_highbeam = false; int temp_light_highbeam = 0; boolean signal_abs = false; boolean signal_offroad = false; boolean signal_handbrake = false; boolean signal_lowtirepressure = false; boolean signal_dieselpreheat = false; boolean signal_watertemp = false; int temp_signal_abs = 0; int temp_signal_offroad = 0; int temp_signal_handbrake = 0; int temp_signal_lowtirepressure = 0; int temp_signal_dieselpreheat = 0; int temp_signal_watertemp = 0; //Variables (Speed and RPM) int speed = 0; byte speedL = 0; byte speedH = 0; int rpm = 0; short tempRPM = 0; byte rpmL = 0; byte rpmH = 0; int distance_adder = 0; int distance_counter = 0; //Variables LCD LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Addr, En, Rw, Rs, d4, d5, d6, d7, backlightpin, polarity //Variables CAN BUS /* the cs pin of the version after v1.1 is default to D9 v0.9b and v1.0 is default D10 */ const int SPI_CS_PIN = 9; MCP_CAN CAN(SPI_CS_PIN); // Set CS pin //Setup Configuration void setup() { //Initialize LCD lcd.begin(16,2); lcd.backlight(); showLCD("VW Dashboard","by Leon Bataille"); delay(2000); showLCD("VW Dashboard","booting..."); //Define Dashboard LEDs as Outputs pinMode(high_beam, OUTPUT); pinMode(fog_beam, OUTPUT); pinMode(park_brake, OUTPUT); pinMode(oilpswitch, OUTPUT); //Visual Start Sequence on Dashboard digitalWrite(high_beam, HIGH); digitalWrite(fog_beam, HIGH); digitalWrite(park_brake, LOW); digitalWrite(PARKING_BREAK, HIGH); delay(500); // wait for a second digitalWrite(high_beam, LOW); digitalWrite(FUEL_WARNING, HIGH); digitalWrite(PARKING_BREAK, LOW); delay(500); digitalWrite(FUEL_WARNING, LOW); digitalWrite(LEFT_INDICATOR, HIGH); digitalWrite(RIGHT_INDICATOR, HIGH); digitalWrite(fog_beam, LOW); delay(500); digitalWrite(LEFT_INDICATOR, LOW); digitalWrite(RIGHT_INDICATOR, LOW); //Begin with Serial Connection Serial.begin(115200); //Show Sketch information on LCD showLCD(game,"by "+vendor); //Begin with CAN Bus Initialization START_INIT: if(CAN_OK == CAN.begin(CAN_500KBPS)) // init can bus : baudrate = 500k { Serial.println("CAN BUS Shield init ok!"); } else { Serial.println("CAN BUS Shield init fail"); Serial.println("Init CAN BUS Shield again"); delay(100); goto START_INIT; } } //Reload LC Display void showLCD(String line1,String line2) { lcd.clear(); lcd.setCursor(0, 0); lcd.print(line1); lcd.setCursor(0, 1); lcd.print(line2); } //Send CAN Command (short version) void CanSend(short address, byte a, byte b, byte c, byte d, byte e, byte f, byte g, byte h) { unsigned char DataToSend[8] = {a,b,c,d,e,f,g,h}; CAN.sendMsgBuf(address, 0, 8, DataToSend); } //fuel gauge (0-100%) void Fuel(int amount) { pinMode(2, INPUT); pinMode(3, INPUT); pinMode(4, INPUT); pinMode(5, INPUT); pinMode(6, INPUT); pinMode(7, INPUT); if (amount >= 90) { pinMode(2, OUTPUT); digitalWrite(2, LOW); return; } if (amount >= 75) { pinMode(3, OUTPUT); digitalWrite(3, LOW); return; } if (amount >= 50) { pinMode(4, OUTPUT); digitalWrite(4, LOW); return; } if (amount >= 25) { pinMode(5, OUTPUT); digitalWrite(5, LOW); return; } if (amount >= 10) { pinMode(6, OUTPUT); digitalWrite(6, LOW); return; } if (amount >= 0) { pinMode(7, OUTPUT); digitalWrite(7, LOW); return; } } //Loop void loop() { //############################################################################################################## //MAIN SETUP FOR OPERATION //Set constant speed and RPM to show on Dashboard speed = 0; //Set the speed in km/h rpm = 800; //Set the rev counter Fuel(30); //Set the fuel gauge in percent //Set Dashboard Functions backlight = true; //Turn the automatic dashboard backlight on or off turning_lights = 0; //Turning Lights: 0 = none, 1 = left, 2 = right, 3 = both turning_lights_blinking = false; //Choose the mode of the turning lights (blinking or just shining) add_distance = false; //Dashboard counts the kilometers (can't be undone) distance_multiplier = 2; //Sets the refresh rate of the odometer (Standard 2) signal_abs = false; //Shows ABS Signal on dashboard signal_offroad = false; //Simulates Offroad drive mode signal_handbrake = false; //Enables handbrake signal_lowtirepressure = false; //Simulates low tire pressure oil_pressure_simulation = true; //Set this to true if dashboard starts to beep door_open = false; //Simulate open doors clutch_control = false; //Displays the Message "Kupplung" (German for Clutch) on the dashboard's LCD check_lamp = false; //Show 'Check Lamp' Signal on dashboard. B00010000 = on, B00000 = off trunklid_open = false; //Simulate open trunk lid (Kofferraumklappe). B00100000 = open, B00000 = closed battery_warning = false; //Show Battery Warning. keybattery_warning = false; //Show message 'Key Battery Low' on Display. But just after first start of dashboard. light_fog = false; //Enable Fog Light light_highbeam = false; //Enable High Beam Light seat_belt = false; //Switch Seat Betl warning light. signal_dieselpreheat = false; //Simualtes Diesel Preheating signal_watertemp = false; //Simualtes high water temperature dpf_warning = false; //Shows the Diesel particle filter warning signal. //############################################################################################################## //Conversion Speed speed = speed / 0.0075; //KMH=1.12 MPH=0.62 //Conversion Low and High Bytes speedL = lo8(speed); speedH = hi8(speed); tempRPM = rpm*4; rpmL = lo8(tempRPM); rpmH = hi8(tempRPM); if (add_distance == true) { distance_adder = speed * distance_multiplier; distance_counter += distance_adder; if (distance_counter > distance_adder) { distance_counter = 0; } } if ( oil_pressure_simulation == true) { //Set Oil Pressure Switch if (rpm > 1500) { digitalWrite(oilpswitch, LOW); } else { digitalWrite(oilpswitch, HIGH); } } /*Send CAN BUS Data*/ //Immobilizer CanSend(0x3D0, 0, 0x80, 0, 0, 0, 0, 0, 0); //Engine on and ESP enabled CanSend(0xDA0, 0x01, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00); //Enable Cruise Control //CanSend(0x289, 0x00, B00000001, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00); //Dashboard Functions //Turning Light blinking if (turning_lights_blinking == true) { if (turning_lights_counter == 15) { temp_turning_lights = turning_lights; turning_lights_counter = turning_lights_counter + 1; } if (turning_lights_counter == 30) { temp_turning_lights = 0; turning_lights_counter = 0; } else { turning_lights_counter = turning_lights_counter + 1; } } else { temp_turning_lights = turning_lights; } //Check main settings //DPF if (dpf_warning == true) temp_dpf_warning = B00000010; else temp_dpf_warning = B00000000; //Seat Belt if (seat_belt == true) temp_seat_belt = B00000100; else temp_seat_belt = B00000000; //Battery Warning if (battery_warning == true) temp_battery_warning = B10000000; else temp_battery_warning = B00000000; //Trunk Lid (Kofferraumklappe) if (trunklid_open == true) temp_trunklid_open = B00100000; else temp_trunklid_open = B00000000; //Check Lamp Signal if (check_lamp == true) temp_check_lamp = B00010000; else temp_check_lamp = B00000000; //Clutch Text on LCD if (clutch_control == true) temp_clutch_control = B00000001; else temp_clutch_control = B00000000; //Warning for low key battery if (keybattery_warning == true) temp_keybattery_warning = B10000000; else temp_keybattery_warning = B00000000; //Lightmode Selection (Fog Light and/or High Beam) if (light_highbeam == true) temp_light_highbeam = B01000000; else temp_light_highbeam = B00000000; if (light_fog == true) temp_light_fog = B00100000; else temp_light_fog = B00000000; lightmode = temp_light_highbeam + temp_light_fog; //Engine Options (Water Temperature, Diesel Preheater) if (signal_dieselpreheat == true) temp_signal_dieselpreheat = B00000010; else temp_signal_dieselpreheat = B00000000; if (signal_watertemp == true) temp_signal_watertemp = B00010000; else temp_signal_watertemp = B00000000; engine_control = temp_signal_dieselpreheat + temp_signal_watertemp; //Drivemode Selection (ABS, Offroad, Low Tire Pressure, handbrake) if (signal_abs == true) temp_signal_abs = B0001; else temp_signal_abs = B0000; if (signal_offroad == true) temp_signal_offroad = B0010; else temp_signal_offroad = B0000; if (signal_handbrake == true) temp_signal_handbrake = B0100; else temp_signal_handbrake = B0000; if (signal_lowtirepressure == true) temp_signal_lowtirepressure = B1000; else temp_signal_lowtirepressure = B0000; drive_mode = temp_signal_abs + temp_signal_offroad + temp_signal_handbrake + temp_signal_lowtirepressure; //Send CAN data every 200ms pack_counter++; if (pack_counter == 20) { //Turning Lights 2 CanSend(0x470, temp_battery_warning + temp_turning_lights, temp_trunklid_open + door_open, backlight, 0x00, temp_check_lamp + temp_clutch_control, temp_keybattery_warning, 0x00, lightmode); //Diesel engine CanSend(0x480, 0x00, engine_control, 0x00, 0x00, 0x00, temp_dpf_warning, 0x00, 0x00); ///Engine //CanSend(0x388, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00); //Cruise Control //CanSend(0x289, 0x00, B00000101, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00); pack_counter = 0; } //Motorspeed CanSend(0x320, 0x00, (speedL * 100), (speedH * 100), 0x00, 0x00, 0x00, 0x00, 0x00); //RPM CanSend(0x280, 0x49, 0x0E, rpmL, rpmH, 0x0E, 0x00, 0x1B, 0x0E); //Speed CanSend(0x5A0, 0xFF, speedL, speedH, drive_mode, 0x00, lo8(distance_counter), hi8(distance_counter), 0xad); //ABS CanSend(0x1A0, 0x18, speedL, speedH, 0x00, 0xfe, 0xfe, 0x00, 0xff); //Airbag CanSend(0x050, 0x00, 0x80, temp_seat_belt, 0x00, 0x00, 0x00, 0x00, 0x00); //Wait a time delay(20); } Hi, this is probably a missing oil pressure switch. If the RPM of the cluster is above 2000 the oil pressure switch has to be permanantly "pressed", otherwise the cluster starts beeping as it would become a motor damage in real life. In version 3.0 of my code there is an option called "oil_pressure_simulation", which should be set to true. You also have to make sure that arduino pin 8 is connected to pin 27 on the cluster. Hope that helps. Hi, I do have a Porsche 911 electrified, it is from 1998 so a little before CAN-BUS was introduced. Now I try to get some Engine noise added. As I have a Android based Car radio and a nice app found (voom voom) I would be able to emulate Engine sound. It works best if the Car Radio would connect to CAN-BUS to detect the RPM. Here I use the electronic available RPM signal of my engine controller and intend via CAN-BUS schield to make this as CAN Bus signal available for the radio. and for that you written code is quite helpful. there is one thing I do not get. Why do you multiply the rpm input you have by 4? Many Thanks for your project, and Many Thanks for your reply. hi , i want to control my polo 6 lights with arduino (high beam , low beam , blikers doors lock ....) but i can't find thier canbus adresse i wish you can help me please answer yes or no thanks anyway Can you show dumps of messages with ID 0x320 coming from panel? I'm trying to run with VW dashboard, but can't adjust speedometer. Messages with ID 0x1A0 and 0x5A0 affects speedometer, but not stable, in messages 0x320 I see error bit in speed calculation. I got this error message in compiling tne sketch : Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno" C:\Users\Tai\Documents\VWCode3.0_static\VWCode3.0_static.ino:23:33: fatal error: LCD.h: No such file or directory #include <LCD.h> ^ compilation terminated. exit status 1 Error compiling for board Arduino/Genuino Uno. This report would have more information with "Show verbose output during compilation" option enabled in File -> Preferences. Please help. add the library in the arduino IDE. You may need to do this with other libraries as well. Just youtube how to add a library. It is pretty standard Hi Leon! I have a question. How is possible to use int high_beam = 13; int fog_beam = 12; int park_brake = 11; ports for LED-s, if this pins are used by the SPI bus for communication with CAN-BUS? the LEDs are used before initializing the CAN BUS, so that I see when I reupload the sketch when the process is completed. It's just a debugging help and could be removed without a problem. What's the newest (best?) source for wiring? On first glance the fritzing diagram is not identical to Is0-Mick's diagram ... and both do contain things which didn't work on the dashboard I'm using. Maybe (the source for) the PCB might be a good reference - but where to get that? Hi! I just uploaded the source files of the circuit board. downloaded the updated diagram, found out it's made with autodesk eagle which in order to use i need an account, any chance for an exported file like .pdf or something that doesn't require to create accounts? Oh I see. Apparently it was Freeware a year ago. Could you please try it with the free version by Cadsoft? the Cadsoft link no longer works, it redirects to the same autodesk eagle which you have to make an account. OK, I think my PC had the original download page in cache. I‘ll make an PDF of the schematic and the board. Sorry for this misunderstanding. Hello again, When will the installation setup tool be available? Thanks Hi, Does it work with the petrol version dash? Thanks Should also work with the petrol version, yes. Hey Leon, I have seen a wiring diagram for the engine temperature and the fuel gauge on a photo. Can we see this circuit diagram in more details?? Thanks :) Yes of course :) Did you mean the outside temperature insted of the engine temp.? Hello, I'm trying to bring this project to life on my own, however - it seems like the cluster isn't communicating with Arduino. Have you removed a 62k resistor from can bus shield? Regs, Tom no, i didn't remove any parts from the can bus shield. however it could be that newer versions of the can bus shield are little bit different. especially the CS pin could have changed. I think mine has D9 as CS pin and newer have D10. but I'm not sure at the moment. Hi Leon! Thank you for the reply. Indeed - mine shield has CS pin on D10, but that wasn't the case. It turned out that on my shield CAN high an low pins are swapped (pins itself are fine, but the pins' description on the shield are contrariwise), so I've got it working :) Unfortunately - I couldn't get the Passat's B6 Instrument to work (speed gauge was jumping for few seconds and after that - it's been turning off), so I've took a instrument cluster out from... Fiat Panda and it's working perfect ;) Thank you very much for this project :) Best regs Tom i've got the tacho, the arduino and the canbus shield, got the code on the arduino but when i go into ets 2 nothing happens. the rpm needle stays at 800 rpm and that's it. could it be from the plugin? maybe they changed something in the telemetry. Silas's plugin is 3 years old... Oh this would be not godd (*panic). I will double check this and reply when I know more about it. Thanks for the info. I've purchased the exact same tacho from a 6R with the same pinout and all. But when I connect it it says no key and beeps then no function with any of the can bus calls. Do you have any suggestions to bypass this or what might be the issue? How do you connect the immobiliser pins or is it not necessary to touch? The tacho should work even when it says "no key". Mine tells me the same. Did you upload my newer script or did you try to send one single command? hi! I have the same issue at the moment with the “no key found” message. It seems that if I send any CAN message of the steering wheel buttons to go to the next MFD display, nothing bypasses the “no key found” message. Do you have any suggestion for this? Thanks Hie i am a student trying to build a two way communication (using can bus protocol) between two arduino's which have some sensors and actuators on them, can you please help me with the code required for sending and receiving the sensor values on CAN BUS protocol. (atleast where to refer) Hi, sorry for my late replay. But I hope it's not too late ;-). There are very useful examples for the CAN BUS protocol in the Arduino library of the Seeedstudio CAN BUS Shield. Just open Arduino IDE, import the library and click on File>Examples>CAN. There should be everything you need. wiring diagram has some missing components thanks for the info. yes the diagram is out of date. I'll make a new one as soon as i can. Perhaps I am missing something, but I have the Silas Parker plugin installed and telemetry is working. Compiled on the Arduino and running RMP goes to 800, so I know the CanBus Shield is talking to the cluster. Yet when playing ETS2 it is not talking to the cluster. What am I doing wrong? Hi, did you check the config file inside the plugin folder of ETS2? (i.e. C:\Program Files\Euro Truck Simualtor 2\bin\win_x86\plugins\dash_plugin.txt) You have to configure the COM Port of your Arduino inside this file. Best regards, Leon Hi Leon, I lost my board schematic you send me along with your Board. Could you please send me a copy? Best Regards, Jeroen Hi Leon, Could you show us the code you used to get the gas gauge working? Hi Leon, I'm trying to replicate your work but using a Skoda Octavia 2002 instrument cluster and a LM3S8962 dev board from Texas Instruments (which has a CAN peripheral included). I could immediately turn on / off a few lights and the RPM indicator ( ) but now I'm completely stuck with the Speed indicator and/or the other 2 smaller ones (oil temperature and petrol tank). I've obviously tried you codes for the speed but they don't seem to work... any other idea ? Dan hey leon is there a way to PM you? yes of course, just click on my name and write me an PM :) Hi Leon, Thank you for sharing this projekt! I have strange issue with my speedometer: after 20-30 sec from start i have very loud sound. What's happening?
https://hackaday.io/project/6288-can-bus-gaming-simulator
CC-MAIN-2019-47
refinedweb
3,032
60.75
Firebase is a cloud based platform for mobile and Web application development. In this article, which is aimed at Android enthusiasts, we explain how to use Firebase’s cloud services to store and retrieve real-time data. In today’s digital economy, most of our interactions, such as streaming stock exchange news, weather reports or news updates, occur in near real-time. The need for real-time data is shaping the way technology and markets are evolving currently. While the mobility trend and Android usage have grown over the past decade, combining mobility with real-time data will open up a plethora of opportunities to explore. Firebase is one cloud based platform that has great support for dealing with real-time data when it comes to Android. In this article, I will explain how to integrate Firebase with your app in Android Studio, with an illustration. For start-ups, Firebase is a quick and easy-to-use cloud based platform for making apps without worrying about servers, cloud storage and high availability among those servers. About Firebase Firebase is a unified mobile and Web app development platform from Google. It serves as a back-end as a service that provides real-time data syncing with all the clients subscribed to it, at a given instant. It also gives tools to rapidly develop high-quality apps with quick turnaround times. It is easy to implement Android apps using Firebase without the need for any server side expertise or any knowledge of the database. Firebase provides a real-time database for storing and syncing your app’s data. The data is stored in JSON format and synchronised to every connected client. Besides, it automatically backs up user data every day without any performance or bandwidth impact on the app. Getting started with Firebase Before integrating your app with Firebase, the pre-requisites are: 1. Android Studio version 1.5 or higher, and the device should be running Android 2.3 (Gingerbread) or above. Android Studio being the official SDK, it can be downloaded from the Android developer’s website. 2. A Firebase account is needed to be able to use its services. You can create a free account by visiting and signing up using your Google credentials. 3. SDK tools: Android studio needs to have Google Play services (version 9.2.0 or newer) installed. If not, you can install it using the SDK manager of Android Studio. Integrating the Android app with Firebase Firebase provides Java APIs for the Android platform to use its cloud services. To use these APIs, one needs to include Firebase libraries in the app’s build scripts to point to the class path and compile-time dependencies. The three steps described below explain how to set up the necessary environment in Android Studio. 1. Since we are using an external library here, the build.gradle at project level (which should be in the root directory of your project) needs to be told about the classpath for Google services by mentioning it as a dependency in the buildscript as shown below: classpath ‘com.google.gms:google-services:3.0.0’ The buildscript block of build.gradle at the project level should now look like what’s shown below, with the above addition: buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:1.5.0' classpath 'com.google.gms:google-services:3.0.0' } } 2. The module’s buildscript (build.gradle in the app folder) needs to add the Firebase library as a dependency: compile ‘com.google.firebase:firebase-database:9.2.1’ This library is for the real-time database’s features. The dependencies block of the module’s build.gradle will now look like what’s shown below, with this addition: dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.2.1' compile 'com.android.support:design:23.2.1' compile 'com.google.firebase:firebase-database:9.2.1' } 3. Finally, make sure that AndroidManifest.xml has permissions set for Internet access, as the app needs to contact the Firebase server for pushing and pulling real-time data. All these steps are done on the SDK side. Now, you may have to register the app with a Firebase account. This can be done with the following steps: 1. Log in to your account from using your Google credentials. The site has support for both Firebase’s legacy and its latest consoles. This whole article is based on the latest styled consoles. The consoles here are used to access your account to check the real-time database to which the app will be writing. 2. You might see the post login screen as shown in Figure 1. Click on ‘Create New Project’ to start with the Firebase project. 3. A new project gets created under your account, and you can view and use different Firebase services using the project’s dashboard as shown in Figure 2. These different services are seen on the left side column of the dashboard as shown in this figure. This article deals with the database service for dealing with real-time data. 4. Now the mechanism in which the app communicates with your Firebase account during its run time needs to be set up. For this, we need to register the Android app with the created account. This can be done by clicking on ‘Add Firebase to your Android app’ as shown in Figure 2, that will pop up a window like the one seen in Figure 3, prompting you to enter the package name of your Android project. Once added, click on ‘Add App’. 5. The website then generates a config file named google-services.json using the package name provided in Step 4. This file needs to be placed in your Android Studio app’s root directory. All these instructions are displayed on the Firebase site (Figure 4). 6. Google-services.json is needed during the compile time of the Android app. It indicates which Firebase URL/account the app needs to connect with to store and retrieve data. In this case, it happens to be the account you have just created using Google credentials. With this, the environment needed for using Firebase has been set up. We are now ready to use Firebase APIs to push and pull data from the mobile device. A simple application for pushing data Let me now illustrate a sample Android application that writes weather updates to Firebase’s cloud database which, in turn, notifies other clients registered to this account. Let us take a couple of cities, say Bengaluru and Delhi, and their corresponding temperature in Celsius, humidity in percentage and atmospheric pressure in millibars. Then let’s try to update the Firebase database from the app. Firebase APIs will try to write the Java object’s values to the cloud’s database. So, we first need to create a class, say Weather as shown below, then create objects of this class representing different cities and populate the objects with temperature, humidity and atmospheric pressure values. Here, the classes for serialisation expect to contain a default blank constructor. public class Weather { private String city; private int temperature; private int humidity; private int pressure; public Weather() { } public void setCity(String city) { this.city = city; } public void setTemperature (int temperature) { this.temperature = temperature; } public void setHumidity(int humidity) { this.humidity = humidity; } public void setPressure (int pressure) { this.pressure = pressure; } public String getCity() { return city; } public int getTemperature() { return temperature; } public int getHumidity() { return humidity; } public int getPressure() { return pressure; } } With this class, one can create objects representing Bengaluru and Delhi, and use setter methods to set temperature, humidity and pressure. Once the values are set, they can be written to the database like in the following code snippet: DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference(); Weather bangalore = new Weather(); bangalore.setCity(“Bangalore”); bangalore.setTemperature(24); bangalore.setHumidity(83); bangalore.setPressure(1013); rootRef.child(“Bangalore”).setValue(bangalore); Weather delhi = new Weather(); delhi.setCity(“Delhi”); delhi.setTemperature(27); delhi.setHumidity(94); delhi.setPressure(1003); rootRef.child(“Delhi”).setValue(delhi); FirebaseDatabase.getInstance().getReference() returns a reference to the real-time database you got on creating your Firebase account. The app gets compiled with details of the database URL from google-services.json that you had downloaded and added to your project. When the app runs the above code fragment, it writes the object’s values to the Firebase db using setValue() methods that get immediately reflected in your account, as shown in Figure 5. In addition, the database rules which dictate who can read and write in real-time to the DB can be set using the Rules menu, as shown in Figure 5. Permissions are set as public for this illustration. You might want to create the GUI and other means of interaction with the Android app to feed in these weather values, which I’m not covering in this article as it would digress from the intended topic. I am hosting the code of a sample app at for reference. Getting notified on real-time updates Now that data is pushed to the cloud, one can also register for real-time data updates by adding callbacks or event listeners in the app’s code. The clients need to have their google-services.json compiled with this account’s URL to get these notifications. Event listeners get notified whenever any of the JSON object’s values get updated. A sample code snippet on how to add this callback for value change notifications is shown below: rootRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { for (DataSnapshot postSnapshot : snapshot.getChildren()) { Weather climate = postSnapshot.getValue(Weather.class); /* You could extract the values of object using the getter methods * and display it in your GUI. * climate.getCity() * climate.getTemperature() * climate.getHumidity() * climate.getPressure() **/ } } @Override public void onCancelled(DatabaseError firebaseError) { /* * You may print the error message. **/ } }); The onDataChange() method gives an iterable snapshot of the database which could be used to read the updates. This way, a simple publisher-subscriber model could be implemented quickly using Firebase. There are also many other services like authentication, crash reporting, cloud messaging, analytics, etc, that are provided. You could learn and explore these different services from the Firebase site. Thank You); I just read your article in “Open Source” Is there any way to communicate Real time db to MySQL database ? Thanks Nithin for going through!! So, firebase itself is a NOSQL based real time dB. Any reasons behind attempting to connect real time db with mysql ? May I know the exact requirement you are looking for? — Shravan. thanks for this information, i was just thinking that, is there any way to make connect with server and firebase .if it is possible, then make it as cache… that’s why i asked. thanks for your great consideration. So, If you’d want to maintain a cache in your mobile device (probably to improve app’s performance), then yes should be possible. You could use Android sqlite and your app could first look into this local dB(cache, if this is what you are referring to) and if it doesn’t find whatever its looking for can then contact the remote firebase dB. But this I feel this would defeat the complete purpose of firebase dB. The idea here is to provide real-time updates to your app. And in real-time scenarios (like say stock market updates), you need to make sure mysql cache on your mobile always needs to be in sync with firebase. Hope this helps, –Shravan Thank You..! Sir how to show this data in custom listview Are you referring to the dat in the firebase site?
https://opensourceforu.com/2016/12/retrieve-real-time-data-android-using-firebase/
CC-MAIN-2018-34
refinedweb
1,956
56.25
AnalyticDB for PostgreSQL is fully compatible with the message-based protocol of PostgreSQL. Therefore, you can use tools that support the protocol, such as psql, libpq, Java Database Connectivity (JDBC), Open Database Connectivity (ODBC), and psycopg2. You can also use graphical user interface (GUI) tools such as pgAdmin, DBeaver, and Navicat. Note that AnalyticDB for PostgreSQL V4.3 supports only pgAdmin III 1.6.3 and earlier, while AnalyticDB for PostgreSQL V6.0 supports the latest version of pgAdmin 4. You can use Data Management (DMS) to manage and develop AnalyticDB for PostgreSQL instances. DMS console DMS manages relational databases (such as MySQL, SQL Server, PostgreSQL, PPAS, and Petadata), OLTP databases (such as DRDS), OLAP databases (such as AnalyticDB and DLA), and NoSQL databases (such as MongoDB and Redis). DMS offers an integrated solution to manage data, schemas, and servers. You can also use DMS to authorize users, audit security, view BI charts and data trends, track data, and optimize performance. This section describes how to use the DMS console to connect to an AnalyticDB for PostgreSQL instance. - Log on to the AnalyticDB for PostgreSQL console. - Create an instance. For more information, see Create an instance. If you have created one, find the target instance and click its ID. - Create an account. For more information, see Configure an account.Note This account is used to log on to the DMS console. A single account can be created for each instance. - In the upper-right corner, click Login Database. - On the RDS Database Logon page that appears, enter the username and password, and click Log On. psql psql is a command line tool used together with Greenplum, and provides a variety of commands. Its binary files are located in the bin directory of Greenplum. To use psql to connect to an AnalyticDB for PostgreSQL instance, follow these steps: Connect to the instance by using one of the following methods: Connection string psql "host=yourgpdbaddress.gpdb.rds.aliyuncs.com port=3432 dbname=postgres user=gpdbaccount password=gpdbpassword" Specified parameters psql -h yourgpdbaddress.gpdb.rds.aliyuncs.com -p 3432 -d postgres -U gpdbaccount Parameter description: - -h: the host address. - -p: the port used to connect to the database. - -d: the name of the database. The default value is postgres. - -U: the account used to connect to the database. - You can run the psql - helpcommand to view more options. You can also run the \?command to view the commands supported in psql. - Enter the password to go to the psql shell interface. The psql shell is as follows: postgres=> References For more information, visit gp6 psql in the Greenplum database documentation. AnalyticDB for PostgreSQL also supports psql commands for PostgreSQL. Pay attention to the differences between psql in Greenplum and that in PostgreSQL. For more information, visit PostgreSQL 8.3.23 Documentation - psql in the PostgreSQL documentation. Download method The download method varies depending on your operating system version: For Red Hat Enterprise Linux 6 or CentOS 6, click HybridDB_client_package_el6. For Red Hat Enterprise Linux 7 or CentOS 7, click HybridDB_client_package_el7. For Windows or other operating systems, download AnalyticDB for PostgreSQL Client from the Pivotal website. pgAdmin pgAdmin is a graphical client tool for PostgreSQL and can be used to connect to an AnalyticDB for PostgreSQL instance. For more information, visit the official pgAdmin website. AnalyticDB for PostgreSQL V4.3 is based on the PostgreSQL 8.3 kernel. Therefore, you must use pgAdmin III 1.6.3 or earlier to connect to an AnalyticDB for PostgreSQL V4.3 instance. AnalyticDB for PostgreSQL V4.3 does not support pgAdmin 4. AnalyticDB for PostgreSQL V6.0 is based on the PostgreSQL 9.4 kernel and supports the latest version of pgAdmin 4. You can download pgAdmin III 1.6.3 or pgAdmin 4 from the PostgreSQL official website. pgAdmin is compatible with various operating systems such as Windows, macOS, and Linux. For other graphical client tools, see Graphical client tools. Procedure Download and install the supported version of pgAdmin. Choose. - In the New Server Registration dialog box that appears, set parameters as prompted. Click OK to connect to the AnalyticDB for PostgreSQL instance. JDBC You must use the official JDBC of PostgreSQL. Use one of the following methods to download JDBC: Click PostgreSQL JDBC Driver to download the official JDBC of PostgreSQL and add it to an environment variable. Obtain JDBC from the tool package provided at the official Greenplum website. For more information, visit:34, visit The PostgreSQL JDBC Interface. Python You can use psycopg2 to connect to Greenplum or PostgreSQL. The procedure is as follows: Install psycopg2. There are three installation methods in CentOS: -. After the variable is set, it can be referenced. import psycopg2 sql = 'select * from gp_segment_configuration;' conn = psycopg2.connect(database='gpdb', user='mygpdb', password='mygpdb', host='mygpdbpub.gpdb.rds.aliyuncs.com', port=3432) conn.autocommit = True cursor = conn.cursor() cursor.execute(sql) rows = cursor.fetchall() for row in rows: print row conn.commit() conn.close() The system displays information similar to the following application programmer's interface to PostgreSQL. You can use libpq libraries to access and manage PostgreSQL databases in a C program. If Greenplum or PostgreSQL is deployed, you can find both the static and dynamic libraries of libpq in the lib directory. For example programs, click 30.19. Example Programs. For more information about libpq, visit PostgreSQL 9.4.10 Documentation - Chapter 31. libpq - C Library. ODBC PostgreSQL ODBC is an open source tool licensed based on the GNU Lesser General Public License (LGPL) protocol. You can download it from the official PostgreSQL website. Procedure Install the driver. yum install -y unixODBC.x86_64 yum install -y postgresql-odbc.x86_64 View the driver configuration. cat /etc/odbcinst.ini # Example driver definitions # Driver from the postgresql-odbc package # # Driver from the mysql-connector-odbc package # Setup from the unixODBC package [MySQL] Description = ODBC for MySQL Driver = /usr/lib/libmyodbc5.so Setup = /usr/lib/libodbcmyS.so Driver64 = /usr/lib64/libmyodbc5.so Setup64 = /usr/lib64/libodbcmyS.so FileUsage = 1 Configure the DSN. Replace ****in the following code with actual information. [mygpdb] Description = Test to gp Driver = PostgreSQL Database = **** Servername = ****.gpdb.rds.aliyuncs.com UserName = **** Password = **** Port = **** ReadOnly = 0 Test connectivity. echo "select count(*) from pg_class" | isql mygpdb +---------------------------------------+ | Connected! | | | | sql-statement | | help [tablename] | | quit | | | +---------------------------------------+ SQL> select count(*) from pg_class +---------------------+ | count | +---------------------+ | 388 | +---------------------+ SQLRowCount returns 1 1 rows fetched After ODBC is connected to the instance, connect your application to ODBC. For more information, visit psqlODBC - PostgreSQL ODBC driver and psqlODBC HOWTO - C#. More information Graphical client tools Greenplum client tools The official Greenplum website provides a tool package, which includes JDBC, ODBC, and libpq. The package is easy to install and use. For more information, visit Pivotal Greenplum documentation.
https://www.alibabacloud.com/help/doc-detail/35428.htm
CC-MAIN-2020-50
refinedweb
1,115
52.66
Next.js is an excellent tool for building web applications with React. I kinda see it as Ruby on Rails for React applications. It packs a lot of goodies. One of those goodies is that it handles routing for you. However, over the years, I have used various routing libraries — a couple versions of react-router, found, Navi, and now Next. Often, I had to switch libraries or update react-router, which at every major version is like a new library. Because of this, I got into the habit of isolating routing from the rest of my application. In this article, I’m going to explain two of my techniques for isolating routing in your application. I use Next as an example, but they can be applied to pretty much all routing libraries: - Use a custom Linkcomponent - Have all paths in a single file Technique 1: Custom Link component My first technique is wrapping the Link component. Every routing library has a similar component; it is used instead of the <a> tag. When clicked, it changes the URL without a full page redirect, and then the routing handles loading and displaying the new page. In almost all of my projects, I use my own component named Link. This component wraps the underlying routing library Link component. Next has a similar Link component. Its interface is a bit different than that of the others, but it functions in the same way: <Link href="/about"> <a>About</a> </Link> I understand why they designed it this way. It is quite clever; it uses React.cloneElement internally. You can check its code here. However, it is a bit cumbersome for my taste. It adds a lot of visual destiny to your pages. This alone can be a good enough reason to wrap a component. In this case, however, I have even bigger reasons. Say I want to migrate out of Next to something like Gatsby. I’d have to change a lot of code structure; it won’t just replace imports from next/link to gatsby/link. Here is how a wrapped version of Link is going to work: import * as React from 'react'; import Link from 'next/link'; // allow this component to accept all properties of "a" tag interface IProps extends React.AnchorHTMLAttributes<HTMLAnchorElement> { to: string; // we can add more properties we need from next/link in the future } // Forward Refs, is useful export default React.forwardRef(({ to, ...props }: IProps, ref: any) => { return ( <Link href={to}> <a {...props} ref={ref} /> </Link> ); }); Note: I’m using TypeScript for all examples. Code will work without types as well. This is how it will be used: <Link to="/about">About</Link> The new Link component starts quite simple, but over time, you can add more functionality. A good candidate for additions is overwriting the defaults for the library. In Next 9, automatic prefetching was turned on by default. This prefetches link contents when they are in the page’s viewport. Next uses a new browser API called IntersectionObserver to detect this. This is a handy feature, but it can be overkill if you have a lot of links and pages that are dynamic. It is OK for the static side. Usually, I want to have this for specific pages, not for all of them. Or you might want to prefetch only when the mouse is hovering the link. Our Link component makes it simple to turn this feature off: interface IProps extends React.AnchorHTMLAttributes<HTMLAnchorElement> { to: string; prefetch?: boolean; } export default React.forwardRef(({ to, prefetch, ...props }: IProps, ref: any) => { return ( <Link href={to} prefetch={prefetch || false}> <a {...props} ref={ref} /> </Link> ); }); Now imagine if we didn’t have our Link component and we had to turn off prefetching for every link. Technique 2: Have all paths in a single file One thing I see people doing in React applications is hardcoding links. Something like the following: <Link to="/about">About</Link> <Link to="/contact">Contact</Link> This is very brittle. It is not type-safe, and it makes renaming URLs or changing URL structure hard. The way I solve this is to have a file named path.ts at the root of the project. It looks something like the following: export default { about: '/about', contact: '/contact', } This file contains all the routes in my application. This is how it is used: import paths from '~/paths'; <Link to={paths.about}>About</Link> <Link to={paths.contact}>Contact</Link> In this way, I can change the routes, and I’m protected from typos. Handling dynamic routes in Next Next 9 was an epic release. Its most significant feature was support for dynamic route segments. Before that, Next didn’t support dynamic routes like /products/1 out of the box. You had to use an external package like next-router or use URLs like /products?id=1. The way dynamic routes are handled, we need to pass two props to Link: href: Which file is this in the pagesfolder as: How this page is shown in address bar This is necessary because the Next client-side router is quite light and doesn’t know about the structure of your whole route. This scales quite well since you don’t hold complicated routing structures in browser memory, as in other routing systems. Here is how it looks in practice: <Link href="/products/[id]" as="/product/1"> <a>Product 1</a> </Link> This makes dealing with links even more cumbersome. Fortunately, we have our custom Link and paths. We can combine them and have the following: <Link to={paths.product(product)}Product 1</Link> How is this implemented? First, we add a function in paths that returns both props for the page: export default { about: '/about', contact: '/contact', // paths can be functions // this also makes it easier to change from "id" to "slug" in the future product(product: { id: string }) { return { href: '/products/[id], as: `/products/${id}`, }; } } Second, we have to handle those props: interface IProps extends React.AnchorHTMLAttributes<HTMLAnchorElement> { // allow both static and dynamic routes to: string | { href: string, as: string }; prefetch?: boolean; } export default React.forwardRef(({ to, prefetch, ...props }: IProps, ref: any) => { // when we just have a normal url we jsut use it if (typeof to === 'string') { return ( <Link href={to} prefetch={prefetch || false}> <a {...props} ref={ref} /> </Link> ); } // otherwise pass both "href" / "as" return ( <Link href={to.href} as={to.as} prefetch={prefetch || false}> <a {...props} ref={ref} /> </Link> ); }); Migration story Before version 9, Next didn’t support dynamic routing. This was a big issue, and I had been using next-router for dynamic routing. It has a central file where you create the mapping from URL to file in the pages folder. Its Link component works quite differently. It was a lifesaver before Next 9. But when dynamic routes were added to Next, it was time to stop using the library; it is even in maintenance mode now. Imagine having a large application with hundreds of links. How much time do you think a migration like this could have taken? For me, it took less than an hour. I just replaced the code in the Link component and changed the dynamic paths to return an object and not a route/params as next-router wanted. Conclusion Those techniques have helped me a lot over the years working with React applications. They are relatively simple but help you to decouple your application from underlying libraries, make your system easy to change, and have type safety. I hope you find them useful as well. For any questions or comments, you can ping me on Twitter. “Dealing with links in Next.js” Hello, im getting 404 when refreshing page to which i’ve navigated using Link with as, i.e. simple any ideas? Using next 9.4.4 It looks like you have a typo in your product path function: “`js product(product: { id: string }) { return { href: ‘/products/[id], as: `/products/${id}`, }; } “` You are missing the closing quote for href. I think it should be: “` product(product: { id: string }) { return { href: ‘/products/[id]’, as: `/products/${id}`, }; } “` But I’m a PHP guy, so please correct me if I’m wrong.
https://blog.logrocket.com/dealing-with-links-in-next-js/?utm_source=jsk&utm_medium=referral&utm_campaign=jsk_q42019
CC-MAIN-2020-40
refinedweb
1,361
73.98
Red Hat Training A Red Hat training course is available for Red Hat Enterprise Linux 5.8 Technical Notes Detailed notes on the changes implemented in Red Hat Enterprise Linux 5.8 Edition 8 Abstract Preface Chapter 1. Technology Previews - Chapter 2. Known Issues 2.1. anaconda - After a reboot of a freshly-installed system, the IP over Infiniband (IPoIB) interface fails to come up automatically as Anaconda fails to manually enable the openibd init script. To work around this issue, enable the openibd init script in the post section of the Kickstart file prior to the installation of the system: %post chkconfig --level 12345 openibd on - When installing Red Hat Enterprise Linux 5.8 on a machine that had previously used a GPT partitioning table, Anaconda does not provide the option to remove the previous disk layout and is unable to remove the previously used GPT partitioning table. To work around this issue, switch to the tty2 terminal (using CTRL+ALT+F2), execute the following command, and restart the installation process: dd if=/dev/zero of=/dev/USED_DISK count=512 - Starting with Red Hat Enterprise Linux 5.2, to boot with ibft, the iSCSI boot firmware table support, use the ip=ibftoption as the network install option: ip=<ip> IP to use for a network installation, use 'dhcp' for DHCP.By default, the installer waits 5 seconds for a network device with a link. If an iBFT network device is not detected in this time, you may need to specify the linksleep=SECONDSparameter in addition to the ip=ibftparameter by replacing SECONDSwith an integer specifying the number of seconds the installer should wait, for example: linksleep=10 - Setting the dhcptimeout=0parameter does not mean that DHCP will disable timeouts. If the user requires the clients to wait indefinitely, the dhcptimeoutparameter needs to be set to a large number. - When starting an installation on IBM S/390 systems using SSH, re-sizing the terminal window running the SSH client may cause the installer to unexpectedly exit. Once the installer has started in the SSH session, do not resize the terminal window. If you want to use a different size terminal window during installation, re-size the window before connecting to the target system via SSH to begin installation. - Installing on June with a RAID backplane on Red Hat Enterprise Linux 5.7 and later does not work properly. Consider the following example: a test system which had two disks with two redundant paths to each disk was set up: mpath0: sdb, sdd mpath1: sda, sdcIn the above setup, Anaconda created the PReP partition on mpath0 (sdb/sdd), but set the bootlist to boot from sda. To work around this issue, follow these steps: - Add mpathto the append line in the /etc/yaboot.conffile. - Use the --ondisk=mapper/mpath0in all partdirectives of the kickstart file. - Add the following script to the %postsection of the kickstart file. %post # Determine the boot device device=; # Set the bootlist in NVRAM if [ "z$device" != "z" ]; then bootlist -m normal $device; # Print the resulting boot list in the log bootlist -m normal -o; bootlist -m normal -r; else echo "Could not determine boot device!"; exit 1; fiThe above script simply ensures that the bootlist is set to boot from the disk with the PReP partition. - Mounting an NFS volume in the rescue environment requires portmap to be running. To start portmap, run: /usr/sbin/portmapFailure to start portmap will return the following NFS mount errors: sh-3.2# mount 192.168.11.5:/share /mnt/nfs mount: Mounting 192.168.11.5:/share on /mnt/nfs failed: Input/output error - The order of device names assigned to USB attached storage devices is not guaranteed. Certain USB attached storage devices may take longer to initialize than others, which can result in the device receiving a different name than you expect (for example, sdcinstead of sda).During installation, be sure to verify the storage device size, name, and type when configuring partitions and file systems. - Performing a System z installation, when the install.imgis located on direct access storage device (DASD) disk, causes the installer to crash, returning a backtrace. anaconda is attempting to re-write (commit) all disk labels when partitioning is complete, but is failing because the partition is busy. To work around this issue, a non-DASD source should be used for install.img. (BZ#455929) - When installing to an ext3or ext4file system, anaconda disables periodic file system checking. Unlike ext2, these file systems are journaled, removing the need for a periodic file system check. In the rare cases where there is an error detected at runtime or an error while recovering the file system journal, the file system check will be run at boot time. (BZ#513480) - Red Hat Enterprise Linux 5 does not support having a separate /varon a network file system ( nfs, iSCSIdisk, nbd, etc.) This is because /varcontains the utilities required to bring up the network, for example /var/lib/dhcp. However, you may have /var/spool, /var/wwwor the like on a separate network disk, just not the complete /var file system. (BZ#485478) - When using rescue mode on an installation which uses iSCSI drives which were manually configured during installation, the automatic mounting of the root file system does not work. You must configure iSCSI and mount the file systems manually. This only applies to manually configured iSCSI drives; iSCSI drives which are automatically detected through iBFT are fully supported in rescue mode.To rescue a system which has /on a non-iBFT configured iSCSI drive, choose to skip the mounting of the root file system - Mount your /partition: $ mount /dev/path/to/root /mnt/sysimage $ mount -t bind /dev /mnt/sysimage/dev $ mount -t proc proc /mnt/sysimage/proc $ mount -t sysfs sysfs /mnt/sysimage/sys - Now you can chrootto the root file system file systems, especially the root file system, are directly visible to the host, a host OS reboot may inadvertently parse the partition table and mount the guest file systems. This can lead to highly undesirable outcomes. - The minimum memory requirement when installing all Red Hat Enterprise Linux packages (i.e. *or @everythingis listed in the %packagessection of the kickstartfile) on a fully virtualized Itanium guest is 768MB. After installation, the memory allocated to the guest can be lowered to the desired amount. - Upgrading a system using Anaconda is not possible if the system is installed on disks attached using zFCP or iSCSI (unless booted from the disk using a network adapterto the installer using the boot command line. - If you are using the Virtualized kernel when upgrading from Red Hat Enterprise Linux 5.0 to a later 5.x release, you must reboot after completing the upgrade. You should then boot the system using the updated Virtualized kernel. - When provisioning guests during installation, theoption will not be available. When this occurs, the system will require an additional entitlement, separate from the entitlement used by dom0. -button appears at the end of the guest installation, clicking it shuts down the guest, but does not reboot it. This is an expected behavior.Note that when you boot the guest after this it will then use its own bootloader. - Using the swap --growparameter in a kickstartfile without setting the --maxsizeparameter at the same time makes anaconda impose a restriction on the maximum size of the swap partition. It does not allow it to grow to fill the device. - disks containing different Linux distributions, the anaconda installer may overwrite the bootloaders of the other Linux installations although their hard disks have been unchecked. To work around this, choose manual partitioning during the installation process. - The minimum RAM required to install Red Hat Enterprise Linux 5.8 is 1GB; the recommended RAM is 2GB. If a machine has less than 1GB RAM, the installation process may hang.Furthermore, PowerPC-based machines that have only 1GB of RAM experience significant performance issues under certain RAM-intensive workloads. For a Red Hat Enterprise Linux 5.8 system to perform RAM-intensive processes optimally, 4GB of RAM is recommended. This ensures the system has the same number of physical pages as was available on PowerPC machines with 512MB of RAM running Red Hat Enterprise Linux 4.5 or earlier. - Installation on a machine with existing Linux or non-Linux file systems on DASD block devices may cause the installer to halt. If this happens, it is necessary to clear out all existing partitions on the DASD devices you want to use and restart the installer. 2.2. autofs - Starting with Red Hat Enterprise Linux 5.4, behavior of the umount -lautofs command has changed. For more information, refer to BZ#452122.Previously, the umount -lwould unmount all autofs-managed mounts and autofs internal mounts at start-up, and then mounted all autofs mounts again as a part of the start-up procedure. As a result, the execution of the external umount -lcommand was not needed.The previous autofs behavior can be used via the following commands: ~]# service autofs forcerestartor ~]# service autofs forcestart 2.3. cmirror -) 2.4. compiz - Running rpmbuildon the compizsource RPM will fail if any KDE or qtdevelopment packages (for example, qt-devel) are installed. This is caused by a bug in the compizconfiguration script. 2.5. cpio - The cpio utility uses a default block size of 512 bytes for I/O operations. This may not be supported by certain types of tape devices. If a tape device does not support this block size, cpio fails with the following error message: cpio: read error: Cannot allocate memory 2.6. device-mapper-multipath - respond. 2.7. dmraid - 2.8. dogtail 2.9. firstboot - The IBM System z does not provide a traditional Unix-style physical console. As such, Red Hat Enterprise Linux 5.8 for the IBM System z does not support the firstboot functionality during initial program load.To properly initialize setup for Red Hat Enterprise Linux 5.8 on the IBM System z, run the following commands after installation: /usr/bin/setup— provided by the setuptoolpackage. /usr/bin/rhn_register— provided by the rhn-setuppackage. 2.10. gfs2-utils GFS2file systems. GFS2as the root file system is unsupported. 2.11. gnome-volume-manager - 2.12. initscripts 2.13. iscsi-initiator-utils -) 2.14. kernel-xen - When booting paravirtualized guests that support gigabyte page tables (i.e. a Fedora 11 guest) on Red Hat Enterprise Linux 5.7 Xen, the domain may fail to start if more than 2047MB of memory is configured for the domain. To work around this issue, pass the " nogbpages" parameter on the guest kernel command-line. (BZ#502826) - Boot parameters are required to enable SR/IOV Virtual Function devices. SR/IOV Virtual Function devices can only be accessed if the parameter pci_pt_e820_access=on is added to the boot stanza in the /boot/grub/grub.conf file. For example: - Diskette drive media will not be accessible when using the virtualized kernel. To work around this, use a USB-attached diskette drive instead. -. (BZ#422531) - Upgrading a host ( dom0) system to Red Hat Enterprise Linux 5.7 may render existing Red Hat Enterprise Linux 5.4 SMP paravirtualized guests unbootable. This is more likely to occur when the host system has more than 4GB of RAM. - On some Itanium systems configured for console output to VGA, the dom0virtualized kernel may fail to boot. This is because the virtualized kernel failed to properly detect the default console device from the Extensible Firmware Interface (EFI) settings. - On some Itanium systems (such as the Hitachi Cold Fusion 3e), the serial port cannot be detected in dom0when VGA is enabled by the EFI Maintenance Manager. As such, you need to supply the following serial port information to the dom0kernel: These details must be specified in the - Speed in bits/second - Number of data bits - Parity io_baseaddress append=line of the dom0kernel in /boot/efi/elilo.conf. For example: append="com1=19200,8n1,0x3f8 -- quiet rhgb console=tty0 console=ttyS0,19200n8" -. 2.15. kernel - size of the PowerPC Management Services (SMS) with the command: ~]# 0> dev /packages/gui obe 2.16. kexec-tools -) - Some Itanium systems cannot properly produce console output from the kexec purgatorycode. This code contains instructions for backing up the first 640k of memory after a crash. 2.17. kvm - Erroneous boot-index of a guest with mixed virtio/IDE disks causes the guest to boot from the wrong disk after the OS installation and hang with the error message boot from HD. - When using PCI device assignment with a 32-bit Microsoft Windows 2008 guest on an AMD-based host system, the assigned device may fail to work properly if it relies on MSI or MSI-X based interrupts. The reason for this is that the 32-bit version of Microsoft Windows 2008 does not enable MSI based interrupts for the family of processor exposed to the guest. To work around this problem, the user may wish to move to a RHEL6 host, use a 64-bit version of the guest operating system, or employ a wrapper script to modify the processor family exposed to the guest as follows (Note that this is only for 32-bit Windows guests): - Create the following wrapper script: ~]$ cat /usr/libexec/qemu-kvm.family16 #!/bin/sh ARGS=$@ echo $ARGS | grep -q ' -cpu ' if [ $? -eq 0 ]; then for model in $(/usr/libexec/qemu-kvm -cpu ? \ | sed 's|^x86||g' | tr -d [:blank:]); do ARGS=$(echo $ARGS | \ sed "s|-cpu $model|-cpu $model,family=16|g") done else&2 exec /usr/libexec/qemu-kvm $ARGS - Make the script executable: ~]$ chmod 755 /usr/libexec/qemu-kvm.family16 - Set proper SELinux permissions: ~]$ restorecon /usr/libexec/qemu-kvm.family16 - Update the guest XML to use the new wrapper: ~]# virsh edit $GUESTand replace: <emulator>/usr/libexec/qemu-kvm</emulator>with: <emulator>/usr/libexec/qemu-kvm.family16</emulator> - that - The mute button in the audio control panel on a Windows virtual machine does not mute the sound. - (that is, Remote Installation Services (RIS) or Windows Deployment Services (WDS)). - and es1370 sound card emulations - bluetooth emulation - qemu CPU models other than qemu32/64 and pentium3 - qemu block device drivers other than raw, qcow2, and host_device 2.18. less - The "less" command has been updated. less no longer adds the "carriage return" character when wrapping long lines. Consequently, lines longer than the terminal width will be displayed incorrectly when browsing the file line per line. The command line option "--old-bot" forces less to behave as it did previously, with long text lines displayed correctly. (BZ#441691) 2.19. lftp - As a side effect of changing the underlying cryptographic library from OpenSSL to GnuTLS in the past, starting with lftp-3.7.11-4.el5_5.3, some previously offered TLS ciphers were dropped. In handshake, lftp does not offer these previously available ciphers: TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA TLS_DHE_DSS_WITH_AES_256_CBC_SHA TLS_DHE_DSS_WITH_DES_CBC_SHA TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA TLS_DHE_RSA_WITH_AES_256_CBC_SHA TLS_DHE_RSA_WITH_DES_CBC_SHA TLS_RSA_EXPORT_WITH_DES40_CBC_SHA TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 TLS_RSA_EXPORT_WITH_RC4_40_MD5 TLS_RSA_WITH_AES_256_CBC_SHA TLS_RSA_WITH_DES_CBC_SHAlftp still offers variety of other TLS ciphers: TLS_RSA_WITH_AES_128_CBC_SHA TLS_RSA_WITH_3DES_EDE_CBC_SHA TLS_RSA_WITH_RC4_128_SHA TLS_RSA_WITH_RC4_128_MD5 TLS_DHE_DSS_WITH_AES_128_CBC_SHA TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA TLS_DHE_DSS_WITH_RC4_128_SHA TLS_DHE_RSA_WITH_AES_128_CBC_SHA TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA 2.20. lvm2 - LVM no longer scans multipath member devices (underlying paths for active multipath devices) and prefers top level devices. This behavior can be switched off using the multipath_component_detectionoption in the /etc/lvm/lvm.conf. 2.21. mesa -" 2.22. mkinitrd - When installing Red Hat Enterprise Linux 5.8, the following errors may be returned in install.log: Installing kernel-2.6.18-158.el5.s390x cp: cannot stat `/sbin/dmraid.static': No such file or directoryThis message can be safely ignored. 2.23. mod_revocator - In order to run mod_revocator successfully, the following command must be executed in order to allow httpdto connect to a remote port which SELinux would otherwise deny: ~]# setsebool -P httpd_can_network_connect=1This is due to the fact that by default, Apache is not allowed to also be used as an HTTP client (that is, send HTTP messages to an external host). 2.24. openib 2.25. openmpi - A bug in previous versions of openmpiand lammay prevent you from upgrading these packages. This bug manifests in the following error (when attempting to upgrade openmpior lam: error: %preun(openmpi-[version]) scriptlet failed, exit status 2As such, you need to manually remove older versions of openmpiand lamin order to install their latest versions. To do so, use the following rpmcommand: rpm -qa | grep '^openmpi-\|^lam-' | xargs rpm -e --noscripts --allmatches 2.26. perl-libxml-enno 2.27. pm-utils - nVidia video devices on laptops can not be correctly re-initialized using VESA in Red Hat Enterprise Linux 5. Attempting to do so results in a black laptop screen after resume from suspend. 2.28. rpm - Users of a freshly-installed PowerPC Red Hat Enterprise Linux 5.8 system may encounter package-related operation failures with the following errors: rpmdb: PANIC: fatal region error detected; run recovery error: db4 error(-30977) from db->sync: DB_RUNRECOVERY: Fatal error, run database recovery 2.29. redhat-release-notes - The Revision History of the Red Hat Enterprise Linux 5.8 Release Notes contains an incorrect release date for the 1-0revision: Thu Feb 16 2011. The revision date should be Tue Feb 21 2012. The content of the Release Notes reflects changes made to Red Hat Enterprise Linux 5.8. 2.30. qspice - Occasionally, the video compression algorithm starts when the guest is accessing text instead of video. This caused the text to be blurred. The SPICE server now has an improved heuristic for distinguishing between videos and textual streams. 2.31. subscription-manager -. 2.32. systemtap - the systemtap.base/uprobes.exp systemtap.base/bz10078.exp systemtap.base/bz6850.exp systemtap.base/bz5274.exp uprobes.komodule. Some updated user-space probe tests provided by the systemtap-testsuite package use symbols available only in the latest uprobes.komodule (also provided by the latest SystemTap update). As such, running these user-space probe tests result in the error mentioned earlier. -. (BZ#239065) 2.33. xen - In some cases, Red Hat Enterprise Linux 6 guests running fully-virtualized under Red Hat Enterprise Linux 5 experience a time drift or fail to boot. In some cases, drifting may start after migration of the virtual machine to a host with different speed. This is due to limitations in the Red Hat Enterprise Linux 5 Xen Hypervisor. To work around this, add clocksource=acpi_pmor clocksource=jiffiesto the kernel command line for the guest. Alternatively, if running under Red Hat Enterprise Linux 5.7 or newer, locate the guest configuration file for the guest and add the hpet=0option in it. -) 2.34. virt-v2v - VMware Tools on Microsoft Windows is unable to disable itself when it detects that it is no longer running on a VMware platform. As a consequence, converting a Microsoft Windows guest from VMware ESX, which has VMware Tools installed, resulted in multiple error messages being displayed on startup. In addition, a Stop Error(also known as Blue Screen of Death, or BSOD) was displayed every time when shutting down the guest. To work around this issue, users are advised to uninstall VMware Tools from Microsoft Windows guests before conversion. (BZ#711972) 2.35. virtio-win -. 2.36. xorg-x11-drv-i810 - When switching from the X server to a virtual terminal (VT) on a Lenovo ThinkPad T510 laptop, the screen may. -). (BZ#468259) 2.37. xorg-x11-drv-nv 2.38. xorg-x11-drv-vesa -u" 2.39. yaboot - Chapter 3. New Packages Note Note Chapter 4. Package Updates 4.1. acl. 4.2. acpid Bug Fixes - BZ#729769 -#545760 -. 4.3. alsa-utils Enhancement 4.4. anaconda Bug Fixes - BZ#477748 - When performing the kickstart upgrade with a key for advanced platforms, additional repositories were not enabled, and only the base repository packages were upgraded. - BZ#506361 - Adding a VT repository to the kickstart file and using the "key --skip" command resulted in an error when trying to install the Virtualization-en-US package. - BZ#566668 - Reusing the LVM logical volumes from the previous installation process caused the bootloader program to use the old disk labels so that the system was unable to boot. - BZ#571513 - If the file system label ended with the "0" character, this character was stripped so that the existing file system label was different from what was explicitly specified by the user. - BZ#681219 - The "CMSCONFFILE" parameter could have contained wrong syntax. This could have resulted in certain Bash errors on IBM S/390. - BZ#689470 - Specifying the "CMSDASD" parameter with a hex number using uppercase letters resulted in the kickstart file not being found. - BZ#684220 - The installer environment lacked the symbolic links for stdin, stdout, and stderr. As a result, the console output to the files instead of the screen. - BZ#695299 - The installer used the maximum LV size limit based on the LVM 1 limits. Now, the maximum LV size limit is based on the LVM 2 limits. - BZ#702024 - Only stderr was logged to the output file during the kickstart installation. Now, stdout is also logged. - BZ#703081 - Using the parameter "--no-ssh" in kickstart failed to propagate the same parameter to /root/anaconda-ks.cfg. - BZ#703082 - The "--no-ssh" parameter was not documented in /usr/share/doc/anaconda-*/kickstart-docs.txt. - BZ#707143 - Downloading the Red Hat Enterprise Linux Release Notes resulted in errors, even though the Release Notes were downloaded successfully. - BZ#708121 - The /var/log/ directory required by the Subscription Manager logging was not created. - BZ#709880 - The list-harddrives script did not work as expected. - BZ#712443 - Errors emitted by the kickstart scripts were not properly reported to the user. - BZ#713120 - Even though the installation was run with IPv6 enabled, IPv6 was disabled in the installed environment. - BZ#714243 - The Solarflare network adapters were not available to the user during the installation. - BZ#718123 - The installation performed on an XTS-encrypted partition failed. - BZ#719578 - When specifying the network mask during the manual network setup using the dotted format, a spurious error message was displayed. - BZ#727774 - When using the bnx2i iSCSI adapters, the installer did not read IP from iBFT properly. - BZ#737161 - The "dhcptimeout" option was not propagated. - BZ#738186 - The "--only-use" ignoredisk parameter did not work so that Anaconda terminated unexpectedly. - BZ#742889 - portmap was not available in rescue mode so that the rescue environment was unable to mount NFS volumes. - BZ#756707 - Adding "-@conflicts" to the kickstart file did not prevent the conflicting packages from the @conflicts group to be installed if other packages depended on the conflicting packages. Now, the conflicting packages and packages that depend on the conflicting packages are not installed. - BZ#758106, BZ#768082 - Pressing Esc in certain Anaconda windows had the same result as clicking "OK". With this update, pressing Esc has the same result as clicking "Cancel". - BZ#709931 - The Network Configuration interface localization was incomplete. - BZ#711363 - The Installation Number screen did not display links under the pa_IN locale. Enhancement 4.5. aspell Bug Fix 4.6. aspell-sr Bug Fix 4.7. audit Note Bug Fixes - BZ#654883 -#671261 - The audit.rules(7) and auditctl(8) manual pages were not consistent in the order of the "action" and "list" fields for the "-a" option. The auditctl(8) manual page has been modified to inform users that the fields can be used in either order. - BZ#702279 -#706156 -. Enhancement 4.8. autofs Bug Fix - BZ#750463 -. Bug Fix - BZ#744698 - Previously, when a mounted autofs entry was removed from the autofs direct map and the map was reloaded before the map entry expired, the mount failed to unmount. If such a file system was unmounted manually, the next time a process tried to access this file system, the process became unresponsive. With this update, conditions preventing this behavior have been included into the code. The file system can now be accessed normally and the process no longer hangs. Bug Fix - BZ#735935 - Prior. Bug Fixes - BZ#655685 -#692814 -#700142 - Previously, the automount logged confusing error messages when syntax errors occurred in map entry locations. This update modifies these messages and displays more informative messages were possible. - BZ#700896 -#725536 -#731514, BZ#732333 -2332 - Previously, automount could become unresponsive when reloading a master map that included a combination of direct and indirect maps due to incorrect lock ordering. This update corrects the logic used to determine if the lookup needs to continue into included maps. - BZ#734675 -#747020 - Previously, the map key lookup mechanism did not find keys in an included multi-mount map entry. This update modifies the lookup mechanism so that keys in multi-mount map entries are now found correctly. - BZ#759221 -. Enhancement 4.9. bind. Bug Fixes - BZ#663112 - Previously, the "named" name service daemon failed to set the max open files limit to "unlimited" by default. Consequently, the error message "max open files (1024) is smaller than max sockets (4096)" was logged. With this update the problem has been fixed, named now sets max open files limit to "unlimited" as documented, and the problem no longer occurs. - BZ#676242 -#692758 -03451 - When the "search" option was present in the "/etc/resolv.conf" file but there were no arguments entered for the option, the contents of the following line in the file was interpreted as the missing argument. Consequently, if the following line contained the only "nameserver" option in the file, the system would have no nameservers specified and therefore fail to resolve any hostnames. With this update the code has been improved, the resolv.conf file is parsed correctly, and the problem no longer occurs in the scenario described. - BZ#712791 - The "/usr/sbin/bind-chroot-admin" script created symlinks with a double-slash (//) in the paths. This caused logrotate to fail to rotate "/var/log/named.log" correctly. With this update, the bind-chroot-admin utility is fixed and no longer creates symlinks with a double-slash and as a result "/var/log/named.log" is rotated as expected. - BZ#726120 - When /etc/resolv.conf contained nameservers with disabled recursion, nslookup failed to resolve certain host names. With this update, nslookup has been patched and now works as expected in the scenario described. - BZ#733698 - During a DNS zone transfer, named sometimes terminated unexpectedly with an assertion failure. With this update, a patch has been applied to make the code more robust, and named no longer crashes in the scenario described. - BZ#758873 - The named daemon, configured as master server, sometimes failed to transfer an uncompressible zone. The following error message was logged:transfer of './IN': sending zone data: ran out of space The code which handles zone transfers has been fixed and this error no longer occurs in the scenario described. Enhancement 4.10. bind97. 4.11. binutils. 4.12. boost Bug Fix - BZ#727895 -. Bug Fix - BZ#727895 -. Security Fixes - CVE-2008-0171 -72 - NULL pointer dereference flaws were found in the way the Boost regular expression library processed certain, invalid expressions. An attacker able to make an application using the Boost library process a specially-crafted regular expression could cause that application to crash. Bug Fixes - BZ#472384 -#567722 - Prior to this update, header files in several Boost libraries contained preprocessor directives that the GNU Compiler Collection (GCC) 4.4 could not handle. This update instead uses equivalent constructs that are standard C. 4.13. bootparamd Bug Fix - BZ#729306 -. 4.14. busybox Bug Fix - BZ#761532 -. Security Fixes - CVE-2006-1168 --2011-2716 -. Bug Fixes - BZ#689659 -#756723 - Prior to this update, the findfs command failed to check all existing block devices on a system with thousands of block device nodes in "/dev/". This update modifies BusyBox so that findfs checks all block devices even in this case. 4.15. cdparanoia. 4.16. certmonger Bug Fix - BZ#767573 - The RHSA-2011-1533 security advisory, which fixed a security vulnerability in the IPA (Identity, Policy and Audit) web-based service, caused incompatibility with older versions of certmonger. As a consequence, certmonger was unable to correctly submit enrollment requests to IPA's CA. With this update, certmonger has been modified and it now operates correctly with newer versions of IPA. Interoperability with older versions of IPA remains unaffected. Bug Fix - BZ#729803 - When submitting a signing request to a Red Hat IPA (Identity, Policy, Audit) CA, certmonger is expected to authenticate using the client's host credentials, and to delegate the client's credentials to the server. Recent updates to libraries on which certmonger depends changed delegation of client credentials from a mandatory operation to an optional operation that is no longer enabled by default, which effectively broke certmonger's support for IPA CAs.This update gives certmonger the ability to explicitly request credential delegation when used with newer versions of these libraries, which introduce an API that allows certmonger to explicitly request that credential delegation be performed. Bug Fixes - BZ#712072 - Prior to this update, ipa-getcert list calls from non-root users logged the misleading message ""Number of certificates and requests being tracked: 0". This update modifies the underlying code to display the correct message "Insufficient access. Please retry operation as root." when non-root users call ipa-getcert list. - BZ#756745 - Prior to this update, starting the certmonger service as non-root user looged the uninformative message "Error connecting to D-Bus.". This update modifies the underlying code to display the correct message "Insufficient access. Please retry operation as root." when non-root users start the certmonger service. - BZ#757883 - Prior to this update, the IPA web-based service was not compatibile with certmonger. As a consequence, certmonger was unable to correctly submit enrollment requests to IPA's CA. With this update, certmonger has been modified and it now operates correctly with newer versions of IPA. Enhancement 4.17. Cluster_Administration 4.18. clustermon Bug Fixes - BZ#618321 - Prior to this update, under certain circumstances, outgoing queues in inter-node communication of the modclusterd service could grow over time. To prevent this behavior, the inter-node communication is now better balanced and queues are restricted in size. Forced queue interventions are logged in the /var/log/clumond.log file. - BZ. 4.19. cman Bug Fix - BZ#782833 -. Bug Fix Enhancement Bug Fixes - BZ#739966 - The FENCED_OPTSvariable was escaped incorrectly. Consequently, only the first option passed to FENCED_OPTSwas processed correctly and any further options were ignored. This update corrects the escaping of the FENCED_OPTSand all options are now honored as expected. - BZ#590101 - The shutdown_convariable was not cleared if the shutdown process was killed. This caused the cmanservice to terminate with a segmentation fault in the unbind_con()function if another process shut down the utility. The shutdown_convariable is now cleared after the shutdown process is canceled and the utility shuts down gracefully. - BZ#727215 - The cman utility released the connection prematurely on shut down. As a consequence, cman sent spurious messages to the syslog utility. With this update, the connection is released after the shutdown process has finished and the spurious messages are no longer sent to syslog. - BZ#730634 - The fence_drac5 agent did not grant enough time to the Dell Remote Access controller 5 (DRAC5) hardware to update its internal connection count. This update adds a sleep function to the respective code to provide the firmware enough time to clean old sessions and new connections are now established as expected. If you are using the DRAC5 firmware released earlier than version 1.60, the firmware needs to be upgrade to 1.60 or later to fix this bug. - BZ#746599 - The cman service_cman.lcrsoservice did not provide debug symbols because the service was built without the -gCFLAGS option. The gcc compiler then built the debuginfo files without debugging symbols. This flag has been added to the Makefile and the service is now built with debugging symbols as expected. - BZ#745536 - The pingcommand examples on the qdisk(5) manual page were missing the -woption. If the pingcommand is run without the option, the action can timeout. With this update, the -woption has been added to the example pingcommands. - BZ#689851 - On a blade removal, the prompt does not signal that the blade is no longer available. Previously, the fence rebootcommand with the --missing-as-offoption relied on the prompt, and the fencing failed. With this update, fence reboot works as expected. - BZ#732773 - The fence_ipmilan agent did not parse the arguments of the passwd_scriptoption in the cluster.conffile and fencing could fail. The arguments are now parsed correctly and fencing succeeds as expected. - BZ#704243 - The qdiskddaemon failed to update a Quorum disk device after it was changed and the clustatcommand showed an old qdisk device as being used. The interactions between the cman utility and qdisk utility have been improved including cman logging, error reports, and checks of Quorum API usage. The qdiskddaemon can now update device names in cman; the error checking at qdickd startup has been improved. - BZ#718194 - Due to a mistake in the fence_drac5list operation, Dell Drac CMC devices were not working correctly as fence devices. The fence_drac5list operation has been fixed for Dell DRAC CMC devices. - BZ#727492 - The cman(5) manual page contained an invalid multicast address in the example of a multicast address overriding. The example has been changed and now contains a valid multicast address. - BZ#715107 - Previously, the fence_vmware_soap utility did not expose valid virtual machine names for fencing. The fence_vmware_soap()function has been updated to support unique virtual machine names. - BZ#753797 - Fencing a Red Hat Enterprise Linux cluster node running in a virtual machine on VMWare with the fence_soap_vmware fence agent failed with the following error message: KeyError: 'config.uuid'This happened because the fencing agent was not able to work with more than one hundred machines in the cluster. With this update, the underlying code has been modified to support fencing of such clusters. Enhancements - BZ#731167 - The fence_rhevm utility has been updated to conform to the changes in the RHEV-M 3.0 API: The RUNNING status has been changed to the UP status. - BZ#730639 - The user can now pass specific options to the fenceddaemon. - BZ#726731 - The fence_ipmilan fencing agent now supports the -Loption for logging in as a non-privileged user and fence with the user session privileges. - BZ#749245 - The fence_scsi fencing mechanism now works with CLVM (Clustered Logical Volume Manager) when High Availability LVM (HA-LVM) in CLVM mode is used to provide a data store for services. 4.20. cmirror. 4.21. comps-extras Bug Fix 4.22. conga Bug Fix - BZ#741169 -. Security Fixes - CVE-2010-1104, CVE-2011-1948 -. Bug Fixes - BZ#709478 - Previously, due to incorrect permissions from libvirt, the riccidaemon failed to detect if a host was capable of running a virtual machine. As a consequence, the Add a Virtual Machine Service tab was not displayed under Services when using the luci tool. With this update, calling the virsh program is now avoided, and the Add a Virtual Machine Service tab is now displayed under Services. - BZ#723000 - If the user modified in luci the attribute of a shared resource that was attached to an existing service, the attribute for the shared resource in the cluster.conffile was not updated. With this update, luci is modified so that the attribute in cluster.confis correctly updated to reflect the new name of the resource. - BZ#723188 - Previously, luci did not allow users to modify the __max_restartsand __restart_expire_timeattributes for independent subtrees, but only for non-critical resources. If the user tried to set values for "Maximum number of restart failures before giving up (applies only for non-critical resources)" and "Restart expire time (applies only for non-critical resources)", these values were not added for the resource in the cluster.conffile. This update modifies luci so that users are now able to modify the aforementioned values in luci. - BZ#732483 - Prior to this update, execution of external programs (such as /usr/sbin/clustat) from within the modclusterddaemon or ricci's helper program, modcluster, could make these unresponsive. In such a case, processes depending on them. - BZ#734562 - When adding a resource to a service, luci only checked to verify that the name of the resource did not match the name of a resource in the resources stanza. The luci tool did not check to see if any resources in other services shared the same name, and therefore allowed users to create two services with the resources of the same name. This led to unique attribute collisions. With this update, luci's name validation is improved, and adding a resource to a service no longer leads to collisions. In addition, certain error messages have been modified to display more verbose information. - BZ#739600 - Previously, users were able to insert the quote character (") with NFS resources in the "resources" section of the cluster configuration in conga. The resource data submitted for this service was not properly formed and converted into the cluster.conffile. With this update, if the user inserts the quote character, the following error message appears: The resource data submitted for this service is not properly formed - BZ#755941 - Previously, the luci_admin restorecommand did not fully restore a database to the original state. This was because the luci_adminscript only added items contained in the previously generated backup XML file. This update adds new options, -u( --update) and -r( --replace), that are used to either keep or remove existing configuration when restoring a database. Enhancement service luci restart) for the update to take effect. 4.23. crash. 4.24. cups -#625900 - Prior to this update, the "Show Completed Jobs," "Show All Jobs," and "Show Active Jobs" buttons returned results globally across all printers and not the results for the specified printer. With this update, jobs from only the selected printer are shown. - BZ#625955 -60518 -68009 - Prior to this update, the file descriptor count increased until it ran out of resources when the cups daemon was running with enabled Security-Enhanced Linux (SELinux) features. With this update, all resources are allocated only once. - BZ#759081 -. 4.25. curl Bug Fix - BZ#727884 -. Bug Fixes - BZ#652557 - In the FTP implementation, libcurl incorrectly called the accept() function from a system library, which caused a stack overflow under certain circumstances. This update applies a backported upstream patch that corrects this bug, and the stack overflow no longer occurs. - BZ#655073 - Previously, an attempt to send an LDAP request through an HTTP proxy tunnel ended up with cURL trying to connect to the LDAP server directly using a wrong port number. With this update, the underlying source code has been modified to fix this problem, and cURL now works as expected. - BZ#688871 - Previously, the "multi" interface of libcurl was broken, which caused the "git push" command to work incorrectly over the Web Distributed Authoring and Versioning (WebDAV) protocol. This update applies an upstream patch, which corrects counting of active connections in the "multi" interface. The "git push" command now works as expected over WebDAV. - BZ#723643 - As a solution to a security issue, GSSAPI credential delegation was disabled, which broke the functionality of the applications that were relying on delegation, which was incorrectly enabled by libcurl. To fix this problem, the CURLOPT_GSSAPI_DELEGATION libcurl option has been introduced in order to enable delegation explicitly when applications need it. All applications using GSSAPI credential delegation can now use this new libcurl option to be able to run properly. Enhancements - BZ#657396 - Previously, curl did not support proxy authentication using Kerberos. With this update, underlying code has been modified and curl now allows Kerberos proxy authentication by using the "--proxy-negotiate" option. - BZ#746849 - The cURL utility did not allow Kerberos credential delegation although the libcurl library provided appropriate support for this functionality. This update introduces a new option, "--delegation", which enables Kerberos credential delegation in cURL. 4.26. cvs. 4.27. cyrus-imapd Security Fixes - CVE-2011-3372 - An authentication bypass flaw was found in the cyrus-imapd NNTP server, nntpd. A remote user able to use the nntpd service could use this flaw to read or post newsgroup messages on an NNTP server configured to require user authentication, without providing valid authentication credentials. - CVE-2011-3481 - A NULL pointer dereference flaw was found in the cyrus-imapd IMAP server, imapd. A remote attacker could send a specially-crafted mail message to a victim that would possibly prevent them from accessing their mail normally, if they were using an IMAP client that relies on the server threading IMAP feature. Security Fix - CVE-2011-3208 -. 4.28. dapl Bug Fixes - BZ#634323 - Previously, an error in the code path in the uDAPL layer did not allow the cp_ptr entry to be cleaned up correctly in the internal link list. This could cause new connections to fail. With this update, the entry is cleaned up correctly and subsequent connections work as expected. - BZ#634324 - Previously, dapl could leak file descriptors and the application could terminate. With this update, the leak is closed and dapl behaves as expected. - BZ#636193 - Previously, verbs CQ and completion channels were not correctly disconnected and freed, which could cause an application crash. With this update, verbs CQ and completion channels behave as expected. - BZ#636197 - Previously, an error in the code path in the compat-dapl layer did not allow the cp_ptr entry to be cleaned up correctly in the internal link list. This could cause new connections to fail. With this update, the entry is cleaned up correctly and subsequent connections work as expected. - BZ#645825 - Under certain circumstances, the dat_ia_open() call and the programs using the function could become unresponsive. With this update, the underlying code has been modified and the function behaves as expected. - BZ#658950 - Due to an invalid error mapping, when dapl received a signal during the execution of the dapls_evd_dto_wait() function, it could fail to set the correct error type, which may have led to an incorrect operation. With this update, the relevant part of the source code has been modified to return the correct value, and dapl now works as expected. 4.29. dbus. 4.30. Deployment_Guide 4.31. device-mapper Bug Fix - BZ#454618 - The dmeventd daemon was not properly restarted after the package update. Consequently, dmeventd did not apply the newly updated libraries and continued using the old libraries. Therefore, logical volume monitoring failed and had to be re-activated because particular monitoring events were not handled as expected. With this update, dmeventd properly restarts after the package update so that updated libraries are applied and logical volumes are monitored as expected. 4.32. device-mapper-multipath Bug Fix - BZ#729478 -. Bug Fix - BZ#728144 - Previously, device-mapper-multipath was looking for a CCISS device information at the incorrect location in the sysfs file system. As a consequence, it was impossible to configure multipath on CCISS devices. This bug has been fixed, device-mapper-multipath now finds the device information properly in the described scenario, and multipath can now be properly configured on CCISS devices. Bug Fixes - BZ#741664 - If a multipath device was deleted while its path was being checked, the multipathddaemon did not abort the path check. Consequently, the multipath application terminated unexpectedly if it attempted to access the multipath device information. With this update, multipathdaborts the path check and the daemon no longer crashes in this scenario. - BZ#703501 - Previously, the multipathddaemon was looking for Compaq Command Interface for SCSI-3 Support (CCISS) device information at an incorrect location in the sysfsfile system. As a consequence, it was impossible to configure multipath on CCISS device. This bug has been fixed, device-mapper-multipath now finds the device information in the described scenario, and multipath can now properly configure CCISS devices. - BZ#702410 - The multipathddaemon was printing warning messages on removal of non-multipath Device Mapper devices. With this update, the underlying code has been fixed and no warning messages are logged on removal of such devices. - BZ#737072 - Previously, SCSI targets could time out on SCSI commands and consequently become unresponsive. This happened because the mpath_prio_alua priority callout used by the commands was set to five minutes. With this update, the callout timeout has been changed to one minute. - BZ#703277 - The multipathddaemon maintains a list of essential directories it needs to be able to access from its private namespace at all times. When unmounting an unnecessary device, multipath checks if the device mount point is not in the list. Previously, multipathddid not check whether the directories listed were symbolic links to the devices and did not consider the devices mounted at the symlinked mount point to be necessary. Consequently, if such a device was marked as unnecessary, multipathd unmounted the device even though the location was listed as essential, because it was listed as a symbolic link. With this update, multipathd detects symbolic links to necessary devices in the list and the symlinked devices are not unmounted. This update also adds a new parameter, keep_dir, which allows users to specify directories that multipathd preserves in its private namespace. - BZ#655203 - If the user attempted to delete a multipath device but failed because partitions of the device were in use, some of the device partitions remained deleted. With this update, if multipathdfails to delete the entire device, it restores any partitions, which were already deleted. - BZ#729478 - The multipath priority callout programs did not work correctly with CCISS (Compaq Command Interface for SCSI-3 Support) devices because the multipath utility was not able to convert the exclamation mark ( !) character in the CCISS sysfsname to the slash ( /) character in the CCISS device name. As a consequence, the callout programs failed to set path priorities for these devices. The multipath utility now supports the new %cwildcard for callout functions and the CCISS names are converted correctly. - BZ#650795 - The multipathddaemon returned incorrect path groupings for the multipath devices configured to use the group_by_node_name grouping policy. This was due to an incorrect reporting of the target node name for iSCSI targets. With this update, multipath checks the iSCSI target name if the FC (Fibre Channel) path check fails and the target name reporting works as expected. - BZ#716329 - Previously, multipathdterminated unexpectedly if the file_timeoutparameter was set to 0. With this update, multipathd uses the default file timeout of 90 seconds just as when the parameter is set to a negative value and the problem no longer occurs. - BZ#740512 - The mpath_prio_alua callout occasionally failed. This happened because multipathddid not clean some of the buffers used to collect the SCSI data. With this update, the buffers are cleaned properly and the problem no longer occurs. - BZ#740022 - Multipath commands failed on a multipath device if the current working directory contained a file with the same name as the multipath device name. This happened because multipathdassumed that the argument was referring to the file. Multipath now performs a check to prevent such an incorrect argument handling and the commands are executed as expected in this scenario. - BZ#655976 - On a device set to manualfailback, multipath was incorrectly failed back to the primary path group on a path's priority change. With this update, the device no longer fails back to the primary path group under these circumstances. - BZ#711970 - Previously, the multipath default configuration defined the path selector using the selectorkey word, while device sections were using the path_selectorkey word. To ensure consistency, the default section now accepts both key words, the selectorand path_selector. - BZ#719575 - The kpartx utility built partition devices for GUID partition tables (GPT) with incorrect partition entry size. This happened because the utility did not validate the size of the GUID partitions. The kpartx utility now checks the size of the partitions, and partitions of an invalid GPT are no longer created. - BZ#715524 - Previously, the default config value file_timeoutwas not documented. This update adds the respective documentation to the multipath.conf.annotatedfile. 4.33. dhcp Security Fixes - CVE-2011-2748, CVE-2011-2749 - Two denial of service flaws were found in the way the dhcpd daemon handled certain incomplete request packets. A remote attacker could use these flaws to crash dhcpd via a specially-crafted request. Bug Fix - BZ#736515 - Previously, the anaconda dhcptimeout value was not fully propagated to libdhcp4client's internal timeout_arg. As a result, it used the insufficient default timeout of 60 seconds. With this update, anaconda dhcptimeout value is correctly propagated and the problem no longer occurs with this update. This update is a dependency of BZ#737155 and BZ#737161. 4.34. dovecot Security Fix - CVE-2011-1929 -. 4.35. ecryptfs-utils Security Fixes - CVE-2011-1831 -32 - A race condition flaw in umount.ecryptfs_private could allow a local attacker to unmount an arbitrary file system. - CVE-2011-1834 - It was found that mount.ecryptfs_private did not handle certain errors correctly when updating the mtab (mounted file systems table) file, allowing a local attacker to corrupt the mtab file and possibly unmount an arbitrary file system. - CVE-2011-1835 -37 - A race condition flaw in mount.ecryptfs_private could allow a local attacker to overwrite arbitrary files. - CVE-2011-3145 - A race condition flaw in the way temporary files were accessed in mount.ecryptfs_private could allow a malicious, local user to make arbitrary modifications to the mtab file. - CVE-2011-1833 -. Bug Fixes - BZ#554740 -36. 4.36. esound. 4.37. fcoe-utils". 4.38. fetchmail. 4.39. file Bug Fixes - BZ#486328 - Previously, the file utility always checked a section of the core file which was only used by FreeBSD when looking up command names. As a consequence, an incorrect command name could be reported. This update checks this offset only if the core file was generated on a FreeBSD plattfrom. Now, the file utility displays the correct file name. - BZ#489493 - Previously, the file utility did not correctly recognize file system dumps generated by the "dump" utility on PowerPC and IBM System z platforms which were wrongly identified as a "JVT NAL" sequence. This update modifies the order of the magic patterns. Now, the file utility correctly identifies these dumps. - BZ#494831 - Previously, the Note field stored in Executable and Linkable Format (ELF) binaries was wrongly processed twice. As a consequence, the message "for GNU/Linux X.Y.Z" was displayed twice for certain binary files. This update modifies the process. Now, the Note field is processed only once. - BZ#498671 - Previously, the definition for the Multipurpose Internet Mail Extensions (MIME) type "XML" was missing in the magic file. As a consequence, the MIME type for XML files was not displayed. This update adds this MIME type to the magic file. - BZ#504417 - Previously, the file utility did not recognize the swap file system on PowerPC platforms. Now, a new magic pattern for swap on PowerPC platforms is added and the file utility now identifies the swapspace correctly. - BZ#505656 - Previously, the "msword" MIME type was listed two times in DOC/XLS magic patterns. As a consequence, the "application/msword" MIME type was displayed twice for certain Microsoft Office 2007 files. Now, the second MIME type definition is removed. - BZ#508688 - Previously, the magic pattern for detecting the PPD files did not work as expected. As a consequence, the file utility truncated the "version" string of certain PPD files. This update displays the "version" string correctly and no longer truncates the version number. - BZ#548450 - Previously, the manual page did not mention that a 0 exit code was returned when input files were not found. This update adds the missing information to the manual page. - BZ#618910 - Previously, the file utility always attempted to read complete files from stdin to get additional information about ELF binary even when the file was not an ELF binary. As a consequence, the process used a large amount of memory and took a long time. This update detects if a file is an ELF binary using the ELF magic bytes and reads the complete file only when the file is an ELF binary. - BZ#641838 - Previously, the file utility could wrongly recognize gzip files as FLC files. This update changes the order of gzip and FLC magic patterns. Now, the file utility identifies gzip files correctly. - BZ#668125 - Previously, the GFS1 and GFS2 file systems shared the same magic number in the superblock which the file utility used to identify the GFS2 file system. As a consequence, the file utility wrongly recognized GFS2 file systems as GFS1 file systems. This update adds a new magic pattern for the GFS2 file system. Now, the file utility identifies GFS2 correctly. - BZ#692435 - Previously, two magic patterns for XML identification were wrongly merged into one. As a consequence, the file utility could not identify the MIME type for XML files starting with "?xml". This update splits these two patterns. Now, the correct MIME type is displayed. - BZ#758429 - Previously, the file utility could wrongly recognize JPEG files as Minix file systems. This update changes the order of JPEG and Minix magic patterns. Now the file utility recognizes JPEG files correctly. 4.40. firefox-2011-3647 -648 - A cross-site scripting (XSS) flaw was found in the way Firefox handled certain multibyte character sets. A web page containing malicious content could cause Firefox to run JavaScript code with the permissions of a different website. - CVE-2011-3650 - A flaw was found in the way Firefox handled large JavaScript scripts. A web page containing malicious JavaScript could cause Firefox to crash or, potentially, execute arbitrary code with the privileges of the user running Firefox. Security Fixes - CVE-2011-2995 - Several flaws were found in the processing of malformed web content. A web page containing malicious content could cause Firefox to crash or, potentially, execute arbitrary code with the privileges of the user running Firefox. - CVE-2011-2372 --3000 --2999 - A flaw was found in the way Firefox handled frame objects with certain names. An attacker could use this flaw to cause a plug-in to grant its content access to another site or the local file system, violating the same-origin policy. - CVE-2011-2998 -. Security Fix Security Fix - BZ#734316 -. Security Fixes - CVE-2011-2982 - Several flaws were found in the processing of malformed web content. A web page containing malicious content could cause Firefox to crash or, potentially, execute arbitrary code with the privileges of the user running Firefox. - CVE-2011-0084 - A dangling pointer flaw was found in the Firefox Scalable Vector Graphics (SVG) text manipulation routine. A web page containing a malicious SVG image could cause Firefox to crash or, potentially, execute arbitrary code with the privileges of the user running Firefox. - CVE-2011-2378 - A dangling pointer flaw was found in the way Firefox handled a certain Document Object Model (DOM) element. A web page containing malicious content could cause Firefox to crash or, potentially, execute arbitrary code with the privileges of the user running Firefox. - CVE-2011-2981 - A flaw was found in the event management code in Firefox. A website containing malicious JavaScript could cause Firefox to execute that JavaScript with the privileges of the user running Firefox. - CVE-2011-2983 - A flaw was found in the way Firefox handled malformed JavaScript. A web page containing malicious JavaScript could cause Firefox to access already freed memory, causing Firefox to crash or, potentially, execute arbitrary code with the privileges of the user running Firefox. - CVE-2011-2984 - It was found that a malicious web page could execute arbitrary code with the privileges of the user running Firefox if the user dropped a tab onto the malicious web page. 4.41. firstboot. 4.42. foomatic Security Fix - CVE-2011-2697 -. 4.43. freeipmi Bug Fixes - BZ#439411 - Prior to this update, the "ipmi-sel" tool did not properly initialize itself and crashed when reading an empty SEL (System Event Log). With this update, ipmi-sel initialization is fixed and the tool no longer crashes when reading an empty SEL. - BZ#639850 - Prior to this update, the "freeipmi-bmc-watchdog" service start did not expect that a Baseboard Management Controller (BMC) watchdog timer could already be running and did not reset the timer. In addition, the service stop did not stop the BMC watchdog timer. This could result in a watchdog timer resetting, or shutting down, the machine. With this update, "service freeipmi-bmc-watchdog start" resets any previously started BMC watchdog timer and "service freeipmi-bmc-watchdog stop" correctly stops the timer. As a result the machine boots up normally. 4.44. freeradius2 Bug Fixes - BZ#546583 - The documentation of command-line arguments was incomplete and in some cases erroneous; some commands did not have a man page. The man pages and help output were updated to correct these deficiencies. - BZ#602567 -#658508 - The freeradius-pam-conf configuration file, /etc/pam.d/radiusd, referenced a non-existent pam configuration "password-auth". This has been fixed to refer to "system-auth". - BZ#756442 -#760193 - The radtest command-line argument to request the PPP hint option was not parsed correctly. Consequently, radclient did not add the PPP hint to the request packet and the test failed. This update corrects the problem and radtest now functions as expected. Enhancements - BZ#630072 -. 4.45. freetype Security Fixes - CVE-2011-3439 - Multiple input validation flaws were found in the way FreeType processed CID-keyed fonts.. Security Fixes - CVE-2011-3256 -. 4.46. gamin Bug Fix 4.47. gawk Bug Fix - BZ#629196 -. 4.48. gcc. 4.49. gcc44 Enhancement 4.50. gdb Bug Fix - BZ#728151 -. Bug Fixes - BZ#658851 - GDB could stop with an error when trying to access the libpthread shared library before the library was relocated. With this update, GDB lets the library relocations be resolved first, allowing GDB to debug programs properly under these circumstances. - BZ#696148 - Modifying a string in the executable using the "-write" command line option could fail with an error if the executable was not running. With this update, GDB can modify executables even before they are started. - BZ#720717 - When printing data from a string buffer of constant size, GDB, by default, also prints the data following after the first zero byte ("\0") of the string. To display only the data before the zero byte, the "set print null-stop" option has to be set. Previously with this option set, GDB did not display any string content due to an incorrect zero byte test condition in the code. The test condition has been corrected and GDB now properly displays data located before the first zero byte. - BZ#727726 - GDB convenience variables allow a user to store and retrieve arbitrary data of arbitrary data types. Previously, when the GDB convenience variable contained a structure data type, accessing a field of the structure caused an internal error. With this update, this problem has been corrected, and GDB now works with structure convenience variables correctly. - BZ#748267 - When loading a core dump file for debugging, GDB could incorrectly interpret inappropriate memory content as the pthread_t identifier if the version of the glibc library installed on the system did not match the glibc version used to create the core dump file. Consequently, initialization of the libthread_db library failed due to an unexpected value of pthread_t, which led to a GDB internal error. With this update, GDB only displays a warning message and successfully loads the core file. Instead of the pthread_t identifiers, which are unavailable in this failure scenario, GDB displays the LWP (light-weight process) identifiers that match the Linux TID (Thread Identifier) values of the threads found in the core file. 4.51. gdm. 4.52. gfs-kmod Bug Fixes - BZ#732129 - Previously, the directory pre-fetching GFS functionality could decrease performance of some applications that were running on the GFS file system. This update introduces a new GFS mounting option, "-o noprefetch", which disables the directory pre-fetching feature. The applications running on the GFS file system mounted with this option no longer experience performance problems caused by this feature. - BZ#761157 - When attempting to add files to a GFS file system and the file system became full, the GFS kernel daemon did not properly release resources allocated for inodes that could not be created. This could result in file system corruption. This patch introduces new cleanup code, which removes partially created inodes and releases allocated resources correctly. 4.53. gfs-utils. 4.54. gfs2-utils Bug Fixes - BZ#711451 - To expand a GFS2 file system, additional resource groups must be added to manage new space. The gfs2_grow utility ensures this by writing to the rindex file. Previously, if there was not enough free space in the file system to write out new resource group entries, gfs2_grow was unable to update the rindex file. As a consequence, gfs2_grow was unable to expand the file system and failed with the following error message:Error writing new rindex entries;aborted.With this update, gfs2_grow writes one resource group at first, and then the rest instead of attempting to write all the new resource groups at once. Now, gfs2_grow successfully expands the file system in the described scenario. - BZ#714739 - Previously, the libgfs2 library used the obsolete MAJOR() and MINOR() macros to handle device numbers. These macros did not support device numbers greater than 255, and could cause error messages to be displayed when using gfs2-utils. The macros have been replaced by the major() and minor() functions, and gfs2-utils now works properly with device numbers greater than 255. - BZ#720935 - Previously, the "mkfs.gfs2" command worked only on block devices. Using the command on sparse files failed with an error message. An upstream patch has been applied to address this issue, and the mkfs.gfs2 utility now also recognizes regular files. - BZ#730091 - Previously, the gfs2_grow utility failed to expand a GFS file system if the file system contained only one resource group. This was due to old code. The file system with only one resource group can now be expanded successfully. - BZ#745126 - was required (for example, a file system with block size of 512, and 9 or more journals). With this update, incrementing the count of the directory entry is now avoided when dealing with sentinel entries. GFS2 file systems created with large numbers of journal metadata blocks now pass the fsck check cleanly. Enhancement - BZ#702296 - Prior to this update, when executing the "gfs2_edit" command with the "savemeta" or "restoremeta" options specified, the command produced uncompressed files that were very large in size. This update allows gfs2_edit to compress metadata while writing by using the "savemeta" option, and also read a compressed metadata file by using the "restoremeta" option. 4.55. ghostscript - It was found that Ghostscript always tried to read Ghostscript system initialization files from the current working directory before checking other directories, even if a search path that did not contain the current working directory was specified with the "-I" option, or the "-P-" option was used (to prevent the current working directory being searched first). If a user ran Ghostscript in an attacker-controlled directory containing a system initialization file, it could cause Ghostscript to execute arbitrary PostScript code. - CVE-2010-4820 -. NoteThe fix for CVE-2010-4820 could possibly break existing configurations. To use the previous, vulnerable behavior, run Ghostscript with the "-P" option (to always search the current working directory first). - CVE-2010-4054 -. Bug Fixes - BZ#734764 - Prior to this update, the page orientation was incorrect when pages in landscape orientation were converted to the PXL raster format. This update matches landscape page sizes as well as portrait page sizes, and sets the orientation parameter correctly when a match is found. - BZ#734767 - Prior to this update, certain input files containing CID Type2 fonts were rendered with incorrect character spacing. This update modifies the code so that all input files with CID Type2 fonts are rendered correctly. Bug Fixes - BZ#675307 - Previously, using the ps2pdf utility to convert a PostScript file to the PDF format caused the resulting document to be created with non-working hyperlinks. This update applies an upstream patch that resolves this issue, and ps2pdf now creates PDF files with correct hyperlinks. - BZ#688996 - Prior to this update, certain input files containing CID Type2 fonts were rendered with incorrect character spacing. This update modifies the code so that all input files with CID Type2 fonts are rendered correctly. - BZ#692165 - Prior to this update, the page orientation was incorrect when pages in landscape orientation were converted to the PXL raster format. This update matches landscape page sizes as well as portrait page sizes, and sets the orientation parameter correctly when a match is found. 4.56. glibc-2010-0830 - Fix - BZ#745487 -. Bug Fixes - BZ#585433 - Priviously, glibc incorrectly computed the amount of memory needed by strcoll_l and strxfrm functions. As a consequence, a stack overflow could occur, especially in multi-threaded applications with small stack sizes. This update fixes the memory usage computations and avoids the stack overflows. - BZ#657570 - Prior to this update, glibc used an incorrect matching algorithm in the strptime function. As a result, strptime could misparse months in certain locales including Polish and Vietnamese. This update corrects the matching algorithm in strptime. - BZ#675259 - Priviously, the glibc locale information was wrong for certain French, Spanish and German locales. As a result, incorrect numeric output could be reported. This update corrects the information. - BZ#678318 - Prior to this update, nss_nis client code in glibc attempted to read the passwd.adjunct table for certain usernames. This typically required more privileges than a normal user has and thus errors were logged on the The Network Information Service (NIS) server. This update changes glibc to only refer to passwd.adjunct when it is actually necessary. - BZ#711924 - Priviously, the dl_debug_state RT_CONSISTENT incorrectly occurred before applying dynamic relocations. As a result, debugging tools could not correctly monitor this call. This update adds systemtap-probes at a superset of the locations where the dl_debug_state was called. - BZ#711531 - Prior to this update, glibc did not initialize the robust futex list after a fork. As a result, shared robust mutexes were not cleaned up when the child exited. This update ensures that the robust futex list is correctly initialized after a fork system call. - BZ#707998 - Prior to this update, glibc returned incorrect error codes from the pthread_create. This could lead some programs to incorrectly issue an error for a transient failure, such as a temporary out of memory condition. This update ensures glibc returns the correct error code when memory allocation fails in pthread_create. - BZ#706894 - Prior to this update, the system configuration option _SC_NPROCESSORS_CONF returned the total number of active processors configured rather than the total number of configured processors. This update changes glibc to query system configurations to get the number of configured processors correctly. - BZ#703345 - Prior to this update, getpwent could incorrectly query NIS when using the nss_compat option. This could lead to incorrect results (missing entries) for calls to getpwent. This update changes glibc to only query the NIS domain when needed. - BZ#729661 - Prior to this update, the dynamic loader generated an incorrect ordering for initialization according to the ELF specification. This could result in incorrect ordering of DSO constructors and destructors. With this update, dependency resolution has been fixed - BZ#756453 - Prior to this update, the libresolv routines were not compiled with the stack protector enabled. As a consequence, a buffer overflow attack vector could occur if the libresolv routines had potential stack overflows. This update turns on the stack protector mechanisms for libresolv. - BZ#758252 - Prior to this update, the futimes function rounded values rather than truncate them. As a consequence, file modification, access, or creation times could be incorrect. This update correctly truncates values and gives the correct file modification, access & creation times. 4.57. Global_File_System 4.58. gnome-screensaver Bug Fix - BZ#771849 - When locking the screen, the gnome-screensaver application takes exclusive control of the mouse and keyboard. If another application has already taken exclusive control of the keyboard, gnome-screensaver is unable to take over that control. Under these circumstances, gnome-screensaver previously did not engage the screen saver but waited for the keyboard to become available. During this time-frame, the system was unresponsive to mouse clicks because gnome-screensaver held on to control of the mouse. With this update, gnome-screensaver has been modified to release control of the mouse until it can get control of both, the mouse and the keyboard, and the system is no longer unresponsive in this scenario. Bug Fix - BZ#766799 -. 4.59. gnome-system-monitor Bug Fix - BZ#616487 - The previous version of the gnome-system-monitor utility did not close the socket when it terminated, which may have rendered it unable to start for the second time. This update applies a patch that ensures the socket is properly closed when the utility terminates, and gnome-system-monitor now works as expected. Enhancement - BZ#722866 - Previously, the minimum width of the gnome-system-monitor window was limited by the minimum width of its content. Consequently, running this utility on a system with a large number of CPUs caused this window to be very large. This update adds a horizontal scrollbar to make sure the gnome-system-monitor window can fit to the screen even when the system has multiple CPUs. 4.60. gpart Bug Fix 4.61. groff. 4.62. gtk2 Bug Fix 4.63. hmaccalc. 4.64. httpd Security Fix - CVE-2011-3368 -. Bug Fix - BZ#736593, BZ#736594 - The fix for CVE-2011-3192 provided by the RHSA-2011:1245 update introduced regressions in the way httpd handled certain Range HTTP header values. This update corrects those regressions. Security Fix - CVE-2011-3192 - A flaw was found in the way the Apache HTTP Server handled Range HTTP headers. A remote attacker could use this flaw to cause httpd to use an excessive amount of memory and CPU time via HTTP requests with a specially-crafted Range header. Bug Fixes - BZ#700322 - In situations when httpd could not allocate memory, httpd sometimes terminated unexpectedly with a segmentation fault rather than terminating the process with an error message. With this update, a patch has been applied to correct this bug and httpd no longer crashes in the scenario described. - BZ#767990 - issues an appropriate error message in this scenario. Enhacements - BZ#677279 - The rotatelogs program now provides a new "rotatelogs -c" option to create log files for each set interval, even if empty. - BZ#677288 - The rotatelogs program now provides a new "rotatelogs -p" option to execute a custom program after each log rotation. - BZ#709869 - The Apache module mod_proxy now allows changing the BalancerMember state in the web interface. - BZ#714725 - The Apache module mod_alias now supports redirecting to a local path (that is, a partial URL). - BZ#719907 - The Apache module mod_proxy now supports the "connectiontimeout" parameter. - BZ#719941 - The httpd service is now automatically restarted after a package upgrade, if the service is running. 4.65. hwdata Enhancements - BZ#711121 - The monitor database has been updated with information about Acer 76ie monitors. - BZ#720938 - The pci.ids database has been updated with information about future Intel PCH (Platform Controller Hub) devices. - BZ#714098 - The pci.ids database has been updated with information about the latest HP iLO4 devices. - BZ#713068 - The pci.ids database has been updated with information about future Atheros wireless devices. - BZ#747861 - The pci.ids database has been updated according to the latest upstream changes. 4.66. ibutils Security Fix - CVE-2008-3277 -. Bug Fix 4.67. icu. 4.68. ifd-egate Bug Fixes - BZ#667126 - The ifd-egate package is dependent on the pcsc-lite package but pcsc-lite is not a part of the minimal system installation. Previously, the ifd-egate driver generated a spurious error message when it was installed on the system with minimal installation even though pscs-lite was installed during the same installation transaction. With this update, the spec file has been modified to correct this problem and the error message is no longer generated in this scenario. - BZ#759638 - The idf-egate.spec file incorrectly used the "%{dist}" flag instead of the "%{?dist}" flag. With this update, the correct flag is now used. 4.69. ImageMagick. 4.70. initscripts Security Fix - CVE-2008-1198 -. Bug Fixes - BZ#568896 - Prior to this update, the DHCPv6 client was not terminated when the network service was stopped. This update modifies the source so that the client is now terminated when stopping the network service. - BZ#679998 - Prior to this update, on some systems the rm command failed and reported the error message "rm: cannot remove directory `/var/run/dovecot/login/': Is a directory" during system boot. This update modifies the source so that this error message no longer appears. - BZ#744734 -45681 -. 4.71. ipa-client Bug Fix - BZ#768058 -. Bug Fix - BZ#736658 -. Bug Fixes - BZ#723667 -#752226 -#739068 -10143 -#750338 -#723620 -. 4.72. iproute Bug Fixes - BZ#645260 -264 - Prior to this update, the "lnstat" usage message and man page contained spelling mistakes for the "-dump" and "-key" options. With this update these errors have been corrected. - BZ#645267 - Prior to this update, the "ss" usage message and man page erroneously included an unsupported option ("-query") and omitted three supported options ("-diag", "-D", and "-socket"). With this update these errors and omissions have been corrected. - BZ#727059 -. 4.73. iprutils Enhancement 4.74. iptables Bug Fixes - BZ#520797 - Prior to this update, the memory alignment of ipt_connlimit_data was incorrect on x86-based systems. An error message in the format "ip_tables: connlimit match: invalid size" was logged. This update adds an explicit alignment attribute to the ipt_connlimit_data structure to correct this. - BZ#552522 - The sysctl values for netfilter kernel modules were not restored after a firewall restart. Consequently, the firewall did not always perform as expected after a restart. This update applies a patch to optionally load sysctl settings on iptables start, if specified by the user in the /etc/sysctl.conf file. Users can now define sysctl settings to load on start and restart. - BZ#554340 - Prior to this update, the kernel netfilter modules were not loaded at all times. Consequently, some commands did not perform as expected the first time they were executed. With this update, a patch has been applied to ensure the modules are properly loaded and the problem no longer occurs. Enhancements - BZ#471163 - Prior to this update, the statistic match module was not included in the iptables package. With this update, this module in now included. - BZ#710050 - A service reload option has been added to enable a refresh of the firewall rules without unloading netfilter kernel modules and dropping connections. 4.75. iscsi-initiator-utils Bug Fixes - BZ#714744 - Prior to this update, the iscsiadm help wrongly listed discovery2 mode instead of discoverydb. This update modifies the help file and now the correct output of the help contents is shown. - BZ#716323 - Prior to this update, iscsiadm did not accept host names or aliases as valid values for the --portal argument. As a consequence,the iscsiadm failed with the error message "iscsiadm: no records found!". This update matches the host name to the IP address returned during discovery, so this issue no longer occurs. - BZ#729355 - Prior to this update, the brcm_iscsiuio daemon did not rotate the brcm-iscsi.log file. As a consequence, the log file could grow excessively. This update adds a logrotate entry for the brcm-iscsi.log file. - BZ#759651 - Prior to this update,the iface net configuration parameters were not parsed on. As a consequence, the iface parameters could not be updated. This update modifies the idbm_recinfo_node routine to include the parsing of these parameters. Enhancements - BZ#715396 - This update upgrades uIP (micro IP) to the latest upstream version 0.7.0.6+ to make uIP compatible with the updated bnx2x driver. - BZ#723715 - This update adds leading-login support to reduce login storms during boot and allows for initiating multiple iSCSI sessions from a single iface record. 4.76. java-1.6.0-openjdk Security Fixes - CVE-2011-3556 - A flaw was found in the Java RMI (Remote Method Invocation) registry implementation. A remote RMI client could use this flaw to execute arbitrary code on the RMI server running the registry. - CVE-2011-3557 - A flaw was found in the Java RMI registry implementation. A remote RMI client could use this flaw to execute code on the RMI server with unrestricted privileges. - CVE-2011-3521 - A flaw was found in the IIOP (Internet Inter-Orb Protocol) deserialization code. An untrusted Java application or applet running in a sandbox could use this flaw to bypass sandbox restrictions by deserializing specially-crafted input. - CVE-2011-3544 - It was found that the Java ScriptingEngine did not properly restrict the privileges of sandboxed applications. An untrusted Java application or applet running in a sandbox could use this flaw to bypass sandbox restrictions. - CVE-2011-3548 - A flaw was found in the AWTKeyStroke implementation. An untrusted Java application or applet running in a sandbox could use this flaw to bypass sandbox restrictions. - CVE-2011-3551 -4 - An insufficient error checking flaw was found in the unpacker for JAR files in pack200 format. A specially-crafted JAR file could use this flaw to crash the Java Virtual Machine (JVM) or, possibly, execute arbitrary code with JVM privileges. - CVE-2011-3560 --3389 -. NoteTh. - CVE-2011-3547 - An information leak flaw was found in the InputStream.skip implementation. An untrusted Java application or applet could possibly use this flaw to obtain bytes skipped by other threads. - CVE-2011-3558 - A flaw was found in the Java HotSpot virtual machine. An untrusted Java application or applet could use this flaw to disclose portions of the VM memory, or cause it to crash. - CVE-2011-3553 - The Java API for XML Web Services (JAX-WS) implementation in OpenJDK was configured to include the stack trace in error messages sent to clients. A remote client could possibly use this flaw to obtain sensitive information. - CVE-2011-3552 - It was found that Java applications running with SecurityManager restrictions were allowed to use too many UDP sockets by default. If multiple instances of a malicious application were started at the same time, they could exhaust all available UDP sockets on the system. Bug Fix Enhancements 4.77. kdelibs Security Fix - CVE-2011-3365 - An input sanitization flaw was found in the KSSL (KDE SSL Wrapper) API. An attacker could supply a specially-crafted SSL certificate (for example, via a web page) to an application using KSSL, such as the Konqueror web browser, causing misleading information to be presented to the user, possibly tricking them into accepting the certificate as valid. 4.78. kernel Security Fix - CVE-2012-2100, Low -. -.Additionally, when attempting to transition priority groups on a busy FC device, the multipath layer retried immediately. If this was the only available path, a large number of retry operations, Important - A flawkernel257 guest can get preempted by the host, when a higher priority process needs to run. When a guest is not running for several timer interrupts in a row, ticks could be lost, resulting in the jiffies timer advancing slower than expected and timeouts taking longer than expected. To correct for the issue of lost ticks, do_timer_tsc_timekeeping() checks a reference clock source (kvm-clock when running as a KVM guest) to see if timer interrupts have been missed. If so, jiffies is incremented by the number of missed timer interrupts. Security Fixes - CVE-2011-4077, Important --4348,,25,, Important - Buffer overflow flaws in the Linux kernel's netlink-based wireless configuration interface implementation could allow a local user, who has the CAP_NET_ADMIN capability, to cause a denial of service or escalate their privileges on systems that have an active wireless interface. - CVE-2011-2519, Moderate - A flaw was found in the way the Linux kernel's Xen hypervisor implementation emulated the SAHF instruction. When using a fully-virtualized guest on a host that does not use hardware assisted paging (HAP), such as those running CPUs that do not have support for (or those that have it disabled) Intel Extended Page Tables (EPT) or AMD Virtualization (AMD-V) Rapid Virtualization Indexing (RVI), a privileged guest user could trigger this flaw to cause the hypervisor to crash. - CVE-2011. 4.79. kexec-tools Enhancement - BZ#772164 -. /sbin/kexecbinary and utilities that together form the user-space component of the kernel's kexec feature. The /sbin/kexecbinary facilitates a new kernel to boot using the kernel's kexecfeature either on a normal or a panic reboot. The kexecfastboot mechanism allows booting a Linux kernel from the context of an already running kernel. Security Fixes - CVE-2011-3588 - Kdump used the SSH(Secure Shell) StrictHostKeyChecking=nooption vmcoredumps. - CVE-2011-3589 - The mkdumprd utility created initrdfiles with world-readable permissions. A local user could possibly use this flaw to gain access to sensitive information, such as the private SSH key used to authenticate to a remote server when kdump was configured to dump to an SSH target. - CVE-2011-3590 - The mkdumprd utility included unneeded sensitive files (such as all files from the /root/.ssh/directory and the host's private SSH keys) in the resulting initrd. This could lead to an information leak when initrdfiles were previously created with world-readable permissions. Note:. Bug Fixes - BZ#678308 - On certain hardware, the kexec kernel incorrectly attempted to use a reserved memory range, and failed to boot with an error. This update adapts the underlying source code to determine the size of a backup region dynamically. As a result, kexecno longer attempts to use the reserved memory range, and boots as expected. - BZ#682359 - The mkdumprdutility lacked proper support for using VLAN devices over a bond interface. Consequently, the network could not be correctly set up in the kexec kernel and Kdump failed to capture a core dump. This update modifies mkdumprdso it now provides full support for configuring VLAN devices over a bond interface. Kdump now successfully dumps the vmcorefile to a remote machine in such a scenario. - BZ#759006 - A bug in the mkdumprdcaused Kdump to be unable to bring up a network interface card (NIC) if a NIC configuration file, such as /etc/sysconfig/network-scripts/ifcfg-eth0, did not contain a default gateway. When sending the vmcorefile over a network using the SSHor NFSprotocol, any attempt to bring the NIC up failed with the following error: ifup: option with empty value "gateway"Consequently, the connection to the remote machine could not be established and Kdump failed to dump the vmcorefile. With this update, mkdumprd performs a check whether the default gateway is specified and thus avoids adding an empty gateway into the /etc/kdump.conffile. The vmcorefile is now successfully dumped to a remote machine. - BZ#760844 - A bug in mkdumprdcaused Kdump to be unable to bring up a bridge device when its slave device was renamed in the kexec kernel. When sending the vmcorefile over a bridged network, any attempt to bring the bridge device up failed with a similar error: ifup: Ignoring unknown interface eth2Consequently, the connection to the remote machine could not be established and Kdump failed to dump the vmcorefile. This update modifies mkdumprdto search for the correct slave device names in NIC configuration files instead of using the old names. Kdump over a bridged network now works as expected. - BZ#761048 - Certain storage devices, such as HP Smart Array 5i controllers using the CCISSdriver, are known to be non-resettable in the kexec kernel. Therefore, when such a device was selected as a dump target, any attempt to dump a core file on it caused the kexec kernel to become unresponsive. This update modifies mkdumprdto check whether the target device is resettable. If the target device is non-resettable, then Kdump will not start and the kexec kernel no longer hangs under these circumstances. - BZ#761336 - The mkdumprdutility was unable to handle errors returned by the makedumpfilecommand if the command was piped with other commands. Therefore, when sending a core dump file over a network using the SSH protocol and makedumpfilefailed, the system rebooted immediately instead of dropping to the shell. This update allows mkdumprdto catch return codes of piped commands so that Kdump now fails right after a makedumpfilefailure and the system drops correctly to the shell. - BZ#765702 - The mkdumprdutility did not properly handle renaming of NIC devices in the kexec kernel. Therefore, when sending a core dump using a VLAN device over a bond interface, Kdump displayed various error messages related to VLAN device names. This update modifies mkdumprdso it now works with VLAN device names correctly. - BZ#781907 - The mkdumprdutility did not handle NFS unmount failures correctly. Therefore, when dumping a core over the NFSprotocol and a test attempt to unmount an NFS export failed, mkdumprdremoved all files from this NFS export. This update corrects mkdumprdso that it only removes empty NFS exports and no data loss occurs under these circumstances. Enhancements - BZ#668706 - The mkdumprdutility lacked support for the XFSfile system, and therefore Kdump failed to capture the vmcore dump file on XFS file systems. This update backports support for the XFSfile system from Red Hat Enterprise Linux 6 so Kdump now creates core dumps on XFSfile systems as expected. - BZ#690678 - This update adds a new option for the mkdumprdutility, blacklist. This option allows mkdumprdto prevent specified kernel modules from being loaded into the kexec kernel. - BZ#715531 - With this update, the mkdumprdutility supports static route configuration so that Kdump is now able to dump the vmcorefile to a remote machine over a network with static routing. - BZ#719384 - The mkdumprdutility has been modified to recognize and support iSCSIdevices so that iSCSI devices can now be specified as a dump target. - BZ#743217 - Kdump on Xen HVM guests is now enabled in Red Hat Enterprise Linux 5.8 as a Technology Preview. Performing a local dump to an emulated (IDE) disk using an Intel 64 Hypervisorwith an Intel CPU is the only supported implementation. Note that the dump target must be specified in the /etc/kdump.conffile. 4.80. krb5. Security Fix - CVE-2011-1526 -. Bug Fixes - BZ#701444 -#708516 -13500 -29067 -35363, BZ#736132 - Due to a regression, multi-line FTP macros terminated prematurely with a segmentation fault. This occurred because the previously-added patch failed to properly support multi-line macros. This update restores the support for multi-line macros and the problem no longer occurs. 4.81. ksh 4.82. kudzu 4.83. kvm Security Fixes --2011-46. Security Fixes - CVE-2011-4347 -.Red Hat would like to thank Sasha Levin for reporting this issue. Bug Fixes - BZ#700281 - Due to leaking file descriptors, if a Network Interface Card (NIC) was attached to or detached from a guest machine more than 250 times, KVM failed with the following error message: get_real_device: /sys/bus/pci/devices/0000:09:00.0/resource: Too many open filesThe problem has been fixed, and NIC can now be successfully attached to or detached from a guest machine more than 250 times. - BZ#701616 - When booting a guest with more than 8 PCI devices, QEMU exits with the following message: Too many assigned devicesHowever, when hot plugging PCI devices, the limitation of maximum number of devices assigned did not take effect, and the user could hot plug more than 8 PCI devices. QEMU has been modified to refuse to assign the ninth and any further hot plugged PCI devices with the aforementioned error message. - BZ#703335 - Previously, the mktime()function incorrectly modified an input parameter according to the time zone of the host machine. As a consequence, if the user did not use Network Time Protocol (NTP) and the time zone on the host machine was set to "America/New_York", time displayed on the clock of a guest machine was shifted one hour forward on the first reboot. With this update, mktime()is not used if UTC time is specified, and the correct time is displayed in the aforementioned scenario. - BZ#703446 - When the user booted a guest machine with a virtual Intel e1000 network interface card (NIC) and changed the maximum transmission unit (MTU) value, the guest machine could not be pinged from the host machine. With this update, multi-buffer packets are now supported, and the guest machine can be pinged successfully. - BZ#704081 - Previously, variables that represented RAM addresses were declared as the "long" data type. Large numbers (guests with large memory defined) could lead to overflow, and consequently cause screen corruption or cause the utility to terminate unexpectedly with a segmentation fault. With this update, variables that represent RAM addresses are declared as the "ram_addr_t" data type, and the aforementioned problems no longer occur on guests with large memory defined. - BZ#725629 - Previously, asynchronous I/O (aio) threads were created by threads of the virtual CPU. If the affinity of the virtual CPU was set, asynchronous I/O threads inherited this affinity. This could, in certain cases, lead to unexpectedly high latency of the virtual machines. With this update, asynchronous I/O threads are created by the main thread, and therefore inherit the main thread's affinity instead of the affinity of the virtual CPU. This ensures proper responses of virtual machines. - BZ#725876 - Previously, the kvm utility did not properly emulate the real-time clock (RTC) alarm interrupts (AIE) on host machines running Red Hat Enterprise Linux 5. Newer kernels use AIE interrupts exclusively for RTC functionality (including update interrupt, or UIE, mode). As a consequence, if the user ran a guest machine with a recent kernel on the Red Hat Enterprise Linux 5 host, various bugs could manifest. Among these, for example, the following message could appear when running the hwclock utility: select() to /dev/rtc to wait for clock tick timed outThis update adds support for the AIE mode emulation, so that UIE and AIE mode interrupts now work properly and applications run as expected. - BZ#751482 - During the boot process inside the qemu-kvm utility, the screen was resized to the height of 1. A mouse click at this point caused a division by zero (the SIGFPE signal was sent) when calculating the absolute position of the pointer from the pixel. As a consequence, qemu-kvm terminated with the "Floating point exception" error. With this update, mouse click coordinates are forced to return values from the middle of the screen, so that qemu-kvm no longer terminates in the described scenario. Important - Stop all KVM guest virtual machines. - Either reboot the hypervisor machine or, as the root user, remove (using "modprobe -r [module]") and reload (using "modprobe [module]") all of the following modules which are currently running (determined using "lsmod"): kvm, ksm, kvm-intel or kvm-amd. - Restart the KVM guest virtual machines. 4.84. less 4.85. lftp Bug Fixes - BZ#532099 -#570495 -#727435 -. 4.86. libcxgb3 4.87. libdhcp. 4.88. libexif Bug Fix - BZ#689614 -. 4.89. libhbaapi. 4.90. libmlx4 Bug Fix 4.91. libpng. 4.92. libusb. 4.93.. 4.94. libvorbis Security Fix - CVE-2012-0444 -. 4.95. libX11 Bug Fix - BZ#736175 - Previously, in the 64-bit mode, libX11 computed addresses using the 32-bit arithmetic. As a consequence, under heavy load, applications running in the X environment terminated unexpectedly. A patch has been provided to address this issue, and the crashes no longer occur in the described scenario. 4.96. libXcursor Bug Fix - BZ#688657 -. 4.97. libXfont Security Fix - CVE-2011-2895 -. 4.98. libxml2 Security Fixes - CVE-2011-3919 --0216 -. - CVE-2011-1944 - An integer overflow flaw, leading to a heap-based buffer overflow, was or, possibly, execute arbitrary code. - CVE-2010-4008, CVE-2011-2834 - Flaws were. - CVE-2011-3905 - An out-of-bounds memory read flaw was found in libxml2. A remote attacker could provide a specially-crafted XML file that, when opened in an application linked against libxml2, would cause the application to crash. Note Bug Fix - BZ#747865 - The libxml2 XML Schemas implementation allowed empty values for integer fields using, for example, the predefined schemas type, xsd:byte. This led to unwanted validation of documents that were invalid per these schemas. The implementation has been modified to forbid those empty integer values, and all documents containing such values will now fail the XML Schemas validation. 4.99. lsof 4.100. ltrace Bug Fix - BZ#733216 -. 4.101. lvm2 Bug Fix - BZ#773587 -. Bug Fix - BZ#732006 - When running the "lvconvert" command to convert a linear device to a mirror with stripes, the "lvconvert" command entered an infinite loop.The problem occurred if the number of needed extents was not divisible by the number of areas. This has been fixed: the allocation is now properly rejected if the number of extents is not divisible by the number of areas. Note Bug Fixes - BZ#597010 - LVM no longer scans multipath member devices (underlying paths for active multipath devices) and prefers top-level devices. This new default behavior can be switched off using the multipath_component_detectionoption in the /etc/lvm/lvm.conffile. - BZ#636991 - Prior to this update, placing mirror images on different physical devices with the lvcreate --alloc anywherecommand did not guarantee placement of data on different physical devices. With this update, the above command tries to allocate each mirror image to a separate device first before placing it on a device that is already used. - BZ#702065 - LVM mirrors can be operated in single-machine or cluster-aware mode. The cluster-aware mode requires a service daemon and an additional kernel module. HA-LVM makes use of the single-machine mode and should not require the extra daemon or module as long as the LVM mirrors are active exclusively. When a volume was being repaired or converted using the lvconvertcommand, the exclusive nature of the activation was lost and the cluster-aware mode was attempted. This failed due to the lack of the necessary daemon or kernel module. The following error message was logged: Unable to send cluster log request [DM_CLOG_CTR] to server: -3Consequently, mirrors managed by HA-LVM were unable to handle device failures. The commands that are used to repair or convert LVM mirrors have been fixed in order to preserve exclusive activation. This ensures that only the single-machine kernel representation is used and the extra daemon and kernel module necessary for cluster-aware operation, which may not be present, are not invoked. As a result the lvconvert command now works correctly in the scenario described. - BZ#706036 - Any I/O operations sent to an underlying device while it is suspended are queued and will not complete until the device is resumed. When running the pvmove utility on a Logical Volume (LV), pvmove sometimes became unresponsive trying to suspend a device when the underlying device was already suspended and had I/O operations pending. The code for pvmove has been improved and pvmove now temporally resumes all the underlying LVs before trying to suspend an LV in order to allow any I/O operations to complete. - BZ#707056 - The automatic snapshot resize process was reported to have finished twice by dmeventd, the event monitoring daemon for device-mapper devices. The code has been improved and the redundant information after a resize operation is no longer logged to system log. - BZ#707779 - When running the lvconvertcommand to convert a linear device to a mirror with stripes, the lvconvertcommand entered an infinite loop. The problem occurred if the number of needed extents was not divisible by the number of areas. This has been fixed: the allocation is now properly rejected if the number of extents is not divisible by the number of areas. - BZ#708444 - The automatic extension of volumes was reported by dmeventdwhen they were being written to and filling up even when the threshold was turned off by setting snapshot_autoextend_threshold = 100. This update removes this message as it is now considered redundant because the LVM command lvextendreports all relevant information. - BZ#711185 -#719760 - If an MD linear device had set rounding using the overloaded chunk size attribute, the pvcreatecommand logged the following erroneous error: /dev/md0 sysfs attr level not in expected format: linearThis update removes the unnecessary warning in pvcreatefor MD linear devices. - BZ#745522 - In some circumstances, when running lvm reporting commands and a physical volume was not specified, the following error message appeared: dm_report: left-aligned snprintf() failedThe memory allocation code has been improved and this error no longer appears. - BZ#749650 - When using striped mirrors, improper and overly-restrictive divisibility requirements for the extent count could cause a failure to create a striped mirror, even though it was possible. The condition that was checked took account of the mirror count and the stripe count, when the stripe count alone was satisfactory. This update corrects the code, and creating a striped mirror no longer fails in the scenario described. - BZ#755762 - Splitting an LV between two volume groups failed when the mirrored volumes had logs which were also mirrored. With this update, the vgsplitcommand is now able to split a volume group containing a mirror with mirrored logs. - BZ#769053 - If preallocated memory was too low, lvm2 issued the following error message: Internal error: Maps lock < unlockThe message has been changed to a message in the following format: Reserved memory (%ld) not enough: used %ld. Increase activation/reserved_memory?where %ldis replaced with the value of memory used. This provides better information about the source of the problem to the administrator. Preallocated memory can be changed in the lvm.conffile using the reserved_memoryoption. - BZ#773432 -. Enhancements - BZ#575967 - Some of the lvm2 operations were optimized to speed up activation and deactivation time if running over a large group of logical volumes. - BZ#523324 - The updated allocation policy now better handles allocation of new segments for mirrors with multiple segments (for example, mirrors which were repeatedly extended). - BZ#720971 - The ext4 file system will now be automatically resized after executing the lvextendcommand with the -roption. 4.102. lvm2-cluster Enhancements 4.103. man-pages Bug Fixes - BZ#699701 -#698691 - Previously, the rt_sigprocmask(2) manual page contained an erroneous description of the "oset" parameter. This update corrects this description. - BZ#640299 - Previously, the db(3) manual page was pointing to the non-existent dbopen(3) manual page. An error message, "fopen: No such file or directory", was displayed when the command "man db" was issued. With this update, the db(3) manual page is removed. - BZ#751877 -. Enhancements 4.104. man-pages-ja Bug Fix 4.105. man-pages-overrides Bug Fixes - BZ#510019 - Previously, the Japanese version of the rpm(8) manual page contained multiple typos. This update corrects those typos. - BZ#647113 - Previously, the manual page for the /usr/sbin/named_sdb binary was incorrectly named named-sdb(8). This update changes the name of the manual page to the correct named_sdb(8). - BZ#678326 - Previously, the ethtool(8) manual page incorrectly referenced the "--blink" option in SYNOPSIS. The option has been modified to the correct "--identify" option. - BZ#703440 - Previously, the dig(1) manual page did not document the exit codes of the dig tool. With this update, the exit codes are now described on the manual page. - BZ#766784 - Previously, the lsvio(8) manual page did not document the "-D" and "-v" options. With this update, the options are now described on the manual page. - BZ#731938 - Previously, multiple ecryptfs manual pages contained an incorrect link in the SEE ALSO section. With this update, the link is fixed. - BZ#769375 - Previously, the man-pages-overrides package incorrectly overrode the mount.cifs(8) manual page from both the samba3x-client and samba-client packages. With this update, only the mount.cifs(8) manual page from the samba-client package is overridden. - BZ#749319 - This update removes multiple manual pages from the original package. 4.106. mesa. 4.107. microcode_ctl 4.108. mkinitrd Bug Fix - BZ#753693 -. -. 4.109. mod_auth_kerb Bug Fix - BZ#783228 - circumstances. 4.110. mod_revocator. 4.111. mrtg Bug Fixes - BZ#436662 -. 4.112. mysql Security Fixes - CVE-2012-0075, CVE-2012-0087, CVE-2012-0101, CVE-2012-0102, CVE-2012-0114, CVE-2012-0484, CVE-2012-0490 - This update fixes several vulnerabilities in the MySQL database server. Information about these flaws can be found on the Oracle Critical Patch Update Advisory page: 4.113. mysql-connector-odbc -. 4.114. MySQL-python 4.115. net-snmp. 4.116. net-tools Bug Fixes - BZ#319981 - Previously, the "hostname -s" command returned the "hostname: Unknown host" error message on a host if a host name was not resolved in DNS (Domain Name System). The utility has been modified and now always returns a short host name instead of the error message. - BZ#531980 - Previously, the mii-tool command displayed an I/O error on a network interface if the Intel e1000e driver was used. With this update, the tool is modified to only check generic Media Independent Interface (MII) registers defined in linux/mii.h. Now, the error message is no longer displayed. - BZ#622734 - Previously, net-tools incorrectly used 32-bit integers for 64-bit architectures. As a result, certain entries in the "lpExt" section were displayed with negative values when running the "netstat -s" command. With this update, integers on 64-bit architectures are handled properly and the "netstat -s" command now produces the correct output. - BZ#668047 - Prior to this update, the netstat utility could terminate unexpectedly with a stack smashing message when running the "netstat -nr -A inet6" command and /proc/net/ipv6_route contained lines of different length. With this update, the code that reads the content of /proc/net/ipv6_route is fixed and netstat no longer displays lpExt entries with negative values. - BZ#699698 - Prior to this update, the route(8) manual page did not clearly describe that the "mss" option can set the maximum transmission unit (MTU) value. With this update, the route(8) manual page now includes a detailed description of the "mss" option. - BZ#707427 - Prior to this update, the "netstat -p" command incorrectly displayed a number instead of the program name in the PID/Program name column. With this update, the code is modified and the command now correctly displays the program name. - BZ#707460 - Prior to this update, several command line options were missing from the plipconfig(8) manual page. This update modifies the SYNOPSIS section and the usage output of the plipconfig command to add these missing options. - BZ#732983 - The netstat utility truncated IPv6 (Internet Protocol version 6) UDP sockets even if the "--notrim" or "-T" option was specified. With this update, complete IPv6 addresses are displayed for UDP sockets when using netstat with one of these options. 4.117. netpbm Security Fixes - CVE-2011-4516, CVE-2011-4517 --2009-4274 -.. 4.118. nfs-utils Security Fix - CVE-2011-1749 - It was found that the mount.nfs tool did not handle certain errors correctly when updating the mtab (mounted file systems table) file. A local attacker could use this flaw to corrupt the mtab file. Bug Fixes - BZ#529588 -. - BZ#593097 - When a user's Kerberos ticket expired, the "sh rpc.gssd" messages flooded the /var/log/messages file. With this update, the excessive logging has been suppressed. - BZ#600497 -. - BZ#710020 -. - BZ#712438 - The "nfsstat -m" command did not display NFSv4 mounts. With this update, the underlying code has been modified and the command returns the list of all mounts, including any NFSv4 mounts, as expected. - BZ#715523 - Previously, the nfs manual pages described the fsc mount option; however, this option is not supported. This update removes the option description from the manual pages. - BZ#729603 -. - BZ#736677 -. Enhancement 4.119. nfs-utils-lib Enhancement 4.120. nfs4-acl-tools Bug Fix - BZ#693422 - Due to a regression introduced in Red Hat Enterprise Linux 5.5, if the format of the input ACL file was incorrect, the "nfs4_setfacl" command failed with the following unexpected message:*** glibc detected *** nfs4_setfacl: double free or corruption (out)This update applies a patch that corrects the memory handling process and the nfs4_setfacl command now fails with a useful error message if the input file syntax is invalid. 4.121. nss Security Fix - BZ#751366 -. NoteDigicert Sdn. Bhd. is not the same company as found at digicert.com. NoteThis fix only applies to applications using the NSS Builtin Object Token. It does not render the certificates untrusted for applications that use the NSS library, but do not use the NSS Builtin Object Token. Bug Fix - BZ#743508 -. Security Fix - BZ#734316 - It was found that a Certificate Authority (CA) issued fraudulent HTTPS certificates. This update renders any HTTPS certificates signed by that CA as untrusted. This covers all uses of the certificates, including SSL, S/MIME, and code signing. NoteThis fix only applies to applications using the NSS Builtin Object Token. It does not render the certificates untrusted for applications that use the NSS library, but do not use the NSS Builtin Object Token. Bug Fixes - BZ#348761 - Prior to this update, the selinux policy for mod_nss did not allow for correct handling of access vector caches (AVC). As a consequence, AVC could fail when running NSS. This update modifies the selinux policy so that AVC is handled as expected. - BZ#704595 - Prior to this update, the crmf library used a maximum length of 2048 bits for wrapped private keys. As a consequence, private keys exceeding the maximum lengths failed. With this update, the maximum key length is now identical with the the maximum modulus length. - BZ#713373 - Prior to this update, certain file descriptors were not closed. As a consequence, a file descriptor leak resulted upon continued reloading of the httpd service. This update modifies the underlying code and the descriptors are now correctly closed. 4.122. nss_ldap Bug Fix - BZ#743193 - Previously, a fixed size buffer to store the LDAP configuration could exceed its size. As a consequence, nss_ldap failed when it was used with certain large configurations, especially on 64-bit architectures where pointers in internal data structures occupy twice as much space in the buffer as on 32-bit architectures. This caused situations where a certain LDAP configuration worked on 32-bit architecture but not on 64-bit architecture. With this update, the size of the buffer has been increased to 64 KB, and nss_ldap now works correctly with LDAP configurations that do not exceed the size of 64 KB. Bug Fixes - BZ#593242 -#696707 -#705841 -. Enhancements 4.123. ntp. 4.124. oddjob Bug Fix - BZ#628683 -. 4.125. openais Bug Fixes - BZ#752443 - When stopping the cman service on a cluster node shutdown, the groupd daemon often exited with the "groupd: cpg_leave error retrying" error message, causing OpenAIS to become unresponsive. As a consequence, the cluster node was not shut down correctly. With this update, the underlying code has been modified to stop cman correctly. Cluster nodes can now be shut down as expected. - BZ#754717 - Under certain circumstances, if the system clock was changed on a cluster node, cman could terminate unexpectedly on all cluster nodes, resulting in nodes not being fenced. As a consequence, the cluster was not shut down gracefully and had to be rebooted manually. With this update, the underlying code has been modified to handle significant time changes. The cman service no longer terminates and the cluster no longer fails. Bug Fixes - BZ#731460 - Previously, when OpenAIS was used in a lossy network, and a large number of configuration changes occurred, OpenAIS sometimes terminated unexpectedly. To solve this problem, the underlying source code has been modified, and OpenAIS no longer crashes in the scenario described. - BZ#739083 -086 - Under certain circumstances, the previous version of OpenAIS sometimes used an incorrect sort message queue when the "memb_join" message was sent during recovery. With this update, this error has been fixed, and OpenAIS now uses a correct sort message queue in this scenario. Bug Fix Bug Fixes - BZ#708335 - Previously, the length of the array cpg_exec_service[]/cpg_exec_engine[] in OpenAIS and corosync differed. Consequently, OpenAIS failed if corosync ran on the same network. This update modifies the length of this array in OpenAIS. Now, OpenAIS and corosync successfully run on the same network. - BZ#718773 - Previously, the receive buffers could overflow under heavy traffic. Consequently, packets could be lost and retransmit list error messages appeared in the log files. Now, incoming messages are processed more frequently, and the retransmit list error messages no longer appear. - BZ#726142 - Previously, the OpenAIS service could, under certain circumstances, encounter a deadlock when starting or stopping the process. This update modifies the underlying source code to prevent such a deadlock. Deadlock situations no longer happen during a rapid start or stop process. - BZ#729081 - Previously, OpenAIS could, under certain circumstances, terminate unexpectedly when OpenAIS was used in a network losing packets and a large number of configuration changes occurred. This update modifies the underlying source code, and OpenAIS no longer terminates under these circumstances. - BZ#734865 - Previously, OpenAIS could, under certain circumstances, use an incorrect sort message queue when the "memb_join" message was sent during recovery. Consequently, OpenAIS could join all nodes. Now, OpenAIS uses the correct sort message queue if memb_join message is sent during recovery. - BZ#737100 - Previously, openais_response_send could, under certain circumstances, change the value of req->ics_channel_handle. Consequently, OpenAIS terminated unexpectedly when using the subscribe function of the eventing (EVT) service. This update saves the handle outside the message. OpenAIS no longer terminates if an application is using the subscribe function of the EVT service. - BZ#738468 - Previously, cman could, under certain circumstances, terminate unexpectedly on all cluster nodes and nodes were not fenced if the system clock was changed on a cluster node. Consequently, the cluster was not shut down gracefully and had to be rebooted manually. Now, the underlying code has been modified to handle significant time changes. The cman service no longer terminates and the cluster no longer fails. - BZ#746807 - Previously, the groupd daemon often exited with the "groupd: cpg_leave error retrying" error message, causing OpenAIS to become unresponsive when stopping the cman service on a cluster node shutdown. Consequently, the cluster node was not shut down correctly. Now, the underlying code has been modified to stop cman correctly. Cluster nodes can be shut down as expected. - BZ#752952 - Previously, totemip_parse used the getaddrinfo function without an associated freeaddrinfo call. Consequently, a small amount of memory leaked when calling OpenAIS. This update adds a call to freeaddrinfo. OpenAIS no longer leaks memory in totemip module. Enhancement 4.126. openCryptoki Bug Fixes - BZ#538879 - Prior to this update, the process to unwrap an Advanced Encryption Standard (AES) key could, under certain circumstances, fail after a hardware cryptographic token was initialized. As a result, openCryptoki returned the error "CKR_TEMPLATE_INCOMPLETE". This update modifies the AES key unwrapping process so that it no longer fails. - BZ#539168 - Prior to this update, the message authentication code (MAC) could, under certain circumstances, fail to be verified when using the PKCS#11 API for the acceleration of cryptographic instructions and the error "411 = MAC did not verify." was retunred. This update modifies the underlying code so that the MAC is now computed successfully after being offloaded to the CPACF. - BZ#541028 - Prior to this update, openCryptoki did not correctly recognize whether secure-key crypto support was installed when the pkcs11_startup and pkcs_slot scripts were running. As a consequence, the Common Cryptographic Architecture (CCA) token did not correctly work. This update modifies the pkcs11_startup and pkcs_slot scripts to improve the secure-key crypto support check. Now, the CCA token works as expected. - BZ#612274 - Prior to this update, OpenCryptoki used linked lists to track objects and sessions in memory, performing an exhaustive search in practically every PKCS#11 call. As a consequence, the overall performance of cryptographic operations degraded exponentially with the number of objects per token or open sessions per process. This update modifies the underlying source code so that the overall performance remains constant. 4.127. OpenIPMI Bug Fix - BZ#722462 - When IPMI-enabled devices reported SDR (sensor data record) records under a different owner than the BMC (Baseboard Management Controller), the IPMItool utility tried to retrieve these SDR records from the IPMI bus instead of the BMC bus. Due to timeout setting for the SDR read attempt, serious performance issues occurred and no sensor data was shown. This issue has been fixed and IPMItool now correctly reads these SDR records from the BMC and shows the correct sensor data on these platforms. 4.128. openldap Bug Fix - BZ#750538 -. Bug Fixes - BZ#734144 -145 -. Enhancement - BZ#733659 -. Bug Fixes - BZ#741184 - When an OpenLDAP server was running with the LDAP Sync replication engine ( syncrepl) enabled and a large amount of data was replicated, the memory was used extensively. Consequently, the standalone LDAP daemon ( slapd) was sometimes not able to allocate enough free memory using its default memory allocation mechanism and slapdfell back on the secondary memory allocation mechanism without freeing the memory properly, causing memory leaks. With this update, the slapddaemon frees the memory correctly in such a scenario, and memory leaks no longer occur. - BZ#591419 - Due to an error introduced in one of the previous updates, initializing a connection to a slapdserver may have caused the CPU usage to reach 100% and the server to become unresponsive for about three seconds. With this update, an existing upstream patch has been applied to target this issue, and the OpenLDAP suite now works as expected. - BZ#641953 - Previously, multiple concurrent connections to an OpenLDAP server could cause the slapdservice to terminate unexpectedly with an assertion error. This update applies an upstream patch that adds mutexes to protect multiple threads from accessing a structure with a connection, and the slapd service no longer crashes. - BZ#655133 - The libldaplibrary did not provide the ldap_init_fd()function, even though certain utilities such as cURLrely on it and could not work properly as a result. This update applies a backported upstream patch that implements this API function, and these tools now work as expected. - BZ#620621 - When the openldap-servers package was installed with the syncreplutility configured, adding or removing data from a master server occasionally caused the slapdserver to terminate unexpectedly. An upstream patch has been provided and the crashes no longer occur in the described scenario. - BZ#665951 - When running the slapdservice with the ppolicyoverlay enabled, an attempt to delete the userPasswordattribute could cause the service to terminate unexpectedly, leaving the database in a corrupted state. With this update, an upstream patch has been applied to address this issue, and deleting the userPasswordattribute no longer causes the slapdservice to crash. - BZ#684630 -#732381 - Previously, the openldap package compilation log file contained warning messages returned by strict-aliasing rules. These warnings indicated that unexpected runtime behavior could occur. With this update, the -fno-strict-aliasingoption is passed to the compiler to avoid optimizations that can produce invalid code, and no warning messages are now returned during package compilation. - BZ#609722 - When the openldap client was configured with the TLS_CACERTDIRoption, some of the certificate files were not accessible. Consequently, openldap could not establish TLS (Transport Layer Security) connections. An upstream patch has been provided to address this issue and openldap now establishes TLS connections to the server, even if some certificates specified in TLS_CACERTDIRare inaccessible. - BZ#738768 - Previously, the ldapinit script was incorrectly marked as a configuration file. When manual modifications had been made to it while the openldap-servers package was installed, and when the package had been updated, the init script was not overwritten as part of the upgrade. With this update, the openldap spec file has been updated to reflect that the ldapinit script is not a configuration file, and openldap-servers now overwrites the init script properly in the described scenario. - BZ#604092 - With the openldap-servers package was installed, when the server was shut down incorrectly and the database needed recovery, the openldap init script failed to start the server again. With this update, a new option has been added to the tool which checks openldap server configuration. The new option skips the database checks, and the openldap server now starts properly in the described scenario. - BZ#699652 - The ldap.conf(5)manual page has been updated to emphasize that to specify Certificate Authorities, the TLS_CACERToption is the preferred one to the TLS_CACERTDIRoption. - BZ#563148 - When the migrate_all_offline.shscript was used to migrate duplicate accounts, the migration process terminated. With this update, the script no longer interrupts the process, when certain errors occur. Local duplicate accounts no longer cause the migration process to interrupt. Enhancement - BZ#733435 - Previously, when a connection to an LDAP server was created by specifying search root DN (distinguished name) instead of the server hostname, the SRV records in DNS were requested and a list of LDAP server hostnames was generated. The servers were then queried in the order, in which the DNS server returned them but the priority and weight of the records were ignored. This update adds support for priority/weight of the DNS SRV records, and the servers are now queried according to their priority/weight, as required by RFC 2782. 4.129. openmotif Bug Fixes - BZ#583977 -#584287 -#644824 -#684210 -#695650 -. 4.130. openscap 4.131. openssh Bug Fix - BZ#730652 - When Federal Information Processing Standards (FIPS) mode was enabled on a system, key-based authentication was always unsuccessful. This was caused by the newly introduced pubkey_key_verify() verification function, which did not take into consideration the fact that it was running in a FIPS environment. With this update, the pubkey_key_verify() function has been modified to respect FIPS, and authentication using an RSA key is now successful without any issues when FIPS mode is enabled. Bug Fixes - BZ#642935 - Previously, the SSH daemon (sshd) attempted to bind port 22 to both Internet Protocol version 6 (IPv6) and Internet Protocol version 4 (IPv4). As a consequence, SSH targeted IPv4 and failed to bind after the second attempt. This update uses the IPV6_V6ONLY flag to allow SSH to listen to both on IPv4 and IPv6. (BZ#640857) * Previously, SELinux denied /sbin/setfiles access to a leaked SSH tcp_socket file descriptor when requested by the restorecon command. This update modifies sshd to set the file descriptors flag FD_CLOEXEC on the socket file descriptor. Now, sshd no longer leaks any descriptor. - BZ#674747 - Previously, the pubkey_key_verify() function did not detect if it was running in a Federal Information Processing Standards (FIPS) environment. As a consequence, key-based authentication failed when the FIPS mode was enabled on a system. With this update, the pubkey_key_verify() function has been modified to respect FIPS. Now, authentication using an RSA key is successful when the FIPS mode is enabled. - BZ#681291 - By default, OpenSSH used the /dev/urandom file to reseed the OpenSSL random number generator. Prior to this update, this random number generator was reseeded only once when the SSH daemon service, the SSH client, or an SSH-aware utility was started. To guarantee sufficient entropy, this update modifies the underlying source code to reseed the OpenSSL random number generator periodically. Additionally, the "SSH_USE_STRONG_RNG" environment variable has been added to allow users to specify /dev/random as the random number generator. - BZ#689406 - Previously, the SELinux policy did not allow to execute the passwd command from sshd directly. With this update, sshd resets the default policy behavior before executing the passwd command. - BZ#706315 - Previously, the lastlog command did not correctly report the last login log when processing users with User IDs (UIDs) greater than 2147483647. This update modifies the underlying code so that lastlog now works for all users. - BZ#710229 - Previously, SSH did not send or accept the LANGUAGE environment variable. This update adds the SendEnv LANGUAGE option to the SSH configuration file and the AcceptEnv option to the sshd configuration file. Now, the environment variable LANGUAGE is send and received. - BZ#731925 - Previously, running the mdoc option "groff -m" on OpenSSH manual pages caused formatting errors. This update modifies the manual page formatting. Now, the mdoc option "groff -m" runs as expected. - BZ#731930 - Prior to this update, the ssh-copy-id script wrongly copied the identity.pub key instead of the id_rsa.pub key. This update modifies the underlying code so that ssh-copy-id now copies by default the id_rsa.pub key. - BZ#750725 - Previously, SSH clients could, under certain circumstances, wait indefinitely at atomicio() in ssh_exchange_identification() when the SSH server stopped responding. This update uses the ConnectTimeout parameter to stop SSH clients from waiting after timeout. Enhancement 4.132. openssl. 4.133. openswan Security Fix - CVE-2011-4073 - A. Bug Fixes - BZ#549811 - When an NSS database is created with a password (either in FIPS or non-FIPS mode), access to a private key (associated with a certificate or a raw public key) requires authentication. At authentication time, openswan passes the database password to NSS. Previously, when this happened, openswan also logged the password to /var/log/secure. The password could also be seen by running "ipsec barf". With this update, openswan still passes the database password at authentication time but no longer logs it in any fashion. - BZ#609343 - The pluto key management daemon terminated unexpectedly with a segmentation fault when removing a logical IP interface. With this update the code has been improved, pluto now withdraws a connection to a dead logical interface cleanly and no longer crashes in the scenario described. - BZ#652733 - no longer delayed. Enhancements - BZ#524191 - With this update, the openswan packages now include support for message digest algorithm HMAC-SHA1-96 as per RFC 2404. - BZ#591104 - RFC 5114, Additional Diffie-Hellman Groups for Use with IETF Standards, adds eight Diffie-Hellman groups (three prime modulus groups and five elliptic curve groups) to the extant 21 groups set out in previous RFCs (e.g. RFCs 2409, 3526 and 4492) for use with IKE, TLS, SSH and so on.This update implements groups 22, 23 and 24: a 1024-bit MODular exPonential (MODP) Group with 160-bit Prime Order Subgroup; a 2048-bit MODP Group with 224-bit Prime Order Subgroup; and a 2048-bit MODP Group with 256-bit Prime Order Subgroup respectively. NoteImplementation of group 24 (a 2048-bit MODP Group with 256-bit Prime Order Subgroup) is required for US National Institute of Standards and Technology (NIST) IPv6 compliance and ongoing FIPS-140 certification. 4.134. oprofile. 4.135. pam_krb5 Bug Fix - BZ#715073 - Previously, if a system was configured to perform Kerberos authentication using PKINIT, users who attempted to change their passwords using the "passwd" command or other PAM-aware application, while a smart card was inserted, would be erroneously prompted for the smart card PIN. With this update, the plugin returns an error to any requests for non-password information while attempting to obtain password-changing credentials. As a result, the unnecessary request for the smart card PIN is no longer made to the user in the scenario described. 4.136. pam_pkcs11 Bug Fix - BZ#623640 - The commands "pklogin_finder" and "pkcs11_inspect", both call "pk_configure" with their entire "argv" array. This includes the command name, which is not recognized as a valid option. Consequently, when running pklogin_finder or pkcs11_inspect, unnecessary error messages were written to the system log in the following format:pkcs11_inspect: argument /usr/bin/pkcs11_inspect is not supported by this module This update applies a patch that improves the code, and the unnecessary error messages are no longer generated. 4.137. pango Security Fix - CVE-2011-3193 -. 4.138. parted. 4.139. pciutils Bug Fix Enhancements 4.140. pdksh Bug Fix - 634666 - Prior to this update, when a SIGINT or SIGTERM was sent to a pdksh process, the signal was propagated to the entire process group. As a consequence sending SIGTERM to a process killed other processes even if the first process was not the parent. With this update the SIGINT and SIGTERM signals are correctly propagated and unexpected termination of processes no longer occurs. 4.141. perl Security Fixes - CVE-2011-3597 --2010-2761 --4410 -. Bug Fixes - BZ#548249 - Due to an error in the threads module, memory was leaked each time a thread was detached. Over time, this could cause long-running threaded Perl programs to consume a significant amount of memory. With this update, a patch has been applied to ensure the allocated memory is properly freed when a thread is detached, and using threads in Perl applications no longer causes memory leaks. - BZ#523827 - If the "-default" parameter contained a plus sign ("+"), the CGI::popup_menu() method failed to generate valid HTML code and the closing tag of a paired tag was sometimes missing. The regular expression that contributes the HTML code in such scenarios has been fixed and the closing tag is now always present. - BZ#537777 - Previously, joining or undefining a thread variable in a Perl script resulted in the following error message: "Attempt to free unreferenced scalar: SV 0x7b7dcb0, Perl interpreter: 0x7b4cfb0 during global destruction." A backported upstream patch has been provided and the internal error is no longer returned in the described scenario. - BZ#590644 - Previously, the CGI::popup_menu() method generated invalid HTML code; a space character was sometimes missing between two attributes of a tag. With this update, the regular expression responsible for generating such code has been fixed and the space characters are now properly generated in the described scenario. - BZ#675863 - When threads were being rapidly created and detached on a multi-processor system with Perl, a variety of unexpected terminations occurred as a result. With this update, the threads module has been updated to version 1.79 and the crashes no longer occur. - BZ#593752 - Previously, the NDBM_File module was missing in Perl packages and Perl could not provide support for NDBM files. With this update, NDBM_File has been added back to the Perl RPM packages. - BZ#676050 - Previously, string evaluation in Perl threads sometimes resulted in an unexpected termination of the process. To partially fix this bug, handling of these strings has been moved to non-threaded variables. The update of the threads module to version 1.79 also contributed to the fix of this bug. Now, the crashes no longer occur in the described scenario. - BZ#621542 - Due to a missing definition in Unicode table 4.0, Perl did not recognize the small letter Palochka (U+04cf). With this update, the Unicode table has been updated to version 5.0.1 and Palochka letters are now supported in Perl. - BZ#625746 - When two nested loops were using the same iterator, the interpreter tried to double-free the iterator, resulting in a warning. Moreover, referring such an iterator caused the "Attempt to free unreferenced scalar" run-time error message to be returned. A backported patch from Perl 5.10.1 has been applied to handle shared iterators properly and no warnings or error messages are now returned in the described scenario. - BZ#676547 - Previously, the value of a variable used for string evaluation was too small. Consequently, a large number of string evaluations made the interpreter return syntax error messages. Now, the variable for storing strings is using a bigger value and the error messages are no longer returned in the described scenario. 4.142. perl-XML-SAX Bug Fixes - BZ#641735 -#744200 -. 4.143. php Security Fix - CVE-2012-0830 -. Bug Fixes - BZ#548142 - PNG files in certain formats, which were loaded with the "gd" extension, were displayed incorrectly. This update adds support for such files and the files are now loaded correctly. - BZ#552436 - Connecting to an Internet Message Access Protocol (IMAP) service could fail with the following error message:PHP Warning: imap_open(): Couldn't open streamThis happened if the server advertised support for Kerberos authentication, but the client was not configured to use Kerberos. This update adds the DISABLE_AUTHENTICATOR option for the imap_open() function, which allows to disable a specific authentication method. - BZ#594813 - A PHP script that is using the#607453 - Previously, the PHP mktime() function and some daytime functions were limited to 32-bit time stamps on 64-bit platforms due to a build configuration error. This update fixes the error and allows the use of 64-bit time stamps on 64-bit platforms. - BZ#611662 - If a prepared statement was unset when using PostgreSQL through the PHP Data Objects (PDO) interface, the current transaction was aborted. This caused subsequent SQL queries in the transaction to fail. With this update, the prepared statement is unset correctly and subsequent queries work as expected. - BZ#695251 - If a negative array index value was sent to the var_export() function, the function returned an unsigned index ID. With this update, the function has been modified to process negative array index values correctly. Enhancement 4.144. php53 Security Fix - CVE-2012-0830 - It was discovered that the fix for CVE-2011-4885 (released via RHSA-2012:0019 for php53 packages in Red Hat Enterprise Linux 5) introduced an uninitialized memory use flaw. A remote attacker could send a specially- crafted HTTP request to cause the PHP interpreter to crash or, possibly, execute arbitrary code. - CVE-2011-2483 -. NoteDue. - CVE-2011-0708 --1466 - An integer overflow flaw was found in the PHP calendar extension. A remote attacker able to make a PHP script call SdnToJulian() with a large value could cause the PHP interpreter to crash. - CVE-2011-1468 - Multiple memory leak flaws were found in the PHP OpenSSL extension. A remote attacker able to make a PHP script use openssl_encrypt() or openssl_decrypt() repeatedly could cause the PHP interpreter to use an excessive amount of memory. - CVE-2011-1148 - A use-after-free flaw was found in the PHP substr_replace() function. If a PHP script used the same variable as multiple function arguments, a remote attacker could possibly use this to crash the PHP interpreter or, possibly, execute arbitrary code. - CVE-2011-1469 -71 - An integer signedness issue was found in the PHP zip extension. An attacker could use a specially-crafted ZIP archive to cause the PHP interpreter to use an excessive amount of CPU time until the script execution time limit is reached. - CVE-2011-1938 --2202 -. Bug Fixes - BZ#700724 - If a negative array index value was sent to the var_export() function, the function returned an unsigned index ID. With this update, the function has been modified to process negative array index values correctly. - BZ#717158 - Previously, subpackages of the php53 package did not contain the "Provides" definition corresponding to the definitions of the php package. This update adds the missing "Provides" definitions for these subpackages. 4.145. piranha 4.146. poppler. 4.147. postgresql Bug Fix - BZ#728828 -. 4.148. postgresql84 4.149. ppc64-utils. 4.150. procinfo Bug Fix - BZ#769857 -. 4.151. procps. 4.152. python Bug Fix - BZ#734005 -. Bug Fixes - BZ#732954 -. - BZ#708292 - Prior to this update, python did not include an alias for "en_in" to convert "en_IN" into "en_IN.ISO8859-1". Consequently, the yum grouplist command would not work when the console LANG variable was set as follows: LANG=en_IN. With this update, an alias has been added in the locale.py file and yum grouplist now functions as expected with LANG=en_IN. 4.153. python-rhsm. 4.154. python-virtinst Bug Fixes - BZ#704396 - Running the "virt-install" command with the "--noapic" or "--noacpi" option overrides the operating system type so that it disables the Advanced Programmable Interrupt Controller (APIC) or Advanced Configuration and Power Interface (ACPI) setting on a fully virtualized guest. Previously, executing the command with the option mentioned did not take effect when installing a guest. A patch has been applied to address this issue, and running the "virt-install" command with the "--noapic" or "--noacpi" option specified works as expected. - BZ#704417 - When cloning a KVM guest by using the virt-clone utility, the new MAC address was generated with an incorrect prefix. This was becasue the prefix allocated to Xen was used instead of the prefix allocated to QEMU. An upstream patch has been applied to address this issue, and the correct MAC prefix is now generated when cloning KVM guests. - BZ#706398 - Previously, the maxnode variables returned for virtio, scsi or paravirtualized disks were hard-coded to number 16. As a consequence, the virt-manager utility failed to add more than 16 paravirtualized disks, and displayed the following message:no more space for disks of type xvdThis update increases the number to 1024. Users can now add more than 16 new storage devices successfully, without errors. 4.155. PyXML Bug Fixes - BZ#521307 - Prior to this update, PyXML contained the shebang line, "#!/usr/bin/env python". This made it difficult to install alternative versions of Python on the system. With this update, the shebang lines in Python executables have been changed to, "#!/usr/bin/python", to ensure the Python interpreter installed on the system is used. - BZ#472009 -. 4.156. qt4 Security Fixes - CVE-2007-0242 --2011-3193 -. 4.157. rdesktop Bug Fixes - BZ#581010 - When using rdesktop to connect to a Windows Server 2008 R2 machine, the server generated a cursor-related command that rdesktop did not support. As a consequence, the mouse pointer was all black. This update applies an upstream patch to fix this issue and the mouse pointer is now white in color with a black border when connecting to a Windows Server 2008 R2 machine. - BZ#572287 - When connecting to a Windows Server 2008 R2 machine, receiving a redirect could cause the rdesktop client to terminate unexpectedly with a segmentation fault. This update applies a patch that fixes this error, and receiving a redirect from a Windows Server 2008 R2 machine no longer causes rdesktop to crash. 4.158. redhat-release 4.159. redhat-release-notes 4.160. rgmanager Bug Fix - BZ#759542 - Previously, rgmanager inappropriately.. 4.161. rhn-client-tools Bug Fixes - BZ#595837, BZ#751760 - Prior to this update, the libraries provided by the rhn-client-tools packages may have occasionally failed with a traceback when the network connection was reset by peer. With this update, the underlying source code has been modified to display an appropriate error message in this situation. - BZ#706148 - When more then one server was enabled in the /etc/sysconfig/rhn/up2date configuration file and the first server was not available, a yum command such as "yum update" did not attempt to connect to the second server and kept connecting to the first one. This update applies a patch that corrects this error, and when the first server is unavailable, yum now attempts to connect to the second server as expected. - BZ#720966 - The rhn-channel utility allows users to subscribe or unsubscribe from a channel on the command line. Previously, an attempt to provide both username and password interactively caused the authentication to fail with the "Invalid username/password combination" error message. This happened, because rhn-channel did not remove the newline character from the username. With this update, this error has been corrected, and the rhn-channel utility no longer fails to authenticate the user when correct credentials are entered interactively. - BZ#729467 - When a user runs the rhn_register utility on a system that is already registered, the utility displays a warning message that the system is already set up for software updates. This update rephrases this warning message for clarity. - BZ#744111 - When a user registered a system with RHN Classic immediately after its provisioning, the Subscription Manager incorrectly reported that the system is non-compliant. Consequent to this, the user had to log out and then log in to the system to work around this problem. With this update, when a user registers a system with RHN Classic, the Red Hat Network Client Tools now send a message to the Subscription Manager over D-Bus, resolving this issue. - BZ#773463 - When using the firstboot application to register a system, "RHN Classic Mode" is now selected by default on the "Choose Server" screen. - BZ#681132 - The underlying implementation of exception handling has been corrected. 4.162. rhnlib Bug Fix - BZ#665026 - Prior to this update, programs that used rhnlib were unable to connect to RHN or RHN Satellite using an IPv6 address. With this update, the underlying source code has been modified to correct this error, and rhnlib-based applications are now able to connect to RHN or RHN Satellite without any problems with IPv6 address resolution. 4.163. rhpl. 4.164. rng-utils Enhancement 4.165. rpm. 4.166. rsh Bug Fix 4.167. rsync Bug Fix - BZ#726060 -. 4.168. rsyslog Bug Fixes - BZ#592039, BZ#582288 - Previously, rklogd, the daemon that provides kernel logging, was replaced with a loadable module. However, the functionality was disabled in the configuration. Consequently, rsyslog did not log any kernel messages. With this update, the /etc/rsyslog.conf configuration file has been corrected to include the "$ModLoad imklog" directive and the kernel messages are now logged as expected. - BZ#674450 - The previous version of rsyslog introduced a patch, which fixed unexpected termination that occurred when a large number of clients was sending their logs to rsyslog. However, the patch was not applied due to the outdated Autoconf package in the build environment. With this update, the package is no longer needed during the build process and the patch is applied successfully. - BZ#583621 - The previous rsyslog release introduced a new format of the message time stamps. However, some utilities, such as logwatch, were unable to parse such message time stamps properly. This update adds the "$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat" directive to the /etc/rsyslog.conf configuration file so that the old format is used by default and the respective utilities now work correctly. - BZ#546645 - Previously, some rsyslog modules were stored in the /usr/lib{,64} directory tree. Consequently, rsyslog could fail to start if the /usr/ directory resided on a different file system and the file system was unavailable during the daemon startup. With this update, the module directory has been relocated to the /lib{,64}/ directory and the modules are always accessible to rsyslog. - BZ#601711 - The omsnmp module was missing in the rsyslog package. Consequently, sending of messages with Simple Network Management Protocol (SNMP) could not be used. This update adds the omsnmp module to the package and the SNMP messages mechanism works as expected. - BZ#746179 - Wrong data types were used to hold some configuration values, which caused rsyslog to ignore the values. This update changes the data types and the configuration is now processed as expected. - BZ#726525 - The retry limit was not checked correctly and suspended actions could fail to resume. This update fixes the underlying code and suspended actions resume as expected. - BZ#654379 - The rsyslog utility failed to close the stdout and stderr streams properly when running in background mode. This caused the operating system to become unresponsive on system boot. The output streams are now closed properly, which fixes this bug. - BZ#637959 - The rsyslog process could consume excessive memory when using message forwarding with Transport Layer Security (TLS) encryption. With this update, the underlying code has been modified and the bug is fixed. - BZ#694413 - The build script wrongly detected the MySQL support when building 32-bit packages in a 64-bit multilib environment. Consequently, the building process failed. With this update, the build script now uses the proper mysql_config binary and the package is built successfully in this scenario. - BZ#650509 - The lock file created by the rsyslog init script did not match the init script name. Consequently, the system did not run the stop action to stop the process on system shut down. With this update, the file is named correctly and the daemon shuts down as expected. Enhancement 4.169. ruby Bug Fixes - BZ#435631 - To identify the current working directory, the Ruby virtual machine used the path_check_0() function that recursed until it identified the respective absolute path. Previously, the function could cause the Ruby virtual machine to recurse infinitely and consume excessive memory. This happened if the environment path was broken as the getcwd() function failed to determine the full path of the current working directory. This update backports the non-recursive implementation of the path_check_0() function from Ruby 1.8.6, which relies on a series of macros, and the path_check_0() function returns the correct current working directory under these circumstances. - BZ#510277 - The ruby update released on 2009-07-02 as RHSA-2009:1140 included a fix for CVE-2009-1904. This fix introduced a regression which caused leading zeros after the decimal point in BigDecimal objects to be dropped. This could, potentially, lead to incorrect mathematical calculations. This update fixes this problem by ensuring that leading zeros following a decimal point in BigDecimal objects are not dropped. - BZ#445399 - Due to the missing "require 'rdoc/usage'" statement in the RI (Ruby Index) library, which is part of the ruby package, the Ruby virtual machine could raise the following exception:uninitialized constant RI::Paths (NameError)This update adds the missing require statement to the ri_options.rb file of the RI library file and the problem no longer occurs. - BZ#577351 - The "Text::normalize" method included in the REXML (Regular Expressions XML) library, which is part of the Ruby standard library, did not work correctly for ampersand entities (&). With this update, the underlying "REXML::Text" class in the text.rb library has been modified and the ampersand characters are now normalized correctly. 4.170. s390utils Bug Fixes - BZ#705400 - Prior to this update, the dasdinfo utility always returned a zero value even if an action failed. As a consequence, the return value could not be used if dasdinfo was used in a script. This update modifies the underlying code so that dasdinfo now returns a non-zero value if an error has occurred. - BZ#711774 - Prior to this update, the lsluns utility always filtered for logical unit numbers (LUN) with the values 0xc101000000000000 or 0x0. As a consequence, the lsluns option "-a" listed only active LUNs with the values 0xc101000000000000 or 0x0. This update modifies the underlying code so that "-a" option no longer filters LUNs. - BZ#718696 - Prior to this update, the cpuplugd utility failed to do a sanity check if the cpu/cmm_max value was greater than the cpu/cmm_min value. As a consequence, no action was performed. This update adds sanity checks for situations where the cpu/cmm_max value is greater than the cpu/cmm_min value. - BZ#718744 - Prior to this update, the cpuplugd utility encountered a race condition when running the daemon and checking or creating the process ID (PID) file. As a consequence, multiple cpuplugd instances could be started concurrently. This update uses the flock() function when checking or creating the PID file and starting the daemon. - BZ#729609 - Prior to this update, the fdasd check for a valid volume label did not correctly differentiate between interactive and non-interactive usage. As a consequence, the fdasd options "-config" and "-auto" on a device without a valid disk label could stop with the question "Should I create a new one? (y/n)" or completely fail with the message "Disc does not contain a VOL1 label, cannot create partitions". This update modifies the checking mechanism and fdasd now generates valid volume labels as expected. - BZ#730371 - Prior to this update, the lsluns utility help contained the invalid "--ports" option. This update corrects the misprint so that lslun now uses the valid "--port" option. - BZ#736398 - Prior to this update, the getharp utility terminated with the error "buffer overflow detected" if qetharp was invoked with an invalid interface name longer than 16 bytes. This update checks the length of a given interface name parameter. Now, getharp no longer encounters overflows in such situations. - BZ#738342 - Prior to this update, the lsluns utility did not check whether the required SCSI generic (sg) functionality was available. As a consequence, lsluns failed silently if the sg functionality was unavailable. This update modifies the underlying code so that lsluns now checks for the availability and prints an error message if the sg functionality is not available. 4.171. sabayon. 4.172. samba-2010-0787 --0547 - packages distributed by Red Hat does not have the setuid bit set. We recommend that administrators do not manually set the setuid bit for mount.cifs. Security Fix - CVE-2010-0926 -. Warning Bug Fix 4.173. samba3x-2724 -3x packages distributed by Red Hat does not have the setuid bit set. We recommend that administrators do not manually set the setuid bit for mount.cifs. Note
https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/5/html-single/5.8_technical_notes/index
CC-MAIN-2021-43
refinedweb
24,073
54.12
PROLOG This manual page is part of the POSIX Programmer’s Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux. NAME vfork - create a new process; share virtual memory SYNOPSIS #include <unistd.h> pid_t vfork(void); DESCRIPTION. RETURN VALUE Upon successful completion, vfork() shall return 0 to the child process and return the process ID of the child process to the parent process. Otherwise, -1 shall be returned to the parent, no child process shall be created, and errno shall be set to indicate the error. ERRORS The vfork() function shall fail if:The following sections are informative. EXAMPLES None. APPLICATION USAGE. RATIONALE None. FUTURE DIRECTIONS This function may be withdrawn in a future version. SEE ALSO exec(), exit(), fork(), wait(), .
https://reposcope.com/man/en/3p/vfork
CC-MAIN-2019-51
refinedweb
141
56.05
Flask-Heroku-Auth 0.0.4 Flask Based Heroku Authentication. Flask-Heroku-Auth A set of Flask Route decorators to enable either Session-Based Authentication via Heroku’s OAuth mechanism, or Basic Stateless Authentication via Heroku’s API Key facilities. Installation pip install flask-heroku-auth Configuration To enable regex routes within your application from flask import Flask from flask_heroku_auth import HerokuAuth app = Flask(__name__) HerokuAuth(app) or from flask import Flask from flask_heroku_auth import HerokuAuth auth = HerokuAuth() def create_app(): app = Flask(__name__) auth.init_app(app) return app From here, it is a matter of decorating the appropriate routes. For example, the following would implement authentication via the Heroku OAuth facility @app.route('/') @auth.oauth def index(): return "Ok" On the other hand, you may wish to authenticate via the Heroku API Key facility. In this case, the credentials are sent through with every request as an ‘Authorization’ header @app.route('/') @auth.api def index(): return "Ok" You can also restrict access to a Heroku user who has an @heroku.com email address. @app.route('/') @auth.oauth @auth.herokai_only def index(): return "Ok" History 0.0.3 (16/09/2012) - User field is now not required for sudo operations. 0.0.2 (24/08/2012) - Checking for ‘herokai_only’ now occurs only if the user is logged in. 0.0.1 (24/08/2012) - Conception - Initial Commit of Package to GitHub. - Downloads (All Versions): - 0 downloads in the last day - 12 downloads in the last week - 213 downloads in the last month - Author: Rhys Elsmore - License: Copyright 2013 Rhys Els: any - Categories - Package Index Owner: r.elsmore - DOAP record: Flask-Heroku-Auth-0.0.4.xml
https://pypi.python.org/pypi/Flask-Heroku-Auth/0.0.4
CC-MAIN-2016-18
refinedweb
275
55.74
This post is next in the sequence of our last article on working with Python sockets. In the previous post, we demonstrated a TCP server in Python accepting and responding requests from a single TCP client. Now, we want to share the implementation of a Multithreaded Python server which can work with multiple TCP clients. Write a Multithreaded Python server. The Multithreaded Python server is using the following main modules to manage the multiple client connections. 1. Python’s threading module. 2. SocketServer‘s ThreadingMixIn. The 2nd class out of the above two modules enables the Python server to fork new threads for taking care of every new connection. It also makes the program to run the threads asynchronously. Before we move on to checking the code of the threaded socket server, we suggest you read our previous post. It gives full information on Python sockets and illustrates a single threaded server program. Now let’s come back to the today’s topic. In this section, we’ll show you the threaded socket server code followed by the two TCP clients source code. Implement a Multithreaded Python Server. This Multithreaded Python server program includes the following three Python modules. 1. Python-Server.py 2. Python-ClientA.py 3. Python-ClientB.py Python-Server.py import socket from threading import Thread from SocketServer import ThreadingMixIn # Multithreaded Python server : TCP Server Socket Thread Pool class ClientThread(Thread): def __init__(self,ip,port): Thread.__init__(self) self.ip = ip self.port = port print "[+] New server socket thread started for " + ip + ":" + str(port) def run(self): while True : data = conn.recv(2048) print "Server received data:", data MESSAGE = raw_input("Multithreaded Python server : Enter Response from Server/Enter exit:") if MESSAGE == 'exit': break conn.send(MESSAGE) # echo # Multithreaded Python server : TCP Server Socket Program Stub TCP_IP = '0.0.0.0' TCP_PORT = 2004 BUFFER_SIZE = 20 # Usually 1024, but we need quick response tcpServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcpServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) tcpServer.bind((TCP_IP, TCP_PORT)) threads = [] while True: tcpServer.listen(4) print "Multithreaded Python server : Waiting for connections from TCP clients..." (conn, (ip,port)) = tcpServer.accept() newthread = ClientThread(ip,port) newthread.start() threads.append(newthread) for t in threads: t.join() Python-ClientA.py # Python TCP Client A import socket host = socket.gethostname() port = 2004 BUFFER_SIZE = 2000 MESSAGE = raw_input("tcpClientA: Enter message/ Enter exit:") tcpClientA = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcpClientA.connect((host, port)) while MESSAGE != 'exit': tcpClientA.send(MESSAGE) data = tcpClientA.recv(BUFFER_SIZE) print " Client2 received data:", data MESSAGE = raw_input("tcpClientA: Enter message to continue/ Enter exit:") tcpClientA.close() Python-ClientB.py # Python TCP Client B import socket host = socket.gethostname() port = 2004 BUFFER_SIZE = 2000 MESSAGE = raw_input("tcpClientB: Enter message/ Enter exit:") tcpClientB = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcpClientB.connect((host, port)) while MESSAGE != 'exit': tcpClientB.send(MESSAGE) data = tcpClientB.recv(BUFFER_SIZE) print " Client received data:", data MESSAGE = raw_input("tcpClientB: Enter message to continue/ Enter exit:") tcpClientB.close() How to run the Multithreaded Python server program. For your note, please run the above three modules with the Python 2.7 version. Becuase the above code is compatible with Python 2.7. However, you can always convert this demo to run with Python 3.x. You need to make the few changes as mentioned below. - The print function in Python 3 requires wrapping the input arguments in brackets. - The string methods accept input either in decoded or encoded format. Footnote. Threading can make any program to run faster. But it also increases the code complexity. So if you are finding it hard to understand, then adding more logs will help to check what’s happening inside. Next, please share your feedback about the post. Also, if you know a better way of creating Multithreaded Python server then do write to us. In case you want micro level details on Python sockets then refer it’s online documentation. Lastly, if you liked the above tutorial, then help us reach to a larger audience. Keep learning and Make it Big, TeachBeamers. There are some issues I would like to address: 1. The socket is not closed, thus the program will stay in an endless loop on tcpServer.accept() 2. THe last infinity loop is never broken, something like an exception that catches strg+c (KeyboardInterrupt) should be implemented. 3. In the loop (which is now never called) the thread will never be joined since this part will never be reached. 4. The mentioned exception should also be in the infinty loop of the run method in case that the client never sends “exit” – so one should check this otherwise the server can never be closed 5. I do not have a solution for this but: Running ClientA and ClientB on the same machine results in some conflicts and one kicks out the other server. Also after closing one client the client cannot reconnect, no idea why here atm. So in conclusion thank you for the introduction it is good to know the basics Thanks for your close observations. And yes, the primary objective was to provide a basic platform for understanding the socket vs. multithreading concepts. However, will surely see through the points you just made. Hi Meenakshi, Very helpful indeed! I was working on something which required me to plot some data coming on from 3 threaded clients. But there was a Runtime error:’ main thread not in main loop’, I can get a faint idea as to what the problem is but if possible can you suggest a solution? Regard, Karan Hello! I liked this post.It is very helpful.But, my server is not exiting even after I entered exit in the terminal.Kindly help. Hi, It’s great doc, I have small doubt, ai want to send message to specific tcp client from server , how can i do this stuff. i would be thankful for your doc. Glad you liked the post. Next, to answer your query, you can pass the IP address of a specific server in the following call. >>tcpClientA.connect((host, port)) In the first parameter (i.e. host), pass the IP address or the hostname of the system where the server is running. This is how you can connect to a particular server.
http://www.techbeamers.com/python-tutorial-write-multithreaded-python-server/
CC-MAIN-2018-26
refinedweb
1,040
58.69
489 [details] structure (PCL, XForm 1.3.1) Not sure if this is a bug.... We have many apps. To handle this we have a common project for IOS and a common project for Android apps. See Screenshot. If we put a Renderer in the Common IOS project, it is ignored. If we move the renderer to the main project it works. How do we register a renderer so that it will work from a common project that all our apps can share? [assembly: ExportRenderer(typeof(CleanListView), typeof(CleanListViewRenderer))] namespace Common.IOS.Renderers { public class CleanListViewRenderer :ListViewRenderer { protected override void OnElementChanged(ElementChangedEventArgs<ListView> e) { base.OnElementChanged(e); var tableView = Control as UITableView; if (tableView != null) tableView.SeparatorStyle = UITableViewCellSeparatorStyle.None; } } } Xamarin.Forms only looks at loaded assemblies. That means If you are putting renderers into a custom library, then that library needs to be loaded before Forms.Init is called. That means you must have used some type in the library already. EX: public static class CustomControls { public static void Init() { } } Then, call the above Init method just before you call Forms.Init in your platform assemblies - make sure to do it there, the GetMainPage call is too late - everything is up by then. Calling the above method will force the custom assembly to be loaded into memory, which will then let Forms spot your attribute.
https://xamarin.github.io/bugzilla-archives/26/26402/bug.html
CC-MAIN-2019-43
refinedweb
225
67.45
Afternic Sues ICANN, Claims Unfair Treatment 127 gfoyle writes: "The NY Times is reporting (free registratration required) that the cash strapped Icann is being sued by Afternic for being denied entrance into the domain registration market. This is believed to be the first suit challenging Icann's authority over domain registrations." The NYT article points out that both Network Solutions and Register.com now offer domain resale services -- services on which basis Afternic says ICANN rejcted their application to be a top-tier registrar. Re:Good for Afternic (Score:2) In other words it's turning into a pile of useless, moronic shit just like the crap the said corporations churn out in their TV and print media. Oh, hooray, that is an improvement. The irony is, of course, that today's "multimedia experience" is as dull as ditch-water and twice as predictable. TWW Seriously interested in replacing DNS/Registrars? (Score:1) If yoru serious about getting rid of "official" "regulated" corporately controlled domain names, etc you can. Slashdot has enough technically oriented individuals to make it happen, as least as far as the individuals are concerned. No you can't fix your workplace's DNS and your MS using co-workers name resolution (unless your in charge anyway). But you can set your DNS servers up the way YOU want them to resolve. You can subscribe to whatever top-level DNS server you want, including your pal Taco's. If you want whitehouse.com to resolve to whitehouse.com the pron site (as opposed to whitehouse.gov the pornographers site ;) you can. Ditto the inverse. If your serious, willing to dedicate time, effort, server/badwidth use, let me know. One individual's DSL line isn't enough to do it all. HTTP mirrors will be needed. Please though, only serious replies, not "Me too, brain dead AOLers" for the sake of my poor little yahoo mailbox (hint hint for people who dont know pig-latin). BLAH BLAH BLAH (Score:2) I plug again, joker.com. PLUG PLUG PLUG JOKER.COM Re:Good for Afternic (Score:2) Why the fsck do people on Slashdot seem to think that the net has gone from a government toy to a corporate tool? The one place I would not expect to see repeated The Internet (IMHO) was created by government for the army and used by the only people who could figure out how to make it do something useful and then improved upon by them until eventually even stupid corporate managers could start to remember that they just had to open the right program and type in a domain name, then the net got spamdotted to hell. What is the corporate signal to noise ratio online (i.e. complete bag of poo sites to something with a modicom of sense) and is it any better than the signal to noise ratio of joe blogg's homepages? Lets face it the net is a pile of poo with a few plants thriving in the manure, it doesn't matter how any DNS system is organised, the cream will float and the dung will drop out of view. The only people who care about this rubbish are the fools who belive that the "magic" of having many people staggering over their site by accident is worth an IPO. Lets leave this behind here on Slashdot and start accepting that the net is not anyones and should never be anyones, it is a co-operative system where barriers of entry are minimal and we can all stick up our own signal or noise. Lets stop debating how we should help corporations structure the Internet to service their needs (like the current RIAA battle to corrupt the net to preserve their market). The simple question is this, if the RIAA get a ban on the transferal of copyrighted material over a digital interface are you going to stop stripping your CDs onto your file-server so you can play them at any workstation in your house; and if Afternic get accredited as a reseller are you going to stop typing in domain names and start learning IP addresses? Let's get slashdot talking about how to create the next generation net based on distributed architectures NOT the last generation DNS system and how it is or isn't suiting corporate americas needs. A finally to slightly justify and defend this rant: Anarchic DNS (Score:1) So it's crazy. But *I* like the idea. That way there can be more seamus.org's than just the one (why, oh why was I so slow? :) Of course, eventually people would get pissy about having "convenient" IP addresses to type in... can you imagine network card and router sales/manufacturing in this future? Neat... Re: International .tld's (Score:3) Re:Do the math: peer to peer DNS will not work. (Score:1) By contrast in a peer to peer DNS network, in a world with many hundreds of thousands of DNS servers, to find an unknown, not commonly accessed domain would require tens of thousands of lookups if it were possible at all. This IS a world with many hundreds of thousands of DNS servers. I was being flippant in my call to people to start their own DNS servers - but a well designed root server heirarchy could very well be made that would allow for arbitrary TLDs without killing the 'performance' of DNS. In fact, I specifically mentioned that you could simply extend the existing BIND mechanism. There is no change to the method, merely an addition of an infinite number of TLDs. At a tenth of a second per lookup, it would take about two hours to resolve the average domain name. What's that one-liner about statitics being made up on the spot? Are you implying that it would take 72,000 searches to find an arbitrary domain name/ip address pair? Are you planning on searching these domains with the famous 'Ransack Search' algorithm? Good computing isn't about math 101 - linear and iterative algorithms are almost always the wrong way to do anything complex. It's a technologically illiterate suggestion. Anyone who made it, go back and do maths101. Don't be so negative! -- blue Re:You want DNS to be like USENET? (Score:1) Afternic vs. others (Score:2) One major difference I see between Afternic and the other registrars: the others are primarily pushing registration with the resale being almost an afterthought, while Afternic seems from thier home page to be mainly aiming for resale with registration primarily to support that resale. To me this makes a world of difference. Re:Perhaps good may come of this (Score:2) Alternate root DNS servers? (Score:2) Anybody who runs a DNS server, and wishes to, could configure their name server to view my server as the root. Then, I could implement whatever policy *I* feel is appropriate for handing out domain names (People Eating Tasty Animals gets priority, BTW). I know that most people wouldn't use these servers (businesses, for example), but I bet someone could get a good underground following going (imagine a .sucks TLD -). So, why hasn't anybody else done this? Why couldn't I do this? Re:Why are we still dealing with these loosers ? (Score:1) .arpa is used for reverse DNS lookups based on an IP address. The IP address flipped backwards and converted into a -- Re:Perhaps good may come of this (Score:1) If everyone started breaking off IPs from subnets and moving them around on a daily basis the Internet would quickly come to a screeching halt. Could be done, BUT... (Score:2) Another problem is dealing with 2 people creating the same TLD - if A creates Any (good and workable) suggestions on fixing these problems? Re:A simpler solution? (Score:2) Hey, here's an idea: make it so that every file on the Internet can be downloaded at the same speed, regardless of how fast your connection is. Wow, that'd be neat! Comon folks, at least think about the actual content of some of these comments before you moderate them up. Whoever thinks that the super-smart crowd that is Slashdot is collectively coming up with ground-breaking Internet concepts should go write an article for ZDNet about it... I'm sure they'd take it. Re:Its called justice, an unusual concept these da (Score:2) If what they are accused of is indeed what happened, they broke the law and should be punished accordingly. Of course, I think a better solution [slashdot.org] would be to simply stop paying attention to the ICANN and develop our own method for mapping names to ip addresses. Re:A simpler solution? (Score:1) -- -- -- -- -- Even simpler. 'Zero Level' to the domain system. Think of it like this... You keep the existing DNS, but fill in around it. You add two levels above the current search through the '.com' domain. Add an "Alphabet Server", and a "Character Server" above the current "Top-Level Domains". The "Alphabet Server", is the master DNS server with a very short list of entries to check through, a list of each valid character a TLD can start with referencing a series of IP addresses for the corresponding "Character Server". It would look something like this: a 104.234.34.45 32.34.45.56; b 67.89.01.23 45.67.89.01; c 45.67.84.32 234.210.198.76 24.56.75.32; z 24.32.45.76 32.45.87.234; Each "Character Server" would have a similar list of TLDs that begin with that character and the IP address(es) of the Domain Servers that handle them. For example, the "c" Character Server might have a list like this: cc com car 111.111.111.2 111.111.111.3; cars 222.222.222.2 222.222.223.2; conspiracy 999.999.999.9 911.911.911.1; cx The beauty of this approach is that we don't have to break the current DNS system to implement this, and we could actually MAYBE fix the current Lets say Microsoft immediately grabs the The With this method, the "Alphabet List" could be EASILY propogated to practically every DNS server, while the Character Lists would only have to propogate to a few widely scattered servers, and each Domain Server would get handled much like they are now. What do you think? Re:history... (Score:1) Re:A simpler solution? (Score:2) So, according to you, in order to even be permitted to express an idea in this or any forum, one must have already worked out all of the technical specifics, else said ideas should be ignored and derided? Please. Hacking a browser to call an alternative domain resolution service in response to an URL beginning with alt:// would be fairly simple. There are already modules to deal with ftp:// (FTP), mailto:, etc. Most of the code needed for the alt:// appraoch is already present, one needs to simply rip out the DNS resolution code and replace it with whatever the alternative approach would be. As for a gnutella type system, if you'd even bothered to read my original post, you would have seen my suggestion to use the existing DNS software, perhaps running on a different port, with different root servers. Not that a more distributed and less top-down approach, a la FreeNet, wouldn't necessarilly be as good. Some technical robustness against hoards of lawyers might actually be worth a performance tradeoff, particularly in today's climate. Comon folks, at least think about the actual content of some of these comments before you moderate them up. Some of us do think. Perhaps you should do likewise before going off half-cocked. (HINT: Actually reading the post you're replying to helps). Re:Icann is right (Score:1) Re:It's the whole system that sucks! (Score:2) Another poster to this thread suggested that we get rid of the big 3 current TLDs and force companies and people to register domains in the appropriate country TLD. This would certainly limit confusion (Is that .com I'm looking at in the States, UK, Belgium? Where?) I think active management by a set of domain registrars who have purchased name space off a TLD is the way to go. Don't just let any dipshit register any domain. It might make the process more expensive and increase waits, but ultimately that's the only way any semblance of order is to be had. LDAP would probably be better suited for this sort of thing, too. Anyone feel like rewriting gethostbyname? Re:Perhaps good may come of this - Different now (Score:1) The admins that were in charge of maintaining these hierarchies simply did not have the time to do it. And if you have ever dealt with the folks at ISI.EDU before, than you can tell they don't really have the time either (if they still do it, I have not done dns in a while). Then there is the problem with Have your say at ICANN: Use the public forums. (Score:1) That's WINS you idiot. (Score:1) Come back and talk when you DO know what you are talking about. Re:Perhaps good may come of this - Different now (Score:1) Domain name mil, edu and gov have always been supposedly restricted for the exclusive use of USAn organization. Cf this [iana.org]. You can notice that the three counter-example you give me are canadian. An ICANN guy may have estimed that Canada was sortof part of the USA. I dare you to find any south-american, african, european, asian, oceanian or antartican (?) counter example. Re:Double Negatives (Score:1) I apparently read it wrong, and have been amused by the total lack of ettiquite/elegance with which you have all responded. Please allow me to try to clarify how I read that line. "In a statement..." In one sentance, in summary, etc. "... Icann denied treating Afternic unfairly" the part I was picking at. Now, if none of you can see it being read that way, I suggest you go back to school to gain better knowledge of the English language. The English language is NOT the best language in the world, it's probably one of the worst/ugliest, and I'm pretty sure it's one of the hardest to learn. Why are we still dealing with these loosers ? (Score:4) If someone with a machine that can be a DNS server just appoints themselves head resolver honcho, then everyone who chooses to use the service can. Of course, perhaps Bruce and Eric might both start resolving *.communityloudmouth, but people will choose whose service to use individually, and I think that's the way it should be. What would be needed is to set up the whole plan carefully, so that it was easy for users to assign different DNS servers to different blocks of domain names. This continuous annoyance would be fixed as people simply voted for the DNS servers they trusted. I for one would be delighted to point my DNS requests at a server that pledged to resolve etoy and etoys correctly, and ignored whatever judicial injuctions that the "official" top level DNS's choose to respect. What has to be set up carefully is the tool which allows users to do this. If we make it easy for people to do what they want instead of what an incompetent committee rules, then the right things will happen. If you put useful information on machines with Funnily enough... (Score:2) TWW Re:Perhaps good may come of this (Score:1) Re:Perhaps good may come of this (Score:2) Do we really still need to keep the Internet robust vs. large-scale nuclear war? Re:Good for Afternic (Score:1) You want to see something pathetic? Go to Pizza Hut's Web site [pizzahut.com]. Two "front pages", one of which is Shockwave. I don't even see why they have a Web site; it's not like they let you order pizza online [papajohns.com] or anything. Re:Domain registration & distributed DNS (Score:1) Re: International .tld's (Score:1) Or, go for the gold-rush mentality, and just start fresh, under a new domain hierarchy... Restructured so that -Ever notice that there's a read without a login (Score:2) Re:BLAH BLAH BLAH (Score:2) you don't have to pay double to have the domain name hosted unlike joker. Also you actually own the domain and can't have it snapped off you like joker. Read the FAQ and T&C The new trend in domain registrations, hidden charges! Re:This just isn't working out (Score:1) Somebody would do it. You know they would. -- Do the math: peer to peer DNS will not work. (Score:3) I am amazed at the degree of ignorance that Slashdot readers show on this subject. Do the math! Suppose I want to visit a website I've never visited before, in a GTLD domain. My client makes a call to my DNS server. If it hasn't got the name in it's cache, it queries my ISPs DNS server; if it hasn't got the name in it's cache, it queries a root name server. The root name server issues it the NS record for the domain, and my ISP's DNS server then queries the authoritative name server for the domain. That's a maximum of four lookups. A CCTLD domain adds one, and each level of delegated subdomain adds another. But you're looking at a very small numbers of lookups. By contrast in a peer to peer DNS network, in a world with many hundreds of thousands of DNS servers, to find an unknown, not commonly accessed domain would require tens of thousands of lookups if it were possible at all. At a tenth of a second per lookup, it would take about two hours to resolve the average domain name. In the mean time, because the load on DNS servers would have increased by three orders of magnitude, either far mor powerful servers would have to be used, or the DNS system would grind to a halt. It's a technologically illiterate suggestion. Anyone who made it, go back and do maths 101. Y00r 0n craQ (Score:1) NYT: Did you treat Afternic unfairly? ICANN: No. Therefore, they denied treating Afternic unfairly. "In a statement, ICANN treated Afternic fairly" does not mean the same thing. In fact, they did not do anything towards Afternic in the statement. They merely denied the allegations that they treated Afternic unfairly. Do the extra words make it clearer for you? Grammer troll. Re:Why are we still dealing with these loosers ? (Score:1) -- Supporting cybersquatting (Score:2) Its called justice, an unusual concept these days (Score:2) Oh, since about the time people started bandying the word "justice" about. It is called illegal restraint of trade, and it will get your ass fined and a substantial portion of your assets handed over to the offended party in this country if you are found guilty. If the ICANN did indeed do what they are accused of, there is a very good chance they are guilty and will have to make financial ammends for their behavior. As much as we gripe about the justice system here in the US, it often appears to be the only functioning branch of government left, where there is at least some semblance of justice, occasionally, at times. The Legislative and Executive branches are, to all appearances, already a lost cause. The leading question is, of course, how long can a government stand on only one good leg (or branch). Re:Perhaps good may come of this - Different now (Score:1) The University of Waterloo [uwaterloo.ca], in Waterloo, Ontario, Canada, used to be "waterloo.edu". They later changed to "uwaterloo.ca". So it wasn't limited to "USAn" educational institutions, at one point in time. Re:"partners" Stopped Working, but "www10" Is Good (Score:1) I'd hate for someone to avoid posting something useful because they didn't want to look like they were seeking out karma. [not to mention, if I was desperate for karma, I would've bypassed the +1 bonus. The comment would have still been moderated to 3 and I would have received an additional karma point.] ----- Re:Perhaps good may come of this (Score:1) Dissatisfied with a DNS entry? You can change it! (Score:1) Re:A simpler solution? (Score:2) Even those who do not change their default to alt:// could be led there, via URL links of the form "A HREF="alt://myantimicrosoftsite.microsoft.com". The notion is that the most common application of DNS today is with respect to the web. This solution does not address issues with respect to shell accounts, telnet, ssh, ftp, etc., although a more comprehensive, alternative name resolution system is probably called for. As for techies forgetting about Internet NEwbies and AOL dorks, well, why not? They can educate themselves, just like the rest of us. Ignorance like yours is why this is FUBAR (Score:1) If, however, I was representing something with a valid Maxwell trademark (and I can't help but think of Maxwell House Coffee, even though I can't stand the stuff), then yes, it would be first-come, first-serve. Re:Perhaps good may come of this (Score:1) Yeah, that will work great with IPv6... Re:Could be done, BUT... (Score:1) And as for two people with the same top level domain, the point is that each individual can choose how to handle that (all though the majority will go along with the default of their setup). We don't want to replace domain name disputes with tld disputes. The idea is to simply put the power for each person to decide for themselves out there; I expect ICANN and friends will get their act together under threat of competition. One could set up a proxy similar to the anomozier which would allow you to enter a URL such as With good reason (Score:5) Re:history... (Score:1) It's the whole system that sucks! (Score:4) <IMHO> Like the subject says, its the whole system that sucks! I say we need an international entity responsible for domain name assignment and dispute resolution, and that each country that wishes to participate in the Internet must acknowledge the entity's authority. Maybe a UN-sponsored organization? Is this too unreasonable in the long run? </IMHO> Perhaps good may come of this (Score:4) With the whole issue of the trampled namespaces, plus the many legal issues, I wonder if this may push people away from registering a bazillion more domains. Hmm... Nope. "It doesn't end in .com? That ain't a real Web site!" Re:A simpler solution? (Score:2) You keep the existing DNS, but fill in around it. That's an interesting approach, although it does have the disadvantage of allowing the ICANN to retain its domain of authority. Prehaps competing sets of root servers would be better, each addressable by either a different URL prefix, or a different "one-off" domain (microsoft.com.ican, microsoft.com.alt, etc...). This assumes we stick with DNS, which might be more practical short term, but not necessarilly what we'd want in the long term. An ideal situation would be an approach where no central authority exists to say "yeah" or "nay" to a domain name, where anyone can simply register a name, such as "jean-michel.smith" and, if no one else already has it, you get it. Any legal action is betwen you and whoever, as only you can change it (with your secret key, presumably -- this already assumes a slightly more sophisticated appraoch than the current DNS heiarchy.) This doesn't necessarilly mean no heiarchy. One idea might be to have a hybrid system, in which each heiarchical level is peer to peer (with automated conflict resolution via timestamp or some other reasonably fair methodology), such that anyone can set up a root server in cooperation with other root servers, anyone can set up a This would mean that Micrsoft wouldn't control all names within the There are other issues which would need to be fleshed out, such as what to do if someone forgets or loses their private key (or claims they did) and so forth, but you get the idea. As another put it, power and responsibility both reside with the individual registrant, to whom other parties and the legal system could turn if legal remedies were called for. All this is TOTAL BS... (Score:1) What authority? (Score:1) It's annoying to have to make this comment all the time on DNS-related stories, but I feel it's worth it to keep this fresh in peoples' minds: What authority does ICANN actually have? Sure, they run the defacto standard DNS network. But nothing significant is stopping anyone from creating an alternate DNS network (and thus, an alternate namespace, at least under the TLD level). Heck... AlterNic is the prime example of this. I feel that a DNS network that uses all of the existing TLDs, but with the addition of a .o domain (a previous post of mine [slashdot.org] for more info on my .o idea) or a (usenet-esque) .alt domain is definitely in order. Domain registration & distributed DNS (Score:3) It seems to me that instead of having all this ICANN accreditation nonsense, any authoratitive DNS server should be world-writable, with some form of digital signature required to update an existing domain, but unregistered domains go to anyone who requests them. Billing could be done post-facto, or not at all. Further, why not scrap the whole DNS heirarchy? Every ISP has at least two DNS servers, and they all talk to the upstream DNS servers until you get to the root servers. DNS should be made peer-to-peer, not top down, and the need for ICANN and it's 5M$/year budget goes out of the window. At the time of writing, this was a first post. what about a hybrid system? (Score:2) queries get passed up and down to the appropriate level as now for resolution. Peers would only have to cache databases for their level, not the entire internet. Once reaching the appropriate level (e.g. Anyone can add a peer, and manage a name within that level as they wish, with conflict resolution using timestamps or some other, reasonably fair appraoch. Thus, no one has authority over any domain, top level or otherwise, yet everyone can remain certain that, once they have registered a name it is theres. Possible problems: hijacking of lower level names. E.g. you have a network my.firm, and you want to name all kinds of names like mars.my.firm, venus.my.firm, jupiter.my.firm, but some other jerk has gone around and registered millions of names, eating up most of the usable hostnames. Possible solution? (This is probably heresy) Introduce a small modification to the standard domain name nomenclature, in which a hostname is seperated from the domain name by a different character than "." Within each domain name each person has complete authority as they do now with standard dns, but without, none. So, in our example above, some jackass could go on to register mars.my.firm, venus.my,firm, etc., but these point to domains and not specific hosts, which would be resolved as mars:my.firm, venus:my.firm, etc. (a colon probably isn't the best example here, but dashes are out and nothing else springs directly to mind. Maybe commas?) I don't know if this is at all workable, but it seems to be a better solution than the centralized system we have now with all of its abuses and centers of authority, while still preserving much of the performance gain in a heiarchical system. What do you think? Good for Afternic (Score:1) What you have to remember is that the net is no longer the Government's little toy, designed and maintained for the sole benefit of ivory tower academics and covered by an "appropriate use" policy. It is now the domain of the corporations that have turned the web from a text-based, dull place into the multimedia experiance that people want to see today. ICANN is a remnant of the Government's long-gone days in which the controlled the net, and I don't think anyone really wants them to control anything. Instead we need to allow market forces to be brought into play in the domain name market, so that consumers can get the best deal possible - something which ICANN seem to be determined to stop. No, hopefully Afternic will win this case and ICANN will be consigned to the attic like it should have been. The time for government control over the net has gone, and that can only be a good thing for all of us. --- Jon E. Erikson Consequences? (Score:1) Re:Funnily enough... (Score:1) The rest of the practice sucks, though. "partners" Stopped Working, but "www10" Is Good (Score:4) Of course, this side-steps the issue of whether it's ethical to take someone's content for free that they are requesting you to register for. ----- Re:Perhaps good may come of this (Score:1) Re:Ignorance like yours is why this is FUBAR (Score:1) so.. (Score:2) There's no reason at all for them to be so stodgily defined. BIND doesn't give a damn what domain name you use. It's a sort of artificially created monopoly, in the sense that only a small number of I say we all just start our own root servers, and allow any tld to be posted to it. Come on, donate some broadband to the Free The World From ICANN's Domaination! project. -- blue Go ahead... (Score:2) Grounds for Lawsuit? (Score:2) Re:Perhaps good may come of this - Different now (Score:4) "Thank you for your submission. Currently, InterNIC processes over 600 domain submissions a week. Please be advised, that your registration will take up to three weeks to process. Also, there is a one domain per organization limit. Multiple registrations will be rejected" Back then, all registrations were done by hand, (I remember Robert used to handle all of ours). Only ISP's or similar networking organizations could have a It was very different back then. Oh well, I used to also walk 8 miles uphill both ways in the snow in July when I was a boy... Re:Domain registration & distributed DNS (Score:1) No. If the root nameservers became world-writeable, how long before some l33t skr1pt k1dd13 comes along and writes a Perl script to automatically register every possible alphanumeric domain name between two to 25 characters that hasn't already been registered? I'd give it, what, half an hour maybe? -- Re:Domain registration & distributed DNS (Score:5) Okay, so maybe you are picturing an architecture along the lines of BGP (large networks share routing information about each other all over the world with no central "Internet route server"). Well, that's a nice concept, except that every DNS server in the world would have to maintain an entire copy of the DNS database (just as most routers employing BGP on the Internet maintain an entire copy of the Internet's routing table via Autonomous System Numbers). The key difference is that the DNS database is many orders of magnitude larger than a "BGP database." In addition, you can't summarize domain names like you can with IP address blocks (i.e. DNS CIDR = oxymoron).. and remember, you said no hierarchy, which would imply that you don't pull "views" of the DNS database from any sort of central/upstream DNS server. When you speak so vaguely ("DNS should be made peer-to-peer, not top down"), it sounds good.. but that statement carries no real weight in any discussion approaching technical viability. If you're merely speaking idealistically (e.g. "in a perfect world, we would be able to implement DNS in a distributed manner in such a way that it didn't suck"), I agree wholeheartedly. This notion can definitely be explored further, but it's safe to say that this is not a simple solution, and I daresay that without some fundamental modifications to basic concepts such as "peer-to-peer" and "no hierarchy," very little progress would be made in seeking a superior solution. I don't see any technical merit in your proposal, so the only motivation is "ICANN is bad, now we don't need them." The next logical step is to fix ICANN, not break DNS. Gnutella Like System? (Score:2) There are two immediate problems with this, one technical, and one political. First the technical, because it's the most important (politics can go t hell for the moment...). The problem is that things like Round Robin DNS for server pools, and for those poor souls with dynamic IP's who still want to run a server, we need some sort of clever way to prevent this decentralized blob of servers from keeping stale name entries around. Maybe if each entry in the system got a UTC timestamp along with it's signature, and any server that had a previous copy would replace that with the new one, but it still has the capacity to stagnate. Maybe if when aquiring new links A La Gnutella, there could be some specific protocol provision for requesting at least a couple distant servers as peers to keep the average distance between any two servers small... I'm sort of sleep deprived, so i'm not sure if that would work, but how's it sound? The political problem is trying to overcome the F.U.D. that will be kicked up by the powers that be when a system is created that cannot be 'sued' and from which names cannot be revoked because they are offensive, or because some stupid corporation is scared of them (think or the etoy-etoys ruckus...). Oh well. *yawn* Re:Good for Afternic (Score:1) Yes, sure, corporation is good, government is bad. Rightist WTO propaganda. Rich multimedia experience is good (with my tiny modem, I sure love all those heavy pages, that take one hour to load). Dull text is information centered, light, quick to load and easy to adapt. Awful ! > The time for government control over the net has gone, and that can only be a good thing for all of us. Bwahahahahah! Bullshit. What control was there ? Control over domain name ? Is that a true control ? Why do you think corporation and marketing guys will want to act for the good of us all ? Re:"partners" Stopped Working, but "www10" Is Good (Score:1) Umm, the registration for nytimes.com is free... so you using the other link to 'take someone's content for free' isn't much of a point. Being a someone in charge of looking at stats for a web page, the only reason I can think of to ask people to register before browsing, is so you can get more accurate statistics. Yes, of course you can look at the http logs... but having seen that your home page has been loaded 100 times in one day doesn't really tell you much. Was it 100 people? was it just a few people who reloaded the homepage a lot (a-la slashdot homepage)? By having people register, you can find out how many different people visited your site on a day. That information is much more usefull, although, still, not wholy accurate. jerky boys (Score:1) JB: Well, why don't i just sue you? Lawyer: Sue who? JB: Sue you. L: Sue me? JB: Sue everybody! brought to you by a bored intern Re:Perhaps good may come of this - Different now (Score:1) > Almost any educational institution could get an .edu .edu Almost any USAn educational instituation could get an A simpler solution? (Score:4) This FUD is easilly gotten around. Hack Mozilla and other browsers to recognize a different prefix as html, but using the new Name Service. Perhaps something like "alt://" instead of "http://" Allow the user to define one or the other as the default. Then, whenever someone tries to look up alt://fucktheicann.com they'll get the anti-icann site, while isn't resolved because the ICANN has "reserved" it. (Disclaimer, the previous example is entirely fictional, I have no idea if such a domain exists or how ICANN would respond to it if it did). One could go a step further, in inviting all of the country code TLDs to participate in both systems, such that the integrity of This could probably be hacked using the existing DNS system, or an improved version with better security features. Names could be given on a first come, first serve basis (automated), with no provisions for arbitration whatsoever (take it up with the other party, if you get a court order, send the police to there house, don't bother us). Re:Double Negatives (Score:1) Re:A simpler solution? (Score:2) THat sounds like a nifty idea. Re:Perhaps good may come of this (Score:1) Re:Why are we still dealing with these loosers ? (Score:1) Re:Why are we still dealing with these loosers ? (Score:2) Re:"partners" Stopped Working, but "www10" Is Good (Score:1) No, what the cookies are really used for is tracking how often any given person accesses the page, and which pages. Thus the ads can be targeted based on interests, and the company can develop a demographic profile of its userbase through the use of pageviews, surverys, and referrer URLs. --- Ignorance like yours is why this is SNAFU (Score:1) So who gets maxwell.com? Whoever got to it first, that's who, and to fuckall with latecomers. A trademark is not an exclusive right to be the sole user of the word or name in every conceivable form in every market and in every corner of the world. It allows exclusive right to use the name for a product or range of products in a specific category, and that's all. Re:Gnutella Like System? (Score:1) Actualy, there was some disscussion of DNS over Freenet sometime back. Check the Freenet-chat archives [geocrawler.com]. The idea got passed around a lot. Eventualy, we just decided that it was a good idea but there was no reason to implement it now, but maybe in the future. Freenet would also have to get a lot faster at doing requests (hey, its only in 0.2 beta!) ------ Re:Good for Afternic (Score:1) You probably aren't living in the right area. Pizza Hut does deliver [pizzahut.com]. Not like Papa Johns (I didn't know they did. Thanks for the link.) but it is coming. Pizza Hut's splash page is pretty, but pointless. Re:This just isn't working out (Score:1) Re:With good reason (Score:1) Re:Perhaps good may come of this (Score:2) Good job; you just described what DNS is--except your idea uses numbers, which are harder to remember than names are. You deserve a medal. Re:This just isn't working out (Score:2) Personally, I think the Official Pr0n TLD should be .xxx. I think the pornsites would like that too, since they already try to get as many x's in their names as possible (at least, so I've heard...not that I'd know from firsthand experience...or anything...er...ahem). I'm more concerned about only nonprofits getting .org, no companies (sorry, Hemos). My favorite suggestion is to let each country manage their own DNS. So, say, pets.com would mean pets.com.au in Australia and pets.com.us in the USA. To get to a domain in another country, just qualify it with the ISO country code (pets.com.au would always be the same site no matter where you are). Of course, there would have to be restrictions: a country couldn't create a TLD that matched a country code. --- Zardoz has spoken! history... (Score:4) and 2000 is the year that attorneys found out about it. Re:Perhaps good may come of this (Score:2) Trust me - Domain Naming is a GOOD THING. Having a decentralized system of DNS servers is what makes it possible for you to move your web server from your SPARC box in your office to a co-lo facility inside a missile silo in South Dakota and have users still be able to find the server after the DNS refreshes even though the IP has changed.-carl Re:Perhaps good may come of this (Score:2) People have been using numbers for their telephones for decades, so it's not like the web would become impossible to use. Re:Good for Afternic (Score:3) By "multimedia experiance" you mean "crap". Re:With good reason (Score:5) Where is the court filing that you speak of? I find your claim to be outrageous, and completely un-found. In an completely one-sided advisory [icann.org], which is clearly propaganda, ICANN states: "In investigating Afternic's application for accreditation, ICANN discovered that Afternic's web site presented many offers to sell domain names based on other company's names, some with remarks reflecting the abusive nature of the offers. One company name, for example, was offered with the remark that it would be an "Excellent domain for a reseller, owner, or competitor of" the company (this example was offered at a starting bid of $125,000)....Currently, Afternic's site is offering many other domains incorporating well-known business, celebrity, and government agency names..." Nobody likes cybersquatters, myself included, but how is this different from how Network Solutions or any other company operates in this market? You can go to register.com or Network Solutions and register anything you want, no matter what law or trademark it violates. That is between the user and the entity which feels it is being violated. The same thing is true on afternic. Just like EBAY, with almost 200,000 auctions it would be impossible to actively police everything. Afternic did not encourage these people to purchase these names, and they fully comply with ICANN's dispute resolution process, as wells requests from trademark holders, etc. Re:"partners" Stopped Working, but "www10" Is Good (Score:4) (and, by the way, the partners link does still appear to be working for me, though it didn't in a previous story) ----- Icann is right (Score:3) Icann is absolutely right for turning down Afternic. Its companies and people like them that prevent regular people from buying domains with simple, easily remembered names. A decent analogy would be if a person or company tried to buy all the 800/877/toll free prefixed telephone numbers that spell something, in order to resell them at a later date. Its irritating at the very least, and although IANAL, I suspect it is illegal. Re:Perhaps good may come of this (Score:2) Good point. Subnet transfers would be a problem. OTOH BoLean's idea of meaningless random number strings as domain names seems to have no downside, other than the loss of vanity names. Re:Its called justice, an unusual concept these da (Score:2) Not rejected, just on hold (Score:2) -russ This just isn't working out (Score:3) 1. I agree needed are more TLD's, but they need to be logical ones. Sex sites on 2. There need to be rules and the registration services need to enforce them. aka if your not a company you don't get a 3. First come first served, end of story. If you register xxxx.yyy its yours unless there is a superior claim. ie mcdonalds.com should belong to the company, but if you register mcdonalds.fam because thats your family name no one cna take it away. 4. Trademarks mean nothing on the internet, and should not be enforcable. see above. 5. A new central authority, the current ones don't work. 6. Registration services cannot own domain names, or horde domain names that they do not use as part of their business. 7. Domain names are the property of the person who registers them, the fee is simply for the up keep of the central domain records, so your DNS server can be found. 8.Owners have the right to move to a different service if they so desire at anytime. 9. Anyone can provide registration services, just like networksolutions, register.com whatever. 10. Domain names cannot be suspended or taken away, unless you can provide a superior claim, TRADEMARKS do not count. You must simply have existed longer doing what you are doing on the internet...first come first served again. 11. You have the right to a single top level domain. If you have xxxx.yyy you cannot own xxxx.zzz as well unless it is providing entirely different content and services. This is common sense stuff, that personally i had always thought was just standard practice until I really started paying attention to internet politics.
https://slashdot.org/story/00/06/26/1235233/afternic-sues-icann-claims-unfair-treatment
CC-MAIN-2018-05
refinedweb
7,621
71.65
Overview Atlassian SourceTree is a free Git and Mercurial client for Windows. Atlassian SourceTree is a free Git and Mercurial client for Mac. Fabtest Fabtest is a set of utilities and base TestCases that aid testing Fabric scripts against VirtualBox VMs. License is MIT. VM is rolled back to initial state before each test so tests can do anything with target system; Fabric commands can be run from Python. Installation pip install fabtest VMs In order to run tests you'll need VirtualBox 4.x and an OS image. Image should have ssh server installed. Example VMs (they can be imported to VirtualBox via File->Import Appliance): Due to bugs in VirtualBox it is better to convert imported .vmdk disk images to .vdi images, e.g.: VBoxManage clonehd Ubuntu-10.10-disk1.vmdk Ubuntu-10.10-disk.vdi --format VDI Then detach (and remove) vmdk disk from the VM and attach the vdi image. After you get the image, make sure it is not running and execute the fabtest-preparevm script (pass your VM name or uid to it): fabtest-preparevm Lenny This command configures port forwarding (127.0.0.1:2222 to guest 22 port, 127.0.0.1:8888 to guest 80 port) and takes 'fabtest-initial' snapshot used for test rollbacks (it is taken from booted machine in order to speedup tests). Writing tests Subclass fabtest.VirtualBoxTest or fabtest.FabTest and use fabtest.fab for fabric commands execution: from fabric.api import run from fabtest import FabTest, fab def whoami(): return run('whoami') class MyTestCase(FabTest): def test_root_login(self): output = fab(whoami) self.assertEqual(output, 'root') Look at source code (and example/runtests.py) for more.
https://bitbucket.org/kmike/fabtest
CC-MAIN-2015-27
refinedweb
279
69.18
how to get the recipients addresses of an outlook mail in python... Discussion in 'Python' started by venutaurus539@g04 - Beat Bolli - Jun 21, 2005 Physical Addresses VS. Logical Addressesnamespace1, Nov 29, 2006, in forum: C++ - Replies: - 3 - Views: - 897 Max recipients of mail message?Bobby Edward, Jan 4, 2009, in forum: ASP .Net - Replies: - 1 - Views: - 781 - Bobby Edward - Jan 4, 2009 HOW TO Track How Many Recipients Open Your Mail IN RAILSTony Augustine, Apr 22, 2010, in forum: Ruby - Replies: - 4 - Views: - 589 - Mathew Augustine - Apr 24, 2010 Sending mail through Mail::Outlook, May 25, 2006, in forum: Perl Misc - Replies: - 2 - Views: - 989 - A. Sinan Unur - May 25, 2006
http://www.thecodingforums.com/threads/how-to-get-the-recipients-addresses-of-an-outlook-mail-in-python.640135/
CC-MAIN-2014-41
refinedweb
111
70.13
From. I'll also be going through a crash course on reinforcement learning, so don't worry if you don't have prior experience! The cart pole problem is where we have to push the cart left and right to balance a pole on top of it. It’s similar to balancing a pencil vertically on our finger tip, except in 1 dimension (quite challenging!) You can check out the final repl here:. RL Crash Course If this is your first time in machine learning or reinforcement learning, I’ll cover some basics here so you’ll have grounding on the terms we’ll be using here :). If this isn’t your first time, you can go on and hop down to developing our policy! Reinforcement Learning. Similarly the agent's goal will be to maximise the total reward over its lifetime, and we will decide the rewards which align with the tasks we want to accomplish. For the standing up example, a reward of 1 when standing upright and 0 otherwise. An example of an RL agent would be AlphaGo, where the agent has learned how to play the game of Go to maximize its reward (winning games). In this tutorial, we’ll be creating an agent that can solve the problem of balancing a pole on a cart, by pushing the cart left or right. State A state is what the game looks like at the moment. We typically deal with numerical representation of games. In the game of pong, it might be the vertical position of each paddle and the x, y coordinate of the ball. In the case of cart pole, our state is composed of 4 numbers: the position of the cart, the speed of the cart, the position of the pole (as an angle) and the angular velocity of the pole. These 4 numbers are given to us as an array (or vector). This is important; understanding the state is an array of numbers means we can do some mathematical operations on it to decide what action we want to take according to the state. Policy A policy is a function that can take the state of the game (ex. position of board pieces, or where the cart and pole are) and output the action the agent should take in the position (ex. move the knight, or push the cart to the left). After the agent takes the action we chose, the game will update with the next state, which we’ll feed into the policy again to make a decision. This continues on until the game ends in some way. The policy is very important and is what we’re looking for, as it is the decision making ability behind an agent. Dot Products A dot product between two arrays (vectors) is simply multiplying each element of the first array by the corresponding element of the second array, and summing all of it together. Say we wanted to find the dot product of array A and B, it’ll simply be A[0]B[0] + A[1]B[1]... We’ll be using this operation to multiply the state (which is an array) by another array (which will be our policy). We’ll see this in action in the next section. Developing our Policy To solve our game of cart pole, we’ll want to let our machine learn a strategy or a policy to win the game (or maximize our rewards). For the agent we’ll develop today, we’ll be representing our policy as an array of 4 numbers that represent how “important” each component of the state is (the cart position, pole position, etc.) and then we’ll dot product the policy array with the state to output a single number. Depending on if the number is positive or negative, we’ll push the cart left or right. If this sounds a bit abstract, let’s pick a concrete example and see what will happen. Let’s say the cart is centered in the game and stationary, and the pole is tilted to the right and is also falling towards the right. It’ll look something like this: And the associated state might look like this: The state array would then be [0, 0, 0.2, 0.05]. Now intuitively, we’ll want to straighten the pole back up by pushing the cart to the right. I’ve taken a good policy from one of my training runs and its policy array reads: [-0.116, 0.332, 0.207 0.352]. Let’s do the math real quick by hand and see what this policy will output as an action for this state. Here we’ll dot product the state array [0, 0, 0.2, 0.05] and the policy array (pasted above). If the number is positive, we push the cart to the right, if the number is negative, we push left. The result is positive, which means the policy also would’ve pushed the cart to the right in this situation, exactly how we’d want it to behave. Now this is all fine and dandy, and clearly all we need are 4 magic numbers like the one above to help solve this problem. Now, how do we get those numbers? What if we just totally picked them at random? How well would it work? Let’s find out and start digging into the code! Start Your Editor! Let’s pop open a Python instance on repl.it. Repl.it allows you to quickly bring up cloud instances of a ton of different programming environments, and edit code within a powerful cloud IDE that is accessible anywhere as you might know already! Install the Packages We’ll start off by installing the two packages we need for this project: numpy to help with numerical calculations, and OpenAI Gym to serve as our simulator for our agent. Simply type gym and numpy into the package search tool on the left hand side of the editor and click the plus button to install the packages. Laying Down the Foundations Let’s first import the two dependencies we just installed into our main.py script and set up a new gym environment: import gym import numpy as np env = gym.make('CartPole-v1') Next we’ll define a function called “play”, that will be given an environment and a policy array, and will play the policy array in the environment and return the score, and a snapshot (observation) of the game at each timestep. We’ll use the score to tell us how well the policy played and the snapshots for us to watch how the policy did in a single game. This way we can test different policies and see how well they do in the game! Let’s start off with the function definition, and resetting the game to a starting state. def play(env, policy): observation = env.reset() Next we’ll initialize some variables to keep track if the game is over yet, the total score of the policy, and the snapshots (observations) of each step during the game. done = False score = 0 observations = [] Now we’ll simply just play the game for a lot of time steps, until the gym tells us the game is done. for _ in range(5000): observations += [observation.tolist()] # Record the observations for normalization and replay if done: # If the simulation was over last iteration, exit loop break # Pick an action according to the policy matrix outcome = np.dot(policy, observation) action = 1 if outcome > 0 else 0 # Make the action, record reward observation, reward, done, info = env.step(action) score += reward return score, observations The bulk of the code above is mainly just in playing the game and recording the outcome. The actual code that is our policy is simply these two lines: outcome = np.dot(policy, observation) action = 1 if outcome > 0 else 0 All we’re doing is doing the dot product operation between the policy array and the state (observation) array like we’ve shown in the concrete example earlier. Then we either choose an action of 1 or 0 (left or right) depending if the outcome is positive or negative. So far our main.py should look like this: Now we’ll want to start playing some games and find our optimal policy! Playing the First Game Now that we have a function to play the game and tell how good our policy is, we’ll want to start generating some policies and see how well they do. What if we just tried to plug in some random policies at first? How far can we go? Let’s use numpy to generate our policy, which is a 4 element array or a 4x1 matrix. It’ll pick 4 numbers between 0 and 1 to use as our policy. policy = np.random.rand(1,4) With that policy in place, and the environment we created above, we can plug them into play and get a score. score, observations = play(env, policy) print('Policy Score', score) Simply hit run to run our script. It should output the score our policy got. The max score for this game is 500, chances are is that your policy didn’t fare so well. If yours did, congrats! It must be your lucky day! Just seeing a number though isn’t very rewarding, it’d be great if we could visualize how our agent plays the game, and in the next step we’ll be setting that up! Watching our Agent To watch our agent, we’ll use flask to set up a lightweight server so we can see our agent’s performance in our browser. Flask is a light Python HTTP server framework that can serve our HTML UI and data. I’ll keep this part brief as the details behind rendering and HTTP servers isn’t critical to training our agent. We’ll first want to install ‘flask’ as a Python package, just like how we installed gym and numpy in the previous sections. Next, at the bottom of our script, we’ll create a flask server. It’ll expose the recording of each frame of the game on the /data endpoint and host the UI on /. from flask import Flask import json app = Flask(__name__, static_folder='.') @app.route("/data") def data(): return json.dumps(observations) @app.route('/') def root(): return app.send_static_file('./index.html') app.run(host='0.0.0.0', port='3000') Additionally we’ll need to add two files. One will be a blank Python file to the project. This is a technicality of how repl.it detects if the repl is either in eval mode or project mode. Simply use the new file button to add a blank Python script. After that we also want to create an index.html that will host the rendering UI. I won’t dive into details here, but simply upload this index.html to your repl.it project. You now should have a project directory that looks like this: Now with these two files, when we run the repl, it should now also play back how our policy did. With this in place, let’s try to find an optimal policy! Policy Search In our first pass, we simply randomly picked one policy, but what if we picked a handful of policies, and only kept the one that did the best? Let’s go back to the part where we play the policy, and instead of just generating one, let’s write a loop to generate a few and keep track of how well each policy did, and save only the best policy. We’ll first create a tuple called max that will store the score, observations, and policy array of the best policy we’ve seen so far. max = (0, [], []) Next we’ll generate and evaluate 10 policies, and save the best policy in max. for _ in range(10): policy = np.random.rand(1,4) score, observations = play(env, policy) if score > max[0]: max = (score, observations, policy) print('Max Score', max[0]) We’ll also have to tell our /data endpoint to return the replay of the best policy. @app.route("/data") def data(): return json.dumps(observations) should be changed to @app.route("/data") def data(): return json.dumps(max[1]) Your main.py should look something like this now. If we run the repl now, we should get a max score of 500, if not, try running the repl one more time! We can also watch the policy balance the pole perfectly fine! Wow that was easy! Not So Fast Or maybe it isn’t. We cheated a bit in the first part in a couple of ways. First of all we only randomly created policy arrays between the range of 0 to 1. This just happens to work, but if we flipped the greater than operator around, we’ll see that the agent will fail pretty catastrophically. To try it yourself change action = 1 if outcome > 0 else 0 to action = 1 if outcome < 0 else 0. This doesn’t seem very robust, in that if we just happened to pick less than instead of greater than, we could never find a policy that could solve the game. To alleviate this, we actually should generate policies with negative numbers as well. This will make it more difficult to find a good policy (as a lot of the negative ones aren’t good), but we’re no longer “cheating” by fitting our specific algorithm to this specific game. If we tried to do this on other environments in the OpenAI gym, our algorithm would definitely fail. To do this instead of having policy = np.random.rand(1,4), we’ll change to policy = np.random.rand(1,4) - 0.5. This way each number in our policy will be between -0.5 and 0.5 instead of 0 to 1. But because this is more difficult, we’d also want to search through more policies. In the for loop above, instead of iterating through 10 policies, let’s try 100 policies by changing the code to read for _ in range(100):. I also encourage you to try to just iterate through 10 policies first, to see how hard it is to get good policies now with negative numbers. Now our main.py should look like this If you run the repl now, no matter if we’re using greater than or less than, we can still find a good policy for the game. Not So Fast Pt. 2 But wait, there’s more! Even though our policy might be able to achieve the max score of 500 on a single run, can it do it every time? When we’ve generated 100 policies, and pick the policy that did best on its single run, the policy might’ve just gotten very lucky, and in it could be a very bad policy that just happened to have a very good run. This is because the game itself has an element of randomness to it (the starting position is different every time), so a policy could be good at just one starting position, but not others. So to fix this, we’d want to evaluate how well a policy did on multiple trials. For now, let’s take the best policy we found from before, and see how well it’ll do on 100 trials. scores = [] for _ in range(100): score, _ = play(env, max[2]) scores += [score] print('Average Score (100 trials)', np.mean(scores)) Here we’re playing the best policy (index 2 of max) 100 times, and recording the score each time. We then use numpy to calculate the average score and print it to our terminal. There’s no hard published definition of “solved”, but it should be only a few points shy of 500. You might notice that the best policy might actually be subpar sometimes. However, I’ll leave the fix up to you to decide! done=True Congrats! 🎉 We’ve successfully created an AI that can solve cart pole very effectively, and rather efficiently. Now there’s a lot of room for improvement to be made that’ll be part of an article in a later series. Some things we can investigate more on: - Finding a “real” optimal policy (will do well in 100 separate plays) - Optimizing the number of times we have to search to find an optimal policy (“sample efficiency”) - Doing a proper search of the policy instead of trying to just randomly pick them. - Solving other environments. If you’re interested in experimenting more with ML with pretrained models and out-of-the-box working code, check out ModelDepot! It would be really cool if the user can play the game and see how hard it is @IEATPYTHON You could definitely try to hack it out! It's probably possible if you hack around with the OpenAI gym library since you can control when a next step is taken and then you can render the output either using the native gym's rendering system or my HTML/JS version This is purely amazing well done! @ProgrammerAI you should be able to check out the whole repl here! Traceback (most recent call last): File "main.py", line 5, in <module> import gym ModuleNotFoundError: No module named 'gym' Thats what happens when I run Great! I get error messages every time I try to run the code. It looks exactly how you say it should. One line says I need to unindent because it doesn’t match other indentation. If I unindent then it says there is a syntax error. Syntax error: ‘return’ outside of function. Also when I plugged in the “random numbers” all I got was an error message. I went through line by line, everything is the same. The Repl is not working(I can’t move the cart.) Very good, I hope you win the tutorial competition!
https://replit.com/talk/learn/From-Scratch-AI-Balancing-Act-in-50-Lines-of-Python/6586
CC-MAIN-2021-25
refinedweb
3,013
71.04
I'm trying to use namespaces and have got them working but I am a little confused. Am I right in saying the advantages are: Correct? Here's where I'm confused: Thanks. Consider taking a look at some projects that use namespaces. Doctrine 2, Symfony 2, Silex etc. Namespaces can make your code easier to read and maintain by listing classes used in given file along the top (use statements) and then allowing for shorter class names (aliases). But stick to using them the way the php folks intended them to be used. Lots of people get into trouble trying to apply namespace concepts from other languages. Thanks, I do like the concept of namespaces and am going to stick with it. Although I don't like the look of \ in my code I do like the autoloading. So, is it a given that once you set a namespace it never changes? My main gripe as a project gets bigger you may wish to split packages—or it may turn out a class is better in a different package. It makes it harder to update the code. It's worth mentioning that it's not necessary to use namespaces if you want to use autoloading. Thanks, yes. I should have said the other good reason is, of course, I know my Database class won't class with anyone else's. This topic is now closed. New replies are no longer allowed.
http://community.sitepoint.com/t/help-understanding-php-namespaces/31865
CC-MAIN-2015-22
refinedweb
242
82.95
I noticed on a datasheet that ATtiny44 and ATtiny84 have built in temperature sensors. Is there a way to access the value of the chip's temperature? I know its not good for ambient air temperature but curiousity runs wild with me. Sure, the datasheet describes it. I fiddled with it once on an ATmega328P but didn't really spend enough time with it to even know if I had it working right. Here is a sketch that seems to work with an ATmega328P-MU. I get around 365mV, which would be about 75°C according to the example in the datasheet. Room temp is currently around 26°C, so that seems a bit high, but it’s not a precise thing. Can the internal chip temp be that hot? The package certainly isn’t that hot. It does respond fairly quickly (increases) when I put my finger on it. So maybe it’s just not well-calibrated. I thought maybe this could be coded just with standard Arduino function calls, but I don’t think so; I ended up manipulating the registers directly. Something similar should work with the ATtinies, but the register definitions are not identical, so be sure to review them. #include <Streaming.h> // void setup(void) { Serial.begin(115200); } void loop(void) { float v; ADMUX = 0xC8; //channel 8 ADCSRA = 0xC7; //start the conversion while (ADCSRA & _BV(ADSC)); //wait for it to complete v = 1.1 * ADC / 1024.; Serial << _FLOAT(v, 3) << endl; delay(1000); }
https://forum.arduino.cc/t/attiny44-84-built-in-temperature-sensor/114997
CC-MAIN-2022-27
refinedweb
248
75.5
30 December 2008 23:57 [Source: ICIS news] (Adds updates throughout) HOUSTON (ICIS news)--A day after Rohm and Haas’ stock took a 16% hit, shares rebounded 11.92% on Tuesday to $59.70 on speculation that the Philadelphia-based company may still be bought by Dow Chemical. Dow’s share price on the New York Stock Exchange inched up slightly on Tuesday to $15.55, an increase of 1.5%, after losing 19% on Monday in the wake of the demised K-Dow deal and debt rating reductions by Moody’s and Standard and Poor’s. Dow is under pressure to quickly make a final decision regarding the planned $18.8bn (€13.3bn) acquisition of Rohm and Haas following the collapse of the K-Dow joint venture with ?xml:namespace> The K-Dow joint venture would have provided $9bn in cash payments to Dow, including a planned $1.5bn distribution from K-Dow. The acquisition of Rohm and Haas and the lack of cash from the failed K-Dow venture would put Dow under a huge amount of debt, analysts have noted.. Dow is under pressure to act quickly. Under its agreement with Rohm and Haas, the buyout price of $78/share will rise each day that Dow does not sign off on the acquisition after 10 January. However, Dow may still be able to walk away from its takeover of Rohm and Haas “net cash positive,” analysts at HSBC said in a research note. Also, Dow would have to prove in court that HSBC, for its part, remained “overweight” on Dow Chemical with a share price target of $30.00, based on an attractive valuation and a dividend yield of over 8% which Dow was not likely to cut, it said. ($1 = €0.71) Additional reporting by Stefan Baumgarten, Joseph Chang and Brian Ford
http://www.icis.com/Articles/2008/12/30/9181142/rohm-and-haas-shares-rebound-on-takeover-pressurerohm-and-haas-shares-rebound-on-takeover-pressure.html
CC-MAIN-2015-06
refinedweb
306
71.44
If you have worked a lot with MOSS you probably know how to make new page layouts. But if you create new page layouts you might sometimes wonder that how could I add some common functionalities to my page layout pages. One example could be localization. You have decided that Variations isn't the way to go in your case, but you still want to have different site structures for different languages... and of course you want to have texts localized. Or you want to change your master page for some reason on the fly... one example could be for printing reasons. Or even wilder... you want to change you page layout to another! You could do this kind of stuff pretty easily if you create your own PublishingLayoutPage class that has support your new functionalities. I'm going to explain how you can do that with SharePoint Designer and Visual Studio. Create new class that will extend the functionality of PublishingLayoutPage I started my journey by creating new Class Library project. I named it "Microsoft.MCS.Common" (since I work in MCS inside Microsoft... cool naming right :-). I added new class and named it PublishingLayoutPageEx. I inherited that from PublishingLayoutPage which is class behind page layouts. Where did I got that class name? Well I just opened ArticleLeft.aspx with SharePoint Designer and checked the first line: <%@ Page language="C#" Inherits="Microsoft.SharePoint.Publishing.PublishingLayoutPage, Microsoft.SharePoint.Publishing, Version=12.0.0.0,Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> So it was pretty obvious that if I want to extend the functionality of the basic publishing page, I needed to inherit from it. At this point my code looked like this (not much since we just started): } And now I'm ready to test my new class in action. I just added strong name key, compiled and put it in the GAC. And then I changed the ArticleLeft.aspx to use my new class: <%@ Page language="C#" Inherits="Microsoft.MCS.Common.PublishingLayoutPageEx, Microsoft.MCS.Common,Version=1.0.0.0, Culture=neutral,PublicKeyToken=b1e9400215c03709" %> <small sidetrack to .NET Reflector> If you're interestested in the stuff that's implemented in PublishingLayoutPage, then you can play around with incredible tool: Lutz Roeder's NET Reflector: In just few clicks we can see that there is some MasterPageFile retrieving in OnPreInit: </small sidetrack to .NET Reflector> If you now try your new PublishingLayoutPageEx in action you'll get this kind of error message:: Server Error in '/' Application. Parser Error Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately. Parser Error Message: The base type 'Microsoft.MCS.Common.PublishingLayoutPageEx' is not allowed for this page. The type is not registered as safe. Source Error: Source File: /_catalogs/masterpage/ArticleLeft.aspx Line: 1:<SafeControl Assembly="Microsoft.MCS.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b1e9400215c03709" Namespace="Microsoft.MCS.Common" TypeName="PublishingLayoutPageEx" Safe="True" AllowRemoteDesigner="true" /> And then hit F5 in your browser and you should be all set. Now you have base what we're going to extend in next. Add localization support to your pages If you haven't played with ASP.NET Resource files, then you should take small detour into localization quickstart. So now you know about .RESX files 🙂 I created Example.resx, Example.en-US.resx and Example.fi-FI. I have added only two words to the resource files: - House: - en-US: House - fi-FI: Talo - You: - en-US: You - fi-FI: Sinä I copied those resource files to my applications App_GlobalResouces folder: C:\Inetpub\wwwroot\wss\VirtualDirectories\80\App_GlobalResources Now I modified my default_Janne.master page so that it would receive text from my resource files. I added following line just before </body> in master page. <asp:Literal <-> <asp:Literal We have now added resource files and modified master page so that it will take text from our resource file. Let's just add code to our new class so that we could change the language on the fly. protected override void OnPreInit() 20 { 21 base.OnPreInit(); 22 this.InitializeCulture(); 23 } 24 25 protected override void InitializeCulture() 26 { 27 if (Request["mylang"] != null) 28 { 29 Thread.CurrentThread.CurrentCulture = new CultureInfo(Request"mylang"].ToString()); 30 Thread.CurrentThread.CurrentUICulture = new CultureInfo(Request["mylang"].ToString()); 31 } 32 33 base.InitializeCulture(); 34 } 35 } 36 } And now we can change the language from URL: Here is result without the mylang parameter: Of course you might not want to change your language by url parameter 🙂 This is just sample that you CAN do that. Maybe it would be much wiser to use some kind of site structure for localization. But I'll leave that to you... Change master page on the fly Now we want to make something fancier... like changing the master page on the fly. You could want to use this for print layouts, smaller screen, mobile etc. But anyway.. You just might want to do that sometimes 🙂 So let's throw some code in here and see what happens: ... 1 protected override void OnPreInit() 2 { 3 base.OnPreInit(); 4 if (Request["Print"] != null) 5 { 6 this.MasterPageFile = "/_catalogs/masterpage/BlueBand.master"; 7 } 8 } ... On lines 4 to 6 we have just check that if there is mysterious Print parameter set. If that is set, we'll change the master page to nicely hardcode one. Let's see what happens on our browser: So the result is quite easy to see... our master page changed from default_janne.master to BlueBand.master. Change the page layout Before I start... I'm going to give credit of this idea to Vesa Juvonen (colleague of mine at MCS who also works with SharePoint). He said that this would be interesting thing to checkout. And since I happened to have some code ready we tried this stuff on my environment. But he's going to create full solution of this page layout change and publish it in his blog. So you probably want to check that place out too. Okay.. but let's get back to the subject. This might sound a bit strange but still... sometimes you might want to change page layout after the page has been created. Consider the Article Page content type which is OOB content type in SharePoint. It has 4 different kind of page layouts. User could have selected Image on right layout and has filled the page with data. After a while you want to change it to another layout.... BUT there isn't easy way to do that... unless we'll extend our nice class again. Idea is take (again) some nice url parameter that tells the destination page layout. In this example I'll just take integer which is used to get the correct page layout from array of possible page layouts of this content type. And yes... I know that this code sample has a lot to improve... It just gives you ideas. Let's throw some code in here and see what happens: ... 1 protected override void OnPreInit() 2 { 3 SPContext current = SPContext.Current; 4 if (current != null && 5 Request["changepagelayout"] != null && 6 Request["done"] == null) 7 { 8 SPWeb web = current.Web; 9 // We need to allow unsafe updates in order to do this: 10 web.AllowUnsafeUpdates = true; 11 web.Update(); 12 13 PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web); 14 PageLayout[] layouts = publishingWeb.GetAvailablePageLayouts(current.ListItem.ContentType.Parent.Id); 15 PublishingPage publishingPage = PublishingPage.GetPublishingPage(current.ListItem); 16 publishingPage.CheckOut(); 17 // This is the magic: 18 publishingPage.Layout = layouts[Convert.ToInt32(Request["changepagelayout"])]; 19 publishingPage.Update(); 20 publishingPage.CheckIn("We have changed page layout"); 21 22 SPFile file = current.ListItem.File; 23 file.Publish("Publishing after page layout change"); 24 // We have content approval on: 25 file.Approve("Approving the page layout change"); 26 Response.Redirect(Request.Url + "&done=true"); 27 } 28 base.OnPreInit(e); 29 } ... And you can right away see from code that there isn't any checks or any error handling. So this code is only for demonstration purposes and you shouldn't take it any other way.... but here we can see the results after user has type in parameter changepagelayout=1 (Image on left): And here is page if parameter is 2 (Image on right). If you look at the code on line 14 where page layouts are retrieved... I'm using Parent of the current content type. You might ask why... But the reason is simple since your content type from the list actually inherits the Article Page content type from Site collection level. So if you would use ListItem.ContentType you wouldn't get those 4 page layouts of Article Page. Insted you need to get the parent of the content type in the list and then you get 4 different page layouts. Makes sense if you think how inheritance in SharePoint works. If you wonder that done parameter I'm using... It is just helper to avoid recursive page layout change 😉 Note: If you look at the code you probably already noticed that it's not changing the layout for this rendering... it has changed the page layout permanently. Of course you can change it back if you want to. Summary You can use a lot of stuff from ASP.NET right in your SharePoint page layouts. I can't even imagine all the capabilities of this but I'm just going to give you brief list what I can think of now: 1) Localization: - This one is obvious 🙂 I live in Finland and we need to deal with this in every project. 2) Change the master page - Print layouts - Mobile UIs 3) Change page layout - If you had created page but you later on want to change to more suitable one... here's how you can do it I hope you got the idea of this post. I know I could improve those samples a lot, but I just wanted to share my idea and give you the opportunity to make it much better than I did. Anyways... happy hacking! J PingBack from Hello Janne, Thanks for that great article. But I’m still strugling with a couple of things :(. I inherited my page from the custom PublishingLayoutPageEx and it wend fine, All sharePoint words became in the right language exept the webparts?. All webparts stay in english despite what culture you using, is that normal? Or is a webparts rendered differently than the Page? Hi koen! Web parts don’t differ in that sense that if their made using resources, then they work fine. Here’s an example: writer.Write("Resource: " + HttpContext.GetGlobalResourceObject("Example","House").ToString() + "<br/>"); If you add that to you web part then you get example same text than in your page. What is the exact web part your having problems with? It could be that it’s using XSL Style Sheets and there is hardcoded text. Is that web part your own or OOB web part? I hope my answer helped a little bit. Feel free to ping me if you didn’t get the idea. Anyways… Happy hacking! J Hi janne, First of all, thanks for the quick response :). I’m not using a custom webpart. Instead I inserted a view of the common task list on the page and this view will always stay in english, nomatter what culture you set your thread to. Really strange. If you go and look at the structure of the task list (feature at C:Program FilesCommon FilesMicrosoft Sharedweb server extensions12TEMPLATEFEATURESTasksListTasksSchema.xml) you can see it uses resources stored in C:Program FilesCommon FilesMicrosoft Sharedweb server extensions12Resources. I have installed multiple language packs on my SHarepoint server so that every resource file is there in different language but for some strange reason it refuses to use it :). If I use variations, it will translate the tasklist in different languages but the problem is that I can use only one tasklist and that’s wy I used your solution. Hi Koen! Thanks for asking because it was really nice to dig on this one. I like to solve problems and this was definately a nice one 🙂 Okay.. I’ll explain what I did. 1) I first verified your problem by creating same situation. And you’re absolutely right! Web Parts don’t actually change texts 🙁 2) Started digging with .resx files and DLLs with Reflector. 3) Noticed that behind the scenes there is CoreResources class that handles translations. And if you look at the following code, does this ring a bell on you: static CoreResource() { _aIntl = Assembly.Load("Microsoft.SharePoint.intl, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"); _SPRM = new ResourceManager("Microsoft.SharePoint", _aIntl); _WebPartPageRM = new ResourceManager("Microsoft.SharePoint.WebPartPages.strings", _aIntl); } 4) You start wondering why there is _WebPartPageRM (and is different from the other texts) and where are those text then. 5) Take Reflector and open "Microsoft.SharePoint.intl, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c". Under it there is Resources and of course: Microsoft.SharePoint.WebPartPages.strings.resources. 6) Search text that you know some web part page uses 7) You have found the place for your text. Okay.. so now we have this "neutral" dll where are resources. But I don’t have access to systems that has multiple languages installed, so I don’t know that is that DLL available for different cultures. I hope that this gives you the answer your looking for… If you can dig your system too and you could give me feedback that you have verified my idea. Anyways… Happy hacking! J I just wanted to add a note for my previous comment: "Web Parts don’t actually change texts". But of course your own web parts change languages if you use resources 🙂 Just to make this clear. J Janne, You are right, I have found the CoreResource en the resource DLL’s. In a multilingual environment, you have a dll for each language: Microsoft.SharePoint.intl.dll –> Microsoft.SharePoint.resources Microsoft.SharePoint.WebPartPages.strings.resources microsoft.sharepoint.intl.resources.dll Language Dutch) –> Microsoft.SharePoint.nl.resources Microsoft.SharePoint.WebPartPages.strings.nl.resources microsoft.sharepoint.intl.resources.dll Language French) –> Microsoft.SharePoint.fr.resources Microsoft.SharePoint.WebPartPages.strings.fr.resources When I look at the resource string of a common task list, for instance the Priority field, you have following schema: <Field ID="{a8eb573e-9e11-481a-a8c9-1104a54b2fbd}" Type="Choice" Name="Priority" DisplayName="$Resources:core,Priority;" SourceID="" StaticName="Priority"> <!– _locID@DisplayName="camlidT2" _locComment=" " –> <CHOICES> <CHOICE>$Resources:core,Priority_High;</CHOICE> <CHOICE>$Resources:core,Priority_Normal;</CHOICE> <CHOICE>$Resources:core,Priority_Low;</CHOICE> </CHOICES> <MAPPINGS> <MAPPING Value="1">$Resources:core,Priority_High;</MAPPING> <MAPPING Value="2">$Resources:core,Priority_Normal;</MAPPING> <MAPPING Value="3">$Resources:core,Priority_Low;</MAPPING> </MAPPINGS> <Default>$Resources:core,Priority_Normal;</Default> </Field> So, when I search for Priority_High, Priority_Normal, Priority_Low, I found nothing in the resource files. I can found it back in the resource file C:Program FilesCommon FilesMicrosoft Sharedweb server extensions12Resourcescore.resx C:Program FilesCommon FilesMicrosoft Sharedweb server extensions12Resourcescorecore.nl-nl.resx C:Program FilesCommon FilesMicrosoft Sharedweb server extensions12Resourcescorecore.fr-fr.resx Also, I have seen that, like you said, there is a clear difference between plain SharePoint and a sharepoint WebPartPage internal static string GetString(CultureInfo culture, ResourceGroup rg, string name, params object[] values) { string text = null; StringBuilder builder; int num3; switch (rg) { case ResourceGroup.SharePoint: text = _SPRM.GetString(name, culture); case ResourceGroup.WebPartPage: text = _WebPartPageRM.GetString(name, culture); } So, I followed the trace from above in the listviewWebpart but so far I don’t see it yet. I keep you posted, I hope you will do it also Regards, Koen Hi Janne I’m having a few problems with this. Firstly I’m at the point where it’s time to register in the GAC. Is it possible to register this Class Library in the bin folder of the web application (site collection) rather than in the GAC? I’ve tried placing the dll (which is strong named) into InetpubwwwrootwssVirtualDirectoriesMyAppbin folder and putting the entry in the web.config with the correct details (including the PublicKeyToken) but I get the Parser Error you show above still. We have been able to get our webparts working by doing the above. I thought I’d try registering it in the GAC on the server, but my first hurdle was that the gacutil was for version 1.1 only and would not accept it. The admin control panels also only have the 1.1 .net configuration control panel. Obviously .net 2 is on there (as SP is running) but I’ve double checked IIS which confirms it is using 2.0. I’ve copied up gacutil for 2.0 and it says it is registering it, but does not appear in the list (and I still get this parser error). Any ideas? Preferably I’d like to get this class running from the web bin. I’ve been able to get it into the GAC now, but I release the error I am getting is different to the one on this page. I get this error in all cases… Parser Error Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately. Parser Error Message: Could not load the assembly "…" Hi Andy! So now your’re having the "Could not load the assembly" error? I think you get the error because it’s not probably installed to the GAC. Did you use Visual Studio Command prompt and GACUTIL /i your_assembly_here? And did you verify that version number of gacutil is "Version 2.0.50727.42"? Or how did you install it to gac? Because if it’s installed to GAC properly and that "Inherits=…" part is also correctly set in page layout then this should be fine. Please give comment if that didn’t solve your problem. Anyways… happy hacking! J Hi Janne, the server I am installing to was missing the v 2.0.5… gacutil but I copied a version of it to the server and used: gacutil -i MyCompany.PublishingLayoutPageEx.dll which reported it was OK. I did gacutil -l MyCompany.PublishingLayoutPageEx and it showed up. In my layout page (I made a copy of Article Left and modified that) I changed the top to read: <%@ Page language="C#" Inherits="MyCompany.PublishingLayoutPageEx,MyCompany,Version=1.0.0.0,Culture=neutral,PublicKeyToken=1294058909b4416a" %> The PublicKeyToken is correct (checked with Net Reflector). In VS2005 I have this: using System; using System.Collections.Generic; using System.Text; using System.Web.UI; using Microsoft.SharePoint.Publishing; using Microsoft.SharePoint; namespace MyCompany { public class PublishingLayoutPageEx : PublishingLayoutPage { public PublishingLayoutPageEx() : base() { } } } And I have added references to System.Web and the two sharepoint dll’s. My AssemblyInfo.cs properties show Assembly name: MyCompany.PublishingLayoutPageEx and Default namespace as MyCompany. I am new to both SharePoint and .NET but the instructions on your blog are clear enough and I’m not sure what I might be missing or doing wrong. Even after an iisreset I get that error with "Could not load the assembly". Hi Andy! It seems that there is conflict with these two: MyCompany.PublishingLayoutPageEx.dll and Inherits="MyCompany.PublishingLayoutPageEx,MyCompany,Version=1.0.0.0,… I think the Inherits should be: MyCompany.PublishingLayoutPageEx,MyCompany.PublishingLayoutPageEx,… (just add ".PublishingLayoutPageEx") That looks like the problem… But you’re close the finish line already 🙂 Anyways.. happy hacking! J Thank you so much Janne I’m getting closer. I’m now getting "Parser Error Message: Could not load type" so at least it is being recognised now and I can go back over my previous steps to check its all set up correctly. Got it more or less sorted now. For information on my last problem, that was caused by an error in case (Mycompany v MyCompany). Thank you so much for the help, I wonder if I could ask one more question. In SharePoint designer, the copy of ArticleLeft.aspx I created is stating "Master Page error – The page has controls that require a Master Page reference, but none is specified. Attach a Master Page, or correct the problem in Code View." Attach a Master Page is a link but does not do anything and Code View is a link and highlights my <@ Page line at the top. I should add that currently my DLL sits in the sites bin folder and not the GAC as I originally wanted it just for my site collection and not anything else on the server, is the the problem or should I be looking elsewhere? Hi Andy! You can define the master page at the Page directive like this: … MasterPageFile="~/_layouts/default.master" … After that SPD should be fine with it. I think you can just deploy to your bin. I don’t see any problems with that. Anyways… happy hacking! J Dear Janne, I want to publish the News articles without text formatting. I mean I want to modify ArticleLeft.aspx PageLayout to display Left aligned image and text only. MOSS users can make news entries with Image on the left template. They may copy some news and texts from Internet and paste them into the content of news entry. But there would be text formatting at that entries. What I need to do is to display only Image with text without formatting. Is it possible to create new PageLayout to display like that? Can you give me some ideas how to do? Please kindly advice me. I hope your reply. Myo This is powerful stuff, and thanks to this I can do a lot more powerful MOSS WCM custom development. I was wondering if you had tried to do the masterpage change using a custom HttpModule? I have been trying to do it using the following code: public class Hook : IHttpModule { public void Init(HttpApplication context) { context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute); } void context_PreRequestHandlerExecute(object sender, EventArgs e) { Page page; IHttpHandler handler = HttpContext.Current.Handler; page = handler as Page; if (page != null) page.PreInit += new EventHandler(page_PreInit); } void page_PreInit(object sender, EventArgs e) { Page page = sender as Page; if (page != null) { string strUrl = "/Docs/_catalogs/masterpage/"; SPWeb web = SPControl.GetContextSite(HttpContext.Current).OpenWeb(); SPUser user = web.CurrentUser; if (user == null) strUrl = ""; else strUrl += "BlueBand.master"; if (strUrl.Length > 0) page.MasterPageFile = strUrl; } } public void Dispose() { } } I works like a charm on wss 3.0, but MOSS publishing pages just ignores it. The preInit event hook is set on the page, but it is never called. I’m all out of ideas, any comments would be greatly appreciated. Hello Janne, I am interested in the code to change the PageLayout associated with a PublishingPage. To my mind, the PublishingPage represents the data, and the PageLayout represents the view on that data. Consequently the view should be selectable dynamically. I would expect to be able to place webparts on the PageLayout aspx page which connected to Field Values from the PublishingPage via FieldControls. Thus the overall content displayed on a Publishing page would include PublishingPage columns, and adhoc data from else where, via connected web parts. I would expect to control rights to the edit the web parts discretely from the rights to edit the columns of a PublishingPage via a PageLayout page (ie someone may be able to edit web parts, but not the PublishingPage data, and vice versa). However I have two concerns over whether I am off track with these thoughts: 1) I not sure how to select the PageLayout dynamically at render time. The closest I have got is to derive from the TemplateRedirectionPage, and set the PublishingPage.Layout property in it’s PreInit event (somehow). 2) An article "How to Upgrade an Area based on a Custom Site Definition" at says "Webpart associations are also based on the actual publishing page" I am not sure of the consequences of this. I would be very interested to have your response to this. Many Thanks Martin Kristian, did u find a solution to the problem? I am having the same issue I found a great article Janne Mattila. discuses that if the layout page just inherit from Microsoft.SharePoint.Publishing.PublishingLayoutPage… great article…..helped med a lot namespace Microsoft.MCS.Common { public class PublishingLayoutPageEx : PublishingLayoutPage { public PublishingLayoutPageEx() : base() { } } } I am getting bellow error " : base() " in this line Could not load file or assembly ‘Microsoft.SharePoint.Library, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c’ or one of its dependencies. The system cannot find the file specified. PublishingLayoutPage vs. WebPartPage U cannot always inherit from PublishingLayoutPage, If you are not using Default. Master Read this article Thanks for the tip on PublishingLayoutPage changing the MasterPageFile on OnPreInit(). See how I changed it back in my Page scope OnPreInit() override. Thanks for this article. very helpful. Sorry, I have a basic question — where do i get the class library project template from? do you mean any regular class? I am trying to understand, what would i need to start working on this. Thanks in advance! Overview The National Native Title Tribunal of Australia assists people to resolve native title issues i couldnt get your Print trick to work. For one, the page (either master page or page layout) says that there is no suitable method to override for OnPreInit so I tried Page_PreInit instead. This didnt work on the master page and while it executed on the page layout it did not change my master page. Is there an update call missing? did you test your code? oops – it works, I just didnt read the first half of the article and jumped to the code :-/ sorry! Hi, Please correct me if I am wrong. What I under stand from above is that this would work for custom webparts but not for OOB webparts.
https://blogs.msdn.microsoft.com/jannemattila/2007/04/13/adding-functionalities-to-pages-by-inheriting-publishinglayoutpage/?replytocom=303
CC-MAIN-2018-30
refinedweb
4,311
58.89
Hello World! Let’s do instant gratification stuff. First, we need a Scheduler whenever asynchronous execution happens. // We need a scheduler whenever asynchronous // execution happens, substituting your ExecutionContext import monix.execution.Scheduler.Implicits.global // Needed below import scala.concurrent.Await import scala.concurrent.duration._ Task, the Lazy Future For using Task or Coeval, usage is fairly similar with Scala’s own Future, except that Task behaves lazily: import monix.eval._ // A specification for evaluating a sum, // nothing gets triggered at this point! val task = Task { 1 + 1 } Task in comparison with Scala’s Future is lazy, so nothing gets evaluated yet. We can convert it into a Future and evaluate it: // Actual execution, making use of the Scheduler in // our scope, imported above val future = task.runToFuture // future: monix.execution.CancelableFuture[Int] = [email protected] We now have a standard Future, so we can use its result: // Avoid blocking; this is done for demostrative purposes Await.result(future, 5.seconds) // res8: Int = 2 Observable, the Lazy & Async Iterable We already have the Scheduler in our local scope, so lets make a tick that gets triggered every second. import monix.reactive._ // Nothing happens here, as observable is lazily // evaluated only when the subscription happens! val tick = { Observable.interval(1.second) // common filtering and mapping .filter(_ % 2 == 0) .map(_ * 2) // any respectable Scala type has flatMap, w00t! .flatMap(x => Observable.fromIterable(Seq(x,x))) // only take the first 5 elements, then stop .take(5) // to print the generated events to console .dump("Out") } Our observable is at this point just a specification. We can evaluate it by subscribing to it: // Execution happens here, after subscribe val cancelable = tick.subscribe() // 0: Out-->0 // 1: Out-->0 // 2: Out-->4 // 3: Out-->4 // 4: Out-->8 // 5: Out completed // Or maybe we change our mind cancelable.cancel() Isn’t this awesome? (✿ ♥‿♥) You are viewing the documentation for the latest Monix 3.x series. If you're looking for the older 2.x click here! If you're looking for the older 2.x click here!
https://monix.io/docs/3x/intro/hello-world.html
CC-MAIN-2019-51
refinedweb
345
52.26
05 August 2010 14:18 [Source: ICIS news] (adds detail throughout) LONDON (ICIS)--A unit at Pardis Petrochemical Company's (PPC's) complex in Iran has been destroyed by fire following an explosion at the facility, despite firefighters managing to contain the blaze, Iranian news services said on Thursday. It is still unknown what type of unit was destroyed. It was reported that a ruptured gas pipe caused the explosion at the PPC complex, which left five workers dead and injured two others on Wednesday. The second-phase PPC plant, which produces urea and ammonia, was inaugurated last week, according to Iranian news services. The factory is located in the port city of Assalouyeh, south of ?xml:namespace> PPC started commercial production at its new 1.1m tonne/year urea plant at The company’s 680,000 tonne/year ammonia plant, situated at the same complex, started production in February 2010.
http://www.icis.com/Articles/2010/08/05/9382390/explosion-destroys-unit-at-pardis-petrochemical-complex-in-iran.html
CC-MAIN-2015-11
refinedweb
151
51.18
Created on 2003-02-08 23:50 by quevedo, last changed 2003-02-09 03:20 by tim.peters. This issue is now closed. Hello world. Well, let's see. When you open a file with "write-only" permission, then you write some in and after that you print the text contained in the file, you get your code (or almost all) and some other characters by output (See 1 ). - 1: a) Code: #!/usr/bin/python file = open("test.txt", "w") file.write("We love Python") text = file.read() print text b) Output: ÿÿ pen("test.txt", "w") file.write("We love Python") text = file.read() print text ext ufferTypes tuples TupleTypes lists ListTypes dicts DictTypes DictionaryTypes _fs FunctionTypes LambdaTypes func_codes CodeTypes RuntimeErrors gs GeneratorTypes _Cs ClassTypes _ms UnboundMethodTypes _xs InstanceTypes MethodTypes lens BuiltinFunctionTypes appends BuiltinMethodTypes ModuleTypes files FileTypes xranges XRangeTypes TypeErrors exc_infos tbs TracebackTypes tb_frames FrameTypes AttributeErrors slices SliceTypes Ellipsiss EllipsisTypes __dict__s DictProxyType(( s IntTypes tbs BuiltinFunctionTypes BooleanTypes _Cs UnboundMethodTypes StringTypes BuiltinMethodTypes FloatTypes DictionaryTypes TypeTypes DictProxyTypes _fs GeneratorTypes InstanceTypes ObjectTypes DictTypes FileTypes syss EllipsisTypes Strý% Lÿh HNh ListTypes MethodTypes TupleTypes ModuleTypes FrameTypes LongTypes BufferTypes TracebackTypes gs CodeTypes ClassTypes _xs UnicodeTypes SliceTypes ComplexTypes LambdaTypes FunctionTypes XRangeTypes NoneType( ( s C:\PYTHON23\lib\types.pys ? sr s | i i ? Sd S( N( s selfs datas itervalues( s self( ( s C --------------------------------------------------- But if you try this without writing to the file you get just an error (See 2). - 2: a) Code: #!/usr/bin/python file = open("test.txt", "w") text = file.read() print text b) Output: Traceback (most recent call last): File "tralara.py", line 3, in ? text = file.read() IOError: [Errno 9] Bad file descriptor ------------------------------------------------ It's stupid, I know. Why somenone would want to read a file after writing to it ? Don't know, I've discovered this by error ;) Tested in Python 2.3 Beta (Win32). Happy coding friends. Logged In: YES user_id=33168 I cannot reproduce on Linux, I'm guessing this is a windows bug. Logged In: YES user_id=31435 Python doesn't implement files, the operating system and platform C libraries do that. If the same thing happens in a C program, there's no hope. Which version of Windows were you running (their file implementations aren't the same, especially not 95/98/ME vs NT/2000/XP)? Logged In: YES user_id=707875 Windows 98 Second Edition ;) Logged In: YES user_id=31435 Figures <wink>. I tried this C program on Win98SE, using Microsoft's MSVC 6: #include <stdio.h> #include <stdlib.h> void main() { char buf[1000]; size_t n; FILE *f = fopen("temp.txt", "w"); fprintf(f, "%s\n", "Hello, world!"); memset(buf, ' ', sizeof(buf)); n = fread(buf, 1, sizeof(buf), f); printf("read %d chars, ferror is %d, feof is %d\n", n, ferror(f), feof(f)); } It didn't complain. The output was read 1000 chars, ferror is 0, feof is 0 Since the OS doesn't complain, there's really nothing Python can do about it short of writing our own file implementation, and that's a huge project. When I boosted the buf size in the above to 10000, it said it read 4082 characters, suggesting it's just reading whatever bits were left on the disk and sucked into its internal buffer. File temp.txt was 4097 bytes when the program ended. Since Python isn't doing any of this, I'm closing this as Windows, 3rdParty, and WontFix. BTW, I use Win98SE too at home, but I don't expect it to act like a real operating system <wink>.
https://bugs.python.org/issue683160
CC-MAIN-2020-50
refinedweb
589
66.54
Archives Open Court's "Popular Culture and Philosophy" Series I've been reading several volumes of Open Court's series on popular culture and philosophy. Among the titles already in print: .NET v.2.0 makes using custom cultures way easier Last year, I did a tutorial on developing custom cultures for your applications, "Globalizing ASP.NET Applications with Non-Standard Languages", showing how one could somewhat easily develop a custom type to use for languages either not supported in v.1.0 of the .NET Framework, or basically, not in existence at all. Shawn Steele from Microsoft just gave me the 411 on some new features in Whidbey to make this process even easier, namely through using the System.Globalization.CultureAndRegionInfoBuilder class. (He also mentioned that in contrast to the method used by my earlier article, MS doesn't recommend deriving custom types from System.Globalization.CultureInfo anymore). Shawn's got some cool stuff on it at and. Junfeg Zhang's also got something on it at. Thanks fellas!. :) Beyond the glitz and glamour... OK, I had my moment of gratuitous self-indulgence when I verbally patted myself on the back for having won an award for "Best Regional News Site" for my work with KUAM.COM. I'm seriously more proud of my colleague and longtime friend, Mindy Fothergill, who also won Best Documentary for her incredibly personal story "Finding My Roots", in which she, an adoptee who hadn't seen her birthmother since she was 3, made the trek back to Korea to meet her for the first time in 21 years. Absolutely emotional stuff, and we're phenomenally in awe of her courage to do so. That I could never do, much less document and broadcast it. I've known and worked with Mindy for 5 years, but we know each other like it's been 15. I'm extremely honored to win this alongside her. KUAM.COM wins "Best Regional News Site" award Yeah! Today was a pretty sweet day, with the news that my labor of love for the past 5 years, my company's site, won the prestigious Edward R. Murrow Award as outstanding regional news site for Guam, Hawaii, California and Nevada. We represented markets of like size and traffic levels within those areas, so this is a real treat and honor. It's always nice to be appreciated for your labors, especially by your peers and people that really know what you go through and the ins and outs of the biz. We've long been the fan favorite, and this is gravy, baby. I actually was informed yesterday by a rep from the committee, but it's official today. Is that a raise I smell? Why doesn't VH-1 do DVDs? One thing that really confounds me as a marketing major, a TV industry professional and lifelong critic of other people's work is why VH-1, despite all it's phenomenal success and acclaim, especialy over the last 4 years, doesn't get more into merchandising its shows and series by making them available on DVD. Comedy Central really had revolutionized the practice of cashing in on its shows by selling past seasons of its biggest hits, like "Chapelle's Show", "South Park", and "Reno 911". And with VH1 currently dominating the market for niche-and-nostalgia series (i.e., "I Love the 80s", "I Love the 70s", "The Fabulous Life Of...", et al.) one would think this would make for a perfect sales opportunity. Hell, if I were a VH-1 marketer, I'd be foaming at the mouth to be able to take on this project. One might think that Brian Grazer, the TV genius who produced the first season of "South Park" and then moved to an executive role at VH1, would be in favor of such a strategy. Not having the privilege of knowing or talking to Brian, I wouldn't know. Both networks recycle their programming more than a hobo does underwear, and in Comedy Central's case, it still garners millions of viewers tuning in every night....to watch stuff they've seen a thousand times before AND own on DVD. Maybe it's in the works, maybe the third-parties that produce the series and shows on VH1 would demand too much in royalties, maybe there's something else afoot, I admittedly don't know. Would be nice though. Care for a snowcone from Hades? JSalas uses VS.NET 2003 It's no secret that I'm not a big fan of the Visual Studio .NET IDE. Don't get me wrong....I loves me some VS2K5, but I've not really gotten off on its predecessors, what with the forced code-behind model, layers upon layers of files and extra gimmicks that take away from the web development purist I pride myself in being. Give me ASP.NET Web Matrix, Query Analyzer, and Notepad and I'm one blissful person. (Also, not being a computer science or engineering major - I have a BBA in Marketing...yikes! - I like writing code, as it makes me feel smart.) That having been said, you may throw tomatoes...now. I've been using my copy of VS.NET 2003 extensively over the last few weeks, getting ready for my company's NCAA March Madness Challenge, an online contest using the tournament bracket control available from TourneyLogic. I don't normally use third-party products, but the control is best used with Microsoft's IDE, and the API was so extensive I couldn't not use it if I was to finish my project in time for the tournament. And by all that is holy...I like it. The one thing I have enjoyed about the IDE since I started messing with the ealy beta versions in 2002 was the ease for XML web services. But I've enjoyed several aspects of the IDE, more so than I thought I would, beyond IntelliSense. Go figure. Was that a pig I saw flying outside? Rediscovering C#: prepopulated constructors One thing I've picked up this week is a rarely-used constructor overload (at least within ASP.NET communities) in C#m in which a class instance's members are pre-populated. Take for example the following sample NewsStory type: public class NewsStory { // data members private string _title; private string _author; // properties public string Title { get { return this._title; } set { this._title = value; } } public string Author { get { return this._author; } set { this._author = value; } } // constructors public NewsStory(string title,string author) { this._title = title; this._author = author; } public NewsStory() : this("Man learns new C# constructor trick.","Jason Salas") {} } Take note of the latter of the two constructors, in pre-defining a class instance with data. Obviously, this isn't useful in a case where you'd be running news stories, but can be quite helpful in cases where you'd use fairly consistent numeric data, or date- or time-specific data. It's come in handy lately for me. :) I had the TourneyLogic boyz on my radio show I had a great time yesterday featuring some new friends of mine, Joel Ross and Brian Anderson from TourneyLogic, on the sportstalk radio show I host. We rapped about their Tourney Bracket Control (which I'm using for my site's NCAA March Madness online competition), and also about the NCAA's in general (both boys are huge Big Ten fans...makes sense, both being from Michigan). It was a blast....serious sports chatter mixed with dev news and some comedy. I should have had the MP3 file of our convo up by now for a podcast...BUT like a dumbass, I didn't personally check to see that the producer was rolling on the show. So for the moment, if you missed my live feed, you're out of luck. So, I've got to ditch my developer/news anchor/radio show host hats this morning and don a new archaeologist cap...and try to find a backup recorded version somewhere here. If not, I'll have Joel and Brian on again after the national championship to do a post-mortem report. AND, I promise to have the dang audio. :) Dammit, if you want something done, ya gotta do it yourself. Integrating Community Server :: Forums with intra-site search tool At the moment, I'm working on revamping my site's search tool, which currently returns a resultset consisting of a nicely-separated collection of full-text indexed news articles from my station's archive, plus a series of multimedia exhibits the URLs for which we hardcode into a database (searchable via keywords, a la AOL). This has worked beautifully for us, given that we're a TV/radio/web operation, and can cross-promote the hell out of whatever we do. People really enjoy the diversity of the results. Now, I'm taking it a step further. The next version is going to finally integrate two other key components: reporter/producer blogs, and also forum posts from the recently-released Community Server :: Forums. The entire thing is basically a bunch of DataTables, cleanly making distinction between what results came from where. It's pretty fun. Using a DataGrid's OnUpdateCommand event to send e-mail Yesterday, I thought about doing something quirky, in wiring up some code to a DataGrid's OnUpdateCommand not to update an existing data store, but basically to turn a DataGrid into an outgoing e-mail client. Basically, you'd "edit" a row containing info for a user (like an address book, I suppose), display a TextBox, and then insert code to send a message programmatically. I figured it was totally possible, but just wanted to know if anyone out there was doing anything like this.
http://weblogs.asp.net/jasonsalas/archive/2005/03
CC-MAIN-2014-41
refinedweb
1,633
63.09
Search found 1 match Search found 1 match • Page 1 of 1 - Sun Aug 03, 2014 6:31 pm - Forum: Volume 5 (500-599) - Topic: 524 - Prime Ring Problem - Replies: 74 - Views: 19332 Re: 524 - The Prime Ring Problem - Is backtracking the only I am trying to solve this problem and I think my programm is rigth ;), but I still get WA. I am pretty sure that I forgot any whitespace or kind like that. But I can't find the mistake. public class Main { public boolean [] primes = new boolean[33]; int[] array; boolean[] used; StringBuilder builder... Search found 1 match • Page 1 of 1
https://onlinejudge.org/board/search.php?author_id=140858&sr=posts
CC-MAIN-2020-16
refinedweb
105
84.81
Types of Strings in Groovy Last modified: February 18, 2019 1. Overview In this tutorial, we’ll take a closer look at the several types of strings in Groovy, including single-quoted, double-quoted, triple-quoted, and slashy strings. We’ll also explore Groovy’s string support for special characters, multi-line, regex, escaping, and variable interpolation. 2. Enhancing java.lang.String It’s probably good to begin by stating that since Groovy is based on Java, it has all of Java’s String capabilities like concatenation, the String API, and the inherent benefits of the String constant pool because of that. Let’s first see how Groovy extends some of these basics. 2.1. String Concatenation String concatenation is just a combination of two strings: def first = 'first' def second = "second" def concatenation = first + second assertEquals('firstsecond', concatenation) Where Groovy builds on this is with its several other string types, which we’ll take a look at in a moment. Note that we can concatenate each type interchangeably. 2.2. String Interpolation Now, Java offers some very basic templating through printf, but Groovy goes deeper, offering string interpolation, the process of templating strings with variables: def name = "Kacper" def result = "Hello ${name}!" assertEquals("Hello Kacper!", result.toString()) While Groovy supports concatenation for all its string types, it only provides interpolation for certain types. 2.3. GString But hidden in this example is a little wrinkle – why are we calling toString()? Actually, result isn’t of type String, even if it looks like it. Because the String class is final, Groovy’s string class that supports interpolation, GString, doesn’t subclass it. In other words, for Groovy to provide this enhancement, it has its own string class, GString, which can’t extend from String. Simply put, if we did: assertEquals("Hello Kacper!", result) this invokes assertEquals(Object, Object), and we get: java.lang.AssertionError: expected: java.lang.String<Hello Kacper!> but was: org.codehaus.groovy.runtime.GStringImpl<Hello Kacper!> Expected :java.lang.String<Hello Kacper!> Actual :org.codehaus.groovy.runtime.GStringImpl<Hello Kacper!> 3. Single-Quoted String Probably the simplest string in Groovy is one with single quotes: def example = 'Hello world' Under the hood, these are just plain old Java Strings, and they come in handy when we need to have quotes inside of our string. Instead of: def hardToRead = "Kacper loves \"Lord of the Rings\"" We can easily concatenate one string with another: def easyToRead = 'Kacper loves "Lord of the Rings"' Because we can interchange quote types like this, it reduces the need to escape quotes. 4. Triple Single-Quote String A triple single-quote string is helpful in the context of defining multi-line contents. For example, let’s say we have some JSON to represent as a string: { "name": "John", "age": 20, "birthDate": null } We don’t need to resort to concatenation and explicit newline characters to represent this. Instead, let’s use a triple single-quoted string: def jsonContent = ''' { "name": "John", "age": 20, "birthDate": null } ''' Groovy stores this as a simple Java String and adds the needed concatenation and newlines for us. There is one challenge yet to overcome, though. Typically for code readability, we indent our code: def triple = ''' firstline secondline ''' But triple single-quote strings preserve whitespace. This means that the above string is really: (newline) firstline(newline) secondline(newline) not: like perhaps we intended. Stay tuned to see how we get rid of them. 4.1. Newline Character Let’s confirm that our previous string starts with a newline character: assertTrue(triple.startsWith("\n")) It’s possible to strip that character. To prevent this, we need to put a single backslash \ as a first and last character: def triple = '''\ firstline secondline ''' Now, we at least have: One problem down, one more to go. 4.2. Strip the Code Indentation Next, let’s take care of the indentation. We want to keep our formatting, but remove unnecessary whitespace characters. The Groovy String API comes to the rescue! To remove leading spaces on every line of our string, we can use one of the Groovy default methods, String#stripIndent(): def triple = '''\ firstline secondline'''.stripIndent() assertEquals("firstline\nsecondline", triple) Please note, that by moving the ticks up a line, we’ve also removed a trailing newline character. 4.3. Relative Indentation We should remember that stripIndent is not called stripWhitespace. stripIndent determines the amount of indentation from the shortened, non-whitespace line in the string. So, let’s change the indentation quite a bit for our triple variable: class TripleSingleQuotedString { @Test void 'triple single quoted with multiline string with last line with only whitespaces'() { def triple = '''\ firstline secondline\ '''.stripIndent() // ... use triple } } Printing triple would show us: firstline secondline Since firstline is the least-indented non-whitespace line, it becomes zero-indented with secondline still indented relative to it. Note also that this time, we are removing the trailing whitespace with a slash, like we saw earlier. 4.4. Strip with stripMargin() For even more control, we can tell Groovy right where to start the line by using a | and stripMargin: def triple = '''\ |firstline |secondline'''.stripMargin() Which would display: firstline secondline The pipe states where that line of the string really starts. Also, we can pass a Character or CharSequence as an argument to stripMargin with our custom delimiter character. Great, we got rid of all unnecessary whitespace, and our string contains only what we want! 4.5. Escaping Special Characters With all the upsides of the triple single-quote string, there is a natural consequence of needing to escape single quotes and backslashes that are part of our string. To represent special characters, we also need to escape them with a backslash. The most common special characters are a newline (\n) and tabulation (\t). For example: def specialCharacters = '''hello \'John\'. This is backslash - \\ \nSecond line starts here''' will result in: hello 'John'. This is backslash - \ Second line starts here There are a few we need to remember, namely: - \t – tabulation - \n – newline - \b – backspace - \r – carriage return - \\ – backslash - \f – formfeed - \’ – single quote 5. Double-Quoted String While double-quoted strings are also just Java Strings, their special power is interpolation. When a double-quoted string contains interpolation characters, Groovy switches out the Java String for a GString. 5.1. GString and Lazy Evaluation We can interpolate a double-quoted string by surrounding expressions with ${} or with $ for dotted expressions. Its evaluation is lazy, though – it won’t be converted to a String until it is passed to a method that requires a String: def string = "example" def stringWithExpression = "example${2}" assertTrue(string instanceof String) assertTrue(stringWithExpression instanceof GString) assertTrue(stringWithExpression.toString() instanceof String) 5.2. Placeholder with Reference to a Variable The first thing we probably want to do with interpolation is send it a variable reference: def name = "John" def helloName = "Hello $name!" assertEquals("Hello John!", helloName.toString()) 5.2. Placeholder with an Expression But, we can also give it expressions: def result = "result is ${2 * 2}" assertEquals("result is 4", result.toString()) We can put even statements into placeholders, but it’s considered as bad practice. 5.3. Placeholders with the Dot Operator We can even walk object hierarchies in our strings: def person = [name: 'John'] def myNameIs = "I'm $person.name, and you?" assertEquals("I'm John, and you?", myNameIs.toString()) With getters, Groovy can usually infer the property name. But if we call a method directly, we’ll need to use ${} because of the parentheses: def name = 'John' def result = "Uppercase name: ${name.toUpperCase()}".toString() assertEquals("Uppercase name: JOHN", result) 5.4. hashCode in GString and String Interpolated strings are certainly godsends in comparison to plain java.util.String, but they differ in an important way. See, Java Strings are immutable, and so calling hashCode on a given string always returns the same value. But, GString hashcodes can vary since the String representation depends on the interpolated values. And actually, even for the same resulting string, they won’t have the same hash codes: def string = "2+2 is 4" def gstring = "2+2 is ${4}" assertTrue(string.hashCode() != gstring.hashCode()) Thus, we should never use GString as a key in a Map! 6. Triple Double-Quote String So, we’ve seen triple single-quote strings, and we’ve seen double-quoted strings. Let’s combine the power of both to get the best of both worlds – multi-line string interpolation: def name = "John" def multiLine = """ I'm $name. "This is quotation from 'War and Peace'" """ Also, notice that we didn’t have to escape single or double-quotes! 7. Slashy String Now, let’s say that we are doing something with a regular expression, and we are thus escaping backslashes all over the place: def pattern = "\\d{1,3}\\s\\w+\\s\\w+\\\\\\w+" It’s clearly a mess. To help with this, Groovy supports regex natively via slashy strings: def pattern = /\d{3}\s\w+\s\w+\\\w+/ assertTrue("3 Blind Mice\Men".matches(pattern)) Slashy strings may be both interpolated and multi-line: def name = 'John' def example = / Dear ([A-Z]+), Love, $name / Of course, we have to escape forward slashes: def pattern = /.*foobar.*\/hello.*/ And we can’t represent an empty string with Slashy String since the compiler understands // as a comment: // if ('' == //) { // println("I can't compile") // } 8. Dollar-Slashy String Slashy strings are great, though it’s a bummer to have to escape the forward slash. To avoid additional escaping of a forward slash, we can use a dollar-slashy string. Let’s assume that we have a regex pattern: [0-3]+/[0-3]+. It’s a good candidate for dollar-slashy string because in a slashy string, we would have to write: [0-3]+//[0-3]+. Dollar-slashy strings are multiline GStrings that open with $/ and close with /$. To escape a dollar or forward slash, we can precede it with the dollar sign ($), but it’s not necessary. We don’t need to escape $ in GString placeholder. For example: def name = "John" def dollarSlashy = $/ Hello $name!, I can show you a $ sign or an escaped dollar sign: $$ Both slashes work: \ or /, but we can still escape it: $/ We have to escape opening and closing delimiters: - $$$/ - $/$$ /$ would output: Hello John!, I can show you a $ sign or an escaped dollar sign: $ Both slashes work: \ or /, but we can still escape it: / We have to escape opening and closing delimiter: - $/ - /$ 9. Character Those familiar with Java have already wondered what Groovy did with characters since it uses single quotes for strings. Actually, Groovy doesn’t have an explicit character literal. There are three ways to make a Groovy string an actual character: - explicit use of ‘char’ keyword when declaring a variable - using ‘as’ operator - by casting to ‘char’ Let’s take a look at them all: char a = 'A' char b = 'B' as char char c = (char) 'C' assertTrue(a instanceof Character) assertTrue(b instanceof Character) assertTrue(c instanceof Character) The first way is very convenient when we want to keep the character as a variable. The other two methods are more interesting when we want to pass a character as an argument to a function. 10. Summary Obviously, that was a lot, so let’s quickly summarize some key points: - strings created with a single quote (‘) do not support interpolation - slashy and tripled double-quote strings can be multi-line - multi-line strings contain whitespace characters due to code indentation - backslash (\) is used to escape special characters in every type, except dollar-slashy string, where we must use dollar ($) to escape 11. Conclusion In this article, we discussed many ways to create a string in Groovy and its support for multi-lines, interpolation, and regex. All these snippets are available over on Github. And for more information about features of the Groovy language itself, get a good start with our introduction to Groovy.
https://www.baeldung.com/groovy-strings
CC-MAIN-2019-22
refinedweb
1,978
60.45
Pycon 201615 Jun 2016 Pycon was wonderful this year. It was held at the Portland convention center which I like, and there were about 40% women at the conference; my perception was that around the same percentage of women were speaking. I credit Guido Van Rossum with requesting that the conference and the community become more inclusive (his goal is 50%). This is an amazing accomplishment in our field; my usual experience is in the low single digits. It has been shown that diverse companies make more money, and I think that the Python community will grow and become more successful because of this goal. It seemed to me that the women felt comfortable enough to talk about what it is actually like to be a woman in this field. My take: it’s easy to think things have gotten better, and perhaps they have, but the situation is still pretty miserable and we have a long way to go (concerning diversity in general). This situation is holding the whole field back and I’m proud that the Python community is leading the way. I’ve gone to many Pycons, including giving two keynotes in past years and speaking at Pycons in other countries. But this year I wanted to expand my experience by doing things that I haven’t before. This included volunteering. I stumbled into bag-stuffing the first day. I did this once years ago, and the process was completely different. I think this is because volunteering is often more self-organized. In this case, it had evolved from people stuffing a bag one at a time to people cycling around holding their bag open and others dropping items into the open bag. It seemed much more efficient to me, and I found it very interesting to see how it had evolved. I also signed up ahead of time to work at the registration desk and the green room (where speakers get ready to go to their rooms). Apparently the registration software is improved every year, to make it easier for inexperienced people (like me) to quickly become functional. Years ago, when I worked with the now-defunct Software Development conference (which couldn’t adapt to the Internet), one of the big, expensive problems they always had was registration. It was interesting to see how the open-source solution (at least, I think it was open source) had improved things, and will no doubt continue to do so. In the green room, it turned out that one of the hosts for one of the speaking rooms had not shown up, and the green-room manager handed me a radio and said “you’re it.” (The radios were awkward and unfamiliar and I wish we could have just texted instead, or even better, used some kind of app that maintained status on a big board in the green room). There are runners that walk people from the green room to the room where they speak. This seems like a simple job, but it’s very useful because speakers can then focus on mentally preparing themselves rather than worrying about (and potentially becoming flustered) finding their room. The runner also talks to the speaker and I think this can be calming. Pycon often has first-time speakers so this is an important role. The room manager role which I was doing is for three consecutive talks in a single room. I introduced each speaker and then held up signs for 15, 10, 5 minutes and one for stopping. Each sign was held up 5 minutes before the actual time. I didn’t find out how this time-shifting practice had evolved but apparently it works. All three speakers finished with enough time for questions, at which point I ran around with a microphone. Often this is a problem when people start asking their question before the mike arrives, but for each talk I reminded people that this was being recorded and that folks watching on YouTube want to hear the question. I was also watching for the next questioner while the current question was being asked, and bringing the microphone to the new questioner during that time. That might have helped as well, but I think the biggest effect was simply reminding the audience about home viewers. I enjoyed all three presentations, and also being involved with the production. In the last year I’ve started to watch, as part of my research, presentations on YouTube, Vimeo, etc. It’s been a huge addition to the way I learn. I also realize what a big effect this must be starting to have on the rest of the world. Anyone with Internet can have the benefits of conference presentations. Pycon has always been a leader in this area (and they get the presentations up very quickly), and I was quite aware this year that I can see any presentation on YouTube. For that reason I decided to try to only do things that were not recorded, and to take advantage of physical presence. Considering that I hold all open-spaces conferences, and that the first open-spaces (and lightning talks) I ever saw was at Pycon, it surprised me that I wasn’t more attuned to them. I attended three this year: One on freelancing, one on conference organization (where I was able to contribute from my experiences), and one called “Random Storytelling.” I attended this last one because my friend (and book designer) Daniel Will-Harris has invented a technique for creating stories—in fact, he’s in China right now setting up a system to teach it to drama students there. I thought I should look into this in case there were some ideas for him. It turned out to be telling stories from your life. For me, it felt like I had suddenly stepped out of Pycon and into Burning Man, and I ended up telling a story about the first time I went to Burning Man. The session was a very connecting experience, and a group of us ended up going out to dinner. The group included Audrey and Daniel Roy Greenfeld (second and third from left, and flanked by the ReadTheDocs guys), who met at Pycon and got married. Audrey created the Cookiecutter project which I spent some time with during sprints and created a basic introduction. Also at that dinner were the guys who do ReadTheDocs.org, which I also sprinted on. For the first time at Pycon, I held two openspaces sessions, the first about Teal organizations and how we might start them, and the second to gather feedback for a book on Python concurrency, which looks very likely to be my next project. The book session was extremely helpful. Kevin Quick came, who works at GoDaddy and helped create the Thespian Python actor system. This is in active use at GoDaddy and seems a likely candidate to demonstrate actors in the book. My intent with the book is to expect Python proficiency but not to assume the reader knows anything about concurrency. This seemed to appeal to the group. We also talked about print books vs. ebooks. I have been pushing for ebook-only publication, but this conversation set me back. Everyone in the group declared that, although they like ebooks well enough for “regular” books, for a programming book in particular, a print book is essential. One thing that impressed me was the description, which I have heard several times subsequently, of having a mental model of the physical book including where certain topics are located. Wednesday night I had dinner with Guido Van Rossum and a group from Dropbox, also to discuss the book. Guido was the first person I told when I got the idea, to ask him if he thought it filled a need, and he was quite positive and said that just within Dropbox it would be good to have some way to educate people. This group also declared they wanted a print version of the book. Both groups also expressed interest when I floated the idea of holding an openspaces conference (like the Winter Tech Forum) around Python concurrency, starting next summer. After hearing this feedback and spending time during the Sprints with the ReadTheDocs group, I’ve started visualizing a scenario of publishing the book as it’s being developed (much as I did with the original version of Thinking in Java) on ReadTheDocs, then creating a print version for sale. If indeed people really want a print book, this model should produce enough income to pay for the project. If I enjoy it enough to create a seminar, then that would certainly make it worthwhile (I got rather burned out after giving C++ and Java seminars, but Python concurrency might be fun; in addition I’ve learned a lot of tricks over time that make seminars more enjoyable for both me and the participants). ReadTheDocs provides different download formats (as well as just using it online), including HTML, PDF and Epub. During my time sprinting with them, we discussed the possibility of creating a process to produce a camera-ready PDF that could go directly to a print-on-demand service like LightningSource (which I use; they also make it effortless to switch to a press run and are owned by Ingram, which will handle distribution for you if you want). This process might become a business model to support ReadTheDocs: if you want to go to print, they could have several levels of paid help: basic (turn your docs into camera-ready PDF), self-publish (hand-hold you through the process but you remain the publisher) or ReadTheDocs might even become your publisher, recieving a portion of sales. Sprinting Finally, for the first time in all my Pycons I stayed for the sprints. This is one of those life experiences where learning something new can lead to regret that you haven’t been doing it all along, but oh well. And Guido pointed out that this might not be true, because I participated in what might have been the very first sprint after a Pycon in Washington DC, when a group of us went to the Zope Corporation in Virginia and were coached by Jim Fulton — Guido said this is the moment when Jim invented the sprint. But I probably wasn’t ready for it then. People at the conference seem hesistant to join in, I think because they imagine that to sprint you have to understand the project and be good at something. My own experience disproves this. Indeed, much of the time my strength was my ignorance. I think the initial contact and onboarding experience is very important; if it’s not easy and positive it can turn people away. So if you are clueless about a project, just sit down at a sprint and declare that you’re going through the newbie install process—any project that I know of will be quite happy to have their onboarding checked, because they know it all too well to discover the missing parts. Apparently the normal pattern is that about a quarter of the conference remains for the sprints (then trickles away over the days). The afternoon of the last day of the conference includes different projects giving tiny descriptions of what they are doing, followed by sprint coaching for new folks. There is pre-sprint coaching, but you really can just show up and wander around and find some projects. You learn a ton regardless of whether you’re able contribute something, and it’s likely you can help in some way. If a project isn’t working for you, use the same “Law of Two Feet” as we have in open spaces and find another project. ReadTheDocs This was my first sprint. I’ve read a lot of documentation hosted on ReadTheDocs.org, but I didn’t know how it worked. I started by following the installation directions for those wanting to build documentation on ReadTheDocs. I learned a lot by doing this and by being able to ask questions of the creators (see the conversation about publishing earlier in this post). The place I helped was discovering a configuration problem that, as it turns out, had been plaguing them and wasting a lot of time, so they were elated to be able to fix it. This is what I mean—anyone can be helpful, even if it’s just by bumbling around and tripping over a problem. On top of that, I feel like I have enough of a grasp of ReadTheDocs that I can start using it for my own projects. Invoke Build tools have always been a kind of hobby horse for me; at one point in the distant past I was pushing make to its limits, enough to see that its creators had given up in despair upon realizing that what they were really doing is creating a programming language. Once you know that, you realize that the best solution is to start with an existing programming language, especially one like Python which is really good at manipulating everything. And Python decorators are perfect for annotating things to be tasks/targets. I’ve made a couple of attempts to create a decorator-based build system but I’d much rather use something that someone else has spent a lot of time making. Invoke (Docs here and the github repository is here) by Jeff Forcier seems like it might be that tool. It’s quite thorough but it doesn’t yet do timestamp dependencies like make does. Although I couldn’t get close to making those changes myself, I was able to find a directed-acyclic-graph library that Jeff might be able to use for the task. As it was Python 2 and Jeff wants to use Python 2 and 3 libraries, I modified it to produce Pythondagger23 that works with both versions. I’m hoping it will be a step towards a more powerful Invoke. Cookiecutter When I found out what Cookiecutter does I decided it could be very important to me. I made a very introductory overview of the tool so others could quickly understand its value. They decided to use this as their official first introduction. MicroBit Python The MicroPython project had BBC MicroBits devices and asked us to create new demonstration examples. My goal was just to get one working and to program something on the 5 by 5 grid of LEDs on the back, just as a kind of baseline test. I went down a few wrong paths at first, probably because other parts of the project required creating a full set of build tools and flashing the MicroPython image onto the device. Fortunately I had help from (sorry I forgot your name) who coached me across installing parts of the system until he realized I just wanted to play with the LEDs, at which time he flashed my device from his system and we found that the MU Editor was the thing to get. We didn’t establish whether MU took care of everything necessary to make the connection to the device, or if some driver we had incidentally installed during our explorations was also necessary. Here’s the code we ended up creating: from microbit import * import random pixX = random.randint(0, 4) pixY = random.randint(0, 4) def step(n): r = n + random.randint(-1, 1) if r < 0: return 0 if r > 4: return 4 return r while True: display.clear() display.set_pixel(pixX, pixY, 6) pixX = step(pixX) pixY = step(pixY) sleep(300) This makes a dot that wanders around the 5x5 matrix and bumps into walls and corners. We didn’t submit it because it seemed too simple compared to the other examples, but if the project still wants to use it, feel free. The final night for me was Saturday, and I went to dinner with Barry Warsaw and the MailMan sprinters, so Barry and I were able to catch up. He’s still very happy working with Canonical. We figured out that we had both worked on the Gnu Emacs C++ mode. I created the mode way back when I was working at the University of Washington School of Oceanography with Tom Keffer (who later used our work to start Rogue Wave, supplier of C++ libraries). However, I didn’t do very much with it; just got the basic mode working. Sometime later Barry came along and spent a lot of time making it useful, especially the very tricky reformatting, which I remember taking a shot at but then discovering what a big job it was. This all happened years before we met each other during the (relatively) early days of Python, but he remembers my name at the top of the authors list. It was fun to see how our paths had crossed so long ago without either of us knowing it.
http://bruceeckel.github.io/2016/06/15/pycon-2016/
CC-MAIN-2017-09
refinedweb
2,830
66.07
FlexSlider 2.6.0FlexSlider 2.6.0 - ** Version 2.6.0 ** ** Adds composer json file, scope fix for focused keyword, fixes bower demo folder exclusion, z-index fix for disabled nav arrow, play/pause accessibility fix, itemMargin fix for slider items, fixes accessibility for in focus elements and pagination controls, firefox fix for text selection on slider carousel, adds data-thumb-alt image alt attribute ** ** Version 2.5.0 ** ** Bumped compatibility support starting with jQuery 1.7+. pausePlay icon fix. Firefox touch event fix. Adds customDirectionNav param ** ** Version 2.4.0 ** ** Update for improved standards. Adds classes to li nav elements. Reset for li elements in stylesheet. ** ** Version 2.3.0 ** ** Fixes pauseInvisible attribute issue with Chrome and the Page Visibility API. ** ** Version 2.2.2 ** ** Fixes minified JavaScript file to remove merge conflicts. ** ** Version 2.2.0 ** - Fixed event handler conflicts with devices that are both click and touch enabled. e.g., Windows 8. - Made all slider variables public, stored in slider.vars. This allows manipulation of slider.vars.minItemsand slider.vars.maxItemson the fly to create different fluid grids at certain breakpoints. Check out this example demonstrating a basic technique - Fixed calculations that were causing strange issues with paging and certain FlexSliders to move out of alignment. Be sure to test v2.2.0 with your current slider, before pushing live, to ensure everything is playing nicely. General NotesGeneral Notes FlexSlider is no longer licensed under the MIT license. FlexSlider now uses the license, GPLv2 and later. In an effort to move the plugin forward, support for jQuery 1.4.2 has been dropped. The plugin now requires jQuery 1.7.0+. If you don't have access to the later versions of jQuery, FlexSlider 1.8 should be a perfectly suitable substitute for your needs! Your old styles and properties might not work out of the box. Some property names have been changed, noted below, as well as namespacing prefixes being applied to all elements. This means that .flex-direction-nav .next is now .flex-direction-nav .flex-next by default. The namespacing property is exposed, free for you to change. No more overflow hidden woes! The plugin now generates a viewport element to handle the tedious task of working around overflow hidden. Yay! The slider element is now accessible outside of the callback API via the jQuery .data() method. Example use: $('#slider').data('flexslider') Helper strings have been added for performing actions quickly on FlexSlider elements. Example uses: $('#slider').flexslider("play") //Play slideshow $('#slider').flexslider("pause") //Pause slideshow $('#slider').flexslider("stop") //Stop slideshow $('#slider').flexslider("next") //Go to next slide $('#slider').flexslider("prev") //Go to previous slide $('#slider').flexslider(3) //Go fourth slide Two new methods are available for adding/removing slides, slider.addSlide() and slider.removeSlide(). More details about this coming soon. slider.addSlide(obj, pos)accepts two parameters, a string/jQuery object and an index. slider.removeSlide(obj)accepts one parameter, either an object to be removed, or an index. ExamplesExamples - Basic Slider - Basic Slider customDirectionNav - Slider w/thumbnail controlNav pattern - Slider w/thumbnail slider - Basic Carousel - Carousel with min and max ranges - Video with Vimeo API - Video with Wistia API PropertiesProperties namespace: {new}namespace: {new} namespace controls the prefixes attached to elements created by the plugin. In previous releases, only certain elements were tagged with a prefix class, which was causing class generalization issues for some users. FlexSlider now prefixes all generated elements with the appropriate namespace. Hint: namespace can be an empty string. selector: {new}selector: {new} The markup structure for FlexSlider has been limited to a "ul.slide li" pattern in previous versions of FlexSlider; no longer. You can now take full control of the markup structure used for your FlexSlider. The selector pattern "{container} > {slide}" is mandatory, allowing the plugin to predictably interpret the selector property. Omitting the ">" from the selector is not suggested, but is possible if your markup doesn't follow the immediate descendant pattern. Examples: "section > article", ".slides > .slide", "#hero .slide" easing: {new}easing: {new} easing allows support for jQuery easing! Default options provided by jQuery are "swing" and "linear," but more can be used by included the jQuery Easing plugin. If you chose a non-existent easing method, the slider will break. Note: You need to set useCSS: false to force transitions in browsers that support translate3d. Optional: jQuery Easing Plugin direction: {changed}useCSS: {new} useCSS allow users to override using CSS3 for animation. Translate3d still has numerous bugs that can crop up and wreak havoc, so this is a great property to play with if you are experiencing unexplainable issues in Webkit browsers. Hint: Use conditionals to enable/disable the use of CSS3 on desktops and mobile devices. Mobile devices, in my experience, do not share many of the translate3d bugs seen on desktop browsers. touch: {new}touch: {new} touch allows users to exclude touch swipe functionality from their sliders. keyboard: {changed}keyboard: {changed} Previously called "keyboardNav" in v1.8 and below. multipleKeyboard {new}multipleKeyboard {new} multipleKeyboard allows users to override the default plugin keyboard behavior, enabling keyboard control of more than one slider on the page. This means that all visible sliders will animate, at the same time, via keyboard input. Hint: You can use multipleKeyboard to allow keyboard navigation on pages where multiple sliders are present, but only one is visible. mousewheel: {updated}mousewheel: {updated} mousewheel now requires the jQuery Mousewheel plugin. There are a few reasons for this, but primarily because there is no need for FlexSlider itself to reinvent the awkward complexity of mousewheel interactivity that is handled perfectly by the Mousewheel plugin. Required: jQuery Mousewheel Plugin controlsContainer: {updated}controlsContainer: {updated} controlsContainer is one of the more painstaking, potentially confusing properties within FlexSlider. First, the property is no longer required to workaround overflow: hidden on slide animation. Second, the property now accepts a jQuery object, giving you precise control over the object you want. The plugin no longer attempts to guess what element you are selecting. customDirectionNav: {new}customDirectionNav: {new} customDirectionNav allows the ability to add custom directional navigation elements. Can be used in conjunction with controlsContainer for pagination controls container. Example of customDirectionNav being used sync: {new}sync: {new} sync is a new property that will allow other slider(s) to hook into the current slider via a given selector. The selector should describe an object that has already been initialized as a FlexSlider. Right now, sync will synchronize animation, play, and pause behaviors. More behaviors can be added in the future as the property matures. Example of sync being used asNavFor: {new}asNavFor: {new} Description to be added. itemWidth: {new}itemWidth: {new} itemWidth is the primary property for the new carousel options. Without this property, your slider is not considered a carousel. To use itemWidth, give an integer value of the width of your individual slides. This should include borders and paddings applied to your slides; a total width measurement. itemMargin: {new}itemMargin: }move: {new} move determines how many slides should be animated within the carousel. When left at 0, the slider will animate the number of visible slides. If any value greater than 0 is given, the slider will animate that number of slides in the carousel on each animation interval. Hint: The move property will be ignored if the value is higher than the number of visible slides, which can be utilized in responsive design. added: {new}added: .
https://libraries.io/bower/flexslider-customized
CC-MAIN-2020-29
refinedweb
1,231
50.43
On Monday 20 March 2017, Andi Vajda wrote: > On Mon, 20 Mar 2017, Ruediger Meier wrote: > >> Someone with access to Windows, please help test/fix/finish > >> support for Python 3 on Windows, both with the MSVC and Mingw > >> compilers. I have no access to Windows anymore. > > > > I know already about one MSVC issue: > > > > > > probably fixed by > > > >e8340704fd237 (But this fix is also not tested yet.) > > I changed strhash to use Py_hash_t. This is now wrong and I could reproduce a segfault on OSX 10.11, xcode 8. The buffersize "hexdig + 1" has to match the type we are printing. We can't calculate the size from Py_hash_t but print ulong. Most safely and without precision loss we could do it like the patch below. Notes: 1. "static const" was required to actually fix MSVC's VLA issue. 2. The macro PRIxMAX is the same as "%jx". I've choosed the macro because it should be compatible to Visual Studio >=2013 while "%jx" would need Visual Studio >=2015. Moreover when using incompatible compilers the macro would give an error at compile time rather than "%jx" would just crash at runtime. -------- diff --git a/jcc3/sources/jcc.cpp b/jcc3/sources/jcc.cpp index 8c12f00..90baa8b 100644 --- a/jcc3/sources/jcc.cpp +++ b/jcc3/sources/jcc.cpp @@ -15,6 +15,7 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> +#include <inttypes.h> #include <jni.h> #ifdef linux @@ -194,11 +195,11 @@ static PyObject *t_jccenv_isShared(PyObject *self) static PyObject *t_jccenv_strhash(PyObject *self, PyObject *arg) { - Py_hash_t hash = PyObject_Hash(arg); - size_t hexdig = sizeof(Py_hash_t) * 2; + uintmax_t hash = (uintmax_t) PyObject_Hash(arg); + static const size_t hexdig = sizeof(hash) * 2; char buffer[hexdig + 1]; - sprintf(buffer, "%0*lx", (int) hexdig, (unsigned long) hash); + sprintf(buffer, "%0*"PRIxMAX, (int) hexdig, hash); return PyUnicode_FromStringAndSize(buffer, hexdig); } -------------- cu, Rudi
http://mail-archives.apache.org/mod_mbox/lucene-pylucene-dev/201703.mbox/%3C201703201316.06805.sweet_f_a@gmx.de%3E
CC-MAIN-2019-39
refinedweb
299
68.16
Rapid Website Deployment With Django, Heroku & New Relic. One of the more exciting changes this move to cloud platforms has brought, particularly in the case of smaller projects, is that many clouds provide a free deployment opportunity albeit with minimal hardware usage. This allows for free hosting of prototype applications for example or beta products giving you a live, running application instance which you can make available to anyone you like, quickly. Similarly, it works perfectly for any website receiving a moderate amount of traffic, such as a small local business or even a portfolio website where you can showcase some of your work. Introduction This article focuses on my experience in rapidly developing a portfolio website in Python and the popular Django web framework using some bootstrap templates to style the site. With a neat site able to showcase the work, I'll show you how to add it in to a Django generated content management system (CMS), as well as how easily it can be to deploy to Heroku for the hosting of your site and then monitor traffic, errors and response times using Heroku's built in New Relic integration. All for free, within a few hours of work. Create Your Website First of all, you need a project that you wish to host on the cloud. As mentioned earlier, my project was to rapidly create a portfolio website from which to showcase my articles and other projects, along with my C.V and contact information. Python and Django offered a perfect match for these requirements and you can quickly begin building a dynamic website with Django and its ORM design, providing easy integration between your web templates and underlying data stored in a database. Before writing any code, you should create a Python virtual environment for your project, to keep the dependencies for this project separate from any others. Under the hood, virtualenv effectively copies your global Python installation to the .virtualenvs folder under a named directory for your virtualenv. It then adds this location to the front of your path so that your system uses this Python installation for your project. All dependencies are then installed here instead of globally. You can do this by first installing virtualenv and virtualenvwrapper using Python's package manager " pip". $ pip install virtualenv $ pip install virtualenvwrapper After installing the virtualenv tools you should then add a source line to your .bashrc in your home directory (Linux/Mac OS X), which enables the virtualenvwrapper scripts on the command line, allowing for easy creation, activation and deletion of virtual environments. You can create the virtualenv as follows. $ mkvirtualenv portfolio With your environment setup you can then install Django which you will be using to define the web application. Django can be installed by executing the following command. $ pip install django With the dependencies in place, your first step in creating your Django project is to create a directory to hold your files following a fairly standard structure as shown below. Fortunately, Django helps to automate this process with the use of the django-admin.py command line tool. Execute the following to create your project and application directory. $ django-admin.py startproject tuts This will produce the following structure. tuts/ tuts/ __init__.py settings.py urls.py wsgi.py You can read more on the setup of Django applications over in the Django official documentation, but a basic summary of those files is as follows: settings.py- configuration for your Django application, such as database connections and apps (see below). urls.py- the routes that link to the different parts of your sites. wsgi.py- a file to allow the starting of your application by web servers such as Apache. The project created so far is just the outer container for your actual web application. The meat of the code should live inside an app and you can again make use of Django's helper methods to create the app structure for you. $ python manage.py startapp portfolio This will add in the following to our overall directory structure. tuts/ tuts/ __init__.py settings.py urls.py wsgi.py portfolio/ admin.py models.py tests.py views.py With your app created, you then need to register it to your Django project. Open up settings.py and add "portfolio" to the INSTALLED_APPS tuple: INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'portfolio' ) To check everything is working, enter the following command and visit in your browser. You should see a page such as the one shown in the image below. Defining the Model Now that your project directory is set up, let's start fleshing out the code. As we know the type of data we want to add to the portfolio site, we can begin to define the model. This describes our data in the database and allows Django to go ahead and create the appropriate fields and tables in the database for us. On our website, we will be putting entries for articles, books and thesis material. Each of these could have its own individual model if you would like to give them unique data fields that do not apply to the other entry types. However for this website, each entry will be given a name, publish date, description and URL. In the models.py file under the portfolio app directory, you can define this entry data as: class Item(models.Model): publish_date = models.DateField(max_length=200) name = models.CharField(max_length=200) detail = models.CharField(max_length=1000) url = models.URLField() thumbnail = models.CharField(max_length=200) With the model defined, you can then generate this in the database using Django's built in command line tools which are made available to you after installation. If you make use of the manage.py file again, you can also use the syncdb command to handle the database setup for you. If you issue the following command, you will be shown the available options this admin tool provides. $ python manage.py syncdb Creating tables ... Creating table portfolio_item Installing custom SQL ... Installing indexes ... Installed 0 object(s) from 0 fixture(s) Using the syncdb method allows Django to read the model we have just created and setup the correct structure to store this data in the database. As this is the first time you have executed this command, Django will also prompt you to answer a few questions. These will include items such as creating a superuser for the database (essentially the administrator) allowing you to password protect against making updates and changes to the database. This user will also form the first user able to log in to the CMS which will be generated for the website once we have templates up and running. With the user setup, the command should return showing that it has executed the SQL against the database. The next step is to now be able to access the data that will be stored to create a dynamic front end which you wish to display to the user. To achieve this, you will need to add code to the views to access the data you will store in the database. With the data available to the views, it can then pass this on to templates which can be interpreted as information to the end user. In this case, this will be in the form of HTML pages for a web browser. However, it is worth noting that this pattern could be used for other types of application such as producing JSON or XML, which again would just use the model to define and move the data, and the views presenting it, in the correct format of JSON/XML as opposed to HTML. Our Views In the views, you are going to make use of the data that will be stored in the database for display to the users. To do this, we import the Item class to access that model (with Django handling the access of the database underneath) and provide the data as variables to the "template" which Django will render. The template is mostly static HTML, with the addition of the ability to execute a restricted set of Python code to process your data and display it as required. For example, you may pass the entire list of item objects to the template, but then loop over that list inside the template to get just the name from each item and display it within an H1 tag. Hopefully, this will become clearer with the aid of examples below. Open up the views.py file that was created for you earlier, and add the following code which will be executed when accessing the home (or index) page of your website. def index(request): items = Item.objects.order_by("-publish_date") now = datetime.datetime.now() return render(request, 'portfolio/index.html', {"items": items, "year": now.year}) This will collect all items stored in the database, order them by the publish date field, allow you to display the most recent first and then pass these onto the template which you will create shortly. The dictionary passed to the render method is known as context and you will be able to access this context object easily in the template to display the data as required. Templates Django makes use of the Jinja2 templating library to handle the processing of its templates and is really nice to use, in that its syntax is straightforward and its abilities are powerful enough to produce what you need. It's worth noting however, a trap most developers fall into when working with Jinja2 is doing too much logic within the template. Whilst Jinja2 provides you with a large amount of standard Python operations, it is intended for simple processing to get the data in the format for display. The logic for retrieving and structuring the data should have all been done in controller and or view. You will know when you have fallen into this trap when you are coding a lot inside the templates and getting frustrated as Jinja2 outputs errors or your displayed data just will not appear as you want. At this point, it is worth revisiting the view to see if you can do more processing up front, before passing it on to the template. With our index method handling the accessing of data, all that's left is to define the template to display our items. As suggested by the index method, you need to add an index.html file within the portfolio app for it to render. Add that file with the following code. <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Tuts+ Django Example</title> </head> <body> <h1>Welcome to your Django Site.</h1> <h3>Here are your objects:</h3> <p> <ul> {% for item in items %} <li> {{ item.name }} </li> {% endfor %} </ul> </p> </body> </html> This is a basic HTML page that will loop over and produce a bullet point list of the item names. You can of course style this however you wish and I highly recommend the use of a bootstrap template if you are looking to get something professional up and running quickly. See more on Bootstrap's website. URLs The final piece to see if everything is working, is to go ahead and add the root URL to point at this template to be rendered. Under the app directory "tuts" open up urls.py and add the following URL directive to the auto generated examples and admin URL. urlpatterns = patterns('', # Examples: # url(r'^$', 'tuts.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^$', views.index, name='index'), ) Finally, open up admin.py to expose the Item class to the admin CMS, allowing you to enter the data to be displayed on the homepage. from portfolio.models import Item admin.site.register(Item) You should then be able to start up your site (using run server as before) and perform the following tasks. - Open up the homepage and see that no items are being displayed. - Open and enter the credentials created using syncdbearlier. - Open items and add a new item filling out the fields. - Visit the homage and you should see the item name as a bullet point. Try accessing other aspects of the item data in the template. For example, change the code within the bullet point to add the publish date also. For example: {{ item.publish_date }} - {{ item.name }} You now have a working site that simply needs some styling and more content to be able to function as a working portfolio website. Deploying to Heroku Heroku is a great cloud platform made available to all developers and companies, as an enterprise class hosting service that is tailored to suit all hosting requirements. From hobby websites, all the way through to high traffic, critical business websites, Heroku can handle it all. Best of all, their pricing structure includes a free tier that is more than capable of running a small website such as the portfolio website we have been building. Heroku leverages the ever popular Git source code management tool as their mechanism for controlling deployments to the platform. All you need to get started is a project, git installed and a Heroku account which can be obtained by visiting the sign up page. Once you have signed up, go into your Heroku account and create an app with one "web dyno". Heroku provides one dyne for free, which is capable of running a single application instance and moderate traffic to that instance. Give your app a name or let Heroku assign one for you. As we will need to use a database for our application, go into Add-Ons and attach the free PostgreSQL instance to your app. With your app created, just follow these steps to setup your git repository and push to Heroku. Install the Django Toolbelt which you can find in the developer section of the Heroku website. Initialize the Git repo in your project directory by issuing the following commands: $ git init . $ git add . $ git commit -m "Initial project commit." With the Git repository in place, add the Heroku application remote so that you can push the code to heroku. $ heroku git:remote -a YOUR_APP_NAME Heroku needs to know the command for exactly how to start your application. For this, you need to add a " Procfile". Add the file named " Procfile" into the root of your project directory, with the following contents. web: gunicorn tuts.wsgi To allow the Heroku app the ability to connect to the database instance attached to your application in the cloud, you need to add the following line to settings.py. This means you do not need to hard-code any config and Heroku will handle the connections for you. if not os.environ.get("HOME") == ‘/PATH/TO/YOUR/HOME‘: # Parse database configuration from $DATABASE_URL import dj_database_url DATABASES['default'] = dj_database_url.config() By wrapping the setting of this database connection in the if statement, it allows the configuration to work as is on your local machine but setup the database correctly when on Heroku. You also need to add a requirements.txt, which specifies your Python dependencies for the application so that Heroku can install them into the environment created. Add requirements.txt at the same level as the Procfile with the following contents: Django==1.6.2 dj-database-url==0.3.0 dj-static==0.0.5 django-toolbelt==0.0.1 gunicorn==18.0 newrelic==2.16.0.12 psycopg2==2.5.2 wsgiref==0.1.2 With those files created, add them to Git and then push to the Heroku remote, where it will be received and started. $ git add . $ git commit -m "Added procfile and requirements.txt" $ git push heroku master You should see some output as it is sent to Heroku and will finish with the following message: " deployed to Heroku" If you were to hit the URL now, you would see a failure message. If you recall on your local machine, you needed to run syncdb to create the tables in the database for the application to use. You need to reproduce this behavior on our Heroku instance. Fortunately, Heroku provided a simple way to execute these commands against your application instance in the tool belt you installed previously. $ heroku run python manage.py syncdb You should then be able to visit your link and see the website running on Heroku, for free. Try adding some items to your database in the same way as you did locally, to ensure that the database is all set up correctly. Add New Relic With your application deployed successfully to the Heroku platform, you can now begin to look at the many add-ons that are provided. Heroku provides a great range of add-ons ranging from databases, monitoring tools, advanced log tools, analytics, email providers and many more. The add-ons are one of the great aspects of hosting your application on Heroku as they can quickly and easily be assigned to your application and within minutes, be configured and working. Heroku has streamlined the process for adding in these tools and it takes a lot of the work out of your hands so that you can focus on delivering your product. One of the add-ons this article will focus on, is attaching the great monitoring and analytics tool, New Relic. New Relic has many capabilities for digging into your application and providing statistics and data around items such as requests per minute, errors, response times and more. Best of all, Heroku once again provide a free tier for adding to your website to go along with the free hosting we currently have. Adding New Relic to your Heroku application is simple and requires you to just log in to your Heroku account management page. Once there, click into the application you want to add it to and choose "+ Get Add-Ons". You will then be presented with the wide array of add-ons that Heroku provides. Search through for "New Relic" and click on it. A page showing the description and pricing will be displayed and a breakdown of the features enabled at each price level. For the free tier, you essentially get access to almost every feature but are tied to only the last seven days worth of data. From the New Relic add on page, you can simply copy and paste the code to attach New Relic to your application and run it on the command line. $ heroku addons:add newrelic:stark With that added, you can then revisit your app page within your Heroku account and you should now see New Relic listed below your database. Click it to begin the setup within your New Relic account. Here you will need to accept the terms and conditions and then follow the instructions for installing New Relic into your Django application. These are as follows: - Add " newrelic" to your requirements.txtand then execute: $ pip install -r requirements.txt - Execute this command substituting in the licence key shown to you: $ newrelic-admin generate-config YOUR_LICENCE_KEY newrelic.ini - Open up the newly generated newrelic.iniand change the " app_name" to something meaningful to you, e.g "Django Tuts+" or "Django Portfolio" - Edit the Procfileto include the starting of the New Relic agent with the server: NEW_RELIC_CONFIG_FILE=newrelic.ini newrelic-admin run-program gunicorn tuts.wsgi - Commit and push these changes to Heroku and you should start to see application data reporting to New Relic shortly. $ git add . $ git commit -m "Added New Relic config." $ git push heroku master - After clicking the "Connect App" button on New Relic and sending some requests to the application, New Relic should display that the application has connected and you can click through to your dashboard to see the data. Wrap Up That's all there is to it! Within around 15 minutes, you can have full New Relic application monitoring attached to your application, again for free. Tuts+ have recently had a few great articles introducing New Relic and showing some more advanced techniques and usages for the monitoring tool. You can find the full range of articles or alternatively, you can go straight ahead to my other article on performance testing using New Relic and JMeter. Hopefully you have found this tutorial informative and something which you can dive right into and try for yourself in a spare hour or two. With a bit of styling and some content entered through the admin page Django creates, you can rapidly develop a professional site, hosted and monitored for free. Checkout my website in my author profile that was written in Django, hosted by Heroku and monitored by New Relic , which inspired the writing of this article.
http://code.tutsplus.com/tutorials/rapid-website-deployment-with-django-heroku-new-relic--cms-21543?WT.mc_id=Tuts+_website_relatedtutorials_sidebar
CC-MAIN-2014-42
refinedweb
3,475
62.07
"." is the de-facto way of doing something like this, but now I tend to buy the argument that forcing people to rename their tables will be a lot of trouble. I think it is reasonable to - Remove "." to be a valid table name character. You won't be able to create a table with a "." in the name. - Keep migrated tables under default namespace. default namespace will contain tables with dot in their name as well. - If you have a table "a.b", you cannot create a namespace named "a" - Whenever we refer to table "a.b", we can search for namespace "a", if not found search for table "a.b" in default namespace. Would that work. Enis On Tue, May 7, 2013 at 11:55 PM, James Taylor <jtaylor@salesforce.com>wrote: > Phoenix uses <schema name> . <table name> to reference tables, so > allowing a "." in names would make parsing ambiguous. > > James > > > On 05/07/2013 11:36 PM, Stack wrote: > >> On Tue, May 7, 2013 at 5:22 PM, Francis Liu <toffer@apache.org> wrote: >> >> One thing I had in mind was to automatically assume that the first dot >>> delimits the namespace name. During upgrade we automatically create those >>> namespaces and assign the tables accordingly. They can then eventually >>> migrate/rename their tables (if needed) at a later time. In the extreme >>> case that would be one namespace per table. For which we will provide a >>> tool to rename offline tables. >>> >>> I'm guessing most cases would not require a rename. What else do people >>> use dots in their table name for? >>> >>> >> With namespaces in place, will '.' be illegal in a table name? >> >> With namespaces, is there a no-namespace/default location? If so, what >> will it be called or how will you refer to tables in the >> no-namespace/default namespace? >> >> I just took a user's production website where there are hundreds of >> tables. >> For no good reason that I can see, they happened to have choosen '_' and >> '-' as table name partitioner: i.e. application_feature, etc. My sense is >> they could just as easily have gone with '.' but maybe the '.META.' name >> frightens people away from '.'? >> >> Anyone using '.' in their table names? >> >> St.Ack >> > >
http://mail-archives.apache.org/mod_mbox/hbase-dev/201305.mbox/%3CCAMUu0w8NXXF_5NGiccz_zwgx75mVS36zgaoRrWquGBpb0z=-qA@mail.gmail.com%3E
CC-MAIN-2018-34
refinedweb
369
78.14
Canada is considering Aborigines into their political structure. As the world, especially Canada in this case, orients it's sights toward a more "green" approach, experts must be found to accomodate the transition and these experts are the Aborigines. Their entire lives revolve around consumption and replenishing the natural world, and their vast knowledge will truly be a gift for the "green movement". This is not the only positive benefit from the natives obtaining political seats. This also opens the door a more equal political spectrum. In order to understand and effectively lead a group of people, one must be able to see the positive features and shortcomings of the current political system. The majority of natives have been suppressed, if not oppressed, for many years, and their voice needs to be heard. Natives have endured, and lived in a rather peaceful system, for thousands of years, and Im sure that their way of life could be beneficial for us to comprehend. Wesley, I appreciate the sentiment, but I think the reality of modern native people in Canada is not compatible with your statements. Anecdote and observation leads me to believe that they are as damaging to the environment as any rural Canadians, if not more so because they are not restricted by things like federal and provincial hunting and fishing quotas. I feel extremely sad for Canada's native population. Because of a number of factors, some of which were well-intentioned, their culture is now in tatters, much of their youth hopelessly lost and their general prospects as a people looking grim. Many commenters here have mentioned handouts making other Canadians resent natives, and it's true. But our society is faced with a huge problem - integrating a large group of people that has an even larger set of problems and in many cases has no interest in participating, economically or otherwise. I don't think there is any easy answer to this problem, but whatever it is will likely take generations, and include handouts. In my opinion, giving natives hope for a better future is the only effective method, and that requires involving them in the broader economy. Enabling natives to isolate themselves on their reserves and giving them a truck every few years does nothing to encourage this, while things like vocational and health programs, do. Of course emphasizing the latter over the former is not as easy as it sounds, being as it's all tied up in a complicated set of treaties and native bands are understandably cautious about any changes to their entitlements. I also take issue with your portrayal of natives as peaceful. Yes there were peaceful bands, but there were also brutal ones, by any standard. And modern natives have some of the highest rates of violence in North America. It looks like The Economist didn’t do their homework for this article by first calling the native population by “aborigines”, second failing to realize that 25 native candidates in the Northwest Territories is not that uncommon. I hope that men such as Mr. Saganash will better shape the Canadian political scene. I also hope that more can be done in the United States for the native population that has been vastly marginalized economically and socially. But can anyone explain further what the author meant in the article about Canada’s government wanting to build an alternative pipeline to carry crude oil from Albera’s tar sands to the Pacific coast and then to Asia. Does this imply Candia cutting out the Keystone XL oil pipeline to the United States? I don't know why Europeans continue to refer to Alberta's massive northern oil reserves as the derogatory and wrongly scripted Tar Sands. The reserves are mixed with sand--thus they should be referred to as Oil Sands. Tar is a byproduct of crude oil production, not a natural resource. how interesting that the vast majority of posts on this article deal with political correctness- the proper term for First Nations people, and virtually none with the issues. congratulations to all those whose myopia is symptomatic of the present problems Aborigine: A term not used in Canada, and therefore without connotation. Sounds a bit strange, really. Used in Australia, where most find it offensive and outdated. Aboriginal: Umbrella term for persons of Inuit (north), First Nations (everywhere else), or Métis (mixed First Nations/European) ancestry. All four terms are merely descriptive, and non-offensive when used accurately. First Nations: Umbrella term for the hundreds of individual cultural-linguistic groups (ie nations), eg Cree, Mi'kmaw, Salish, etc. First Nations is not seen to be inclusive of those who do not have their government approved identity - i.e., 'status card', and therefore only refers to those who have treaty relationship "Nation to Nation") with the government. At a Truth and Reconciliation gathering I attended (for Canadian government and Churches setting up Residential Schools which tried to 'kill the Indian in the Indian", "Indigenous" seemed to be the most accurate, covering all groups, and accepted by those who were of indigenous background "Used in Australia, where most find it offensive and outdated" I am Australian and was really confused by this - was there some PC change I was totally unaware of - Aboriginal has NEVER been considered racist as far a I know. So here is a definitive answer I have just rang up my old girlfriend who is aboriginal and heavily involved in politics. After a lovley time catching up on what our kids and families where up to she assured me nothing has changed. Aboriginal is the only proper way way to describe someone unles you are going down to the tribal / nation level though indigenous is starting to be used a little bit. So thank you for motivating me to get off my bottom to catch up with old friends but really - if you are going to say things please make sure they have at least some basis in fact. The way Canadians treat the native people is a really sad reality. I think a big part of this is due to the fact that they get special treatment, other Canadian people are finding it difficult to treat them equally because they don't think that's fair. I am very surprised to see the word aborigines used in the economist because to my knowledge, that term is no longer used at all. Canada is so heavily populated in the major centers of the land that the huge majority of the vast land Canada has is not being used,I think this could help facilitate communication about to do with that land. I am excited to see what Mr. Saganash is going to do in the future, not only for the betterment of the natives, but as Canada as a whole. We wish him good luck We wish him good luck and pray god that one day he be prime minister of canada We wish him good luck and pray god that one day he becomes prime minister of canada As a Canadian, I found 'aborigines' to be rather jarring. Whether the term is offensive or not, it is almost never used in Canada; to me, an aborigine is from Australia. Here the indigenous peoples are called aboriginals or natives, first nations in a political context, or, archaically, indians. I do find it interesting that aborigines seems to be considered racist while aboriginals is not. Is there a reason for this? Or do some syllables simply sound more condescending than others? I am very excited to see the outcome of these Aboriginian efforts. In any situation where a group of people are underrepresented and or under-served, there is historically always one individual that will lead their group in striving for equal representation, which is what Mr. Saganash seems to be doing. His efforts remind me of Civil Rights activists in their pursuit for racial equality in the United States. Mr. Saganash seems to be making excellent progress, and with a strong backing, his efforts won't be unfruitful. I honestly have no idea whether the term is offensive, but the government apparently calls these groups "aboriginal." If that's a problem, I think Mr. Saganash's first order of business should be to rename the department that apparently oversees his people.... Hard to take an article seriously when the title itself is incorrect- there are no Aborigines in Canadian politics. I was extremely disappointed to see that a publication such as The Economist would use the term Aborigine in reference to the Indigenous people of Canada. The appropriate term would be First Nation, Inuit or Metis. In the case of a non-status individual, Native is acceptable. In any case, Native would be better than a term resented in the country in which it originated (Australia). A two second Google search could have prevented such a glaring error. Canadians seem to love to whine no matter what the subject. The responses to this article is no exeception Maybe this will allow Canada to finally have a coherent dialogue about what we want to do with roughly 90% of our territory. Conventional political wisdom seems to relegate it to mining, really crappy federal giveaways and stagnant economy. OK, let's talk sense: in Russia, subsidized (?) airfare lets you fly from Moscow to Naryan-Mar for $450 return (and I wasn't looking at cheapest airfare). How much would it be to fly from Toronto to, say, Yellowknife? Oh, uhm, sorry, you can't even find a direct flight. Airfare into Nunavut (from Ottawa, no less) cost at least over a grand. Only suits in government jobs when employer pays can afford it. Tourism? What tourism? At CAD 5000 per person? What invisible hand of the market? Yet somehow the Department of Aboriginal Affairs sits on an annual budget of 8 billion and fails spectacularly to attract Canadians (who are genuinely curious) to the territories. It may spend millions on ads and branding, but as long as it continues to operate as a self-serving body and not have a realistic plan about how it actually sees thing working long term we're getting nowhere. You see, the "invisible hand of the market" mantra conveniently allows to disown most of the results and lets not to be held accountable for any action - or lack thereof. It is discouraging to see a prestigious publication such as The Economist actually print the word 'aborigines' in the title and all over this article. It is a racist term: get with it! This is 2011 and your editors ought to know better Anything that First Nations folks do to become more constructively involved -- like running for parliament -- is good in my books. Because, in the end, there is not much that Canadian governments can do to solve the problems of First Nations -- they need to do it themselves. We can and should assist, encourage, and do our best to remove barriers, but in the end change must come from within. I will note in particular that a modern post-industrial standard of living depends on high productivity, flexibility, and specialization. That is just not possible with an insular community of 2000 people. Thank you, Aurora11. "Aborigine" is usually only used in reference (by non-natives, usually) to Australian natives, who consider the term racist. Actually not okay to say "Aborigines" no matter who you're talking about, so maybe just stick with "indigenous", "First Nations," or, you know, the actual names of tribal groups. For the record, among Canada's aboriginal peoples the term "natives" is frowned upon, and "aborigines" is not used at all. The way in which us Canadians currently treat our native population is mostly nasty and much worse than anything which happened in the past. If we are to treat them humanely we must come to terms with two things. First, they were and still are a conquered people. When the Europeans came to North American, they conquered the natives with the help of smallpox. The royal decree that they had to negotiate treaties was a fiction to cover the reality. The second is that the way we currently treat natives is working to make them into scapegoats. By allowing them special privileges other Canadians are developing a lot of resentment. As the economy goes down it will be convenient to be able to blame natives rather than ourselves. This is already happening with respect to parts of the West coast fishery where natives are being blamed by some people for a decline of the Fraser River salmon run. The most important thing to do to for natives is to treat them with equality. They should have the same rights and responsibilities as every other Canadian. (The author of this comment has a web log on economics at) Canada (Britain) did not conduct Indian Wars like the US. Most First Nations in Canada were never defeated militarily and many have enduring treaties between them and the Crown. The problem with the Indian Question is that it is complex and subtle. It is not amenable to quick fixes.
http://www.economist.com/comment/1130949
CC-MAIN-2014-52
refinedweb
2,196
60.04
Re: json.js breaks for-in loops Expand Messages - // This should do what you are asking for while staying // current with Crockford's latest code: // after json.js has loaded... // define a namespace to minimize footprint. - On 11/13/06, Stephen M. McKamey <jsonml@...> wrote: >Right. But I don't understand the resistance (or, actually, just lack of any > // This should do what you are asking for while staying > // current with Crockford's latest code: feedback at all) to having the kind of solution I described before (in another thread) incorporated into the original source code, so that we don't have to be going and deleting things like that. Here's what I suggested before, which is largely the same as yours, except that mine avoids creation where yours utilises deletion and is necessarily separate (and hence a little less easily maintained) from the original: -- Martin Cooper // after json.js has loaded... > // define a namespace to minimize footprint[Non-text portions of this message have been removed] >. > > > > > > > Yahoo! Groups Links > > > > > -.
https://groups.yahoo.com/neo/groups/json/conversations/topics/588?l=1
CC-MAIN-2015-14
refinedweb
171
59.84
#include <wx/archive.h> This is an abstract base class which serves as a common interface to archive input streams such as wxZipInputStream. wxArchive(). Closes the current entry. On a non-seekable stream reads to the end of the current entry first. Implemented in wxZipInputStream, and wxTarInputStream. Closes the current entry if one is open, then reads the meta-data for the next entry and returns it in a wxArchiveEntry object, giving away ownership. Reading this wxArchiveInputStream then returns the entry's data. Closes the current entry if one is open, then opens the entry specified by the wxArchiveEntry object. entry must be from the same archive file that this wxArchiveInputStream is reading, and it must be reading it from a seekable stream.
https://docs.wxwidgets.org/stable/classwx_archive_input_stream.html
CC-MAIN-2018-51
refinedweb
123
64.91
Quoting from CPAN's web site "CPAN is the Comprehensive Perl Archive Network, a large collection of Perl software and documentation." That really says it all. It is a central location where Perl developers can contribute the software they write. CPAN has a means of standardizing installation, Makefile.pl (which is a Perl script which creates a Makefile with targets like "install", "test", "config", "clean", etc.). Makefile.pl typically uses the MakeMover module. It also has a means of registering a namespace for the module that a developer is contributing. From the Boost web site "[Boost]." From what I can tell, unlike CPAN, Boost is a bit more focused on standards and review. That is, it is perhaps more Cathedral than Bazaar [1]. Boost does not currently have a standard means of installation.
https://www.haskell.org/cabal/proposal-1.1/x715.html
CC-MAIN-2015-35
refinedweb
133
67.96
One of the most common questions I get as a consultant is, "What is the difference between a liveness and a readiness probe?" The next most frequent question is, "Which one does my application need?" Anyone who has tried Duck Duck Go-ing these questions knows that they are difficult to answer using an internet search. In this article, I hope to help you answer these questions for yourself. I will share my opinion about the best way to use liveness and readiness probes in applications deployed to Red Hat OpenShift. I'm not offering a hard prescription but rather a general framework that you can use to make your own architectural decisions. Each application is different, and these differences might require adapting the "rules" you learn here. To help make the abstract more concrete, I offer four generic example applications. For each one, we'll explore whether and how to configure liveness and readiness probes. Before we dive into the examples, let's look more closely at the two different probe types. Note: Kubernetes has recently adopted a new "startup" probe available in OpenShift 4.5 clusters. The startup probe does not replace liveness and readiness probes. You'll quickly understand the startup probe once you understand liveness and readiness probes. I won't cover startup probes here. Liveness and readiness probes Liveness and readiness are the two main probe types available in OpenShift. They have similar configuration APIs but different meanings to the platform. When a liveness probe fails, it signals to OpenShift that the probed container is dead and should be restarted. When a readiness probe fails, it indicates to OpenShift that the container being probed is not ready to receive incoming network traffic. The application might become ready in the future, but it should not receive traffic now. If the liveness probe succeeds while the readiness probe fails, OpenShift knows that the container is not ready to receive network traffic but is working to become ready. For example, this is common in applications that take time to initialize or to handle long-running calls synchronously. (Handling long-running calls synchronously is an anti-pattern, but unfortunately, we are stuck with it in some legacy applications.) Next, we'll zoom in on the specific uses for each of these probe types. Once we understand the probe types in isolation, I'll show you examples of how they work together in OpenShift. What are liveness probes for? A liveness probe sends a signal to OpenShift that the container is either alive (passing) or dead (failing). If the container is alive, then OpenShift does nothing because the current state is good. If the container is dead, then OpenShift attempts to heal the application by restarting it. The name liveness probe expresses a semantic meaning. In effect, the probe answers the true-or-false question: "Is this container alive?" What if I don't specify a liveness probe? If you don't specify a liveness probe, then OpenShift will decide whether to restart your container based on the status of the container's PID 1 process. The PID 1 process is the parent process of all other processes that run inside the container. Because each container begins life with its own process namespace, the first process in the container will assume the special duties of PID 1. If the PID 1 process exits and no liveness probe is defined, OpenShift assumes (usually safely) that the container has died. Restarting the process is the only application-agnostic, universally effective corrective action. As long as PID 1 is alive, regardless of whether any child processes are running, OpenShift will leave the container running. If your application is a single process, and that process is PID 1, then this default behavior might be precisely what you want—meaning that you don't need a liveness probe. If you are using an init tool such as tini or dumb-init, then it might not be what you want. The decision of whether to define your own liveness probe instead of using the default behavior is specific to each application What are readiness probes for? OpenShift services use readiness probes to know whether the container being probed is ready to start receiving network traffic. If your container enters a state where it is still alive but cannot handle incoming network traffic (a common scenario during startup), you want the readiness probe to fail. That way, OpenShift will not send network traffic to a container that isn't ready for it. If OpenShift did prematurely send network traffic to the container, it could cause the load balancer (or router) to return a 502 error to the client and terminate the request; either that or the client would get a "connection refused" error message. Like the liveness probe, the name of the readiness probe conveys a semantic meaning. In effect, this probe answers the true-or-false question: "Is this container ready to receive network traffic?" What if I don't specify a readiness probe? If you don't specify a readiness probe, OpenShift will assume that the container is ready to receive traffic as soon as PID 1 has started. This is never what you want. Assuming readiness without checking for it will cause errors (such as 502s from the OpenShift router) anytime a new container starts up, such as on scaling events or deployments. Without a readiness probe, you will get bursts of errors every time you deploy, as the old containers terminate and the new ones start up. If you are using autoscaling, then depending on the metric threshold you set, new instances could be started and stopped at any time, especially during times of fluctuating load. As the application scales up or down, you will get bursts of errors, as containers that are not quite ready to receive network traffic are included in the load-balancer distribution. You can easily fix these problems by specifying a readiness probe. The probe gives OpenShift a way to ask your container if it is ready to receive traffic. Next, let's look at specific examples that will help us understand the difference between the two types of probes and the importance of getting them right. Note: The fact that there are different types of probes with identical APIs is a frequent source of confusion. But the existence of two or more probe types is good design: It makes OpenShift flexible for various application types. The availability of both liveness and readiness probes is critical to OpenShift's reputation for being a Container-as-a-Service that accommodates a wide range of applications. Example 1: A static file server (Nginx) The example application shown in Figure 1 is a simple static file server that uses Nginx to serve files. Startup time is low, and it is straightforward to check whether the server is handling traffic: You can request a known page and verify that a 200 HTTP response is returned. Do we need a liveness probe? The application starts up quickly and will exit if it encounters an error that prevents it from serving pages. So, in this case, we do not need a liveness probe. An exited Nginx process means that the application has died and needs to be restarted. (Note that issues like SELinux problems or misconfigured filesystem permissions will not cause Nginx to exit, but a restart wouldn't fix those anyway.) Do we need a readiness probe? Nginx is handling incoming network traffic, so we do need a readiness probe. Anytime you are handling network traffic, you need a readiness probe to avoid encountering container startup errors, such as deployment and autoscaling. Nginx starts up quickly, so you might get lucky, but we still want to avoid forwarding traffic until the container is ready, as per best practice. Updating the server with a readiness probe We will need to make specific changes for each example, but first, here is the top part of the Deployment. We'll change this file as we go, but the top part will remain the same. For future examples, we will only need to modify the template spec. apiVersion: apps/v1 kind: Deployment metadata: labels: app: application-nginx name: application-nginx spec: replicas: 1 selector: matchLabels: app: application-nginx template: metadata: labels: app: application-nginx spec: # Will appear below as it changes Here is the probe configuration for the first example: spec: containers: - image: quay.io/<username>/nginx:latest name: application-nginx imagePullPolicy: Always ports: - containerPort: 8443 protocol: TCP readinessProbe: httpGet: scheme: HTTPS path: /index.html port: 8443 initialDelaySeconds: 10 periodSeconds: 5 Example 2: A jobs server (no REST API) Many applications have an HTTP web component, as well as an asynchronous "jobs" component. Jobs do not need a readiness check because they don't handle incoming network traffic. However, they do need a liveness check. If the process running the jobs dies, then the container is worthless, and jobs will accumulate in the queue. Typically, restarting the container is the correct thing to do, so a liveness probe is ideal here. The example application in Figure 3 is a simple job server that pops and runs tasks from a queue. It does not directly handle incoming network traffic. I've already mentioned that this type of application benefits from a liveness probe, but it doesn't hurt to go through the process of inquiry anyway. Do we need a liveness probe? When our job is running properly, it will be a living process. If the jobs container stops working, it is most likely a crash, unhandled exception, or something similar. How we set up the probe, in this case, depends on whether our job process is running as PID 1. If our job process is PID 1, it will exit when it encounters an exception. With no liveness probe specified, OpenShift will see the exit of PID 1 as a death and will restart the container. For a trivial jobs server, a restart might not be what we want. In real life, however, things can sometimes be more complicated. For example, if our jobs process encounters a deadlock, it might still appear to be alive because the process is running, but it's clearly in a failed state and should be restarted. To help detect deadlock, our application will write the current system time in milliseconds to a file at /tmp/jobs.update whenever it processes a job. This time will then be checked with a shell command (via the exec liveness probe) to ensure that the current job has not been running for longer than a given timeout value. The application can then check itself for liveness by executing /usr/bin/my-application-jobs --alive. We can set up a liveness probe as follows (again, I am omitting the first part of the Deployment YAML file, which I showed previously): spec: containers: - image: quay.io/<username>/my-application-jobs:latest name: my-application-jobs imagePullPolicy: Always livenessProbe: exec: command: - /bin/sh - -c - "/usr/bin/my-application-jobs --alive" initialDelaySeconds: 10 periodSeconds: 5 Do we need a readiness probe? In this case, there is no need for a readiness probe. Remember that a readiness probe sends a signal to OpenShift that the container is ready to handle network traffic and so can be added to the load balancer. Because this application does not handle incoming network traffic, it doesn't need to be checked for readiness. We can leave off the readiness probe. Figure 4 shows the jobs server implementation with a liveness probe configured. Example 3: A server-side rendered application with an API This example is a standard server-side rendered (SSR) application: It renders HTML pages on the server, on-demand, and sends them to the client. We could build an application like this using Spring Boot, PHP, Ruby on Rails, Django, Node.js, or any similar framework. Do we need a liveness probe? If the application starts up in a few seconds or less, then a liveness probe is probably unnecessary. If it takes more than a few seconds, we should put in a liveness probe to ensure that the container initializes without error rather than crashing. In this case, we could use an exec type of liveness probe, which runs a shell command to ensure that things are still running. This command will vary depending on the application. For example, if the app writes a PID file, we could check that it is still alive: livenessProbe: exec: command: - /bin/sh - -c - "[ -f /run/my-application-web.pid ] && ps -A | grep my-application-web" initialDelaySeconds: 10 periodSeconds: 5 Do we need a readiness probe? Because this application handles incoming network requests, we will definitely want a readiness probe. Without a readiness probe, OpenShift will immediately send network traffic to our container after starting it, whether the application is ready or not. If the container starts dropping requests but hasn't crashed, it will continue to receive traffic indefinitely, which is certainly not what we want. We want OpenShift to remove the container from the load balancer if it ceases to return healthy responses. We can use a readiness probe like this one to signal to OpenShift that the container is ready to receive network traffic: readinessProbe: httpGet: scheme: HTTPS path: /healthz port: 8443 initialDelaySeconds: 10 periodSeconds: 5 For easy reference, here's the complete YAML for this example app: apiVersion: apps/v1 kind: Deployment metadata: labels: app: backend-service name: backend-service spec: replicas: 1 selector: matchLabels: app: backend-service template: metadata: labels: app: backend-service spec: containers: - image: quay.io/<username>/backend-service:latest name: backend-service imagePullPolicy: Always ports: - containerPort: 8443 protocol: TCP readinessProbe: httpGet: scheme: HTTPS path: /healthz port: 8443 initialDelaySeconds: 10 periodSeconds: 5 Figure 6 shows a diagram of the SSR application with both liveness and readiness probes configured. Example 4: Putting it all together In a complete, complex, and realistic application, you might have elements of all three of the previous examples. Taking them individually is useful for considering probes, but it's also helpful to see them working together to serve a large application with millions of requests. This final example consolidates the other three. This example application consists of three container pieces: - The application server: This server provides a REST API and performs server-side rendering for some pages. This setup is widespread, as applications that begin as simple server-side renderers are later enhanced to provide REST API endpoints. - A Nginx static file server: This container has two jobs: It renders static assets for the application (such as JavaScript and CSS assets). It also provides TLS (Transport Layer Security) termination for the application server by acting as a reverse proxy for certain paths. This is also a widespread setup. - A jobs server: This container does not handle incoming network traffic on its own but rather processes jobs. The application server pushes each job to a queue, where the jobs server picks it up and executes it. The jobs server frees up the application server to focus on processing network requests rather than running long threads. The example app also includes a couple of data persistence services: - A relational database: The relational database is the source of state for our application. Nearly every application needs a database of some kind, and relational databases are the majority choice. - A queue: The queue provides a first-in, first-out (FIFO) way for the application server to communicate tasks to the jobs server. The app server will always push, and the jobs server will pop. Our containers are spread into two pods: - The first pod consists of our application server and the Nginx TLS terminator or static file server. This simplifies the application server's management by allowing it to communicate directly over HTTP. By sharing a pod, these containers can communicate securely and directly with minimal latency. They also can access a shared volume space. The containers need to be scaled together and treated as a single unit, so a pod is the perfect unit of organization. - The second pod consists of the jobs server. This server needs to scale independently of the other containers, so it must be in its own pod. Because all state is held in the database and queue, the jobs server can easily access the resources that it needs. If you followed the previous examples, the solution here should not be surprising. To integrate, we switch the application server to use HTTP and port 8080 instead of HTTPS and 8443 for the readiness probe. We also add a liveness probe to the application server to cover us if the application server doesn't exit on error. This way, our container will be restarted by the Kubelet once it is "dead": # Pod One - Application Server and Nginx apiVersion: apps/v1 kind: Deployment metadata: labels: app: my-application-web name: my-application-web spec: replicas: 1 selector: matchLabels: app: my-application-web template: metadata: labels: app: my-application-web spec: containers: - image: quay.io/<username>/my-application-nginx:latest name: my-application-nginx imagePullPolicy: Always ports: - containerPort: 8443 protocol: TCP livenessProbe: exec: command: - /bin/sh - -c - "[ -f /run/nginx.pid ] && ps -A | grep nginx" initialDelaySeconds: 10 periodSeconds: 5 readinessProbe: httpGet: scheme: HTTPS path: /index.html port: 8443 initialDelaySeconds: 10 periodSeconds: 5 - image: quay.io/<username>/my-application-app-server:latest name: my-application-app-server imagePullPolicy: Always ports: - containerPort: 8080 protocol: TCP livenessProbe: exec: command: - /bin/sh - -c - "/usr/bin/my-application-web --alive" initialDelaySeconds: 10 periodSeconds: 5 readinessProbe: httpGet: scheme: HTTP path: /healthz port: 8080 initialDelaySeconds: 10 periodSeconds: 5 # Pod Two - Jobs Server apiVersion: apps/v1 kind: Deployment metadata: labels: app: my-application-jobs name: my-application-jobs spec: replicas: 1 selector: matchLabels: app: my-application-jobs template: metadata: labels: app: my-application-jobs spec: containers: - image: quay.io/<username>/my-application-jobs:latest name: my-application-jobs imagePullPolicy: Always livenessProbe: exec: command: - /bin/sh - -c - "/usr/bin/my-application-jobs --alive" initialDelaySeconds: 10 periodSeconds: 5 Figure 8 shows the complete example applications with both probes configured. What about identical liveness and a readiness probes? While this pattern is overused, in my opinion, there are cases where it makes sense. If the application starts experiencing failed HTTP calls, and will likely never come back to ready without a restart, then you probably want OpenShift to restart the pod. It would be better if your application recovered on its own, but that is sometimes not practical in the real world. If you have an HTTP endpoint that is a good canary, you could set up a liveness probe and a readiness probe to hit this same endpoint. Using the same endpoint ensures that your pod will restart if it fails to return success on that endpoint. Final thoughts Liveness and readiness probes send different signals to OpenShift. Each has a specific meaning, and they are not interchangeable. A failed liveness probe tells OpenShift to restart the container. A failed readiness probe tells OpenShift to hold off on sending traffic to that container. There is no one-size-fits-all prescription for probes because the "correct" choice will vary depending on how the application is written. An application that can self-heal will need a different probe setup than one that simply crashes and dies. When deciding on the correct probes for an application, I consider the probe's semantic meaning in conjunction with the application's behavior. Knowing that failing liveness probes will restart the container and failing readiness probes will remove it from the load balancer. It is usually not complicated to determine which probes the application needs. We have considered realistic examples, but you might see considerably more complexity in real systems. For instance, in a service-oriented architecture (SOA), a service might depend on another service to handle requests. If the downstream service is not ready, should the readiness probe for the upstream be healthy or not? The answer is dependent on the application. You will need to do a cost/benefit analysis to determine whether the added complexity is worth it. While probes are conceptually very simple, they can be complex in practice. The best way to narrow it down is to iterate! Do performance testing and chaos testing to determine how your configuration behaves and improve as you go. We rarely get it right the first time.Last updated: November 9, 2020
https://developers.redhat.com/blog/2020/11/10/you-probably-need-liveness-and-readiness-probes
CC-MAIN-2022-05
refinedweb
3,402
52.8
Nobody, who can tell me why I see 2 toolbars: Type: Posts; User: madmaxmatze Nobody, who can tell me why I see 2 toolbars: @Gary: Thanks for your response, but your example seems not related. Maybe you could show my jsFiddle example () to a extjs dev... The toolbar feature in my app is not working together with locked columns. The reduced example shows the problem of a duplicated toolbar: Thanks for every idea to... The <br> workaround works fine (I'm using Extjs 4.0) The header just looks strange if the column is right aligned and sorting is used. Do you have a solution for this? The same problem occurs with toolbars. If I hide its border, a light line remains on the top from the background image. With Dev Preview 5 this problem was not existing. My current workaround is to use the CollapseHandler. The issue can be tested using: LabelProvider<String> comboLabelProvider = new... When trying to hide the frameborder with: panel.setBodyBorder(false); panel.getHeader().setBorders(false); ... the top border is not disappearing, because it's part of the background image. The probem: The error message which appears when hovering the exclamation mark when validating a form, is perfect when showed first. The second time the message is positioned incorrectely. How to... Any reaction? Did anybody from the GXT dev team try to reproduce this error with the test case I provided? In order to change the caption for tabs after they have been added, I tried to use TabPanel.update as described here:... To test the last issue, please use the following code: (Error occures with click on button) public class Designer implements EntryPoint { public void onModuleLoad() { BorderLayoutContainer... Thanks for the getWidget() hint - works! :) The other issue is now gone as well. I didn't realized that even with uibinder the BorderLayoutData has to be passed with the container.setNorthWidget()... When I create a simple example, the problem is fixed with adding BorderLayoutData as suggested in the other bug report: BorderLayoutContainer container = new BorderLayoutContainer(); ... Adding layout data to my uibinder definition as in Did not fix the problem. But hopefully the next release will. What's... I'm not sure if the AccordionLayout is still under development - errors included, or if I'm using it totally wrong: -------------------------------- When I create an AccordionLayout like in... Another question: Where can I find out how and which tags need to be used and structured for the UiBinder declaration, based on existing java code? Current example: I just can't find out how to... Vielen Dank! =D> I can't figure out how to force the BorderLayoutContainer to be full screen/consume all its parents space, like: Instead of:... Using the "old" way of creating elements solved my problem 100% - with windows, drawComponents, etc. So it seems the renderTo attribute is not working very well or has to be used in a different way. To test this issue, please visit: Within the source I clearly marked all changes I made. I would really appreciate any help on this!!! I did the following: - used complex layout from: - added id "tab1_panel" to the first tab in the center. - added a window at... Furthermore I'm searching for the best way to build a kind of auto scroll when selection images. Since in the moment you are limited to the images that fit into you data-view. So the data-view... As you see, Im kind of new to this whole EXT thing... so can you please escalate the bug to the right person or place? Sorry, my mistake. I meant another example: When try to select multiple images with holding the left mouse key, then the selection... There is a problem when selecting images in the image organizer example () If you scroll down and start selecting, the selection area is not...
https://www.sencha.com/forum/search.php?s=469dbe93ca49fd5c4ba6e86b7563e7cc&searchid=19161868
CC-MAIN-2017-17
refinedweb
639
65.73
The previous article showed you what the communication between web clients and servers looks like, the nature of HTTP requests and responses, and what a server-side web application needs to do in order to respond to requests from a web browser. With this knowledge under our belt, it's time to explore how web frameworks can simplify these tasks, and give you an idea of how you'd choose a framework for your first server-side web application. The following sections illustrate some points using code fragments taken from real web frameworks. Don't be concerned if it doesn't all make sense now; we'll be working you through the code in our framework-specific modules. Overview Server-side web frameworks (a.k.a. "web application frameworks") are software frameworks that make it easier to write, maintain and scale web applications. They provide tools and libraries that simplify common web development tasks, including routing URLs to appropriate handlers, interacting with databases, supporting sessions and user authorization, formatting output (e.g. HTML, JSON, XML), and improving security against web attacks. The next section provides a bit more detail about how web frameworks can ease web application development. We then explain some of the criteria you can use for choosing a web framework, and then list some of your options. What can a web framework do for you? Web frameworks provide tools and libraries to simplify common web development operations. You don't have to use a server-side web framework, but it is strongly advised — it will make your life a lot easier. This section discusses some of the functionality that is often provided by web frameworks (not every framework will necessarily provide all of these features!). Work directly with HTTP requests and responses As we saw in the last article, web servers and browsers communicate via the HTTP protocol — servers wait for HTTP requests from the browser and then return information in HTTP responses. Web frameworks allow you to write simplified syntax that will generate server-side code to work with these requests and responses. This means that you will have an easier job, interacting with easier, higher-level code rather than lower level networking primitives. The example below shows how this works in the Django (Python) web framework. Every "view" function (a request handler) receives an HttpRequest object containing request information, and is required to return an HttpResponse object with the formatted output (in this case a string). # Django view function from django.http import HttpResponse def index(request): # Get an HttpRequest (request) # perform operations using information from the request. # Return HttpResponse return HttpResponse('Output string to return') Route requests to the appropriate handler Most sites will provide a number of different resources, accessible through distinct URLs. Handling these all in one function would be hard to maintain, so web frameworks provide simple mechanisms to map URL patterns to specific handler functions. This approach also has benefits in terms of maintenance, because you can change the URL used to deliver a particular feature without having to change the underlying code. Different frameworks use different mechanisms for the mapping. For example, the Flask (Python) web framework adds routes to view functions using a decorator. @app.route("/") def hello(): return "Hello World!" While Django expects developers to define a list of URL mappings between a URL pattern and a view function. urlpatterns = [ url(r'^$', views.index), # example: /best/myteamname/5/ url(r'^best/(?P<team_name>\w.+?)/(?P<team_number>[0-9]+)/$', views.best), ] Make it easy to access data in the request Data can be encoded in an HTTP request in a number of ways. An HTTP GET request to get files or data from the server may encode what data is required in URL parameters or within the URL structure. An HTTP POST request to update a resource on the server will instead include the update information as "POST data" within the body of the request. The HTTP request may also include information about the current session or user in a client-side cookie. Web frameworks provide programming-language-appropriate mechanisms to access this information. For example, the HttpRequest object that Django passes to every view function contains methods and properties for accessing the target URL, the type of request (e.g. an HTTP GET), GET or POST parameters, cookie and session data, etc. Django can also pass information encoded in the structure of the URL by defining "capture patterns" in the URL mapper (see the last code fragment in the section above). Abstract and simplify database access Websites use databases to store information both to be shared with users, and about users. Web frameworks often provide a database layer that abstracts database read, write, query, and delete operations. This abstraction layer is referred to as an Object-Relational Mapper (ORM). Using an ORM has two benefits: - You can replace the underlying database without necessarily needing to change the code that uses it. This allows developers to optimize for the characteristics of different databases based on their usage. - Basic validation of data can be implemented within the framework. This makes it easier and safer to check that data is stored in the correct type of database field, has the correct format (e.g. an email address), and isn't malicious in any way (crackers can use certain patterns of code to do bad things such as deleting database records). For example, the Django web framework provides an ORM, and refers to the object used to define the structure of a record as the model. The model specifies the field types to be stored, which may provide field-level validation on what information can be stored (e.g. an email field would only allow valid email addresses). The field definitions may also specify their maximum size, default values, selection list options, help text for documentation, label text for forms etc. The model doesn't state any information about the underlying database as that is a configuration setting that may be changed separately of our code. The first code snippet below shows a very simple Django model for a Team object. This stores the team name and team level as character fields and specifies a maximum number of characters to be stored for each record. The team_level is a choice field, so we also provide a mapping between choices to be displayed and data to be stored, along with a default value. #best/models.py from django.db import models class Team(models.Model): team_name = models.CharField(max_length=40) TEAM_LEVELS = ( ('U09', 'Under 09s'), ('U10', 'Under 10s'), ('U11', 'Under 11s'), ... #list our other teams ) team_level = models.CharField(max_length=3,choices=TEAM_LEVELS,default='U11') second code snippet shows a view function (resource handler) for displaying all of our U09 teams. In this case we specify that we want to filter for all records where the team_level field has exactly the text 'U09' (note below how this criteria is passed to the filter() function as an argument with field name and match type separated by double underscores: team_level__exact). #best/views.py from django.shortcuts import render from .models import Team def youngest(request): list_teams = Team.objects.filter(team_level__exact="U09") context = {'youngest_teams': list_teams} return render(request, 'best/index.html', context) Rendering data Web frameworks often provide templating systems. These allow you to specify the structure of an output document, using placeholders for data that will be added when a page is generated. Templates are often used to create HTML, but can also create other types of document. Web frameworks often provide a mechanism to make it easy to generate other formats from stored data, including JSON and XML. For example, the Django template system allows you to specify variables using a "double-handlebars" syntax (e.g. { { variable_name } }), which will be replaced by values passed in from the view function when a page is rendered. The template system also provides support for expressions (with syntax: {% expression %}), which allow templates to perform simple operations like iterating list values passed into the template. Note: Many other templating systems use a similar syntax, e.g.: Jinja2 (Python), handlebars (JavaScript), moustache (JavaScript), etc. The code snippet below shows how this works. Continuing the "youngest team" example from the previous section, the HTML template is passed a list variable called youngest_teams by the view. Inside the HTML skeleton we have an expression that first checks if the youngest_teams variable exists, and then iterates it in a for loop. On each iteration the template displays the team's team_name value in a list item. #best/templates/best/index.html <!DOCTYPE html> <html lang="en"> <body> {% if youngest_teams %} <ul> {% for team in youngest_teams %} <li>{{ team.team_name }}</li> {% endfor %} </ul> {% else %} <p>No teams are available.</p> {% endif %} </body> </html> it optimisation where you store all or part of a web response so that it does not have to be recalculated on subsequent requests. Returning a cached response. We've chosen Django (Python) and Express (Node/JavaScript) to write our examples later on in the course, mainly because they are easy to learn and have good support. Note: Let's go to the main websites for Django (Python) and Express (Node/JavaScript) and check out their documentation and community. - Navigate to the main sites (linked above) - Click on the Documentation menu links (named things like "Documentation, Guide, API Reference, Getting Started", etc.). - Can you see topics showing how to set up URL routing, templates, and databases/models? - Are the documents clear? - Navigate to mailing lists for each site (accessible from Community links). - How many questions have been posted in the last few days - How many have responses? - Do they have an active community? A few good web frameworks? Let's now move on, and discuss a few specific server-side web frameworks. The server-side frameworks below represent a few of the most popular available at the time of writing. All of them have everything you need to be productive — they are open source, are under active development, have enthusiastic communities creating documentation and helping users on discussion boards, and are used in large numbers of high-profile websites. There are many other great server-side frameworks that you can discover using a basic internet search. Note: Descriptions come (partially) from the framework websites! Django (Python) follows the "Batteries included" philosophy and provides almost everything most developers might want to do "out of the box". Because everything is included, it all works together, follows consistent design principles, and has extensive and up-to-date documentation. It is also fast, secure, and very scalable. Being based on Python, Django code is easy to read and to maintain. Popular sites using Django (from Django home page) include: Disqus, Instagram, Knight Foundation, MacArthur Foundation, Mozilla, National Geographic, Open Knowledge Foundation, Pinterest, Open Stack. Flask (Python) Flask is a microframework for Python. While minimalist, Flask can create serious websites out of the box. It contains a development server and debugger, and includes support for Jinja2 templating, secure cookies, unit testing, and RESTful request dispatching. It has good documentation and an active community. Flask has become extremely popular, particularly for developers who need to provide web services on small, resource-constrained systems (e.g. running a web server on a Raspberry Pi, Drone controllers, etc.) Express (Node.js/JavaScript) Express is a fast, unopinionated, flexible and minimalist web framework for Node.js (node is a browserless environment for running JavaScript). It provides a robust set of features for web and mobile applications and delivers useful HTTP utility methods and middleware. Express is extremely popular, partially because it eases the migration of client-side JavaScript web programmers into server-side development, and partially because it is resource-efficient (the underlying node environment uses lightweight multitasking within a thread rather than spawning separate processes for every new web request). Because Express is a minimalist web framework it does not incorporate every component that you might want to use (for example, database access and support for users and sessions are provided through independent libraries). There are many excellent independent components, but sometimes it can be hard to work out which is the best for a particular purpose! Many popular server-side and full stack frameworks (comprising both server and client-side frameworks) are based on Express, including Feathers, ItemsAPI, KeystoneJS, Kraken, LoopBack, MEAN, and Sails. A lot of high profile companies use Express, including: Uber, Accenture, IBM, etc. (a list is provided here). Deno (JavaScript) Deno is a simple, modern, and secure JavaScript/TypeScript runtime and framework built on top of Chrome V8 and Rust. Deno is powered by Tokio — a Rust-based asynchronous runtime which lets it serve web pages faster. It also has internal support for WebAssembly, which enables the compilation of binary code for use on the client-side. Deno aims to fill in some of the loop-holes in Node.js by providing a mechanism that naturally maintains better security. Deno's features include: - Security by default. Deno modules restrict permissions to file, network, or environment access unless explicitly allowed. - TypeScript support out-of-the-box. - First-class await mechanism. - Built-in testing facility and code formatter ( deno fmt) - (JavaScript) Browser compatibility: Deno programs that are written completely in JavaScript excluding the Denonamespace (or feature test for it), should work directly in any modern browser. - Script bundling into a single JavaScript file. Deno provides an easy yet powerful way to use JavaScript for both client- and server-side programming. Ruby on Rails (Ruby) Rails (usually referred to as "Ruby on Rails") is a web framework written for the Ruby programming language. Rails follows a very similar design philosophy to Django. Like Django it provides standard mechanisms for routing URLs, accessing data from a database, generating HTML from templates and formatting data as JSON or XML. It similarly encourages the use of design patterns like DRY ("dont repeat yourself" — write code only once if at all possible), MVC (model-view-controller) and a number of others. There are of course many differences due to specific design decisions and the nature of the languages. Rails has been used for high profile sites, including: Basecamp, GitHub, Shopify, Airbnb, Twitch, SoundCloud, Hulu, Zendesk, Square, Highrise. Laravel (PHP). ASP.NET ASP.NET is an open source web framework developed by Microsoft for building modern web applications and services. With ASP.NET you can quickly create web sites based on HTML, CSS, and JavaScript, scale them for use by millions of users and easily add more complex capabilities like Web APIs, forms over data, or real time communications. One of the differentiators for ASP.NET is that it is built on the Common Language Runtime (CLR), allowing programmers to write ASP.NET code using any supported .NET language (C#, Visual Basic, etc.). Like many Microsoft products it benefits from excellent tools (often free), an active developer community, and well-written documentation. ASP.NET is used by Microsoft, Xbox.com, Stack Overflow, and many others. Mojolicious (Perl) Mojolicious is a next-generation web framework for the Perl programming language. Back in the early days of the web, many people learned Perl because of a wonderful Perl library called CGI. It was simple enough to get started without knowing much about the language and powerful enough to keep you going. Mojolicious implements this idea using bleeding edge technologies. Some of the features provided by Mojolicious are: - A real-time web framework, to easily grow single-file prototypes into well-structured MVC web applications. - RESTful routes, plugins, commands, Perl-ish templates, content negotiation, session management, form validation, testing framework, static file server, CGI/PSGI detection, and first-class Unicode support. - A full-stack HTTP and WebSocket client/server implementation with IPv6, TLS, SNI, IDNA, HTTP/SOCKS5 proxy, UNIX domain socket, Comet (long polling), keep-alive, connection pooling, timeout, cookie, multipart, and gzip compression support. - JSON and HTML/XML parsers and generators with CSS selector support. - Very clean, portable and object-oriented pure-Perl API with no hidden magic. - Fresh code based upon years of experience, free and open-source. Spring Boot (Java) Spring Boot is one of a number of projects provided by Spring. It is a good starting point for doing server-side web development using Java. Although definitely not the only framework based on Java it is easy to use to create stand-alone, production-grade Spring-based Applications that you can "just run". It is an opinionated view of the Spring platform and third-party libraries but allows to start with minimum fuss and configuration. It can be used for small problems but its strength is building larger scale applications that use a cloud approach. Usually multiple applications run in parallel talking to each other, with some providing user interaction and others doing back end work (e.g. accessing databases or other services). Load balancers help to ensure redundancy and reliability or allow geolocated handling of user requests to ensure responsiveness. Summary This article has shown that web frameworks can make it easier to develop and maintain server-side code. It has also provided a high level overview of a few popular frameworks, and discussed criteria for choosing a web application framework. You should now have at least an idea of how to choose a web framework for your own server-side development. If not, then don't worry — later on in the course we'll give you detailed tutorials on Django and Express to give you some experience of actually working with a web framework. For the next article in this module we'll change direction slightly and consider web security.
https://developer.mozilla.org/ms/docs/Learn/Server-side/First_steps/Web_frameworks
CC-MAIN-2020-45
refinedweb
2,928
54.52
Created on 2012-02-17.22:45:43 by pekka.klarck, last changed 2015-03-17.14:22:09 by zyasoft. On my Linux machine with UTF-8 system encoding I got the following: $ a=ä python Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.environ['a'] '\xc3\xa4' >>> _.decode('UTF-8') u'\xe4' $ a=ä jython Jython 2.5.2 (Release_2_5_2:7206, Mar 2 2011, 23:12:06) [Java HotSpot(TM) Server VM (Sun Microsystems Inc.)] on java1.6.0_21 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.environ['a'] '\xe4' I have seen Jython to return similarly wrong bytes earlier (e.g. #1592 and #1593) and know that I can decode them using this hack: >>> from java.lang import String >>> String(os.environ['a']).toString() u'\xe4' The problem is that if I set environment variables myself and encode them correctly, using the hack doesn't work: >>> os.environ['b'] = u'\xe4'.encode('UTF-8') >>> String(os.environ['b']).toString() u'\xc3\xa4' In other words I needed to know has the value been set before or during the execution. It turns out that I actually can do that using using java.lang.System.getenv which only knows about the former: >>> from java.lang.System import getenv >>> getenv('a') u'\xe4' >>> getenv('b') is None True Notice also how getenv above returned the correct value as Unicode. What is the setting of "python.console.encoding" in your registry file? Is it set to the actual encoding of your shell? Note also that you should really be passing an encoding to the String constructor when decoding from bytes, i.e. >>> os.environ['b'] = u'\xe4'.encode('UTF-8') >>> String(os.environ['b'], "UTF-8").toString() If you don't specify an encoding, the bytes are unlikely to be decoded properly. No answer in a long time, closing as out of date. Sorry, hadn't noticed Alan's question. Where is the registry file stored? I certainly haven't touched it. Found the registry. "python.console.encoding" is commented out. Pekka: by default it is commented out, I think Alan is suggesting that you specify an encoding. Opening back up. Behavior as of - note that a unicode object is now returned, not a str $ a=ä jython27 -c "import os; print repr(os.environ['a'])" u'\xe4' It's really the only choice we have since we are on Java. But at least it's not an incorrect bytestring. Inconsistency with CPython is not ideal, but returning correct Unicode is definitely better than returning incorrect bytes. How does setting environment variables work now? Should it also be set as Unicode and not as bytes like with CPython? Do you get correct Unicode out if you later query the value? Setting os.environ should be done with Unicode, but we can support bytes as well if we have an encoding. Otherwise we will get an error like so: ====================================================================== ERROR: test_env_bytes (__main__.OSUnicodeTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "dist/Lib/test/test_os_jy.py", line 147, in test_env_bytes newenv["TEST_HOME"] = u"首页".decode("utf-8") File "/Users/jbaker/jythondev/jython27/dist/Lib/encodings/utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) IllegalArgumentException: java.lang.IllegalArgumentException: Cannot create PyString with non-byte value But what to choose from? * ascii - a good default choice that prevents silent error propagation * sys.getdefaultencoding() appears to always return "ascii"; it's not really changeable, Let's double check this by someone running a non US system. * sys.getfilesystemencoding() always returs None, which is legal ("or None if the system default encoding is used",). Let's not change this. * python.console.encoding really should be about the console * python.io.encoding (= env variable PYTHONIOENCODING) is new in 2.7 and corresponds to what is available since 2.6 in CPython Writing the new proposed test properly would have been better - don't mix up encode/decode ;) def test_env_bytes(self): with test_support.temp_cwd(name=u"tempcwd-中文"): newenv = os.environ.copy() newenv["TEST_HOME"] = u"首页".encode("utf-8") p = subprocess.Popen([sys.executable, "-c", 'import sys,os;' \ 'sys.stdout.write(os.getenv("TEST_HOME"))'], stdout=subprocess.PIPE, env=newenv) self.assertEqual(p.stdout.read().decode("utf-8"), u"首页") ====================================================================== FAIL: test_env_bytes (__main__.OSUnicodeTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "dist/Lib/test/test_os_jy.py", line 153, in test_env_bytes self.assertEqual(p.stdout.read().decode("utf-8"), u"首页") AssertionError: u'\xe9\xa6\x96\xe9\xa1\xb5' != u'\u9996\u9875' - \xe9\xa6\x96\xe9\xa1\xb5 + \u9996\u9875 So one can pass through bytes in this fashion, but an additional level of UTF-8 encoding was added; to "fix" the assertion requires self.assertEqual(p.stdout.read().decode("utf-8").decode("utf-8"), u"首页") which is obviously not desirable. 1) I'm fine with getting and setting environment variables, cli arguments, etc. as Unicode on Jython. With Jython only code it would avoid the need to actually know the system encoding, and compatibility with CPython only requires one 'if' to decide is encoding/decoding needed. 2) Getting system encoding with Python is surprisingly complicated. With Robot Framework we get the encoding that is got first using these alternatives in this order: - Any: sys.getfilesystemencoding() - Jython: System.getProperty('file.encoding') - POSIX: Environment variables LANG, LC_CTYPE, LANGUAGE, and LC_ALL - Windows: ctypes.cdll.kernel32.GetACP() Here's the code for anyone interested: 3) If there's a reliable way to get the correct encoding, I'd prefer sys.getfilesystemencoding() to return it. 4) The test that requires double decoding definitely looks wrong. Closing out - it's an interesting question of supporting bytes instead of unicode (msg9430), but Java natively wants unicode. We might be able to support this with JNR in the future, but note that currently JNR returns String as well, not byte[] -
http://bugs.jython.org/issue1841
CC-MAIN-2015-27
refinedweb
992
53.17
The MEBase class is the base class of all objects representing hard matrix elements in ThePEG. More... #include <MEBase.h> The MEBase class is the base class of all objects representing hard matrix elements in ThePEG. There are three methods which must be overridden by a concrete subclass: includedDiagrams(tcPDPair) should return a vector of DiagramBase objects describing the diagrams used for this matrix element for the given pair of incoming parton types. These DiagramBases are used to identify the incoming and outgoing partons which can be handled by the process generation scheme, and is also used to cnstruct a corresponding SubProcess object. scale() should return the scale associated with the phase space point set with the last call to setKinematics(...) or generateKinematics(...). me() should return the the matrix element squared using the the type and momentum of the incoming and outgoing partons, previously set by the setKinematics(...) or generateKinematics(...) member functions, accessible through the methods meMomenta() and mePartonData() inherited from LastXCombInfo, and/or from information stored by sub classes. The returned value should be dimensionless suitable scaled by the total invariant mass squared (accessible through the sHat() member function). Any user of this method must make sure that the setKinematics(...) member function has been appropriately called before. colourGeometries() should return a Selector with the possible ColourLines objects weighted by their relative probabilities given the information set by the last call to setKinematics(...) or generateKinematics(...). There are other virtula functions which may be overridden as listed below. Definition at line 72 of file MEBase.h. The size_type used in the DiagramVector. Definition at line 79 of file MEBase.h. A vector of pointers to DiagramBase objects. Definition at line 77 of file MEBase.h. A vector of pointers to ReweightBase objects. Definition at line 81 of file MEBase.h. Return the value of associated with the phase space point provided by the last call to setKinematics(). This versions returns SM().alphaEM(scale()). Reimplemented in ThePEG::MEGroup. This versions returns SM().alphaS(scale()). Return the amplitude associated with this matrix element. This function is allowed to return the null pointer if the amplitude is not available. Definition at line 351 of file MEBase.h. References theAmplitude. Select a diagram. Default version uses diagrams(const DiagramVector &) to select a diagram according to the weights. This is the only method used that should be outside of MEBase. Referenced by diagrams(). Initialize this object after the setup phase before saving an EventGenerator to disk. Reimplemented from ThePEG::InterfacedBase. Reimplemented in ThePEG::MEGroup, ThePEG::MENCDIS, and ThePEG::MEee2gZ2qq. Referenced by add(). Initialize this object. Called in the run phase just before a run begins. Generate internal degrees of freedom given nDim() uniform random numbers in the interval ]0,1[. To help the phase space generator, the 'dSigHatDR' should be a smooth function of these numbers, although this is not strictly necessary. The return value should be true of the generation succeeded. If so the generated momenta should be stored in the meMomenta() vector. Implemented in ThePEG::MEGroup, and ThePEG::ME2to2Base. Referenced by setKinematics(). Comlete a SubProcess object using the internal degrees of freedom generated in the last generateKinematics() (and possible other degrees of freedom which was intergated over in dSigHatDR(). This default version does nothing. Will be made purely virtual in the future. Referenced by keepRandomNumbers(). Return true, if this matrix element will generate momenta for the incoming partons itself. The matrix element is required to store the incoming parton momenta in meMomenta()[0,1]. No mapping in tau and y is performed by the PartonExtractor object, if a derived class returns true here. The phase space jacobian is to include a factor 1/(x1 x2). Definition at line 222 of file MEBase.h. If this is a dependent matrix element in a ME group, return true, if cuts should be inherited from the head matrix element, i.e. no cut is being applied to the dependent matrix element if the head configuration has passed the cuts. Definition at line 194 of file MEBase.h. Set the matrix element squared as calculated for the last phase space point. This may optionally be used by a matrix element for caching. Set the partonic cross section as calculated for the last phase space point. Set the PDF weight as calculated for the last phase space point, if the matrix element does supply PDF weights. The number of internal degreed of freedom used in the matrix element. This default version returns 0; Reimplemented in ThePEG::MEGroup, and ThePEG::ME2to2Base. Return the order in in which this matrix element is given. Returns 0. Implemented in ThePEG::MENCDIS, ThePEG::MEGroup, ThePEG::ME2to2QCD, and ThePEG::MEee2gZ2qq. Function used to read in object persistently. Referenced by setVetoScales(). Function used to write out object persistently. Select a ColpurLines geometry. The default version returns a colour geometry selected among the ones returned from colourGeometries(tcDiagPtr). Set the typed and momenta of the incoming and outgoing partons to be used in subsequent calls to me() and colourGeometries() according to the associated XComb object. If the function is overridden in a sub class the new function must call the base class one first. Definition at line 154 of file MEBase.h. References constructVertex(), generateKinematics(), and nDim(). Referenced by ThePEG::MEGroup::setKinematics(). Initialize all member variables from another MEBase object. remove?
https://thepeg.hepforge.org/doxygen/classThePEG_1_1MEBase.html
CC-MAIN-2018-39
refinedweb
884
51.24
Microsoft Specific Generates the rdtsc instruction, which returns the processor time stamp. The processor time stamp records the number of clock cycles since the last reset. unsigned __int64 __rdtsc(); A 64-bit unsigned integer representing a tick count. Intrinsic Architecture __rdtsc x86, x64 Header file <intrin.h> This routine is available only as an intrinsic. The interpretation of the TSC value in this generation of hardware differs from that in earlier versions of x64. See hardware manuals for more information. // rdtsc.cpp // processor: x86, x64 #include <stdio.h> #include <intrin.h> #pragma intrinsic(__rdtsc) int main() { unsigned __int64 i; i = __rdtsc(); printf_s("%I64d ticks\n", i); } 3363423610155519 ticks
http://msdn.microsoft.com/en-us/library/twchhe95.aspx
crawl-002
refinedweb
108
52.87
Hi, I'm working on Svelte plugin ( Svelte has syntax for subscribing to stores. It repurposes identifiers on the compiler level and looks like this: <script> import {foo} from 'foo'; console.log($foo); </script> <div>{$foo}</div> (Assume that I have JS properly injected or lazily parsed inside those curly brackets) Basically dollar works as unary operator that cannot be followed by whitespace. You can't declare variable names starting with $ in Svelte files[0]. I would like to link usages of foo to their declarations and stop highlighting $foo as unresolved variable. My initial idea was to extend JS parser and lexer a bit. I created LayeredLexer that breaks IDENTIFIER tokens into DOLLAR and IDENTIFIER. Next I wanted to change parser to interpret such combination as a call to internal function[1] or just valid identifier to start. There's the complication though. You can actually use $-prefixed identifiers inside function arguments (eg. const x = $x => $x.toUpperCase();), in other words everything would need to work depending on context. Now I'm thinking that I could swap IDENTIFIER tokens with custom designed lazily parsable tokens and then parse them depending on parent AST or PSI nodes. I imagine that approach wouldn't require me to extend JS language too much. Or maybe the better approach is to inject reference into substring of identifier with ReferenceContributor or something like that? What about disabling $ part / disabling JSReferenceExpression? I'm asking mainly to limit time wasted on experiments because I'm probably missing many details. Any pointers are highly appreciated. Cheers. [0] There's actually exception to this rule, $$props global but I handled that on the lexer level. [1] Store can be thought of as one value container and $ operator is a "get" function with effective signature of <T>(store: Store<T>) => T. Would be nice to preserve that property in the plugin so code insight provides proper completions etc.. Sadly I have no idea how to do that. Hi Tomasz, The easiest approach is to implement PsiReferenceContributor, we added it for WEB-24393. Built-in javascript resolver won't start if PsiReferenceContributor returns a result. Probably, find usages still won't work, because it scans by words initially, and 'foo' is treated differently with '$foo'. You may take a look at FindUsagesProvider#getWordsScanner, but I don't guarantee that this is the best approach to fix this case. Rename will also require some tweaking.
https://intellij-support.jetbrains.com/hc/en-us/community/posts/360004377420-Treat-part-of-JS-identifier-specially-depending-on-context?sort_by=created_at
CC-MAIN-2021-49
refinedweb
404
57.16
I’m working on a project that needs to go to sleep when not in use, to conserve battery, and wake up quickly to take measurements, but the electron is taking too long to wake up. if (quietCount >= QUIETAMOUNT) //sleep count { #ifdef DEBUG Serial.println("Going to sleep!"); Serial.print(Time.hour()); Serial.print(":"); Serial.print(Time.minute()); Serial.print(":"); Serial.print(Time.second()); Serial.println(); delay(10); #endif quietCount = 0; //already going to sleep //how long until the device needs to wake up at the next measurement period? accel_standby(); read_register(ACCELADDRESS, 0x16); //reset interrupt pin accel_active(); int secToNextMin = 60 - Time.second(); int minToNextHour = 59 - Time.minute(); int currentHour = Time.hour(); if(currentHour % 2 == 0) //odd or even hour seconds = secToNextMin + ((minToNextHour)*60) + 3600; else seconds = secToNextMin + ((minToNextHour)*60); delay(10); System.sleep(WKP, FALLING, seconds); //sleep until time is up, or pin WKP goes high delay(1000); #ifdef DEBUG Serial.println("Pressing snooze"); #endif accel_standby(); read_register(ACCELADDRESS, 0x16); //reset interrupt pin accel_active(); #ifdef DEBUG Serial.println("Waking up!"); Serial.println(); #endif } This is the sleep portion of the code (the entire code is very long) I’m counting the up and down movements of an accelerometer, and the device goes to sleep after a couple of seconds without movement and wakes up when it moves again. When the device wakes up the embedded led flashes green for about 50 seconds before breathing green and moving on with the program. I need this cut down to no longer than 1 or 2 seconds, preferably less. If I had to guess, the electron is getting caught up in trying to connect to cellular. I’m using SYSTEM_MODE(SEMI_AUTOMATIC); and keeping cellular disconnected because I don’t need it and I’m working in an area with pretty bad reception. Is there a way to minimize it looking for a signal it doesn’t need, can’t have, and I don’t want? If that’s not the problem, does anyone have any idea how to cut down the time to fully wake up? Thanks in advance
https://community.particle.io/t/electron-taking-to-long-to-wake-up-from-sleep/50083
CC-MAIN-2020-40
refinedweb
345
54.42
> impractical language, only useful for research. Erik Meijer at one point > states that programming in Haskell is too hard and compares it to assembly > programming! He brings up a very good point. Using a monad lets you deal with side effects but also forces the programmer to specify an exact ordering. This *is* a bit like making me write assembly language programming. I have to write: > do { > x <- getSomeNum > y <- anotherWayToGetANum > return (x + y) > } even if the computation of x and y are completely independant of each other. Yes, I can use liftM2 to hide the extra work (or fmap) but I had to artificially impose an order on the computation. I, the programmer, had to pick an order. Ok, maybe "assembly language" is a bit extreme (I get naming, allocation and garbage collection!) but it is primitive and overspecifies the problem. Tim Newsham
http://www.haskell.org/pipermail/haskell-cafe/2007-January/021717.html
CC-MAIN-2014-35
refinedweb
144
56.86
From: Joel de Guzman (djowel_at_[hidden]) Date: 2002-10-20 18:23:06 ----- Original Message ----- From: "Peter Simons" <simons_at_[hidden]> > The Spirit Parser Framework should be ACCEPTED into Boost for the > following reasons: First of all, thanks, Peter. [snip] > Admittedly, the documentation for Spirit could (and should) be more > extensive -- I remember well that I had some interesting experiences > when I started using it. But the scope of material that had to be > covered in the documentation in order to call it "complete" is > immense. Without a sound understanding of templates, expression > templates, iterators, and -- obviously -- parser theory, you cannot > expect to use the library to its full potential. But you cannot expect > a free-software author to cover all these topics in the user's manual > either. Understood. The original Spirit v1.0 post was a paltry 7 header file and a single html file documentation. Along with the initial boost announcement came tons of wish-lists which I attempted to address soon afterwards. Thanks to the help of many others (listed in the acknowledgement) and especially Dan and Hartmut, development over the past year has been a rocket ride, so to speak. Now, there are 8 modules and more than a hundred A4 pages of documentation. Yet, many parts are still crying for more documentation and a reference material is really needed. As always, the coding outpaces the documentation. ... Not to mention that I am not a native english speaker :-) Sooo :-).. I take this opportunity to call for help... I'd certainly be very happy if someone will come out and help with the documentation and especially the reference. > 2. Portability > > Even though Spirit is built on very sophisticated mechanisms of the > ISO C++ language, it is highly portable. I have been able to compile > Spirit-based parsers without significant problems on any of the > following operating systems: > > Linux > FreeBSD > OpenBSD > MacOS X > Windows > > Furthermore, I was able to compile Spirit with any of the following > compilers: > > GNU g++ 2.95, 3.0, 3.1, 3.1 > Intel C++ 6.0 > Comeau C++ 4.3.0.1 + Borland 5.5.1 + intel 5.0 + msvc 6/7 + Visual Age C++ 5.02 + metrowerks 7.2 [snip] > > 4. Performance > > Spirit parsers are based on expression templates, what allows for some > serious code optimization by the compiler. The drawback is that > compile times may be testing your patience, but the idle time during > compilation is invested well, because the resulting parsers are > _fast_. It might theoretically be possible to write faster parsers by > hand, but I don't see any real-life applications where Spirit's > performance should be insufficient. I must admit, I'm not quite happy with the compile speed on EDG based compilers. I must consult with the gurus (Aleksey, help! :-) to make things smoother with Comeau and others. I remember a case where Comeau took hours and gave up with an infinite recursion. I certainly hope EDG will address this "crawling compiler" issue which I think is rather ironic: EDG is the best so far in ANSI c++ conformance yet modern C++ makes it crawl. > 8. Miscellaneous > > Other reviewers have commented that Spirit would be intertwined with > the Phoenix library that comes with it. It is true that Phoenix is > very useful when working with Spirit, and thus it is used throughout > most of the examples and test programs. But Spirit is completely > independent of Phoenix and most of the things one does with Phonix can > be accomplished with Boost.Lambda, Boost.Bind, or any other framework > as well. All Phoenix-related parts reside in their own namespace and > in their own directory, so Phoenix and Spirit are really not > intertwined at all. I think the culprit is the single header "spirit.hpp" which includes everything and indirectly includes phoenix. There are a couple of module header files as well. It is highly advisable to include the module header files rather than the one-stop-shop-spirit.hpp. Regards, --Joel 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/10/38069.php
CC-MAIN-2021-17
refinedweb
686
56.96
How to identify upcoming regressions or API breaks How to identify upcoming regressions or API breaks Join the DZone community and get the full member experience.Join For Free Java-based (JDBC) data connectivity to SaaS, NoSQL, and Big Data. Download Now. What is a regression ? Regressions are due to a change in the code or its dependencies, but sometimes also to environment changes. We won't be talking about this last point in this post. There are two types of regressions: compile-time and run-time. On one hand compile-time regressions make your code not compliant anymore for your compiler, script interpreter, etc. On the other hand run-time regressions, the tricky ones, cause code crashes, bugs, or strange behavior wherever it was working before. How can I get regressions in my code ? Here we are interested in Object Oriented programming, but other languages without the notion of class or inheritance face the same hurdles with function and method definitions. There are many ways you can get regressions within your own code and much more when you have library dependencies. This is because when a dependency gets updated it may bring any of the following regressions without you knowing it. I'll give an example, let's say class Foo implements the Bar interface public interface Bar { // Cool signatures inside } public class Foo implements Bar { private UnserializableType boo; Foo(UnserializableType boo) { this.boo = boo;// Nothing to do with DBZ } // Cool methods implementations doing stuff with boo } Everything seems fine until this happens! public interface Bar extends Serializable { // Still cool signatures inside } The interface become Serializable but my implementation can't be properly serialized because of the boo field that is not serializable itself. Hence the run-time regression! This case of interfaces extending a new type is special because the Serialization interface has no method constraint yet to add a behavior for Java. But there will be a compile-time regression for any new method added to an interface. Can something help me identify the regressions before they happen ? Some regressions are nearly impossible to predict, however for most of them you can at least have a hint on where to check for regressions. Of course compile-time regressions can be identified easily compared to run-time ones. In the case your working only with your own code in a single project then compile-time regressions are often identified by your IDE single-handed (Eclipse, Netbeans, Visual Studio, etc). And because of your situation you're allowed to do such and just ctrl+Z to get everything back in order. However if you're working with multiple dependencies then it's another game. You're not aware of regression while updating a dependency let's say from a version 1.2 to a newer. Is the 1.3 or 1.4 compliant? both? You'll have to check manually by changing the dependency then compile your code. It is not really funny nor sexy. And when it gets to run-time regressions then you'll have to go for all your test chain again. So now here are the ways to predict regression before they happen ! - Compare the signatures of different API versions: Are some methods or fields modified? Inheritance broken? Created? It's actually really feasible especially in Java thanks to the Reflection API - Detect the implementation changes: It is not necessary to have the source code changes but only a hint on if the bytecode/compiled code changed for this method. Then you'll have a hint on where to check for regression without having to profile all your code. - Identify the use of the API in your code: Are the changes going to affect you code? Or are you not using this part? Tools & Links - For Java They are many tools that can perform API compliance checking, ACC is one of these tools. Available on - ABI Compliance Checker is a tool that does similar process but for C/C++ libraries. Check it out here - This website tracks the APIs breaks of C/C++ libraries. It's interesting to observe the phenomenon is quite common and unpredictable. What's Next ? Version compliance between APIs is a very important matter and is source of number of testing and regression overloads. Hence our company is interested by putting this checking process with no burden in the everyday programmer life. Tocea is coming with an open-source compliance checking maven plugin that can be integrated in a code analysis tool chain. Stay tuned. Connect any Java based application to your SaaS data. Over 100+ Java-based data source connectors. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/how-identify-upcoming
CC-MAIN-2018-43
refinedweb
790
55.44
-- Defines the point data-type with two variables. data Point = XY {x :: IORef Int, y :: IORef Int} -- Creates a new point from a pair of coordinates. -- As it uses variables it should use (monadic) do-notation newPoint (x, y) = do xRef <- newIORef x yRef <- newIORef y return (XY xRef yRef) -- Imperatively updates the point's coordinates movePoint (deltaX, deltaY) (XY x y) = do modifyIORef x (+ deltaX) modifyIORef y (+ deltaY) -- Prints the point to the standard output printPoint (XY x y) = do x' <- readIORef x y' <- readIORef y print (x', y') -- simple test do p <- newPoint (1, 2) printPoint p movePoint (3, 2) p printPoint p -- The result is as expected: (1,2) (4,4)As you can see HaskellLanguage allows mutability on objects. While I agree the operation names could be a little bit better (e.g. readIORef/writeIORef vs. read/write vs. get/set) the idea is simple (also you can write alias to these functions if you prefer simpler names). Also you don't need to grok monads to understand this code, but groking monads is much more enlightening than groking design patterns IMHO. I grok monads now. However, they seem inelegant to me. The minute you devote this much time and effort to add such a fundamental concept as "state", I feel you've been told by the underlying math, "No. This is a bad idea." That aside... Monads weren't created to deal with "state", but they can be used to do so. IMHO you do not grok monads, otherwise you would know that. For example monads can be used to model any kind of computation, including: IO, state, parsing, implicit parameters, logging, non-determinism, exceptions, continuations with call/cc and combinations of such. Wait wait wait, so you're saying that Monads were not part of the effort to integrate stateful operations like IO into purely functional systems? Monads came from category theory, they weren't "invented" to solve programming languages issues. There are several models of IO that respect referential transparency, including UniquenessTypes, monads, stream-based io and ContinuationPassingStyle. Some time later PhillipWadler? wrote the paper "Monads for functional programming" where he showed how to write monads to structure functional programs and include different forms of effects (i.e. computations). The examples showed exceptions, state threading, output, non-determinism and parser combinators. After the Haskell designers decided to use a IO monadic solution (IIRC the previous IO framework in Haskell was stream-based).
http://c2.com/cgi/wiki?HaskellExampleForMutabilityOnObjects
CC-MAIN-2016-26
refinedweb
409
51.78
Hi, We will have our regular meeting Friday, January 13 at 9 am PST to discuss JDO TCK issues and status. Dial-in numbers are: 866 230-6968 294-0479# International: +1 865 544-7856 Agenda: 1. Test status (Michael) 2. Split alltests.conf status (Michael) 3. Fieldtypes test status (Michelle) 4. Suggestion to split alltests.conf into separate configuration files (Craig and others) 4. Build clean-up and enhancements (Michelle) 5. Assertions in the spreadsheet, unimplemented assertion categories in JIRA (Criag) 6. Other issues (any and all) Action Items from weeks past: [Jan 6 2005] AI: Michael: need to add a public static final field in a public class to test fully qualified class name static field in query. [Jan 6 2005] The JIRA issues associated with detachment need to be cleaned up; they mixed the life cycle and behavior of detached and persistent-nontransactional-dirty objects. AI: Matthew and Craig to fix up. . [Dec 9 2005]: Nontransactional write semantics appear to differ between optimistic and datastore transactions. Is this intentional? AI: Craig discuss with expert group. . [Nov 4 2005] AI Martin: Update Martin's wiki with discusion of JDK 1.5 issues. in progress [Oct 14 2005] AI: Michelle distill the mapping support that JPOX has into a list of features that are/are not supported. [Oct 14 2005] AI: Push jars to Apache repository (Craig) In progress. Several things need to be updated, including project.properties, project.xml and maven.xml. [Sep 2 2005] AI: arrange for automated nightly builds. [May 20 2005] AI: Craig to define the JCP distributions and see if maven can help.
http://mail-archives.apache.org/mod_mbox/db-jdo-dev/200601.mbox/%3C43C71B6E.2060306@sun.com%3E
CC-MAIN-2017-09
refinedweb
269
68.26
This week I have been working on a React app using Typescript and I've made a few discoveries that were very useful. This is one of my first projects using Typescript and so far I don't want to go back. Some of these discoveries may be common knowledge but for a Typescript novice, they are very useful for writing better code. For me at least. So without further ado, let's get into it! Only allow specific keys on an object This is quite useful when you want to limit the keys that can be added to an object. For example, allowing another dev to pass functions that should be used as event listeners. In that situation you only want the dev to pass vaild event listeners to avoid nasty errors. type TListenerTypes = "onload" | "progress" | "error" type TListeners = { [k in TListenerTypes]: Function } // Passes! const listenerObj: TListeners = { onload: () => {} } // Error const errorObj: TListeners = { a: "something", // wrong type progress: () => {}, d: 10 // not in objectKeys type } Categorising Storybook Stories In the project I am working on, we are using storybook to test our components. Once you've added a few stories, you start wishing for a way to categorise these into relevant groupings. Luckily there is a solution for this! As a side note, I cannot recommend storybook enough. It is SUPER useful for visually testing components independently. With the power of addons you can do accessibility checking, light/dark mode testing etc. // uncategorised storiesOf("Button", module).add(...) // categorised under "Form" storiesOf("Form|Selectbox", module).add(...) Passing a component as props This became an issue when I wanted to declare a custom <Route> component while using React Router. I needed a way to pass a component to the custom <Route> and then be able to render the component. This was surprisingly annoying. Tip, if you're able to view the type definitions for other modules, DO IT! I have found quite a few solutions from existing codebases, including this one; import { ComponentType } from "react" import { RouteProps } from "react-router-dom" interface ICustomRoute extends RouteProps { // Allows you to pass in components and then render them component: ComponentType<any> } const CustomRoute = ({ component: Component, ...rest }: ICustomRoute) => ( <Route {...rest} render={props => ( <Component {...props} /> )} /> ) Allow native HTML attributes as props Imagine you want to create an <Input /> component, which should accept all properties of a <input /> element as well as an additional theme object. To stop you from creating a custom definition for the component, it would be alot better to just extend the available props of an <input /> element, and, YOU CAN! import { HTMLAttributes } from "react" type Theme = "light" | "dark" interface IProps extends HTMLAttributes<HTMLInputElement> { // additional props if need theme: { variation: Theme } } // You might want to extract certain props and your custom props // instead of just spreading all the props // if you don't have additional props swap IProps for HTMLAttributes<HTMLInputElement> const Input ({ theme, ...props }: IProps) => ( <input {...props} className={`input input--${theme.variation}`} /> ) // Usage <Input onChange={(e) => handle(e)} value={this.state.name} name="name" id="id" theme={{ variation: "light" }} /> Get device orientation This is not really Typescript or React related, however, it could lead to something interesting. I can definitely imagine this being useful for a very cool but also very useless feature. Read more about it on MDN. // Check if it is supported if (window.DeviceOrientationEvent) { window.addEventListener("deviceorientation", function(e) { console.log({ x: e.alpha, y: e.beta, z: e.gamma }) }, false) } Wrapping up Each week we learn new techniques and different ways of thinking. I’d recommend to anyone to note down the different techniques you’ve learnt. Not only will you create a small knowledge base, you will also become more motivated when you see the progress you have made.
https://www.myweekinjs.com/typescript-and-react-discoveries/
CC-MAIN-2019-35
refinedweb
620
57.06
#include <EBLevelAdvect.H> Default constructor. Object requires define(..) to be called before all other functions. Destructor. destroys all objects created by define(..). Passed in data references of define(..) are left alone. Actual constructor. For the coarsest level, an empty DisjointBoxLayout is passed in for coaserDisjointBoxLayout. Inside the routine, we cast away const-ness on the data members for the assignment. The arguments passed in are maintained const. (coding standards). a_nRefine is the refinement ratio between this level and the next coarser level. a_numGhosts is the number of ghost cells in each direction. 1. Average advection velocity to cell centers to get unorm. 2. Do linear C/F interpolation on a_cellState and compute the diffusion source term if necessary. Quadratic is unnecessary because the laplacian does its own CF interpolation in the viscous case. 3. Do linear C/F interpolation in space and time 4. Extrapolate cellState to to faces using patchgodunov->extrapolatePrim Notes: The advection velocity that is sent in is not used. It will be taken out in later designs References m_ebPatchAdvect. Referenced by getPatchAdvect().
http://davis.lbl.gov/Manuals/CHOMBO-RELEASE-3.1/classEBLevelAdvect.html
CC-MAIN-2018-43
refinedweb
176
53.37
electron.dart is a wrapper of the electron API in dart This is under development so if you have suggestion on the existing API or you find a bug don't hesitate to fill an issue :) You can find examples on how to use this package in the electron_examples repos Add this to your package's pubspec.yaml file: dependencies: electron: ^0.0.3+1 You can install packages from the command line: with pub: $ pub get Alternatively, your editor might support pub get. Check the docs for your editor to learn more. Now in your Dart code, you can use: import 'package:electron/electron.
https://pub.dev/packages/electron
CC-MAIN-2019-26
refinedweb
105
60.45
Channel is an observable and observer combined. That means you can write to and also read from it. Where observable is activated once there is a live subscription, Channel has no producer and is always "live". import { Channel } from '@hullo/core';const ch = new Channel<string>();/* here, subject allows for a message* but since there is no subscription* the message is lost */ch.next('echo!');const sub = ch.subscribe({next: v => { console.log(v); }});/* here, there is a live subscription* and so the message will be received */ch.next('ECHO!'); Channel has also two additional methods, unique to channel: take and tryTake. With those you can get a Promise of next message. Both of those are for the same purpose, one is graceful, the other fails fast. import { Channel } from '@hullo/core';const ch = new Channel<string>();async function listen() {console.log(await ch.take());}async function broadcast() {await ch.next('hello');}listen();broadcast();// prints "hello" to the console
https://hullo.dev/hullo-core/api/channel
CC-MAIN-2021-17
refinedweb
159
60.92
Important: Please read the Qt Code of Conduct - Swipe View getting stuck I am using swipe view under which i have three qml's loaded in each page. Total no of pages are 5. One Qml has three waveforms displayed, which changes to 1 waveform in the next page. While Swiping the view, the view gets stuck in between. Is there a signal or function to know if the swipe view has completed the swipe(i.e the page is moved to the next page)? currentIndex and/or currentItem should change only after the transition finished. So you can listen/react to the onCurrentIndexChanged:signal @J-Hilk said in Swipe View getting stuck: onCurrentIndexChanged @J-Hilk Currently i have used a repeater for the 5 pages of the swipeview. Can i load a page dynamically after the current index has changed? and is there a signal to indicate a start of the swipe as well? import QtQuick 2.12 import QtQuick.Controls 2.12 import QtQuick.Window 2.2 Window { visible: true width: 400 height: 100 title: qsTr("Hello World") id:window Component { id:myComponent Rectangle{ property alias pageIndex: name.text Component.onCompleted: console.log("Just completed") Component.onDestruction: console.log("Destructed", pageIndex) Text { id: name anchors.centerIn: parent onTextChanged: console.log("new text:", text) } } } SwipeView{ id:swipeView anchors.fill: parent Repeater{ model: 10 delegate: Loader{ active: index === swipeView.currentIndex onLoaded: item.pageIndex = index sourceComponent: myComponent } } } } and is there a signal to indicate a start of the swipe as well That, I'm unsure about @J-Hilk said in Swipe View getting stuck: currentIndex and/or currentItem should change only after the transition finished. So you can listen/react to the onCurrentIndexChanged: signal This seems isn't true. Here is an example, which illustrates that current index of view changes before swipe transition ends: SwipeView { anchors.fill: parent onCurrentIndexChanged: console.log("CURRENT INDEX", currentIndex) Rectangle { color: "red"; opacity: 0.5 } Rectangle { color: "green"; opacity: 0.5 } Rectangle { color: "blue"; opacity: 0.5 } Component.onCompleted: { contentItem.flickEnded.connect(() => console.log("FLICK ENDED")); } } @IntruderExcluder Thanks for this solution, this helped me solve the issue. @IntruderExcluder uh, interesting. Hard to tell, this would require a deeper dive into the source code. To see, when what signal is emitted when exactly 🤔 Keep in mind, that there is different logic between changing index programmatically and by user interaction. The question is why it is made so? I didn't get it, too complicated. @IntruderExcluder , yes the current index changes before the flick has been ended. but i there a property to get to know if the flick has been done in a positive or a negative direction? You can define additional property, like: SwipeView { anchors.fill: parent currentIndex: 0 property int lastIndex: 0 onCurrentIndexChanged: { if (currentIndex > lastIndex) { console.log("INCREASED"); } else { console.log("DECREASED"); } lastIndex = currentIndex; } Rectangle { color: "red"; opacity: 0.5 } Rectangle { color: "green"; opacity: 0.5 } Rectangle { color: "blue"; opacity: 0.5 } }
https://forum.qt.io/topic/109422/swipe-view-getting-stuck
CC-MAIN-2021-21
refinedweb
489
52.26
In preparation for an alien invasion, the Earth Defense League has been working on new missiles to shoot down space invaders. Of course, some missile designs are better than others; let's assume that each design has some probability of hitting an alien ship, x. Based on previous tests, the distribution of x in the population of designs is roughly uniform between 10% and 40%. To approximate this distribution, we'll assume that x is either 10%, 20%, 30%, or 40% with equal probability. Now suppose the new ultra-secret Alien Blaster 10K is being tested. In a press conference, an EDF general reports that the new design has been tested twice, taking two shots during each test. The results of the test are confidential, so the general won't say how many targets were hit, but they report: ``The same number of targets were hit in the two tests, so we have reason to think this new design is consistent.'' Is this data good or bad; that is, does it increase or decrease your estimate of x for the Alien Blaster 10K? Now here's a solution: I'll start by creating a Pmfthat represents the four hypothetical values of x: In [7]: pmf = Pmf([0.1, 0.2, 0.3, 0.4]) pmf.Print() 0.1 0.25 0.2 0.25 0.3 0.25 0.4 0.25 Before seeing the data, the mean of the distribution, which is the expected effectiveness of the blaster, is 0.25. In [8]: pmf.Mean() Out[8]: 0.25 Here's how we compute the likelihood of the data. If each blaster takes two shots, there are three ways they can get a tie: they both get 0, 1, or 2. If the probability that either blaster gets a hit is x, the probabilities of these outcomes are: Here's the likelihood function that computes the total probability of the three outcomes:Here's the likelihood function that computes the total probability of the three outcomes: both 0: (1-x)**4 both 1: (2 * x * (1-x))**2 both 2: x**4 In [9]: def likelihood(hypo, data): """Likelihood of the data under hypo. hypo: probability of a hit, x data: 'tie' or 'no tie' """ x = hypo like = x**4 + (2 * x * (1-x))**2 + (1-x)**4 if data == 'tie': return like else: return 1-like To see what the likelihood function looks like, I'll print the likelihood of a tie for the four hypothetical values of x: In [10]: data = 'tie' for hypo in sorted(pmf): like = likelihood(hypo, data) print(hypo, like) 0.1 0.6886 0.2 0.5136 0.3 0.4246 0.4 0.3856 If we multiply each likelihood by the corresponding prior, we get the unnormalized posteriors: In [11]: for hypo in sorted(pmf): unnorm_post = pmf[hypo] * likelihood(hypo, data) print(hypo, pmf[hypo], unnorm_post) 0.1 0.25 0.17215 0.2 0.25 0.1284 0.3 0.25 0.10615 0.4 0.25 0.0964 Finally, we can do the update by multiplying the priors in pmfby the likelihoods: In [12]: for hypo in pmf: pmf[hypo] *= likelihood(hypo, data) And then normalizing pmf. The result is the total probability of the data. In [13]: pmf.Normalize() Out[13]: 0.5031000000000001 And here are the posteriors. In [14]: pmf.Print() 0.1 0.342178493341 0.2 0.255217650566 0.3 0.210991850527 0.4 0.191612005565 The lower values of xare more likely, so this evidence makes us downgrade our expectation about the effectiveness of the blaster. The posterior mean is 0.225, a bit lower than the prior mean, 0.25. In [15]: pmf.Mean() Out[15]: 0.2252037368316438 A tie is evidence in favor of extreme values of x. Finally, here's how we can solve the problem using the Bayesian update worksheet: In the next article, I'll present my solution to The Skeet Shooting problem.
https://allendowney.blogspot.com/2016/10/
CC-MAIN-2019-43
refinedweb
663
60.55
> RT. The Hurd is not a real time system. It doesn't make use of RT. The > Hurd runs on RT Mach, though. So you can use the real time extensions in a > Hurd system, but you can't rely on the Hurd servers or the C library to do > any RT'ish things for you. Are the real time changes free? We might > include them by default in the future, if we find someone willing to > port and maintain them. Exactly! > BTW, I guess some stuff was disabled (SMP) when the Linux device driver glue > code was integrated, and never resurrected. With oskit-mach, that part of > the kernel has been cleared up again, and there is hope now to get stuff > like SMP support back into our mach. Agreed. But we'll definitely need some SMP machines to work on. Its quite hard to find SMP motherboads with chipsets compatible to both Linux, FreeBSD-CURRENT (with SMPng) and the yet-to-be-maintained -and-updated Mach SMP code [and maybe a SMP-version of L4 as well] :-(. If there is real interest, we can scan the above mentioned SMP codebases for chipset requirements and post a summary here of what is needed. Someone may have a list of hardware vendors for us too... > > I want to work with distributed systems and clusters until the finish of > > my course (college). I know that many work are being done with L4, but > > in my understanding, when someone say that L4 is "working in process", I > > see in Mach work done with many tests, researches and results waiting to > > be improved and used. > > i think some work can be done here, not only on the kernel level (which you > need), but also in the Hurd servers. I think passing ports over networks > etc can be done in user space on the Hurd (and maybe should). Beside those You want to migrate _Mach_ ports over the net? This essentially means that you have to transfer the message queue, but also leave a forwarding/ redirecting proxy at the old location until all clients have updated their destination portnames. If you move the ports further, you quickly develop a chain of forwarding proxies (which is bad). This is exactly the problem with VM objects in the old Mach VM that was only recently being solved in NetBSD's UVM (by early-collapsing the chains). > technical features you need, there is, for example, the requirement to have > a network-wide unique process id for a task. Thomas calls such a network > of Hurd systems a "collective". I guess if you want to do distributed > systems in a Hurdish way, collectives are the way to go. The concept exists > only in Thomas head, though, so you will have to nag him a bit to tell us > about his ideas. Network-wide unique identifiers like task-IDs, ports, etc... are a nice thing to have. One idea may be to organize all nodes of a collective in a distributed kind of (hurdisch) filesystem. IDs would then be simple paths and could be located with some kind of distributed lookup() functionality: /collective1/ # namespace for collective #1 /collective1/ipc/ # ipc namespace (ports...) /collective1/ipc/machine1/ # ipc namespace for machine1 /collective1/ipc/machine1/port1 /collective1/ipc/machine1/port2 ... /collective1/vm/ # namespace for VM objects /collective1/vm/machine1/vmobject1 /collective1/vm/machine2/vmobject25 ... Every member of a collective whould have to provide "translator-like" functionality and register itself with the collective. Or if you prefer, each machine will be "translator", serving its own set of ipc, vm, ... namespaces. Now, _that_ would be hurdish! .
http://lists.gnu.org/archive/html/bug-hurd/2001-12/msg00259.html
CC-MAIN-2014-35
refinedweb
602
70.94
SYNOPSIStop -hv|-bcHiOSs -d secs -n max -u|U user -p pid -o fld -w [cols] The traditional switches `-' and whitespace are optional. DESCRIPTIONThe DocumentationThe. HISTORY Former top, 10. AUTHOR, 11. SEE Also OperationWhen Startup DefaultsThe following startup defaults assume no configuration file, thus no user customizations. Even so, items shown with an asterisk (`*') could be overridden through the command-line. All are explained in detail in the sections that follow.. COMMAND-LINE OptionsThe command-line syntax for top consists of: -hv|-bcHiOSs -d secs -n max -u|U user -p pid -o fld -w [cols] The typically mandatory switch (`-') and even whitespace are completely optional. - -h | -v :Help/Version - Show library version and the usage prompt, then quit. - vice versa. See the `c' interactive information regarding this toggle see topic 4c. TASK AREA Commands, sorting. - -p :Monitor-PIDs mode as: -pN1 -pN2 ... or -pN1,N2,N3 ... - Monitor only processes with specified process IDs. This option can be given up to 20 times, or you can provide a comma delimited list with up to 20 pids. Co-mingling both approaches is permitted. matching the one provided. The `p', `u' and `U' command-line options are mutually exclusive. - -w :Output-width-override as: -w [ number ] - In Batch mode, when used without an argument top will format output using the COLUMNS= and LINES= environment variables,... 2c. MEMORY UsageThis portion consists of two lines which may express values in kibibytes (KiB) through exbibytes (EiB) depending on the scaling factor enforced with the `E' interactive command.Listed below are top's available process fields (columns). They are shown in strict ascii alphabetical order. You may customize their position and whether or not they are displayable with the `f' or `F' (Fields Management) interactive. 1. %CPU -- CPU Usage - The task's share of the elapsed CPU time since the last screen accustomed to seeing with an unqualified `set'.. LXC -- Lxc Container Name - The name of the lxc container within which a task is running. If a process is not running inside a container, a dash (`-') will be shown. - 12. NI -- Nice Value - The nice value of the task. A negative nice value means higher priority, whereas a positive nice value means lower priority. Zero in this field simply means priority will not be adjusted in determining a task's dispatch-ability. - 13.). - 14. PGRP -- Process Group Id - Every process is member of a unique process group which is used for distribution of signals and by terminals to arbitrate requests for their input and output. When a process is created (forked), it becomes a member of the process group of its parent. By convention, this value equals the process ID (see PID) of the first member of a process group, called the process group leader. - 15. PID -- Process Id - The task's unique process ID, which periodically wraps, though never restarting at zero. In kernel terms, it is a dispatchable). - 16. PPID -- Parent Process Id - The process ID (pid) of a task's parent. - 17.. - 18. RES -- Resident Memory Size (KiB) - The non-swapped physical memory a task is using. - 19. RUID -- Real User Id - The real user ID. - 20. RUSER -- Real User Name - The real user name. - 21. S -- Process Status - The status of the task which can be one of: D = uninterruptible sleep R = running S = sleeping T = stopped by job control signal t = stopped by debugger during trace. - 22. SHR -- Shared Memory Size (KiB) - The amount of shared memory available to a task, not all of which is typically resident. It simply reflects memory that could be potentially shared with other processes. - 23.. - 24. SUID -- Saved User Id - The saved user ID. - 25.. - 26.. - 27. SUSER -- Saved User Name - The saved user name. - 28. SWAP -- Swapped Size (KiB) - The non-resident portion of a task's address space. - 29. TGID -- Thread Group Id - The ID of the thread group to which a task belongs. It is the PID of the thread group leader. In kernel terms, it represents those tasks that share an mm_struct. - 30.. - 31. TIME+ -- CPU Time, hundredths - The same as TIME, but reflecting more granularity through hundredths of a second. - 32.). - 33.. - 34. UID -- User Id - The effective user ID of the task's owner. - 35. USED -- Memory in Use (KiB) - This field represents the non-swapped physical memory a task has used (RES) plus the non-resident portion of its address space (SWAP). - 36. USER -- User Name - The effective user name of the task's owner. - 37. VIRT -- Virtual Memory Size (KiB) - The total amount of virtual memory used by the task. It includes all code, data and shared libraries plus pages that have been swapped out and pages that have been mapped but not used. - 38. WCHAN -- Sleeping in Function - This field will show the name of the kernel function in which the task is currently sleeping. Running tasks will display a dash (`-') in this column. - 39. nDRT -- Dirty Pages Count - The number of pages that have been modified since they were last written to auxiliary storage. Dirty pages must be written to auxiliary storage before the corresponding physical memory location can be used for some other virtual page. - 40. nMaj -- Major Page Fault Count - The number of major page faults that have occurred for a task. A page fault occurs when a process attempts to read from or write to a virtual page that is not currently present in its address space. A major page fault is when auxiliary storage access is involved in making that page available. - 41. nMin -- Minor Page Fault count - The number of minor page faults that have occurred for a task. A page fault occurs when a process attempts to read from or write to a virtual page that is not currently present in its address space. A minor page fault does not involve auxiliary storage access in making that page available. - 42. nTH -- Number of Threads - The number of threads associated with a process. - 43. nsIPC -- IPC namespace - The Inode of the namespace used to isolate interprocess communication (IPC) resources such as System V IPC objects and POSIX message queues. - 44. nsMNT -- MNT namespace - The Inode of the namespace used to isolate filesystem mount points thus offering different views of the filesystem hierarchy. - 45. nsNET -- NET namespace - The Inode of the namespace used to isolate resources such as network devices, IP addresses, IP routing, port numbers, etc. - 46. nsPID -- PID namespace - The Inode of the namespace used to isolate process ID numbers meaning they need not remain unique. Thus, each such namespace could have its own `init/systemd' (PID #1) to manage various initialization tasks and reap orphaned child processes. - 47. nsUSER -- USER namespace - The Inode of the namespace used to isolate the user and group ID numbers. Thus, a process could have a normal unprivileged user ID outside a user namespace while having a user ID of 0, with full root privileges, inside that namespace. - 48. nsUTS -- UTS namespace - The Inode of the namespace used to isolate hostname and NIS domain name. UTS simply means "UNIX Time-sharing System". - 49. vMj -- Major Page Fault Count Delta - The number of major page faults that have occurred since the last update (see nMaj). - 50. vMn -- Minor Page Fault Count Delta - The number of minor page faults that have occurred since the last update (see nMin). 3b. MANAGING FieldsAfter pressing the interactive command `f' or `F' (Fields Management) you will be presented with a screen showing: 1) the `current' window name; 2) the designated sort field; 3) all fields in their current order along with descriptions. Entries marked with an asterisk are the currently displayed fields, screen width permitting. -.Listed, & 4a. GLOBAL CommandsT provide a reminder of all the basic interactive commands. If top is secured, that screen will be abbreviated. Typing `h' or `?' on that help screen will take you to help for those interactive commands applicable to alternate-display mode. - = :Exit-Task-Limits - Removes restrictions on which tasks are shown. This command will reverse any `i' (idle tasks) and `n' (max tasks) commands that might be active. It also provides for an exit from PID monitoring, User filtering and Other filtering. horizontal scrolling. When operating in alternate-display mode this command has a broader meaning. - 0 :Zero-Suppress toggle - This command determines whether zeros are shown or suppressed monochrome mode, the entire display will appear as normal text. Thus, unless the `x' and/or `y' toggles are using reverse for emphasis, there will be no visual confirmation that. -, top displays a summation of all threads in each process. - I :Irix/Solaris-Mode toggle - When operating in Solaris mode (`I' toggled Off), a task's cpu usage will be divided by the total number of CPUs. After issuing this command, you'll be told the new> -. windows. For details regarding this interactive command see topic 4d. COLOR Mapping. - * - The commands shown with an asterisk (`*') are not available in Secure mode, nor will they be shown on the level-1 help screen. 4b. SUMMARY AREA. - C :Show-scroll-coordinates toggle - Toggle an informational message which is displayed whenever the message line is not otherwise being used. For additional information see topic 5c. SCROLLING a Window. - l :Load-Average/Uptime toggle - This is also the line containing the program name (possibly an alias) when operating in full - 1 :Single/Separate-Cpu-States toggle - This command affects how the `t' command's Cpu States portion statistics for each NUMA Node. It is only available if a system. 4c. TASK AREA CommandsThe task area interactive commands are always available in full-screen mode. The task area interactive commands are never available in alternate. It may also impact the summary area when a bar graph has been selected for cpu states or memory usage via the `t' or `m' toggles. - disabled. | F :Fields-Management - These keys display a separate screen where you can change which fields are displayed, their order and also designate the sort field. For additional information on these interactive commands see topic 3b. MANAGING Fields. - o | O :Other-Filtering - You will be prompted for the selection criteria which then determines which tasks will be shown in the `current' window., effective,). Note: Typing any key affecting the sort order will exit forest view mode in the `current' window. See topic 4c. TASK AREA Commands, SORTING for information on those keys. SIZE of task window - i :Idle-Process toggle - Displays all tasks or just active tasks. When this toggle is Off, tasks that have not used any CPU since the last update will not be displayed. However, due to the granularity of the %CPU and TIME+ fields, some processes may still be displayed that appear to have used no CPU. If this command is applied to the last task display when in alternate-display mode, then it will not affect the window's size, as all prior task displays will have already been painted. - n | # :Set-Maximum-Tasks - You will be prompted to enter the number of tasks to display. The lessor of your number and available screen rows will be used. - These keys display a separate screen where you can change which field is used as the sort column, among other functions. This. 4d. COLOR MappingWhen summary. 5b. COMMANDS for Windows - - | _ :Show/Hide-Window(s) toggles - The `-' key turns the `current' window's task display On and Off. When On, that task area will show a minimum of the columns header you've established with the `f' interactive command. It will also reflect any other task area options/toggles you've applied yielding zero or more tasks. filter) displays designating the with color mapping and fields management 5c. SCROLLING a WindowTypically a task window is a partial view into a systems's total tasks/threads which shows only some of the available fields/columns. With these scrolling keys, you can move that view vertically variable width column has also been scrolled.. - y = n/n (tasks) - The first n represents the topmost visible task and is.., - for example PID is good but %CPU bad.. 5e. FILTERING in a WindowYou can use this Other Filter feature to establish selection criteria which will then determine which tasks are shown in the `current' window. -. message `='.. 6. FILES 6a. SYSTEM Configuration FileThe presence of this file will influence which version of the help screen is shown to an ordinary user. More importantly, it will limit what ordinary users are allowed to do when top is running.This. 6.plerMany of these tricks work best when you give top a scheduling boost. So plan on starting him with a nice value of -10, assuming you've got the authority. 7a. Kernel MagicFor. -. 7b. Bouncing WindowsFor these stupid tricks, top needs alternate-display mode. - With 3 or 4 task displays visible, pick any window other than the last and turn idle processes Off using the `i' command toggle. Depending on where you applied `i', sometimes several task displays are bouncing and sometimes it's like an accordion, as top tries his best to allocate space. - stupid trick works best without alternate-display mode, since justification is active on a per window basis. - Start top and make COMMAND the last (rightmost) column displayed. 8. BUGSTo report bugs, follow the instructions at: 9. HISTORY Former topThe original top was written by Roger Binns, based on Branko Lankester's <[email protected]> ps program. Robert Nation <[email protected]> adapted it for the proc file system. Helmut Geyer <[email protected]> added support for configurable fields. Plus many other individuals contributed over the years. 10. AUTHORThis entirely new and enhanced replacement was written by: Jim Warner, <[email protected]> With invaluable help from: Craig Small, <[email protected]> Albert Cahalan, <[email protected]>
http://manpages.org/top
CC-MAIN-2019-26
refinedweb
2,283
63.39
The purpose of this article is to show how to allow sorting of controls (e.g. a Listview) that are bound to an ObservableCollection using the MVVM (model, view, view model) pattern and the sorting takes place in the view model. Listview ObservableCollection The background behind this article is that I had a requirement to add sorting to a listview that was data bound to an ObservableCollection. The main issue I found was that ObservableCollection is an unordered list and you can't sort it. I struggled to find an article to help achieve this within an MVVM patterned framework, in order that the sorting was done in the view model as opposed to in code behind. This would therefore be more testable and separates my concerns more cleanly. listview In order to help anyone else who may have the same problem in the future, I thought I'd write up how I achieved this requirement in an MVVM environment. The sample application for this article is a list of people which you will be able to sort by either first name or last name. So to illustrate, we have an unsorted list as below: By clicking on the first name header, it sorts it ascending as shown: Then we click first name again and it resorts it descending as shown: Out of scope for this article is to explain what the MVVM pattern is and any frameworks used to implement MVVM in a more fuller implementation. For more information on MVVM, there are some very good articles on this site that explain both MVVM as an overview and frameworks that can be used when developing full applications. Also out of scope is the way in which the test data is loaded in the application. This data should be loaded from a database, file or entered into the application. The way in which this is done in the code is not best practices but only used to illustrate the sorting element. To start off, here is the test that shows how the sort will be done. All of the test code can be found in the ObservableCollectionSortingExample.Test project. ObservableCollectionSortingExample.Test 1. using Microsoft.VisualStudio.TestTools.UnitTesting; 2. 3. namespace ObservableCollectionSortingExample.Test 4. { 5. [TestClass] 6. public class SortingTests 7. { 8. PeopleVewModel viewModel; 9. Person person1; 10. Person person2; 11. Person person3; 12. Person person4; 13. Person person5; 14. Person person6; 15. 16. [TestInitializeAttribute] 17. public void InitialiseViewModel() 18. { 19. viewModel = new PeopleVewModel(); 20. 21. People people = new People(); 22. person1 = new Person() { Firstname = "Michael", Lastname = "Bookatz" }; 23. people.Add(person1); 24. person2 = new Person() { Firstname = "Chris", Lastname = "Johnson" }; 25. people.Add(person2); 26. person3 = new Person() { Firstname = "John", Lastname = "Doe" }; 27. people.Add(person3); 28. person4 = new Person() { Firstname = "Ann", Lastname = "Other" }; 29. people.Add(person4); 30. person5 = new Person() { Firstname = "Jack", Lastname = "Smith" }; 31. people.Add(person5); 32. person6 = new Person() { Firstname = "Charles", Lastname = "Langford" }; 33. people.Add(person6); 34. 35. viewModel.People = people; 36. } 37. 38. [TestMethod] 39. public void SortByFirstname() 40. { 41. viewModel.SortList.Execute("Firstname"); 42. 43. Assert.IsTrue(viewModel.PeopleView.Count == 6); 44. Assert.IsTrue(((Person)viewModel.PeopleView.GetItemAt(0)) == person4); 45. Assert.IsTrue(((Person)viewModel.PeopleView.GetItemAt(1)) == person6); 46. Assert.IsTrue(((Person)viewModel.PeopleView.GetItemAt(2)) == person2); 47. Assert.IsTrue(((Person)viewModel.PeopleView.GetItemAt(3)) == person5); 48. Assert.IsTrue(((Person)viewModel.PeopleView.GetItemAt(4)) == person3); 49. Assert.IsTrue(((Person)viewModel.PeopleView.GetItemAt(5)) == person1); 50. 51. viewModel.SortList.Execute("Firstname"); 52. 53. Assert.IsTrue(viewModel.PeopleView.Count == 6); 54. Assert.IsTrue(((Person)viewModel.PeopleView.GetItemAt(5)) == person4); 55. Assert.IsTrue(((Person)viewModel.PeopleView.GetItemAt(4)) == person6); 56. Assert.IsTrue(((Person)viewModel.PeopleView.GetItemAt(3)) == person2); 57. Assert.IsTrue(((Person)viewModel.PeopleView.GetItemAt(2)) == person5); 58. Assert.IsTrue(((Person)viewModel.PeopleView.GetItemAt(1)) == person3); 59. Assert.IsTrue(((Person)viewModel.PeopleView.GetItemAt(0)) == person1); 60. } 61. } 62. } Lines 8 to 14 are the declaration for the fields that will be used in the test for the objects that represent the view model and a list of people to be tested against. On line 11, we create the object that is going to do the loop iteration. This is a generic type so that it can be used to test all different classes. On lines 16 to 36, the test initialisation is run. This sets up the objects for the model and then creates the view model that the test will be run against. Line 39 starts the actual test method. Line 41 and 51 represent the list being sorted. The first set of assert on lines 43 to 49 makes sure that after the first sorting by first name, the order of the list is in the correct order of ascending first name. We reverse the list on line 51 and then check on Lines 53 to 50 that the order has been reversed. One of the important points to note in the test is that property from the view model used to obtain the Person to compare to the expected person isn't an ObservableCollection but a ListCollectionView. This is because an ObservableCollection is an unsorted list of items. The way round sorting an ObservableCollection (and also applying grouping and filtering) is to use a class that implements ICollectionView which ListCollectionView does. ListCollectionView ICollectionView For the sake of completeness, below is the test for sorting by last name: 1. [TestMethod] 2. public void SortByLastname() 3. { 4. viewModel.SortList.Execute("Lastname"); 5. 6. Assert.IsTrue(viewModel.PeopleView.Count == 6); 7. Assert.IsTrue(((Person)viewModel.PeopleView.GetItemAt(0)) == person1); 8. Assert.IsTrue(((Person)viewModel.PeopleView.GetItemAt(1)) == person3); 9. Assert.IsTrue(((Person)viewModel.PeopleView.GetItemAt(2)) == person2); 10. Assert.IsTrue(((Person)viewModel.PeopleView.GetItemAt(3)) == person6); 11. Assert.IsTrue(((Person)viewModel.PeopleView.GetItemAt(4)) == person4); 12. Assert.IsTrue(((Person)viewModel.PeopleView.GetItemAt(5)) == person5); 13. 14. viewModel.SortList.Execute("Lastname"); 15. 16. Assert.IsTrue(viewModel.PeopleView.Count == 6); 17. Assert.IsTrue(((Person)viewModel.PeopleView.GetItemAt(5)) == person1); 18. Assert.IsTrue(((Person)viewModel.PeopleView.GetItemAt(4)) == person3); 19. Assert.IsTrue(((Person)viewModel.PeopleView.GetItemAt(3)) == person2); 20. Assert.IsTrue(((Person)viewModel.PeopleView.GetItemAt(2)) == person6); 21. Assert.IsTrue(((Person)viewModel.PeopleView.GetItemAt(1)) == person4); 22. Assert.IsTrue(((Person)viewModel.PeopleView.GetItemAt(0)) == person5); 23. } This is the same as the test above with the only changes being on line 4 and 14 where you sort by last name instead of first name. All the code for the Models can be found in ObservableCollectionSortingExample.Model. ObservableCollectionSortingExample.Model The models used for this are very simple. All the person class does is define two string properties first name and last name and then equality overrides so we can test that two person objects are equal in the tests. The code is: string 1. public class Person 2. { 3. public string Firstname { get; set; } 4. 5. public string Lastname { get; set; } 6. 7. public override bool Equals(object obj) 8. { 9. if (obj == null || GetType() != obj.GetType()) 10. { 11. return false; 12. } 13. 14. Person other = obj as Person; 15. 16. if (this.Firstname != other.Firstname) 17. return false; 18. 19. if (this.Lastname != other.Lastname) 20. return false; 21. 22. return true; 23. } 24. 25. public override int GetHashCode() 26. { 27. return Firstname.GetHashCode() ^ Lastname.GetHashCode(); 28. } 29. 30. public static bool operator ==(Person person1, Person person2) 31. { 32. if (Object.Equals(person1, null) && Object.Equals(person2, null)) 33. { 34. return true; 35. } 36. return person1.Equals(person2); 37. } 38. 39. public static bool operator !=(Person person1, Person person2) 40. { 41. return !(person1 == person2); 42. } 43. } Nothing particularly out of the ordinary here. All the people class is is a specialisation of ObservableCollection class with Person as the type. The code is: Person 1. public class People : ObservableCollection<person> 2. { 3. 4. } </person> I picked ObservableCollection as the collection type as I know this will be used in a display. It made sense to use ObservableCollection which has all the benefits of allowing you to databind to it, rather than have to copy from a different type collection into ObservableCollection later on in the program. All the code for the view model can be found in the ObservableCollectionSortingExample project. ObservableCollectionSortingExample As we have now seen the tests and the models, let's look at the view model that will pass the tests above. Below is part of the code from the view model. This is the property to set a list of people to be used by the view. 1. People observerablePeople = new People(); 2. CollectionViewSource peopleView; 3. 4. public People People 5. { 6. private get 7. { 8. return this.observerablePeople; 9. } 10. set 11. { 12. this.observerablePeople = value; 13. peopleView = new CollectionViewSource(); 14. peopleView.Source = this.observerablePeople; 15. } 16. } There are a few important parts of code to notice. First is that the get on line 6 is private. This is because for the ObservableCollection to be sortable, you need to bind to a view of the collection. So as to prevent binding to the underlying collection instead, the get is made private. get private The set is used for the ObservableCollection that is the underlying data the display is based on. As part of the set, you also need to update the ObservableCollection view that will be used by the view to display the data. If you don't update the view by creating a new CollectionViewSource, then it will point to the original ObservableCollection and therefore display the incorrect information if the Observable collection changes. CollectionViewSource The next part is the code that is the property that allows you to get the view onto the ObservableCollection. 1. public ListCollectionView PeopleView 2. { 3. get 4. { 5. return (ListCollectionView) peopleView.View; 6. } 7. } All this does is return the view onto the ObservableCollection that will be used by the View. We return a ListCollectionView instead of a CollectionView as the ListCollectionView offers better performance and the View property of CollectionViewSource only returns an interface. Plus as we know we are using an ObservableCollection then it makes sense to use the more specific class of ListCollectionView rather then CollectionView which is more generic. View CollectionView View The next part of the class is just a command property that is used by the Command Binding in the WPF to execute the sorting. Line 9 is where the Command has a method assigned to an event that is called when the command is executed. 1. private CommandStub sortList; 2. public ICommand SortList 3. { 4. get 5. { 6. if (sortList == null) 7. { 8. sortList = new CommandStub(); 9. sortList.OnExecuting += new CommandStub.ExecutingEventHandler(sortList_OnExecuting); 10. } 11. return sortList; 12. } 13.} The code below is the actual method that is called by the command set up above. As you can see, the actual code to do the sorting is quite simple. 1. void sortList_OnExecuting(object parameter) 2. { 3. string sortColumn = (string)parameter; 4. this.peopleView.SortDescriptions.Clear(); 5. 6. if (this.sortAscending) 7. { 8. this.peopleView.SortDescriptions.Add (new SortDescription(sortColumn, ListSortDirection.Ascending)); 9. this.sortAscending = false; 10. } 11. else 12. { 13. this.peopleView.SortDescriptions.Add (new SortDescription(sortColumn, ListSortDirection.Descending)); 14. this.sortAscending = true; 15. } 16. } Line 3 works out the name of the column that is to be sorted. We then clear the current sorting in line 4. Lines 6 to 15 performs the actual sorting. There is a flag set to determine if the sort order should be Ascending or Descending and then the correct view depending on ascending or descending is added to the peopleView in lines 8 or 13. The next line after this then toggles the sortAscending flag. peopleView sortAscending And that is all there is to the view model. To sum up, all you need to do is make sure your view binds to a ListCollectionView on to the ObservableCollection and then add sorting to the view. All the code for the view can be found in the ObservableCollectionSortingExample project. The view is defined in XAML in the file PeopleView.xaml. I am going to assume that you have a basic familiarity with XAML, so I am not going to cover it here. For more information on XAML, you can find excellent resources online both at this site and elsewhere. The XAML for the view is: 1. <Window x:Class="ObservableCollectionSortingExample.PeopleView" 2. xmlns="" 3. xmlns:x="" 4. Title="SortingExample"Height="350"Width="200" 5. xmlns: 6. <Window.Resources> 7. <local:PeopleVewModelx:</local:PeopleVewModel> 8. </Window.Resources> 9. <Grid DataContext="{StaticResourcePeopleViewDataContext}"> 10. <Grid.RowDefinitions> 11. < 12. </Grid.RowDefinitions> 13. <ListView HorizontalAlignment="Stretch" Margin="10,10,10,10" Name="ListOfName" 14. 15. <ListView.View> 16. <GridView> 17. <GridViewColumn DisplayMemberBinding="{BindingPath=Firstname}"> 18. <GridViewColumnHeader Command="{BindingSortList}" CommandParameter="Firstname"> Firstname</GridViewColumnHeader> 19. </GridViewColumn> 20. <GridViewColumn DisplayMemberBinding="{BindingPath=Lastname}"> 21. <GridViewColumnHeader Command="{BindingSortList}" CommandParameter="Lastname"> Lastname</GridViewColumnHeader> 22. </GridViewColumn> 23. </GridView> 24. </ListView.View> 25. </ListView> 26. </Grid> 27. </Window> To pick up some of the important lines in this XAML is as follows. Line 7 sets up the link for this view to the view model as a resource in XAML which can then be used in the rest of the XAML. The Data context is set up in line 9 so that all of the other controls in the control can access the view. Now comes the real magic in line 14. The ItemSource is set to the PeopleView in the view model. This as you will remember is the view on to the underlying ObservableCollection list. The Binding on the actual columns of the listview is the same as if you where binding to an ObservableCollection as can be seen in line 17 and 20. ItemSource PeopleView The command binding on lines 18 and 21 is where we bind to the SortList Command from the view model. We pass in the name of the column that will have the command action done to it. This is the parameter that is passed into the sortList_OnExecuting(object parameter) method in the view model. This parameter is used to know which column to sort by. SortList sortList_OnExecuting(object parameter) So as you can see from the example above, the key part to sorting is to make sure you bind to a ListCollectionView on to the ObservableCollection rather than onto the ObservableCollection.
http://www.codeproject.com/Articles/178011/Sorting-an-Observable-Collection-using-the-View-Mo?fid=1619239&df=90&mpp=10&noise=1&prof=True&sort=Position&view=Expanded&spc=None
CC-MAIN-2016-22
refinedweb
2,371
50.84
Parsing Part 4: Megaparsec In part 3 of this series, we explored the Attoparsec library. It provided us with a clearer syntax to work with compared to applicative parsing, which we learned in part 2. This week, we’ll explore one final library: Megaparsec. This library has a lot in common with Attoparsec. In fact, the two have a lot of compatibility by design. Ultimately, we’ll find that we don’t need to change our syntax a whole lot. But Megaparsec does have a few extra features that can make our lives simpler. To follow the code examples here, head to the megaparsec branch on Github! To learn about more awesome libraries you can use in production, make sure to download our Production Checklist! But never fear if you’re new to Haskell! Just take a look at our Beginners checklist and you’ll know where to get started! A Different Parser Type To start out, the basic parsing type for Megaparsec is a little more complicated. It has two type parameters, e and s, and also comes with a built-in monad transformer ParsecT. data ParsecT e s m a type Parsec e s = ParsecT e s Identity The e type allows us to provide some custom error data to our parser. The s type refers to the input type of our parser, typically some variant of String. This parameter also exists under the hood in Attoparsec. But we sidestepped that issue by using the Text module. For now, we’ll set up our own type alias that will sweep these parameters under the rug: type MParser = Parsec Void Text Trying our Hardest Let’s start filling in our parsers. There’s one structural difference between Attoparsec and Megaparsec. When a parser fails in Attoparsec, its default behavior is to backtrack. This means it acts as though it consumed no input. This is not the case in Megaparsec! A naive attempt to repeat our nullParser code could fail in some ways: nullParser :: MParser Value nullParser = nullWordParser >> return ValueNull where nullWordParser = string "Null" <|> string "NULL" <|> string "null" Suppose we get the input "NULL" for this parser. Our program will attempt to select the first parser, which will parse the N token. Then it will fail on U. It will move on to the second parser, but it will have already consumed the N! Thus the second and third parser will both fail as well! We get around this issue by using the try combinator. Using try gives us the Attoparsec behavior of backtracking if our parser fails. The following will work without issue: nullParser :: MParser Value nullParser = nullWordParser >> return ValueNull where nullWordParser = try (string "Null") <|> try (string "NULL") <|> try (string "null") Even better, Megaparsec also has a convenience function string’ for case insensitive parsing. So our null and boolean parsers become even simpler: nullParser :: MParser Value nullParser = M.string' "null" >> return ValueNull boolParser :: MParser Value boolParser = (trueParser >> return (ValueBool True)) <|> (falseParser >> return (ValueBool False)) where trueParser = M.string' "true" falseParser = M.string' "false" Unlike Attoparsec, we don’t have a convenient parser for scientific numbers. We’ll have to go back to our logic from applicative parsing, only this time with monadic syntax. numberParser :: MParser Value numberParser = (ValueNumber . read) <$> (negativeParser <|> decimalParser <|> integerParser) where integerParser :: MParser String integerParser = M.try (some M.digitChar) decimalParser :: MParser String decimalParser = M.try $ do front <- many M.digitChar M.char '.' back <- some M.digitChar return $ front ++ ('.' : back) negativeParser :: MParser String negativeParser = M.try $ do M.char '-' num <- decimalParser <|> integerParser return $ '-' : num Notice that each of our first two parsers use try to allow proper backtracking. For parsing strings, we’ll use the satisfy combinator to read everything up until a bar or newline: stringParser :: MParser Value stringParser = (ValueString . trim) <$> many (M.satisfy (not . barOrNewline)) And then filling in our value parser is easy as it was before: valueParser :: MParser Value valueParser = nullParser <|> boolParser <|> numberParser <|> stringParser Filling in the Details Aside from some trivial alterations, nothing changes about how we parse example tables. The Statement parser requires adding in another try call when we’re grabbing our pairs: parseStatementLine :: Text -> MParser Statement parseStatementLine signal = do M.string signal M.char ' ' pairs <- many $ M.try ((,) <$> nonBrackets <*> insideBrackets) finalString <- nonBrackets let (fullString, keys) = buildStatement pairs finalString return $ Statement fullString keys where buildStatement = ... Otherwise, we’ll fail on any case where we don’t use any keywords in the statement! But it's otherwise the same. Of course, we also need to change how we call our parser in the first place. We'll use the runParser function instead of Attoparsec’s parseOnly. This takes an extra argument for the source file of our parser to provide better messages. parseFeatureFromFile :: FilePath -> IO Feature parseFeatureFromFile inputFile = do … case runParser featureParser finalString inputFile of Left s -> error (show s) Right feature -> return feature But nothing else changes in the structure of our parsers. It's very easy to take Attoparsec code and Megaparsec code and re-use it with the other library! Adding some State One bonus we do get from Megaparsec is that its monad transformer makes it easier for us to use other monadic functionality. Our parser for statement lines has always been a little bit clunky. Let’s clean it up a little bit by allowing ourselves to store a list of strings as a state object. Here’s how we’ll change our parser type: type MParser = ParsecT Void Text (State [String]) Now whenever we parse a key using our brackets parser, we can append that key to our existing list using modify. We’ll also return the brackets along with the string instead of merely the keyword: insideBrackets :: MParser String insideBrackets = do M.char '<' key <- many M.letterChar M.char '>' modify (++ [key]) -- Store the key in the state! return $ ('<' : key) ++ ['>'] Now instead of forming tuples, we can concatenate the strings we parse! parseStatementLine :: Text -> MParser Statement parseStatementLine signal = do M.string signal M.char ' ' pairs <- many $ M.try ((++) <$> nonBrackets <*> insideBrackets) finalString <- nonBrackets let fullString = concat pairs ++ finalString … And now how do we get our final list of keys? Simple! We get our state value, reset it, and return everything. No need for our messy buildStatement function! parseStatementLine :: Text -> MParser Statement parseStatementLine signal = do M.string signal M.char ' ' pairs <- many $ M.try ((++) <$> nonBrackets <*> insideBrackets) finalString <- nonBrackets let fullString = concat pairs ++ finalString keys <- get put [] return $ Statement fullString keys When we run this parser at the start, we now have to use runParserT instead of runParser. This returns us an action in the State monad, meaning we have to use evalState to get our final result: parseFeatureFromFile :: FilePath -> IO Feature parseFeatureFromFile inputFile = do … case evalState (stateAction finalString) [] of Left s -> error (show s) Right feature -> return feature where stateAction s = runParserT featureParser inputFile s Bonuses of Megaparsec As a last bonus, let's look at error messages in Megaparsec. When we have errors in Attoparsec, the parseOnly function gives us an error string. But it’s not that helpful. All it tells us is what individual parser on the inside of our system failed: >> parseOnly nullParser "true" Left "string" >> parseOnly "numberParser" "hello" Left "Failed reading: takeWhile1" These messages don’t tell us where within the input it failed, or what we expected instead. Let’s compare this to Megaparsec and runParser: >> runParser nullParser "true" "" Left (TrivialError (SourcePos {sourceName = "true", sourceLine = Pos 1, sourceColumn = Pos 1} :| []) (Just EndOfInput) (fromList [Tokens ('n' :| "ull")])) >> runParser numberParser "hello" "" Left (TrivialError (SourcePos {sourceName = "hello", sourceLine = Pos 1, sourceColumn = Pos 1} :| []) (Just EndOfInput) (fromList [Tokens ('-' :| ""),Tokens ('.' :| ""),Label ('d' :| "igit")])) This gives us a lot more information! We can see the string we’re trying to parse. We can also see the exact position it fails at. It’ll even give us a picture of what parsers it was trying to use. In a larger system, this makes a big difference. We can track down where we’ve gone wrong either in developing our syntax, or conforming our input to meet the syntax. If we customize the e parameter type, we can even add our own details into the error message to help even more! Conclusion This wraps up our exploration of parsing libraries in Haskell! In the past few weeks, we’ve learned about Applicative parsing, Attoparsec, and Megaparsec. The first provides useful and intuitive combinators for when our language is regular. It allows us to avoid using a monad for parsing and the baggage that might bring. With Attoparsec, we saw an introduction to monadic style parsing. This provided us with a syntax that was easier to understand and where we could see what was happening. Finally in this part, we explored Megaparsec. This library has a lot in common syntactically with Attoparsec. But it provides a few more bells and whistles that can make many tasks easier. Ready to explore some more areas of Haskell development? Want to get some ideas for new libraries to learn? Download our Production Checklist! It’ll give you a quick summary of some tools in areas ranging from data structures to web APIs! Never programmed in Haskell before? Want to get started? Check out our Beginners Checklist! It has all the tools you need to start your Haskell journey!
https://mmhaskell.com/parsing-4
CC-MAIN-2018-51
refinedweb
1,535
65.83
In this series, we are going to show the EcmaScript features from 2015 to today. ES2015 aka ES6 ES2016 aka ES7 ES2017 aka ES8 ES2018 aka ES9 - - Introduction ES2020 is the version of ECMAScript corresponding to the year 2020. This version does not include as many new features as those that appeared in ES6 (2015). However, some useful features have been incorporated. This article introduces the features provided by ES2020 in easy code examples. In this way, you can quickly understand the new features without the need for a complex explanation. Of course, it is necessary to have a basic knowledge of JavaScript to fully understand the best ones introduced. The new #JavaScript features in ES2020 are: ➡️ String.prototype.matchAll ➡️ import() ➡️ BigInt ➡️ Promise.allSettled ➡️ globalThis ➡️ for-in mechanics ➡️ Optional Chaining ➡️ Nullish coalescing Operator String.protype.matchAll The matchAll() method returns an iterator of all results matching a string against a regular expression, including capturing groups. Dynamic import Dynamic import() returns a promise for the module namespace object of the requested module. Therefore, imports can now be assigned to a variable using async/await. BigInt — Arbitrary precision integers BigInt is the 7th primitive type and It is an arbitrary-precision integer. The variables can now represent ²⁵³ numbers and not just max out at 9007199254740992. Promise.allSettled Promise.allSettled returns a promise that is fulfilled with an array of promise state snapshots, but only after all the original promises have settled, i.e. become either fulfilled or rejected. We say that a promise is settled if it is not pending, i.e. if it is either fulfilled or rejected. Standardized globalThis object The global this was not standardized before ES10. In production code you would “standardize” it across multiple platforms on your own by writing this monstrosity: for-in mechanics ECMA-262 leaves the order of for (a in b)... almost totally unspecified, but real engines tend to be consistent in at least some cases. Historical efforts to get consensus on a complete specification of the order of for-in have repeatedly failed, in part because all engines have their own idiosyncratic implementations which are the result of a great deal of work and which they don’t really want to revisit. In conclusion, the different engines have agreed on how properties are iterated when using the for (a in b) control structure so that the behavior is standardized. Nullish coalescing Operator When performing property accesses, it is often desired to provide a default value if the result of that property access is null or undefined. At present, a typical way to express this intent in JavaScript is by using the || operator. This works well for the common case of null and undefined values, but there are a number of falsy values that might produce surprising results. The nullary coalescing operator is intended to handle these cases better and serves as an equality check against nullary values (null or undefined). If the expression at the left-hand side of the ?? operator evaluates to undefined or null, its right-hand side is returned. Optional Chaining When looking for a property value that’s deep in a tree-like structure, one often has to check whether intermediate nodes exist. The Optional Chaining Operator allows handle many of those cases without repeating themselves and/or assigning intermediate results in temporary variables. Also, many API return either an object or null/undefined, and one may want to extract a property from the result only when it is not null: When some other value than undefined is desired for the missing case, this can usually be handled with the Nullish coalescing operator: Conclusion JavaScript is a live language, and that is something very healthy for web development. Since the appearance of ES6 in 2015 we are living a vibrant evolution in the language. In this post we have reviewed the features that arise in ES2020. Although many of these features may not be essential for the development of your Web application, they are giving possibilities that could be achieved before with tricks or a lot of verbosity. Discussion Yea, constant legacy worrying and xbrowser issues push me further and further away from the frontend. Nodejs is far more comfortable and user friendly environment than whatever google next patch will bring, safari wont support or client with ie11 will complain ;) Why don't you try a transpiler? I use transpiler. That doesnt save you from different implementations of features in different browsers. Thanks for taking the time to put this together, great high level summary of some exciting upcoming features! Thanks Calvin! I hope to complete the series although ES6 has already been written enough. However, the ideal is to have a place where the news that the standard brings us annually is summarized and updated. Thanks for the write-up! Any word about browser adoption of these features? Either way, they should be in core-js / babel soon, which will help a lot (especially a fan of using optional chaining 🥳) I keep this compatibility table bookmarked. Finally, ??. I hope with works fine just like ?.in TypeScript. Can I use this in esnext? Nice article, thank you for the explanations. I have written an in-depth blog post on the same topic abhishekdeshmukh.com/blog/javascri... Feel free to check it out In Nullish section falsy examples: const value = values.numberValue || 300; //300 I think you wrote values.numberValue instead of values.zeroValue? Because it's supposed to return 400.
https://dev.to/carlillo/es2020-features-in-simple-examples-1513
CC-MAIN-2020-50
refinedweb
913
54.93
Get to know the assets of your filament stock Step 1: 3D Printer If you have one of these machines, Step 2: Nearly Empty Spools Sooner or later you will get many of these. Nearly empty spools with some meters of filament. If you are somehowe like me, you can't throw them away. Perhapse there comes a small project some day where you can use them? Step 3: Filament Meter Based on my needs, I did develop a 3D prinatable filament meter. It is adopted to fit the top frame of an Anet A8, and are powered with a 9V battery. The power consumptiuon is only 4,5 mA so the battrery will last many hours. Step 4: OLED Display The OLED display frame is carefully made by Mr Dumnac and can be found on Thingervis - Many thanks to him. Step 5: Home Made PCB's The PCB's are design specially for this purpose and etched at my kitchen sink. Perferct results and without any "links". The princip is to have an encoder wheel to be turned around as you drag the filament over a wheel on the other side of the "bugger". The encoder is counted by an photo interupter. Because of variable speed and hence frequencies, the signal from the photo interupter is fed to a HW Schmit trigger (SN74 14), before loaded to the Attiny 85. In the Attiny an interupt is used to count the pulses, and a divider to correct from pulses to cm filament. All is powered by a LM 7805 voltage regulator. Step 6: Lay Out Here is the lay out of the PCB's The smal PCB is soldered to the main board by means of some 90 degrees pins. Step 7: Schemastic Schematic diagram for those of you wanting to make it. Step 8: 3D Printable Here you can see all the parts needed. Including a bearing 608 Yx2Z. Step 9: The Code #include "avr/interrupt.h"; #include #include U8X8_SSD1306_128X64_NONAME_SW_I2C u8x8(/* clock=*/ 2, /* data=*/ 0, /* reset=*/ U8X8_PIN_NONE); // Digispark ATTiny85 int pulse=0; void setup(void) { u8x8.begin(); GIMSK = 0b00100000; // turns on pin change interrupts PCMSK = 0b00001000; // turn on interrupts on pins PB3 sei(); // enables interrupts } void loop(void) { u8x8.setFont(u8x8_font_victoriabold8_r); u8x8.drawString(1,2,"Reset and drag"); u8x8.setCursor(1,4); u8x8.print(" fillament "); u8x8.setCursor(2,6); u8x8.print("cm: "); u8x8.setCursor(8,6); u8x8.print(pulse/3.53); } ISR(PCINT0_vect) { pulse=pulse+1; } Discussions 9 months ago This is great! I need something like this to keep track of my old filament.
https://www.instructables.com/id/Filament-Metering/
CC-MAIN-2019-09
refinedweb
426
73.17
When handling multiple devices it would be handy to be able to maintain a vector of kernel functors, where each functor is associated with a command queue: std::vector<cl::KernelFunctor> kernelFunctors; for (int d = 0 ; d < commandQueues.size() ; d++) { kernelFunctors.push_back(kernel.bind(commandQueues[d], globalNDRange, localNDRange)); } Any ideas for how to implement something like this, given that this won't work without being able to copy KernelFunctors? Reassign to Benedict. I have updated the C++ bindings to provide copy constructor for KernelFunctor and the following program now compiles without error: #include <CL/cl.hpp> int main(void) { std::vector<cl::CommandQueue> commandQueues; cl::Kernel kernel; cl::NDRange globalNDRange; cl::NDRange localNDRange; std::vector<cl::KernelFunctor> kernelFunctors; for (int d = 0 ; d < commandQueues.size() ; d++) { kernelFunctors.push_back( kernel.bind( commandQueues[d], globalNDRange, localNDRange)); } } Please let me know if you have any problems using it and thanks for feedback. This doesn't work as hoped unfortunately. The KernelFunctor has a reference to a Kernel and a CommandQueue, and so strange things start happening when you try reseat the reference in the assignment operator. I can get the original code to execute by changing the copy constructor to: inline KernelFunctor::KernelFunctor(const KernelFunctor& rhs) : kernel_(rhs.kernel_), queue_(rhs.queue_), offset_(rhs.offset_), global_(rhs.global_), local_(rhs.local_), err_(rhs.err_) { //*this = rhs; } (i.e. complete the initializer list and remove the call to the assignment operator) In this case the assignment operator is never called, but it must still be present as stl::vectors mandate it. Perhaps the assignment operator should fail if rhs != lhs. KernelFunctor could maintain a pointer instead of a reference, but that's possibly not as elegant. Indeed. Let me think about this some more and I will get back with a solution. Might be best to simply remove the reference. I do not what to have pointers. (In reply to comment #4) > Indeed. Let me think about this some more and I will get back with a solution. > Might be best to simply remove the reference. I do not what to have pointers. Have you had any thoughts on this? I agree it would be preferable to avoid pointers. My suggestion would be to provide the corrected copy constructor and make the assignment illegal. I'm working on fix for this, not using ponters, and will update the C++ bindings with some other fixes in the next few days. The kernel functors in cl.hpp were reworked several years ago. Since there has been no activity on this bug I'm going to close it as fixed, but feel free to reopen it if the new kernel functors still have problems.
https://www.khronos.org/bugzilla/show_bug.cgi?id=200
CC-MAIN-2015-48
refinedweb
447
57.47
This tutorial guides you to setup a C++ compiler and a text editor to start C++ programming on Ubuntu. The compiler is GNU g++ and the editor is Geany. With this tutorial, you can easily type C++ source codes from your lecturers or books, then compile and run them by clicks. This tutorial is intended for you beginners in programming especially if you're new Ubuntu users. Happy programming! This tutorial is for C++ language. If you're looking for C language, read here. 1. Install Compiler Do it: sudo apt-get install g++ 2. Install Editor Do it: sudo apt-get install geany 3. Write Now type this source code and save it as code.cpp. #include <iostream> using namespace std; int main() { cout << "hello, c plus plus!" << endl; return 0; } 4. Compile Now press Compile button, and then press Build button. If your code has no error, then these should translate your source code into object code and then binary executable code. See gif animation below. - What's Compile button? This is the same as g++ -c code.cpp and it produces file named code.o. This is an object file. - What's Build button? This is the same as g++ -o code code.cpp and it produces file named code (without extension). This is an executable binary file. - What's Run button? This is the same as ./code which is running the executable file produced from your source code. 5. Run Now press Run button. This should run a Terminal and the code of yours says hello, c plus plus! on screen. At this stage, you can compile C++ codes you find on internet. If you find errors, just learn it, find how to solve them. Learn from that. Where to Get C++ Examples? You will want many C++ source code examples to learn. Go to and the Tutorial Page to get sources and compile them one by one. Start from "Structure of a program" there.
https://www.ubuntubuzz.com/2017/09/setup-cpp-programming-tools-on-ubuntu-for-beginners.html
CC-MAIN-2021-21
refinedweb
329
78.85
"""Error classes for CherryPy.""" from cgi import escape as _escape from sys import exc_info as _exc_info from urlparse import urljoin as _urljoin from cherrypy.lib import http as _http class WrongConfigValue(Exception): """ Happens when a config value can't be parsed, or is otherwise illegal. """ pass class InternalRedirect(Exception): """Exception raised when processing should be handled by a different path. If you supply a query string, it will be replace request.params. If you omit the query string, the params from the original request will remain in effect. """ def __init__(self, path): import cherrypy request = cherrypy.request if "?" in path: # Pop any params included in the path path, pm = path.split("?", 1) request.query_string = pm request.params = _http.parse_query_string(pm) # Note that urljoin will "do the right thing" whether url is: # 1. a URL relative to root (e.g. "/dummy") # 2. a URL relative to the current path # Note that any querystring will be discarded. path = _urljoin(cherrypy.request.path_info, path) # Set a 'path' member attribute so that code which traps this # error can have access to it. self.path = path Exception.__init__(self, path) class HTTPRedirect(Exception): """Exception raised when the request should be redirected. The new URL must be passed as the first argument to the Exception, e.g., cperror.HTTPRedirect(newUrl). Multiple URLs are allowed. If a URL is absolute, it will be used as-is. If it is relative, it is assumed to be relative to the current cherrypy.request.path. """ def __init__(self, urls, status=None): import cherrypy if isinstance(urls, basestring): urls = [urls] abs_urls = [] for url in urls: # Note that urljoin will "do the right thing" whether url is: # 1. a complete URL with host (e.g. "") # 2. a URL relative to root (e.g. "/dummy") # 3. a URL relative to the current path # Note that any querystring in browser_url will be discarded. url = _urljoin(cherrypy.request.browser_url, url) abs_urls.append(url) self.urls = abs_urls # RFC 2616 indicates a 301 response code fits our goal; however, # browser support for 301 is quite messy. Do 302/303 instead. See # if status is None: if cherrypy.request.protocol >= (1, 1): status = 303 else: status = 302 else: status = int(status) if status < 300 or status > 399: raise ValueError("status must be between 300 and 399.") self.status = status Exception.__init__(self, abs_urls, status) def set_response(self): import cherrypy response = cherrypy.response response.status = status = self.status if status in (300, 301, 302, 303, 307): response.headers['Content-Type'] = "text/html" # "The ... URI SHOULD be given by the Location field # in the response." response.headers['Location'] = self.urls[0] # "Unless the request method was HEAD, the entity of the response # SHOULD contain a short hypertext note with a hyperlink to the # new URI(s)." msg = {300: "This resource can be found at %s.", 301: "This resource has permanently moved to %s.", 302: "This resource resides temporarily at %s.", 303: "This resource can be found at %s.", 307: "This resource has moved temporarily to %s.", }[status] response.body = " \n".join([msg % (u, u) for u in self.urls]) elif status == 304: # Not Modified. # "The response MUST include the following header fields: # Date, unless its omission is required by section 14.18.1" # The "Date" header should have been set in Request.__init__ # "...the response SHOULD NOT include other entity-headers. for key in ('Allow', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-Location', 'Content-MD5', 'Content-Range', 'Content-Type', 'Expires', 'Last-Modified'): if key in response.headers: del response.headers[key] # "The 304 response MUST NOT contain a message-body." response.body = None elif status == 305: # Use Proxy. # self.urls[0] should be the URI of the proxy. response.headers['Location'] = self.urls[0] response.body = None else: raise ValueError("The %s status code is unknown." % status) def __call__(self): # Allow the exception to be used as a request.handler. raise self class HTTPError(Exception): """ Exception used to return an HTTP error code to the client. This exception will automatically set the response status and body. A custom message (a long description to display in the browser) can be provided in place of the default. """ def __init__(self, status=500, message=None): self.status = status = int(status) if status < 400 or status > 599: raise ValueError("status must be between 400 and 599.") self.message = message Exception.__init__(self, status, message) def set_response(self): """Set cherrypy.response status, headers, and body.""" import cherrypy response = cherrypy.response # Remove headers which applied to the original content, # but do not apply to the error page. for key in ["Accept-Ranges", "Age", "ETag", "Location", "Retry-After", "Vary", "Content-Encoding", "Content-Length", "Expires", "Content-Location", "Content-MD5", "Last-Modified"]: if response.headers.has_key(key): del response.headers[key] if self.status != 416: # "*". if response.headers.has_key("Content-Range"): del response.headers["Content-Range"] # In all cases, finalize will be called after this method, # so don't bother cleaning up response values here. response.status = self.status tb = None if cherrypy.config.get('show_tracebacks', False): tb = format_exc() content = get_error_page(self.status, traceback=tb, message=self.message) response.body = content response.headers['Content-Length'] = len(content) response.headers['Content-Type'] = "text/html" _be_ie_unfriendly(self.status) def __call__(self): # Allow the exception to be used as a request.handler. raise self class NotFound(HTTPError): """ Happens when a URL couldn't be mapped to any class.method """ def __init__(self, path=None): if path is None: import cherrypy path = cherrypy.request.path self.args = (path,) HTTPError.__init__(self, 404, "The path %r was not found." % path) class TimeoutError(Exception): """Exception raised when Response.timed_out is detected.""" pass _HTTPErrorTemplate = ''' %(message)s %(traceback)s
https://bitbucket.org/kingplesk/cherrypy/raw/992e64bf03668ee189b285407f1088631173ef5f/_cperror.py
CC-MAIN-2015-11
refinedweb
932
53.37
To Be Continuous: Have We Forgotten How To Code? To Be Continuous: Have We Forgotten How To Code? What happens when the vast amount of software is dependent on your open source software, then someone threatens to sue you over copyright, then you remove your open source software from the repository? Join the DZone community and get the full member experience.Join For Free In this Soundcloud podcast episode, Paul and Edith discuss the fallout after the widely covered 'left-pad' incident, and while they agree that these sorts of moments move the entire open-source community forward, they wonder – have we forgotten how to code? This is episode #19 in the To Be Continuous podcast series, all about continuous delivery and software development. This episode of To Be Continuous, brought to you by Heavybit. To learn more about Heavybit, visit heavybit.com. While you’re there, check out their library, home to great educational talks from other developer company founders and industry leaders. Transcript Edith: Hey Paul. Somebody unpublished a module called left-pad and the Internet basically exploded. Now, it’s been a couple of weeks since then so there’s a lot of different topics to cover in terms of what this means for open source, whether it means that people have forgotten how to program. Paul: LaunchDarkly... Sorry, the left-pad… Obviously I’m looking at my own T-shirt. Edith: You’re looking at your LaunchDarkly T-shirt? Paul: The left-pad incident was pretty interesting and one of the things that we did when coming up to this is just like looking at all the hacker news, discussions, and comments on it. There’s wildly varying positions on what this means for open source. What it means for whether people can program. What it means about the Node ecosystem. To kick this off, why don’t you give us a recap of the entire incident. Edith: In short, a programmer had a module called kik, K-I-K, which is also a very popular messaging app. Even I’ve heard of it and I’m not a teenager. The Kik lawyers contacted the dude, said, “Please take down your module. Change it.” The programmer said, “No. I basically don’t believe in copyright laws.” Then, the Kik people contacted NPM, the NPM people took down the module called kik. The guy, I’d say I kind of a fit of pique said, “Okay, you took down my one module. I’m going to take down all my modules.” Basically, "I’m taking my marbles and going home." Paul: Okay. Edith: He took down all of his modules, one of which turned out to be an incredibly popular module called left-pad which did basically what the name implied. It inserted left pads. Without this in NPM, the quote I read was, “Builds all over the world started to fail very quickly.” Paul: As I understand it, left-pad was used by another module which is used by another module which is used by something core or like this incredibly popular module. Edith: It was basically turtles on top of turtles on top of turtles and at the bottom turtle was this guy who… Paul: Took his marbles and went home. Edith: Yeah, or yanked the bottom Jenga, basically. Paul: Gotcha. All the builds started to fail, people’s deploys started to fail and people got pissed. Edith: People got pissed because they didn’t even realize that they had this dependency. What happened was NPM basically republished it. They said that, “Even though you’re the original publisher.” Paul: There was a lot of outcry on the Internet and then they republished it. Edith: NPM just basically said, “You don’t have the rights to unpublish this.” Paul: Gotcha. They had an unpublish button as I understand it. He did something that was built into NPM to remove a module. Edith: Since then, they’ve tightened their rules a lot. They’ve basically said that this should be something that’s used extremely rarely if at all and not that you can just do capriciously. Paul: One thing that’s interesting about the NPM ecosystem, and the Node ecosystem in general, is they’ve had a bunch of things like this. Things that are security related or that are drama related and people have repeatedly come out and said, “Node.js is a tar pit” or “ghetto” or whatever it is that people use to describe poor ecosystems. That Node programmers don’t know how to code and so on and so on. What it looks to me like is each of incidents brings the Node ecosystem quite a bit forward to the points that… Node is relatively new. It hasn’t had 15 years before prime time in the way that Ruby or Python did or 20 years before it got big and it’s a real bottom-up thing. Someone built it and there were some stewards and then someone else took over and then NPM took over. It’s this sort of weird language from an ecosystem perspective and it didn’t have the same advantages that Java had or that C or C++ had in order to get to maturity. Each of these incidents propels it closer to maturity. Edith: Yeah. I compare it somewhat to when electricity first started coming out. You where just working through all all issues that could happen. For example, a power line went down or a transformer blew. You work through: "Okay, what are our points of failure. Let’s not make that a point of failure again." Paul: NPM changed their policies on the namespaces, right? Edith: Yep. Now you can’t have an individual contributor being able to unpublish even if they originally published. Now you have to contact them and it’s much more stringent. Paul: Gotcha. Their response, despite people… Well, people were annoyed at their response. Edith: It seems perfectly rational to me. Paul: I think it seems perfectly rational, and this is the thing about the Internet. There’s always some set of people who are annoyed at everything you do. Edith: The Internet if full of billions of people. There’s got to be some sort of standard deviation or otherwise it would be a very boring Internet. Paul: Right, and this is why there’s always haters on hacker news. No matter what you do, if you do it one way there’ll be one group of haters. If you do it the other way there’ll be a different group of haters. With left-pad there was people who were annoyed that NPM retroactively decided that they had ownership over their namespace which previously they had sort of gifted to people in the community, the first people to take the namespace. Edith: You mean the original thing about K-I-K? Paul: There’s that, but also the left-pad. They took away the sort of autonomy of the left-pad author. Edith: I read a good article that basically says part of open source is, if it truly is open source do you maintain the rights to it or is it a community project? Paul: The traditional way of deciding that sort of ownership was the fork. Edith: Yeah. Paul: You could go and you could fork. When you forked your weren’t necessarily entitled to the same name, you weren’t entitled the same trademarks. When Debian forked Firefox, they called it Ice Weasel. When Jenkins was forked, or Hudson was forked it became Jenkins. Even Emacs has had multiple forks and GCC got forked. They all got new names, but what was the fork here it wasn’t even a fork. It was a republish of the same thing, the same software, in a namespace that the original author didn’t control. Typically, you own the URL, if you have a software library you own the URL. They did own, in some sense, the URL within NPM or the name within NPM space and NPM, the sort of owners of that namespace, overwrote it. Edith: I think they did what was necessary for good order. Paul: Sure. I completely agree. I think that was that was a good decision. Edith: I mean, to take this to a logical conclusion, what if you had a module named left-pad and you decided that, like as a prank, you were going to rewrite it to be right-pad. Sure, that’s… Is that within your rights? Kind of, but it’s a real jerk thing to do that you probably want to prevent. Paul: This is kind of one of the dangers of the whole ecosystem around centralized package managers of, sort of trusted package managers. Edith: Yeah. Paul: Where there’s no actual trust involved. What I mean by that is what is published does not have any gatekeepers. Edith: Yeah, exactly. Paul:, what major number means, what a patch means, of what a patch even means. There’s some sort of like general community guidelines in semantic versioning, but there’s no enforcement of that. Edith: Yeah, and I mean this basically does back to the whole Cathedral versus Bazaar. Paul: It’s very Bazaar. Edith: Well, bizarre and Bazaar. Paul: Intentionally so. It’s the thing that allows a community to grow. Is there a point at which Open-source communities need to like, batten down the hatches to prevent that sort of behavior or to prevent that sort of risk? Edith: It’s really interesting. I think this goes back to something we talked about with Nadia and Sean a couple episodes ago about when you buy from a corporation you have some sort of guarantee of standards that they publish somewhere that, “This is our guarantees”, versus with Open-source you don’t normally have those same sort of guarantees. Paul: Even when you do it tends to be a… Edith: There’s no enforcement mechanism. Paul: Right. There’s no enforcement mechanism in the Bazaar. Edith: There’s no… Like, so with a company. If a company has said, “Okay, we’re going to release twice a year and it’s going to have this level of quality and they break that. You can walk with your feet or your money. Paul: Right. Edith: If an Open-source project stops or does something you don’t like there’s very little enforcement. Paul: Theoretically, you could walk. You could fork the thing, but when you end up in an ecosystem that has massive network effects in the way that NPM does you can’t walk with it. Because dependencies is all transitive, the left-pad was a turtle way at the bottom of the stack. Edith: It was almost like a turtle hatchling. Paul: To fork left-pad you would have to fork the entire NPM ecosystem. Edith: It’s not even… The fork is not the issue.. Paul: You could rename it. You could pick a different library, but because of the way… I’m not sure if they still do this because I read something about it. NPM, it used to be that the version of software that your library took was the version that library got. Do you know what I mean by that? Okay. Let’s say I have a… There’s some software. Let’s call it left-pad. Edith: Let’s call it right-pad. Paul: Right-pad. Right-pad version one is being used by library A and right pad version two is being used by library B. In the Java ecosystem and many, many other ecosystems only one version of Right Pad would be used. Edith: Yeah. Paul: I believe in NPM, both versions of right-pad would be used. Library A will use version one and library B will use version two. That’s definitely the way that it used to be, I’m not sure if they’ve actually changed that. Edith: I don’t know, but that sounds very messy very quickly. Paul: Both options are terrible. Edith: Yeah. Paul: There isn’t a right way to do it. Really what it depends on… The NPM way of doing it, every library get it’s own version of the dependencies is fantastic because it lets that library do what it actually intended to do under the covers. If however, you start having an object that gets sent around, that two modules are… Let’s say receives a, I think a http packet or somebody like that would be a good example. Let’s say you take a http packet from one module, you send it to another module and they have different understandings of the shape of that object or what functions you can run on that object. Then that’s messy. Edith: Yeah, absolutely. Paul: On the other hand, if you override the version of right-pad that some other libraries using it you end up with all sorts of problems. This is a major problem in the sort of the Maven ecosystem. At CircleCI we use Closure and Closure is built on top of the Maven ecosystem and we would have bugs where the library that we used… One library that we used had a dependency and that was in the package file before another thing and so that’s the version of the packets that we used. Edith: Yeah. Paul: We would have to pick… To resolve that we have to pick the library that works and often that there isn’t a library that works for both or there isn’t a sort of sub dependency that worked for both. There’s a clusterf*ck no matter which way you do it. Edith: We run into the same issues with our SDKs because we have dependencies on other libraries that sometimes get flipped. Paul: Right. Disaster. Edith: On the other hand… I mean the bigger point I think was… There was an interesting backlash, I think, that everybody kind of projected what they wanted on the NPM thing. People said, “People don’t know how to program anymore.” Why do you even use it if they call it left-pad? Why don’t you just grind your own wheat and make your own bread from scratch and eat it at lunch also. Paul: I have no sympathy at all for this view of the world. Edith: That you should make everything from scratch? Paul: That we’ve forgotten how to program because we left-pad. Edith: The fact that we have modules available that make it easier and easier and easier to program is a good thing. Paul: I think it’s kind of different to that. I think it’s more of a curmudgeon view of the world. It’s a get off my lawn .. Edith: Wait. That you’re the curmudgeon? Paul: No, the people who complain have we forgotten how to program anymore. I think it’s a No True Scotsman kind of argument. Real programmers know how to write their own left-pad. Real programmers write in statically typed languages. Real programmers write in C. Real programmers – I’m going back in time here – Real programmers write in assembly. Real programmers hand code their… Tweak the needles on the… Edith: They do their own garbage collection. Paul: Garbage collection. What is this? Garbage collection is for amateurs coders. You can just as easily have written, “Have we forgotten how to manually allocate memory?” Edith: Or you might as well say nobody knows how to make their own transistors anymore. I mean the entire computer revolution has been that you no longer have to assemble a computer by hand. Paul: Right. Each layer of the ecosystem allows a vastly larger number of people to take part in it. I think the thing that we’re seeing now… This has been happening for five or 10 years, but what’s getting really, really big now is people who only know how to Front-End program. People who only know JavaScript, and HTML, and CSS, and they go to boot camps and they come out… Maybe have some like vague rails understanding and they call themselves coders and we the real programmers who know how to write a quick-sort and who know how to write a left pad, we don’t welcome them to our community and frankly, I have felt this in the past I’ve have since changed my mind, but it’s a very, very common perspective. Edith: I think it goes back to the medieval times. Paul: Mm-hmm. I totally see it. Edith: The entire reason why there were guilds and apprenticeships was because people didn’t want their knowledge to be cheap. Paul: Right. Edith: Like, so it used to be the reason why being a doctor takes seven years is because they wanted it to be something that only a few could do and they can then charge a lot of money. Paul: You can protect your industry to protect your own value to society. Edith: Yeah. Paul: Or just your earnings even. Edith: Your earnings. If somebody could go to boot camp and learn for six months and become an adequate coder in front-end, suddenly it’s very hard to justify charging, or getting paid, $180,000. Paul: Right. The more programmers there are in the ecosystem, the more people available to hire, the less valued your skills become. Edith: I’m certainly going to argue both sides. I think a talented programmer does have a deeper knowledge of the bubble sort, the quicksort. I think there’s a place in the world – and welcoming place to be honest – for people to do lighter coding and that there’s people with more time on the job can become more sophisticated. Paul: One of the ways that I learned to look at programmers is that there’s people who write the tools and there’s people who use the tools. Edith: Yeah, exactly. Paul: To say… I think a lot of people think, “Oh, only real programmers write the tools.” I was are susceptible to this because I worked in compilers and we wrote the tools that the tool makers wrote. Edith: Did you have a factory that made mini factories? Paul: I wish. I think what we see with people who are at the end of the chain. The people who are for harnessing the libraries in the NPM ecosystem and then the browser and that sort of thing to build really fast, really like innovative things Edith: Yeah. Paul: That frankly the tool makers would never have thought of. I don’t think that that’s looking at the world through tool makers are the real programmers and the other guys are kind of they use the tools. I think it’s not a very good way to look at the world. I think the… Everyone’s focusing on where their real value is. Edith: I think a lot of the wave of innovation that we’ve seen in the last 10 years has been because programming is a lot easier. Paul: Right, exactly. Edith: LIke the fact that there’s… You know, Uber was because you didn’t really need a lot of fancy programming when they first started out. Now they have incredibly complex programs. Just to get a basic… Paul: We’re seeing this happening in the AI revolution that’s happening at the moment. Facebook launched its platform today and I’m not sure what the platform does exactly, but now to build bots is infinitely cheaper than it was like a year ago. Building AI and connecting people to do these things is so, so much easier than it was a year ago and a million times easier than it was like 10 years ago. Edith: I remember it used to be to even get like a basic web app up, you had to have knowledge all the way up and down a stack. Paul: Right. Edith: Now, with AWS, and Heroku, and DigitalOcean you can get stuff up just much quicker and then you could focus on what’s the true business value of what you’re building instead of just it’s so hard just to get words on a page. Paul: I’ve been talking… I’m not sure if I’ve talked about it on the podcast, but certainly this is an idea that I’ve been running through awhile. In the future, people are going to build with very, very simple understanding of – or possibly no understanding – of the tools beneath them. Edith: I think that’s great. Paul: You’re going to be able to build something that’s like at the level of complexity of like a Tinder or a Snapchat with just one product manager who’s not not really a coder in the way that maybe now or maybe five years ago that we thought of a coder, but they’re going to be building applications with barely any coding knowledge at all. Edith: I think that’s great Paul: Oh yeah. Completely great. Edith: I compare it to the industrial revolution where it used to be that just getting power was a task in of itself. The reason why there were mills on streams was they had to locate them there so they could grind the wheat. Suddenly, when there was electricity, you could focus on, “Hey, not everything has to be around a river. Let’s build factories everywhere. Let’s make cool stuff.” That was the… It wasn’t just about generating power, it was, “What can we build now that we have power?” Paul: As a necessary part of this, you end up with something like left-pad. Edith: Yeah. Paul: Left-pad is a little bit trivial in that sense, but I think that one of the most entertaining parts of this thing is that left-pad had a quadratic bug in it. Accidentally, the left-pad had some form of quadratic behavior in it and no doubt it would’ve got fixed in a later version and everyone got automatically upgraded and so on. The idea that you’re coding your own version of left-pad means that you’re probably going to have quadratic behavior in it and that’s going to be used to exploit your system at some later date in the future. Edith: I totally agree with your metaphor that there’ll be less and less coding and more and more value. Paul: Right. Edith: I do think though, to argue the other side, I do think though that… I’m thinking more about what you said about the people who build the tools. Paul: Okay. Edith: I do think they need to have a different skill set then. I mean, I go back to the… Paul: You have a different set of users, you have a different set of responsibilities and they do different things and have different properties. Edith: It reminds me very much of… I love Richard Feynman I read all his books when I was growing up and he talked about how he’d learned so much from assembling and reassembling radios. Paul: Okay. Edith: Which just wasn’t something that was possible when I was a kid because we’ve gone to solid-state electronics. Paul: Oh, okay. Edith: I think we’re starting to see a similar transition in coding. Paul: That people can’t take apart their things? Edith: I think, in 20 years people will be amazed at how much access we had to different… Paul: Different components like how open the ecosystems were. That sort of thing? Edith: Yeah. Just that things that we take for granted now will become completely opaque. Paul: People are lamenting this and have been lamenting this for a long long time. One of the first comments I saw on hacker news on the Facebook messenger platform thing today is, “Whatever happened to the open ecosystems? We had IRC, do we really need to this thing?” I agree to a certain degree that the open ecosystems are… Edith: You agree to a degree? Paul: I agree that open ecosystems have some value. What I think that people often don’t get – especially in the Open-source ecosystems – is that usually the best product wins. The openness, basically no one cares. Especially now that these tools go from early adopter to like mass market in such a short period of time. Like, IRC is a fucking wasteland. All the tools around AIM and Pidgin and that sort of thing. Around the IM ecosystem are terrible. XMPP, the protocol doesn’t allow you to do anything remotely like what Facebook platform or what WeChat which is what Facebook platform is going to become. As a result, they lose. Primarily they don’t have 900 million people on them. Edith: You know, when you were talking it reminded me very much of Steve Jobs and Apple computers. Because originally the computers were the province of the hobbyists who would literally build them from hand from parts. Like Radio Shack. Paul: Yep. Edith: Then, he said, “Okay, now it’s this closed box that you can’t open. Paul: Yep. Edith: Everybody’s like, “You’re not going to sell any.” He sold gajillions. Paul: He eventually sold gajillions. If you’re in San Francisco you’ll see that there’s only Macbooks. If you see someone using a Windows computer… Edith: It’s funny because I’m looking around the podcast room and there’s six separate Apple products for three people. Paul: Right. There’s actually five computers for three people. Edith: I blame our producer Ted for the proliferation. Paul: Everyone in this ecosystem is familiar with Linux. At least all the engineers, let’s say within this ecosystem, have used Linux. Used Linux on the server, maybe they used Linux as a kid or when they were growing or at least in some way younger on a Dell. Edith: I remember when Linux was new. Paul: Well, we’ll just move on from that. What I’m saying though is it’s not like we were unfamiliar with Linux. I used Linux for many years and I eventually got sick of it. Apple products were a much, much better product and so I couldn’t dig into the, you know, deep deep down into… Well, actually didn’t do that very much on Linux anyway. Edith: Yeah. Paul: I could, theoretically, if I learned all the stuff and all the vast, vast competing bullshit goes on in the Linux development community, in the Linux desktop community. Frankly, I couldn’t use WiFi so I switched. Edith: It’s an eternal debate of product manager versus engineers except for the product manager is Stockholm Syndromed. Paul: This goes back to our discussion from a few weeks about how Open-source needs product managers? Edith: Well, no. I remember… This is when I worked for a content management system and I would go on customer visits with our architect and the architecture designed a system for architects. Paul: Of course. Edith: Where you could tweedle everything, disassemble everything on the fly, have complete control. We go out to these newspapers or hotels and they’re just like, “I just want to put a picture of a horse on page.” Like, “I do not want to twizzle all this stuff.” It was amazing because the architect, we’d go to the same meeting, we’d go back and he’s like, “Did you see how excited they were bout my configuration?” I’m like, “Marriott screamed at you.” Paul: Actual Stockholm Syndrome. Edith: I was the product manager at the time and I was just like, “No, they do not want your configuration. They want less configuration. They are tired of configuring.” Paul: There are definitely engineers who can only design for themselves, can only empathize with their own usage. Edith: Yeah. It goes back to… I mean, have you read “The Inmates are Running the Asylum”? Paul: I haven’t. Edith: It’s a really good book. It’s about, as the tin says, you know engineers designing for… They think everybody wants all this control and people just want to turn on the tap water and have water come out. Paul: Going back to the left-pad debate. A lot of the people who are screaming about the, “Have we forgotten how to code”, are basically applying their worldview to a whole bunch of people who have a different world view. Edith: Yeah. I mean, to continue on the electricity example. No, I don’t want to have to do my own electricity. I just want to flip the switch and have it come on. Paul: Right. Oh, but I want to be able to dig into my house and I want to be able to change the voltage because I might have a thing that something, something, something. Edith: I might have brought back a hairdryer from Australia and I urgently need to use it. Paul: I need one in every room so every room has to have a 110 thing and a 220 thing. Edith: That house is going to burn to the ground. Paul: Right. Exactly. And the system is built around having people’s houses not burn down to the ground. This is kind of – again back to left-pad – the NPM people have a vested interest in not letting people’s houses burned to the ground. Edith: Well, yeah. I think it’s like with anything. You don’t realize it’s an issue until it’s an issue. Paul: Right. What did they do to fix that? What was their… Edith: Like I said. They changed their policy. They said you can no longer unpublish. Paul: Okay. Edith: It’s for rare emergencies so basically a “Contact Us” instead of a button. Paul: They stood by the kik naming decision Edith: Yep. Paul: They stood by the ability to remove the kik package. Good thing the kik package wasn’t at the bottom of that turtle thing. Edith: You know, that might have been an interesting thing. I mean, what if it turned out that he kik was actually… Paul: Left-pad was kik. Edith: Yeah. It’s interesting. I actually think the Kik people were in the right. I think it was something that was very easy to confuse. Kik is a well-known brand. Paul: Right. Why was it called kik? Edith: The guy said he thought… The non-Kik guy. The programmer just said he liked the name. Paul: Oh, yeah. That happens all the time. You got a three letter thing that sounds a bit like a common word in English and that’s going to happen. Edith: He also said that he didn’t believe in copyright law. Paul: Well, seems like a very expected result of when you don’t believe in a thing that all the rest of society believes in. Edith: Yeah. Paul: Eventually, society’s going to step in and just sort of move you aside. Edith: I thought the way you handled the Uber logo was very gracious. Paul: Well, I mean, we don’t own the idea of sort of two concentric circles. Edith: What? Paul: I know, right? Theirs was a square and a circle so you might argue that it wasn’t even like our logo, but certainly when I look at it I see the Circle logo and it reminds me every time. Edith: Does it make you feel good that you could go all over the world now and see CircleCI’s logo? Paul: No, because it’s not actually CircleCI’s logo. It’s Uber’s logo. At least until they have their next top-down redesign. Edith: I think the overall thing is I think the system is still working out what it means to truly have microservices. I think that this is a good trend. Paul: Sorry. Microservices? How does this tie to microservices? Edith: Well, the left-pad was basically a microservice. Paul: Well, the left-pad was a library. Now, someone made left-pad as a service. Edith: LPaaS? Paul: Yeah. LPaaS is now category in the way that normal PaaSes are. Someone took left-pad, put it behind a REST API and published it. Humorously, not for actual money I think. I’m sure you could pay them. Edith: People pay for feature flags. Paul: I wonder what is their monetization, then. Is there a management service behind left-pad that you can control. Like, have how much padding your developers can have. You can have an audit trail of how often people pad their strings and you might want to make sure that your developers aren’t padding strings too often. Edith: I feel like you’re teasing me but I’m not completely sure. Paul: No, no, no. The general way that people turn something like this into a service is they provide a management layer behind it. I mean, feature flags is the same thing. Your product is the management layer of the feature flags, not the idea that you can write an if statement in code. Edith: Yeah, I mean that’s certainly why people are using us. A feature flag is easy, management is hard. Paul: It’s the same CircleCI. People don’t buy it in order to run a test somewhere because they have plenty machines that they could run tests on. They buy the management service, the unifying place where everyone is doing this thing, where everyone on their team is doing this thing. Back to the microservice idea. I think one of the difficult things that people have to deal with is where do you make the boundaries of your microservice. If you’re being strict on the use of the word micro, left-pad would very easily be like the level of micro that people are talking. I think that’s a little small, personally. I kind of think of it as like, “We have our billing service and then once billing gets small enough that we need to abstract it into like the PayPal service, and the Stripe service, and the invoicing service.” That’s a result of how large our architecture or our customer base is. Edith: I don’t know. I think it’s an entirely appropriate size. It reminds me of like, I get asked a lot, “What’s the appropriate level of feature flag?” My basic answer is, “Whatever you want.” You can do it with literally with every check-in. Paul: You could have a different flag for every… Do people do that? Edith: Sometimes. Paul: That’s interesting. Is that how people do their continuous deployment in the LaunchDarkly world? Edith: Then we have people who do it at a much, much higher level just for like a major infrastructure project. Paul: Gotcha. Oh, that’s interesting. As you deploy a new web server it would check the feature flag for what version that is? Is that the kind of level we’re talking about? Edith: Yeah. Paul: That’s really cool. Edith: Yeah. I think of feature flagging as a technique and I think people sometimes expect us to be more prescriptive than we are. Paul: Okay. Edith: In terms of how much… Like, what you said about microservices. How much should I feature flag? I think I give what comes across as a bit wishy-washy which is, “however much you want.” Paul: Right. Edith: I think people think they have to… At one end is the people who have wholly bought into trunk based development and they feature flag everything. Paul: Oh, okay. I guess once you can feature flag everything you buy into trunk based as opposed to branch based. Edith: Yeah. If you’re full trunk. Paul: That actually makes a lot of sense. Edith: Yeah. Paul: If you start from the start your branch is your feature flag you probably get very, very good at making sure that you don’t break shit as a result of it. You also get very good at the idea that everything goes out with a feature flag. Edith: Yeah. Paul: One of the problems that we had with feature flags, initially when he started using it, was that people would build a new feature and it would start by like eviscerating the old feature and then they’d build a new feature in it’s place and it would look perfect and then someone would say, “Oh, we should put a feature flag in this.” Well, that would take me another two days. I’d have to go back and redo all this work, put it over there, put it behind a feature flag. I see that it got very difficult to build a competency of, “We’re building this other feature on the side and then we’re going to switch to it by a feature flag. Edith: The way I think of it is you’re building a new railroad track. Paul: Right. Edith: The first way is basically… There’s this is hilarious cartoon I’ve seen of like, somebody trying to fix a railroad track while the train is moving. The feature flag way is more like, “Hey, let’s build another track.” Paul: Then we’re ready to switch to it. Edith: That reminds me of microservices. Microservice is kind of a made up term so I think everybody’s still trying to figure out, “What does that actually mean? How micro and mini are these in macro?” Paul: As far as I can tell, microservices are just services around architecture. Edith: Yeah. Paul: They’re really… Anyone who’s using microservices is largely building SOAs and microservices is the common term that people use to describe it and no one’s really that concerned with making them micro. Edith: Yeah. Well, I didn’t think SOA fell out of so much of favor. Paul: Because it got tied to things like SOAP. Software is a very fashion oriented world. Edith: It’s funny that way. Paul: It really is. Maybe everything else is. Edith: No. Terms are popular. Like, CORBA used to be the thing and now people are like, “CORBA?” Paul: CORBA is the kind of thing that you associate it with service oriented architectures. Edith: No, CORBA was before it. Paul: I kind of put them in a similar box. Edith: Under the box of old things. Paul: The box of old things that I’ve touched once or twice and happy that I’m never near them again. }}
https://dzone.com/articles/to-be-continuous-have-we-forgotten-how-to-code
CC-MAIN-2019-43
refinedweb
6,520
81.43
Stssync Protocol Last modified: October 20, 2010 Applies to: SharePoint Foundation 2010 The stssync protocol enables you to add an Events list or a Contacts list that exists on a Microsoft SharePoint Foundation site to Microsoft Outlook or to a third-party application that supports the protocol. Special character escaping: If any of the characters "&", "\", "[", "]", or "|" is part of the value of the sts-url, site-friendly-name, list-friendly-name, or list-url parameters, the character must be preceded by a "|" (pipe) character. For example, a list-friendly-name of Dan [Wilson] - Business\Personal Contacts would become Dan |[Wilson|] - Business|\Personal Contacts. The sts-url, site-friendly-name, list-friendly-name, and list-url parameters can contain Unicode characters. However, the Unicode characters must be enclosed in brackets "[ ]" and must be 4-digit hexadecimal character representations of the Unicode characters. To implement a third-party client that can use the stssync protocol to add and synchronize Events and Contacts lists that exist on a SharePoint site, you typically must implement an ActiveX control named StssyncHandler and provide support for the stssync protocol. The third-party client typically must be able to decode the URL and synchronize the Contacts or Events list on the SharePoint site. You can use the Microsoft.SharePoint namespace or the web services that are exposed by SharePoint Foundation to perform this task. You must also register the stssync protocol in the registry with the name of the executable file of your application. If you are running the Windows operating system with Windows Internet Explorer 5.0 or later, you can use the following code example. Copy the code to a .reg file, and replace <Path to exe> with the path to the executable file of the application that wants to synchronize events and contacts with SharePoint Foundation. Then double-click the .reg file to register the stssync protocol on your computer. For information about the StssyncHandler control that is installed on the client computer during Microsoft Office Setup, see StssyncHandler Control. This URL is for a list named "Evéñts" on a site named "Share|Point [Site]" with site URL and list URL. Note the use of the vertical bar to escape the "|", "[", and "]" characters, and the hexadecimal representation of the two Unicode characters in the list name.
https://msdn.microsoft.com/en-us/library/ms457051.aspx
CC-MAIN-2015-27
refinedweb
382
52.39
Introduction to using Java Persistence API in a web application in Java EE environment interface. Since in this example, RMI-IIOP is not used, technically this bean does not have to implement this interface. Never-the-less it is a good idea to make an entity bean RMI-IIOP ready, so I have done so. 2) There is no deployment descriptor needed to specify that it is an entity bean. Instead the class has been annotated as @Entity as shown below: @Entity public class UserCredential implements java.io.Serializable. The persistence provider automatically determines whether we are annotating FIELDs or PROPERTIEs. In this case, we have decided to annotate fields. 3) Every entity bean must have an identity. In our case, it is specified using @Id as below: @Id private String name; 1) One persistence.xml can be used to define multiple PUs, but in this case we have defined only one PU by name em1. 2) We need not specify any other elements/attributes, as the default values are just fine for most applications. e.g. by default the entity manager's transaction type is JTA. 3) There is no need to enumerate all the entity bean class names inside Step #3: Write. We are having to write an web.xml only because we have to define a couple of request path mappings to servlets. - Login or register to post comments - Printer-friendly version - ss141213's blog - 5119 reads
http://weblogs.java.net/blog/2005/12/04/introduction-using-java-persistence-api-web-application-java-ee-environment
crawl-003
refinedweb
240
57.06
On Fri, May 11, 2012 at 2:20 PM, Eric V. Smith <eric at trueblade.com> wrote: > The only thing I'm aware of is that I need to look at Martin's issue of > how do we gradually migrate to PEP 420 namespace packages from the > existing pkgutil and pkg_resources versions of namespace packages. I'll > do that this weekend. > FWIW, setuptools and distribute (and maybe pip) already do the right thing when installing in "single version" mode, which is usually what the distros use. They would simply need to stop also creating a .pth file (or dummy __init__.py files) when running under 3.3. They'd also need to be updated to support new-style namespace packages in their source trees. The implementation of declare_namespace() for 3.3+ would then just be to create a module object (if not present) and set its __path__ to a virtual path object based on the parent. (Sadly, this can't be backported since older Pythons require an actual list object... hmm... or do they? Maybe a list *subclass* would work.... must check into that. If it works back to 2.3 I could backport... darn, it uses PyList_Size() and PyList_Getitem(), so I'd also need a meta_path hook to trigger updates. Hm. Got to think about that some more.) The only corner case I can think of is mixing __init__ portions with non-__init__ portions. If you have both, it's not sufficient to create a simple PEP 420 virtual path, because it won't include the __init__ portions. A backport or "transition support" version needs a way to force __init__ portions to be included in the resulting virtual path. This can't be done with the current find_loader() protocol, because the finder doesn't distinguish between package and non-package cases. If find_loader() always returned a path for a package (even non-namespace packages), then this would allow virtual paths to be made either inclusive or exclusive of __init__ segments. That is, it would let there be a transition period where you could explicitly declare a namespace to get a mixed namespace, but by default the paths would be exclusive. I'm not sure if anything I just said is clear without an example, so I'll throw one in. Let's say somebody's writing code that spans multiple Python versions, and they want their __init__-based namespace packages to work, but be forward compatible with new subpackages using PEP 420 portions. Basically, they write some code that calls declare_namespace(), which then sets the module's __path__ to be an "inclusive virtual" path. This path object is similar to the current virtual path object, except that it *always* uses the second find_loader() return value, even if the first value returned is not None. Poof! Instant "transitional" namespace package, backward-compatible with older Python versions, and forward-compatible with PEP 420. Okay, technically that was more of a rationale than an example, but I hope it's a bit clearer anyway. ;-) For purposes of the PEP, all I'd request changing is asking that find_loader() always return the path of an existing directory in the second return value, even if it's also returning a loader. More precisely, if it returns a loader for a package, it should also return the package directory in the second argument. importlib can still ignore this second argument, but a transitional version of declare_namespace() can use it to implement "mixed mode" namespace packages. (Which facilitates backporting the mechanism to older setuptools as well - I'll change the nspkg.pth files to do something like 'import pep420; pep420.declare_namespace("foo")' and my pep420 module will include its own mixed-mode virtual path support, and emulate find_loader() for the builtin importers in older Pythons.) -------------- next part -------------- An HTML attachment was scrubbed... URL: <>
https://mail.python.org/pipermail/import-sig/2012-May/000626.html
CC-MAIN-2016-36
refinedweb
637
63.9
Let’s say you have the following authorization policy defined in the Configure method of your ASP.NET Core’s Startup class. .AddAuthorization(options => { options.AddPolicy("IsLucky", builder => { var random = new Random(); builder.RequireAssertion(_ => random.Next(1, 100) < 75); }); }) This policy will grant access about ¾ of the time. It is easy to apply the policy to a controller or Razor page using the Authorize attribute. [Authorize(Policy = "IsLucky")] public class SecretsModel : PageModel { // ... } But, what if you want to imperatively check the policy? For example, when building a navigation menu, you want to know if the user will be able to perform a given action or reach a specific resource before displaying links and command buttons in the UI. In this scenario, ask for an IAuthorizationService type object in any controller or Razor page. The auth service combines a claims principal and a policy name to let you know if the user authorization check succeeds. For example, in the page model for a Razor page: public class SecretsModel : PageModel { public bool IsLucky { get; set; } private readonly IAuthorizationService authorization; public SecretsModel(IAuthorizationService authorization) { this.authorization = authorization; } public async Task OnGet() { var result = await authorization.AuthorizeAsync(User, "IsLucky"); IsLucky = result.Succeeded; } } And then in the page itself: @if(Model.IsLucky) { <div>You got lucky!</div> } else { <div>No luck for you :(</div> } Of course, having an authorization policy that uses a a random number generator is weird, but I'm hoping to work it into a "random access" policy joke someday. Speaking of Pluralsight, I released an update to my C# Fundamentals course in April and I'm just now catching up with the annoucement. The course is focused on the C# language, but I decided to use .NET Core and Visual Studio Code when recording the update. Now, you can follow along on Windows using Visual Studio, but you could also follow along on Linux or macOS using any text editor. If you are looking to learn C# and some object-oriented programming techniques, I designed this course for you! I have a difficult time stating that I left London early to reach New York City in time for a pre-IPO party without laughing at the gaudiness of it all. However, that’s what I did just over one year ago. My Pluralsight story begins at a Visual Studio Live! Conference in 2007 when I met Fritz Onion in a speaker’s prep room. Fritz knew me from writing and blogging, and, eventually, our first meeting led me doing a "test teach" for Pluralsight. A "test teach" is a short tryout involving real students, but it was more than just a check on my speaking ability. I believe the "test teach" evaluated several soft attributes. Could I build a rapport with the students? Do I handle questions well? Can I socialize at lunchtime? Can I successfully arrange and coordinate travel on my own to reach the customer? It’s one thing to plan a trip to visit a tourist attraction where signs and strangers would help you along the way. Planning a trip to arrive at a nondescript office building in a generic business park of Jersey City at a very specific time requires more expertise [1]. The test teach went well, and now I'm on a plane into Newark. Over the last 10 years I've taught dozens and dozens of classes all around the world for Pluralsight. I've made over 50 video courses for Pluralsight.com. The company is ready to go public, and I've been invited to the opening bell ceremony! I’ve never been on a car ride into the city. I’ve always arrived on a plane, or underground on a train. But on this trip, I arranged for a driver to take me from Newark Airport to the W hotel in Times Square. It was my first time in a car through the Holland tunnel, and with all the traffic into the city at 7 pm, I had plenty of time to study the tunnel. The night was dark, wet, and foggy. New York had put on its Gotham city look, and I was waiting for the Batmobile to zoom past using an invisible traffic lane. The pre-IPO dinner party was at Estiatorio Milos, a Greek seafood restaurant on 55th street. Milo’s food was okay. The place had the feel of an upscale restaurant designed to extract as much coin as possible from patrons while giving those same patrons the ability to brag to everyone about eating fish flown in fresh from the Mediterranean. Form over function. The company and festive atmosphere were better than the food. I joined late but found a seat among other authors, including Joe Eames, Deborah Kurata, and John Sonmez. Although there was talk of an after-party involving an ultimate milkshake, being on UK time, I needed sleep before the big morning. Times Square in New York is an astounding place. Bright lights, tall buildings, and a mass of humanity moving through the streets. The ads are so intense they lead to sensory overload. There are animated ads for movies, which want to take your money in exchange for laughs. A four-story jewelry ad wants you to trade money for diamonds. Underwear, outerwear, phones, hotels, and banks all project images in a quest for branding and customers. There was a time when I would have dismissed the square as being too artificial. But, after reading A Splendid Exchange, I’m seeing Times Square as a primal center of trade, and a natural expression of what humans have been doing for centuries. It is the place where humans come to make exchanges. When we leave the hotel the morning of the IPO, the exchange we are looking for is the NASDAQ exchange on 4 Times Square. The NASDAQ is hard to miss thanks to the 7-story curved LED display outside. In fact, this NASDAQ location is really more of a media center than an exchange. The place has television studios inside, and rooms with hundreds of cameras where companies doing an IPO can ring the opening bell and look like they are on the trading floor surrounded by “traders” working diligently in front of computer monitors. The physical NASDAQ trading market exists only in silicon and fiber optics. I’m one of only six or so authors who’ve been invited to be present for the IPO. There is also 50 or more Pluralsight employees, board members, and investors. A few of the people I’ve known for years and grown fond of. But with Pluralsight’s rapid growth, the majority are strangers to me. Nevertheless, we are bonding together like molecules in a high-energy physics experiment. I’m barely through the security entrance when Gene Simmons walks out of a TV studiio. He saunters over to 4 of us gawkers and in a Gene voice says, "So ... what are you gentlemen here to sell today?" You’ve never felt like a true nerd until you tell Gene Simmons about your training videos covering software development. It is impossible to perform this task without sounding like the D&D dungeon master at the corner table of a comic book store. During an IPO, there are two significant moments. The first moment is the opening bell ceremony. Not every company will choose to participate in the ceremony, but I'm glad Pluralsight did. For this ceremony, everyone gathers on the stage in a circular room. In the room there are dozens of electronic displays hanging from the wall, and even more cameras. The cameras cover every possible vantage point on the stage. There’s a podium on the stage, and NASDAQ people walking around wearing headsets, carrying clipboards, and giving orders with all the authority of a television producer. In the moments leading up to the 9:30 am market opening, they are giving us pep talks and telling us the more we clap and yell, the better we'll look on TV. I'm a bit worried that if we manage to add more energy to the room, we will start a chemical reaction that lays waste to the entire building. At 9:30 am, the person at the podium (Aaron, in this case), takes a cue, pushes a button, and the bell rings. Confetti begins to fall. There’s yelling, clapping, and arm raising. I think of my parents. I wish they were still alive to see this moment. I’m one parental memory away from losing it and crying all over the stage. I can’t ever remember euphoria and sadness being mixed like this. After the opening, there is professional picture taking, both inside the building, and outside in Times Square. There's also champagne, and singing and laughing, and selfies. Lots of selfies. The next big moment on IPO day comes when the first share of stock is publicly traded. I don’t remember the precise moment when this happened, but I think it was about an hour or 90 minutes later. There’s a roar when the price of the first trade execution hits the screens. There’s hugging, handshakes, and back-slapping. More selfies, lots of selfies. And then ... dispersion. We leave the studios and head back to the hotel. Most Pluralsight employees are flying out in the afternoon to be back in Utah the same day. I’m beginning to think that if my driver can come early, I’ll get through the tunnel before rush hour hits and catch an earlier flight home. Flights between D.C. and Newark go once an hour when the schedules are working. If I can't catch an earlier flight, maybe I'll take the train. Either way, it’s not even lunchtime and I’m exhausted. In the end, I did catch an early flight. However, before I left, I had a quiet celebration with a meal worthy of a billion-dollar IPO. I had a $5 hot pastrami sandwich from a street vendor two blocks from Times Square. Function over form. [1] Years ago, a renowned training company approached me about teaching a Web API class at Microsoft. For my first class, I was given a location on the Microsoft campus and told a Microsoft employee would be there to let me in the classroom. I arrived 30 minutes early and began waiting for my Microsoft escort to arrive. With 15 minutes left before the class started, I started emailing and trying to reach people at the training company to let them know my escort wasn't arriving. The classroom was in a locked down section of the building, and I wasn't getting past the entrance without my escort. Finally, as my escort arrived 2 minutes before the class began, I entered the room in a state of panic. As I was setting up, I noticed that one of the well known instructors from the training company was sitting in the front row of the class. He was directly in front of my podium, and I heard him say, into his phone, "looks like he finally made it." I didn’t have time to think much of the statement at the time, as I only wanted to get plugged in and take a couple of deep breaths before launching into an all-day technical workshop for 70 MS engineers. Later, when I replayed the opening events in my mind, I was furious. Why didn’t someone let me know he’d be there? Why did no one respond to my calls? Why couldn’t he provide me with an escort? After that experience, I think I finished one or two more classes for this training company that we had already arranged, and then I let the relationship expire quietly. I tell this story because Pluralsight has always treated me with respect, and that's one reason I've been loyal and stuck with them. In a previous post, I suggested you think of your ASP.NET Core application as a command line tool you can use to execute application specific tasks. In an even earlier post, I suggested you keep scripts related to development checked into source control. I think you can see now how these two posts work together to make everyday development tasks automated and easy. The command line renaissance gives us a wide range of tools we can use to speed up .NET Core development. Here are some of the tools I've been using recently, in no particular order: Various dotnet global tools, including dotnet-cake, dotnet-t4, and dotnet-rimraf The Windows Subsystem for Linux, because it opens up an entire universe of standard tools, like Curl The Chocolatey package manager . There's a new episode of the CLoudSkills.fm podcast available, and the episode features yours truly! In this episode I talk with Scott Allen about building and running applications in the Azure cloud. Scott is a legendary software developer, conference speaker, trainer, and Pluralsight author. I hope you enjoy the show. There are hundreds of performance testing tools for the web. The tool I’ve been using the most for the last 10 years is a part of the web test tools in Visual Studio. Microsoft officially deprecated these tools with the 2019 release. The deprecation is not surprising given how Microsoft has not updated the tools in 10 years. While the rest of the world has moved web testing to open standards like JSON, HAR files, and interoperability with developer tools in modern browsers, the VS test tools still use ActiveX controls, and require Internet Explorer. Steve Smith recently asked VS Users what tool they plan on using in the future. In the replies, a few people mentioned a tool I’ve been experimenting with named K6. You can install K6 locally, or run K6 from a container. The documentation covers both scenarios. In addition to the docs, I’ve also been reading the Go source code for K6. I’ve had a fascination with large Go codebases recently, although I think I’m ready to try another new language now, perhaps Rust or Scala. There were a few features of the Visual Studio test tools that made the tools useful and easy. One feature was the test recorder. The test recorder was an ActiveX control that could record all the HTTP traffic leaving the browser and store the results into an XML file. The recorder made it easy to create tests because I only needed to launch IE and then work with an application as a normal user. Although XML isn’t in fashion these days, the XML format was easy to modify both manually and programmatically. The tools also offered several extensibility points you could hook with C# for pre and post modifications of each request. K6 also makes test creation an easy task. Any browser that can export a HAR (HTTP archive) file can record test input for K6, and the developer tools of all modern browsers export HAR. You can modify the JSON HAR file by hand, or programmatically. You can also use K6 to convert the HAR file into an ES2015 module full of JavaScript code. Here is what the generated code looks like. group("page_2 - ", function() { let req, res; req = [{ "method": "get", "url": "", "params": { "cookies": { ".ASPXAUTH": "73..." }, "headers": { "Host": "odetocode.com", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "...": "..." } } },{ "...": "..." }]; res = http.batch(req); sleep(0.69); }); There is an entire API available in K6 with extensibility points for cross cutting concerns. With a script in hand, you can now run load tests from k6. The above run was with a single VU – a single virtual user, but you can add more users and run k6 in a cluster, or in the cloud. In short, K6 has all the features of Visual Studio Load Tests, although with no UI tools for beginners. However, the APIs and command line are easy to use and rely on standard tools and languages. The current Azure load test offerings require either a web test from Visual Studio, or, a single URL for a simple test. Until this Azure story improves to add more sophisticated test inputs, K6 is a tool to keep in the toolbelt. Every so often I like to wander into user experience design meetings and voice my opinion. I do this partly because I want to fight the specialization sickness that hobbles our industry. I believe anyone who builds software that comes anywhere close to the user interface should know something about UX design. When it comes to UX, I follow T.S Eliot’s philosophy that good poets borrow, great poets steal. I’m not a good poet or a good UX designer, but I know what I like when I read poetry, and I know what works for me when I use software. I’ll borrow as many ideas as I can. In UX, there’s time for a hundred indecisions, and for a hundred visions and revisions, before the taking of a toast and tea. I’ve been looking specifically at navigation for platforms that compose themselves from multiple applications. Applications might not be the right word to use, but think about platforms like Office 365, Salesforce, and Google’s GSuite. These are platforms where users move between different contexts. You are reading email, then you are working in a shared document, then you are reviewing a spreadsheet, then video chatting with a coworker. All these platforms use the 9-dot app launcher icon to jump from one context to another. For example, here’s Office 365. There’s a few guiding principles we might borrow from O365 at first glance. However, look closely and you’ll see not every entry follows the guidelines. The outliers here are Calendar and People. Long time users of Outlook would know you can access your contacts and calendar without leaving Outlook, but on the web, Microsoft felt it was necessary to highlight these features of the platform from the highest-level navigation menu. The icons for People and Calendar stand out because the graphics are simple and schematic. The text for these entries stands out because the text is not a product name, but a friendly description of the feature you want to use. Anyone who has ever created content for Microsoft will know how serious Microsoft can be when it comes to product names. I can imagine a war starting inside the company when someone proposed adding People and Calendar to the menu. On one side there are members of the Office team who have promoted the Outlook brand for decades. On the other side are people fighting for the discoverability and usability of the O365 platform. Knowing Microsoft, the final decision relied on user experience testing, and I’m guessing the tests showed some non-trivial number of users couldn’t find their contacts or a calendar in the O365 UI. I think software companies tend to overestimate the brand name recognition of their software, particularly when it comes to product suites and platforms with a variety of brands inside. All the pet names are confusing. Many users don’t care to dig into the details of 5 different product offerings. I assert this fact based on anecdotal evidence, like the following thread about the game show Who Wants to be a Millionaire? That’s Microsoft. What can we borrow from Google? Again, we have the app launcher icon, and a navigation menu with icons and text. The icons are representative, simple, and contain only a touch of shading and nuance. The few brand names that jump out are Gmail, Drive, and the notorious Google+. Most of the entries consist of simple text and icon pairs that work in concert to provide clues about a feature area. For example, the @ icon for Chat suggests a text chat. The camera icon for Meeting suggests a video conference. What about LinkedIn? Once again, we see an app launcher opening a collection of icon and text pairs. However, there’s something ... uninspiring about the LinkedIn UI. The monochrome look gives a washed out appearance. There are no distinctive colors to scan for when trying to locate a familiar feature. Each entry is smaller than the entries in O365 and G Suite, and the menu appears unbalanced with the amount of white space it uses. And what are those icons? Groups and Insights are too similar, and the salary icon (an eight-sided nut laying on two sheets of paper?) is too abstract and appears out of focus - an impressive effect for a 40-pixel icon built with SVG. My criticism of the icons isn’t based solely on some inner sense of aesthetics. There is research from the Nielson Norman Group on icon usability which says icons should be simple, memorable and recognizable. There’s also the basic design heuristics that we should have users rely on recognition, not recall, and that a system should use words and phrases familiar to the user rather than system oriented terms (like abstract product names). In the end you can borrow ideas from multiple platforms and usability studies to guide the design of an app launcher that works best for your system. Just remember that schematic, recognizable icons and user-friendly text make the most effective launcher.
https://odetocode.com/blogs/all?page=3
CC-MAIN-2019-51
refinedweb
3,597
64.3
PHP vs Ruby – Let’s All Just Get Along. Conceptual differences Different languages are often compared to find out which is better, when the differences that make them up are more ideological. Sometimes one thing seems better to one group of people, when that very same thing makes the language a nightmare for other developers. With this in mind, before I get into the “bits of Ruby I like in comparison” I think explaining a few of these conceptual differences will be important. Method, Variable, Property? PHP offers different syntax to access properties, methods or variables. Ruby does not. PHP $this->turtle # Instance Property $this->bike() # Method $apple # Variable Ruby @turtle # Instance Property turtle # "Instance Property" using attr_reader: :turtle bike # Method apple # Variable Pedants will point out here that attr_reader :turtle will define a method dynamically, which is used as a getter for @turtle, making turtle and bike the same thing. A PHP developer looking at usage of turtle with no method or variable name explicitly defined will be incredibly confused about where it’s coming from. This should not be something that causes you problems too often, but it has caught me out now and then. Sometimes folks on your team might change things from an attr_reader to a full method, or vice-versa, and it might cause knock-on affects. That said, it can allow for some really flexible APIs, and let you do some cheeky things that you’re thankful for in the heat of the moment. Deleted a field, but have loads of code, and a JSON contract still expecting it to be there? class Trip def canceled_at nil end end That’ll work nicely. Anything calling trip.canceled_at is going to get a nil for this field, which is fine. We’ll remove it properly later. Type Hints vs. Duck Typing In the PHP world, type hints are a weird and wonderful thing. Languages like Golang absolutely require you to define a type for arguments, and return types. PHP added optional type hinting in 5.0 for arguments. You could require arrays, specific class names, interfaces or abstracts, and more recently callables. PHP 7.0 finally allows return type hinting, along with support for hinting int, string, float, etc. This was done with the scalar type hints RFC. This RFC was bitterly argued and debated, but it got in there, and it is still completely optional; good news for the varied user-base that is PHP. Ruby has literally none of that. Duck Typing is the way to go here, which some folks in the PHP world also maintain is a superior approach. Instead of saying: “The argument needs to be an instance of a class which implements FooInterface” and knowing that FooInterface will have a bar(int $a, array $b) method, you essentially say: “The argument can be literally anything that responds to a bar method, and if it doesn’t we can do something else.” Ruby def read_data(source) return source.read if source.respond_to?(:read) return File.read(source.to_str) if source.respond_to?(:to_str) raise ArgumentError end filename = "foo.txt" read_data(filename) #=> reads the contents of foo.txt by calling # File.read() input = File.open("foo.txt") read_data(input) #=> reads the contents of foo.txt via # the passed in file handle This is really flexible, but to some this is a code smell. Especially in a language like PHP where a int(0) or int(1) are considered valid boolean items in weak mode, taking any value and just hoping it works right can be a scary move. In the PHP world, we might just define two different methods/functions: function read_from_filename(string $filename) { $file = new SplFileObject($filename, "r"); return read_from_object($file); } function read_from_object(SplFileObject $file) { return $file->fread($file->getSize()); } $filename = "foo.txt"; read_from_filename($filename); $file = new SplFileObject($filename, "r"); read_from_object($file); That said, if we wanted to do the exact same duck typing approach in PHP, we easily could: function read_data($source) { if (method_exists($source, 'read')) { return $source->read(); } elseif (is_string($source)) { $file = new SplFileObject($source, "r")); return $file->fread($file->getSize()); } throw new InvalidArgumentException; } $filename = "foo.txt"; read_data($filename); #=> reads the contents of foo.txt by calling # SplFileObject->read(); $input = new SplFileObject("foo.txt", "r"); read_data($input); #=> reads the contents of foo.txt via # the passed in file handle You can do either in PHP. PHP doesn’t care. Pretending that Ruby is “better” because it uses duck typing would be misguided, but very common. You may prefer the approach, and PHP can do both, but basically, Ruby is lacking a feature that PHP has. Being able to do whichever you please does strike me as a bit of a win for PHP, when it is completely impossible to type hint in Ruby even if a developer wanted to. That said, there are many PHP developers who are strongly against type hints, who wished there were none at all and were upset when more were added in PHP 7.0. Interestingly, Python used to be totally lacking type hints just like Ruby. Then recently they added them. I’d be interested in knowing how many people flipped a table over that transition. Fun Features Once I’d accepted those differences, I was able to focus on the fun stuff. These are the features I started to notice myself using regularly, or least fairly often. Nested Classes Nested classes sound a little alien to PHP developers. Our classes live in namespaces, and a class and a namespace can share the same name. So, if we have a class that is only relevant to one class, we namespace it and that’s it. So, we have a class called Box, which can throw a ExplodingBoxException: namespace Acme\Foo; class Box { public function somethingBad() { throw new Box\ExplodingBoxException; } } That exception class declaration has to live somewhere. We could put it at the top of the class, but then we have two classes in one file and… well that feels a little funny to many. It also violates PSR-1, which states: This means each class is in a file by itself, and is in a namespace of at least one level: a top-level vendor name. So, it goes in its own file: namespace Acme\Foo\Box; class ExplodingBoxException {} To load that exception we have to hit the autoloader and go to the filesystem again. Doing that isn’t free! PHP 5.6 lowers the overhead for subsequent requests if the opcode cache is enabled, but it is still extra work. In Ruby, you can nest a class inside another class: module Acme module Foo class Box class ExplodingBoxError < StandardError; end def something_bad! raise ExplodingBoxError end end end end This is available to the defining class, and available outside of the class too: begin box = Acme::Foo::Box.new box.something_bad! rescue Acme::Foo::Box::ExplodingBoxError # ... end That might look a little weird, but it’s pretty cool. A class is only relevant to one class? Group them! Another example would be database migrations. Migrations are available in many popular PHP frameworks, from CodeIgniter to Laravel. Anyone who has used them often will know, if you reference a model or any other class in your migrations, then later you change that class, your old migrations will break in weird and wonderful ways. Ruby gets around this nicely with nested classes: class PopulateEmployerWithUserAccountName < ActiveRecord::Migration class User < ActiveRecord::Base belongs_to :account end class Account < ActiveRecord::Base has_many :users end def up Account.find_each do |account| account.users.update_all(employer: account.name) end end def down # Update all users whose have account id to previous state # no employer set User.where.not(account_id: nil).update_all(employer: nil) end end The nested version of the User and Account ORM models will be used instead of the global declared classes, meaning that they are more like snapshots in time of what we need them to be. This is far more useful than calling code with moving goalposts, which could change at any point. Again, this will sound mad to some people, until you’ve been bitten a few times. PHP developers often end up copying complex logic to do this, or write the SQL by hand, which is a waste of time and effort compared to just copying the relevant bits of a model over. Debugger XDebug is a wonderful piece of work. Don’t get me wrong, using breakpoints is amazing, and revolutionizes the way PHP developers debug their applications, moving beyond the “ var_dump() + refresh” debug workflow that is wildly common amongst junior developers. That said, getting XDebug to work with your IDE of choice, finding the right addon if it’s missing, getting the php.ini tweaked for the right version of PHP to enable zend_extension=xdebug.so for your CLI and web version, getting the breakpoints sent out even if you’re using Vagrant, etc., can be a massive pain in the backside. Ruby has a bit of a different approach. Much like debugging JavaScript in the browser, you can just bang the debugger keyword into your code and you’ve got a breakpoint. At the point your code executes that line – be it the $ rails server, a unit test, integration test, etc., you’ll have an instance of a REPL to interact with your code. There are a few debuggers around. One popular debugger is called pry, but another is byebug. They’re both gems, installable via Bundler by adding this to your Gemfile: group :development, :test do gem "byebug" end This is the equivalent of a dev Composer dependency, and once installed you can just call debugger if you’re using Rails. If not, you’ll need to require "byebug" first. A handy Rails guide Debugging Rails Applications, shows how things look if you shove the keyword in your application: [1, 10] in /PathTo/project/app/controllers/articles_controller.rb 3: 4: # GET /articles 5: # GET /articles.json 6: def index 7: byebug => 8: @articles = Article.find_recent 9: 10: respond_to do |format| 11: format.html # index.html.erb 12: format.json { render json: @articles } (byebug) The arrow shows the line the REPL instance is running in, and you can execute code from right there. At this point, @articles is not yet defined, but you can call Article.find_recent to see what is going on. If it errors, you can either type next to go onto the next line in the same context, or step to go into next instruction to be executed. Handy stuff, especially when you’re trying to work out why the heck some code is not giving you the output you expect. Inspect every single value until you find the culprit, try and make it work in that context, then whatever ends up being the working code can be copied and pasted into the file. Doing this in your tests is amazing. Unless A lot of people do not like unless. It is oft abused, like many features of many programming languages, and unless has been winding people up for years as this article from 2008 points out. The unless control structure is the opposite of if. Instead of executing the code block when a condition evaluates to true, it will only evaluate when the condition evaluates to false. unless foo? # bar that thing end # Or def something return false unless foo? # bar that thing end It makes things a bit easier to work out, especially when there are multiple conditions, maybe an || and some parentheses. Instead of switching it with a bang like so: if ! (foo || bar) && baz you can simply do unless (foo || bar) && baz. Now, this can get a bit much, and nobody at work would let you submit an unless with an else on it, but an unless by itself is a handy feature. When people requested this feature for PHP in 2007, it was ignored for a while until PHP creator Rasmus Lerdorf said it would be a BC break to anyone with a unless() function, and it would be . I disagreed with that, and still do. People reading unless are not going to think it is the “opposite of less” just based on the un. If that were the case, people would read the function uniqid() and think it was the opposite of iqid(). We suggested as much, and got told that we were “just being silly.” It has since been labeled wontfix. Predicate Methods There are a few cool conventions in the world of Ruby that PHP is forced to solve in other ways. One of these is predicate methods, which are methods with a boolean response type. Seeing as Ruby has no return type hints, this is a good suggestion of intent to developers using the method. Ruby has many built in, such as object.nil?. This is basically $object === nil in PHP. An include? instead of include is also a lot more clear in that it is asking a question, not executing an action. Defining your own is pretty cool: class Rider def driver? !potential_driver.nil? && vehicle.present? end end Many PHP developers will do this by prefixing the method name with is and/or has, so instead you have isDriver() and maybe hasVehicle(), but sometimes you have to use other prefixes. A method I wrote in Ruby which was can_drive? would be canDrive() in PHP, and that is not clear it is a predicate method. I’d have to rename it isAbleToDrive() or some guff to make it clear with the is/ has tradition rolling in the PHP world. Even Shorter Array Syntax In PHP, defining literal arrays is easy, and has been made much less verbose in PHP 5.4 with the addition of short array syntax: // < 5.4 $a = array('one' => 1, 'two' => 2, 'three' => 'three'); // >= 5.4 $a = ['one' => 1, 'two' => 2, 'three' => 'three']; Some would say that is still a little too verbose. In Ruby 1.9 they added a new option, to allow rockets to be replaced with semi-colons, which if done in PHP would cut this syntax down a little further: $a = ['one': 1, 'two': 2, 'three': 'three']; That is rather nice if you ask me, and when you get to nesting arrays it really saves a bit of typing when you’re doing it a few hundred times in a day. Sean Coates suggested this with an RFC back in 2011, but it never made it in. This may well not make it into PHP ever. PHP tries to be minimalist with its syntax, and is very often against adding new approaches to do old things, even if the new approach is quite a bit nicer. Basically, syntactic sugar is not a priority for PHP maintainers, whereas it seems to be almost a core goal of Ruby. Object Literals The same RFC linked above highlights a feature in Ruby that I would love to see put into PHP: object literals. In PHP, if you would like to define an StdClass with values, you have two approaches: $esQuery = new stdClass; $esQuery->query = new stdClass; $esQuery->query->term = new stdClass; $esQuery->query->term->name = 'beer'; $esQuery->size = 1; // OR $esQuery = (object) array( "query" => (object) array( "term" => (object) array( "name" => "beer" ) ), "size" => 1 ); I know this is how it’s been done in PHP forever, but it could be so much easier. The proposed syntax in the RFC matches Ruby almost exactly: PHP $esQuery = { "query" : { "term" : { "name" : "beer" } }, "size" : 1 }; Ruby esQuery = { "query" : { "term" : { "name" : "beer" } }, "size" : 1 } I would really really like this to be done, but again, it has been attempted in the past and met with little interest. Rescue a Method Instead of try/ catch in PHP, Ruby has begin/ rescue. The way they work is essentially identical, with PHP 5.6 even getting finally, to match Ruby’s ensure. PHP and Ruby can both recover from an exception anywhere, following their respective try or begin keywords, but Ruby can do something really clever: you can skip the begin method, and rescue directly from a function/method body: Ruby def create(params) do_something_complicated(params) true rescue SomeException false end If things go wrong, an error can be handled somehow instead of bubbling up and forcing the callee to handle it. Not always what you want, but it’s handy to have the option available, and without needing to indent the whole thing to wrap in a begin. In PHP this does not work, but the feature could look a little something like this if implemented: function create($params) { do_something_complicated($params); return true; } catch (SomeException $e) { return false; } While it might not be wildly important, there are a lot of nice little touches like this that make Ruby feel like it wants to help you. Exception Retries A few months ago I spotted a really handy feature that I never noticed before, the retry keyword: begin SomeModel.find_or_create_by(user: user) rescue ActiveRecord::RecordNotUnique retry end In this example, a race condition flares up because the find_or_create_by is not atomic (the ORM does a SELECT and then INSERT) which, if you’re really unlucky, can lead to a record being created by another process after the SELECT but before the INSERT. As this can only happen once you can simply instruct the begin...rescue to try it again, and it will be found with the SELECT. In other examples, you’d probably want to put some logic in place to only retry once or twice, but let’s just ignore that for a second. Focus on how annoying it would be to take one piece of the code and try it again. In Ruby you can do this: def upload_image begin obj = s3.bucket('bucket-name').object('key') obj.upload_file('/path/to/source/file') rescue AWS::S3::UploadException retry end end PHP would require you to create a new function/method just for the contents of the begin block: function upload_image($path) { $attempt = function() use ($path) { $obj = $this->s3->bucket('bucket-name')->object('key'); $obj->upload_file($path); }; try { $attempt(); } catch (AWS\S3\UploadException $e) $attempt(); } } Again, yes, you’d want to put some boilerplate into both to stop infinite loops, but the Ruby example is certainly much cleaner at retrying the code. A little birdie tells me this feature is actively being developed as an RFC which will hopefully be announced soon. It could theoretically be a PHP 7.1 feature if the process goes well. Final Thoughts Dabbling with Ruby in the past, I was mostly just writing Ruby like PHP. Working with a team of amazing and extremely experienced Ruby developers for the past year has taught me a lot of Rubyisms and practices that are a little different, and I don’t hate it. This article points out things I would miss about Ruby if I went back to working with PHP, but that wouldn’t stop me from doing it. What the PHP haters regularly ignore is the progress being made by the PHP core contributors, and whilst they might not have feature X or Y that I like from Ruby, they have done some amazing things for PHP 7 and PHP 7.1 looks full of interesting surprises. PHP has made strong plays towards consistency, with uniform variable syntax, a context-sensitive lexer, and an abstract syntax tree. All of this makes PHP as a whole more consistent, regardless of the inconsistencies in the standard library. While the standard library isn’t going to be fixed any time soon, if PHP could add a few handy features and sprinklings of syntactic sugar like the ones above, then it would be very nice indeed. Other languages can blaze off in all directions working on new theories, experimenting, making cool stuff that gets the HackerNews types happy, then the stuff that makes sense for PHP to take is eventually grabbed. I like this approach. After all, PHP is a pillaging pirate. Play with as many languages as you have time and interest in playing with. Ruby is a good start, Golang is a lot of fun and Elixir is quirky but a good challenge, but don’t feel the need to jump ship from one to the other. You can write in a few, and it keeps your brain nice and active.
https://www.sitepoint.com/php-vs-ruby-lets-all-just-get-along/
CC-MAIN-2018-05
refinedweb
3,382
61.46
Since the beginning of this course a number of you have explored integrating music and sound into your labs (there are more than three of you but there are practical limits to the number of links I can have in a paragraph and remain sane). You will be happy to learn that using processing and Firmata this is now well within your grasp! Here I’ll quickly walk through how you can get started processing sound from your computer microphone in Processing. I will then leave the integration of this and your existing Firmata code to you. To get started you’ll need a working Processing installation. Lab 4 on bCourses should have already walked you through that. With a new Processing program open navigate to Sketch => Import Library => Add Library and search for “sound” in the search box. Your results ought to look something like this: Select the one called “Sound” by “The Processing Foundation” and press the install button to install it. You can find detailed documentation about using this library in your code here. Having done that you can now import and use the library in your current Processing sketch. In the future if you want to use it in a new sketch you won’t need to add it every time and will be able to locate it directly in the Sketch => Import Library context menu. Let’s start with a small program to demo sound input management in Processing. import processing.sound.*; Amplitude amp; AudioIn in; void setup() { size(640, 360); background(255); // Create an Input stream which is routed into the Amplitude analyzer amp = new Amplitude(this); in = new AudioIn(this, 0); in.start(); amp.input(in); } void draw() { println(amp.analyze()); } This program won’t draw anything yet but it does all of the work leading up to drawing. It starts by creating an amplitude analyzer and an AudioIn object which will read information from the computer’s microphone: It then finishes its setup routine by starting to read data from the microphone and feeding that data into the amplitude analyzer: In the draw routine we just print the current amplitude of the sound the microphone is using. This value is bounded between 0 and 1 with 1 being the maximum possible reading from your mic and 0 being no incoming noise. If you can read and use this code all the work of incorporating sound input into your project is done. The only remaining task is to work out how to use the values in a project. If you’d like to take a look at a slightly more involved example of how you might use the sound input from your mic I’ve put together the following small example script (demo image above): import processing.sound.*; import java.util.LinkedList; public class BoundedQueue<E extends Number> extends LinkedList<E> { private int limit; public BoundedQueue(int limit) { this.limit = limit; } @Override public boolean add(E o) { super.add(o); while (size() > limit) { super.remove(); } return true; } public float average() { float total = 0; for (E element : this) { total += element.floatValue(); } return total / size(); } } AudioIn input; Amplitude analyzer; BoundedQueue bq; void setup() { //Set the screen size, turn off "stroke" outlines, and toggle drawing //rectangles with their center coordinates. size(640, 360); noStroke(); rectMode(CENTER); bq = new BoundedQueue(5); // Start listening to the microphone. input = new AudioIn(this, 0); input.start(); // Create an amplitude analyzer and hook it up to our mic input. analyzer = new Amplitude(this); analyzer.input(input); } void draw() { background(51); float read = analyzer.analyze(); bq.add(read); float amplitude = bq.average(); int xPos = int(amplitude * width); int yPos = int(amplitude * height); fill(255, 204); rect(xPos, height/2, yPos/2+10, yPos/2+10); fill(255, 204); int inverseX = width-xPos; int inverseY = height-yPos; rect(inverseX, height/2, (inverseY/2)+10, (inverseY/2)+10); } This builds off the mouse2D Processing example code to visualize the sound coming in on a microphone. The only tricky part here is the BoundedQueue class which assists in calculating a moving average of amplitude values and smooth out some noise on the mic. Feel free to use this as you put together your own programs :)
https://tui.negativefour.com/processing-sound.html
CC-MAIN-2022-21
refinedweb
700
52.39
Ok, so I am doing an assignment for my C++ class at a local community college. The assignment is that I have to program the series "sine(x) = (x^1/1!) - (x^3/3!) + (x^5/5!) - (x^7/7!)....". I have coded everything, but no matter what I try, the while loop in my sine function, does not want to work the way I want it to. I have to enter a precision, such as .001 so the user can see how close the program gets. Anyways, the loop never executes properly. Try and see if you can spot the problem, here is my source code.. Ok, all help will be appreciated, btw d_to_r converts degrees to radians..Ok, all help will be appreciated, btw d_to_r converts degrees to radians..Code:#include <iostream> #include <string> #include <math.h> using namespace std; const double PI = acos(-1); double d_to_r(double term) { double radians; radians = term * (PI/180); return radians; } long factorial(int x) { long product = 1; int k=0; while (k<x) { k++; product = product * k; } return product; } double power(double x, int p) { double product = 1; int k = 0; while (k<p) { k++; product = product * x; } return product; } double sine(double x, double precise) { double term = 1; int k = 1; double sum = 0; do { cout << "k: " << k << endl; cout << "term: " << term << endl; cout << "sum: " << sum << endl; term = (power(-1, k+1) * (power(x, 2*k-1)/factorial(2*k-1))); sum += term; k++; }while ((abs(term)<precise) || (k<7/*Due to factorial, after 7, it is not accurate*/)); return sum; } int main() { string conversion; //The string for the conversion question double term; //The double to hold the angle double precise; // The double to hold precision cout << "Hi, welcome to the Sine Function\n"; cout << "Please enter a angle for the Sine Function\n"; cin >> term; cout << "To what precision?\n"; cin >> precise; cout << "Is the value in degrees or radians?\n"; cout << "If the value is in degrees, type 'degrees', otherwise you\n"; cout << "may type anything else.\n"; cin >> conversion; if (conversion == "degrees") { cout << sine(d_to_r(term), precise); cout << sin(term); } else { sine(term, precise); cout << sin(term); //math.h function to compare } return 0; }
http://cboard.cprogramming.com/cplusplus-programming/42392-while-loop-problem.html
CC-MAIN-2014-35
refinedweb
367
58.32
Hi, I have no idea what's wrong, what to do, what means 'tip'. My code: class Car(object): condition = "new" def __init__(self, model, color, mpg): self.model = model self.color = color self.mpg = mpg def display_car(self, model, color, mpg): self.model = model self.color = color self.mpg = mpg print "This is a %s %s with %s MPG." %(color, model, str(mpg)) my_car = Car("DeLorean", "silver", 88) print my_car.condition print my_car.display_car("DeLorean", "silver", 88) My output is: new This is a silver DeLorean with 88 MPG. None None My error is: Oops, try again. Make sure you pass the self keyword to the display_car() method. Yea, I tried self.color, self.model and str(self.mpg) in def display_car() and same error occurs.
https://discuss.codecademy.com/t/7-problem-with-self-word/14560
CC-MAIN-2018-26
refinedweb
127
73.03
In a typical scenario of staging or production, developers seldom have the option to use the debugger so they turn to the logging functionality to resolve system issues. One of the most underutilized tools at the developer’s disposal, ideally, logs should be the first thing that developers should look at when trying to resolve a system error or spending time tracking down a gnarly bug. This blog will walk you through the Drupal module, Monolog, that logs the messages of the site (words, errors, notices, & warnings) in the file to fix issues swiftly without impacting the site performance. Find out how it can be installed and how it works. The ABC of Monolog Module In a typical scenario, a module trying to log the debug information in the database table has to connect to the database every time, making the whole process tedious. Additionally, the gradual increase in table size starts hampering the site performance. Contrary to this, another way of logging the site messages without impacting the site performance is by saving these messages in the file. Whenever the site will be down due to fatal errors, the messages can be checked from the log file. Monolog is one of the modules in Drupal that saves messages (words, errors, notices, warnings) in the file to save the system from the overhead of buffering logs and network errors. The Monolog module integrates Drupal with the Monolog library to offer a better logging solution. It can send logs to files, sockets, inboxes, databases, and various web services. In a nutshell, it allows you to define a logging pipeline. When it logs something, it dispatches it along that pipeline to whichever files, services, emails, etc. you have defined. Benefits of Monolog Module It offers the following benefits - Enhanced system performance Monolog logs system messages as per the defined file system/structure, thereby enhancing the overall performance of the application and system. - A multitude of handlers The multiple handlers defined in monolog can be integrated hassle-free to send log messages into an email, Slack, etc. - Easy to install The Monolog module is easy to install as it does not require any external library and server for configurations - Complete watchdog integration The Monolog module consists of full watchdog integration, making it easier to work with core and contributed modules out of the box. - Configurable logging levels The Monolog module is PSR-3 (PHP Standards Recommendation). As a result of which, it enables interoperability to help you change the logging library for another that implements PSR-3 without too much headache. Why is Monolog Important? Drupal core logging offers minimal features to developers for defining a log message type, “attention level,” and then saving all the log messages to a destination, usually Syslog; even when the logging can be redirected to another destination. All the log messages, including those where critical problems are listed, are stored at the same place with trivial logged information. Whenever the site encounters an unexpected issue, site owners try to find the cause behind it. Though all the information is written to the log system by Drupal, it quickly gets overwritten with newer log messages on an active site. Once it happens, it becomes difficult to recover because they all stay in the same log stream along with PHP errors and warnings and all the other types of system logs. This is why the Monolog module comes in handy. With it, you can send critical logs to email, HipChat, or NewRelic, normal logs to a persistent backend, and debug to a simple pre-defined log file. The clear separation of information by concerns extensively improves access to the specific log information that is relevant and useful in any given situation. In fact, you can use this module to write operational logs related to the content and user actions to a particular stream so the site owner can gain access to that information instantly without going through all the unnecessary or irrelevant log messages. At the same time, a system administrator can see all system logs on a different stream, and receive critical messages only via email. How to Install the Monolog Module? The monolog module can be installed by using the composer. The Monolog module does not have any configuration form in the backend, and all the configuration is done in services files. You can follow the below-mentioned steps for the same- - Create a site specific services.yml (monolog.services.yml, for example) in the same folder of your settings.php and then add this line to settings.php itself: parameters: monolog.channel_handlers: default: ['rotating_file'] monolog.processors: ['message_placeholder', 'current_user', 'request_uri', 'ip', 'referer'] services: monolog.handler.rotating_file: class: Monolog\Handler\RotatingFileHandler arguments: ['private://logs/debug.log', 10, 'monolog.level.debug'] 3. This configuration will log every message with a log level greater (or equal) than debug to a file called debug.log located into the logs folder in your private file system. Since data will be rotated every day, the maximum number of files that you can keep would be 10. Role of Handlers & Processors in Monolog’s Functionality Handlers are accountable for saving the message to the file, database, or sending it to a mail. In Drupal Monolog’s default monolog.services.yml, several handlers are defined, for instance, monolog.handler.browser_console, monolog.handler.chrome_php, monolog.handler.fire_php, etc. These are registered as services in the Drupal Service Container. You can define as many handlers as you need. Each handler has a name (that should be under the monolog.handler. namespace), an implementing class, and a list of arguments. Mapping among logger channels and Monolog handlers is done by defining parameters. Under the monolog.channel_handlers parameter, it is possible to determine where to send logs from a specific channel. The default mapping should exist as the fallback one. In the previous example, all logs were sent to the monolog.handler.rotating_file handler. Note - Only the handler name is used instead of the full-service name. The following example will send all PHP specific logs to a separate file: parameters: monolog.channel_handlers: default: ['rotating_file'] monolog.processors: ['message_placeholder', 'current_user', 'request_uri', 'ip', 'referer'] services: monolog.handler.rotating_file: class: Monolog\Handler\RotatingFileHandler arguments: ['private://logs/debug.log', 10, 'monolog.level.debug'] It method will write the corresponding message to the private://logs/php.log file. On the other hand, a processor is a PHP callable used to process the log message- Monolog can alter the messages being written to a logging facility using processors. The module provides a set of already defined processors to add information like the current user, the request URI, the client IP, and so on. Processors are defined as services under the monolog. processor. namespace. We can also use the Devel module or Drupal Console to find all of them. 'Message_placeholder': text of message 'Current_user' : logged in user 'Request_uri' : requested url 'Ip' : ip address of user ‘'Referer': url from where the user has arrived to the page. How to log custom messages in a custom module using Monolog? To log custom messages, add the below-mentioned code in your custom module- It will successfully write the corresponding message to the private://logs/debug.log file. E.g Conclusion The Monolog module offers complete flexibility to help you capture the right information and leverage it for troubleshooting and monitoring. Once you have configured your applications to log all the useful information, you can send these logs to a platform where it can be used for in-depth analysis and collaborative troubleshooting. Install the module for speedy development and resolve errors hassle-free.
https://www.srijan.net/resources/blog/fundamentals-of-drupal-monolog-module
CC-MAIN-2021-25
refinedweb
1,264
54.73
The most common requirement for a line of business application is to represent data in pages. Usually this involves showing data in a grid and showing a navigate pane with either page numbers or Next/Previous button (or both) to navigate to multiple pages. This works fine in most cases. However imagine the use case where you are representing a list or stream of data (instead of grid) like say a list of blog post summaries, where the end user is reading from top to bottom, as they go down. In such a case having pagination, kind of breaks the flow. Instead of hitting the next button, if you can load the next page of data as the user scroll down, it would be a nice user experience. Today we will see how to implement this behavior. This UI pattern is often referred to as infinite scrolling. Note: Infinite Scrolling is not a silver bullet for solving all problems related to paged data. Pick and choose your use case. In our sample scenario, we have a Web API service that returns paged list of Posts where a Post is a simple entity with Title, Text and Author. The Web Service fetches data from the repository and serves up 5 pages at a time and stops when there is no more data to fetch. Step 1: We start off with a ASP.NET MVC 4 project and pick the Basic Template for our Solution. Step 2: Next we add the Post entity in the Models folder. public class Post{public int Id { get; set; }public string Title { get; set; }public string Text { get; set; }public string Author { get; set; }} Step 3: Given our oversimplified use case, we install the MvcScaffolding package and scaffold the Data Access code (using EF) as well as the CRUD pages. PM> install-package MvcScaffolding Step 4: We add an empty WebAPI controller called PostServiceController to retrieve the data. Step 5: Then add an empty HomeController to serve up the Home Page. Step 6: Add a Home folder under Views and add an Index.cshtml that will have our Infinite Scroll view. Step 7: At this point we run the Application and use the Posts controller and CRUD screens to add some data to the Posts. Note: If you get a jQuery not found error, remove the two script references on top of the Create.cshtml and Edit.cshtml and add the following at the bottom of the page. @section scripts{ @Scripts.Render(@"~/Scripts/jqueryval"); } After we’ve added about 15 posts full of Lorem Ipsum, we end up with an Index page that looks similar to the following Well, we have our test data now, so let’s see what it takes to implement the infinite scroll pattern Step 8: We add an infiniteScroll.js in the Scripts folder. In this script, we’ll do the following: 1. Declare a view model with two properties to store all the posts that were loaded and the current page that was last loaded. var viewModel = { posts: ko.observableArray(), currentPage: ko.observable(-1)}; 2. In document ready event, we do the following a. Invoke KO data binding to bind the view model, b. Call the Web API service and retrieve data for first page. c. Attach an event handler for the Window Scroll event and if the scroll position has reached the bottom, call the Web API for the next page of data. $(document).ready(function (){ ko.applyBindings(viewModel); getData(viewModel.currentPage() + 1); $(window).scroll(function (evt) { evt.preventDefault(); if ($(window).scrollTop() >= $(document).height() - $(window).height()) { console.log("Scroll Postion" + $(window).scrollTop()); getData(viewModel.currentPage() + 1); } });}); 3. In the getData method that retrieves the data from the Web API, we do the following: a. Check if the requested page number is not the current page number (so as to not load the same page of data twice). I had to add this condition because some browsers fire the scroll event again after Knockout does data binding with new data. This results in duplicate calls and completely messed up data list. b. Next we do an Ajax post to the PostService Web API that we added earlier. We’ll see the details of the API in a bit. c. Once the call is done, we increment the current page count. This is important because we don’t want to increment page numbers unless data is returned. No data returned implies we’ve reached the bottom d. Finally we add the data item returned into the view model which updates the UI thanks to KO binding. function getData(pageNumber){ if (viewModel.currentPage() != pageNumber) { console.log("Scroll Postion begin getData" + $(window).scrollTop()); $.ajax({ url: "/api/PostService", type: "get", contentType: "application/json", data: { id: pageNumber } }).done(function (data) { if (data.length > 0) { viewModel.currentPage(viewModel.currentPage() + 1); for (i = 0; i < data.length; i++) { viewModel.posts.push(data[i]); console.log("Scroll Postion looping ViewModel" + $(window).scrollTop()); } } }); }} Step 9: Now that we are done with fetching data on the client, let’s see the WebAPI implementation. [HttpGet]public IEnumerable<Post> GetPosts(int id){ IEnumerable<Post> posts = _repository.Page(id, 5); return posts;} The GetPosts method simply calls the PostPage method on the repository. But if you have been following along, you’ll see no PostPage method was created in the Repository. Correct, I could have done the paging in the service itself, but decided to update the Repository interface to provide us a mechanism to get Paged data for the Posts DBSet. The interface is as follows IQueryable<Post> PostPage(int pageNumber, int pageSize); The implementation is as follows public IQueryable<Post> PostPage(int pageNumber, int pageSize){ return context.Posts.OrderBy(f => f.Id).Skip(pageSize * pageNumber).Take(pageSize);} We simply use the Skip and Take functions to page through data. As seen in Service call, the page size is set to 5 and pageNumber is determined as we scroll through data. Step 10: With the data fetching complete, all we have to do now is complete the Home\Index.cshtml so that our Home page has a neatly formatted, infinite scrolling View. The markup is rather simple as you can see below: @{ ViewBag.Title = "Posts";} <h2 style="text-align:center">Posts</h2><section data-<div style="width: 25%; height: auto; float: left; text-align: right; padding: 55px 20px 0px 0px"> <h3> <label data-</label> </h3></div><div style="width: 60%; height: auto; float: left"> <h1> <label data-</label> </h1> <label data-</label></div></section> @section Scripts{<script src="~/Scripts/knockout-2.2.0.debug.js"></script><script src="~/Scripts/infiniteScroll.js"></script>} We have used the foreach binding to bind the views property of the ViewModel. Inside the section, we have multiple divs to layout the Author, Title and Text. At the bottom we have the reference to KO and infiniteScroll.js. That’s it we are all done and it’s demo time. Run the application and the home page will come up with 5 posts Now scroll down and you’ll see more posts get added as you reach the bottom. You’ll notice the scrollbar goes up indicating more data is available and when you scroll down further, it shows the newly loaded data. Awesome! One caveat worth mentioning is, make sure your first page of data introduces a scroll bar. If your first page of data doesn’t introduce a scrollbar then the scroll event doesn’t fire as there is nothing to scroll and the subsequent pages will not be loaded. The infinite scroll pattern is simply a different kind of pagination. Use it judiciously and where appropriate. I believe it’s appropriate for streams of data rather than a fixed set of say 100 records broken up into 10 pages. For smaller fixed sets of data it’s still okay to have pagination. Whatever your use case, now you have a new pagination technique in your arsenal! Enjoy!
http://www.dotnetcurry.com/aspnet/911/infinite-scroll-aspnet-webapi-knockoutjs
CC-MAIN-2017-34
refinedweb
1,322
65.22
Do know that IEnumerable and IQueryable serve to be helpful for data manipulation in LINQ. The data manipulation in this context refers to databases and collections. The main difference between the two terms is that IEnumerable gets inherited by Iqueryable. Therefore, IQueryable possesses all features of IEnumerable along with its own. Significantly important when it comes to data manipulation and query data, both iqueryable and ienumerable boost LINQ Query performance in more ways than one. Here, we aim to throw light on the difference between IEnumerable and iqueryable, their features, and advantages. Though both these terms appear alike and are quite similar for coding purposes, they are different in many ways. Along with helping you understand the usability scenarios for which they are recommended, this article will also explain the difference between IEnumerable and iqueryable in the easiest of ways. So, are you ready to know more about IEnumerable vs. iqueryable? Read on. IEnumerable vs. IQueryable IEnumerable IEnumerable is most suited for iterating through collections. IEnumerable is an interface that defines the unique method of GetEnumerator. This method returns an IEnumerator interface of the desired type. The IEnumerator interface allows ‘read-only’ access to collections and allows iteration among the class with the help of a for each loop. After that, the collection that implements the IEnumerable method can be utilized for the coding for-each statements. In c#, IEnumerable forms the abstract aggregate with IEnumerator being the abstract Iterator. IEnumerable is implemented by collections such as Lists. In simple words, Ienumerator relates to an iteration over non-generic collections. It forms the base interface for enumerators. Do note that enumerators can only be used to modify data in any collection. They cannot be used to read the data in a collection. In other words, IEnumerable serves as the abstract aggregate, while IEnumerator happens to be the abstract Iterator. IEnumerable Code class MyArrayList : IEnumerable { object[] stech_Item = null; int Index = 0; public MyArrayList() { // For the sake of simplicity lets keep them as arrays // ideally it should be link list stech_Item = new object[100]; } public void Add(object item) { // Let us only worry about adding the item stech_Item[Index] = item; Index++; } // IEnumerable Member public IEnumerator GetEnumerator() { foreach (object o in stech_Item) { // Lets check for end of list (its bad code since we used arrays) if(o == null) { break; } // Return the current element and then on next function call // resume from next element rather than starting all over again; yield return o; } } } Features of IEnumerable - IEnumerable exists in the form of a System. Collections Namespace. - IEnumerable is capable of moving forward over a collection only. It cannot transfer between the items or backward. - IEnumerable is beneficial for querying data from Lists, Arrays, and other memory collections. - While querying data from databases, IEnumerable helps execute select query on the server-side; it loads data in-memory on the client side; and then filters the data. - IEnumerable helps LINQ handle XML queries. - IEnumerable supports the feature of deferred execution. - IEnumerable fails to support custom query or lazy loading; thus, it cannot be used effectively for paging like scenarios. - IEnumerable supports extension methods for making functional objects. IQueryable IQueryable and IEnumerable are both interfaces that permit the manipulation as well as the query collection of data. As IEnumerable inherits Iqueryable, IQueryable adds its features to IEnumerable interfaces to help manipulate and query the collections of data. As IQueryable inherits IEnumerable, it effectively means that IQueryable bestows its features to the IEnumerable interface. Whenever developers have to deal with massive data containing many records, IQueryable showcases a high performance by filtering data before forwarding the filtered data to clients. IQueryable Code using System; using System.Collections.Generic; using System.Linq; class stech_main { static void Main() { // List and array can be converted to IQueryable. List<int> list = new List<int>(); list.Add(0); list.Add(1); int[] array = new int[2]; array[0] = 0; array[1] = 1; // We can use IQueryable to treat collections with one type. Stechies(list.AsQueryable()); Stechies(array.AsQueryable()); } static void Stechies(IQueryable<int> items) { Console.WriteLine($"Sum: {items.Sum()}"); Console.WriteLine($"Average: {items.Average()}"); } } Features of IQuerytable - IQueryable exists in the System.Linq Namespace. - IQueryable moves in the forward direction in a collection only; it is incapable of moving backward or between the items. - IQueryable is most useful for querying data from the out-memory collections such as remote database, service, etc. - In the course of querying data from databases, it is found that IQueryable is capable of executing the select query on the server side equipped with all filters. - IQueryable is quite suitable for LINQ when it comes to handling SQL queries. - IQueryable is supportive of deferred execution. - IQueryable supports the handling of a custom query with the help of methods like CreateQuery and Execute. - IQueryable supports lazy loading and can be utilized for paging like scenarios. - Iqueryable supports extension methods. Key differences between iqueryable and IEnumerable in points - The main difference existing between “IEnumerable” and “IQueryable” may be related to the location wherein the filter logic is executed. While the former is executed on the client-side in memory locations, the latter is executable on databases. - IEnumerable can be found in the System. Collections namespace while IQueryable dominates the System.Linq Namespace. - IEnumerable is best utilized for querying data from the in-memory collections of the likes of Lists, Arrays, and so forth. On the other hand, IQueryable is used for querying data from remote databases, services, and other out-memory collections. - In the process of querying data from databases, IEnumerable runs the "select query" that’s present on the server-side; it loads the data in-memory fitfully on the client-side; and then proceeds to filter the data. Conversely, IQueryable executes the "select query" with all filters on the server-side. - IEnumerable is useful for handling the LINQ to Object as well as LINQ to XML queries. IQueryable helps manage LINQ to SQL queries. - IEnumerable is slower in terms of its processing speed because, in the course of selecting data from databases, it is known to execute the select query on the server-side, load the data in-memory effectively on the client-side and then go about the process of filtering data. This does not apply to IQuerytable. - IEnumerable is preferable mainly for small data manipulations, while IQueryable is useful for performing big-sized data manipulation tasks. - IEnumerable<T> showcases a forward-only cursor belonging to T. .NET 3.5 added methods. These extension methods are included in the LINQ standard operators for queries like Where and First. They are compatible with those operators that need anonymous functions or functions taking Func<T>. On the other hand, IQueryable<T> implements the similar LINQ standard operator for running a query. However, it accepts the Expression<Func<T>> for anonymous functions and predicates. The Expression<T> serves to be a compiled expression tree. It functions as a broken-up version on the method that is capable of being parsed by the query table's provider and can be used accordingly. - If you are creating an Iqueryable, the same can be converted to SQL and executed on database servers. In the case of creating an IEnumerable, all rows are pulled into the memory location in the form of objects before the query is run. In these methods, in case ToArray () or ToList () is not called, then the query will be run every time it is used. - The extension methods related to IQueryable are known to take expression objects rather than Func objects. This effectively means that the delegate received by IQueryable is in the form of an expression tree rather than that of a method that has to be invoked. - IEnumerable enumerates all its elements at all times, even as IEqueryable is known to enumerate the elements or perform on the things that are based on a specific query. The query happens to be an Expression or a data representation of the .Net code) that has to be explored, interpreted, compiled, etc. by the IQueryProvider for generating good results. Conclusion In this article dedicated to iqueryable and IEnumerable, we have tried explaining the difference between IEnumerable and Iqueryable in the form of a comparison chart as well as through points. A closer look at the features and difference of IEnumerable and iqueryable is likely to enhance your LINQ query performance. We want to receive your valuable feedback on our attempt at explaining the various aspects of IEnumerable and iqueryable methods. We look forward to hearing from you for your views on the difference between IEnumerable and iqueryable in c# with an example – do send us your feedback, questions, and comments in the section below.
https://www.stechies.com/difference-between-ienumerable-iqueryable/
CC-MAIN-2020-50
refinedweb
1,443
54.52
Given a program on fork() system call. #include <stdio.h> #include <unistd.h> int main() { fork(); fork() && fork() || fork(); fork(); printf("forked\n"); return 0; } How many processes will be spawned after executing the above program? A fork() system call spawn processes as leaves of growing binary tree. If we call fork() twice, it will spawn 22 = 4 processes. All these 4 processes forms the leaf children of binary tree. In general if we are level l, and fork() called unconditionally, we will have 2l processes at level (l+1). It is equivalent to number of maximum child nodes in a binary tree at level (l+1). As another example, assume that we have invoked fork() call 3 times unconditionally. We can represent the spawned process using a full binary tree with 3 levels. At level 3, we will have 23 = 8 child nodes, which corresponds to number of processes running. A note on C/C++ logical operators: The logical operator && has more precedence than ||, and have left to right associativity. After executing left operand, the final result will be estimated and execution of right operand depends on outcome of left operand as well as type of operation. In case of AND (&&), after evaluation of left operand, right operand will be evaluated only if left operand evaluates to non-zero. In case of OR (||), after evaluation of left operand, right operand will be evaluated only if left operand evaluates to zero. Return value of fork(): The man pages of fork() cites the following excerpt on return value, “On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately.” A PID is like handle of process and represented as unsigned int. We can conclude, the fork() will return a non-zero in parent and zero in child. Let us analyse the program. For easy notation, label each fork() as shown below, #include <stdio.h> int main() { fork(); /* A */ ( fork() /* B */ && fork() /* C */ ) || /* B and C are grouped according to precedence */ fork(); /* D */ fork(); /* E */ printf("forked\n"); return 0; } The following diagram provides pictorial representation of fork-ing new processes. All newly created processes are propagated on right side of tree, and parents are propagated on left side of tree, in consecutive levels. The first two fork() calls are called unconditionally. At level 0, we have only main process. The main (m in diagram) will create child C1 and both will continue execution. The children are numbered in increasing order of their creation. At level 1, we have m and C1 running, and ready to execute fork() – B. (Note that B, C and D named as operands of && and || operators). The initial expression B will be executed in every children and parent process running at this level. At level 2, due to fork() – B executed by m and C1, we have m and C1 as parents and, C2 and C3 as children. The return value of fork() – B is non-zero in parent, and zero in child. Since the first operator is &&, because of zero return value, the children C2 and C3 will not execute next expression (fork()- C). Parents processes m and C1 will continue with fork() – C. The children C2 and C3 will directly execute fork() – D, to evaluate value of logical OR operation. At level 3, we have m, C1, C2, C3 as running processes and C4, C5 as children. The expression is now simplified to ((B && C) || D), and at this point the value of (B && C) is obvious. In parents it is non-zero and in children it is zero. Hence, the parents aware of outcome of overall B && C || D, will skip execution of fork() – D. Since, in the children (B && C) evaluated to zero, they will execute fork() – D. We should note that children C2 and C3 created at level 2, will also run fork() – D as mentioned above. At level 4, we will have m, C1, C2, C3, C4, C5 as running processes and C6, C7, C8 and C9 as child processes. All these processes unconditionally execute fork() – E, and spawns one child. At level 5, we will have 20 processes running. The program (on Ubuntu Maverick, GCC 4.4.5) printed “forked” 20 times. Once by root parent (main) and rest by children. Overall there will be 19 processes spawned. A note on order of evaluation: The evaluation order of expressions in binary operators is unspecified. For details read the post Evaluation order of operands. However, the logical operators are an exception. They are guaranteed to evaluate from left to right. Contributed by Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
http://www.geeksforgeeks.org/fork-and-binary-tree/
CC-MAIN-2015-35
refinedweb
809
65.01
- NAME - VERSION - SYNOPSIS - DESCRIPTION - ATTRIBUTES - METHODS - AUTHOR NAME Meerkat::Collection - Associate a class, database and MongoDB collection VERSION version 0.015 SYNOPSIS use Meerkat; my $meerkat = Meerkat->new( model_namespace => "My::Model", database_name => "test" ); my $person = $meerkat->collection("Person"); # My::Model::Person # create an object and insert it into the MongoDB collection my $obj = $person->create( name => 'John' ); # find a single object my $copy = $person->find_one( { name => 'John' } ); # get a Meerkat::Cursor for multiple objects my $cursor = $person->find( { tag => 'hot' } ); DESCRIPTION A Meerkat::Collection holds an association between your model class and a collection in the database. This class does all the real work of creating, searching, updating, or deleting from the underlying MongoDB collection. If you use the Meerkat::Collection object to run a query that could have multiple results, it returns a Meerkat::Cursor object that wraps the MongoDB::Cursor and inflates results into objects from your model. ATTRIBUTES meerkat (required) The Meerkat object that constructed the object. It holds the MongoDB collections used to access the database. class (required) The class name to associate with documents. The class is loaded for you if needed. collection_name The collection name to associate with the class. Defaults to the name of the class with "::" replaced with "_". METHODS create my $obj = $person->create( name => 'John' ); Creates an object of the class associated with the Meerkat::Collection and inserts it into the associated collection in the database. Returns the object on success or throws an error on failure. Any arguments given are passed directly to the associated class constructor. Arguments may be given either as a list or as a hash reference. count my $count = $person->count; my $count = $person->count( $query ); Returns the number of documents in the associated collection or throws an error on failure. If a hash reference is provided, it is passed as a query parameter to the MongoDB count method. find_id my $obj = $person->find_id( $id ); Finds a document with the given _id and returns it as an object of the associated class. Returns undef if the _id is not found or throws an error if one occurs. This is a shorthand for the same query via find_one: $person->find_one( { _id => $id } ); However, find_id can take either a scalar _id or a MongoDB::OID object as an argument. find_one my $obj = $person->find_one( { name => "Larry Wall" } ); Finds the first document matching a query parameter hash reference and returns it as an object of the associated class. Returns undef if the _id is not found or throws an error if one occurs. find my $cursor = $person->find( { tag => "trendy" } ); my @objs = $cursor->all; Executes a query against collection_name. It returns a Meerkat::Cursor or throws an error on failure. If a hash reference is provided, it is passed as a query parameter to the MongoDB find method, otherwise all documents are returned. Iterating the cursor will return objects of the associated class. ensure_indexes $person->ensure_indexes; Ensures an index is constructed for index returned by the _index method of the associated class. Returns true on success or throws an error if one occurs. See Meerkat::Role::Document for more. AUTHOR David Golden <dagolden@cpan.org> This software is Copyright (c) 2013 by David Golden. This is free software, licensed under: The Apache License, Version 2.0, January 2004
http://web-stage.metacpan.org/pod/Meerkat::Collection
CC-MAIN-2019-43
refinedweb
550
55.03
Raspberry Pi Cluster Node – 13 Abstracting Slave Code This post builds on my previous posts in the Raspberry Pi Cluster series by abstracting the slave code so it is ready for more complex slaves. Why I am abstracting the Slave code As the system becomes more complex there will be a number of slaves performing different tasks. Currently our basic slave reports a heartbeat to let the master know its still alive. When it joins the cluster it sends over data about the node. Once this has been sent it then receives cluster information about the master. Finally, the slave will begin repeatedly sending heartbeat data. For all slaves we want to ensure that they follow this standard pattern. All of the reconnection code, and sending of the node details needs to be uniform across all slaves. To do this I am going to abstract the code that performs this into a single class. The only difference between the slaves will be what it does once it has connected to the master. For the basic slave we will continue to send the heartbeat, but for the more complex slaves they will perform additional steps. In addition to this I am planning to run the connection code in a separate thread. This will mean that while each slave is communicating with the master it is able to perform other tasks. Abstracting the Slave code Changing the slave code to use a thread will work similar to how we handle each slave connecting to the master. A class is created whose parent is threading.Thread and when used it is created and then started in a new thread. In this case we are going to call it the RpiBasicSlaveThread class. class RpiBasicSlaveThread(threading.Thread): def __init__(self, master_ip, socket_port): threading.Thread.__init__(self) self.client_number = random.randint(1, 100000) self.server_address = (master_ip, socket_port) self.sock = None In the init this takes the master ip, and the socket port which will be used to create the socket connection. In addition to this, a random client number is generated to use used as means of identification. As in previous code, the client number could conflict with another slave, so going forward this will be improved to ensure no client has the same ID. Here the run() method is called once the thread has been started after calling start(). def run(self): logger.info("Starting script...") while True: logger.info("Connecting to the master...") connected = False while connected is False: try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect(self.server_address) connected = True except socket.error as e: logger.info("Failed to connect to master, waiting 60 seconds and trying again") time.sleep(60) logger.info("Successfully connected to the master") try: logger.info("Sending an initial hello to master") send_message(self.sock, create_payload(get_base_machine_info(), 'computer_details')) send_message(self.sock, create_payload("computer_details", "info")) message = get_message(self.sock) logger.info("We have information about the master " + json.dumps(message['payload'])) while True: self.perform_action() except DisconnectionException as e: logger.info("Got disconnection exception with message: " + e.message) logger.info("Slave will try and reconnect once master is back online") This run method is primarily the contents of the original basic slave script. Here it will attempt to connect to the master until it suceeds. This also has disconnection code handling an automatic reconnect if the master is offline for a period of time. The one change that has been made here is to instead of perform the heartbeat code, it calls self.perform_action(). def perform_action(self): logger.info("Now sending a keepalive to the master") send_message(self.sock, create_payload("I am still alive, client: {num}".format(num=self.client_number))) time.sleep(5) Here this method performs the basic heartbeat we had in the basic slave script. However since this is a method it can easily be overwritten from a child class. Going forward new slaves will be a subclass of this class and override this perform_action() method. This means that all the slaves will have the same connection code and the handling for disconnection. The benefit of this is that as we improve the connection handling code, all slaves will benefit from this code. Reviewing the basic_slave.py script Now after the majority of this code has been abstracted the basic_slave script is now significantly shorter. config = ConfigParser.ConfigParser() config.read(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'rpicluster.cfg')) socket_port = config.getint("slave", "socket_port") master_ip = config.get("slave", "master_ip") add_file_logger("slave.log") basic_slave_thread = RpiBasicSlaveThread(master_ip, socket_port) basic_slave_thread.start() The main change now involves creating the RpiBasicSlaveThread object, and then starting it running in a new thread with start(). The rest of the logic that was previously here is now handled now lives in the newly created class. Summary of changes Here we have moved the majority of the slave code into a new class. This has been refactored slightly so that we may start to implement new slaves. The full code is available on Github, any comments or questions can be raised there as issues or posted below.
https://chewett.co.uk/blog/2090/raspberry-pi-cluster-node-13-abstracting-slave-code/
CC-MAIN-2020-40
refinedweb
848
59.09
Second try solution in Clear category for The Hidden Word by golosinas def checkio(text, word): """Takes a multiline string in the form of a rhyme and a single secret word as arguments. Removes the whitespaces and finds the secret word inside the rhyme in the horizontal (from left to right) or vertical (from up to down) lines. If the word is found returns the coordinates in a list, as follows: [row_start,column_start,row_end,column_end], where: row_start = line number for the first letter of the word. column_start = column number for the first letter of the word. row_end = line number for the last letter of the word. column_end = column number for the last letter of the word. Counting of the rows and columns start from 1. Input: Two arguments. A rhyme text as a string and a word as a string (lowercase). Output: The coordinates of the word. """ from itertools import zip_longest # Removes spaces, converts to lower case and split text into a list of strings (lines) lines = text.replace(" ", "").lower().splitlines() # Searches horizontally for i in range(len(lines)): if lines[i].find(word) == -1: pass else: return [i + 1, lines[i].find(word) + 1, i + 1, lines[i].find(word) + len(word)] # If not found searches vertically column = 1 # transpose text, fill missing indexes for chars in zip_longest(*lines, fillvalue="*"): if word in "".join(chars): return ["".join(chars).index(word) + 1, column, "".join(chars).index(word) + len(word), column] else: column +=] print("Coding complete? Click 'Check' to earn cool rewards!") Sept. 20, 2020 Forum Price Global Activity ClassRoom Manager Leaderboard Coding games Python programming for beginners
https://py.checkio.org/mission/hidden-word/publications/golosinas/python-3/second-try/share/8b06dc3994d3de091e09941cfa9c98d0/
CC-MAIN-2021-21
refinedweb
267
67.15
encode() method encode() method encodes a String of letters. It receives two arguments, one is a String of letters that is to be encode and second argument is codes of type String[] contains the code strings (binary digits) for the symbols (space at position 0, a at position 1, b at position 2, etc). Code as follows: Program Code: public class HuffmanTree implements Serializable { /** * Method to encode a message that is input as a string * of * letters that is passed as its first argument, second argument * codes of type String[]. * @param stringMessage The input message as a String of letters * @param codes The String[] array contains the code strings(binary digits) * for the symbols (space at position 0, a at position 1, b at position 2, etc). * @return The encoded message as a String */ public String encode(String stringMessage, String[] codes) { // Creates an object of type StringBuilder to store the encoded string. StringBuilder result = new StringBuilder(); // Repeats the loop until it reaches the end of the string. for (int i = 0; i < stringMessage.length(); i++) { // Store the character at position i to ch. char ch = stringMessage.charAt(i); If ch is space, adds space value to result that is codes[0] append to result. Otherwise it converts ch to upper case, subtracts from value of ‘A’ and adds 1 to it finally the value is stored in index variable. This is necessary because we need to find the index of the character ch. // If ch is space, adds space value to result // else adds particular ch value to result. if( ch == ' ') { result.append(codes[0]); } else { int index = Character.toUpperCase(ch) - 'A' + 1; result.append(codes[index]); } } Finally it returns result string. // Returns the final string. return result.toString(); } }
http://www.chegg.com/homework-help/data-structures-abstraction-and-design-using-java-2nd-edition-chapter-6.6-solutions-9780470128701
CC-MAIN-2015-32
refinedweb
289
64.51
Open Source WS Stacks for Java - Design Goals and Philosophy .jpg) - | - - - - - - Read later My Reading List Introduction In addition to the options offered by commercial vendors, there are a number of open source Java frameworks one can choose from to implement Web services.. I have split this article into two parts: first, I provide an overview of the questions and the highlights from the developers’ answers. Although I have done my best to keep the summary unbiased, the original answers are provided for reference (and for those interested in all of the details) in the second part. The developers interviewed were Paul Fremantle (Axis2), Dan Diephouse (CXF), Arjen Poutsma (Spring Web Services), Thomas Diesler (JBossWS) and Kohsuke Kawaguchi (Metro): Paul Fremantle is a co-founder and VP of Technical Sales at WSO2, a company that is a driving force behind a number of Apache projects. While at IBM, Paul created the Web Services Gateway, and led the team that developed and shipped it as part of WebSphere Application Server. Paul was a member of the team that put the Service Integration Bus technology into WebSphere Application Server 6. He also co-created the Web Services Invocation Framework (WSIF) and was co-lead of JSR 110 and OASIS WS-RX TC Co-chair. Dan Diephouse is a software architect at MuleSource, the company behind the open source Mule ESB. Here he is focused on building and helping others build open source web services/SOA solutions. He is a co-founder of the web services framework Apache CXF, a founder of several other projects including XFire, SXC, and Jettison, and participates in several others whenever possible. Arjen Poutsma is a senior enterprise application architect is the founder and the project lead for the Spring Web Services. This Spring project aims at facilitating development of document-driven web services. Arjen has also contributed to various other open source projects, including XFire, NEO and others. Since early 2005, Arjen has been a consultant for Interface21 (the company behind Spring) in The Netherlands. Thomas Diesler is the Web Service project lead at JBoss and generally helps setting the technical direction at JBoss as a member of the Technical Board of Directors. As a member of the JCP, he helped to define various Web Service specification (e.g JAX-WS). Kohsuke Kawaguchi is a staff engineer at Sun Microsystems has been working on XML and XML schema languages since 2001, including specification work on RELAX NG and W3C XML Schema, and implementation work in a number of related Java artifacts, including JAXB and JAXP. He is active at java.net as one of the original leads of the Java web services and XML community. Part I: Overview Design Goals There are some design goals that are shared among of all of the stacks, such as extensibility, modularity, and performance. Axis2 is designed around an XML object model called AXIOM, a mixture of streaming and tree-based messaging, and provides pluggable data binding support; CXF supports pluggable transports, data bindings, and can even support alternative formats such as JSON. Spring-WS supports lots of different ways to handle XML, too – from XPath-based access to a number of XML APIs such as DOM, SAX and StAX to data binding approaches such as JAXB, Castor and XStream. Metro also features pluggable transports and encodings. Assuming all of these approaches have been put into practice and actually work as expected, it’s hard to see any major difference in this regard. Paul Fremantle noted that Axis2’s architecture was designed to be implementable in both C and Java. He also highlighted Axis2’s module concept, which allows related collections of handlers to be deployed, together with libraries and data files, as a single unit. Dan Diephouse pointed to CXF’s embeddability as one of its key features; another aspect he noted was the focus on ease-of-use for the developer. Arjen Poutsma put strong emphasis on Spring-WS’s support for the “contract-first” style of WS development. Thomas Diesler pointed out that JBossWS can support both its own native stack as well as integrate with others, including CXF and Metro. Interoperability is listed by Sun’s Kohsuke Kawaguchi as a design goal for Metro. JCP Standards There are a number of standards for working with XML and Web Services in the JCP, most notably JAX-RPC, JAXM and their successor, JAX-WS, as well as JAXB (the JCP standard for XML data binding). Opinions start to differ when it comes to support for these standards within the different frameworks. The Axis2 team made the explicit decision to support JAX-WS as a layer above the “minimal, clean API” that followed its own vision of what makes a framework “cool”. JAXB is supported both on its own and in conjunction with JAX-WS. Paul Fremantle dismisses JAX-RPC and JAXM as outdated and never much used, respectively. Dan Diephouse (and the CXF framework) share the opinion on JAX-RPC and JAXM, and CXF supports JAXB and JAX-WS, too. Interestingly, Diephouse considers JAXB to be “fast, very robust” and has found that it “will work with 99.999% of the schemas” he’s come across. He also points to his own SXC project as a way to considerably speed up JAXB. JBossWS supports JAX-RPC, JAX-WS and JAXB. For obvious reasons, support for JCP standards is one of the most important goals for Sun’s Metro; as Kohsuke Kawaguchi points out, Metro includes the reference implementations of both the JAXB and JAX-WS JSRs. Arjen Poutsma explains that the programming model exposed by Spring-WS is very similar to that of JAXM in that it is a message-based programming model, and not “an RPC-like model such as JAX-RPC and JAX-WS”. Thus while JAXB 1 and 2 are supported, JAX-WS is not (as an explicit design decision, or so it seems). It seems that both Axis2 and Spring-WS don’t show much appreciation of JAX-WS, while only Spring-WS goes so far as not to include support for it. Web Services Standards All of the frameworks claim support for a common set of Web services standards which includes SOAP 1.1 and 1.2, WSDL 1.1, MTOM/XOP, and WS-Security. Axis 2 is the only stack supporting WSDL 2.0 (which is probably not surprising as WSO2 co-founder Sanjiva Weerawarana is one of the WSDL 2.0 editors). All except Spring-WS and JBossWS implement WS-Addressing and WS-Reliable Messaging (support for both WSDL 2.0 and WS-Addressing is planned for future versions of both). Metro is the only stack with support for WS-AtomicTransaction and WS-Coordination, which are hooked up to J2EE/Java EE transactions. Data Binding The topic of data binding, i.e. the mapping from XML to objects and back, often leads to intense debates among Web services and XML practitioners. Arjen Poutsma’s opinion (“Data binding […] might be very convenient, but opens the door to a whole range of interoperability issues”) is shared by many of the interviewees, but all stacks – including Arjen’s Spring-WS – support it due to simple user demand. All of them also offer support for direct XML access, usually via SAX, StAX, DOM; some additional options are available, e.g. AXIOM in case of Axis2, Aegis in case of CXF, and XPath for Spring-WS. Interoperability (.NET/WCF in particular) Paul Fremantle believes Axis2 to be one of the most interoperable stacks due to the team’s participation in numerous interop events, and points to interop tests for both individual standards as well as whole profiles. Dan Diephouse splits interop testing into three areas: Data binding (where CXF relies on the proven JAXB and Aegis implementations), WS-I Basic Profile support and WS-* interoperablity. CXF relies on its WS-I BP compliance, usage of frameworks such as WSS4J for security (also used by Axis2) and interop testing to ensure interoperability. Arjen Poutsma considers Spring-WS’s contract-first approach the best guarantee for finding and resolving interoperability issues early. According to Kohsuke Kawaguchi, interoperability with Microsoft products was one of the topics with a lot of management attention at Sun’s Metro project. According to Thomas Diesler, JBossWS developers participate in interop events, too. REST Support The question about the stacks’ support for REST took none of the developers by surprise, although the answers differed quite significantly. According to Paul Fremantle, Axis2 supports both simple XML over HTTP scenarios (which are often not RESTful) as well as “real” REST via WSDL 2.0’s HTTP binding. One area Axis2 does not support yet is hypermedia. (Personally, I’m skeptical about this assertion since WSDL 2 is still centered around the concept of an operation, which seems anathematic to REST from my point of view.) Dan Diephouse describes CXF’s support for both POX (plain XML over HTTP) as well as REST: the latter is done via annotations, similar to the approach taken by JSR 311. Arjen Poutsma concedes REST is an interesting alternative to SOAP, WS-* and POX, but Spring-WS does not support it yet. When it will do so sometime in the future, it the support will be based on the Spring Web framework. Kohsuke Kawaguchi declares his fandom for REST, but sees support for it as outside of Metro’s scope and points to Jersey, Sun’s JSR 311 implementation. Interestingly enough, Thomas Diesler points to Metro when questioned about REST support in JBossWS. Framework Maturity Not surprisingly, all of the developers claim maturity and production readiness for their respective frameworks. Axis2 and CXF are used in numerous other open source projects, Axis2 more so (and even in some commercial products such as IBM WebSphere). According to Arjen Poutsma, the fact that it took two years to get Spring-WS to version 1.0 is due to Interface 21’s high quality standards. Both Kohsuke Kawaguchi (for Sun’s Metro) and Dan Diephouse (for CXF) point to the history of their frameworks, which are rooted in JWSDP and XFire, respectively. Thomas Diesler notes that according to a survery, more than 60% of the JBoss customer base use JBossWS. Kawaguchi cleverly points out that the inclusion of components of Metro in the Java 6 JDK easily makes it the most widely installed toolkit. Conclusion It’s hard to come to any obvious recommendation by just looking at the answers provided by the different stacks’ developers. There definitely seems to be more in common, at least from looking at the goals, than there are differences: a focus on efficiency and performance, extensibility and pluggability, and choice for the developer. Axis2 and Metro support more of the WS-* standards than CXF, Spring-WS and JBossWS. While Axis2 tries to unify the “classical” WS-* style and the REST style, the others view support it either with a different programming model or not at all. Metro is obviously the one most influenced by JCP standards. Wether one views this as fortunate or unfortunate – it seems the Java WS community will continue to have to choose for quite some time. Part II: The Details Below are the original questions I posed and and answers I received from the framework developers. (1) Can you describe the main design goals of “your” framework? What do you perceive as its main strengths and unique features? Paul Fremantle (Axis2): The primary design goal of Axis2 was to build a framework which was cleanly designed around XML, very highly performant and easily extensible to add support for various WS-* protocols. One aim was to take a strongly XML centric design point. That is, unlike other WS stacks, the Axis2 architecture does not treat XML as a hot potato to convert into an object as quickly as possible. Rather, it treats XML as the natural data model to execute on, and allows us to ‘outsource’ databinding to best-of-breed open source projects. Pluggable databinding means we can work with JAXB, XmlBeans, our own simple model (ADB), or any third-party package. AXIOM, our XML API, provides us with incredibly fast and flexible (a blend of streaming and tree-based) message processing. Our “Module” architecture significantly improves the handler-based model of Axis1 and other systems by allowing related collections of Handlers to be deployed, together with libraries and data files, as a single unit. The module constraint system removes the need for manual handler ordering. Modules are engaged by either user configuration or by policy processing, and distributions can go from “bare” to “fully WS-* enabled” with the inclusion of a few files. Both services and modules deploy easily as archive files or exploded directories. Configuration and control is enriched by a “scoped” context model - settings come from messages, operations, services, sessions, or the system as a whole, and are very easy to work with. Our pluggable backends mean it’s easy to implement service adapters for JavaScript, EJBs, Databases or other implementations. Another key design point was that we designed the architecture to be implementable in both Java and C. To the best of our knowledge we’re unique in having a complete native C implementation. We’ve already done PHP bindings of the C stack and are working on Perl and Ruby bindings and will be doing Python bindings as well. Dan Diephouse (CXF): First, as an Apache project, we are based on a community model. This means I can not speak for all the developers or organizations involved in the project. So what follows are my opinions only! In no particular order, some of the goals of our framework are: Support for web service standards, where web service standards means SOAP/WS-*. We support a range of scenarios for developing services from a simple code first service with no annotations needed, to WSDL first services, to the JAX-WS APIs Provider/Dispatch APIs. Ergonomics: Granted we aren’t perfect at it, but we really work hard to make CXF as easy to use as possible. Our APIs are designed to make the simple use cases trivial, and the hard use cases possible. We’ve also worked to create a great set of tools - including Maven/Ant plugins. Embeddability: CXF is designed to be a component which is embedded inside an application. This application can be your own business application, an ESB, or an application server. For instance: Mule, ServiceMix, Geronimo, and JBossWS are some great public examples. Spring Integration: Our Spring integration makes it easy to configure clients, servers, and transports inside an ApplicationContext. Performance: The SOAP/XML portion of CXF is based on a streaming XML message model, which facilitates very fast XML processing and low memory usage. Flexibility and Extensibility: One of the reasons CXF came into being is that we needed a very flexible and extensible framework. You can write new transports easily. You can add support for different bindings. We support non-XML formats such as JSON and Corba. It is all very pluggable and extensible. Arjen Poutsma (Spring-WS): The main design goal of Spring Web Services is “to make the best practice an easy practice”. Contract-first service development (i.e. starting with the WSDL and XSD) traditionally has been a hassle. Spring Web Services aims to make this easier, for instance by generating the WSDL from a XSD schema. Another unique feature of Spring-WS is choice, just like all of the products in the Spring portfolio. You can handle the incoming XML messages in any way you want to: by using low-level APIs such as DOM, JDOM, dom4j, XOM, SAX, or StAX, by using XPath expressions, or even by using one of the supported XML Marshalling mechanisms: JAXB 1 or 2, Castor, XMLBeans, JiBX, or XStream. Thomas Diesler (JBossWS): JBossWS is a framework for plugable web service stacks in the jboss application server. Currently we support our native stack, Sun Metro, and Apache CXF. See here Kohsuke Kawaguchi (Metro): One of the primary design goals of Metro was the performance. We've done one iteration of web distributed technologies (CORBA, JAX-RPC 1.0 and JAXB 1.0, among other things), so we knew for the first-hand that what slows them down, and how to fix them. Those expertise and experience is put into designing Metro, and I think this is showing. Another part of the performance goal is to provide additional proprietary API for those few (often framework developers) that really need to get the maximum juice out of it. A good example of this would be our asynchronous implementation — it’s not easy enough for typical developers, but for example OpenESB guys take advantage of this to achieve great scalability. Another design goals of Metro is the extensibility. Again, we had experience under our belt with our previous generations of technologies, so we knew what are the kind of places where additional abstractions are useful. This includes things like transport and encoding abstraction. We used them to implement FastInfoset support and JSON support, which broadens the applicability of Metro, as well as different transports like JMS, SMTP, and in-JVM local transport. In many places we were also able to design our abstractions to facilitate better performance, too. These extensibility was a key for us to implement a large number of WS-* specs in a modular fashion. Interoperability is another important goal. Also in practice this is more to do with the hard and diligent testing work, rather than designing work. We went through a number of interop workshops with different vendors, we held regular meeting with our engineers and Microsoft engineers to discuss issues, and we even invited a Microsoft guy to JavaOne keynote to show our interoperability. We run interop tests nightly and monitor results. So that's how serious we are about the interoperability. Last but not least, ease of use is another important goal for us. Again, this has more to do with attention to the details, rather than designing. We feel that the loss of productivity most often comes with the difficulty in trouble-shooting some problems. For example, how many of you have an experience spending hours googling trying to look for a solution for a particular problem? So we put a lot of efforts into doing a good error diagnostics and reporting, putting debug and logging switches to let you and us figure out what's going on, etc. The other important pillar for ease of use is good user support experience and docs. We also provide paid support for Metro through several different channels. I don't know if any of them are unique, but I think the combination of them makes Metro a very solid web service stack. (2) What’s your position on and the framework’s support for JCP standards such as JAX-WS, JAX-RPC, JAXM, JAXB? Why is support for it included/not included? Paul Fremantle (Axis2): From the get-go Axis2 was designed to have a minimal, clean API that would really take advantage of the particular things that make our framework cool - scoped contexts, the AXIOM streaming XML model, Module-based extensibility, etc. We also wanted to ensure Java 1.4 compatibility, and had already had some experience with slowdowns and delays around TCK certification. So we decided to support JAX-WS (which requires 1.5) - but as a plugin layer above the base. We also fully support JAXB, either on its own or with JAX-WS, as a pluggable data binding. This allows us both standards support and independent evolution of our own APIs. We decided JAX-RPC wasn’t worth it since JAX-WS has supplanted it, and JAXM was never much used. We also realize that the JVM isn’t just for Java. We’ve done a lot of work on supporting JavaScript services, and we plan to work on bindings into other JVM languages such as JRuby and Groovy too. Dan Diephouse (CXF): JAX-WS: We support the JAX-WS 2.0 standard and are busy implementing the 2.1 standard now as well. I view the JAX-WS as very important for two reasons. First, it makes it relatively easy to build web services and clients. Second, because it is a standard, there is a large growing pool of developer knowledge out there on how to use it. This means you as a developer don’t have to spend time learning proprietary APIs or (many of) the ins/outs of a new framework JAXB: JAXB is also an important JCP standard; for the same reason JAX-WS is: it makes it easy to build services and there is a large body of knowledge out there on how to use it. As an added bonus, the only JAXB implementation out there is very good. It is fast, very robust, and will work with 99.999% of the schemas that I’ve come across. On this last point - you can compare this with ANY other framework, with the exception of possibly XMLBeans, and JAXB will come out ahead. It does have some annoyances though: you often need to create jaxb.index files, it creates elements in the default namespace by default, and it isn’t as fast as it possibly could be. Regarding the last point, we’ve worked on addressing this via the SXC () project which provides compiled readers/writers for JAXB beans. This gives JAXB a substantial performance boost. JAX-RPC: We don’t support JAX-RPC. It is a very outdated standard of very little use if you’re developing a new service. While we’ve discussed adding support for JAX-RPC to help people migrate off from older frameworks, it would provide very little marginal value with a high amount of work on our part. JAXM: We don’t support JAXM either. Its an older standard which hardly anyone uses. Additionally it seems superseded by JAX-WS. Arjen Poutsma (Spring-WS): The programming model provided by Spring Web Services is very similar to that of JAXM, i.e. it is a message-based programming model, and not an RPC-like model such as JAX-RPC and JAX-WS. Furthermore, Spring-WS supports SAAJ, the SOAP message abstraction that has been part of J2EE since 1.4, but makes it more developer friendly. For instance, the checked SOAPExceptions thrown by SAAJ are wrapped by runtime exceptions. Finally, JAXB 1 and 2 are supported by the Object/XML Mapping abstraction. Thomas Diesler (JBossWS): We support JAX-WS, JAX-RPC, JAXB. In our opinion JAX-WS supercedes JAXM. We have hence no support for JAXM. Kohsuke Kawaguchi (Metro): Pieces of Metro is available individually as they often have broader applicability than just web services, and these pieces include the JAXB RI, JAX-WS RI, and SAAJ RI, among other things. For those of you who are not familiar with JCP jargons, the RI status means that they are used as one of the exit criteria of a JCP spec, and we can't ship them unless it passes all the compatibility tests (called as TCKs.) This process usually makes the RI most conforming implementation of the spec. So as you can see, Metro takes compatibility very seriously. We even run TCK tests at least nightly, in some cases continuously to detect any compatibility regressions. So for us, it's a part of the development process, not just something we run at the end of a release cycle. Some other web services toolkits don't place as much emphasis of JCP standards as we do, but I think compatibility is good for users in many ways. For example, it creates a level playing field for competition, it helps avoid a vendor lock-in (thus reducing the risk of you choosing one toolkit and be stuck with it), but more importantly to me, because it creates a bigger ecosystem thanks to a larger user base. A bigger ecosystem makes many things economically feasible that are otherwise impossible, and this encompasses everything from books and articles to training and tools. We still offer proprietary APIs in many places, but because of these reasons we continue to stick to standards wherever make sense. (3) What Web services standards do you support, and why are those you don’t support not supported (i.e. do you plan to include them later, not at all, …) Paul Fremantle (Axis2): Axis2 is itself primarily about XML and SOAP message processing, with support for SOAP1.1 and SOAP1.2, and includes a variety of transports (HTTP/S - including Non-Blocking IO, JMS, TCP, SMTP/POP, XMPP). MTOM is supported out-of-the-box, as are WSDL 1.1 and 2.0, WS-Addressing and WS-Policy. We also support pluggable encodings including FastInfoset and JSON. Higher level specs are all supported via pluggability, and we think that’s particularly important for embedded applications where not every spec is needed. We have plugins for WS-Security (1.0/1.1), WS-SecureConversation and Trust, WS-ReliableMessaging (1.0/1.1), WS-Transactions, WS-MetaDataExchange, WS-Transfer, BPEL (Apache Ode), WS-Eventing, and WS-RF/Notification (Apache Muse). Support for other specs can easily be added by our team or others as they become needed. Dan Diephouse (CXF): We support: - SOAP 1.1, 1.2 - WSDL 1.1 - WS-I BasicProfile 1.1 - WS-Addressing 2004/08, 1.0 - WS-Policy - WS-ReliableMessaging 1.0 - WS-Security 1.0, 1.1 We’re hoping to support WS-SecureConversation and WS-Trust soon as well. There are of course many others out there. Many are unimportant or worthless (you may feel that all of them are, but thats another story!), so we’ve focused in on the ones that we’ve heard from our users about. If you feel you are missing support for an important specification, please send an email to us () so we can look at including it in a future release. Arjen Poutsma (Spring-WS): Obviously, Web services should primarily concerned with interoperability, but a surprisingly large number of these specifications are not interoperable at all. That means that there are implementations in Java, and perhaps .NET, but not in scripting languages such as Ruby, Python, or Perl. Therefore, we try to take a very pragmatic approach when it comes to implementing WS-* specification, and only implement those which add value, or which have sufficient user demand. That said, Spring-WS currently supports SOAP 1.1 and 1.2, WSDL 1.1, MTOM and it has a WS-Security implementation that integrates with Spring Security. For the upcoming 1.1 release, we plan to implement WS-Addressing, and WSDL 2.0. Thomas Diesler (JBossWS): See here. We expect to support more WS-* standards through the Metro/CXF integration. Currently we are also working on native WS-RM support. Kohsuke Kawaguchi (Metro): The thing I hate about web services is that there are way too many specs involved. But anyway, starting with basic easy ones, we use WS-I Basic Profile 1.1 as the base line, so WSDLs we publish and consume conform to WS-I BP. For handling large binary data / attachments, we support WS-I attachments profile 1.0, and MTOM/XOP. We also support the entire WS-Addressing 1.0. We even offer improved programming model that takes advantages of WS-Addressing. WS-MetadataExchange support and WS-Policy is also in Metro, which are more or less transparent, but nonetheless important part of making stuff work transparently. Metro includes WS-ReliableMessaging support for reliable in-order message delivery when intermediaries are involved. It supports WS-AtomicTransaction as well as WS-Coordination. These are hooked up to JavaEE transaction so you can use this to do a declarative distributed transaction that across multiple JavaEE systems and .NET systems without knowing much about the gory details of these on-the-wire protocols. On the security side, Metro comes with WS-Security, WS-Trust, and WS-SecureConversation. These specs address different needs spanning from simple message-level security to more complex federated authentication that spans across different organizations. All the security, transaction, and reliability features are done under the name of WSIT (AKA Tango project), which we invested significant resources into. Even though we implement all these specifications and they do come out of the box, there are several things we paid particular attention to. First, we work closely with NetBeans team so that there's always an accompanying NetBeans plugin, which lets you configure those modules through a nice GUI. This protects you from the gory details of how the underlying system configures these specs. Second, this whole thing is pay-as-you-go model, in the sense that you don't pay the performance, complexity, and cognitive penalty of features that you don't use. Finally, the same modularity allows us to implement other and future WS-* specs, if the user demand the efforts justify doing so. So please let us know what you'd like us to be supporting, if you feel that the list is not adequate. (4) What’s your position with regards to data binding and the problems many people associate with it? Do you support native access to the XML message, an XML/object mapping, or both? Paul Fremantle (Axis2): Axis2 was deliberately designed to support a flexible data-binding model including native XML access to the message. Axis2 supports a wide variety of data-binding toolkits including JAXB, XMLBeans, JIBX, ADB (built-in data binding), and the approach is extensible to any data-binding toolkit - especially if the toolkit supports the StAX standard. If the user chooses direct access to the XML, then Axis2 offers a tree like model (Axiom) as well as the StAX stream, and simple utility classes offer DOM and SAX interfaces as well. We believe that data binding use-cases are very important, and that Java coders should be able to use Web Services with a Java model if they want to, and XML coders should have fast, effective access to the XML if they want to. We think we’ve found a good middle ground which allows both the Java-heads and the XML-heads to be successful with Axis2. Dan Diephouse (CXF): There is this idea out there that data-binding is simply taking XML and making POJOs, but I’d like to enlarge this definition to “any type of processing which hides or removes the original XML infoset.” 99.999% of applications will need to do this - whether they are using JAXB, accessing an XML DOM by hand, or using something like XPath - they will need to extract the data and do some business logic with it. The only applications that won’t need to do this are the ones that end up working with XML as their only datamodel. Looking at it this way, we can chose a databinding based on our answer to the question: what is the best balance of ease of use and retention of the xml infoset? The answer is “it depends.” I feel that for most applications, JAXB hits the sweet spot. It is very easy to use as it creates very simple POJOs. It hides many of the mundane/error prone XML processing tasks from the user. It works with most, if not all, schemas. And, if you follow proper schema versioning practices, you will end up with a very robust, long lived service which adheres to your contract. We do support several other ways of databinding though. You can access the raw XML streams via the “StAX databinding.” There is also the Aegis databinding inherited from XFire which makes it easy to build schemas/WSDLs from just about any code. It has support for a lot of alternative datatypes like Maps or java.sql.Date. We have support for JAX-WS Providers which allow you to work with the XML messages as Source objects. We are hoping to provide XMLBeans and JiBX support for our next release as well. Arjen Poutsma (Spring-WS): Data binding, or Object/XML Mapping as I prefer to call it, might be very convenient, but opens the door to a whole range of interoperability issues. The fact is that the Java language and the XML language are quite different, and whenever a conversion occurs between the two, something can go wrong. Take for instance the difference between an XSD date and java.util.Calendar. Typically, an XSD date “2007-09-14” will be converted to a Calendar that represents 14th September, at midnight in the local time zone. If that Calendar is converted back to XML, you will not end up with the same XSD date that you started out with, but probably a dateTime. But as I said earlier, OXM can be very convenient. So Spring-WS supports it, in the forms of JAXB 1 and 2, Castor, XMLBeans, JibX, and XStream, but also provides access to the raw XML message if you need to. Thomas Diesler (JBossWS): We have a notion of a SOAP content element, which is a abstract view of the message parts relevant to data binding. Client code can natively obtain content as XML (DOM), Java (JAXB), or SAAJ. Kohsuke Kawaguchi (Metro): I don't think anyone disagrees that data-binding is useful for many situations, so of course we offer a data binding solution in Metro. Similarly, I don't think anyone disagrees that access to raw infoset is useful in many other situations, so again obviously we provide that in Metro. OK, so first about data binding. Metro uses JAXB as the data binding solution, which is still to this date the only annotation-driven POJO data binding solution. The use of annotations allow us to support both contract-first and code-first data binding in a single data binding solution, which is something that cannot be said about every data binding technology. Concentrating primarily on JAXB allows us to use our project resources efficiently, as opposed to fragment our developers and users into multiple silos for each data binding technology. Now, the problem with a data binding technology like JAXB is that you lose the access to XML infoset. While it's a feature in certain situations, this becomes problematic in certain other situations, such as when your processing code is layered, when a web service is really just used as a transport layer, or maybe when you have your own domain specific data binding scheme. So to this end, Metro offers access to the raw XML infoset through JAX-WS. You can access the entire SOAP message or just the payload part (which is convenient if you are plugging Metro with another data binding technology.) You can access it in a DOM like tree structure by using SAAJ, you can access it as SAX events, or you can access it by a StAX parser. Speaking of the raw infoset access, we are also working on exposing our efficient internal SOAP message abstraction to you, so that you can access the SOAP message in even more convenient & efficient way. I guess the other thing that's worth mentioning is that through the mechanism called handlers we allow you to combine both. That is, you can access the SOAP message as infoset first to do a few things, then do the data binding and do something else. (5) How well do you support interoperability with other WS implementations, particularly .NET/WCF? Paul Fremantle (Axis2): Our team has participated in interop events with the W3C, OASIS, and Microsoft, and we pride ourselves on a good interop test record. We try to fix all interoperability-related problems as quickly as we can, whether by fixing our own bugs or working around those in released versions of other implementations. As well as the individual interops for specific standards, we’ve worked a lot on interop with .NET/WCF for some particular profiles - especially Secure Reliable with Binary (MTOM, WSRM and WSSecurity together). Based on our testing we believe we are one of the most interoperable stacks. Dan Diephouse (CXF): There are three levels of interoperability testing that matter to you as a user: Databinding: The JAXB and Aegis implementations have been well tested with .NET/WCF over many years. I believe both are around 4 years old now. BasicProfile/SOAP: At this level we’re concerned with ensuring that we’ve followed the assertions and best practices laid out in the BasicProfile standard. If you follow these guidelines you’re pretty much guaranteed good interoperability with other frameworks like .NET/WCF. But we also test our services with .NET/WCF - especially around the harder interopability areas like MTOM. WS-: Each of the WS- specifications has its own ins/outs, so the story here will vary depending on the specification, its longevity, and its complexity. For instance WS-Security, we use Apache WSS4J framework which has been tested extensively with .NET by the community and many organizations who build products using it. Members of the community, notably IONA, also perform integration testing with WCF at various points during the release cycle. This tests not only the WS-* level, but all the lower levels as well. Arjen Poutsma (Spring-WS): One of the advantages of the contract-first approach of Spring Web Services is that interoperability issues with other platforms can be directly resolved by the service developer. This means that you don’t have to “persuade” the SOAP engine to use one particular XSD construct instead of the other, because it does not interoperate with the .NET platform. Rather, you can choose the interoperable construct directly. This approach is illustrated by the sample applications that ship with Spring-WS. These samples show interoperability with Microsoft .NET 1.1, WSE 2.0, and WCF. Thomas Diesler (JBossWS): We regularly attend the the MSFT interop workshops and actively maintain a number of interop endpoints ( and) Kohsuke Kawaguchi (Metro): Metro has a large dedicated team of people whose entire job is to ensure interoperability with .NET. As I wrote earlier, the truth is that interoperability is not something you can simply achieve by doing the right design. Rather, it's a result of tireless diligent hard work of the testing guys. Again, most of the work is done as a part of WSIT effort and now an integral part of Metro. So in Metro, we set up a series of tests for each WS-* modules and constantly run interop testing with Microsoft endpoints. This is at least run nightly to ensure no regressions, and it's one of the release criteria we have — we won't ship Metro unless all the tests pass. We've been working very closely with Microsoft. There was a weekly manager-level meeting to discuss various issues, with all kinds of engineer-level meetings to hash out and resolve issues. Many of us have been to Redmond multiple times to attend interop workshops. We even invited a Microsoft guy to our JavaOne key note session and demoed our interoperability. We also pay particular attention to interop related issues with other Java and non-Java toolkits, although I don't think we are hearing too many of them. We also tend to be very forgiving when it comes to accepting broken inputs, and more strict about what we produce, which also improves the chance of smooth interoperability. All in all, I think it's fair to say we spent a real effort in ensuring interoperability. And thanks to all the hard work of W3C, WS-I, and testing guys of all the web service toolkits, the overall interoperability situation of web services came a long way, and it’s showing. (6) What is your position with regards to REST? Do you offer any kind of REST support? Paul Fremantle (Axis2): There are multiple levels to supporting REST. Firstly we have a simple approach that allows developers to do “Plain Old XML” over any transport, including HTTP GET as well as POST. It works out-of-the-box with POJOs, so simple XML/HTTP scenarios are easy. Secondly, we are the only WS toolkit to fully support the WSDL 2.0 HTTP binding. Using that binding, one can fully describe pretty much any RESTful service - for example, we’ve done a complete description of Atom Publishing Protocol with that. So at the level of dealing with URIs, getting data in and out of the URI, supporting all HTTP operations, getting data in and out of the payload, we are now fully REST compliant. The one area of REST we haven’t attacked yet is known as “hypermedia as the engine of application state”. That is, we do not offer any framework support right now for dealing with creating messages that have links and for properly dealing with those links. That (admittedly hard!) problem is left entirely to the application author. There’s been a lot of conversation about this and we expect to experiment more in a RESTy direction in the future. Dan Diephouse (CXF): I believe that REST is a great way to build services. As an architecture it has a lot of power, but unfortunately it is often mis understood or not understood at all. CXF has several tools to help you build RESTful services. We have an XML over HTTP binding which allows you to turn your SOAP web services into simple Plain Ol’ XML services. We support using annotations and URI templates like @HttpResource(“/foo/{bar}”) to map service operations to resources. We also support a convention based mechanism whereby your service will be introspected an intelligently turned into resources. For instance, a method like getPurchaseOrder(long id) will intelligently be mapped to a GET request on the resource /purchaseOrders/{id}. There is also some work and discussion going on surrounding the JSR 311 specification. Arjen Poutsma (Spring-WS): I think REST is an interesting alternative to SOAP, WS-*, and Plain Old XML (POX). It solves a lot of problems of the WS-* space by basing itself on HTTP, a proven technology. However, I think that REST is just as, or even more restrictive than SOAP is. When writing a REST service, you have to have a clear idea about the resources that are to be exposed , which data formats you support for them (REST is not just about XML!), which HTTP methods you support on them, and what they mean. All of this has to be clearly documented as well; the HTTP specification isn’t enough for this purpose, and I am not sure if WADL is the answer. Spring Web Services does not support a REST programming model at this moment, but it will be added in the 2.0 release, to be released early next year. REST the Spring Web framework. Thomas Diesler (JBossWS): We actively participate in JSR 311 and support REST via the Metro integration. Kohsuke Kawaguchi (Metro): Personally, I'm a big fan of REST. Some of my other projects (like Hudson) is entirely REST based. But the problem I have with REST is that, just like any new technology, users often have different understanding of REST, so when they say "do you do REST?" we need to be careful about what we say (as a case in point, how many of you have heard about someone saying "I did my RESTful XYZ" and others yelling that is not REST?) As we consider REST to be an emerging technology, the current REST support work is going on in our sister project Jersey. Jersey embraces REST to the heart's content, even if it means breaking away from the traditional programming model of Metro. I think this is the right thing, because if you take REST to its logical consequence it's really a different programming model. Just adding some REST like features (such as URI templating) to existing SOAP programming model in a piece meal fashion just wouldn't cut it. This also works nicely for those users for which the primary attraction of REST is to get away from SOAP complexity. Going forward, however, I think we'll be spending efforts into bringing Jersey as a part of Metro. I think it's going to be interesting to see whether we can bring in some kind of integration and unity between SOAP and REST programming model, or whether they'd really remain substantially different. (7) What is your framework’s maturity? Are there any case studies you can point to, are there any commercial or open source products that rely on it? Paul Fremantle (Axis2): Axis2 is definitely production ready. We do regular soak tests, memory usage and performance tests. You can read some of them here:. Axis2 is used in many other frameworks and products including: Eclipse WebTools Project, Apache Geronimo, Apache Tuscany, Apache ODE, IBM WebSphere 6.01, SoapKnox, Apache Synapse, WSO2 Web Services Application Server, WSO2 ESB, Intalio BPMS, and many others. Dan Diephouse (CXF): CXF has a long history. It is based in XFire which started 4 years ago and in Celtix which started several years ago as well. There is a lot of code which has been inherited from both these projects, which has helped create a stable/mature project. While we have bugs still, we believe in doing releases often and keep a tight feedback cycle with our users. We released our 2.0 release in July and are releasing 2.0.2 soon. I’ve seen CXF go into several deployments (which unfortunately I can not talk about due to confidentially). There are also a lot of open source projects which have integration with it. Mule () has a CXF connector which MuleSource supports commercially. ServiceMix () has CXF integration as well which IONA supports via their bundling of ServiceMix/CXF called FUSE. Guillaume Alleon has created a Groovy Web Services () project project which makes it possible to build services using Groovy and invoke services with no WSDL->Code step. I believe several other projects are busy migrating from XFire to CXF as well, like Enunciate (). Arjen Poutsma (Spring-WS): In August, we released Spring Web Services 1.0. Before this release, many people were using the milestones and later the release candidates, and were quite satisfied with its stability. The fact that it took us two years to get to the 1.0 release is due to the high standards of quality that Interface21 has. At the end of the year, we plan to release 1.1. This release will bring support for additional transports (JMS, email, and others), and will add support for WS-Addressing. Spring-WS 2.0 will bring support for REST services. Thomas Diesler (JBossWS): The JBossWS offering is very mature with 2.5 years of ongoing development. According to a survey more than 60% of the JBoss customer base uses JBossWS. Kohsuke Kawaguchi (Metro): We have changed the name, but a good portion of the code dates as far back as 2001 and Java Web Services Developer Pack (JWSDP), which won several awards including 2005 "web service or related tool of the year" and 2006 JDJ Reader’s Choice awared, and it's essentially the same team that's running the show since then. So there are significant chunk of code that's proven by years of use in the real world, maintained by people with significant experience in those code. The JAX-WS specification, which is the heart of Metro, also goes back quite a history, if you include its predecessor JAX-RPC. It's started 2001, and in this industry 5 years is a really long time. So there again, we have a proven technology built by feedbacks from vendors and users alike. Then there’s JAXB. I’ve done much of the RI work and now also doing the spec, so I can tell you a lot about how ubiquitous the JAXB RI became. As a case in point, I think all the other web service toolkits discussed here supports the JAXB RI. When you have that level of adoption with more than 10 releases since JAXB 2.0 under our belt, the code becomes rock solid. On maturity, I guess the other thing we can talk about is the amount of testing that it goes through, which is one of the strength of having a large organization like Sun backing a project. First, each component in Metro goes through a series of testing (normally 3, called unit tests, SQE tests, and TCK tests.) For example in JAXB, we have 1500+ unit tests, 220+ SQE tests, and 5700+ TCK tests. Once the components are integrated into Metro, the whole thing goes through additional testing. This includes interop tests and end-to-end container tests on more than 80 different platform configurations. We even have a cluster of machines dedicated for testing Metro. As we get integrated into JDK and GlassFish, they are running their own tests against Metro, too. Tests of this magnitude doesn't come in one day — it's only made possible by a long history of our project and several teams of multiple engineers dedicated to writing and running tests in repeated, automated fashion. Again, it's not something the users of Metro would see, but that's the kind of things we do behind the scene to deliver a quality software to you. Speaking of adoption, Metro is used by a variety of other projects. A subset of Metro is used in most application servers today, including GlassFish, WebLogic, WebSphere, and even in Geronimo. It's used as one of the transport component in OpenESB, as well as its commercial offering Java Composite Application Platform Suite. A similar subset of Metro is also used in all the major Java6 JDKs from Sun, BEA, and IBM. This alone makes Metro the most widely installed toolkit, easily by an order of magnitude. Rate this Article - Editor Review - Chief Editor Action - Personas - Architecture & Design - Development - Topics - Architecture - Apache CXF - Interop - Apache Axis - WS Standards - Spring Web Services - Spring - XML Databinding - RedHat - Infrastructure - Enterprise Architecture - Glassfish - Pivotal - Apache - SOA - Application Servers - XML - Messaging - Web Servers - Web Services - REST - Web Development - SOAP - JBoss - Web API - Java - API - Markup Languages Hello stranger!You need to Register an InfoQ account or Login or login to post comments. But there's so much more behind being registered. Get the most out of the InfoQ experience. Tell us what you think Open source WS stack not mature, yet! by Erik Bengtson Spring-WS and WS-* by Satadru Roy Re: Open source WS stack not mature, yet! by Ajith Ranabahu) Re: Spring-WS and WS-* by Arjen Poutsma I'm a bit confused with how Spring-WS is positioned - does it aim to be a full WS stack with its own implementations of the WS-* specs? For example, I thought, for WS-Security it leverages the Sun XWSS implementation but the idea is to promote a simpler programming model with configuration based security interceptors to handle signing, encryption etc...did I miss something? Well, we generally try to reuse what is available and fits our requirement. So for supporting WS-Security, we indeed use XWSS from SUN, because it is based on SAAJ, and Spring-WS supports SAAJ as well. In other cases, we have no choice but to implement our own version of a WS-* spec, to make it a good fit in the Spring-WS programming model. Re: Open source WS stack not mature, yet! by Erik Bengtson I'm not sure what you mean by saying 'holes'. It is obvious that none of the stacks implement all the WS-* specs that are out there (if specification compliance was the fact that you are referring to). Right now the WS spec space is maturing and there are some specs that are worth waiting for.) Just as matter of example and under a very common usage: WS-RM. You expect realible messaging, but if you take Axis2 implementation, messages lie in memory, so if you crash you loose your messages, thus not that reliable. Said this, I can conclude OS WS stack != out of the box. Just how ubquitous is Metro really? by Steve Loughran One thing I want to question is Koshuke's claim that metro is the most widely "installed" toolkit. As it is in JAva6, it is out there pretty widely, but how common is it in use. Server side, Java5 support is still stabilising; I don't know how common Java6 is. It is out there on the client, but what is in Java 6 is a version that is stuck at the JAXP 2.0 level *forever*. Is that the version that has benefited from the ongoing interop work with Microsoft, or the version that predates this work. -steve loughran ps "I don't think anyone disagrees that data-binding is useful for many situations" Ah, that would be me. I think its a misguided practise that creates long term interop problems. Data binding to the DB, yes, hibernate is wonderful. But trying to map java data graphs to and from XML trees, no. Adopt a decent XML model like Xom and embrace XPath access to the data structures. Re: Open source WS stack not mature, yet! by Ajith Ranabahu If you look at WSO2 WSAS (wso2.com/products/wsas/) which is based on Axis2, Sandesha and a lot of other Web Services projects, it comes with a sophisticated management console that allows you to control these. Again my point is that 'out of the box' means what you expect as out of the box. In your case you look for extended functionality like WS-RM and that when it does not do the persistent storage by default,you see it as a hole. How I see it is that when you drop in the Sandesha module, a given Axis2 instance becomes instantly compatible with RM enabled services/clients and that is sufficient to make it out of the box. As for persisting the messages it is a configuration option for Sandesha module. This is similar in cases like WS-Security where you have to configure the key stores before/after dropping in the Rampart module. What I believe is that all these OS SOAP stacks have come a long way and are sufficiently mature. If you are to implement a SOAP based Web service solution today, I'm sure all these OS SOAP Stacks will come to the picture and compete with the proprietary solutions. This is a sure sign of being mature. Re: Just how ubquitous is Metro really? by Stefan Tilkov Another good principle by Ganesh Prasad I believe that Service Contracts (expressed as XML schemas in the SOAP doc/lit style) and Java Domain Objects are both First Class Entities. First Class Entities are independently defined and should not be generated from any other entity. The Service Contract is independently negotiated between service providers and consumers. The Domain Model is how the service is actually implemented. Neither should be derived from the other. The JiBX/Castor approach respects this and does not attempt the tight coupling that results with the other data binding frameworks that try to *generate* one from the other. I suspect that's why people don't like data binding. What they really don't like are ADB, JAXB and XMLBeans. They should look at Castor and JiBX. This non-generational data binding is a very good principle, ranking up there with contract-first design! Regards, Ganesh Re: Data binding - a misguided practice by Radu Marian I share your point of view - "trying to map java data graphs to and from XML trees, no". However I would go a step further - why map xml to hibernate value objects? Why not from xml to sql and from resultset to xml? xml schema is the defacto biz domain model - why duplicate it any level pojos or hibernate? In the end isn't a web service a set of transformations from client speak to physical and from physical to client speak through a canonical model (xml schema)? I have done the above successfully using xquery. It turned out nice - metadata got separated and j2ee took care of transactions. - radu marian CXF does not support WS-Security 1.1? by Kjell Winblad *? Re: CXF does not support WS-Security 1.1? by Kjell Winblad In the answer of question number three it is stated that WS-Security 1.0 and 1.1 is supported by CXF. But from what I can find from CXF's webpage, it only supports a part of WS-Security 1.0. I can't find any version information on there main page but they are using WSS4J to support WS-Security. WSS4J supports the following: *?
https://www.infoq.com/articles/os-ws-stacks-background/
CC-MAIN-2017-09
refinedweb
9,470
62.27