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
Given a number n, count total perfect divisors of n. Perfect divisors are those divisors which are square of some integer. For example a perfect divisor of 8 is 4. Input : n = 16 Output : 3 Explanation : There are only 5 divisor of 16: 1, 2, 4, 8, 16. Only three of them are perfect squares: 1, 4, 16. Therefore the answer is 3 Input : n = 7 Output : 1 Naive approach A brute force is find all the divisors of a number. Count all divisors that are perfect squares. // Below is C++ code to count total perfect Divisors #include<bits/stdc++.h> using namespace std; // Utility function to check perfect square number bool isPerfectSquare(int n) { int sq = (int) sqrt(n); return (n == sq * sq); } // Returns count all perfect divisors of n int countPerfectDivisors(int n) { // Initialize result int count = 0; // Consider every number that can be a divisor // of n for (int i=1; i*i <= n; ++i) { // If i is a divisor if (n%i == 0) { if (isPerfectSquare(i)) ++count; if (n/i != i && isPerfectSquare(n/i)) ++count; } } return count; } // Driver code int main() {(sqrt(n)) Auxiliary space: O(1) Efficient approach (For large number of queries) The idea is based on Sieve of Eratosthenes. This approach is beneficial if there are large number of queries. Following is the algorithm to find all perfect divisors up to n numbers. - Create a list of n consecutive integers from 1 to n:(1, 2, 3, …, n) - Initially, let d be 2, the first divisor - Starting from 4(square of 2) increment all the multiples of 4 by 1 in perfectDiv[] array, as all these multiples contain 4 as perfect divisor. These numbers will be 4d, 8d, 12d, … etc - Repeat the 3rd step for all other numbers. The final array of perfectDiv[] will contain all the count of perfect divisors from 1 to n Below is C++ implementation of above steps. // Below is C++ code to count total perfect // divisors #include<bits/stdc++.h> using namespace std; #define MAX 100001 int perfectDiv[MAX]; // Pre-compute counts of all perfect divisors // of all numbers upto MAX. void precomputeCounts() { for (int i=1; i*i < MAX; ++i) { // Iterate through all the multiples of i*i for (int j=i*i; j < MAX; j += i*i) // Increment all such multiples by 1 ++perfectDiv[j]; } } // Returns count of perfect divisors of n. int countPerfectDivisors(int n) { return perfectDiv[n]; } // Driver code int main() { precomputeCounts();.
http://www.geeksforgeeks.org/count-perfect-divisors-number/
CC-MAIN-2017-17
refinedweb
408
59.84
So I have this problem, where I need to create a tool that creates a folder with a bunch of files on the PC and then copies all these files over to a CE device. The method of choice here was via ActiveSync over USB. One of the design goals was to be able to copy these files to a number of devices simultaneously. However, research revealed that this is not really possible since, activesync only supports one active connection at a time. So much for the great idea. So now we are faced with this problem of copying files over to the device over ActiveSync. Since the app had a lot of GUI, I created that in C#. The .NET framework exposes excellent API for file manipulation based on paths. The problem with ActiveSync connections is when the device is cradled, there is no drive letter associated with the connection. So all device paths are then \My Documents\ or \Program Files\ etc. This creates a problem as far as the File manipulation API in System.IO. Since these methods accept relative as well as fully qualified paths, any path like the above, would be treated as a relative path and not a fully qualified path, thereby causing a lot of grief. The only way to get past this so far has been to use RAPI. RAPI stands for Remote Application Programming Interface, and was created ages ago with the first wave of activesync and windows mobile products. RAPI has some documentation on MSDN at: However since RAPI is a native API, almost all the documentation is geared towards native implementation. After searching the intertubes for a suitable solution, I couldn’t find one that was recent, and that was guaranteed to work. Below is the solution: Last year I moved over from supporting developers on SharePoint to testing software for Windows Mobile. This was the driver for my move from India over to Redmond last July. There have been a lot of developments in both the Office Server space as well as the Windows Mobile space. For reasons of my sanity, I will be blogging more on Windows Mobile starting now. Windows Mobile 6.0 was the last release more than a year ago. Over the last year, there were a lot of developments and some interesting releases. Microsoft has a partnership with several operators and several OEMS. These two terms are very important to how Microsoft does business in the Windows Mobile space. From this perspective, operators are network service providers who maintain and operate cellular networks. In the US, the ones that we work with are T-Mobile, Verizon, AT&T and Sprint. Across the pond, in Europe, it is Vodaphone, Softphone etc. OEM's on the other hand, are the companies that actually build the phones themselves. For instance, we work closely with HTC, Samsung, Motorola, Toshiba, etc. These are the companies that build the phone and its hardware. The question then is, what does Microsoft do in terms of having the phone in the hands of the end consumer?There are two major groups within the Mobile division. One group is the OS team, and the other is the commercialization team. The OS team, works over a long cycle, that would involve market prediction, product planning etc, and chalk out and architect a strong platform, which for the purpose of this post, is analogous to cookie dough. These guys would work off of the latest Windows CE platform and create a extendible platform on top of that. Each of their releases is generally a major architectural change from the previous release. However, since the release is analogous to cookie dough, this is not what gets to the market. Of course, no one would want dough if they were shopping around for a cookie would they?The commercialization team on the other hand is responsible for ensuring that the cookie dough gets baked into a delicious cookie that can get to the market. So this team works with OEM's and operators in a triad to figure out the combination of the network and hardware that a particular release would be shipped on. For instance, the team could work with HTC and T-Mobile to chalk out the requirements that they have for T-Mobile to sell the device. This would generally require understanding the new hardware features the OEM has introduced, such as say GPS capabilities, touch capabilities, or 3G network capability etc and then plug that in with new services that the operator might be planning. This generally translates into a new feature set which actually makes into the store. On a time line scale, there is a lag of 2-6 months between the OS team releasing a new platform to the device being in the store. Of course, the operators and OEM's keep coming back with more and more improvements or changes to their feature set, or with questions or report some problems that need to be fixed. These get fixed in incremental fixes that are then commercialized in varying timelines. This is a very iterative process. For instance if a version x.0 is released, then there would be some devices that would ship with x.0, there would be some that would ship with x.0.1, some with x.0.2, etc. These are generally minor fixes or tune ups that certain operators or OEM's need. Then there would be a major holiday/summer push with say a x.1.0, and so on. The process would then repeat, till the OS team would release the next major release.So as you see, there is a major emphasis on ensuring that we enable the OEM's and the operators to build and market their devices and services (enable being the keyword here). This is very easy considering that a lot of effort and planning is done to ensure that the platform is extensible and takes into account a variety of requirements that can be made at a later stage. For instance, the extensibility of the platform allowed HTC to convert the standard Windows Mobile 6.0 pocket PC interface and expand it to add Touch and gesture support via the HTC Touch that is available on Sprint networks. This extension was created by HTC and is now part of the new HTC Touchflo platform that is being targeted for a line of devices ( ).More recently a targeted experience was created for T-Mobile with the Shadow device. This required creating a new Home screen, specifically targeted for T-Mobile, which had the T-Mobile branding and colors etc. Of course, this kind of work, exposes new requirements, and enables us to create application platforms that can be extended. As with the Shadow work, we were able to create a application platform, that could help us create better user experiences in the future. When one looks at the process above, it is obvious that the drivers for improvements are based off the direct customer feedback that the operators receive from the users. This feedback is then channeled back to us via product bugs that are prioritized and then actioned. Of course, since the feedback we receive from the Operators is weighted by their urgency in commercial viability of future devices, some actual user scenarios or pain points get overlooked. I am hoping to make this blog a place where I can have some interaction on what scenarios are causing you pain. There is a lot of great work happening in the Windows Mobile space and with the recent announcements at the Mobile World Congress there is definitely a lot of interesting stuff lined up for this year. ~Harsh It's been quite a while since I have posted here. There have been lots of things going around. As some of you know, I was working in the SharePoint Developer Support team, and some amongst you, who have called in might know that there were huge volumes due to the never-before numbers of MOSS deployments. My team was completely swamped with what was happening due to this. In the midst of all of that, I was interviewing within Microsoft for a position in Redmond. There are a number of articles and discussions out there on the internet that talk about various experiences of people interviewing with Microsoft. Suffice to say that, being already an employee did not put me on a pedestal and I was put through the same rigors as anyone else while I was interviewing. This experience was something that I really liked about the company. It does not matter whether you are an existing employee or not, unless you have the required skills needed for the job you are applying for, there is no way they will let you in. During this process I interviewed with all the teams in the Office Server space as well as with some other teams and the experience was really an eye-opener. There is a standard format to these interviews. You (as in the candidate) searches for a job opening, looks at something that fits what he/she is looking for, and then sends out an email to the recruiter or the hiring manager with a resume and asking for an informational interview. An informational interview at this stage is a staging talk between the candidate and the hiring manager wherein the candidate gets a deep look at what exactly the job description said. Also, at this point, the hiring manager would generally schedule a technical screening, to take a look at whether or not it's worth the effort to schedule a full round of interviews. Of course once this is done, you are looking at the real deal - which is the actual interview process. Typically for the programming position that I was applying for, there would be anywhere between 4-8 different individual interviews in a full "loop" as they call it. Each interview is at least an hour long and has a set pattern too. There are a lot of instances when potential candidates are flown to Redmond for the interviews, however in my case, since I was already at a Microsoft site, we utilized the power of technology to work through the interviews. I would book a video conference room at my end and the recruiters would book a video conference room in Redmond. Once the connection would be established, each of the interviewers would walk-in and grill me over the course of the next hour and a half. One thing that really worked in my favor was having a conference room that had a white board facing the screen/camera. It really eased out a lot since, I could write out code or explain my thought process using figures/diagrams and they could actually see what I was writing compared to using a pen and notepad. The interviews would generally go over as, the first 15 minutes walking through my resume, then a programming problem which would take up about 40 minutes or so followed by more questions on why I did something or why I chose not to do something in the code. This would be followed up about 5-10 minutes for me to ask them questions on what they do and what potentially I would be doing.After about two or three months of interviewing I finally found a "mutual perfect fit" team that I was excited to work with. Then started the tedious process of paper work, going back and forth over the offer, working through the visa issues, the travel itinerary and then the actual relocation. It was quite enlightening to understand during this period that each of the individual verticals within Microsoft operated as independent organizations all being part of one parent company. So, while I was in India, I rolled up into Microsoft India R&D which encompassed Services, R&D, Engineering, Sales and Evangelism. However, once I accepted the offer, I realized that I would now be rolling into Microsoft Corp which kind of encompassed almost everything. However, since Microsoft India R&D was a independent subsidiary, all finances, accounts and in general everything was separate and apart from email address and employee number nothing was being transferred. So when I was making the move, the India organization treated this as an employee resigning and leaving, and the US organization treated this as a new employee joining. This definitely was a very interesting process. Back in March just after I had got back from my TechReady trip me and my wife Ketaki had found out that we were expecting our first child. So this was definitely something that we would have to factor in when we were relocating. There were obviously travel restrictions on how late into the pregnancy she would be allowed to travel and I wanted to make sure that we moved over to Redmond well in time to get ourselves settled in and with some time on our hands till the baby was due. She was working with HP at the time and decided to take time off from work to lend a hand with the whole relocation thingy. Going through the visa process was a fun experience since the legal had taken care of practically everything and all we had to do was to show up and answer some questions. Of course, with me, nothing can be smooth sailing for long. We landed in New Delhi on the morning of the visa interview and proceeded to the US consulate. The US consulate in New Delhi is heavily barricaded with a number of security checks before you actually enter the visa processing centre. On the outside they have this huge queue to check if all documents are in order. Most of the people are sent back from here. Once this is done you go through a huge security gate that makes airport security checks seem like a joke. Inside, there is another line for finger printing and then the last long wait for the actual interview at the window. When we got there at around 11:45 for a 12:00 PM interview, there was this huge line on the outside for the document check. I had just resigned to the fact of a long wait when out of nowhere, I tripped and fell while getting off the sidewalk. There was a small trench like gap between where the side walk ended and the road began, and I had somehow managed to get my foot trapped in that gap, twisted it violently and crashed on the tar in full view of everyone there. For a moment I was writhing with pain, and had no sense of what was happening around me. From amongst the crowd this lady came up to us, and offered me some water, and actually ran back to her car parked some distance back to get me a pain reliever gel and a crepe bandage. Before we could ask her who she was, she had disappeared just as suddenly as she had appeared. Both me and Ketaki were just left wondering who she was – and also thinking there are indeed some kind hearted souls in this world. Thank you Mysterious Lady for helping us out during that brief moment. I was visibly limping after I got up, with my ankle looking like a soccer ball. The guards saw this and just let us through to the finger printing. Some good did come off the pain that I was in. Instead of waiting in line for an hour and a half we were just ushered in to the fingerprinting and then onward to the interview. We were out in a flat 30 minutes. We took a flight back the same evening. In a couple of days I had received my passport at my office and Ketaki had received hers at the home. We were all set, now we only needed the plane tickets. All of this was June. During the same period both of us were running about getting everything else done, we needed to close the rental agreement that we had for the place we were living in, sell the Opel Corsa we had, and get all our belongings packed and shipped. The relocation guys were tremendously helpful in arranging for a packing and moving company to just come over one day pack everything into neat boxes and send it out. After the packing was done, and the apartment was practically just four walls standing, we took the next flight out to Mumbai where we planned to spend a couple of days meeting our friends and family. The relocation specialist I was dealing with did an excellent job of getting us the flight itinerary that worked for us as well as getting us the temporary accommodation at such short notice. On the 19th of July at about 3:00 AM we boarded a BA flight from Mumbai to Heathrow. A eight hour really taxing and boring halt at Heathrow and we were onward for our direct connection to Sea-Tac. We arrived at about 5:30 local time, completely exhausted. The total trip time from boarding to alighting was close to 26 hours. Under normal circumstances that would have been bearable, but with a 7 ½ months pregnant wife, it was really taxing. A friend had come over to receive us and take us to the temp housing. We just crashed on getting there. We had arrived in Bellevue/Redmond on the 20th of July. Following Error Code Meaning When Thrown Bubbled Behavior How To Overcome -2140993974 SSO is not configured Failure when SSO has not been setup via Central Administration Critical error logged in ULS with error code. If SSO is not configured then configure from Central Admin. -2140993973 SSO Wrong Version SSO config setting or master secret has changed and change has not reflected. Not applicable. Self healing error. -2140995575 Failed to connect to SQL Server Creation of the SSO database fails. Critical error logged in ULS with error code.Error logged in application event log. Check SQL connectivity. Check permissions for the account running the MS SSO service. -2140995576 SharePoint Central administration virtual root not found The SSO folder under 12\Template\Admin\SSO does not exist. This check performed while configuring master secret server. Either a call into Configuration.ConfigureSecretServer via OM or the UI page to configure SSO can throw this error. Error logged in ULS with error code. Or error returned to calling function Repair the product installation.Most likely the files were not copied properly -2140995588 Web application not running with windows authentication. When a custom webpart is placed on a page in a non-windows auth web app. SSO CANNOT WORK WITH FORMS AUTHENTICATION. Or error returned to calling function. Check authentication providers for the web application. If you have a requirement to have the web app behind FBA, then SSO cannot work. -2140995589 SQL Server not supported. If the SQL server specified to host the SSO db is not greater than or equal to SQL Server 2000 SP3. Check SQL Server patching and version numbers. Minimum required is SQL Server 2000 SP3 -2147023143 Failure to connect to the Microsoft Single-SignOn Service. Failure to connect to the MS SingleSign On Service. Either when the service is not started or the service has a logon failure. Error logged in ULS with error code - The above information is indicative of the errors that you may encounter while working with Single SignOn on MOSS 2007. This is only for troubleshooting purposes. Single Sign On does not work with Forms Based AuthenticationSingleSignonException caught.Exception Code: 0x8062fffcSource: Microsoft.SharePoint.Portal.SingleSignonStackTrace: at Microsoft.SharePoint.Portal.SingleSignon.Credentials.SetUserCredentials(String strApplicationName, String strUserAccount, Object[] Args) at MethodName: SetUserCredentialsMessage: A call into SPS Single Sign-on failed. The error code returned was '-2140995588'. R.I.P A couple of weeks earlier, I saw an interesting issue. It was a normal day as far as days go in support and in comes this issue, where the person in question wants to investigate or rather should I say automate the process of creating IRM settings on document libraries. I wasn't working on this issue and a colleague took this over. But then somewhere it was lurking, how the hell do you do that? The natural starting point is getting a site/web context and going down to the list and then getting dirty with the properties exposed by the particular SPList object. So after finishing what I had on my plate, I dug into figuring out how exactly to set the IRM settings for a list using the object model. So here goes: Step 1 Enable IRM on the farm SPWebService svc = SPFarm.Local.Services.GetValue<SPWebService>();SPIrmSettings irmSettings = svc.IrmSettings;irmSettings.IrmRMSEnabled = true;//set true or false based on the situationirmSettings.IrmRMSUseAD = true;irmSettings.IrmRMSCertServer = "certificate server here";irmSettings.IrmChanges = irmSettings.IrmChanges + 1;svc.Update(); Step2 Set the IRM properties for a document library Phew! I am attending TechReady 4 at the moment. If you are there as well, I would really like meeting up with you. Reaching Seattle from India, was one heck of a journey. With more than 30 hours spent looking at the insides of a plane, we were lucky we didn't lose it, by the time we landed in Sea-Tac at midnight on Friday. Sessions started today morning, with some great enthusiastic pitches by Norm Judah and Steve Balmer on where Microsoft is heading in the near future. As one would expect, the focus is on the new wave of products that's just been rolled out. With Vista and Office 2007 System, hitting retail a week ago, everyone's pretty excited about whats happening in the connected application platform space. Again, given that we are looking at LongHorn server just round the corner, the objective as such is pretty much geared up towards making sure, that we as an organization are well oiled and the machinery is all smooth, in order to ensure that we can get amazing next-gen solutions out the door to our customers. All these products that just went retail are so well created, to fit together like, pieces of a giant jigsaw, the amount of solutions that can be created out of this jigsaw is phenomenally enormous to say the least.TechReady by itself is a unique Microsoft platform, that brings together the entire gamut of people in customer facing environments together from sales, premier field engineers, MCS, product support, everyone is in here right now in Seattle. As we said a week ago, the 'WOW' starts now! Right It's a very common task with SharePoint to create a custom Search web part. The objective ranges from the very intuitive – need to change the search results display - to the very complex perform some complex queries that are not possible Out of the Box. For a large part, customizing the search behavior in Microsoft Office SharePoint Server 2007 is very similar to how it was done in SharePoint Portal Server 2003. The major difference however is how the Search behaves. Since a great deal of time and energy has been spent in completely rewriting the underlying search engine, the results are very obvious. If you have not yet seen the MOSS search behavior, I will suffice it to say that it's pretty close to SharePoint 2003 search on steroids.For a large part, here's how a typical custom search would look like:referencing Microsoft.Office.Server.Search and Microsoft.SharePoint.Search depending on whether its OSS or WSS. /(); This is a typical lab scenario. But something interesting happens when you execute this on an actual farm deployment. Consider a deployment architecture as follows:You have web application on port 80 as contoso.com. So the root site collection on that web application will be. Contoso decides that they want to expose the same web application on the intranet, extranet as well as internet zones. So the admin goes ahead and creates extended web applications on port 80 for different URL zones. So now you have contoso.com on the default zone contoso-intra.com on the intranet zonecontoso-extra.com on the extranet zone. Note that the root site collections will now be identified as respectively. Since it's an extended web application, the content is the same across all URL's though the URL's accessed would be different for each. The implicit advantage this offers is the ability to expose the same content to different sets of users that are authenticated using different authentication mechanisms. Now consider say that the custom search web part that you created earlier is deployed in such a scenario. When a user fires a query on this custom query part, the query executes etc. No problems at all there. But look closer. If you hover over the hyperlinks for the individual items in the search results the URL's will actually be pointing to the URL corresponding to the default URL zone. This is not such a cool thing, since the user on the extranet does not need to know, what the actual content URL is.Now, just to cover all bases, execute a similar query from the Search box that ships with SharePoint. Irrespective of the zone you are browsing from, the URL's for the search result items are properly structured. What is it that SharePoint is doing but we are not in our code?PSS actually received a couple of calls on how to get past this seeming bug. For one, there are no articles online or even in the SDK at the moment that explain how this can be done. The answer popped up from a relatively uncanny place – how, SharePoint implements Search. Solution: Internally, there is a seemingly incongruous property that's being set to get past this weird problem. Now, for the record, the SDK does not glorify this property at all and if you use your favorite web search engine, there would be just a couple of lines describing what this does. //set some properties for the FullTextSqlQuery instancequery.ResultTypes |= Microsoft.Office.Server.Search.Query.ResultType.RelevantResultsl;query.QueryText = "some query";SPSite site = SPControl.GetContextSite(HTTPContext.Current);query.SiteContext = new Uri(site.Url);//and then execute the queryquery.Execute(); What is this doing? In essence it fetches the current site context from the HTTPContext and then specifies that the query executes under that specific context. Solution delivered and issue resolved.~harsh There have been a lot of great posts in the blogosphere on how to setup forms based authentication. Some of them:SharePoint Product Group Blog by Steve PeschkaNick="/"description="Stores and retrieves roles data from the local Microsoft SQL Server database" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /></providers></roleManager> - Membership Provider XML<membership defaultProvider="AspNetSqlMembershipProvider"><providers><remove name="AspNetSqlMembershipProvider" /><add connectionStringName="SqlProviderConnection" passwordAttemptWindow="10" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="false" passwordFormat="Hashed" description="Stores and retrieves membership data from the Microsoft SQL Server database" name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /></providers></membership>" server=[server name as string]<" server=[server name as string]</providers></roleManager> WebSSO (ADFS)- Modification to the Web Application Web.config ><add name="SingleSignOnRoleProvider" type="System.Web.Security.SingleSignOn.SingleSignOnRoleProvider, System.Web.Security.SingleSignOn, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" fs="" /></providers></roleManager> "/><add name="SingleSignOnRoleProvider" type="System.Web.Security.SingleSignOn.SingleSignOnRoleProvider, System.Web.Security.SingleSignOn, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" fs="" /></providers></roleManager> ASPNET Active Directory Provider Connection string<connectionStrings><add name="ADConnectionString" connectionString="LDAP://[domainname]/OU=UserAccounts, DC=[fqdnstringpart],DC=[fqdnstringpart],DC=com" /></connectionStrings> Membership Provider<membership defaultProvider="AspNetActiveDirectoryMembershipProvider"><providers><add name="AspNetActiveDirectoryMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ADConnectionString" enableSearchMethods="true" attributeMapUsername="sAMAccountName" /></providers><. Its been quite some time since the B2TR builds for Microsoft Office SharePoint Server 2007 were released. The builds have been released as patches and the general upgrade experience has been something that has helped us learn a lot about upgrades and patching scenarios. Amongst all the scenarios that we have seen there have been some that have been dominant in nature and affected a large number of users while there were some that are the on-off types and occurring in an essentially random manner. In this post I would be talking about some that have been very erratic and have had a significant impact: ------------ISSUE: Beta2 to Beta2 TR upgrade fails with a MSI error. ERROR: The installation of this package failed. Please see for more information." with the error code 1603EVIDENCE: Navigate to the %temp% directory, the Windows Installer logs would show a error as follows:Product: Microsoft Windows SharePoint Services 3.0 -- Error 1406. Setup cannot write the value QMEnable to the registry key \Software\Microsoft\Shared Tools\Web Server Extensions\12.0\WSS\Diagnostics. Verify that you have sufficient permissions to access the registry or contact Microsoft Product Support Services (PSS) for assistance. For information about how to contact PSS, seePSS10R.CHM. RESOLUTION: - Open the Registry Editor [Start->Run->regedit]. - Navigate to HKLM\Software\Microsoft\Shared Tools\Web Server Extensions\12.0\WSS\Diagnostics - Right Click, select New ->DWORD Value. Change the name to 'QMEnable' without the quotes. - Change the value to 0 ROOT CAUSE: This error is misleading to say the least. The error reported in the log files is about permissions, however, the patch installer searches the registry for the key QMEnable and does not seem to find it. However, it will also find that the component requiring this registry key is installed and hence will try to repair the installation. But in order to do so, it will try to use the value for this key from the registry which in the first place was not there. And hence the failure. ------------- ISSUE: Errors in the application event log. ERROR: ProblemDescription: Event Type: Error Event Source: DCOM Event Category: None Event ID: 10016 Date: <somedate> Time: <sometime> User: <domain\username> Computer: <computername> Description: The application-specific permission settings do not grant Local Activation permission for the COM Server application with CLSID {61738644-F196-11D0-9953-00C04FD919C1} to the user <domain\username> SID (X-X-X-XX-XXXXXXXXX-XXXXXXXXXX-XXXXXXXXXX-XXXXX). This security permission can be modified using the Component Services administrative tool. For more information, see Help and Support Center at. ISSUE: Enabling BDC with SSO authentication, throws the following error. ERROR: Exception thrown while performing the BDC query in Entity Picker Microsoft.Office.Server.ApplicationRegistry.MetadataModel.InvalidMetadataPropertyException: The Type name for the single sign-on provider is not valid. ---> System.TypeLoadException: Could not load type 'Microsoft.SharePoint.Portal.SingleSignOn.SpsSsoProvider' from assembly 'Microsoft.SharePoint.Portal.SingleSignOn, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c'. Sys... The xml tags in the BDC xml file are case sensitive and there was a recent update to the assembly type names. So you would need to replace the tag > To read as: > ~Harsh Blogged with Microsoft® Office® Word 2007 Beta2 TR As with v2, v3 also has seen its fair share of requests on how you can add an item to a folder in a list. Now, there are two types of lists that we are dealing with, lists that store documents and lists that store items. Internally they are identified by the list type which can be a DocumentLibrary or a GenericList. Actually the enumeration is quite huge, but these are the two values that we are concerned with. Both these types of lists can have folders and these folders can have items in them. Adding items to the folders though the UI is pretty straight forward. On the other hand, doing the same through code is a bit tricky. The SDK documents it to an extent but that is not very clear. Adding a document to a folder in a document library is the simplest SPSite site = new SPSite(""); SPWeb web = site.OpenWeb(); SPList list = web.Lists["Documents"]; SPListItemCollection folderColl = list.Folders; foreach (SPFolder folder in folderColl) { if (folder.Name == "TestFolder") { SPFileCollection fileColl = folder.Files; // Use fileColl.Add() to upload the file } } Adding an item to a folder for a generic list took me some time to figure out. The point where I got mislead was believe it or not a missing '/' character. There were a number of things I tried in getting to the SPListItemCollection representing the items inside a folder. However, all attempts at getting there ended up in recurrent loops [sic]. The simplest approach was of course using the SPListItemCollection.Add(). The moment I finally obtained that collection, from there on it took me several tries to get the actual syntax right. So here's the polished up code. SPList list = web.Lists["Tasks"]; for (int i = 0; i < folderColl.Count; i++) if (folderColl[i].Folder.Exists) SPFolder folder = folderColl[i].Folder; SPListItemCollection itemColl = list.Items; SPListItem item = itemColl.Add("/Lists/Tasks/TestFolder", SPFileSystemObjectType.File, null); item["Title"] = "AddedFromOM"; item.Update(); } All in a day's work. Cheerio /Harsh Blogged using Microsoft Office Word 2007 running on Microsoft Vista Publishing sites are just WSS sites with a special template. Though there is a separate namespace to help with the feature light-up specific to publishing sites. A very trivial scenario would be copying a page from a library, say the Pages library in a publishing site to say a Pages library in another Publishing site. For the sake of theory, let's consider that both the sites are part of the same site collection. Looking at the SDK the obvious choice would have been churning out a piece of code that looked like: SPSite site = new SPSite(""); PublishingSite psite = new PublishingSite(site); PublishingWeb pweb = PublishingWeb.GetPublishingWeb(site.RootWeb); PublishingPageCollection ppages = pweb.GetPublishingPages(); foreach (PublishingPage ppage in ppages) { if (ppage.Name == "Default.aspx") { ppage.ListItem.CopyTo("" + ppage.Name); pweb.Update(); } } This is what I would have agreed to as well. Until a very interesting behavior was brought to my attention. When the above code is executed, the file gets copied over as one would expect, however, what does not get copied over is the associated details such as the master page, the content types etc. In order to get a deep-copy so to speak one would need to get to the underlying SPFile objects and the code would in general look like: SPSite site1 = new SPSite(""); SPSite site2 = new SPSite(""); SPWeb web1 = site1.OpenWeb(); SPWeb web2 = site2.OpenWeb(); PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(site1.RootWeb); PublishingPageCollection pubpageCollection = pubWeb.GetPublishingPages(); foreach(PublishingPage pubPage in pubPageCollection) if(pubPage.Name == "SomePage.aspx" SPFile file = web1.GetFile(pubPage.Url); Byte[] binFile = file.OpenBinary(); string filename = file.Name; SPFolder destFolder = web2.GetFolder("Pages"); if(destFolder != null) { file.CheckOut(); destFolder.Files.Add(filename, binFile, true); file.CheckIn("temp"); file.Approve("temp"); } foreach(SPFile destFile in destFolder.Files) if(destFile.Name == filename) { destFile.Approve("temp"); } } With this you are all set to go. -Harsh As with SPS 2003, MOSS ships with some default web services as well. Most of them have been carried over from SPS 2003, whereas there are some that are newly introduced. The Lists webservice offers some interesting functions to perform remote operations on the lists in a site collection. Some of the web methods that are exposed are: Of these the last two might be the ones seeing the most usage. UpdateList and UpdateListItems, both are extremely handy when adding, modifying or deleting columns (in the case of the former) and list items (in the case of the latter). The SDK documents the usage of both but it does seem that there can be quite a few pitfalls while actually implementing these. Here are some examples:I am using the UpdateListItems here as this is the easiest Creating the lists web service reference and initializing all data required for making the actual call. PostLists.Lists lst = new TESTBED.PostLists.Lists(); lst.Credentials = System.Net.CredentialCache.DefaultCredentials; // Adding a new Item in this case a folder string strBatch = "<method id='1' Cmd='New'>" + "<Field Name='ID'>New</Field>" + "<Field Name='FSObjType'>1</Field>" + "<Field Name='BaseName'>testFolder</Field>" + "</Method>"; XmlDocument doc = new XmlDocument(); XmlElement el = doc.CreateElement("Batch"); XmlElement properties = doc.CreateElement("listproperties"); properties.InnerXml = ""; XmlElement newFields = doc.CreateElement("newFields"); XmlElement updateFields = doc.CreateElement("updateFields"); updateFields.InnerXml = ""; XmlElement deleteFields = doc.CreateElement("deleteFields"); deleteFields.InnerXml = ""; el.SetAttribute("OnError", "Continue"); el.SetAttribute("ListVersion", "0"); el.SetAttribute("PreCalc", "TRUE"); el.SetAttribute("ViewName", "{4A163CCB-3CE7-40B1-9EB5-A9568F355E3D}"); el.InnerXml = strBatch; // the actual call System.Xml.XmlNode node = lst.UpdateListItems("Documents", el); MessageBox.Show(node.OuterXml); Now let's look at the UpdateList webmethod. This is a bit complicated. So if you dont get it right the first time try try till you get it working! Hell no, just kidding. Setting the environment: PostLists.Lists lst = new TESTBED.PostLists.Lists(); lst.Credentials = System.Net.CredentialCache.DefaultCredentials; XmlNode ndList = lst.GetList("ASampleList"); XmlNode ndVersion = ndList.Attributes["Version"]; XmlDocument xmlDoc = new System.Xml.XmlDocument(); XmlNode ndDeleteFields = xmlDoc.CreateNode(XmlNodeType.Element,"Fields", ""); XmlNode ndProperties = xmlDoc.CreateNode(XmlNodeType.Element, "List",""); XmlAttribute ndTitleAttrib = (XmlAttribute)xmlDoc.CreateNode(XmlNodeType.Attribute,"Title", ""); XmlAttribute ndDescriptionAttrib =(XmlAttribute)xmlDoc.CreateNode(XmlNodeType.Attribute,"Description", ""); XmlNode ndNewFields = xmlDoc.CreateNode(XmlNodeType.Element,"Fields", ""); XmlNode ndUpdateFields = xmlDoc.CreateNode(XmlNodeType.Element,"Fields", ""); ndTitleAttrib.Value = "RobinSannerList"; ndDescriptionAttrib.Value = "New_Description"; ndProperties.Attributes.Append(ndTitleAttrib); ndProperties.Attributes.Append(ndDescriptionAttrib); Creating a new field: ndNewFields.InnerXml = "<Method ID='1'>" + "<Field Type='DateTime' DateOnly='TRUE' DisplayName='A_New_Test_Field' FromBaseType='TRUE' Required='TRUE' Description='sometextdescription'/>" + "</Method>"; Making the call: try { XmlNode ndReturn = lst.UpdateList("{18D0E90B-20B9-4931-96EB-5435D08532DC}", ndProperties, ndNewFields, null , null, ndVersion.Value); MessageBox.Show(ndReturn.OuterXml); } catch (Exception ex) { MessageBox.Show("Message:\n" + ex.Message + "\nStackTrace:\n" + ex.StackTrace); } Updating the field: ndUpdateFields.InnerXml = "<Method ID='2'>" + "<Field Type='DateTime' Name='A_New_Test_Field' DisplayName='SomeNewName'/>" + "</Method>"; try { XmlNode ndReturn = lst.UpdateList("{18D0E90B-20B9-4931-96EB-5435D08532DC}", ndProperties, null, ndUpdateFields, null, ndVersion.Value); MessageBox.Show(ndReturn.OuterXml); } catch (Exception ex) { MessageBox.Show("Message:\n" + ex.Message + "\nStackTrace:\n" + ex.StackTrace); } Deleting the Field: ndDeleteFields.InnerXml = "<Method ID='3'>" + "<Field Name='SomeNewName'/></Method>"; try { XmlNode ndReturn = lst.UpdateList("{18D0E90B-20B9-4931-96EB-5435D08532DC}", ndProperties, null, null, ndDeleteFields, ndVersion.Value); MessageBox.Show(ndReturn.OuterXml); } Of course all is not so rosy while you are doing this and there are some issues that have been trudging along since SPS2003. More on this in the next post. -Harsh
http://blogs.msdn.com/harsh/
crawl-002
refinedweb
6,440
55.95
"China's Ministry of Information Industry plans to add three top-level domain names: dot-net, and dot-com and dot-net. The move puts the Ministry of Information Industry in competition with ICANN for the dot-com domain, although China will use a different character set." is it me, or are 2 of those the same? [edited by: engine at 5:09 pm (utc) on Mar. 1, 2006] [edit reason] specifics ;) [/edit] I've owned a bunch of these alternate domain names for a while now. These are not romanized domain names at all. They are the Chinese language equivalent of .com, .net, & .org and were established by China as an alternative for the International Domain Name (IDN) proposed and implemented by the West. The Chinese were rightfully upset by the lackluster handling this solution was given in the outside world so they made their own. Like one of the linked articles says, these domains are really just third level variations of the .cn domain. For example my Chinese language .com domain also resolves at .com.cn. If .com, boy that'd be funny but clearly insane. I guess I can see it happening though, if you're in china, that you start resolving towards .com.cn if you type in .com with a special character set. This will cause some pain for global chinese types, but might not be that big of a deal for local types that are really just interested in chinese websites anyways. This could cause a mess of confusion. I guess it's how the chinese are trying to break the network effect that icann has by introducing this confusion and leveraging the .com / .net / .org brand. It's not like anyone can sue them for trademark infringement. How do you get to webmasterworld.com in China? Do you have to type webmasterworld.com.us? What about a link to webmasterworld.com? Is it just a romanized set of characters? I guess nations could start enacting a law that forces ISPs to use a root server which resolved .com to .com.localcountry, but boyo, that'd mess up the internet pretty bad. Or are you saying that this article is so superbly out to lunch and it's not even .com it's like .<kanji for com? company?> resolves to .com.cn ...? It's more like this: example.com.cn example.Chinese characters for com The system works somewhat like the old RealNames technology did. You need a browser plug-in or certain server software in place. Another example would be the new.net extensions. The Chinese technology works along the same lines. These are names that resolve within the namespace controlled by CNNIC. The bloggers got it all wrong in this case. This really isn't news. It's a misunderstanding. Basically, it doesn't seem too bad. They just went ahead and made their own TLDs with Chinese characters, unless I'm misunderstanding something. Where as, the corresponding reporter lacks the understanding of the real situation, the content of the report is severely inconsistent with the facts...
http://www.webmasterworld.com/forum32/1134.htm
CC-MAIN-2015-06
refinedweb
515
68.26
Logging Breadcrumbs Newer Sentry versions support logging of breadcrumbs in addition of errors. This means that whenever an error or other Sentry event is submitted to the system, breadcrumbs that were logged before are sent along to make it easier to reproduce what lead up to an error. In the default configuration the Python client instruments the logging framework and a few popular libraries to emit crumbs. You can however also manually emit events if you want to do so. There are a few ways this can be done. Breadcrumbs are enabled by default but starting with Raven 5.15 you can disable them on a per-client basis by passing enable_breadcrumbs=False to the client constructor. Enabling / Disabling Instrumentation When a sentry client is constructed then the raven library will by default automatically instrument some popular libraries. There are a few ways this can be controlled by passing parameters to the client constructor: install_logging_hook: - If this keyword argument is set to False the Python logging system will not be instrumented. Note that this is a global instrumentation so that if you are using multiple sentry clients at once you need to disable this on all of them. hook_libraries: - This is a list of libraries that you want to hook. The default is to hook all libraries that we have integrations for. If this is set to an empty list then no libraries are hooked. The following libraries are supported currently: 'requests': hooks the Python requests library. 'httplib': hooks the stdlib http library (also hooks urllib in the process) Additionally framework integration will hook more things automatically. For instance when you use Django, database queries will be recorded. Another option to control what happens is to register special handlers for the logging system or to disable loggers entirely. For this you can use the ignore_logger() and register_special_log_handler() functions: raven.breadcrumbs.ignore_logger(name_or_logger, allow_level=None) - If called with the name of a logger, this will ignore all messages that come from that logger. For instance if you have a very spammy logger you can disable it this way. raven.breadcrumbs.register_special_log_handler(name_or_logger, callback) - Registers a callback for log handling. The callback is invoked with given arguments: logger, level, msg, args and kwargs which are the values passed to the logging system. If the callback returns true value the default handling is disabled. Only one callback can be registered per one logger name. Logger tree is not traversed so calling this method with spammy_module argument will not silence messages from spammy_module.child. Typically it makes sense to invoke record() from it unless you want to silence a message based on its attributes other than level. raven.breadcrumbs.register_logging_handler(callback) - This is similar to register_special_log_handler()but it adds a global callback that is invoked for all log entries. Otherwise it works the same but multiple handlers can be registered. Manually Emitting Breadcrumbs If you want to manually record breadcrumbs the most convenient way to do that is to use the record() function which will automatically record the crumbs with the clients that are working with the current thread. This is more convenient than to call the captureBreadcrumb method on the client itself as you need to hold a reference to that. raven.breadcrumbs.record(**options) - This function accepts keyword arguments matching the attributes of a breadcrumb. For more information see Event Payloads. Additionally, a processor callback can be passed which will be invoked to process the data if the crumb was not rejected. The most important parameters: - the message that should be recorded. - data: - a data dictionary that should be recorded with the event. - category: - The category for this error. This can be a module name, or just a string that clearly identifies the crumb (eg: http, rpc, etc.) - type: - can override the type if a special type should be sent to Sentry. Example: from raven import breadcrumbs breadcrumbs.record(message='This is an important message', category='my_module', level='warning') Because crumbs go into a ring buffer, often it can be useful to defer processing of expensive operations until the crumb is actually needed. For this you can pass a processor which will be passed the data dict for modifications: from raven.breadcrumbs import record def process_crumb(data): data['data'] = compute_expensive_data() record(message='This is an important message', category='my_module', level='warning', processor=process_crumb)
https://docs.sentry.io/clients/python/breadcrumbs/
CC-MAIN-2020-45
refinedweb
721
54.83
A C program is built up from a collection of items such as functions and what we could loosely call global variables. All of these things are given names at the point where they are defined in the program; the way that the names are used to access those items from a given place in the program is governed by rules. The rules are described in the Standard using the term linkage. For the moment we only need to concern ourselves with external linkage and no linkage. Items with external linkage are those that are accessible throughout the program (library functions are a good example); items with no linkage are also widely used but their accessibility is much more restricted. Variables used inside functions are usually ‘local’ to the function; they have no linkage. Although this book avoids the use of complicated terms like those where it can, sometimes there isn't a plainer way of saying things. Linkage is a term that you are going to become familiar with later. The only external linkage that we will see for a while will be when we are using functions. Functions are C's equivalents of the functions and subroutines in FORTRAN, functions and procedures in Pascal and ALGOL. Neither BASIC in most of its simple mutations, nor COBOL has much like C's functions. The idea of a function is, of course, to allow you to encapsulate one idea or operation, give it a name, then to call that operation from various parts of the rest of your program simply by using the name. The detail of what is going on is not immediately visible at the point of use, nor should it be. In well designed, properly structured programs, it should be possible to change the way that a function does its job (as long as the job itself doesn't change) with no effect on the rest of the program. In a hosted environment there is one function whose name is special; it's the one called main. This function is the first one entered when your program starts running. In a freestanding environment the way that a program starts up is implementation defined; a term which means that although the Standard doesn't specify what must happen, the actual behaviour must be consistent and documented. When the program leaves the main function, the whole program comes to an end. Here's a simple program containing two functions: main #include <stdio.h> /* * Tell the compiler that we intend * to use a function called show_message. * It has no arguments and returns no value * This is the "declaration". * */ void show_message(void); /* * Another function, but this includes the body of * the function. This is a "definition". */ main(){ int count; count = 0; while(count < 10){ show_message(); count = count + 1; } exit(0); } /* * The body of the simple function. * This is now a "definition". */ void show_message(void){ printf("hello\n"); }.
http://publications.gbdirect.co.uk/c_book/chapter1/functions.html
crawl-001
refinedweb
486
69.92
Red Hat Bugzilla – Bug 217242 MonoDevelop package from yum is not complete Last modified: 2008-08-02 19:40:33 EDT Description of problem: MonoDevelop will install, however, when attempting to build and run one of the sample projects (or any other Gtk-sharp2 based project) the compiler can never find the type or namespace Gtk. Version-Release number of selected component (if applicable): 0.12 How reproducible: Not attempted to reproduce as of yet, seems very reproducible. Steps to Reproduce: 1. Install MonoDevelop using yum 2. Fire MonoDevelop up 3. Create a new Gnome# 2 project from the samples (File > New Project) 4. Attempt to Run it. It fails here. Actual results: Compiler throws error Expected results: Sample project should compile and run Additional info: I fixed this by running yum install gtk-sharp2* Which build on monodevelop are you using? 0.12-7 certainly has R gtk-sharp2-gapi in it (this is what is needed for the gnome# 2 stuff) It was the MonoDevelop found in the repositories, The Help>About menu says that it is MonoDevelop 0.12.0.0 The Yum install gtk-sharp2* said that it installed gtk-sharp2-docs and gtk-sharp2-devel. Running yum install gtk-sharp2* has NOT fixed the Gnome-sharp problems, however, Gtk# 2 projects are possible, just not Gnome# will not compile. rpm -qa monodevelop will help here. I'll look into the problem and should hopefully have a fix at some point soon [root@localhost $]# rpm -qa monodevelop monodevelop-0.12-7.fc6 monodevelop is currently at version 0.12-8 - I'm not sure if that's the case in fc6, but it is in rawhide - try the version from there and let me know if it's still causing a problem Is it still causing you a problem with the 0.12-8 release? This problem seems still present both on F7 and F8T1. Yesterday I needed a simple program, so I did a 'yum install monodevelop' on F8T1, run it, created a Gtk project without problems, but when I tried to compile the project, I got the error "The type or namespace 'Gtk' could not be found. Are you missing a using directive or assembly reference?(CS0246)". Then I booted to F7, and tried the same thing, and got the same error. After looking a bit, I found that installing gtk-sharp2-devel fixes it. I double-checked it now: a 'rpm -e gtk-sharp2-devel' makes the compilation fail, a 'yum install gtk-sharp2-devel' makes it work again. So it seems that monodevelop should depend on gtk-sharp2-devel. Trying the Gnome# 2.0 Project under Samples still fails. Again installing 'gnome-sharp-devel' fixes the error. Both gtk-sharp2-devel and gnome-sharp-devel are near 4Kb in size each, so I think is not a big problem. Instead, to be able to read the gtk documentation, I need to manually install 'gtk-sharp2-doc'. It would be nice to have it pulled automatically, but is a bit fat and not strictly required... Is this happening with 0.17b2 in rawhide? ping
https://bugzilla.redhat.com/show_bug.cgi?id=217242
CC-MAIN-2017-13
refinedweb
521
65.22
You.. Load the DLL with the following lines: from ctypes import * eyex_dll = CDLL(DLL_DIRECTORY + "/Tobii.EyeX.Client.dll") tracker_dll = CDLL(DLL_DIRECTORY + "/Tracker.dll") Then you can define some simple wrapper functions that call the DLL functions:() With these in place, it’s easy to bind them to voice commands using the handy dragonfly Function action.! 19 thoughts on “Getting Started with Eye Tracking” Hi James, My name is Tim and I am the user on the tobii forums that started the post concerning voice integration that we both have been updating. I’m very interested in getting this working with VAC but dont have the coding prowess that you do to do so. I read through your blog and DLed the tracker.dll from github and would greatly appreciate any help you could give in getting the above wrapper to listen for keypresses. Can this be done with an elseif statement or a while loop to trigger off the two or three keys that we want with sendinput or something similar? I tried to use AHK to send the virtual key code, the hardware scan code, and key down key up commands but it still wont trigger from Tobii’s prebuilt app. If i use sendplay instead of sendinput it bypasses tobii and still sends the key through voice commands but at the same time doesnt trigger at a low enough level for what im guessing would be tobii’s keyboard hook to see it and trigger the mouse movement. Thanks so much for any help! Tim Hi Tim, welcome to the site! I don’t think I’m familiar with the voice command software you’re referring to, but I’ll do my best to help. First, the key thing to understand is that my wrapper does not make software keypresses suddenly start working. Instead, it offers a few simple functions you can call *instead* of the software keypress functions. You can see the list of these functions in the header file: Hence, it requires that your voice command software be able to call into a DLL. This definitely works in Python using Dragonfly with Dragon NaturallySpeaking, but the process is going to be different if you’re using a different environment (it should be the same in any other Python environment, though). If your voice command software can only send keypresses, but cannot execute arbitrary code, then I’m afraid my solution won’t work. Hopefully that is not the case here! James, I checked per your suggestion and confirmed VAC can’t call into a DLL. So I have downloaded python and dragonfly and watched a few tutorials on dragonfly commands in hopes of giving that a try instead. So far I have copied your commands above into a .py file and modified them with the path of the two DLLs below. I read that since backslash is used in windows path’s that I need a second backslash as a terminator. ————————– Traceback (most recent call last): File “C:Python27Libsite-packagespythonwinpywinframeworkscriptutils.py”, line 326, in RunScript exec codeObject in __main__.__dict__ File “C:Python27Scriptseyetracker.py”, line 2, in ctypes.CDLL(“c:\Program Files (x86)\Tobii\Tobii EyeX\Tobii.EyeX.Client.dll”) File “C:Python27libctypes__init__.py”, line 365, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Error 127] The specified procedure could not be found ————————— import ctypes ctypes.CDLL(“c:\Program Files (x86)\Tobii\Tobii EyeX\Tobii.EyeX.Client.dll”) ctypes.CDLL(“c:\Program Files (x86)\Tobii\Tobii EyeX\Tracker.dll”)() Then after I can get this working, I assume I need to map the actions. I found a tutorial for mapping keys like this class KeystrokeRule(MappingRule): mapping = { “enter []” : Key (“enter:%(n)d”), And tried to apply it to the function commands: class KeystrokeRule(MappingRule): mapping = { “connect tracker” :def connect(), or “connect tracker” :tracker_dll.connect(), “disconnect tracker” : “move” : “click” : If you have any suggestions on the dll path error and/or mappings once again your help is greatly appreciated. Thanks again so much for your help, Tim You are really close to getting this to work. The DLL error bit me first too, there are couple things to double check: 1) You are right that backslashes would need to be escaped, but note that in my code I use forward slashes which are perfectly legal in Windows Python and are less prone to escaping errors. Try using that. 2) Try opening the tracker DLL in dependency walker, and it will tell you what dependencies you are missing. I will save you the Google search and tell you you probably need to download this:. I believe you only need the 32-bit version, but it wouldn’t hurt to install both if you have a 64-bit processor. Next, you need to use a slightly different syntax for declaring these macros. Here’s what it looks like: “(I|eye) connect”: Function(connect), “(I|eye) disconnect”: Function(disconnect), “(I|eye) print position”: Function(print_position), Also, make sure other dragonfly macros in general are working before trying to get this working. I’m going to post my dragonfly macros within the next couple weeks (hopefully the next couple days), although they will contain a bunch of stuff you won’t want, so it is still worth figuring this out on your own. Thanks for powering through this, I promise it’ll be sweet when you get there! Hello James, thank you for sharing your solution, I was little disappointed when I found out that EyeX doesn’t handle virtual keystrokes at the moment. I cannot work with Dragonfly, since my native language isn’t English, but I have different software that can do various stuff. One of them is running an arbitrary executable file on a voice command. Would it be, in principal, possible to create a python script, which would call functions connect() and activate_position() directly? So far i didn’t have much luck with this – using your example, I end with error messages like result = tracker_dll.connect() NameError: global name ‘tracker_dll’ is not defined OR NameError: global name ‘c_double’ is not defined I’m not very skilled in Python, but I think I can get the basics in couple of days – the main question is, whether the solution above can be realized using your DLL. Hi Michal, My first snippet of Python code was broken; please try again now that it is fixed. I guess I must’ve mixed up a couple versions of the code. I’m not sure how well your approach will work exactly as described. The trouble is that as soon as the Python process exits, the eye tracker context will be destroyed and disconnect. There are couple ways of solving this. The quick and dirty way would be to create a script that does everything you want in one go (connect, activate position, then quit). The problem is this is likely to be slow due to reconnecting each time. A cleaner approach would be to create a long-running Python server that you start separately one time and then have your executable file just send a request to your server. You would just need to pick some interprocess communication mechanism to send and receive the request. Another approach is to make the long-running Python process do the work of listening for virtual keypresses and then triggering actions. It sounds like that’s what most folks really want. Thank you, James. I think that your last suggestion is the best one. I was able to make it running very fast despite the fact that I’ve never worked with Python before. I also use the function Warp sometimes. Do you think it can be controlled by voice, too? Glad to hear this worked for you! The warp function is not built into the API, but it shouldn’t be too hard to do this yourself using Python libraries to move the mouse pointer, using the function in my DLL to get the last gaze position. I do this using Dragonfly, which is in turn using Python libraries to handle the mouse movements. Here is the full list of actions currently built into the API, for reference: I’m looking forward to the zoom functions. I can add support for this when it is available. I tried one of the more expensive eye tracking solutions a few years ago, and wasn’t very impressed. The natural flickering of my eyes made it nearly impossible to hone in on my targets. However, I didn’t have control of when the cursor moves like you do, and it never occurred to me to separate the motion of the eye tracker cursor from the motion of the system cursor. I read that in your article (where you have a function for moving the cursor) and thought to myself, what a good design choice. It makes me want to give eye tracking a second try. Thanks, let me know how it goes! Of course, the one downside of separating these actions is that it is slower. But usually I use eye tracking as a last resort, so I’m just happy to have something (and it’s certainly faster than using “mouse grid”). Don’t you need some kind of hardware to do eye tracking as well? I assume that isn’t free. Yes, I’m using the Tobii EyeX eye tracker, which is $140. I’ve got a short comparison of options in the second paragraph of my post. I’m surprised it’s that cheap; I’d heard I trackers were in the $1000 range. Do you have to calibrate it each time you sit down? One time calibration is all that is necessary. The accuracy is so-so, though. Most trackers are way more expensive, even from the same company. I got a promotional email from Tobii encouraging me to step up to their next best eye tracker… at only 20x the price 🙂 Just wanted to shout out, Thanks! For writing this up and making that DLL wrapper. It took me a while to get it working with my limited experience, but now I can voice warp too! Hm. This is unrelated maybe, but sometimes I’m able to use the Tobii EyeX – Pointer Interaction – Warp on mouse movement, to move scroll bars and windows when I touch the mouse, when usually it does not. But, I haven’t isolated what causes it to start working… I find it useful actually, and wondered if you’ve run into it? In case it’s something the dll accidently causes. Thanks for the shout out 🙂 I haven’t ever noticed mouse warping. I’d be really surprised if my DLL caused that; it shouldn’t. If you find it useful though, I suppose you can just enable it in the settings permanently. Hi James. Thanks alot for making this publicly available. Did you have to update/change anything when you changed to 4C? I just bought a 4C and trying to make your hack work. but nothing really happens. At the moment I’m just using the precompiled DLL found at your “releases” in your github, and then I found the Tobii.EyeX.Client. I placed the two files alone in a directory which I fed to the “local.py” file. when I load natlink no tracker errors appears, and the functions seem to work i.e. it recognizes the commands “eye connect”, “eye print position” and “eye move “. However there are no reaction to them, the cursor doesnt move and nothing is printed. Do you have an idea of what could be the cause? If i have to compile a DLL myself: I cant find a “sample” folder in my Tobii SDK ( i guess that is just the folder called “Tobii” installed per default in the program-files directory? I think I did have to rebuild this at some point a while back. I’ve released the version that I’m currently using: Let me know if you still have trouble. Splendid, the few commands i tried works flawless. Thanks alot.
http://handsfreecoding.org/2014/11/16/getting-started-with-eye-tracking/
CC-MAIN-2018-34
refinedweb
2,016
71.44
Write your question here. hello everyone, ok so i have an array matrix called tmat,,and i know that in every row of tmax there are values which repeat two times...and am writing a code to extract the values WHICH DOES NOT REPEAT into another matrix called tcopy...the codes compiles fine...and it writes nicely to file...but without the desired result...so is surely me ...can some one check it out and tell me where am doing it wrong? thanks One last question...how can i get the array tcopy written to file in the form 5x3...and not all the figures in line one after the other? i mean i wish to see the matrix like a matrix on file..not like a list of numbers..thank you again Code: #include <iostream> #include <fstream> #include <vector> using namespace std; const int R = 5; const int C = 5; const int R1 = 5; const int C1 = 3; void extract (int mat [R][C]); void filling (int mat [R1][C1], int value); int control= 0, st_r = 0, st_c = 0, found = 0; int rr = 0, cc = 0 ; int tcopy [5][3]; int main (){ int tmat [5][5] = {{1,2,3,4,4,}, {7,4,5,7,6,}, {4,0,7,9,0,}, {4,5,5,9,0,}, {4,5,9,9,0,}, }; extract(tmat); fstream file; file.open("oppose.txt", ios::in | ios::out); if (file.is_open()){ for(int k= 0; k< 5; k++) for(int i = 0; i <3; i++) {file<<tcopy[k][i]<<", ";} cout<<"copied to file successfully"; file.close(); } else cout<<"cound not open file..."; return 0; } void extract (int mat [R][C]){ while (control != R*C) { int k = mat [st_r][st_c]; for(int i = 0; i<R ; ) for (int c= 0; c<C; c++) { { if (k == mat [i][c]); //over here i want to loop over the whole row. found++;}// is it one at a time? or am looping the row? if (found < 2) {filling(tcopy,k );} found = 0; if(st_c < C) st_c++; else{ st_c = 0; if(st_r < R) st_r ++;} i++; } control ++; } } void filling (int mat [R1][C1], int value) { mat[rr][cc] = value; if (cc < C1) cc++; else { cc = 0; if(rr<R1) rr++;} }
http://forums.codeguru.com/printthread.php?t=538741&pp=15&page=1
CC-MAIN-2013-48
refinedweb
369
82.85
Here's an example of a better way to pass arguments to main() methods of Java classes than using String[] args. First, pass two named parameters, user and level, that come into a GamePlayer class: java -Duser=champ -Dlevel=expert GamePlayer Classes will use them as follows: public class GamePlayer { public static void main( String[] args ) { String user = System.getProperty( "user", "unknown" ); // get user name or use 'unknown' System.out.println( "Welcome to Inter-Galactic Rooster Race: " + user ); GameStarter.start(); // start game which uses the start level } } class GameStarter { // use arguments in other classes as well static void start() { System.out.println( "Your level " + System.getProperty( "level", "beginner" ) ); } } The parameters are preceded by a -D, to indicate that they are named properties. The arguments will not be available in the String argument array of the main() method. With -D parameters, you do not have to worry about the positions, and can refer to the arguments by name. You can use the arguments in other methods and even other classes, without having to pass them around. A second parameter to System.getProperty() is used as a default value in case the named parameter has not been passed. You can use this code to list all passed properties, including system properties, to standard output: System.getProperties().list( System.out ); // get properties from system and list them to stdout Please enable Javascript in your browser, before you post the comment! Now Javascript is disabled. Your name/nickname Your email WebSite Subject (Maximum characters: 1200). You have 1200 characters left.
http://www.devx.com/tips/Tip/13081
CC-MAIN-2015-48
refinedweb
256
57.16
Remoting in .NET An example that will help you understand how the remoting mechanism works in .NET. This Article Covers .NET Web Services RELATED TOPICS Let other users know how useful this tip is by rating it below. Got a tip or code of your own you'd like to share? Submit it here! .NET Remoting provides a way for application in different machines/domains to communicate with each other and offers a powerful yet easy way to communicate with objects in different app domains. Any object that executes outside the app domain can be considered as objects are accessed via channels. Channels can be thought of as transport mechanism to pass messages to and from remote objects. All the method calls along with the parameters are passed to the remote object through the channel via HTTP or TCP. I have also used the utility SOAPSUDS.EXE, which is used to generate proxies for the remote component. The following example will help you understand the remoting mechanism in .NET. I chose to use C# for this example. We will create a server that will have a method. Step 1: Creating the server server.cs on machine1 using System; using System.IO; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels;otingConfiguration.RegisterWellKnownServiceType(typeof . On the console you should see: Server ON at 1095 Press enter to stop the server... To check whether the HTTP channel is binded to the port, open the browser and type:. You should see a XML file describing the service. Step 2: Creating client proxy and code on machine2: Creating a client proxy requires that you use a Microsoft tool called soapsuds.exe. This utility ready the XML description and generates a proxy assembly used to access the server. Go to a different machine and type in: soapsuds -url:http:// This will create a proxy called Server.dll that will be used to access the remote object. Client code TheClient.cs > using System; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Http; using Server; public class TheClient { public static void Main (string[] args) { HttpChannel c = new HttpChannel (1077); ChannelServices.RegisterChannel (c); ServiceClass sc = (ServiceClass) Activator.GetObject (typeof(ServiceClass), "http:// Source: DotNetExtreme.com Start the conversation
http://searchwindevelopment.techtarget.com/tip/Remoting-in-NET
CC-MAIN-2017-51
refinedweb
375
52.36
NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab. Support Forum » Create a library Hi all! Hope everyone that is still utilizing these forums is doing well. It has been a while again...man life just doesn't seem to slow down much right now. Anyways, I have been looking at creating my own library for some of the sensors/devices that I have written code for, ie. BMP085 pressure sensor, EEPROM. However, I have a couple of questions/thoughts. How does one go about building something like the libnerdkits library? Are there any resources that can be found on the subject? I have read through: This tutorial However, it seems to leave out quite a bit of information. Are there certain requirements, as in is lib a required prefix before the library name? Also, looking at the uart.h and uart.c files in the libnerdkits folder: first, uart.c // uart.c // for NerdKits with ATmega168, 14.7456 MHz clock // mrobbins@mit.edu #include <stdio.h> #include <stdlib.h> #include <avr/io.h> #include <inttypes.h> #include "uart.h"); } void uart_write(char x) { // wait for empty receive buffer while ((UCSR0A & (1<<UDRE0))==0); // send UDR0 = x; } uint8_t uart_char_is_waiting() { // returns 1 if a character is waiting // returns 0 if not return (UCSR0A & (1<<RXC0)); } char uart_read() { // wait while(!uart_char_is_waiting()); char x = UDR0; return x; } int uart_putchar(char c, FILE *stream) { uart_write(c); return 0; } int uart_getchar(FILE *stream) { int x = uart_read(); return x; } And uart.h #ifndef __UART_H #define __UART_H #include <inttypes.h> #include <stdio.h> FILE mystream; void uart_init(); void uart_write(char x); uint8_t uart_char_is_waiting(); char uart_read(); int uart_putchar(char x, FILE *stream); int uart_getchar(FILE *stream); #endif Why does the .h file and .c files both have some of the same include files? They both include inttypes and stdio. I thought that the header basically was read and took care of all the include files. Is this not the case? Or is it because two of the prototypes defined in uart.h are declared integers? It just seems redundant. Do I need to "make" the library with a makefile? Or is there a way to do it manually? Does anyone have any advice or a "formula" for making libraries? Again, Thanks for sticking in here, I appreciate all of your help! Dave Hi Dave, one of the key points from the article is: That's the one that has caught me in the past. What do you see as missing? Ralph Putting .c source and .h includes into a common folder does not make a library. It is just a common directory where reusable code may reside. A true library is a file containing precompiled objects. Although there exists both static and dynamic linking, in the world of the nerdkit we deal only with static linking. With a real library, the linker will reference only the library file instead of one or many individual objects. So the libnerdkits directory is just a common directory. It can be named anything you wish as the name doesn't make any difference. Likewise, a library file, typically a .o, can be named anything you wish. It's what's inside that makes the difference. From an organizational perspective it is good to have a common place for reusable code to reside. This is particularly helpful in larger projects with many .c and .h files used by many other .c files. In the tutorial above, Dean is showing a method that helps to organize and manage reusable code. At the very end he says you may want to put the common objects in a library for distribution. His method of organization is not a library, it is just one way to have a common directory for reusable code. Another way is to put all your reusable code in a directory named libnerdkits. It could just as easily be named common or share. As for the include<avr/whatever>, it doesn't really matter to the compiler how many times they are included because it only uses the first one it comes across. Hard to say why some authors put/leave useless includes into header or source files. NOTER, Thanks for the information. This helped me to understand the naming concept better.. Jim Noter, As always you really help me(and everyone else) understand things easier. So, how does one go from just "managing" reusable code in a common directory to a full blown library? (I would imagine some sort of a makefile leading to a .o file correct? Or is it not necessary to go through the trouble? Thanks again for your help! I was building and using a library for a while but now just directly link the objects again. I don't use a lot of shared code so it doesn't make much difference to me. Usually I just put code for the usart in the program I'm writing because it's just a couple of small functions and it's easier to change them there. I use the avr-gcc util/delay's now and seldom use the lcd display and typically my program has no includes from a common directory. Makes it easier to send it or post it for someone else too. I said above the library was a .o and the name doesn't matter. After a quick review of the documentation I realize I forgot it's a .a and the name must begin with lib. Here's the makefile I used to build the nerdkits library - # # compile all c source and insert objects into a library file (libNerdkit.a) # all: $(patsubst %.c,%.o,$(wildcard *.c)) %.o: %.c %.h #avr-gcc -g -O0 -c -Wall -mmcu=atmega168 $< -o $@ avr-gcc -g -O0 -c -Wall -mmcu=atmega328p $< -o $@ avr-ar rcsv libNerdKit.a $@ clean: -rm *.o Then to use it in a make file this is the rule and recipe I used - %.o: %.c ../libnerdkits/libNerdKit.a Makefile avr-gcc -g -Os -Wall -mmcu=$(MCU) -mcall-prologues \ -Wl,-u,vfprintf -lprintf_flt -Wl,-u,vfscanf -lscanf_flt -lm \ -Wl,-Map=$@.map \ $< -o $@ ../libnerdkits/libNerdKit.a \ -DF_CPU=$(F_CPU) -DBAUD=$(PGM_BAUD) Please log in to post a reply.
http://www.nerdkits.com/forum/thread/2799/
CC-MAIN-2020-29
refinedweb
1,037
68.77
<< Name:GoogleSearch orJonathan Sum5,039 Points Create a function named string_factory that accepts a list of dictionaries and a string. Return a new list build by usin dicts = [ {'name': 'Michelangelo', 'food': 'PIZZA'}, {'name': 'Garfield', 'food': 'lasanga'}, {'name': 'Walter', 'food': 'pancakes'}, {'name': 'Galactus', 'food': 'worlds'} ] string = "Hi, I'm {name} and I love to eat {food}!" def string_factory(dicts, string): return_list=[] for intel in dicts: list1.append(string.format(**dicts)) list1=return_list return return_list #i know i need to change list1 to return_list, but i want to know why the code from above doesn't work? 2 Answers Name:GoogleSearch orJonathan Sum5,039 Points Micheal Allen That is what i am asking. I know i can pass it if i removed "list1=return_list and change list1 to return_list. I want to know why. Is that because it is in the for loop? Micheal Allen19,311 Points What you're doing in your version of the code is asking to format the whole list of dictionaries instead of single dictionary from the list. so swapping **dicts ( the list of dictionaries ) to **intel ( a single dictionary from the list of dictionaries) fixes the problem. Name:GoogleSearch orJonathan Sum5,039 Points Micheal Allen That was my mistake. I have done this changlle more than 10 times. It is just i mistakly put the **dicts,instead of **intel. This is just a answer key from google search. I just don't know why i can't use these code. I guess that is because in the "for loop". list1=return_list return return_list Micheal Allen19,311 Points Ahh I see what you mean, heres your code with comments on why: def string_factory(dicts, string): return_list = [] for intel in dicts: list1.append(string.format(**intel)) # you are trying to append to a variable (list1) which hasn't been defined yet, # return_list.append(string.format(**intel)) would work as return_list has already # been defined outside of the loop and before the loop list1 = return_list # list1 will define itself as return_list every time # the 'for loop' loops ( 4 times in this case) return return_list # return return_list would be returning an empty list as return_list still = [] Hope this helps Micheal Allen19,311 Points Micheal Allen19,311 Points Hey Jonathan, Seems like you are trying to use when it should be You might want to change the list1.append to return_list.append aswell as you've already created an empty list to append the strings to. Here's the modified version of your function with comments for you to refer to, you should be able to pass the code challenge with it.
https://teamtreehouse.com/community/create-a-function-named-stringfactory-that-accepts-a-list-of-dictionaries-and-a-string-return-a-new-list-build-by-usin-2
CC-MAIN-2022-40
refinedweb
431
70.23
I have a parent and a child script. I am trying a command (WLST nmConnect) from the child script but I got a "NameError: nmConnect" error message when I tried. The strange thing is that I can call it from the parent script! So I think the system variables (e.g. CLASSPATH) are not passed to the child script? parent script import wl ... wlmanager = wl.WeblogicManager() ... if not wlmanager.connect_to_nodemanager(ssl, domainName, userConfigFile, userKeyFile): .... child script def connect_to_nodemanager(self, p_ssl, p_domainName, p_userConfigFile, p_userKeyFile): try: nmConnect(domainName=p_domainName,userConfigFile=p_userConfigFile,userKeyFile=p_userKeyFile) return True except: ... return False So when I put the nmConnect to the parent script, it worked... Could you please help? Thanks, V. I had to add the next import: from wlstModule import * it is not needed in the parent but it is in the child. Similar Questions
http://ebanshi.cc/questions/5624868/jython-calling-command-from-child-script
CC-MAIN-2017-04
refinedweb
139
52.15
RH-53391 is fixed in the latest WIP Hi Dan, I tested GhPython in WIP 7.0.19176.14015 (06/25/2019) and indeed the ‘Input is path’ option is present and I’m able to execute a script, but how do I get access to the input and output variables? See you Flo you should type, in the .py file, the same things you would type in the GhPython editor. Where is the confusion coming from? Thanks, Giulio Giulio Piacentino for Robert McNeel & Associates giulio@mcneel.com Hi Giulio, no unfortunately that is not working. Here is my test: test.py (34 Bytes) GhPyWipTest.gh (13.1 KB) The embedded script works as expected, it can access the input ‘myStr’. The script streamt from a file in the old way works as expected. The script given by filename in the new way does is executed, but not have access to the GhPython inputs and outputs. I’m I missing something? See you Flo Hi Florian, yes I see the problem. I’ll try to have it fixed by Tuesday, when the next WIP should go out. Thanks, Giulio Giulio Piacentino for Robert McNeel & Associates giulio@mcneel.com Hi Giulio I’ll try to have it fixed by Tuesday Cool. If you really find the time to work on the problem, could you briefly explain how you solved it? I’d be interested because right no I do not see a nice solution. One quick fix of course is to load the file and use the ExecuteScript to execute the script, but that would not solve the debugging issue. The only thing I can think of is to use ExecuteScript to execute something like this: import __builtin__ __builtin__.myStr=myStr import importlib extSript=importlib.import_module("test.py", package=None) reload(extSript) This gives test.py access to myStr, but it seems like a dirty hack (and I’m not even sure it how this would look like for outputs). See you Flo I am adding a new method to ScriptScope: ScriptScope.ExecuteScriptInScope(). You are right: with the previous method it would not work. Hi Giulio, I tested the latest WIP version and it work as expected now. This is a really nice feature as it allows to edit and debug GhPython scripts in an external IDE. I’m using Visual Studio 2019 but, VS Code, Eclipse or any other IDE would work just as fine. See you Florian Any chance you guys could collaborate on a step by step guide to setting things up to edit and debug GhPython scripts in Visual Studio? Great if it could end up in the Developer docs, too. I’ve read through this thread and looked elsewhere: the info may all be there, but if it is, it’s scattered and hiding from me! Regards Jeremy Hi Jeremy Any chance you guys could collaborate on a step by step guide to setting things up to edit and debug GhPython scripts in Visual Studio? Sure, I already had two requests buy other people, and I started working on a detailed step by step guide, but I did not find the time to finish it. But it’s still on my to do list. See you Flo I also heard that @DavidLeon was going to write something for the Dev Docs. I think he is on vacation this week, though. I’ve added a step-by-step guide on how to make this work in the DevDocs. Happy debugging! Hi @DavidLeon, @piac Thanks for the Guide! However, following the set up procedure (with Visual Studio 2017), I get the following error when I try to use the component: Edit: FYI after installing the latest build of the WIP the error message no longer appears and the component runs. Regards Jeremy I have to run the “Attach to process” step each time I start a new GH session: is there a way to make the settings stick to the VS project? @jeremy5 if you have already attached once in the VS session you can quickly attach again with Debug > Reattach to Process (Shift + Alt + P) Is that what you are looking for? Hi @DavidLeon, Thanks, that is helpful, but I would like to be able to make the setting sticky between sessions. Typing the string is hardly onerous so the question doesn’t warrant effort, but this would be a small nicety, should anyone already know the answer. Jeremy I don’t suppose this can be made to work in V6? The “Input as Path” option doesn’t exist. It cannot, sorry. A post was split to a new topic: Problems connecting to VS2019 debugger from Python
https://discourse.mcneel.com/t/ghpython-debugging-in-visual-studio/85096/14
CC-MAIN-2022-21
refinedweb
780
81.22
Calling BLAS Functions that Return the Complex Values in C/C++ Code Complex values that functions return are handled differently in C and Fortran. Because BLAS is Fortran-style, you need to be careful when handling a call from C to a BLAS function that returns complex values. However, in addition to normal function calls, Fortran enables calling functions as though they were subroutines, which provides a mechanism for returning the complex value correctly when the function is called from a C program. When a Fortran function is called as a subroutine, the return value is the first parameter in the calling sequence. You can use this feature to call a BLAS function from C. The following example shows how a call to a Fortran function as a subroutine converts to a call from C and the hidden parameter resultgets exposed: Normal Fortran function call: result = cdotc( n, x, 1, y, 1 ) A call to the function as a subroutine: call cdotc( result, n, x, 1, y, 1) A call to the function from C: cdotc( &result, &n, x, &one, y, &one ) has both upper-case and lower-case entry points in the Fortran-style (case-insensitive) BLAS, with or without the trailing underscore. So, all these names are equivalent and acceptable: Intel® oneAPI Math Kernel Library cdotc, CDOTC, cdotc_, and CDOTC_. The above example shows one of the ways to call several level 1 BLAS functions that return complex values from your C and C++ applications. An easier way is to use the CBLAS interface. For instance, you can call the same function using the CBLAS interface as follows: cblas_cdotc( n, x, 1, y, 1, &result ) The complex value comes last on the argument list in this case. The following examples show use of the Fortran-style BLAS interface from C and C++, as well as the CBLAS (C language) interface: Example "Calling a Complex BLAS Level 1 Function from C" The example below illustrates a call from a C program to the complex BLAS Level 1 function zdotc(). This function computes the dot product of two double-precision complex vectors. In this example, the complex dot product is returned in the structure c. #include "mkl.h" #define N 5 int main() { int n = N, inca = 1, incb = 1, i; MKL_Complex16 a[N], b[N], c; for( i = 0; i < n; i++ ) { a[i].real = (double)i; a[i].imag = (double)i * 2.0; b[i].real = (double)(n - i); b[i].imag = (double)i * 2.0; } zdotc( &c, &n, a, &inca, b, &incb ); printf( "The complex dot product is: ( %6.2f, %6.2f)\n", c.real, c.imag ); return 0; }], b[N], c; n = N; for( i = 0; i < n; i++ ) { a[i] = std::complex<double>(i,i*2.0); b[i] = std::complex<double>(n-i,i*2.0); } zdotc(&c, &n, a, &inca, b, &incb ); std::cout << "The complex dot product is: " << c << std::endl; return 0; } Example "Using CBLAS Interface Instead of Calling BLAS Directly from C" This example uses CBLAS: #include <stdio.h> #include "mkl.h" typedef struct{ double re; double im; } complex16; #define N 5 int; } cblas_zdotc_sub(n, a, inca, b, incb, &c ); printf( "The complex dot product is: ( %6.2f, %6.2f)\n", c.re, c.im ); return 0; }
https://software.intel.com/content/www/us/en/develop/documentation/onemkl-linux-developer-guide/top/language-specific-usage-options/mixed-language-programming-with-the-intel-math-kernel-library/calling-blas-functions-that-return-the-complex-values-in-c-c-code.html
CC-MAIN-2021-10
refinedweb
547
60.04
SQL Database This article will show you to create a WinForms application and access data stored in the cloud. It shows how you can connect to the Azure SQL database instance from a blank WinForms project as well. Step 1: Setup a Database Go to your Azure portal, then SQL Databases > Add, and fill all required information. The process is fairly easy, however if you need detailed information you can check this article. You will need to add a firewall rule for your IP Address. Otherwise you will be not able to connect. Detailed information is available here. Step 2: Create the Table Once the database is created you can connect from Microsoft SQL server Management Studio. You need to take the server name from the database overview page in the azure portal. Use the name and password from step 1. Once you are connected you can interact like with any other database. For this example execute the following query in order to create a table. CREATE TABLE Movies ( ID int, Name varchar(255), Director varchar(255), YearOut varchar(255), ); Step 3: Creating the Winforms Application First create the WinForms project, to do that create a blank Telerik UI for WinForms project and add a RadGridView and two buttons to it. The application design should look like this: Step 4: Create Entity Framework Model. Install the Entity Framework from the Nuget manager. Add a new item to your project and choose ADO.NET Entity Data Model from the list of available items. Choose Code First from database from the Choose Model Contents dialog. . Click on New Connection... and input the server name and credentials which you can obtain from the Azure portal. Choose the SQL Server Authentication option to log on to the server. Choose whether or not to include the sensitive data in the connection string, choose a name for it and click Next. Pick the database object you wish to include and click Finish. . Step 5: Define the Context Object Entity Framework will create the context object but you need to modify it and include the business object. Your code should look like this: public partial class MoviesModel : DbContext { public MoviesModel() : base("name=MoviesModel") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { } public IDbSet<Movie> Movies { get; set; } public new IDbSet<T> Set<T>() where T : class { return base.Set<T>(); } } public class Movie { public int ID { get; set; } public string Name { get; set; } public string Director { get; set; } public string YearOut { get; set; } } Partial Public Class MoviesModel Inherits DbContext Public Sub New() MyBase.New("name=MoviesModel") End Sub Protected Overrides Sub OnModelCreating(ByVal modelBuilder As DbModelBuilder) End Sub Public Property Movies() As IDbSet(Of Movie) Public Shadows Function [Set](Of T As Class)() As IDbSet(Of T) Return MyBase.Set(Of T)() End Function End Class Public Class Movie Public Property ID() As Integer Public Property Name() As String Public Property Director() As String Public Property YearOut() As String End Class The final step is to create a context object which will allow you to load and save the data. MoviesModel dbContext; public RadForm1() { InitializeComponent(); dbContext = new MoviesModel(); } private void radButtonLoad_Click(object sender, EventArgs e) { dbContext.Movies.Load(); radGridView1.DataSource = dbContext.Movies.Local.ToBindingList(); } private void radButtonSave_Click(object sender, EventArgs e) { dbContext.SaveChanges(); } Private dbContext As MoviesModel Public Sub New() InitializeComponent() dbContext = New MoviesModel() End Sub Private Sub radButtonLoad_Click(ByVal sender As Object, ByVal e As EventArgs) dbContext.Movies.Load() radGridView1.DataSource = dbContext.Movies.Local.ToBindingList() End Sub Private Sub radButtonSave_Click(ByVal sender As Object, ByVal e As EventArgs) dbContext.SaveChanges() End Sub Now you can manage the data directly in the grid.
https://docs.telerik.com/devtools/winforms/cloud-integration/azure/connect-to-data-in-the-cloud/sql-database
CC-MAIN-2020-34
refinedweb
604
54.12
39618/difference-between-client-and-resource-in-boto3 The main difference between Client and Resources are as follows: Here's an example of using boto client-level access to an s3 bucket: import boto3 client = boto3.client('s3') response = client.list_objects(Bucket='example') for content in response['cont']: obj_dict = client.get_object(Bucket='example', Key=cont['Key']) print(cont['Key'], obj_dict['LastModified']) an example of using boto resource-level access to an s3 bucket: import boto3 s3 = boto3.resource('s3') bucket = s3.Bucket('example') for obj in bucket.objects.all(): print(obj.key, obj.last_modified) The major difference between these two pieces ...READ MORE Classic Load balancer are used in times ...READ MORE AMI is the Amazon Machine Image which provides ...READ MORE S3 Native FileSystem (URI scheme: s3n) A ...READ MORE suppose you have a string with a ...READ MORE if you google it you can find. ...READ MORE Syntax : list. count(value) Code: colors = ['red', 'green', ...READ MORE can you give an example using a ...READ MORE As far as I understand and use ...READ MORE EC2 EC2 is Amazon's service that allows you ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/39618/difference-between-client-and-resource-in-boto3
CC-MAIN-2020-05
refinedweb
195
53.98
Build a Versioning System With IPFS and Blockstack Justin Hunter Originally published at Medium on ・18 min read There are so many great use cases for versioning. Handling code deployments, document edits, and database snapshots are just a few immediate uses that come to mind. Normally, a versioning system is another segment within a database, but it can be so much more when you think of it through the lens of immutable data and DHT (distributed hash tables) technology. So, today, we’re going to build a stream of consciousness note-taking app with version history. This will be different than other notes apps as it will have just ONE note that the user can edit over time, removing information or adding information. But we’ll include versions so they can grab their history. We’ll do all that by using Blockstack and IPFS. Blockstack is a decentralized application platform that lets users choose where there data is stored. For the similicity of this tutorial, we’re going to use the storage hub provided by Blockstack the company (it’s free and there’s no configuration needed). IPFS a peer-to-peer network that allows data to be served based on its content, not its location. This means that when the data changes, it is represented by a different identifier (a hash), and the old version of the data still exists, unchanged. This is perfect for a versioning system. We’re going to build all of this by creating a new React project and installing just one dependency: SimpleID. SimpleID provides developer tools for the decentralized web. In a nutshell, SimpleID lets developers add decentralized authentication and storage to their apps without asking their users to go through the cumbersom process of generating seed phrases and managing those 12-word backups. Users get a traditional username/password authentication flow while still owning their identity and getting access to Web 3.0 technology. To get started, visit SimpleID and sign up for a free developer account. Once you verify your account, you’ll be able to create a project and select the Web 3.0 modules to include in your project. Let’s walk through that quickly: Click the verification link in your email Once your account is verified, you’ll be on the Accounts page where you can create a new project Give that new project a name and a URL where you may eventually host it (this can be a fake url for now as long as it’s https based) Save and then click View Project Copy down your API Key and Developer ID Go to the Modules page and select Blockstack for your Authentication Module and both Blockstack and Pinata for your Storage Module Click Save That’s it! Now, you’re ready to work. Quick note about Pinata: They provide an IPFS pinning service, so SimpleID uses them behind the scenes to add content to the IPFS network and to pin said content to ensure it is always available. Read more about pinning here. Let’s build a project. My instructions will be from the MacOS perspective, but those of you on different systems should be able to use similar commands to get started. First, open up your terminal and create the new React project: npx create-react-app ipfs-blockstack-versioning When that’s done, change into the directory and then install the SimpleID dependency: cd ipfs-blockstack-versioning npm i simpleid-js-sdk Ok, open the project up in your text editor of choice. We’re not going to spend time with complex folder structure. This is a very basic application designed to show off the power of Blockstack and IPFS. With that in mind, find the src folder and open App.js. At the top of that file add the following right below the import css statement: } Ok, now with the SimpleID package imported and this config object (which comes right from theSimpleID Docs), you’re ready to get started. Let’s work on the user interface a bit. As I mentioned, this is going to be a really simple app, so let’s drop in an editor for handling our document. We’ll do this with a script tag in the index.html file rather than installing a dependency via NPM. You can use any WYSIWYG library, but I'm going to use is called Medium Editor. You can find it here. Your index.html file is located in the public folder. Find it and add this above the title tag: <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/medium-editor@latest/dist/css/medium-editor.min.css" type="text/css" media="screen" charset="utf-8"> <script src="//cdn.jsdelivr.net/npm/medium-editor@latest/dist/js/medium-editor.min.js"></script> <title>NoteStream</title> You’ll note, I set the title of my app here since we were already editing the file. Feel free to use the same name or create your own. Now that we’ve added the stylesheet and the script we need, let’s move to our App.js file which is located in the src folder. We're going to clear everything out of this file and start mostly from scratch. So, update your App.js file to look like this: import React from 'react'; import './App.css'; } class App extends React.Component { constructor(props) { super(props); this.state = { userSession, content: "", versions: [], selectedVersionContent: "", pageRoute: "signup", versionPane: false, versionModal: false } } render() { return ( <div className="App"> </div> ); } } export default App; I’ve converted the function component to a class component, but you can do this as a function component with some minor changes to the way state is handled. You can see I have four state variable that I expect to use: userSession (which will be filled from our Blockstack authentication), content (which will be the actual streaming note), versions (which will be our history), selectedVersionContent (which will be used for displaying the actual content of past versions), pageRoute (which is for handling that is displayed on the screen), versionPane (which determines if the version pane is showing), and versionModal (which determines if the version modal is open or not). I think the first thing we should do is get a signup and sign in screen rendering. Within thewith the className of “App”, add some conditional logic with form inputs like this: render() { const { pageRoute, userSession } = this.state; return ( <div className="App"> { pageRoute === "signup" && !userSession.isUserSignedIn() ? <div> Sign Up </div> : pageRoute === "signin" && !userSession.isUserSignedIn() ? <div> Sign In </div> : <div> App Content </div> } </div> ); } We are obviously going to fill this in with actual content, but this should help illustrate what’s happening. If that pageRoute state is "signup" and the user is NOT logged in, we should show the signup form. If the pageRoute state is "signin" and the user is NOT logged in, we should show the sign in form. Otherwise, we should show the app. Now, let’s build this out a little. Let’s start by handling the Blockstack userSession state. This is actually pretty simple. At the top of our App.js file, just add this below the import statements: import { UserSession } from 'blockstack'; import { AppConfig } from 'blockstack' const appConfig = new AppConfig(['store\_write', 'publish\_data', 'email']); const userSession = new UserSession({ appConfig }); You should add this to the top of your actions.js file as well below the existing import statement. Blockstack comes installed with SimpleID, so you don't need to add anymore dependencies. Ok, now let's add the necessary sign in and sign up forms to our App.js file: class App extends React.Component { constructor(props) { super(props); this.state = { userSession, content: "", versions: [], selectedVersionContent: "", pageRoute: "signup", versionPane: false, versionModal: false, username: "", password: "", email: "", loading: false, error: " } } handleUsername = (e) => { this.setState({ username: e.target.value }); } handlePassword = (e) => { this.setState({ password: e.target.value }); } handleEmail = (e) => { this.setState({ email: e.target.value }); } handleSignIn = (e) => { e.preventDefault(); } handleSignUp = (e) => { e.preventDefault(); } render() { const { pageRoute, userSession, username, password, email, error } = this.state; return ( <div className="App"> { pageRoute === "signup" && !userSession.isUserSignedIn() ? <div> <form onClick=> ); } } export default App; There’s a lot we’ve added here, but it’s pretty simple to understand. We added the functions to handle the sign up and sign in flow. We added a form to handle each of those inputs as well. We added a state switcher so that someone on the sign in form could switch to the sign up form and vice versa. We also have a paragraph section ready in both the sign up form and the sign in form to handle any error that might happen during sign up or sign in. With all of this in place, I think we can finally fire up our app and see how well it’s working. From the terminal run npm start. Hopefully that worked for you. If it did you’ll see a god-awful ugly sign up form. You can switch to the sign in form and switch back as well.We’re not going to be touching much CSS in this tutorial, but we’ve got the start of a functioning app. You may have noticed earlier, I added a state variable called loading. We’re going to use that here in just a second as we actually sign a user up and log them in. We’ll start with the sign up process. And again, for this, we’ll be using the SimpleID Docs. Find the handleSignUp function and fill it in like so: handleSignUp = async (e) => { e.preventDefault(); this.setState({ loading: true, error: "" }); const { username, password, email } = this.state; const credObj = { id: username, password: password, hubUrl: '', //This is the default Blockstack storage hub email: email } try { const account = await createUserAccount(credObj, config); localStorage.setItem('blockstack-session', JSON.stringify(account.body.store.sessionData)); window.location.reload(); } catch(err) { console.log(err); this.setState({ loading: false, error: "Trouble signing up..."}) } } We made our function asynchronous because we need to wait for the createUserAccount promise to resolve before we can do anything else. Other that that, we simply followed the docs and added a try/catch. If there’s an error, the error state will be updated and the loading state will be set back to false. The user should see the error message on the screen then. If there’s no error, the localStorage item Blockstack needs is updated and we refresh the window. One last thing we should do before testing the sign up flow is add a loading indicator. This isn’t going to be anything special, but when signing up, the indicator will replace everything else on the screen. Let’s update our app code JSX to look like this: <div className="App"> { loading ? <div> <h1>Loading...</h1> </div> : <div> { pageRoute === "signup" && !userSession.isUserSignedIn() ? <div> <div onSubmit=> } </div> Let’s test this out now. Go ahead and type a username, password, and email and then click sign up. Assuming that worked, you should have seen the loading screen and then after a few seconds, the user is logged in and the words “App Content” appear. Nice! But now what? We haven’t handled sign in, and the user can’t sign out. Let’s handle sign out first since it’s really simple. In the section of your app where you have the words “App Content” add a button that calls the handleSignOut function: <button onClick={this.handleSignOut}>Sign Out</button> Then make sure to add that function up with your other functions: handleSignOut = () => { localStorage.removeItem('blockstack-session'); window.location.reload(); } Give that a try and the user should be signed out. Now, we can work on log in. I hope you remembered your username and password. Let’s wire up the handleSignIn function: handleSignIn = async (e) => { e.preventDefault(); this.setState({ loading: true, error: "" }); const { username, password } = this.state; const credObj = { id: username, password, hubUrl: '' //This is the default Blockstack storage hub } const params = { credObj, appObj: config, userPayload: {} //this can be left as an empty object } try { const signIn = await login(params); if(signIn.message === "user session created") { localStorage.setItem('blockstack-session', JSON.stringify(signIn.body.store.sessionData)); window.location.reload(); } else { this.setState({ loading: false, error: signIn.message }) } } catch(err) { console.log(err); this.setState({ error: "Trouble signing in..."}) } } We are using the SimpleID Docs once more to sign in, and most of this code is re-used from the sign up function. We don’t need the email for sign in, and we have to create a params object, but other than that, it’s mostly the same. With that in place, let’s give this a shot. You should have seen the loading indicator and then your user was signed in. Of course, we just have a sign out button now when a user in logged in. Let’s change that by dropping in our Medium-style editor. Below your constructor in App.js and above your other functions, let’s add a componentDidMount method: componentDidMount() { var editor = new window.MediumEditor('.editable'); } This is using window to fetch the MediumEditor script we added to our index.html file. For us to see anything, we need to edit the App Contents section of our JSX. So in the area where you put your sign out button, let’s add something below that to handle the editor: <div className="editor"> <h1>NoteStream</h1> <p>Start where you left off or shove your thoughts in the middle somewhere. It's up to you!</p> <div className="editable"></div> </div> Without any css styling this is going to be too ugly to handle. So, let’s just drop a little in to fix that. In the same folder, but in the App.css file, add the following: .editor { max-width: 85%; margin: auto; margin-top: 100px; } .editable { max-width: 85%; margin: auto; border: 1px solid #282828; border-radius: 3px; min-height: 500px; padding: 15px; text-align: left; } We can change this later, but it at least makes the application presentable. You should see something like this: Not the prettiest thing, but it’ll do for now. We need to be able to handle the changes to the editor, so let’s start there before we even begin to save data. In our componentDidMount lifecycle event, let’s change things a bit: componentDidMount() { var editor = new window.MediumEditor('.editable'); //We'll load our content here soon editor.subscribe('editableInput', (event, editable) => { this.setState({ content: editor.getContent(0) }); }); } If you remember, we had created a state variable called content to hold the content of our note. We are setting that state on every change in the editor. That means when we are ready to save the note, we can just fetch our data from the content state. Let’s see how that looks by doing two things. We’ll add a save button and we’ll add a saveContent function. Right where the sign out button is, add a save button below it: <button onClick={this.handleSignOut}>Sign Out</button> <button onClick={this.saveContent}>Save</button> Then, with all your other functions, create the saveContent function: saveContent = () => { const { content, userSession } = this.state; console.log(content) } We’re going to be using the userSession state in a minute, so I threw it in there. But with this, you should be able to open the developer console, type into the editor, and then hit save. You’ll see the html content. That means you’re ready to save content and load that content back. Let’s thing this through first, though. We need to save the content to Blockstack’s storage system and IPFS. Blockstack’s storage system will be an overwrite function every time, but for IPFS, we’re going to store a new version to the network. We also need to be able to fetch the IPFS hashes, so we should store that to Blockstack as well. It sounds to me like we have two files to store on Blockstack: content and versions (hashes). But we have to first save to IPFS so that we have the hash result. Let’s start writing that out in our saveContent function. } const pinnedContent = await pinContent(params); console.log(pinnedContent); } We’ve added the async keyword to the function and we’ve used the paramaters necessary to post the content to IPFS as given by the SimpleID docs. In some cases, a developer will need to query Pinata for content they previously posted to IPFS. that’s the whole point of the id field. In this case, we’ll be using Blockstack to manage all of our hashes, so we don’t really care what this identifier is except that it’s unique (thus, Date.now()). Let’s test this out with console open and see how it goes before we move on. Add some content to your editor then hit Save. If all goes well, you should see something like this in the console: { message: "content successfully pinned", body: "QmbRshi9gjQ2v5tK4B8czPqm3jEQ3zGzsuQJuQLyti4oNc" } That body key in the object is an IPFS hash. We want to use that and store it as a version with Blockstack. So let’s tackle that next. } if(pinnedContent.message === "content successfully pinned") { const newVersion = { timestamp: Date.now(), hash: pinnedContent.body } versions.push(newVersion); this.setState({ versions }); const savedVersion = await userSession.putFile("version\_history.json", JSON.stringify(versions), {encrypt: true}); console.log(savedVersion); } else { console.log("Error saving content"); } } I’ve added a check to make sure the content pinning to IPFS was successful before trying to save the hash to Blockstack. We need to know the time of the version, so we’re building up a newVersion object with the timestamp and the hash itself and then we are pushing that into the versions array. We are then saving this to Blockstack, where something cool is happening. You can see an object in the putFile call that says encrypt. We are able to encrypt data that easily. Don’t believe me? Here’s the file I used to test this section of the tutorial: That’s just encryption our version history, which is important, but wouldn’t it be cool to encrypt the content before sending it to IPFS too? Let’s do that before we tackle the last part of saving content. In your saveContent function, right about the contentToPin variable, add this: const encryptedContent = userSession.encryptContent(JSON.stringify(content), {publicKey: getPublicKeyFromPrivate(userSession.loadUserData().appPrivateKey)}); We need to import the getPrivateKeyFromPublic function as well. So at the top of your App.js file with the other import statements, add: import { getPublicKeyFromPrivate } from 'blockstack/lib/keys'; And update the contentToPin variable to look like this: const contentToPin = { pinnedContent: JSON.stringify(encryptedContent) } We’ll see in a moment if this works. Let’s pick up after setting and saving the version history. So right after the savedVersions line, add this: const savedVersion = await userSession.putFile("version\_history.json", JSON.stringify(versions), {encrypt: true}); const savedContent = await userSession.putFile('note.json', JSON.stringify(encryptedContent), {encrypt: false}); console.log(savedContent); Here’s what I get back in the console log by doing that: Looks like it worked! So, to recap, we are encrypting the content, storing it on IPFS, using the IPFS hash that’s returned to create a new entry in the versions array, saving that to Blockstack, then saving the current version of the note content to Blockstack. Pretty cool stuff, but we need to be able to fetch content too, right? Initially, there are just two files we need to fetch when the application loads up: The current content (from note.json), and the versions file (from version_history.json). We should do that as soon as the app loads, so this will need to be added to our componentDidMount lifecycle event. Update the entire event like this: async componentDidMount() { const { userSession } = this.state; const content = await userSession.getFile('note.json', {decrypt: false}); const decryptedContent = userSession.decryptContent(JSON.parse(content), {privateKey: userSession.loadUserData().appPrivateKey}); this.setState({ content: JSON.parse(decryptedContent )}); var editor = new window.MediumEditor('.editable'); editor.subscribe('editableInput', (event, editable) => { this.setState({ content: editor.getContent(0) }); }); editor.setContent(JSON.parse(decryptedContent), 0); } Save that and go back to your app. When it reloads, the content you had saved will now appear in the editor. We’re getting there. We have just a couple more things to do. We need to load the version history, so let’s do that next. Right below the decryptContent variable, add the following: const versions = await userSession.getFile('version\_history.json', {decrypt: true}); this.setState({ content: JSON.parse(decryptedContent), versions: JSON.parse(versions) }); Now, we can start having fun with versions. Let’s make sure we can render our version history first. In the App Contents section of your JSX, below the editor, add the following: <div className={versionPane ? "versionPaneOpen" : "versionPaneClosed"}> <ul> { versions.map(v => { return( <li key={v.timestamp}><a href="#" onClick={() => this.handleVersionModal(v.hash)}>{v.timestamp}</a></li> ) }) } </ul> </div> We are creating a section to hold the version history. You’ll note the className is conditional on the state variable versionPane. This is because we want to be able to change that variable and open the version history rather than have it open all the time. Let’s add a button up with our sign out and save button called Version History. <button onClick={() => this.setState({ versionPane: !versionPane })}>Version History</button> And let’s update our CSS one more time to handle the display of the pane: .versionPaneOpen { position: fixed; top: 0; right: 0; width: 250px; z-index: 999; border-left: 2px solid #282828; height: 100vh; background: #eee; display: inline; } .versionPaneOpen { display: none; } Go ahead and test it out. You should have at least one version saved, so hit that Version History button to toggle the pane open and closed. It’s ugly, but it works. The last thing we need to do is pop up a modal to show the content of a past version. Let’s get to work on that by adding a function called handleVersionModal. handleVersionModal = (hash) => { const { userSession } = this.state; this.setState({ selectedVersionContent: "", versionModal: true }); fetch(`{hash}`) .then(function(response) { return response.json(); }) .then(function(myJson) { const encryptedContent = myJson.pinnedContent; const decryptedContent = userSession.decryptContent(JSON.parse(encryptedContent), {privateKey: userSession.loadUserData().appPrivateKey}); this.setState({ selectedVersionContent: JSON.parse(decryptedContent)}); }); } We are using the JavaScript native Fetch API to handle calling out to an IPFS gateway to fetch the content specific to the version we select in the version pane. That content is encrypted and needs to be parsed and decrypted properly to be accessible. But if you console log the decryptedContent variable, you’ll see the content of the version in question is properly being fetched. We are setting that content to the selectedVersionContent state variable and setting the versionModal to true. Let’s put that all to use to render the past version on screen. Below the version page JSX you wrote earlier, add this: <div className={versionModal ? "versionModalOpen" : "versionModalClosed"}> <span onClick={() => this.setState({versionModal: false})}Close</span> { selectedVersionContent ? <div dangerouslySetInnerHTML={{\_\_html: selectedVersionContent}} />: <h3>Loading content for selected version...</h3> } </div> Now, we need to style that a bit to be manageable. In App.css, add this: .versionModalOpen { display: inline; position: fixed; text-align: left; left: 12.5%; top: 15%; width: 75%; min-height: 500px; margin: auto; z-index: 999; background: #eee; padding: 25px; border: 1px solid #282828; border-radius: 3px; } .versionModalClosed { display: none; } #version-close { position: relative; right: 10px; top: 10px; z-index: 1000; cursor: pointer; } Let’ give this thing a try now. Open up the version history pane. Click on a past version. A modal should pop up with the content of that version for you to view. That’s it! We made it. You can now have an endless stream of consciousness note taking system while retaining control of all past iterations via version history. And to top it all off, every version of the note is encrypted with a private key wholly under your control. Take your new powers and build other cool things and propel Web 3.0 into the mainstream. If you’d like to see the code for this tutorial, you can find it here.<<
https://practicaldev-herokuapp-com.global.ssl.fastly.net/polluterofminds/build-a-versioning-system-with-ipfs-and-blockstack-1no6
CC-MAIN-2019-43
refinedweb
4,031
58.08
In the past two articles, I’ve looked at Redux as an implementation of the flux architecture and I’ve looked at wrapping React components so that they can take advantage of Redux without a lot of boilerplate code. However, I had noted one issue – async actions. Redux action creators need to return an object that describes the action. When you deal with async actions, the thing that is returned is generally a Promise these days. It most definitely is not an object that you can immediately dispatch. Personally, I think this is a complete failure of Redux. Async operations are the cornerstone of server-client communication and the decision to defer this functionality to another library is really a problem. It’s a problem I can live with, but I shouldn’t have to. Now that I’ve got that off my chest, let’s take a look at the facility that allows Redux to handle async functions – middleware. You’ve probably seen middleware before – ExpressJS, for example, relies on middleware to handle even the most basic functionality. The concept within Redux is the same thing. We insert a function in between the action and the reducer to transform the action into a form that the reducer can digest. Even though my app does not make use of a major amount of server-side API right now, I want to solve this because I expect a large amount of communication between backend and frontend and I want to be able to handle the async requests the same way as the simpler synchronous requests. Let’s take another look at my Promise-based action creator:)); }); }; } Theoretically, I can just create an action and then call the action, like this: // Dispatch the initial action let requestAction = requestAuthInfo(); requestAction(store.dispatch); However, I normally use dispatch like this: store.dispatch(requestAuthInfo()); Fortunately, you don’t actually have to write your own middleware. Today I’m going to introduce three pieces of middleware. We’ll get to the main attraction shortly, but first let’s take a look at how middleware works by implementing some dispatch logging. The redux-logger middleware will log the actions dispatched and provide information about the before and after state. To implement this, we alter our store: import { createStore, applyMiddleware } from 'redux'; import createLogger from 'redux-logger'; import { requestAuthInfo } from './actions'; import reducer from './reducers'; const initialState = { phase: 'pending', user: null, error: null, leftMenuVisibility: false }; const logger = createLogger(); const store = createStore( reducer, initialState, applyMiddleware(logger) ); // Dispatch the initial action let requestAction = requestAuthInfo(); requestAction(store.dispatch); export default store; UPDATE Based on advice from the Redux author – Dan Abramov – I’ve updated this sample. The applyMiddleware() function takes a list of middleware functions – this is appended to the end of the createStore() paraeters so that the middleware is applied to the store. Note that the logger middleware must be placed last – otherwise you get wierd logs for actions that need to be transformed. If you run this project, you might get something like the following in the console window: Each action is grouped and you see the before and after. This gives me a confidence that my components are doing the right thing – another ad-hoc test capability when doing development. On to the meat of my problem though – how do I handle promises and functions in general? The answer is to use a thunk. A what? Who makes up these terms? Seriously. Ok, let me break it down. A thunk is an action creator that returns a function instead of an object. My requestAuthInfo() action creator uses an arrow function which is basically a function, so I definitely need this. The middleware for this is called redux-thunk. That just handles the function mechanism though – I also need to handle the fact that the function returns a promise. That’s handled by redux-promise. Let me add all that to my redux/store.js: import { createStore, applyMiddleware } from 'redux'; import createLogger from 'redux-logger'; import thunk from 'redux-thunk'; import reduxPromise from 'redux-promise'; import { requestAuthInfo } from './actions'; import reducer from './reducers'; const initialState = { phase: 'pending', user: null, error: null, leftMenuVisibility: false }; const reduxLogger = createLogger(); const store = createStore( reducer, initialState, applyMiddleware(thunk, reduxPromise, reduxLogger) ); // Dispatch the initial action store.dispatch(requestAuthInfo()); export default store; UPDATE Dan Abramov (who wrote redux) updated me to show the more JS-friendly way of doing this, and I love the new syntax. I have updated the syntax above to match what Dan is recommending now. We need to order the middleware so that they are executed in the right order. The thunk handles the action creator that returns a function; the reduxPromise handles the case when the function returns a Promise, and finally, reduxLogger logs the before and after of the store state. I can now change the request for authentication information (line 24) to be a dispatched action. Back on my soap-box. The redux-thunk and redux-promise libraries should just be incorporated into the createStore() call – they should not really be separate functions – async connectivity is core to most web apps. It won’t stop me from using Redux. Remember when I started – my code was 214 lines long (not including the library code). This code is 167 lines long. In addition to the 25% reduction in actual code I have to write, there is also a reduction in boilerplate code that I have to write to use the store. That’s in addition to the fact that I don’t have to maintain my own library that doesn’t do half of what Redux does. All in all, I’d be happy if Redux stopped here. But it doesn’t. As always, my code is available at my GitHub Repository. Since I updated the code after I published, please note that the code in the repo is different (see store.js)
https://shellmonger.com/2016/02/23/an-introdution-to-react-redux-part-3/
CC-MAIN-2016-44
refinedweb
983
54.52
digitalmars.D.learn - I want to implement operation feasible? - Brian (52/52) Dec 15 2014 package com.kerisy.mod.base - Adam D. Ruppe (18/24) Dec 15 2014 You can't do that - interface methods must be either final or package com.kerisy.mod.base interface BaseMod { auto getInstance(); } package com.kerisy.mod.a class A : BaseMod { A getInstance() { return (new A); } void hello() { // in A writeln("in A"); } } package com.kerisy.mod.b class B : BaseMod { B getInstance() { return (new B); } void hello() { // in B writeln("in B"); } } import std.stdio; import com.kerisy.mod.a; import com.kerisy.mod.b; int main(string[] argv) { string packageClass; packageClass packageClass = "mod.forum.controller.forum.A"; BaseMod modObje = cast(BaseMod)Object.factory(packageClass); auto a = modObj::getInstance(); Object.callMethod(a, "hello"); packageClass packageClass = "mod.forum.controller.forum.A"; BaseMod modObje = cast(BaseMod)Object.factory(packageClass); auto a = modObj::getInstance(); Object.callMethod(a, "hello"); return 0; } Dec 15 2014 On Tuesday, 16 December 2014 at 04:45:31 UTC, Brian wrote:interface BaseMod { auto getInstance(); }You can't do that - interface methods must be either final or have concrete types (they can't be templates or auto returns). Make it BaseMod getInstance(); and the rest of your classes will work.auto a = modObj::getInstance();Since this comes from the interface, a will be typed to the interface too. It will have the dynamic type of the underlying class, but the interface functions will all return the interface. If your hello method is in the interface, you can just call it at that point though and you'll get the results you want. BTW it is modObj.getInstance rather than ::. D always uses the dot.Object.callMethod(a, "hello");You could write a reflection method like that in D, but it isn't done automatically (partially due to bloat concerns making it opt-in). Check out the free sample of my D book: The free chapter is about D's reflection. I also go into how to make runtime methods like you have in other parts of the book. Dec 15 2014
http://www.digitalmars.com/d/archives/digitalmars/D/learn/I_want_to_implement_operation_feasible_66835.html
CC-MAIN-2017-43
refinedweb
349
52.36
Tcl_TraceCommand(3) Tcl Library Procedures Tcl_TraceCommand(3) _________________________________________________________________ Tcl_CommandTraceInfo, Tcl_TraceCommand, Tcl_UntraceCommand - monitor renames and deletes of a command #include <tcl.h> ClientData Tcl_CommandTraceInfo(interp, cmdName, flags, proc, prevClientData) int Tcl_TraceCommand(interp, cmdName, flags, proc, clientData) void Tcl_UntraceCommand(interp, cmdName, flags, proc, clientData) Tcl_Interp *interp (in) Interpreter containing the com- mand. const char *cmdName (in) Name of command. int flags (in) OR'ed col- lection Tcl Last change: 7.4 1 Tcl_TraceCommand(3) Tcl Library Procedures Tcl_TraceCommand(3) by Tcl_CommandTraceInfo, so this call will return informa- tion about next trace. If NULL, this call will return informa- tion about first trace. _________________________________________________________________ com- mand, application-specific data structure that describes what to do when proc is invoked. OldName gives the name of the com- mand being renamed, and newName gives the name that the Tcl Last change: 7.4 2 Tcl_TraceCommand(3) Tcl Library Procedures Tcl_TraceCommand(3) command is being renamed to (or an empty string or NULL when the command is being deleted.) Flags is an OR'ed combina- tion of bits potentially providing several pieces of infor- mation. speci- fied match- ing traces after it. This mechanism makes it possible to step through all of the traces for a given command that have the same proc.. Tcl Last change: 7.4 3 Tcl_TraceCommand(3) Tcl Library Procedures Tcl_TraceCommand(3) It is possible for multiple traces to exist on the same com- mand.. In a delete callback to proc, the TCL_TRACE_DESTROYED bit is set in flags. inter- preter, since its state is partially deleted. All that trace procedures should do under these circumstances is to clean up and free their own internal data structures. Tcl does not do any error checking to prevent trace pro- cedures from misusing the interpreter during traces with TCL_INTERP_DESTROYED set. clientData, trace, command Tcl Last change: 7.4 4
http://uw714doc.xinuos.com/cgi-bin/man?mansearchword=Tcl_CommandTraceInfo,%20Tcl_TraceCommand,%20Tcl_UntraceCommand&mansection=3tcl&lang=en
CC-MAIN-2020-29
refinedweb
304
56.25
Up. Project setup As I’ve told a few times already. The greatest place to start any Spring project is start.spring.io. In this case I’m going to create a project with four dependencies: Web, HSQLDB, JPA and Thymeleaf. The screenshot above is missing the HSQLDB dependency After creating, downloading, extracting and importing the project in your IDE, you’re ready to start writing some code! Data model In this case I’m going to create a simple CRUD application and it seems that 99% of all simple CRUD applications are about todo lists, so let’s follow that trend as well. First of all we need an entity: @Entity @Table(name = "task") public class Task { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; @Column(name = "description") private String description; @Column(name = "completed") private boolean completed; public Long getId() { return id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean isCompleted() { return completed; } public void setCompleted(boolean completed) { this.completed = completed; } } We have three properties here, an auto-generated ID, the task description and a boolean indicating if the task is completed or not. So, let’s create our table schema now: CREATE TABLE task ( id INTEGER IDENTITY PRIMARY KEY, description VARCHAR(64) NOT NULL, completed BIT NOT NULL); If you save this file as schema.sql in src/main/resources, it gets automatically executed when you launch the application, convenient, isn’t it? Anyhow, if you create a schema this way, you’ll have to disable Spring’s default behaviour, which is generating a schema based on your entities if you’re using HSQLDB. So, open application.yml (or application.properties) and add the following: spring: jpa: hibernate: ddl-auto: none Now all we need is some test-data: INSERT INTO task (description, completed) VALUES ('Setting up our application', 1), ('Handling our form', 0); Similarly to our schema, if you save this file as data.sql inside the src/main/resources folder, it will automatically executed when you start your application. The last step is to create a repository to handle our data. Create an interface called TaskRepository and make it extend from JpaRepository: public interface TaskRepository extends JpaRepository<Task , Long> { } Creating a service Writing a service isn’t really that difficult either: @Service public class TaskServiceImpl { @Autowired private TaskRepository repository; public List<Task> findAll() { return repository.findAll(); } @Transactional public Task create(Task task) { Task newTask = new Task(); newTask.setDescription(task.getDescription()); newTask.setCompleted(task.isCompleted()); return repository.saveAndFlush(newTask); } @Transactional public Task update(Long id, Task task) { Task entity = findOneSafe(id); entity.setDescription(task.getDescription()); entity.setCompleted(task.isCompleted()); return entity; } @Transactional public void delete(Long id) { Task task = findOneSafe(id); repository.delete(task); } private Task findOneSafe(Long id) { Task task = repository.findOne(id); if (task == null) { throw new TaskNotFoundException(); } else { return task; } } } The findAll() method is quite simple, this method simply uses the repository. In real cases there might also happen some mapping here to make sure you don’t expose your entities to the outer world. The create() method creates a new Task and saves it using the repository’s saveAndFlush() method. The reason I’m creating a new task and I’m not using the input is because this allows you to have more control. Some properties do not have to be inserted, like the ID for example. Actually, when you’re using a separate model, you can use this to convert your model to your entity. The same happens for the update() method. I’m retrieving the entity using the findOne() method and then I’m copying the properties over, one by one. When I can’t find an entity with the given ID I’m throwing an exception called TaskNotFoundException: public class TaskNotFoundException extends RuntimeException { } This allows you to show proper error messages in case someone tries to update a non-existing entity, though that should not happen if using the application. Finally, the delete() method also uses the same findOne() method to delete the entity using the delete() method of the repository. Showing the tasks The first step in the application is to show the tasks themself. To do that, create a controller called TaskController and make it extend from WebMvcConfigurerAdapter like this: @Controller @RequestMapping("/") public class TaskController extends WebMvcConfigurerAdapter { @Autowired private TaskServiceImpl service; @RequestMapping(method = RequestMethod.GET) public String findAll(Model model) { model.addAttribute("tasks", service.findAll()); return "tasks"; } } This uses the service to add the tasks to the model. Then create an HTML file called tasks.html inside the src/main/resources/templates folder. <"> <input type="checkbox" name="completed" th: <span th:</span> </div> <div class="three columns"> <button class="button u-full-width" type="submit">Delete</button> </div> </div> <hr /> </div> </body> </html> If you run the application now, you’ll see that the dummy tasks we created are already visible. Adding new tasks The next thing we’ll do is adding new tasks. To do that, first you have to provide a separate model in the findAll() method in the controller: @RequestMapping(method = RequestMethod.GET) public String findAll(Model model) { model.addAttribute("tasks", service.findAll()); model.addAttribute("newTask", new Task()); return "tasks"; } I also added some validations to the Task entity by adding some annotations to the properties: @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; @NotNull @Size(min = 1, max = 64) @Column(name = "description") private String description; @Column(name = "completed") private boolean completed; The annotations you’re seeing here are the JSR-303 annotations I was speaking of. They allow you to validate the properties on your objects. In this case we added both the @NotNull and @Size annotations. And finally, we also have to add a method to the controller to save the new task by calling the service: @RequestMapping(method = RequestMethod.POST) public String post(@Valid @ModelAttribute("newTask") Task task, BindingResult bindingResult, Model model) { if (bindingResult.hasErrors()) { model.addAttribute("newTask", task); model.addAttribute("tasks", service.findAll()); return "tasks"; } else { service.create(task); return "redirect:/"; } } With the @Valid annotation you tell Spring that you want to validate the DTO with these annotations, while the @ModelAttribute annotation is used to bind the values from the form (which we’ll edit after this) back to the model. The name ( "newTask") fits the name of the model which we added to the findAll() method on the controller. The BindingResult on the other hands contains more info about the result, like the errors from the validation (using the hasErrors() method). We’ll use this method to either show the error by returning the same model again, and the erroneous task model. On the other hand, if the model is valid, then we add the task using the service and we redirect back to the findAll() method. So now we only have to add the form on which we will bind the model to. To do that, open tasks.html again and add the following below the <hr /> tag: <form method="post" th: <div class="row"> <div class="nine columns"> <input type="text" placeholder="Description of the task" class="u-full-width" th: <span th:Description errors</span> </div> <div class="three columns"> <button type="submit" class="button-primary u-full-width">Add</button> </div> </div> </form> Important here to see are the Thymeleaf attributes starting with the th: like th:action, th:object, th:field and th:if. Some of them are quite obvious, like th:action, which is just a wrapper for the action attribue, telling which location to use to submit the form. The th:object attribute on the other hand allows you to bind the model to a form, in this case ${newTask}. To bind the values of the form elements, you use the th:field attribute. In this case we’re binding the description property to it. With the th:if on the other hand we can show/hide elements on a specific condition. In this case we use the Fields class, which is part of the integration of Thymeleaf with the Spring framework and allows you to check if any field contains an error according to the bean validations. With the th:errors attribute we can show which error occured, which you can override by setting the message property of the JSR-303 annotations ( @NotNull and @Size in this case). Obviously, in proper web applications you would also validate the form on the client as well, using the maxlength and required attributes, but that would make it a bit harder to test the bean validation, so I’m not going to do that in this case. So, let’s test it out now by running the application. If you open the application, you’ll see that the form is now appended correctly. After entering and submitting a value, you’ll see that it properly gets appended to the list, which indicates that the application is behaving correctly, at least when following the “happy path”. Now, when we don’t enter a value and press the button, you’ll see that a message is displayed below the input field, right where we added the th:errors attribute. Updating the tasks The next thing we’re going to do is to update the tasks, when we check them so we can complete them. Sadly, while this is all quite obvious with JavaScript frameworks like AngularJS, Ember.js, …, we’re going a bit out of the boundaries of what Spring/Thymeleaf does (at least about the model binding part), so the best way to do this is by creating your own form and using hidden fields for the ID. <form th: <input type="hidden" name="id" th: <input type="hidden" name="description" th: <input type="checkbox" name="completed" th: <span th:</span> </form> Another form here, with the th:action attribute we’ve already seen. The th:method on the other hand is quite new, but this is very similar to the normal method attribute, with the exception that it also allows put/delete by proxying them through a POST call. The reason for this is that most browsers do not allow this. Within the form we have the id/description and completed attributes, where two of them (the ID and the description) are hidden. To make the form submit itself when we change the checkbox, we use a little bit of JavaScript, namely the onchange="form.submit()" part, which allows you to submit the form in which the element is in. The last part we have to do to make the update work is to add a method to the controller: @RequestMapping(method = RequestMethod.PUT) public String update(@RequestParam Long id, Task task) { service.update(id, task); return "redirect:/"; } While there is less “magic” involved here, compared to adding items, Spring does allow some neat things, for example, in stead of binding each property individually (the description and the completed), you can simply add a Task parameter to your method and Spring will fill the properties for you, allowing us to just send it to the service and redirect it back to the findAll() method. If you reload the application and check the checkbox next to one of the tasks, you’ll see that the page gets reloaded, this means the form successfully got submitted and the task was updating. To guarantee that it works you can simply refresh the page, and you’ll see that the checkbox is still checked (or unchecked if you unchecked one of the tasks), meaning that your change successfully got persisted. Deleting a task The final part of this application is deleting the tasks. While this no longer has anything to do with form validation, I like finishing something I started and a full CRUD application seems to be a good point to end this article, so all we need is the delete part now. To do that we do something similar to the update part, by adding another form with the ID as a hidden field on the form, wrapping it around the delete button: <form th: <input type="hidden" name="id" th: <button class="button u-full-width" type="submit">Delete</button> </form> Compared to the update form there’s nothing new here, and the method we have to add to the controller is similar as well: @RequestMapping(method = RequestMethod.DELETE) public String delete(@RequestParam Long id) { service.delete(id); return "redirect:/"; } So, if we test it out, you’ll see that the page reloads as well and the item should properly be deleted. Conclusion While it’s hard to imagine a world without JavaScript these days, this would be a solution if you really would have to, but honestly, this code is quite cumbersome compared to JavaScript libraries and frameworks nowadays. Does this mean that the entire code is obsolete? Certainly not, bean validation with Spring is pretty useful, certainly for validating your REST API’s.
http://g00glen00b.be/spring-form-validation/
CC-MAIN-2017-26
refinedweb
2,152
50.26
Attributeerror: module collections has no attribute mutablemapping error is because of internal code changes in the 3.10 version. If you are using any syntax related to the collections module which is compatible with the 3.9 version over the python 3.10-based python environment, you will get this error. In this article, we will explore the best ways to fix module collections has no attribute mutablemapping error. Attributeerror: module collections has no attribute mutablemapping ( Solution ) – There are multiple approaches to fixing these issues. In this section, we will address them one by one. Solution 1: Downgrading the python version to 3.9 version or less – Since this error is specific to python 3.10 version. Hence we will downgrade our python version version to 3.9 or any compatible lower version. All you need to install the lower version successfully. It will replace the older python version. It means you do not have to explicitly uninstall the current python version. Solution 2: Changing the import statement – Actually, since the internal structure is changed in the 3.10 version so have to use two different ways for importing this mutablemapping module. Here is the syntax difference- For version 3.10 or above – from collections.abc import MutableMapping For version 3.9 or lower – from collections import MutableMapping If you want this environment completely dynamic then call the below code. import collections if sys.version_info.major == 3 and sys.version_info.minor >= 10 from collections.abc import MutableMapping else from collections import MutableMapping The above code will check the current python major and minor versions. On the basis of the available configuration, it will flow with the correct syntax. This is a standard way to make code version independent. `Solution 3: Upgrading related package – In some scenarios, upgrading the below setup packages along with the requests module, etc has resolved this error. Hence if the above two have not resolved the error completely then firstly we should try these set of commands. After this, we should again try solution 2. pip install --upgrade pip pip install --upgrade wheel pip install --upgrade setuptools pip install --upgrade requests Hope now you are able to fix the error collection that has no attribute mutablemapping. In case of any query please comment below. Thanks Data Science Learner Team Join our list Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
https://gmailemail-login.email/module-collections-has-no-attribute-mutablemapping/
CC-MAIN-2022-33
refinedweb
401
59.3
I can't count in mod 15 apparently; on GHC HEAD it occurs every 14. I've traced the 15 -> 14 change to this commit:, which increases the size of GCDetails and RTSStats with an extra field. I'm looking at Criterion internals, and seeing an inconsistency in the allocations reported by GCStats and RTSStats. Here is a small reproduction: {-# LANGUAGE CPP #-} module Main where import GHC.Stats import System.Mem (performGC) main :: IO () main = do runOldThing 1000 #if __GLASGOW_HASKELL__ >= 802 putStrLn "Running new:" runThing 1000 #endif runOldThing :: Int -> IO () runOldThing n = loop n 0 >> return () where loop 0 _ = return 0 loop count x = do performGC stats <- getGCStats putStrLn $ show (count `mod` 15) ++ ": " ++ show (bytesAllocated stats - x) ++ " num: " ++ show (numGcs stats) loop (count-1) (bytesAllocated stats) #if __GLASGOW_HASKELL__ >= 802 runThing :: Int -> IO () runThing = loop where loop 0 = return () loop n = do performGC stats <- getRTSStats putStrLn $ show (n `mod` 15) ++ ": " ++ show (gcdetails_allocated_bytes (gc stats)) ++ " num: " ++ show (gcs stats) loop (n-1) #endif This code just performs a garbage collection and then prints the stats in a loop. Here is a snippet of the output. ... 4: 8840 num: 1967 3: 4880 num: 1968 2: 4880 num: 1969 1: 4880 num: 1970 0: 4880 num: 1971 14: 4880 num: 1972 13: 4976 num: 1973 12: 4976 num: 1974 11: 4976 num: 1975 10: 4976 num: 1976 9: 4976 num: 1977 8: 4880 num: 1978 7: 4880 num: 1979 6: 4880 num: 1980 5: 4880 num: 1981 4: 8840 num: 1982 3: 4880 num: 1983 2: 4880 num: 1984 1: 4880 num: 1985 0: 4880 num: 1986 14: 4880 num: 1987 13: 4976 num: 1988 12: 4976 num: 1989 11: 4976 num: 1990 10: 4976 num: 1991 9: 4976 num: 1992 8: 4880 num: 1993 7: 4880 num: 1994 6: 4880 num: 1995 5: 4880 num: 1996 4: 8840 num: 1997 3: 4880 num: 1998 2: 4880 num: 1999 1: 4880 num: 2000 On the left, I've included the gc number mod 15 to show that exactly every 15 gcs, there is an extra 4k bytes reported. This output was made with 8.2.1. On 7.8.4, 7.10.3, and 8.0.2 it's every 23. And on 8.4.0.20180204 it's every 14. I've played around with extra allocations between garbage collections, but the interval remained constant. I tried poking around the rts, but I've been unable to determine if this is a bug or just unavoidable noise. It appears that building all the docs on a single platform is not possible, unfortunately. Haddock cannot process .hsc files, but we cannot generate the associated .hs files because we do not have the headers. For example, Win32/System/Types.hsc includes windows.h and so cannot be preprocessed. I've worked through a number of these problems in Hadrian, and opened a PR for comments. Some more comments specifically about this ticket: Cabal's guide's configuration requires the "Read the Docs" theme. Packaging the theme inside the folder or requiring the user to install it both seem wrong to me, so it might be nice to have a default theme for local building. But that would have to be changed in the cabal/Cabal/doc/conf.py source. Building all of the docs on a single platform should be doable. However, the current implementation needs package-data.mk generated by ghc-cabal configure. This fails to configure Win32 on Unix, and I would imagine the opposite is also true. However, I believe the data should be attainable just from the cabal file. I'll need to do some research to see if we can get by without ghc-cabal for the docs. I have managed to eliminate the need for gen_contents_index, which just leaves the mkDocs script. This script really just unifies the documentation built on both platforms, so solving the above would remove the need for this script. Likewise your upload script should become much simpler. Do we want to include the Haddock and Cabal guides in distributions? As it stands right now, the distribution only has the zipped html of the Haddock guide. We could also provide full html (which would be browsable like the GHC guide) and/or a pdf. What happens to the mkUserGuidePart code now? I seem to have left a bit of orphaned content laying around the build system and code comments. I'm making a pass at the documentation in general, and next up on my list is simplifying the building process a bit. I hope to create something like docs/dist-install that would collect and hold all of the generated documentation. This would help in writing the docs, as you could verify links, say, from the user's guide to the library documentation. This would also allow installation and distribution to mainly be a cp. While looking into this, I ran into some discrepancies between releases. The contents of !\~ghc/VERSION/docs for 7.10, 8.0, and 8.2 are all different. 8.0 dropped *.ps files and haddock.pdf. 8.2 now additionally holds a windows folder that has a wide array of binaries and documentation. Going back further, the Cabal user's guide used to be included. I searched around for a reason that it was dropped and only found a git commit citing the change from docbook. But now most sources use Sphinx, so we could generate and include them if we so wished. The Cabal guide can be found at: The Haddock guide can be found at: Unfortunately, the links are the most prominent when Googled. To bring this back to a point, I would like to clean up the docs folder of the distribution. The windows folder inside seems like it might be a mistake. Additionally, Cabal and Haddock have ended up in strange positions, and I think they probably could both use the same solution. This was wrapped into the change from mkUserGuidePart to Sphinx based generation. Tables are manually sized in flags.rst, but even still it's not perfect. LaTeX can't break flags like -XGeneralizedNewtypeDeriving, which means that the sum of the minimum column widths is larger than the width of the line. I believe there aren't any egregious overlaps remaining, but some flags do spill out of their cells. Column widths are set in a percentage format that looks like |\Y{20}|\Y{40}|\Y{10}|\Y{30}|, which is reasonably amenable to change. Things are mostly working now, but a question has arisen. How do we want to categorize the flags? We could just have them grouped by source file (inflexible but simple). Alternatively, we could add an additional option to the flag declaration that chooses the category (flexible but requires specifying where every single flag should go). I could even make it an optional override deal where it is put under source file by default, but you can choose another if you want. I believe the current system is mostly source file based, but not entirely. I'm hesistant to add a 4th field to the declaration, so I thought I would ask if this is something worth supporting or not. I have a proof of concept for this. It's looking like the best plan is to wrap the table info into the declaration of a flag, something like: .. ghc-flag:: -v :shortdesc: verbose mode (equivalent to -v3) :type: dynamic :reverse: (none for this flag) Longer decription here... Which would render as: Longer description here and then the table could look like, | **-v** | verbose mode (equivalent to -v3) | dynamic | | The main tasks remaining are figuring out the formatting of the table, determining what variables actually need to be passed around, and moving all the info into the flag declarations from the mkUserGuidePart files. The Sphinx tutorial on writing extensions is very similar to this:. That one just happens to use a list instead of a table. I'll see what I can do. I am not familiar with Sphinx outside of this brief expedition, but I would certainly be willing to take on those tickets. I'm making a full pass of the users guide in general, so I can work those in too. This just happened to be a relatively self-contained chunk. I've submitted a patch implementing option 2. Additionally, a fair bit of work was done to bring all the other pieces into line, so now almost all flag related references should be valid. Those that are not (there are about 350) are references to flags with no documentation. I noticed that most places in the docs that referenced flags with arguments manually appended them to the ref anyway. This way they are now automatically included. I also added a note about how to quickly find the proper flag argument names for easy copy-pasting. I'm working on cleaning up the users guide, and I have come across an issue with referencing ghc-flags. Essentially, it has to with flags that take arguments. You can see a couple examples if you go to the flag reference here:\~ghc/latest/docs/html/users_guide/flags.html\#redirecting-output The top flags all have valid links, but the code to generate them is doing it slightly wrong. Let's consider -o ⟨filename⟩ for instance. There needs to be a specific reference name for this flag. This name serves a couple purposes. First, it forms the end of the url (i.e. .../separate_compilation.html#ghc-flag--o). Second, the form of cross-references to it (i.e. :ghc-flag:-o``). There are two options: Option 1 (The current system): We exclude the arguments from the reference name of the flag. So :ghc-flag:-o is a valid reference that gets rendered as __-o__. The main issue with this system is loss of information. If someone wanted to include the flags in the link, they would have to do `:ghc-flag:`-o ⟨filename⟩ <-o>, which would render as -o ⟨filename⟩ but link to the same place as -o. This also leads to possibly different choices for the argument name. In fact, the definition has ⟨file⟩ but the reference table has ⟨filename⟩. Option 2: We include the arguments in the reference name. So to make the reference, one would have to match the definition exactly: :ghc-flag:-o ⟨file⟩ which would be rendered as __-o ⟨file⟩__, and `:ghc-flag:`-o ⟨filename⟩ would not be a valid reference. This solves the loss of information issue from option 1, but does require the person documenting to check for the exact argument wording. I would argue for the second option as it is more consistent, but either is workable. Also note that the current parser automatically converts < (less than) into ⟨, so dealing with special characters is very easy. And these issues also apply to flags that use '='. I thought it best to ask before I converted everything to one way of dealing with these.
https://gitlab.haskell.org/trac-patrickdoc.atom
CC-MAIN-2021-21
refinedweb
1,834
72.26
When trying to run the basic tests I get the following error: Module not found gopigo Any suggestions? When trying to run the basic tests I get the following error: Module not found gopigo Any suggestions? Hey xpop43, Are you using the Dexter Industries image or SD card. Looks like the GoPiGo library is not installed on your pi. Can you try running the install script from here following the directions on the Readme and let us know if that helps. -karan Hi Karen, I thank you for your reply. I did do the install as you instructed. I should point out I am using my own SD card. After retrying the install I still get the following error message when running the “basic_robot.py” script. File “basic_robot.py” line 39 in <module> from gopigo import * Import error: No Module named gopigo I than ran the tests to produce the log file which I am including. I thank you for any help you may be able to offer. Hey, From the output of the troubleshooting script, it looks like the install script did not work properly for you. Can you try running it again sudo chmod +x install.sh and then sudo ./install.sh and then try again. Can you post the output that you get when you run the install script. -Karan Karan, The reinstall did the trick. Everything is now working. Thank you for your help!
https://forum.dexterindustries.com/t/module-not-found-gopigo/1097
CC-MAIN-2022-33
refinedweb
238
84.37
table of contents NAME¶ execl, execlp, execle, execv, execvp, execvpe - execute a file SYNOPSIS¶ #include <unistd.h> extern char **environ; int execl(const char *pathname, const char *arg, ... /* (char *) NULL */); int execlp(const char *file, const char *arg, ... /* (char *) NULL */); int execle(const char *pathname, const char *arg, ... /*, (char *) NULL, char *const envp[] */); int execv(const char *pathname, char *const argv[]); int execvp(const char *file, char *const argv[]); int execvpe(const char *file, char *const argv[], char *const envp[]); execvpe(): _GNU_SOURCE DESCRIPTION¶ The exec() family of functions replaces the current process image with a new process image. The functions described in this manual page are layered on top of execve(2). (See the manual page for execve(2) for further details about the replacement of the current process image.) The initial argument for these functions is the name of a file that is to be executed. The functions can be grouped based on the letters following the "exec" prefix. l - execl(), execlp(), execle()¶ The const char *arg and subsequent ellipses. By contrast with the 'l' functions, the 'v' functions (below) specify the command-line arguments of the executed program as a vector. v - execv(), execvp(), execvpe()¶ The char *const argv[] argument is an array of pointers to null-terminated strings that represent the argument list available to the new program. The first argument, by convention, should point to the filename associated with the file being executed. The array of pointers must be terminated by a null pointer. e - execle(), execvpe()¶ The environment of the caller is specified via the argument envp. The envp argument is an array of pointers to null-terminated strings and must be terminated by a null pointer. All other exec() functions (which do not include 'e' in the suffix) take the environment for the new process image from the external variable environ in the calling process. p - execlp(), execvp(), execvpe()¶ These functions duplicate the actions of the shell in searching for an executable file if the specified filename does not contain a slash (/) character. The file is sought in the colon-separated list of directory pathnames specified in the PATH environment variable. If this variable isn't defined, the path list defaults to a list that includes the directories returned by confstr(_CS_PATH) (which typically returns the value "/bin:/usr/bin") and possibly also the current working directory; see NOTES for further details. If the specified filename includes a slash character, then PATH is ignored, and the file at the specified pathname is executed..) All other exec() functions (which do not include 'p' in the suffix) take as their first argument a (relative or absolute) pathname that identifies the program to be executed. RETURN VALUE¶ The exec() functions return only if an error has occurred. The return value is -1, and errno is set to indicate the error. ERRORS¶ All of these functions may fail and set errno for any of the errors specified for execve(2). VERSIONS¶ The execvpe() function first appeared in glibc 2.11. ATTRIBUTES¶ For an explanation of the terms used in this section, see attributes(7). CONFORMING TO¶ POSIX.1-2001, POSIX.1-2008. The execvpe() function is a GNU extension. NOTES¶.. BUGS¶ Before glibc 2.24, execl() and execle() employed realloc(3) internally and were consequently not async-signal-safe, in violation of the requirements of POSIX.1. This was fixed in glibc 2.24. Architecture-specific details¶ On sparc and sparc64, execv() is provided as a system call by the kernel (with the prototype shown above) for compatibility with SunOS. This function is not employed by the execv() wrapper function on those architectures. SEE ALSO¶ sh(1), execve(2), execveat(2), fork(2), ptrace(2), fexecve(3), system(3), environ(7) COLOPHON¶ This page is part of release 5.10 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at.
https://manpages.debian.org/bullseye/manpages-dev/execlp.3.en.html
CC-MAIN-2021-49
refinedweb
658
54.52
Can anyone explain me pointers to 2D array ?? I have to input array of string using and read them in another function but I am having a REALLY TOUGH time with pointersan anyone explin it to me or refer good guide to pointers ?? I am using borlnd c++ 3.0v. - 5 Contributors - forum10 Replies - 12 Views - 10 Years Discussion Span - comment Latest Post by Salem Alex Edwards 321 I think you need to be more concise with the requirements. You have 30 strings correct? Does this mean that they each cannot be more than 20 characters long (including the null terminator)? You must make your char[20][30] (or most likely char[30][20]) in pointer form, then convert it into an array of strings, or vice versa? What are the required functions to use in this project? mahlerfive 23 First of all, if you want 30 strings of up to 20 characters each, then your declaration should be the other way around, and you need an extra char for each null terminator (the character that ends a string): char axx0[30][21]; // 30 strings of up to 20 character Now for a little lesson on arrays/pointers. If you have a normal 1D array such as this: char myString[10]; This declaration does a few things... it makes a pointer to char (type is char*), allocates space for 10 chars somewhere in memory, and then makes the pointer point to the first char in that allocated space. The pointer is named myString. So really, myString is of type char*, a pointer to char. Now when you do something like myString[2] = 'A'; , what happens is it dereferences the myString pointer, moves 2 positions in memory, and puts the character 'A' there. Essentially myString[0] is the same as *myString, and myString[2] would be the same as *(myString + 2); Now, when we move to 2D arrays, something similar happens. When we declare char axx0[30][21]; , it makes a pointer to a pointer of char (type is char**) which is the variable axx0. Space is allocated for 30 pointers to char (char*), and axx0 will point to the first of those. Then, space is allocated for 21 characters for each pointer to char that was created, each pointer points to the first character of the corresponding 21 character sequence in memory. So, getting to the point, axx0 is a char**. If you want to send the 2D array to a function, you simply send axx0. The function should look like one of the following: void myFunction( char myArrayOfStrings[30][21] ); OR void myFunction( char myArrayOfStrings[30][] ); When accepting a multi-dimensional array as a parameter to a function, you must at LEAST include the size of each dimension except the last. You have the option of including the size of the last dimension if you wish. but How do I read it ?? like I pass the pointer to another function to echo the data. void Echo_dat ( char a[30][21],OR char* a[30][21] ?) { I want to read the string till it detects the string END. } will the normal nested for loop work for reading ?? Plz suggest me a good guide to pointers, I have my practical in around 2 weeks. The main program is :- /*==========================|| PRG-7 ||=================================== | Name - Atishay Kiran | Class- XII - A | Program info. - | | i) Program to Display | | \ Upper lalf of left diagonal | \ Lower half of left diagonal | \ sum of each row | \ sum of each colum | \ sum of left diagonal | \ sum of right diagonal | | Date 12th August | ==========================================================================*/ #include<iostream.h> #include<conio.h> #include<process.h> class matrix { private: int M[][20],row,col; public: char* sum_r(); char* sum_c(); int sum_d(); int input(); void display(); void diag_up(); void diag_dn(); }; //========================================================================= int matrix :: input() { cout<<"Input the number of rows in you matrix -> \n"; cin>>row; cout<<"Input the number of colums in your matrix -> \n"; cin>>cin; clrscr(); for(int i=0;i<row;i++) { for(int j=0;j<col;j++) { cout<<"Enter x= "<<i<<" y= "<<j<<" for the array -> "; cin>>M[i][j]; } } cout<<"\n\n Martrix Sucessfully Inputted !! \n"; } /*========================================================================= Sum of Rows The function will store the values of the sum of each row of the array in a CHAR 2D array. The End of file will be detected by a string 'end'. In a seperate non-member function to the class, the CHAR array will be passed and each string will be converted to a number using ATOI. ==========================================================================*/ char* sum_r () { char *a[20]; tHE PROBLES IS GIVING THE SUM OF EACH Row and coloum, TO THE USER. Hello, this is a small suggestion for your problem. This (the code is my solution to similar problem) is recommended in Stroustrup (C++ program language) book, about passing 2d arrays to functions. Try it and I hope it will help you with your problem. #include <iostream> void print(int* first, int dim1, int dim2) // pointer to first element of array; dim1, dim2 - // dimensions of array { for (int i = 0; i < dim1; i++) { for (int j = 0; j < dim2; j++) { std::cout << first[i*dim2 + j] << "\t"; } std::cout << "\n"; } } int main() { const int dim1 = 3; const int dim2 = 5; int v[dim1][dim2] = {{1, 2, 3, 4, 5}, {3, 4, 5, 6, 7}, {6, 7, 8, 9, 10}}; print(&v[0][0], dim1, dim2); } > int M[][20],row,col; You need to specify a size here. > char* sum_r () Since you can't return arrays (not without dynamic allocation, or trickery, which you're not ready for), the easiest thing to do would be to pass the array where you want the answer stored as a parameter. Eg. sum_r ( char answers[21][10] ); The main() call would be simply int main ( ) { char answers[21][10]; matrix var; // some other operations on var var.sum_r ( answers ); } > The End of file will be detected by a string 'end'. This is why it's 21
https://www.daniweb.com/programming/software-development/threads/141810/pointer-to-2d-array
CC-MAIN-2018-47
refinedweb
984
66.98
LRFS Part 4: Early Userspace: initrd and initramfs31 Dec 2018 This is part of a series of articles. You can find the first part here. Although init is considered the beginning of the Linux userspace, this is not technically the case. There are other facilities that are part of the userspace and run even before init. Using these is not mandatory, and as it happens we are not going to use them in our distro (not now, at least), but I thought it might be educational to examine them here. Why? So why do we need something to run before init? Here are a few cases that this might be necessary: Mounting the root file system might need access to kernel modules that are not built into the kernel, but are instead built as kernel modules and reside on the very file system we are going to mount. It is, of course, possible to built these into the kernel, but we might want to keep the kernel from becoming too large. This was especially the case before, when RAM used to be more limited than it is now. The root file system might be encrypted and it might need being decrypted before being mounted. The system might be in hibernation and need special treatment before waking up. The kernel provides two facilities for running a small userspace before the actual init: these are called initrd and initramfs, the latter being a more recent addition to the kernel, although both have been there for quite some time now. The names initrd and initramfs, although referring to distinct facilities, are frequently used interchangeably. initrdis a file system image that is mounted as root. It usually contains an executable named /linuxrcthat is run after the image is mounted. After performing any necessary preparations and mounting the real root file system in a temporary location, this program then uses the pivot_rootsystem call to switch to the new root and then unmounts initrd. initramfsis a file archive that becomes the root file system. An executable called /initon this archive is then run by the kernel, effectively becoming init (that is, PID 1). This can continue as an init, or later mount a new root and execthe real init. In the next two sections, we will examine each of these carefully and see some examples. initrd We will be using the following C program as the “early init”: #include <stdio.h> #include <unistd.h> #include <sys/types.h> int main(int argc, char *argv[]) { printf("Early Init\n"); printf("----------\n"); printf("PID=%d UID=%d\n", getpid(), getuid()); printf("----------\n"); for(;;); return 0; } Save this as earlyinit.c and compile it statically: gcc earlyinit.c -static -Wl,-s -o linuxrc Now create a file system image and copy linuxrc to it: dd if=/dev/zero of=image.img bs=20M count=1 mke2fs image.img sudo mount image.img /mnt sudo cp linuxrc /mnt sudo umount /mnt You can also compress this file: gzip -9 image.img You probably won’t be able to use your distribution’s kernel for this as support for initrd is probably not built into the kernel. Build a new kernel from source and make sure the CONFIG_BLK_DEV_INITRD and CONFIG_BLK_DEV_RAM options are set to y in the .config file. Like in previous sections, we will be using qemu to run the kernel and initrd. qemu has a -initrd option that we can use: qemu-system-x86_64 -kernel /path/to/bzImage \ -initrd image.img.gz \ -enable-kvm \ -append "console=ttyS0" \ -nographic Take a look at the output. Notice the PID reported in the output. It is not 1. An initrd is not an init. A real initrd would mount the root file system as part of its work. When initrd returns, the kernel assumes that root is already mounted and so proceeds to running init (from /sbin/init, for example). Let’s try this. Update the C program above like this: #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <string.h> int main(int argc, char *argv[]) { printf("Init\n"); printf("----------\n"); printf("PID=%d UID=%d argv[0]=%s\n", getpid(), getuid(), argv[0]); printf("----------\n"); if (strcmp(argv[0], "linuxrc") == 0) { /* running as initrd */ return 0; } else { for(;;); } } We are going to use this as both linuxrc and init. Recompile, like before and update the image like this: gunzip image.img.gz sudo mount image.img /mnt sudo cp linuxrc /mnt sudo mkdir /mnt/sbin sudo cp linuxrc /mnt/sbin/init sudo umount /mnt We won’t be compressing the image this time, since qemu does not accept a compressed image as an argument to -hda. Run qemu like this: qemu-system-x86_64 -kernel /path/to/bzImage \ -initrd image.img \ -enable-kvm \ -hda image.img \ -append "console=ttyS0 root=/dev/sda" \ -nographic Again we are not actually mounting the real root file system here. So in this case, when initrd returns, the kernel runs /sbin/init from the already mounted RAM disk (i.e. initrd iteself). In the output, you will see two invocations of our program, one as linuxrc, the other as /sbin/init. initramfs Originally, initramfs is supposed to be a an archive embedded into the Linux kernel itself. This archive is mounted as root and a /init file inside it is executed as init (i.e. with PID 1). What this incarnation of early init does is slightly different from initrd. First of all, initramfs cannot be unmounted. It usually deletes all of its contents in the end, however, chroots into the real root file system and invokes init using one of the exec system calls. pivot_root cannot be used in initramfs. klibc and busybox each have a utility (called run-init and switch-root respectively) that helps initramfs writers with the usual tasks (deleting files, chroot and exec, among other things). In order to try this, we’ll revert to the original version of our simple early init: #include <stdio.h> #include <unistd.h> #include <sys/types.h> int main(int argc, char *argv[]) { printf("Early Init\n"); printf("----------\n"); printf("PID=%d UID=%d\n", getpid(), getuid()); printf("----------\n"); for(;;); return 0; } Compile this as init: gcc earlyinit.c -o init -static -Wl,-s Now we have to create an archive, instead of a file system image. This is a cpio archive. The concept is very similar to the more widely used tar archive. Let’s create an archive with init as its only content: echo init | cpio -o -H newc | gzip -9 >initramfs The -H flag specifies the variant of cpio that the kernel uses. Now, as we said before, initramfs is an archive that is embedded inside the kernel and indeed when building a kernel you can configure an initramfs to be built inside the kernel. However, there is a simpler way of doing this as when the kernel receives a cpio archive instead of a file system image for its initrd parameter, it uses the archive as if it is a built-in initramfs archive. So in effect, you can pass the initramfs archive like an initrd to qemu. Let’s try it: qemu-system-x86_64 -kernel /path/to/bzImage \ -initrd initramfs \ -enable-kvm \ -append "console=ttyS0" \ -nographic You will see that this time our program is run with PID 1. It can simply do its work and exec the real init in the end. Tools for initramfs writers If writing an initramfs in C, in many cases, alternative C standard libraries are used in place of glibc which is feature-rich and very large. musl is one popular implementation of the C standard library that is used when size is important. klibc is another which, although not implementing the full extent of the standard library, has been specifically written for writing an early init. Both provide wrapper scripts for building against them. For musl, you can use the musl-gcc script: musl-gcc earlyinit.c -static -Wl,-s -o linuxrc while for klibc you can use klcc: klcc earlyinit.c -static -Wl,-s -o linuxrc Both provide very smaller executables than when linking against glibc. In many cases, the early init program is in fact written in shell script, so a shell and a number of utilities are included. You can use bash and GNU coreutils for this, but again these are quite large and all of their features is probably not necessary for the small initramfs script. busybox is one alternative, which includes a shell, and a large number of utilities, including the previously-mentioned switch-root. klibc also comes with a number of utilities, which are more limited, and smaller, than the ones with busybox. It also includes the run-init utility which helps with wrapping up the work in initramfs. A note on Ubuntu’s initramfs If you try taking a peek at the initramfs on an Ubuntu system with cpio, a few files are extracted and then you’ll receive an error message. At least, that’s how it is on Ubuntu 16.04 and 18.04 where I tried this. This is because the Ubuntu initramfs is actually two cpio archives put one after the other in a single file. Ubuntu 18.04 comes with an unmkinitramfs utility (installed with the initramfs-tools-core package) capable of extracting the contents of this initramfs. It’s a shell script so you can take a look at it and see how it actually works. Wrapping up supermin contains a small initramfs program that can be very educational to look at. Just get the source code and open the init/init.c file. I also found the following links very informative: - - - As I said in the beginning, we are not going to use either initrd or initramfs in our distro-to-be. So we’ll just carry on.
http://elektito.com/
CC-MAIN-2019-35
refinedweb
1,642
64.1
Does C# Need VB9's XML Literals? Microsoft’s two flagship languages, C# and VB, are set to diverge even more in the next release. One of the major features C# is not getting is XML Literals, and not everyone is happy about that. Despite the fact that XML Literals were originally designed for C-Omega, the C# team decided to not support them because they didn’t want to “tie the C# language with another specific language/structure”. The VB team, on the other hand, is betting heavily on deep XML support. Paul Vick summarized the C# teams concerns back in September of 2005:? Paul, the Technical Lead for Visual Basic, also gives some of the reasons why VB choose to support XML Literals despite these objections. Like so many things in life, it’s all about tradeoffs. The C# team looks at the problem and says, “It’s more important to us that we design a language that is as minimal as possible and whose pieces are guaranteed (as much as anything ever is) to retain relevance for the forseeable future. Therefore, we’re willing to sacrifice some usability and some programmer speed to ensure this goal is reached.” Perfectly valid. The VB team, on the other hand, looks at the problem and says, “It’s more important to use that we design a language that allows people to solve the problems that are confronting them today in as simple and straightforward manner as possible. Therefore, we’re willing to take the chance that some feature that is fantastically useful right now may lose relevance in the future and perhaps even become almost entirely useless (c.f. Gosub, On … Goto, Open/Close, etc.).” Also perfectly valid. Currently, the top search result for “VB 9 XML literals” is developer Steve Eichert post, XLinq has me wanting to code in VB.NET?!?! :#) . I’ve semi-recently gotten to XLinq and it has me envying VB.NET programmers! The Xml literal support within VB.NET is pretty sweet. Microsoft’s XML Team has posted some of the more recent changes to VB’s XML Literals. These include changing the Attributes axis from an Attribute object to a String, a slight change to the syntax for importing XML namespaces, auto-completion of tags, and treating all XML names as symbols in a manner similar to CLR variables. InfoQ Asks: Does C# Need VB9's XML Literals? Does C# Need VB9's XML Literals? by Tomas Petricek BTW: I think that XML literals in C-omega were more general than these in VB, beacuse they were used for initializing not only XML data, but also object structure. This concept is used in C# 3, but is realised using "object initializer" syntax. To
http://www.infoq.com/news/2007/03/CSharp-XML
CC-MAIN-2015-32
refinedweb
459
61.46
13 July 2010 06:28 [Source: ICIS news] SINGAPORE (ICIS news)--?xml:namespace> The country exported 474,928 tonnes of palm oil between 1-10 July as against the 435,148 tonnes it had exported during the same period in June, according to data from cargo surveyors, Intertek Testing Services. Exports of refined bleached and deodorised palm olein rose by 40,938 tonnes to 229,590 tonnes, while refined bleached and deodorised palm stearin exports were up 1,655 tonnes to 32,190 tonnes during the period. Refined bleached palm oil exports also increased by 1,843 tonnes to 52,540 tonnes, the data showed. There was a drop in exports of some palm oil products during the period, according to the data. While crude palm oil exports fell by 15,672 tonnes to 61,850 tonnes, crude palm kernel oil slid by 520 tonnes to 2,480 tonnes and palm fatty acid distillate exports fell 5,200 tonnes to 17,800 tonnes in July. While exports of some products had fallen, overall palm oil exports had risen on increased demand from India, the trader said. “Palm oil exports to Exports to Palm oil and its products are used in a wide range of industrial applications ranging from biodiesel to food stuffs, personal care products and deterg
http://www.icis.com/Articles/2010/07/13/9375872/malaysias-1-10-july-palm-oil-exports-rise-9-on-india-demand.html
CC-MAIN-2015-11
refinedweb
217
63.02
At 09/14/2012 09:36 AM, Hugh Dickins Wrote:> On Thu, 13 Sep 2012, Johannes Weiner wrote:>> On Thu, Sep 13, 2012 at 03:14:28PM +0800, Wen Congyang wrote:>>> root_mem_cgroup->info.nodeinfo is initialized when the system boots.>>> But NODE_DATA(nid) is null if the node is not onlined, so>>> root_mem_cgroup->info.nodeinfo[nid]->zoneinfo[zone].lruvec.zone contains>>> an invalid pointer. If we use numactl to bind a program to the node>>> after onlining the node and its memory, it will cause the kernel>>> panicked:>>>> Is there any chance we could get rid of the zone backpointer in lruvec>> again instead?> > It could be done, but it would make me sad :(> >> Adding new nodes is a rare event and so updating every>> single memcg in the system might be just borderline crazy.> > Not horribly crazy, but rather ugly, yes.> >> But can't>> we just go back to passing the zone along with the lruvec down>> vmscan.c paths? I agree it's ugly to pass both, given their>> relationship. But I don't think the backpointer is any cleaner but in>> addition less robust.> > It's like how we use vma->mm: we could change everywhere to pass mm with> vma, but it looks cleaner and cuts down on long arglists to have mm in vma.>>From past experience, one of the things I worried about was adding extra> args to the reclaim stack.> >>>> That being said, the crashing code in particular makes me wonder:>>>> static __always_inline void add_page_to_lru_list(struct page *page,>> struct lruvec *lruvec, enum lru_list lru)>> {>> int nr_pages = hpage_nr_pages(page);>> mem_cgroup_update_lru_size(lruvec, lru, nr_pages);>> list_add(&page->lru, &lruvec->lists[lru]);>> __mod_zone_page_state(lruvec_zone(lruvec), NR_LRU_BASE + lru, nr_pages);>> }>>>> Why did we ever pass zone in here and then felt the need to replace it>> with lruvec->zone in fa9add6 "mm/memcg: apply add/del_page to lruvec"?>> A page does not roam between zones, its zone is a static property that>> can be retrieved with page_zone().> > Just as in vmscan.c, we have the lruvec to hand, and that's what we> mainly want to operate upon, but there is also some need for zone.> > (Both Konstantin and I were looking towards the day when we move the> lru_lock into the lruvec, removing more dependence on "zone". Pretty> much the only reason that hasn't happened yet, is that we have not found> time to make a performance case convincingly - but that's another topic.)> > Yes, page_zone(page) is a static property of the page, but it's not> necessarily cheap to evaluate: depends on how complex the memory model> and the spare page flags space, doesn't it? We both preferred to> derive zone from lruvec where convenient.> > How do you feel about this patch, and does it work for you guys?> > You'd be right if you guessed that I started out without the> mem_cgroup_zone_lruvec part of it, but oops in get_scan_count> told me that's needed too.> > Description to be filled in later: would it be needed for -stable,> or is onlining already broken in other ways that you're now fixing up?We will test your patch, please wait some time.> > Reported-by: Tang Chen <tangchen@cn.fujitsu.com>> Signed-off-by: Hugh Dickins <hughd@google.com>> ---> > include/linux/mmzone.h | 2 -> mm/memcontrol.c | 40 ++++++++++++++++++++++++++++++++-------> mm/mmzone.c | 6 -----> mm/page_alloc.c | 2 -> 4 files changed, 36 insertions(+), 14 deletions(-)> > --- 3.6-rc5/include/linux/mmzone.h 2012-08-03 08:31:26.892842267 -0700> +++ linux/include/linux/mmzone.h 2012-09-13 17:07:51.893772372 -0700> @@ -744,7 +744,7 @@ extern int init_currently_empty_zone(str> unsigned long size,> enum memmap_context context);> > -extern void lruvec_init(struct lruvec *lruvec, struct zone *zone);> +extern void lruvec_init(struct lruvec *lruvec);> > static inline struct zone *lruvec_zone(struct lruvec *lruvec)> {> --- 3.6-rc5/mm/memcontrol.c 2012-08-03 08:31:27.060842270 -0700> +++ linux/mm/memcontrol.c 2012-09-13 17:46:36.870804625 -0700> @@ -1061,12 +1061,25 @@ struct lruvec *mem_cgroup_zone_lruvec(st> struct mem_cgroup *memcg)> {> struct mem_cgroup_per_zone *mz;> + struct lruvec *lruvec;> > - if (mem_cgroup_disabled())> - return &zone->lruvec;> + if (mem_cgroup_disabled()) {> + lruvec = &zone->lruvec;> + goto out;> + }> > mz = mem_cgroup_zoneinfo(memcg, zone_to_nid(zone), zone_idx(zone));> -);> + lruvec->zone = zone;> + }> + return lruvec;> }> > /*> @@ -1093,9 +1106,12 @@ struct lruvec *mem_cgroup_page_lruvec(st> struct mem_cgroup_per_zone *mz;> struct mem_cgroup *memcg;> struct page_cgroup *pc;> + struct lruvec *lruvec;> > - if (mem_cgroup_disabled())> - return &zone->lruvec;> + if (mem_cgroup_disabled()) {> + lruvec = &zone->lruvec;> + goto out;> + }> > pc = lookup_page_cgroup(page);> memcg = pc->mem_cgroup;> @@ -1113,7 +1129,17 @@ struct lruvec *mem_cgroup_page_lruvec(st> pc->mem_cgroup = memcg = root_mem_cgroup;> > mz = page_cgroup_zoneinfo(memcg, page);> -);According your comment, lruver->zone != zone if a node is onlined. Soit is not a bug, and VM_BUG_ON() should not be used here.ThanksWen Congyang> + lruvec->zone = zone;> + }> + return lruvec;> }> > /**> @@ -4742,7 +4768,7 @@ static int alloc_mem_cgroup_per_zone_inf> > for (zone = 0; zone < MAX_NR_ZONES; zone++) {> mz = &pn->zoneinfo[zone];> - lruvec_init(&mz->lruvec, &NODE_DATA(node)->node_zones[zone]);> + lruvec_init(&mz->lruvec);> mz->usage_in_excess = 0;> mz->on_tree = false;> mz->memcg = memcg;> --- 3.6-rc5/mm/mmzone.c 2012-08-03 08:31:27.064842271 -0700> +++ linux/mm/mmzone.c 2012-09-13 17:06:28.921766001 -0700> @@ -87,7 +87,7 @@ int memmap_valid_within(unsigned long pf> }> #endif /* CONFIG_ARCH_HAS_HOLES_MEMORYMODEL */> > -void lruvec_init(struct lruvec *lruvec, struct zone *zone)> +void lruvec_init(struct lruvec *lruvec)> {> enum lru_list lru;> > @@ -95,8 +95,4 @@ void lruvec_init(struct lruvec *lruvec,> > for_each_lru(lru)> INIT_LIST_HEAD(&lruvec->lists[lru]);> -> -#ifdef CONFIG_MEMCG> - lruvec->zone = zone;> -#endif> }> --- 3.6-rc5/mm/page_alloc.c 2012-08-22 14:25:39.508279046 -0700> +++ linux/mm/page_alloc.c 2012-09-13 17:06:08.265763526 -0700> @@ -4456,7 +4456,7 @@ static void __paginginit free_area_init_> zone->zone_pgdat = pgdat;> > zone_pcp_init(zone);> - lruvec_init(&zone->lruvec, zone);> + lruvec_init(&zone->lruvec);> if (!size)> continue;> >
http://lkml.org/lkml/2012/9/13/634
CC-MAIN-2016-36
refinedweb
942
56.15
5, 1945029 Related Items Preceded by: Clewiston progress Full Text f F : i r $i : THE CLEWISTON NEWS I 1 A ' It ".1 VOLUME 16-NUMBER 26 CLEWISTON, FIjORIDA, FRIDAY, JANUARY 5, 1945 SunsCRIPTION-'j2.; PER YEAR i - i : KIWANIS OFFICERS Belcher Oil CompanyTo GERMAN POW HANGS P. O. Rural StationsTo ,ROGERS IS SPEAKER Begin Operations, Be Established . \ 1 i ARE INSTALLED ON In Okeechobee Area SELF NEAR LIBERTY Middle of MonthMrs. AT GARDEN CLUB , I WEDNESDAY NilE William B. Powers, representing POINT AFTER ESCAPEThe .. Jewel Lawrence, acting postmaster MEETING THURSDAY :i i the' Belcher Oil Company of Miami, of the Clewiston office, stat- was in Clewiston Wednesday with ed this week that the three new rural - ---- l Ladies Night was, observed at the other company officials and a rep- body of Karl Behrens, eigh postal stations would be estab- J. Kenneth Rogers, representingthe :, Wednesday night meeting of the resentative of the Robert E. Clarke teen-year old German prisoner of I lished on the sixteenth of January.One Clewiston city commission, madea t. : 1 Kiwanis Club when the officers for Advertising agency of Miami and war at the Liberty Point camp, for of the stations will be locat- most interesting talk at the December 1, : 1945 were installed by Glynn Q. stated that his company' was readyto whom a general search was made ed at South Shore Plantation Village meeting of the Garden Club 1 Rasco of Miami Beach, lieutenant- move into the Lake Okeechobeearea. throughout south' Florida after he I' with Mra. Natevidad Rios de which was held at the Community I governor of the Southeast division was discovered to be missing at, four Stiehl as clerk, another will be at Center on'Thursday afternoon of last of the Florida district. Mr. Powers' did not elaborate on o'clock Saturday was ,found Monday Ritta Village where Mrs. Polly Grant week and gave the group of ladies Officers installed were: R. C.I i this statement so it is not known afternoon hanging from a tree about McLeod will be clerk and the third I present a glimpse of city govern.. I Wilson, president; G. H. Brown, vice- whether it, is the company's intentionto three miles from the camp on the will be at Benbow Village where, ment that many of them had never president and J. E. Beardsley, J. W. build service stations and bulk south side of the lake levee. The Mrs. Marion Tracy Ange will serve before seen. , l I Ezelle, D. C. Hancock, C./ A Martinez plants throughout' the area. Since body was found by an FBI agent I as clerk. Mr. Rogers pointed out that M. M. Prewitt, E. L. Stewart his company caters' largely ,to industrial from West Palm Beach. Regular window service will be Clewiston has no bonded indebtedness - 1 and B. L. Thompson as members users it is probable, that Following discovery of the prison- maintained at these stations but no and, that homeowners here really cf the board of, directors. they will confine their activities er's escape' on Saturday 'a general postal savings accounts will be handled know what homestead exemptionmeans : installation strictly to wholesale business.In alarm was sounded and local law and no war bonds will ,be sold. so far as city taxes are con- Following the impressive connection with the company's enforcement officers assisted mili These three stations will serve to cerned. He gave figures as ,to the I t service a talk was made Etherton by re- proposed expansion to include, the tary guards and FBI agents in a I take much of the labor off the already costs of city maintenance such as Glen H. tiring president, lake area an advertising contracthas general search of the area. Roads over-burdened clerks in the, cutting of weeds in vacant lots, gar- his appreciation - which he I in expressed been taken with the Clewiston were blocked and all passing cars Clewiston office for the' rural routes bage and trash collection, maintenance l i to the club for their coopera- out of Clewiston have stead- i News which calls for an advertise- were searched, authorities apparently grown I of streets, bridges, culverts, : tion during the past year, and commended - i his fellow'officers and com ment each week during the ;year ,of working on the theory' that the ily since established. parkways, parks. street lights all of : I ; 'mittee chairman on the handling of similar nature to the first one of prisoner would attempt to make his I which is done without any cost in i their duties during 1944. the series which runs this week. way out of the country. The agent t New Withholding taxes to the residents of the city. Definite! plans for the expansion the assumption I j R. C. Wilson, newly installed perhaps working on Fire vrotection'and- police protection - will probably be announcedvery to take his life Rates On Incomes I 4' president, made a talk on his plans program Behrens was seeking are also afforded without cost, each shortly. went to the levee canal where, the to the homeowner.The . 'i for the club year, and requested Effective Jan 1 , .j one present, ,visitors included, to prisoners are taken for swimmingat speaker also explained that write on slips of paper what they Masons And 'Eastern the site of the old Liberty Point Intermix the city has far less l labor and more of' John L. Fahs, Collector f' consider the most worthwhile project Fish Camp and soon. thereafter inadequate equipment now than it Star Hold JointInstallation found the body' about two miles west al Revenue, today called ;attention ; } I : which could be undertaken by had two years ago yet were havingto of employers and employees to the the club during the year. In his of that point. take care of four hundred more FridayMoore fact that January 1 and January 31, talk he, stressed the importance of Behrens left no note, but circumstances light and water customers than it 1945, are important dates in connec- :) the underprivileged child and youths indicated that he had taken did at that time. He also explainedthat tion with withholding of income tax '':: service work.Recognition. Haven Lodge No. 61, F. and his own life as there was no evidenceof jthe members of the city commission - from 1' jf +t was'given and a vote A. M. and Moore Haven Lodge No. violence discovered. The rope wages. by charter, serve without ':_ -of thanks taken to E. E. Kelly, honorary 116 0., E. S. held joint installationof used was from his own barracks bag. January 1 is the effective date any remuneration whatsoever. City : ;j club member, for a sizeable officers for the new year at one Behrens was one of the last groupof for the'ne1" rates of withholding income and utility rates were also ::'i donation to the underprivileged of the most impressive and well-at- prisoners brought to the Liberty prescribed by the Individual Income ( discussed and at the conclusion of I ti child fund.J. tended installations ever held her Point camp and had been capturedat Tax Act of 1944. By terms of that 1 his talk Mr. Rogers satisfactorily M. Stout, Jr., acted as pianist I The officers of the Eastern Star Cherbourg. Officers at the camp II Act, the new rates apply to all wages answered many of the questions during the evening. I ewre installed first with Mrs. Caro- said that there was no substantiation paid on and after January 1, regardless with which he was plied by the Guests at the meeting were: Mrs. line Bales acting as installing of- for the stories that he had been of when the wages were members. H Luther Owens, Mrs. G. 'H. Brown, ficers, Mrs. Stella Pirkle as Mar- the victim of other prisoners because earned. The new rates are intendedto Mr. Rogers' talk was at the con- Mrs. W. C. Owen, Mr. and Mrs. J. shal, Mrs. Mary Moore as Chaplainand of anti-Nazi beliefs. He had adjust each employee's withholding clusion of a brief business session : M. Stout, Jr., Mrs. G. H, Small, Mrs.J. Mrs. Elsie Jordan as Organist:, received no news from home since more closely to his actual during which the following ladies income tax. The new rates average E. Beardsley, Mrs. E. L. Stewart, Officers installed were: Mrs his capture. were voted in as members: Mrs. about the same the old rates, but as :Airs.-J. W. Ezille, Mrs. B. L. Thomp- Thelma Twiddy, as worthy matron; The body was sent to Camp Bland- Frank W. McCarthy, Mrs. J. Paul '4: L son, 'Mrs. ,R. l\{. Bishop, Mrs. G., 'B. C. C. Klutts, worthy patron, ; Mrs. ing Monday evening for, burial in I 'vary in' individual received cases. Employers' Bartz,: Mrs. M. M. Driver, Mrs, F,. ' :, : '- "Thonis.Mra;: C .A,, ;Martinez, 'Mrs. Mary Etheuton/; 'i",. "%IaM'' 'matron; the prisoner war .cemetery ther r alreadyhave detailed instructions Carl LongMrs .;3V 'IX::, Doty, Mrs.'VA - Circular"WT-Rev. in 1944, V. S. Mumfo"d" Mrs R. C; Wil Melvin Keen as' associate patron; Reames and Mrs. U. T. Koch., li li'N Mrs. Naomi Rogers treasurer Mrs.\ I' additional copies of which may be I and Mr. Rasco.Basketball .. ; Postwar street planning was discussed - Thelma Wright conductress Mrs. obtained at any" Collector's office. ; at some length and a motion Y DAVIDSON IS AGAIN January 31 is the deadline by , j Season I Naomi Dull, associate conductress; i was made and carried that the club which the law requires employers ; Mrs. Esther Klutts, ,chaplain; Mrs. assist in fertilizing the trees in r 'Opens Next Friday Elsie Jordan, organist; Mrs. Gayle to furnish each employee a With I Clewiston if the city will furnishthe I I Woodward as Ada; Mrs. Hazel Keen, ELECTED CHAIRMANOF holding Receipt on Form W-2 (Rev. fertilizer. Ruth; Mrs. Sally Towsend Martha showing how much wages were paid , The Clewiston Tigers and Tiger- Mrs. Sara Fountain, Electa Mrs.; I him and ]how much income tax was I, The January meeting of the club ; COUNTY BOARDHendry will] be tour of C. J. Gonterman's a withheld from his the j their during basketball -ettes will open sea- Rene Lanier, Esther; Mrs. J. W. wages ) son next Friday night at Moore Ha- Sexton, warder and J. K. Rogers, I calendar year 1944. These, receipt/ Osceola Groves and_ Ed W. Men- the Terriers and Ter- this I ninger I a noted garden authority of 1 'ven against sentinel have a special importance year : 'rierettes of that place. ( County News) because the new law authorizes I Stuart, will be the guest speaker. Neither Clewiston nor Moore Ha- Mrs. Pirkle as outgoing worthy The new board of county com- most employees to use their Receiptsas This promises to be a real treat and : ven teams 'have been able to get in matron, presented each of the installing missioners which took office Tues- simplified income tax returns. I all members are urged to make plansto I II I ,officers with a gift and in attend. day elected J. O. Davidson as chair- : : 'a great deal practice during the I' This new feature is explained in an Christmas vacation but it is expected I,turn was presented a gift by: her man-he served as chairman of the official leaflet entitled "How to.I Hostesses for Thursday's meeting! that plenty of action will be seen in fellow officers of the past year in old board-and decided that William Use Your Withholding Receipt as were Mrs. R. C. Wilson, Mrs. J. F. this 'game. The Tigers lost one of I I recognition the 'office. for her splendid work In T. Hull should continue as an Income Tax Return," and em- I Tippey, Mrs. G. N. Pitzen and Mrs.: 'their leading players, Marty WalE board secretary. ployers have been asked to distribute j I Foy Durrence. ; dron, to the services during the The Masons then conducted their ,Minutes of the double meeting copies to their employees. i Christmas holiday which gives the installation 'with J.% M. Couse actingas cannot be prepared for this issue of Collector Fahs also urged employers National War Fund installing officer and Carr Settleas the ,News but will be published next ' ; 'Terriers a slight edge for the open to be especially careful, when i--' ing engagement but the Tigerettes Marshal. week. preparing each Withholding Re Finances Many War :are believed to be evn stronger_ thanat Masonic Officers installed wereN. The old board wound up the year ceipt, to show the employee's home the close of the season last, year. V. S. Mumford worshipful master -: by approving minutes of previous address and social security number, I Related Agencies ; J. ,B. Cox, senior warden; J,. K. meetings and approving bills to date. as well as all other required Infor- 1 I -, !r .. 'School BoardReorganized Rogers as 'proxy for G. E. Etherton, On the new board, which went i into mation. The home address and social I The National War Fund organized - : Junior warden; C. W. Fuller, chaplain session after lunch, Charles E. security number are vital for just two ;years ago has to date Jan. '2nd .; Melvin Keen as proxy for M. Miner of Clewiston replaced G. E. identification purposes. distributed a total of 139295173. '"1; A. Thomas, as senior deacon; George Etherton and R. B. Waldron of west I An employer; is required to make 28 to its twenty-two member agen- " ;y Beck, junior deacon; W. H. Lanier LaBelle replaced George L. Poole. three copies of each Withholding cies for war philanthropies, it was ;: The Hendry County Board of senior I steward; H. J. Middloton, The new board raised the pay of Receipt. He must give two copiesto announced Winthrop W. Aldrich, : I ;}x: public instruction held its last meet- junior steward ;y and W. C. Owen. county laborers to a flat rate of $5a the employee, so that the employee president of the fund. I i ing of the old term and first of the tyler. I. E. Scott re-elected treasurer day, an increase of 50 cents over will have one copy to use for Ten thousand community war iz;' ,\ new Tuesday morning in the office' and W. L. Bellamy re-elected the, rate, being paid recently, afterit his return and another copy to keep. I funds representing the National War 1s'' of County Superintendent C. E. secretary were not installed. ''was brought out that help was Also by January 31, the employer I Fund have made two appeals for "Weaver. At the conclusion of, the installation very, hard to get and that workers must send the third copy to the I funds to support USO, United Sea- r There only one change on the ; ( was ceremonies refreshments cf were constantly leaving jobs because Collector of Internal Revenue, together men's Service, War Prisoners Aid1r.Tid ; three-district board, only 'one sandwiches, cake and coffee were they could get higher wages. with the regular] withholding I nineteen fiH'citn: relief agen- n' 1"!F' 'member being forced to run in 44, served by an Eastern. Star committee. Members of the new board are tax return (Form W-l for the I cies. The first appeal made in 1943 B. L. Stallings was elected over the Davidson, chairman, 1IinerValdron, !last quarter of 1944, and a state- was for $125,000,000 and the second - J \. member of District 2, Dil- r retiring I A. J. Evers and Asa Townsend ment on Form W-3 reconciling the in 1944 for $115,000,000 is still ,; ',' lon Hall,' who was unable to be present - Clewiston Man Is wage and tax amounts as shown by in progress. The work of the memo : at the meeting. * the quarterly retui'ns with the sim- I ber agencies for the period up 'tl 1 Farmers Must File E' f Bills were approved for payment Injured In WreckIn ilar amounts as shown on the Withholding i September 30, 1945! will be f as business for the old term was 1 'f" Performance ReportsAll Receipts. I IISchool nanced through, fund.T which a s /'wound up. The new board elected Moore : Haven -- still coming in from the 1944 q; E. M. Cornette, Clewiston member , ., I I II paigus of community war fun t.i. To Resume t. as chairman, the office held by Hall Edward Hendry County farmers, and When the National War r 'the past two years. The third Vaughn, an employee of this,includes LaEelle, Denaud, FeUla: , Chalker Monday Morning was organized it had USO, s . and Lund, Clewistou nember' is M. O. Allen of Felda, whoserves was Clewiston Devil's I 1 and Garden , t painfully but not seriously injured areas I Seamen's Service and War, ? also Denaud - ! I must file 1944 performance reportsnot ers Aid and twelve for I I Members are elected for a four- Sunday evening when he lost control later than January 15, accord- I Clewiston school pupils will wind : ft: , agencies as members I , term. Both Cornette and Allen of his car, a 1939 Ford coach their sixteen Christmas holidays - year up day , I ing to County Agent H. L. Johnson.January I and it nances the work of tw ; ran into the roadside canal at ;; v ill be forced to run in two years 15 is the final cut-off date Sunday and return to classes ' I I ' in 'It they desire to serve again. the i! first corner east of Moore Haven as announced by the AgTicuU'uralAdjustment again Monday morning.No r related agencies wh' i i'a i on road 67. been ninety-one geograp I announcement has as yet Agency Washington, six continents. rAt 'i j STATE CATTLEMEN TO MEET I Vaughn was en route to Moore Each farm icport shoulf,., show n'.ado by the school board concern- the time r' ,I \ Haven to have supper with Mr. and the extent of soil-building practices horn Eart(' vacation or other possible there were stain 'r,, : The State Cattlemen's Association I' Mrs. Joe Gill and was alone when carried ort during 1014!) whichis I vacations during the latter part Rhode Isl] n 'I. ill meet on January 10 in Plant the accident I of the I : occured. He was made for AAA payment, 'the county year. to affiliat ' t: ''Si9tv and all interested: cattlemen of thrown out, or was able to escape agent says. For terraces,> damsor '\ ., FnItm :/ ' '1. luth Florida are urged to attend. 1 from the car after it left the road I ; reservoirs, if the practice is to be I "We want every farmer who has !t.pe Hillsborough Association will and before it went into *the canal eligible for payment under the 1944 carried out approved practicethis''I- - l Jk'if: hosts and a big barbecue is plan-I" and made his way' to town for help. program, the dirt-moving operationsmust year to receive OJ'v yments that! a' d.I He was badly bruised and cut about- Agenl 3 have been completed duringthe have been earned, County / M'\ the face, shouldQr and arms and 1944 program year and reported H. L. Johnson says "and so we 'asf) . Uncle Sam still needs all the War after being treated by Dr. D. M. before ! ( January 15, 1945, even though that every farmer file his perform 1 'L- ,rlmds'you can afford to buy every Draughn of Moore Haven is re- j such work as vegetative protectionof ante report without, delay and : ) > > : tr r day. I IcupeTating at his home here outlets has not been, completed. I quest his neighbor to file also% I I \ I \ 1 .; } - r - j ti" 1 ; -, v 1--... 0 --.---', -, _. "- -- ;;;... ;l ,, _. --.----- ------,.,.., ; UNIFORM IMPROVED,INTERNATIONAL -- OUSEHOLD , H SUNDAY | 1 INTSI . GEORGE F. WORTS .. n _' Lesson . / WN.U.RELEASE Use a large oiled silk bowl cover By HAROLD L. LUNDQUIST. D. D. THE STORY THUS FAR:, Zone Corey, "You need sleep. Sleep as late as Zorie walked out into the lanai, Of Released The Moody by Western Bible Institute Newspaper of Union.Chicago. for an emergency shower cap. 'I:: Who bates herself for being so meek, Is you can. Good night." with the admiral trotting along behind -e- ;= railroaded into taking a job she does not "But ." Zorie began with de her. Glue a bright piece of linoleumover want, assisting Admiral Duncan write his termination. Then she realized that Steve the old worn top of a card in a white toweling dress- Lesson for January 7 'j memoirs. She is in love with Paul Duncan table. the admiral's grandson. Aboard the she must be patient with Paul. ing gown, was stretched out in one .i.ie steamship Samoa en route to Hawaii, There were many people with whom : of the long bamboo chairs. His pallor Lesson subjects and Scripture texts selected ;: she dances with Steve, Paul's brother. she hadn't the slightest intention of was' shocking. His eyes were Council and copyrighted by International Coffee grounds make a good of Religious Education: used by Paul is furious, and warns Zone against being patient, but Paul was not one pale. He looked really ill. permission. sweeping compound for use in the him, claiming that Steve is a Nazi spy. of them. She adored Paul. She He grinned slowly' and said, "Hello basement. r On returning to her stateroom after take would see to it that he lost his grim- glamour girl!" THE CHILDHOOD ,OF JESUS -e- ing dictation Zone discovers that her ness and his stuffiness. Then Paul The admiral said, "Zorie, do you Clean your brick hearth by first I{ ':I,. While alone on r notebook Is missing. would be perfect.She think you're going to feel like work- LESSON TEXT-Matthew 2:1323.: scrubbing with a stiff brush and i.i her : I : deck a brutal hand is clamped over GOLDEN TEXT-Behold. I am with thee: month, she is scooped up and thrown went to bed. She was almost ing today?" and will keep thee In all places whither hot soapy water. Rinse clean and :: ' overboard. She avoids the propellersand asleep when Amber let herself in. "Yes," Zorie answered, "I feel thou goest..: Genesis 28:15. wipe dry. Let stand a day and ;j manages to catch a life ring which Amber opened and closed the doorso very much like working today." then coat with boiled linseed oil. : tome sailor has tossed into the sea. carefully that it didn't make a "I wanted to get on with the Bat- Matthew is the Gospel of the King 1\\ I sound. She undressed noiselessly.She tle of Manila Bay, then I thought and His kingdom. It stresses the CHAPTER X took the greatest pains not to we'd go back and finish up those fulfillment of prophecy in the com- . disturb the girl who had slapped her chapters on my first years in Annap ing of Christ,' the' King. After His SNAPPY 'FACTSABOUT :i "The nurse told me not to disturb face. ,olis." rejection, it tells us of the Church, you for a while. I'd like to see youas The telephone awoke her at a lit- For a moment, her resolve fal "the kingdom in mystery," and of . It's im- tle before nine.,, ,Amber reached for tered.,Habit-that detested old habitof the death of Christ for our sins His : soon as possible. very RUBBERCommercial portant, are you alone?" it, answered it, and handed it to' meekness-made'her pliant. But resurrection for our justification, "I will be," said Zorie. She Zorie, saying, "It's for you, dar- the wavery feeling passed. and His'glorious coming again. With- , reached for her dressing gown and ling." "I'm sorry," Zorie said. "I'm sor- out assigning definite verses to our F/- said to Amber: "You won't mind go- It was the admiral. He hoped he ry to let you waste all that time. II points"we note that: ing out for a while. My fiance wantsto hadn't waked her. He hoped she you want me to help you with your I. Men Received or Rejected talk things over." was feeling well after her experience memoirs, Admiral, the chapters on Jesus.It motor vehicles In r 11 There was droll amusement inAmber's -hm' ? Annapolis and everything, perhaps, has always been so. Men, thenas the U. S.,, based on gasolino "Ah, yes! Your fiance! Not "Do you suppose you could drop but a short chapter" on Manila Bay now, were either for Him or allotments, are expected to " at all dear." around sometime this morning? he go overboard. run 56 billion miles my against Him. The world of today is a year. j Zorie was sitting at the dressing asked. "Steve" is very anxious to, "Now, wait a minute-" the admiral far different from that of the first Reduced to truck tire wear, c' I I table, thoughtfully considering Amber's talk to you. began."I ." century, but the difference is all on that represents a tremendous ! array of cosmetics, when Paul "How is Steve?" mean it, she 'said. "Steve was the outside. Almost breathtakinghave number of tires. f. knocked. She opened the door. He "He'll be all right. Steve is pretty right yesterday. ,You're the only been the of mod- developments The rubber used in masks is alive the came in and closed it. tough, you know. person who can tell storyof gas the lit ern science, but these have not now 100 per cent synthetic. 6 ; "Was_it something he ate? Zone Duncan family. From the She half lifted her arms, expect- still changed the heart of man. He j I ing that he would seize her and hug asked. tle I've heard of it,it's a fascinating fears and hates and fights and sins. Never use a tube in a tire and kiss her out of sheer relief that "The doctor couldn't say. I'll 'tell story, .a really wonderful story. If larger, or smaller than that she was alive. him you'll be, around as soon as you want me to help you on a book- 1. Men Are Against' Christ. for which it was designed by 1 He looked her over quickly. He you've had a' bite of breakfasthm that's going to be the book." How do men show their rejection ofGod's the manufacturer. Premature She heard chuckle from the Son? Just as 'they did at nodded jerkily. "You were lucky," ? a failure will result'if you do. !d he.said. "You certainly were lucky. "All right," said Zorie. She wouldsee bamboo chair. His birth, by: To return full mileage, syn- Are you sure you're all right?" Steve when she got around to it. The admiral's eyes were fiery. His a. Fear. Herod was afraid lest thetic tubes must be lubri- j "Yes," Zorie said. "I'm all right.- u" obstinate chin was unusually promi- the coming of this One"should resultin cated with vegetable'oil soap She was surprised that her feeling "" nent. His right fist 'was clenched. the loss of his ill-gotten gains. solution when mounted on : i about Paul hadn't changed. Every- "- '\ With it he banged on the table. His anger 'and fear 'made all .Jerusalem rims. : I thing else had changed, but she was ) "Nobody is going to tell me how afraid. t12Az : , still in love with Paul. With a little :; ) I'm going to write my book!" he b. Indifference. When the Wise : 1 11 working over, Paul would be satis- 1c shrilled. "Not even you, Zorie. No, Men asked where Christ was to be factory. sir! I write my own book my own born, the priests and scribes knew ti "Well," Paul said in a business- way-or there won't be a book!" exactly where to find the facts in the . like way, "I've just had a long talk :ta. "Very well," Zone said serenely. Holy Scriptures, but having done so, \\1- I with the captain-with the doctor "There won't'be a book. As a mat- they relapsed into utter indifference. '" and the chief officer sitting in. Thisis o ) ter of fact, there isn't any portion of They had no interest in the fulfill- pretty serious, Zorie." srr( any book. All of yesterday's dicta- ment of the prophecy.c. : "Yes," said Zorie, "I suppose it tionShe lifted her hands in a Hatred. 'Herod poured out the, BFGoudrich:1L ''l isn't an everyday occurrence." ,.;. gesture indicative of emptiness. violence of his heart by killing the, , "You didn't destroy it!" the ad. first-born. He was'the first of She'realized she had to make a many decision. Her sole desire just now 1 miral gasped." who have ,raged against the Christin I 4 was to find;out who had thrown her "Gone! said" Zorie. futile anger.d. If I.:; 'i "Good girl! said Steve. f overboard. Sorrow. The tears of the mothers - 4 r "I'm sorry, Admiral," Zorie said, of but. JO 1 '. greater ...., .... ... ....:.,. .' .' :: : '_n:'. ':' 'w.. :.': .. ":-.J'! ( - ::, .;:nrL' ftl."N-r\C': \ : ,o: 1 '": t.\ I -<4i .1 : :. ', Editorial THE (COLUMBIA from S. C.) STATE : : .,'.. nlSJ: (; .li\ ; : '. r j ... . :. ,:.....:..... ,RAILROAD\ ... :, " ....Ji ::. iiii:! :::: ". CLEWISTON REALTY CORPORATION r: SERVING I AMERICA'S I NEW FRONTIERFRln. , ':i.. _____, ! ', "r., _, I I , Contact Us | Permissions | Preferences | Technical Aspects | Statistics | Internal | Privacy Policy © 2004 - 2011 University of Florida George A. Smathers Libraries.All rights reserved. Acceptable Use, Copyright, and Disclaimer Statement Powered by SobekCM
https://ufdc.ufl.edu/UF00028415/01029
CC-MAIN-2019-39
refinedweb
4,941
74.69
In our sorting algorithm series of tutorials, today we will focus on the Bubble Sort algorithm. Previously, we looked upon an introduction of sorting algorithms and focused primarily on selection sort. Let us learn about Bubble sort in this guide. Like selection sort, bubble sort is also considered as one of the simplest sorting algorithms. It works on the principle of continuously swapping elements in the list until they are in the correct order. Bubble Sort Algorithm Let’s see how to sort a list of integers given to us in a form of an array. Suppose we have an array of 5 integers named X with unordered numbers. Our aim is to sort the following numbers in increasing order of values by using a bubble sort algorithm. In this type of algorithm, we will scan the array several times from left to right. Each scan will be considered as one pass on the array. First Pass – Bubble Sort We will first compare the elements at index 0 and index 1. When we will scan the array and we are at a particular position, we will compare the element at that particular position with the adjacent element at the next position. When we are at index 0, then we will compare the element at index 0 and the element at index 1. If the element at the current position is greater than the element at the next position, we will swap the two elements. Now we have element ‘4’ at index 0 and element ‘1’ at index 1. As 4 is greater than 1 we will swap the two elements: Now the list of elements will be something like this. ‘1” has moved to index 0 and ‘4’ has moved to index 1. Now we will move to the next position which is index 1. Check if the element at index 1 is greater than the element at index 2. In our case it is not true so we will not swap the elements and move onto the next index. For the next position we will again compare the elements of the current position and its adjacent position. For index 2 the element is ‘5’ and its adjacent index 3 has element ‘2’. As 5 is greater than 2 thus we will swap the two elements and they will move to different positions. ‘5’ will move to index 3 and 2 will move to index 2 as shown below: Now we will move to the next position which is index 3. At index 3 we have the element ‘5’ and index 4 we have the element ‘3’. As 5 is greater than 3 hence we will swap the two elements. Now ‘5’ will move to index 4 and ‘3’ will move to index 3. As you will notice, this whole process is pushing the highest element towards the higher indices at each step. Our highest element was ‘5’ and by the end of this process it has moved to its appropriate position. After one pass on the array, the highest element will reach the last position. In other words we can say that ‘5’ has ‘bubbled’ up to the right most position in the array. The first pass on the array is like running a loop from 0 to (n-1) considering ‘n’ is the number of elements in the array. If X[i], the element at position i, is greater than than the element at position (i+1), then we will swap the two elements. Otherwise, we will move to the next position. However for i=n-1, X[i+1] would be out of the range as there is no element after the last one. So instead of running the loop from i=0 to (n-1) we will run it from i=0 to (n-2). We do not want to access an index that will be out of the range of the array. Next Pass – Bubble Sort Now we will perform another pass on the array. Once again we will keep comparing the adjacent elements and swapping then when required. In the next swap, the second largest element will now end up at its appropriate position which is index 3. For our list, the second largest element is ‘4’ and after the first pass in present at index 1. After the second pass completes, this element will bubble up to index 3. Lets see how it happens. We will first compare the elements at index 0 and index 1. If the element at the current position is greater than the element at the next position, we will swap the two elements. Now we have element ‘1’ at index 0 and element ‘4’ at index 1. As 1 is less than 4 hence we will not the two elements and move ahead to the next position. Now we will move to the next position which is index 1. Check if the element at index 1 is greater than the element at index 2. In our case it is true so we will not swap the elements and move onto the next index. Now element ‘4’ will move to index 2 and element ‘2’ will move to index 1. For the next position we will again compare the elements of the current position and its adjacent position. For index 2 the element is ‘4’ and its adjacent index 3 has element ‘3’. As 4 is greater than 3 thus we will swap the two elements and they will move to different positions. ‘4’ will move to index 3 and ‘3’ will move to index 2 as shown below: Original list of elements: 4,1,5,2,3 After first pass: 1,4,2,3,5 After second pass: 1,2,3,4,5 With every pass on the array, the array will be divided into two parts: the sorted part and the unsorted part. After the first pass, the element at index 4 is sorted and the rest are unsorted. After the second pass all the elements are at their appropriate positions. In our example it only took us two passes on the array to get the list sorted in increasing order of values however it can take several passes until all the elements get sorted. With each pass, the highest element in the unsorted array will bubble up to the highest index in the unsorted half. In general, if we will conduct (n-1) passes we are guaranteed to be sorted. Pseudocode Bubble Sort Algorithm Below you can view the pseudocode for the bubble sort algorithm: BubbleSort(X,n) { for j=1 to n-1 { for i=0 to n-2 { if (X[i] > X[i+1]) { swap(X[i],X[i+1]) } } } } To monitor the time complexity of Bubble Sort algorithm we will make use of the pseudocode given above. The total running time of this algorithm will be the total running time of the statements inside the nested loops. Assuming the following statements take a constant time C to execute considering the worst case scenario: if (X[i] > X[i+1]) { swap(X[i],X[i+1]) } Both the outer and inner loops will run (n-1) times. So the total time taken as a function of n will be: T(n) = (n-1)*(n-1)*C =(Cn^2)-2Cn+1 Thus, we can say that the time complexity is O(highest order) so O(n^2). As you may see selection sort also had the same time complexity as that of bubble sort. Both of these are relatively simple sorting algorithms but are not time efficient as compared to other sorting algorithms that we will learn about in later tutorials. Improving Time Complexity of Bubble Sort Algorithm However, we can modify our program code slightly to improve the time complexity in certain cases of Bubble sort. Modification 1 The first thing that we will change is that we do not need to run the loop till (n-2) in all cases. As you already know by now, at any stage during the sorting process, the array will be divided into unsorted and sorted parts. There is no need to go into the sorted part of the array. For the first pass, we will run the inner loop till (n-2). For the second pass we will run the inner loop till (n-3). Likewise, for the third pass, we only need to run the inner loop till (n-4) and so on. In general, we will run the loop till (n-j-1), so when j=1 we will run till (n-2), when j=2 we will run till (n-3) and so on. In this way we are improving the loop logic. However, the time complexity still remains O(n^2). BubbleSort(X,n) { for j=1 to n-1 { for i=0 to n-j-1 { if (X[i] > X[i+1]) { swap(X[i],X[i+1]) } } } } Modification 2 Let us modify our code further to improve the time complexity. As you may remember the example array we used to demonstrate bubble sort got sorted after only 2 passes. Hence running the loop more times will be redundant. If the list is already sorted, then there will no swaps. If we go to a pass without swapping anything then definitely at that stage the list is already sorted. Using this theory we will modify our algorithm further as shown below: BubbleSort(X,n) { for j=1 to n-1 { flag =0 for i=0 to n-j-1 { if (X[i] > X[i+1]) { swap(X[i],X[i+1]) flag=1 } } if (flag==0) break } } Now we have included a variable called ‘flag’ and set it to zero. This will be used to monitor if we need to continue the loop or not. Once the condition X[i] > X[i+1] is true for any i then we will swap the elements and also set the flag value to 1. When we will come out of this loop, after a pass if is flag =0 then it means there was no swap so we do not need to conduct any more passes. Thus we will break out of this loop. This way we will avoid making unnecessary passes once the array is sorted. Best Case For the best case, if our array is already sorted, then the inner loop will execute only once to figure out that it is already sorted. Assuming the following statements take time C in the worst case: if (X[i] > X[i+1]) { swap(X[i],X[i+1]) flag=1 } So now the time taken will be C*(n-1). The best case for our algorithm will be O(n). In an average case, taking (n/2) passes to exit the loop so the inner loop will also run (n-1) times so time complexity will still be O(n^2) Bubble sort is in place and a stable sorting algorithm with time complexity ranging from O(n^2) for worst-case and O(n) for the best case. Bubble Sort Algorithm Code in C #include <stdio.h> void swap (int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; } void BubbleSort (int X[], int n) { int flag; for (int i = 0; i < n - 1; i++) { flag = 0; for (int j = 0; j < n - i - 1; j++) { if (X[j] > X[j + 1]) { swap (&X[j], &X[j + 1]); flag = 1; } } if (flag == 0) break; } } int main () { int X[] = { 4, 1, 5, 2, 3 }; BubbleSort (X, 5); for (int i = 0; i < 5; i++) { printf ("%d", X[i]); } } 12345
https://csgeekshub.com/c-programming/bubble-sort-algorithm/
CC-MAIN-2021-49
refinedweb
1,947
68.6
# Even shell scripts require unit tests Once a upon a time I moved to brand new project. And without much thought, I decided to take DevOps responsibilities (after a long period of Frontend). Huge mono-repository (Angular and Node.js) gives rise to many specific problems. And this project was no exception. At the very beginning CI/CD duration was about 1.5h. And that was the biggest problem to take care of. But at first, I want to talk about "**B**ourne**a**gain**sh**ell", cause CI/CD automation almost entirely was implemented by means of shell scripts (Bash). In context of huge mono-repo even regular build becomes a piece of odd stuff. That`s why a huge amount of scripts with complicated logic inside (build, test, deploy, generation of release notes, collection of logs and metrics, ...) was another significant problem. Regardless of lang, quality of complex logic should be under control. It is no secret that key aspect of code quality control - is tests. For example, to refactor safely major logic should be covered with tests. We decided to keep shell scripts untouched and cover the major ones with tests before any refactoring. Of course, it is possible to use Jest (or Mocha) with a bunch of awful utils to test shell scripts. This approach is a bit wordy and has no value if scripts under test are written in Bash. Also I have no idea how to mock external shell commands (such as *curl, ls, touch, npm, ...*) with Jest or similar framework. In our particular case it was great to have the following to test CI/CD scripts: * Tiny testing framework with no assertions API. Double square brackets statement covers majority of cases; check [this](https://devhints.io/bash#conditionals) out for more detail. * Tests isolation (for parallelization). * Mock API (to mock external shell commands). * JUnit reporting format (to integrate with CI). It was not hard to implement appropriate testing framework from scratch <https://github.com/redneckz/red-shell-unit> ### How to run tests Lets start from the very basic example: add.sh ``` #!/usr/bin/env bash echo $(( $1 + $2 )) ``` This script just adds the first argument to the second one and outputs the result to *stdout.* One of the approaches is to place tests along with modules. This approach simplifies things, cause technically there is no need to explicitly point out path to shell script under test. Path can be computed relative to spec. add.spec.sh ``` #!/usr/bin/env red-shu.sh it 'should add two numbers' # Act result=$(run 2 2) # Assert [[ $result -eq 4 ]] ti ``` In order to make this test up and running shebang should reference *red-shu.sh.* It is a wrapper which provides core functionality (*it/ti/run/mock*) and tests isolation*.* *it/ti* commandsdeclare isolated block to test the only requirement. For each block subshell is initiated. If block exits with non-zero code, appropriate requirement turns red. Framework provides *run* command to execute script/command under test. Such decoupling makes refactoring less expensive. For example, you can move or rename scripts along with corresponding tests without difficulty. The best technical solution is a solution that does not require any new components or modules. That`s why exit codes are used to interpret test results. In this case, no dedicated assertion API is needed. Bash`s double square brackets statement is powerful enough to cover most needs and assert anything you ever wanted. Please check [this](https://devhints.io/bash#conditionals) out. Also commands like *grep* or *diff* are suitable for more complicated kinds of assertions. ### How to mock external commands Mocks are just necessary to write unit tests. Most dependencies should be mocked to test module functionality in isolation and highlight external parts of contract. The implementation of mocks turned out to be surprisingly straightforward. To mock something just write regular function named appropriately: ``` function node() { mock::log node "$@" if [[ "$1" == --version ]]; then echo v16.4.0; fi } ``` *mock::log* command makes it possible to assert invocation of mocked commands as follows: ``` node --version mock::called node --version ``` Under the hood, *mock::log* writes every and each invocation to temporary file; *mock::called -* just *greps* this file. Also regular expressions could be used to assert args: ``` mock::called node '.*' [[ $(mock::called_times node '.*') -eq 999 ]] ``` Optionally, the following utility allows to declare mocks without implementation: ``` mock node node --version ``` Lots of shell commands require *stdin* as well as args. That was one of the reasons this shell-based framework to take its place. For example, to pipe something to script/command under test just use basic shell structures: ``` echo "Lorem ipsum..." | command under test ``` Or: ``` diff ./file.txt <(printf '%s\n' 'first line' 'second line' 'third line') ``` To mock command which require *stdin* and assert such input: ``` # Arrange mock::stdin wc # Act run # Assert mock::consumed wc "some line" ``` ### How to report test results Ofcourse, test result should be binary - either passed or failed. There should be no need to interpret test result manually. This framework offers a simple approach. As mentioned above, test is considered red if exit code is non-zero, otherwise it is green. On the other hand, parsable output is a mandatory feature for each testing framework to make it possible to integrate with IDE, CI/CD and whatever else. The framework produces *TSV* . For example: ``` $ add.spec.sh REDSHU CASE 2020-02-24T12:39:01+0300 add.sh 1 should add two numbers REDSHU PASS 2020-02-24T12:39:02+0300 add.sh 1 ``` Columns: 1. REDSHU - constant prefix 2. CASE/PASS/FAIL - test case status 3. Timestamp 4. Script/command under test 5. Test case ID 6. Requirement description *Jenkins*, *Bamboo*, *GitLab CI/CD* and all of them support *JUnit* reporting format. This framework comes with special utility to reformat test output to *JUint* format: ``` $ add.spec.sh | red-shu-2-junit.sh ``` ... I would be grateful if you share your experience of testing of CI/CD scripts. Please try [Red Shell Unit](https://github.com/redneckz/red-shell-unit). I`m open to your proposals and new ideas.
https://habr.com/ru/post/655297/
null
null
1,018
58.89
If you haven't been living under a rock you have probably heard of Web 3.0! One of the most important parts of a full-stack is authentication. So let's see how to authorize users with their Metamask wallet in a Next.js app. If you don't know what is metamask then check out their website Setting up the app Create a new next app npx create-next-app next-metamask Navigate into the app cd next-metamask Installing the required dependencies npm i @walletconnect/web3-provider moralis react-moralis # npm yarn add @walletconnect/web3-provider moralis react-moralis # yarn Start the server npm run dev # npm yarn dev # yarn Get Moralis Credentials Go to moralis and signup/login. After that click on Create new Server and select TestNet Server By selecting it you will see a popup. Fill in the details, and click the Add Instance button. After the server is created click on view details We are going to need the server URL and Application ID Building out the authentication system Adding the environment variables Create a .env.local file in the root of your folder and add the env variables like this- NEXT_PUBLIC_MORALIS_APP_ID=<app_id> NEXT_PUBLIC_MORALIS_SERVER_ID=<server_id> You need to replace the values of the variables with the credentials you got from Moralis. Wrap the app in a MoralisProvider Go to _app.js and wrap the <Component {...pageProps} /> with the Moralis Provider with the env variables like this- <MoralisProvider appId={process.env.NEXT_PUBLIC_MORALIS_APP_ID} serverUrl={process.env.NEXT_PUBLIC_MORALIS_SERVER_ID} > <Component {...pageProps} /> </MoralisProvider> Now import MoralisProvider from react-moralis import { MoralisProvider } from "react-moralis"; Creating the sign-in button I am going to do create the login button on the home page, feel free to create it on any page you need. Get the authenticate function from the useMoralis hook- const { authenticate } = useMoralis(); You also need to import the hook from react-moralis import { useMoralis } from "react-moralis"; Create a button like this- <button onClick={() => { authenticate({ provider: "metamask" }); }} > Sign in with MetaMask </button> Now if we click on sign in, it will open the metamask extension for sign in. %[] Show signout button if the user is signed out We need to get a few more things from the useMoralis hook like this- const { authenticate, isAuthenticated, logout } = useMoralis(); Create a ternary operator to show the logout button, if the user is signed in otherwise show the sign-in button- {isAuthenticated ? ( <button onClick={logout} > Logout </button> ) : ( <button onClick={() => { authenticate({ provider: "metamask" }); }} > Sign in with MetaMask </button> ); } Now our sign in and sign out is working 🥳🥳 Getting the user data Let's see how to get some basic data like their eth address and username. When the user is authenticated, you can add this fragment to show the userName and their address wallet- <> <button onClick={logout}>Logout</button> <h2>Welcome {user.get("username")}</h2> <h2>Your wallet address is {user.get("ethAddress")}</h2> </> You need to get the user from the useMoralis hook as well- const { authenticate, isAuthenticated, logout, user } = useMoralis(); The userName is very random 😂but it can help in some cases and the eth address can be used for transactions. It was this easy to implement authentication of metamask with moralis 🤯 Hope you found this tutorial useful and stay tuned for more of these web 3.0 tutorials ✌️ Discussion (2) thank you this helpul AF. the NEXT_PUBLIC_piece is essential b/c you get an error if you don't put it b/c these env vars need to be exposed on the browser Yeah. Glad you found it useful
https://dev.to/byteslash/metamask-authentication-with-moralis-in-nextjs-1hbc
CC-MAIN-2022-05
refinedweb
590
55.07
I am trying to create a simple invoice program for a school project. I have the basic layout of my program. The large text boxes on the left are for the invoice, and the ones on the right are for the price of that input. I want the text boxes to return the input into them, and assign it to say JobOne. The next step is that I need these values to be send to a file in Notepad when the 'Send To Invoice' button is clicked. I am really stuck here, I've tried so many different combinations of things, and I'm forever getting "TextCtrl" object is not callable. Any help would be greatly appreciated. I've taken out my messy attempts to get the problem working and stripped it down to its barebones. import wx class windowClass(wx.Frame): def __init__(self, *args, **kwargs): super(windowClass, self).__init__(*args, **kwargs) self.basicGUI() def basicGUI(self): panel = wx.Panel(self) self.SetSizeWH(1200, 800) menuBar = wx.MenuBar() fileButton = wx.Menu() exitItem = fileButton.Append(wx.ID_EXIT, 'Exit', 'status msg...') menuBar.Append(fileButton, 'File') self.SetMenuBar(menuBar) self.Bind(wx.EVT_MENU, self.Quit, exitItem) yesNoBox = wx.MessageDialog(None, 'Do you wish to create a new invoice?', 'Create New Invoice?', wx.YES_NO) yesNoAnswer = yesNoBox.ShowModal() yesNoBox.Destroy() nameBox = wx.TextEntryDialog(None, 'What is the name of the customer?', 'Customer Name' , 'Customer Name') if nameBox.ShowModal() ==wx.ID_OK: CustomerName = nameBox.GetValue() wx.TextCtrl(panel, pos=(10, 10), size=(500,100)) wx.TextCtrl(panel, pos=(550, 10), size=(60,20)) wx.TextCtrl(panel, pos=(10, 200), size=(500,100)) wx.TextCtrl(panel, pos=(550, 200), size=(60,20)) wx.TextCtrl(panel, pos=(10, 400), size=(500,100)) wx.TextCtrl(panel, pos=(550, 400), size=(60,20)) self.SetTitle('Invoice For ' +CustomerName) SendToNotepadButton = wx.Button(panel, label='Convert to invoice',pos=(650, 600), size=(120, 80)) def SendToNotepad(e): f = open("Notepad.exe", 'w') f.write(()) call(["Notepad.exe", "CustomerInvoice"]) self.Bind(wx.EVT_BUTTON, SendToNotepad) self.Show(True) def Quit(self, e): self.Close() def main(): app = wx.App() windowClass(None) app.MainLoop() main() If you manage to help me, I thank you!
http://www.howtobuildsoftware.com/index.php/how-do/60k/python-windows-wxpython-wxpython-getting-input-from-textctrl-box-to-send-to-notepad
CC-MAIN-2019-22
refinedweb
359
56.21
Animate your world with ThreeJS and TweenJS During one of our last hackdays at Marmelab, I discovered ThreeJS through a subject that has become one of my favorite since my integration period... The game of reversi. I've developed a 3D scene offering a realistic and immersive experience of the reversi gameplay, complete with a board, disks, interactions. At some point, I wanted to add animations, and I had to make a choice. Let me explain the pros and cons of programmatic animation compared to manual ones. ThreeJS, When 3D Meets 3W As its name suggest, threeJS is a JavaScript library which brings 3D capabilities to the World Wide Web. It acts as a lightweight facade between your code and some great browser features such as WebGL, Canvas, CSS3D, and SVG. ThreeJS lets you create geometries programmatically, or import them from JSON files. It is the same for animations. Let's review the different possibilities to program animations. Manual Mesh Animations, The Use Cases In the traditionnal world of 3D, it's a common thing to animate meshes directly in a 3D authoring tool, be it Blender, Maya, or any other blending tool. Source: 3dartistonline.com Although these tools give you infinite possibilities because you can control all keyframes individually, they are also very complex to take over. Moreover, since all vectors are stored for each frame of the animation, this results in heavy files, which take longer to import into projects. Here are the pros and cons of the manual blending: Pros - Limitless - Lets you preview in instant - Lets you develop some new skills Cons - Exported files are heavy - No control at runtime Declarative Mesh Animations, The Simple Path? ThreeJS is a fantastic tool that lets you create very complex environments. But in somes cases, animating objects from a blending tool can be overkill and time-consumming. This is especially the case when the goal is to add a simple translating, rotating or scaling animation to a mesh. That's why I've looked for a simpler way to add flipping animation to my board disks. TweenJS is a JavaScript tweening library published under MIT license, which is part of the createJS suite. It allows to create transitions both on object and CSS properties. The way TweenJS works is very simple. For each "tick" (triggered update), TweenJS determines a new intermediate value, and assigns it to the wanted property. To achieve this task, TweenJS computes a simple "cross product" from different variables. First, it takes the time elapsed since the animation "start" trigger. For this elapsed time, it defines a percentage which is used to compute the transitional value of the changed property between start and end. Assume that you want to change the position of a cube on the "x" axis from 0 to 100 pixels in 10 seconds, and that the "tick" is triggered every 1 second. Therefore, the different computed values for the "x" axis will be subsequently 10px, 20px, 30px and so on. Of course, this is just one example, in real life it is common to use a ticker which is triggered about every 16.66ms, be 1000/60 for 60fps with requestAnimationFrame. Here is a small app to show you the concept in a more "comprehensive" way. In this example, you can traverse the time through a simple slider, have an overview of computed properties, and see the final rendering. codepen.io might track you and we would rather have your consent before loading this. Another advantage of declarative animations is the possiblity to chain them. Indeed, each animation is a simple JS object which can be stored, muted and used consecutively or simultaneously to another one. For example, you can wrap your animation objects into a Promise, and benefit from a full functional animation system. import { Tween, Easing } from 'tween'; const getDiskFlip = disk => ( new Tween(disk.rotation) .to({ x: -disk.rotation.x }, 400, Easing.Elastic.InOut) .onStart(() => { new Tween(disk.position).to({ z: [40, disk.position.z] }, 400).start(); }) ); const flippedDisks = [...]; const diskFlips = flippedDisks.map((disk, index) => ( new Promise((resolve) => { getDiskFlip(disk) .delay(50 * index) .onComplete(resolve) .start(); }) )); Promise.all(diskFlips).then(() => { // Do what you want when all disk flips ends }); Here are the pros and cons of the declarative blending: Pros - Easy to use - Very lightweight (compared to manual blending files) - Combine multiple animations Cons - Very hard to make complex animations Conclusion My experience with ThreeJS was very interesting. Although difficult to dive in at first sight, it was very intuitive and productive after a while. The possibilities that ThreeJS offer out of the box without any skills in 3D are very significant when we want to create some multi-dimensionnal projects in no time. Associated to ThreeJS, TweenJS is enough to let me create pleasant motions to my projects. Considering that transitions and animations are no longer an option these days, that's very important. In other cases, ThreeJS offers the possibility to import manual animations. The opportunities are endless.. for the pleasure of your eyes, but for the developer experience too ;)
https://marmelab.com/blog/2017/06/15/animate-you-world-with-threejs-and-tweenjs.html
CC-MAIN-2022-27
refinedweb
842
55.34
Map Making with Google Sheets and React Data visualizations have gotten a lot more popular over the last 5-10 years with the rise of software like D3, Tableau, and infographics. Maps just might be the original data visualization. In fact, maps are so commonplace that we don’t often see them in the same realm as the newer/shinier forms of data visualization. But like other data visualizations, they are just a representation of data (spatial in this case). For almost every web application that works with spatial data, maps are essential. There are a variety of libraries for building maps in React-based applications. This tutorial will focus on building a simple google map using React, Google Sheets, and the very powerful (and well-maintained) google-map-react library. In my previous article, I covered how to make a simple React app that pulled data in from a Google Sheet using the sheets API. We’ll be building upon that to make a simple map using that same data. Let’s Build a Map of Sweet Views A little backstory on the demo app we’ll build: the San Francisco Bay Area is full of hills. On some of these hills, you can find public spaces with incredible views of the ocean, city, bay, and various neighborhoods. After having your head in a computer all day, there’s no better way to zoom out, admire your gorgeous and expensive city, and think about how small you are. But if you just moved to the area, you might not know where to find these great views. Hence the need for a map! Let’s help people get to places like this Here are some of my favorite views in the bay area and the data we’ll be using for this app: Install Dependencies and Set Required Values To add a map to our original project (clone here) , we first need to install google-map-react: $ yarn add google-map-react With that done, let’s create a MapAndMarkers component that we’ll call in our main App component and pass some props to. Let’s first call the component in our main App.js file (and we’ll build it after). import MapAndMarkers from './MapAndMarkers.js' The GoogleMapReact component (from google-map-react) has a few required props in order to make a map. Two of these props are center and zoom. These are, logically, the minimum for having a map. The map needs to know which tiles (map images) to load and center on and how far to zoom in. Let’s have these live in our parent App’s state. We can change these state values later (with user events) to have our components re-render. So state will now look like this in the component: Google maps zoom values must range between 1 (the whole world) and 20 (down to specific buildings). These center coordinates are located roughly in the San Francisco Bay. This zoom level of 10 shows the general Bay Area. Now pass these to the MapAndMarkers component: <MapAndMarkers markers={this.state.items} zoom={this.state.zoom} center={this.state.center} /> Create MapAndMarkers Component We are now going to create a very simple MapAndMarkers component. I’ll put comments in the code to explain what is happening: This component will render a map and markers that looks something like this: Pretty ugly, right? The only reason I did this was to show that google-map-react can render any component on a map. It can be a map pin/marker, a custom animation, shapes, or just plain text like above. This library gives the React developer a lot of freedom to make maps in a component-driven way. We are simply rendering components on a map. Other mapping libraries (e.g. tomchentw/react-google-maps) might give you more HOCs and built-in methods to play with, but I found they didn’t follow the React small-composable-components paradigm as much. Make Prettier Map Markers Let’s make our map markers more marker-like with some icons. Feather icons is a well-maintained and lightweight icon library. React-feather offers feather icons as components. Let’s use that. $ yarn add react-feather We import the feather map pin icon simply enough: $ import { MapPin } from 'react-feather'; And change our marker to this: Getting warmer: How About a Tooltip? A tooltip would go a long ways toward making these markers look a bit more map-like. There are dozens of React tooltip libraries out there. They vary greatly in terms of their APIs and maintenance. As with any library, I recommend some caution and research before adding a tooltip library to your project. There are few things more frustrating than finding your issue is the same issue that many other have (and the maintainer hasn’t accepted pull requests in many months). Rc-tooltip is a well-maintained tooltip library and has a straightforward and robust API. Implementing the tooltip is quite straightforward: $ yarn add react-tooltip This gives us clean, animated tooltips for our map icons. We’ve now covered the basics of rendering map points on a Google map and giving them cute icons and tooltips. There’s so much more we can do, of course. Future tutorials will delve into responding to user events like hovering on the map and opening and closing our tooltips using state and props. The code for this tutorial is here:
http://brianyang.com/map-making-with-google-sheets-and-react/
CC-MAIN-2018-51
refinedweb
916
71.75
Hello, I am trying to connect to a XML file that is stored on a device and this XML file is password protected with a username and password. If I open a web browser and type in the URL to the XML it asks for a username and password (User: admin / Pass: admin) and it loads up the XML file fine. However, I am now trying to load this XML up in VB.net (2012) but I seem to get an error saying: The remote server returned an error: (401) Unauthorized. and the following line is where it stops on with the above error: However I know the username and password is correct as I could load it up in the web browser.However I know the username and password is correct as I could load it up in the web browser.Code: Dim response As System.Net.HttpWebResponse = request.GetResponse() I am using the following VB.net code to do this: My App.config file looks like this:My App.config file looks like this:Code: ' Create a WebRequest to the remote site Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("") ' NB! Use the following line ONLY if the website is protected request.Credentials = New System.Net.NetworkCredential("admin", "admin") ' Call the remote site, and parse the data in a response object Dim response As System.Net.HttpWebResponse = request.GetResponse() ' Check if the response is OK (status code 200) If response.StatusCode = System.Net.HttpStatusCode.OK Then ') MsgBox(contents) ' Now you have a XmlDocument object that contains the XML from the remote site, you can ' use the objects and methods in the System.Xml namespace to read the document Else ' If the call to the remote site fails, you'll have to handle this. There can be many reasons, ie. the ' remote site does not respond (code 404) or your username and password were incorrect (code 401) ' ' See the codes in the System.Net.HttpStatusCode enumerator Throw New Exception("Could not retrieve document from the URL, response code: " & response.StatusCode) End If Does anyone know why I am getting the 401 Unauthorized error?Does anyone know why I am getting the 401 Unauthorized error?Code: <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.net> <settings> <httpWebRequest useUnsafeHeaderParsing = "true"/> </settings> </system.net> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> </configuration>
http://forums.codeguru.com/printthread.php?t=534275&pp=15&page=1
CC-MAIN-2017-51
refinedweb
397
57.27
October WSG Meetup: Microformats | Comments (15) Posted in Events on 17th August 2006, 9:32 pm by Stuart Due to going on holiday in September I’ll be missing out on both Barcamp London and d.Construct. This has also made it really impossible for me to organise the second WSG event for September (when it should have been as I wanted to do these events every two months), not to mention a lot of you will be having a busy month anyway, given the cool stuff happening. So the plan is that the next WSG event will be held on a thursday in October and the topic for the whole evening will be Microformats. Now I think this really is a fascinating topic and the purpose of the event will be to explain what microformats are all about and to get all of you to start using microformats in your work where possible if you aren’t already started doing so. To help with the planning of this event I’m interested to know, is there anything about microformats that you’d like to see covered at this event? I’m looking into venue options in central London presently and I’m also interested in securing a more geek-friendly venue for drinks afterwards so if you have any ideas for either of those please let me know. I’ll post more details as soon as I have them. I’d like some discussion/instruction about how to mark-up recurring events (for example, those constituting a weekly programme schedule, where each program is more or less the same, and in the same slot, from week to week). Not sure if I’ll be able to make to the meetup, but still, would be great to see this covered amongst other things. How about the applications of microformats? It’s all very well and good understanding microformats, but what are the various uses for them across al the different genres of web site? How about some case studies for things like ecommerce sites, corporate sites, blogs, portfolios etc.? Great choice of subject though. Looking forward to it already! Oooh, excellent. I’d like to know how to mark up the cost of an event (and also a reduced cost for booking early). I had a look through the specs when I was marking up some data that needed just this, and I couldn’t see anything that fitted. I’ll definitely be there. Probably a good call not having it in September - it really is going to be a busy month. Currently I’m number one on the waiting list for Barcamp London, I’m down in Brighton on the 8th, before scooting straight up to Nottingham on the 9th, I’ve got my birthday to fit in there somewhere, and I don’t think I have a weekend free until well into October. It’s a busy life… Count me in. Not sure what you should cover, but there’s some overlap with the WSG group and the microformateers (myself being in both). I’d suggest a good overview talk for new comers (applications of, semantic web) and maybe a slightly more advanced topic. This might be a cool WSG meeting. However, I’m not traveling three hours (on a week day) to the big smoke, just for a couple of hours. However, the Multipack will be holding some presentations soon enough, and I’ve been writing a Microformats presentation for that. @Trovster: Understandable that you’d choose not to travel 3 hours on a weekday. Hopefully you will get something together that’ll cater for developers who live north of london. Oh and what do you mean “might be a cool WSG meeting” At our Geek Meet in Stockholm in June we had a talk about Microformats. You can find a good write-up in Current issues with Microformats. Maybe a good point to start a discussion? All, I very much encourage you to raise questions and issues (like recurring events, applications, etc.) on the microformats-discuss mailing list so that some things can be quickly answered (e.g. applications, see ) and others at least somewhat discussed so that a richer in-person discussion is possible. Robert, as far as that “Current issues with Microformats” post, most of those have been disposed of with the microformats.org FAQ and other discussions. E.g. namespaces themselves are actually more of a problem and this has been well documented on the microformats.org wiki. The poster also misses the whole point of DRY, the need to prefer visible data to invisible metadata, etc. Putting data in class attributes (as is suggested for dates) has also been refuted as a bad idea (see invisible metadata critiques). If you feel any of those issues actually merit/require any further discussion, please post them individually to the microformats-discuss mailing list. Thanks, Tantek I’d love to see some discussion in the area of Microformats for computers and the parsing of Microformats. Looking forward to October already Why are you doing this? Wouldn’t it be more sensible to get behind the London Microformats event, which is just a few weeks before this one? @Buck: Surely the more events relating to microformats the better? That’s one way of looking at it. Another is that it’s dividing what could be one great event into two inadvertantly watered-down events. “Hey Fred, are you going to this Microfotmats event?” “Nah, I’m going to the other Microformats event” @ Buck: There’s another key difference–the other Microformats event seems to be a social gathering, whereas Stuart’s event is a proper standards meet up. I feel there’s a very distinct difference in the tone. Still looking forward to this, any idea when we’ll get the details nailed down? @David: Hi David the details should be online later today. Thanks for being patient!
http://muffinresearch.co.uk/archives/2006/08/17/october-wsg-meetup-microformats/
crawl-001
refinedweb
992
61.16
Hikari packages not working [FIXED] i have a discord bot that i code in python on here and i used to use discord.py but since it's no longer being maintained, i'm switching over to a new library called hikari. when i used to work in d.py, it let me install the package and everything worked fine but now since i'm using hikari, it's not letting me install the package from the packages tab and i'd have to do pip install hikari and pip install hikari-lightbulb in the shell over and over again just to get my bot online and the commands working. it gives me this error whenever i try to install the packages from the tab and i don't know what to do, can anyone help? edit: I've figured this out with people helping, but if you want to use hikari in replacement of discord.py, paste this into your pyproject.toml file and it'll install the packages: hikari = {version = "^2.0.0-alpha.105", python = "~3.8"} hikari-lightbulb = {version = "^2.1.3", python = "~3.8"} if you want proof that it did install, you can do this in your main file: import hikari import lightbulb print(f"hikari: {hikari.__version__}") print(f"lightbulb: {lightbulb.__version__}") I'm having the same issue. Any fixes? Nope @thatgurkangurk
https://replit.com/talk/ask/Hikari-packages-not-working/146169
CC-MAIN-2022-21
refinedweb
229
82.34
In this article, We can execute the script of “C Program to Print Current Date and Time on Command Line”. Shall we start the program execution below? Let’s go. C Program to Print Current Date and Time on Command Line Program Code #include <stdio.h> #include <conio.h> #include <dos.h> int main() { struct date d; getdate(&d); printf("Current system date: %d/%d/%d", d.da_day, d.da_mon, d.da_year); getch(); return 0; } Conclusion We hope this article helps you to know about “Print Current Date and Time on Command Line Using C Program”. If you have any doubts about this topic then please let us know via the comment section. We will help you. Share this article with other C/C++ developers.
https://codingdiksha.com/c-program-print-current-date-and-time-on-command-line/
CC-MAIN-2022-05
refinedweb
125
76.93
, 3 weeks ago. how to disable and enable interrupts How can I disable the interrupt for (0.25) and enable it again in the following code: #include "mbed.h" InterruptIn squarewave(p5); //Connect input square wave here DigitalOut led(p6); DigitalOut flash(LED4); void pulse() { //ISR sets external led high for fixed duration led = 1; wait(0.01); led = 0; } int main() { squarewave.rise(&pulse); // attach the address of the pulse function to // the rising edge while(1) { // interrupt will occur within this endless loop flash = !flash; wait(0.25); } } 1 Answer 5 months, 3 weeks ago. Something like? squarewave.rise(NULL); wait(0.25); squarewave.rise(&pulse); Also use <<code>> your code <</code>> and it will format things correctly. Thanks for the answer, but I want to know how this can be done using these two functions : disable_irq(); enable_irq();posted by 18 Jun 2019 Short answer: You don't do that. Wait uses an internal timer interrupt. If you disable interrupts the timer won't run and so the wait will never end. Disabling all interrupts should only every be done for the shortest possible time if you have some task that needs to take place uninterrupted. e.g. if you have a serial receive buffer that you want to copy you don't want more data arriving half way through the copy. So you disable interrupts, copy the contents and then re-enable them. You don't disable all interrupts for a length of time just to stop something from happening, in that situation you disable the specific interrupt you want to stop. You can either use the mbed way above to remove the interrupt and then put it back or you can poke the interrupt handler directly and disable it using NVIC_DisableIRQ(device_IRQn) but you would need to look up the appropriate IRQ number for your board, it'll be in the device specific header files in the mbed library. You need to log in to post a question
https://os.mbed.com/questions/86227/how-to-disable-and-enable-interrupts/
CC-MAIN-2019-51
refinedweb
332
70.23
Acid2 is a sample page available at created with the precise goal of helping browser vendors to test their product against proper support for latest Web standards. Few of the currently used Web browsers have passed the test. Among the others, I'd like to mention Safari, iCab, Konqueror, Opera and Firefox 3. What about Internet Explorer? Internet Explorer 8 -- only in beta 2 at the time of this writing -- has passed the Acid2 test; and it is the first version of the Microsoft's browser to make it. The IE8 team worked out a completely new rendering engine that now follows the CSS 2.1 specification as closely as possible. This new rendering mode is enabled by default for pages hosted in Internet Web sites with the clear purpose of giving users the best possible viewing experience. Unfortunately, such a great viewing experience is only possible if Web pages are created according to the latest Web standards. This is not often the case. To avoid breaking so many Web pages, a compatibility view mode has been added to Internet Explorer 8. The Compatibility View feature works in a rather intuitive manner. It simply switches back the rendering engine of Internet Explorer 8 to version 7. In this way, from a rendering perspective you are just not using a newer browser. As a result, all sites not explicitly redesigned and restyled for latest standards will display correctly. How would you activate the Compatibility View mode? As mentioned, the compatibility mode is disabled by default on Internet Web pages, but it is the default for intranet sites. Large organizations can keep on using their applications as usual even when they upgrade to Internet Explorer 8. In this way, they can plan sites updates ahead and proceed with that as their earliest convenience. Changing the settings about Compatibility View is possible interactively too. A new UI button is displayed in the navigation bar, at the right end of the address bar and near to the Refresh button. It is worth noting that the button is hidden when you are in Compatibility View mode and only appears when the page is being viewed through the new Standards mode engine. As a Web developer, you can force a given page to use the new rendering mode or stick to the Internet Explorer 7 rendering mode. All you need is a simple <meta> declaration like the one shown below: <meta http- You place the tag into the <head> section of the page. As a result, Internet Explorer 8 will render the page using the new standards mode. Likewise, you can programmatically force a legacy rendering through a slightly different <meta> tag: <meta http- The X-UA-compatible header is not case sensitive. It poses other constraints though. In particular, it must appear in the <head> before all other elements, except for the title element and other <meta> tags. If you don't want to edit each and every Web page, you can resort to adding a custom header to the site configuration. For IIS 7, the following web.config script suffices: <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <httpProtocol> <customHeaders> <clear /> <add name="X-UA-Compatible" value="IE=EmulateIE7" /> </customHeaders> </httpProtocol> </system.webServer> </configuration> For IIS 6, instead, you resort to the user interface of the IIS Manager. Finally, you can check the rendering engine via JavaScript. You use the documentMode property on the document object. function IsStandardsMode() { !if(document.documentMode) return false; return (document.documentMode == 8); } The property exists only in Internet Explorer 8 and is undefined for other browsers. It takes a value of 8 if the newest rendering engine is active.
http://www.drdobbs.com/web-development/internet-explorer-8-and-compatibility-vi/212901412
CC-MAIN-2015-32
refinedweb
612
55.64
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Martijn Faassen wrote: > Hi there, > > Chris McDonough wrote: > [snip] >> I'm pretty sure a steering group and a rebranding of existing software is not >> going to make us more effective. > > I'm proposing a deconstruction, not a rebranding; a new name is > introduced as an entity needs to be named, namely the Zope Framework. > > What is going to make us more effective is: > > * a recognition of current reality, i.e. the Zope Framework is not the > same as the Zope 3 application server and it serves a far wider audience. > > * leadership At the moment, the leadership in the "big tent" Zope community is diffuse: I will agree that we have a vacuum when it comes to leading the direction of the "widely used" bits which make up part of the current Zope3 release, mostly because folks are super busy. One way people can contribute to the leadership needed here is to avoid chipping in on pieces of the puzzle where they don't have a real stake: for instance, I would hereby disqualify myself from any attempt to steer the bits which make up the Z3 ZMI. >> - encouraging radical change for experimentation purposes, releasing folks >> from >> various constraints (backwards compatibility, style policing, historical >> ownership) > > Who is going to make that decision to encourage this? Allow this? You? > Me? Who? Right now, *nobody* is making such decisions and nobody can > properly get away with saying they allow it. Leadership is a way to get > out of it. Avoiding the "stop energy" Chris metnioned is part of the "encourage radical change." One way to do radical change is to fork a project. Such a fork has several benefits: - - Existing consumers of the forked project are not perturbed, because the already-releasd old project serves their needs. - - The new package can experiment with heavy refatorings, new APIs, etc., without the burdens imposed on "in place" upgrades (deprecations, BBB imports, etc.) - - The develpoer can proceed with making the forked version work as well as possible without "asking permission" from anybody who feels ownership over the original version. - - Until the fork is successful, we don't have any need to "steer" at all. A failed fork is low-cost for the community: it just dies on the vine. The only downside is namespace issues (e.g., zope.app.form vs. zope.formlib vs. z3c.form). Defining "successful": I would say that a successful fork is one which is being used in "real" projects in ways which displace the original version of the package. Once a fork reaches this stage, *then* we have the opportunity to "steer": should we try to re-merge the fork back into the original (a la egcs)? Or should we deprecate the original and all switch to using the fork? >> - discourage the contribution of stop energy (discourage >> the utterances of "don't", "stop", "this is wrong", >> "stop talking about this"). > > +1, though a simple discouraging of utterance can't accomplish it by > itself. What you need is active leadership that encourages such > experimentation. Right. I will note that Chris isn't being hypothetical here: we have seen a number of cases where folks who were motivated to improve a widely-used package were discouraged from their efforts by such discourse. >> - focusing on externalizing software; each egg should stand on its own as >> something that a non-Zope person would be able to understand and use >> in isolation. This means documentation for each thing, as well as >> a sane dependency graph. > > Sure, I agree with all this. Does everybody? What if we get 3 times -1 > and 3 times +1 in a discussion on it? The -1 votes would be "stop energy." Any package which satisfies Chris' criteria is *still* useful in the bigger Zope framework, while the converse is not true. E.g., consider the current dependencies of zope.component: if I made checkins which stripped out the use of 'zope.deprecation', 'zope.deferredimport', and 'zope.proxy' (or made them optional), the package would be more useful to people outside of Zopeland (e.g., developers targeting the GSA, Jython, IronPython can't use zope.component today because of hard C dependencies). The tradeoff would be that "old" Zope3 code might need to be updated (e.g., removing use of BBB features, or relaxing security requirements). >>. > > Someone's still developing all this software: our community. Someone > needs to take responsibility for all this software. I'd say that group > is the Zope project. I would say that *nobody* is developing all this software: different sets of people are working on different pieces / subsets of it. > Who decides to kill something off? Who decides whether a merge is okay? > Who decides we should have a documentation website for a widely used > component. In the end, only the people willing to do the work. For instance, the recent sprint on reducing dependencies made changes which, if discussed ahead of time on this list, might have been "vetoed." Because the sprinters went ahead *without* discussion (outside the sprint itself), they made progress which would have been much more painful, and maybe infeasible, in a more heavyweight process. >> - Stop trying to version control and treat all this software in some >> overall release. Let each piece of software have its own life. Likewise >> if a piece of software does not have its own life, kill it. > > If you don't have a list of "known good" versions you don't know what to > test together, unless you maintain a separate list for each library, > which would require a lot of coordination overhead which a single list > does not. The usefulness of the "single list" drops off fast for folks who don't need the whole thing, or who need newer / older versions of one of the packages. > If you say we shouldn't maintain a known good set, then other systems > building on top of this will need to maintain their independent lists > all by themselves, and there's less chance that Zope 2's, Zope 3's and > Grok's list will agree. I think such an agreement is a good idea. > > Just because *you* tend to use a few selective libraries for your own > efforts doesn't mean everybody else is. I think we should definitely > support your use case, but not only your use case. A steering group > would be aware of these use cases and balance them. In the scenario I outlined above (a developer proposes stripping out CPython-only dependencies from zope.component), how would a steering group help? The "vested" groups would see little benefit (*their* code works already with the CPython-only code), and would therefore have little incentive to encourage such an effort: they would likely be big contributors of "stop energy."rHNy+gerLs4ltQ4RAvwkAKCIcG83UaQgzVltDeQmZgt1cPAR1ACglJAv gNhIH/oNtBpiqUZp/gyoncc= =Q9Mk -----END PGP SIGNATURE----- _______________________________________________ Zope-Dev maillist - Zope-Dev@zope.org ** No cross posts or HTML encoding! ** (Related lists - )
https://www.mail-archive.com/zope-dev@zope.org/msg28089.html
CC-MAIN-2017-51
refinedweb
1,154
62.38
Python Static Methods Vs Class Method In this article, we will learn about the difference between a static method and a class method in Python. We will use some built-in functions available in Python and some related custom examples as well. We will compare both methods with examples in this module. Let's first have a quick look over the term decorator, what is a static method, what is a class method, when to use these methods, and compare its working. What is a Decorator in Python? Before reading the differences between static and class methods, you must know what is a decorator in Python. Decorators are simple functions. The user can write them, or include them in Python standard library. Decorators are used for performing logical changes in the behavior of other functions. They are an excellent way to reuse code and can they help to separate logic into individual bits. Python provides decorators to define static and class methods. Static Methods Static methods are methods that are related to a class but do not need to access any class-specific data. There is no need to instantiate an instance because we can simply call this method. Static methods are great for utility functions. They are totally self-contained and only work with data passed in as arguments. - This method is bound to the class but not to the object of the class. - This method can not access or modify class state. - This method is defined inside a class using @staticmethoddecorator. - It does not receive any implicit first argument, neither selfnor cls. - This method returns a static method of the function Example: Static Methods class static_example(object): #decorator @staticmethod def fun(arg1, arg2, ...): ... Class Methods In Python Class methods are methods that are related to a class and have access to all class-specific data. It uses @classmethod, a built-in function decorator that gets evaluated after the function is defined. It returns a class method function. It receives the cls parameter instead of self as the implicit first argument. - This method is also bound to the class but not to the object of the class. - This method can access the state of the class, therefore it can modify the class state that will be applicable to all the instances. - This method is defined inside a class using @classmethoddecorator. - It takes clsas a parameter that points to the class and not to the instance of the object. Example: Define Class Method class class_example(object): #decorator @classmethod def func(cls, arg1, arg2, ...): .... Working Example of Static and Class Methods The below example shows how static and class methods work in a class. Class methods are used for factory purposes, that's why in the below code @classmethod details() is used to create a class object from a birth year instead of age. Static methods are utility functions and work on data provided to them in arguments. from datetime import date class Person: #class constructor def __init__(self, name, age): self.name = name self.age = age @classmethod def details(cls, name, year): return cls(name, date.today().year - year) @staticmethod def check_age(age): return age > 18 #Driver's code person1 = Person('Mark', 20) person2 = Person.details('Rohan', 1992) print(person1.name, person1.age) print(person2.name, person2.age) print(Person.check_age(25)) Mark 20 Rohan 29 True Difference between a static method and a class method Conclusion In this article, we learned about decorators in Python, static methods, and class methods. We learned the working of both methods. We saw key differences between the two methods and how a class defines them.
https://www.studytonight.com/python-howtos/python-static-methods-vs-class-method
CC-MAIN-2022-21
refinedweb
602
65.42
Lucy does not (yet) support multi-value fields natively. I want to override the behavior of the RangeQuery class to support my pseudo multi-value fields, which I achieve by concatenating values with the \x03 byte. I have fields containing values like: doc 1: "123\x{03}abc" doc 2: "def\x{03}456" and I want to be able to do a range query like: lower => 'abc', upper => 'def' and match both docs. It looks like there are 2 possible approaches: * override the static methods in core/Lucy/Search/RangeQuery.c for find_lower_bound() and find_upper_bound(), or * the core/Lucy/Index/SortCache.c Find() and Value() functions, so that they can split the field values on the \x03 delimiter and treat each substring as a separate value. It seems like that second option is the better one since that should also affect sorting, which would be a nice side effect. Maybe. :/ I'm wondering if (a) SortCache or RangeCompiler could/should be exposed as public classes for overriding, and/or (b) if I'm just way off on this line of thought. pek -- Peter Karman . . peter@peknet.com
http://mail-archives.apache.org/mod_mbox/incubator-lucy-dev/201106.mbox/%3C4E002F53.3080507@peknet.com%3E
CC-MAIN-2017-39
refinedweb
188
61.26
53474/doubt-in-numpy-vstack I wanted to ask that the following code doesn't work c=vstack(tsne_data,label_1000).T where shape of tsne_data is (1000,2) and the shape of label_1000 is (1000,) but the following code works for the same c=vstack(tsne_data.T,label_1000).T for the same shape of tsne_data and label_1000 so I wanted to know that why do we need to use transpose with tsne_data in vstack The vstack function in numpy will stack the sequence vertically (row wise). If you see the below example shape of the row in a and b are not similar so you won't be able to add b to a. In order to do that you will have to find the transpose of it so that shape of rows in a and b are similar Use this - numpy.savetxt("data.csv", arr, delimiter=",") READ MORE np.average() can be used to calculate weighted ...READ MORE You can use np.maximum.reduceat: >>> _, idx = np.unique(g, ...READ MORE If you have matplotlib, you can do: import ...READ MORE Good question, glad you brought this up. I ...READ MORE Hi, it is pretty simple, to be ...READ MORE just index it as you normally would. ...READ MORE Use the .shape to print the dimensions ...READ MORE In this case, you can use the ...READ MORE Memory management in python involves a private heap ...READ MORE OR
https://www.edureka.co/community/53474/doubt-in-numpy-vstack
CC-MAIN-2019-35
refinedweb
239
76.32
jGuru Forums Posted By: Alexander_Torstling Posted On: Saturday, December 21, 2002 02:44 PM Hi there! Im writing yet another tetris clone as an assignment at my college. My goal is to make it as flexible as possible, letting all logical components draw themselves. I use doublebuffering, and the Tetris "application" (which actually is a Canvas, listening to TetrisEvents eg ROTATE_LEFT), is scalable (listens to componentResized-events). It has all worked just great, until i started letting the pieces contain java.awt.Image's to make it all look fancy. I keep getting these horizontal, empty lines, in my picture. I have tried to be restrictive about using update(), but the problem persist. I have heard that the problem may lie in som bug in java runtime (i use win2000, java 1.3.1), showing especially where resizes are involved. By the way: all drawImage()-calls return true. I also have overwritten the isDoubleBuffered() -method to return true. I would very much appreciate som help here! here's some sample code (the main drawing procedure and the bits own drawing system): public void update(Graphics g) { if (bg == null) g2.clearRect(0,0,getWidth(),getHeight()); else g2.drawImage(bg,0,0,spelSize.width+1, spelSize.height+1 ,this); if (mainThread != null) { mainArena.paint(g2,new Point(0,0),dsize); klossFallande.paintAdjusted(g2,pointFallandePos,dsize); } else { drawCentered(stopMessage, stopFont, Color.white, g2); } if (pause) { drawCentered("Pause", stopFont, Color.white, g2); } paint(g); } public void paint(Graphics g) { g.drawImage(imageDouble, 0, 0, this); } public void compResized(ComponentEvent e) { dsize = new Point(getWidth()/NO_COLS, getHeight()/NO_ROWS); spelSize = new Dimension(getWidth() - (getWidth()%NO_COLS), getHeight() - (getHeight()%NO_ROWS)); imageDouble = createImage(getSize().width,getSize().height); g2 = imageDouble.getGraphics(); repaint(); } // The bit class and its painting: public class ImageBit extends Bit { Image im; String filename; public ImageBit(Image im) { this.im = im; } public void paint(Graphics g, Point pos, Point dsize) { g.drawImage(im, pos.x, pos.y, dsize.x, dsize.y, this); } public Object clone() { return new ImageBit(im); } } Re: horizontal lines drawImage Posted By: Rahi_Parsi Posted On: Sunday, February 23, 2003 03:56 PM Looking at your code, I don't see any problems with it. If you're getting horizontal lines mixed up with the output, then you probably need to use a MediaTracker to make sure that the image has loaded. Also keep in mind that when scaling images to a dimension larger than it's original one, you will get ugly blurring effects. A more reliable approach is to use a group of images as a texture pallete. For example, let's say all the puzzle pieces will have a wood pattern. Then to draw the 'L' shape, you would draw the wood texture 4 times.
http://www.jguru.com/forums/view.jsp?EID=1040303
CC-MAIN-2014-35
refinedweb
454
50.02
Snapping You may have noticed that it is easy to draw features that don't line up nicely with existing features. In addition, when modifying features, we can break topology — adding a void between polygons that were previously adjacent. The Snap interaction can be used to help preserve topology while drawing and editing features. First, import the Snap interaction into your main.js: import Snap from 'ol/interaction/Snap'; As with the other editing interactions, we'll configure the snap interaction to work with our vector source and add it to the map: map.addInteraction( new Snap({ source: source, }) ); With the draw, modify, and snap interactions all active, we can edit data while maintaining topology.
https://openlayers.org/workshop/en/vector/snap.html
CC-MAIN-2021-43
refinedweb
115
53
Threeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee. Make sure you find your partner before starting this. You and your partner will need to arrange a time to meet before the next homework assignment is due. 1. Optional and Keyword Arguments This is a feature of function calls in Python that isn't present in most other programming languages. When you define a function, the arguments have names: >>> def parrot(first, second, third): ... print first, second, third ... >>> You can use those names when you call the function, to specify the arguments in any order you want. You simply write the argument name with an equals sign preceding the argument: >>> parrot(1, 2, 3) 1 2 3 >>> parrot(first='we', third='pythons', second='like') we like pythons >>> This can help make your program more resilient to change when you're using a function that has lots of arguments. Someone else can rearrange the arguments and your program will still work. You can use the same syntax when defining a function to specify an optional argument. The value after the equals sign is the default value that the argument will get if the caller doesn't specify that argument. You can have as many optional arguments as you like, but they must go at the end of the list. In the following example, the exponent argument is optional and defaults to 2. >>> def root(x, exponent=2): ... return x ** (1.0 / exponent) ... >>> root(4) 2.0 >>> root(5) 2.2360679774997898 >>> root(5, 3) 1.7099759466766968 >>> These two features are very handy together when you're describing an operation that has many small options. For example, if you were writing a drawing program, it might have a function like this: def draw_circle(x, y, radius=100, thickness=1, colour='black', fill='white'): ... Then you could call this function as simply draw_circle(200, 200), or as draw_circle(200, 200, colour='red'), or as draw_circle(200, 200, radius=50, fill='blue'), depending how specific you wanted to be. The default values of the arguments can be expressions. The expressions are evaluated and wrapped up in the function at the time the function is defined, not when it is called. 2. Iteration The for keyword lets you run a loop that iterates over the elements of any sequence. >>> for c in 'abcd': ... print c ... a b c d >>> for item in [3, [], 'ooga', 5.7]: ... print item ... 3 [] ooga 5.7 >>> In the first example above, we're iterating over the four elements of a string. (Each character is a string of length 1.) In the second example, we're iterating over the four elements of a list. We can also use for to iterate over the lines of a text file. Files are opened using the built-in open function. Suppose the file foo.txt contains: Ah. I'd like to have an argument, please. Certainly sir. Have you been here before? No, I haven't, this is my first time. I see. Well, do you want to have just one argument, or were you thinking of taking a course? Then we could read the contents like this: >>> file = open('foo.txt') >>> for line in file: ... print line ... Ah. I'd like to have an argument, please. Certainly sir. Have you been here before? No, I haven't, this is my first time. I see. Well, do you want to have just one argument, or were you thinking of taking a course? >>> line 'or were you thinking of taking a course?\n' >>> Notice a couple of things here. The printed output is double-spaced because each line we read from the file is a string with a newline character ( '\n') on the end. The Also notice that the variable line retains its last value after the for loop has ended. You can see from the above that it contains a trailing newline character. Iterating with a for statement always requires that you have a sequence to iterate over. So, in order to run a loop to count numbers, we have to generate a sequence of numbers. The range() function takes care of this for us. This function can take one, two, or three arguments: range(end)produces the list of integers from 0to end-1. range(start, end)produces the list of integers from startto end-1. range(start, end, step)produces the list of integers starting from start, incrementing by stepeach time, not including any numbers beyond end-1. >>> range(5) [0, 1, 2, 3, 4] >>> range(3, 8) [3, 4, 5, 6, 7] >>> range(3, 30, 7) [3, 10, 17, 24] >>> range(20, 10, -1) [20, 19, 18, 17, 16, 15, 14, 13, 12, 11] >>> Q1. What happens if you ask for the range() of a single negative number? Q2. What happens if the start argument is bigger than the end argument? Q3. What happens if some of the arguments contain fractions? When you get to this point, get out of your chair, find someone else in the room, and ask them if they have any Grey Poupon. No, really. I mean it. Take a break. 3. List methods You've already seen the .append() method on lists: it alters the list in place, adding one element on the end. You can use dir() to discover the other methods on lists: >>> dir([]) ['_'] >>> You can ignore all of the names that start and end with underscores, for now. Those are all special methods. (Special methods are methods that are called automatically instead of by name. For example, some of them correspond to operators: x + y corresponds to calling x.__add__(y). But we won't worry about this until later.) The ones we care about are the nine "normal" methods: x.append(item)adds a single item onto the end of list x, increasing the length of xby 1. x.count(y)tells you how many times yoccurs in the list x. x.extend(items)expects another sequence as the argument, and appends all the elements of that sequence onto the end of x. x.index(y)tells you the first position at which yoccurs as an element of x. x.insert(index, item)inserts an item into the list xat a particular index, and shoves everything after it to the right. x.pop(index)removes a single item from the list x, and returns it. x.remove(y)finds the first occurrence of yin the list and removes it. x.reverse()reverses the list xin place. And x.sort()sorts the list xin place. Give them all a whirl. Q4. What happens if you try to insert at a negative index? Q5. What happens if you try to append a list to itself? Q6. What happens if you try to extend a list with itself? Q7. Write a little function to find the median of a list of numbers. 4. String methods Strings also have a lot of methods, which will come in handy as you're doing the assignment. Again, you can get a list of them using dir(): >>> dir('') ['__add__', '__class__', '__contains__', '__delattr__', '_'] >>> Here are the most commonly used ones: x.strip()produces a new string by removing all the whitespace characters (spaces, tabs, newlines) from the beginning and end of x. The similar method x.lstrip()strips spaces only off the beginning, and x.rstrip()strips spaces only off the end. x.split()produces a list of words by splitting xon whitespace. Any whitespace at the beginning and end of the string is ignored. x.split(substring)splits the string xon every occurrence of substring. x.join(list)takes a list of strings, and joins them all together with repetitions of x. If the list has length n, then n - 1 copies of xwill be used to join it together. x.replace(old, new)replaces every occurrence of oldwith new, and returns the new string. x.lower()and x.upper()change all the characters to lowercase or uppercase. x.startswith(string)and x.endswith(string)compare the beginning or ending part of xto a given string. x.find(substring)searches for a substring within the string x, and returns the index of the first occurrence. It returns -1 if the substring is not found. x.rfind(substring)searches from right to left, returning the last occurrence. Both these methods also accept an optional second argument, an index at which to start looking. Try them out. There is also an operator called in that you can use to test if something is a member of a sequence. >>> 'a' in 'abc' 1 >>> 'd' in 'abc' 0 >>> 3 in [1, 2, 3] 1 >>> 3 in [1, 2, 4] 0 >>> Curiously enough, the opposite of in is not in. >>> 3 not in [1, 2, 4] 1 >>> Q8. Write a little function that takes a sentence and converts it (very simplistically) into Pig Latin. Each word that begins with a vowel should have "way" appended in the resulting sentence; each word that begins with a consonant should have the consonant moved to the end of the word and "ay" appended after that. Don't worry about punctuation, combined consonants, or capital letters; just handle these two simple cases: >>> def piglatin(sentence): ... <you fill this in> ... >>> piglatin(' ethel the aardvark goes quantity surveying.') 'ethelway hetay aardvarkway oesgay uantityqay urveying.say' >>> When you get here, find someone you haven't met yet and show them your Pig Latin program. 5. Dictionaries The dictionary type in Python is a totally new type of collection. Like lists, dictionaries contain things, but they don't order them in sequence. Instead, dictionaries contain associations between pairs of things. Each pair consists of a key and a value. You look up things in a dictionary by providing the key, and the dictionary returns the value. To write a dictionary, you use curly braces, and join each key-value pair with a colon. >>> d = {'a': 'aardvark', 'b': 'balloon'} >>> print d {'a': 'aardvark', 'b': 'balloon'} >>> len(d) 2 >>> d['a'] 'aardvark' >>> d['b'] 'balloon' >>> d['c'] Traceback (most recent call last): File "<stdin>", line 1, in ? KeyError: c >>> d['x'] = 'xylophone' >>> print d {'a': 'aardvark', 'b': 'balloon', 'x': 'xylophone'} >>> d['x'] 'xylophone' >>> As you can see from the example, len() returns the number of pairs in the dictionary. You use square brackets to look up things in a dictionary, just like a list, except the thing inside the square brackets is a key instead of a numeric index. You also use square brackets to add a new pair to a dictionary, like we did with the key 'x' and the value 'xylophone'. There will be more to say about dictionaries later, but for now you only need to know two methods: >>> d.keys() ['a', 'b'] >>> print d.get('c') None >>> print d.get('c', 'flugelhorn') flugelhorn >>> The keys() method returns a list of the keys in a dictionary, which is helpful for getting at the contents. The keys will be returned in no particular order. Printing a dictionary also prints the key-value pairs in no particular order. The get() method provides you a safe way of looking up a value, when you don't know whether the key is present. If you simply ask to get(x) and x is not a key in the dictionary, you will get None. You can also specify a second argument to get, which will be the default value returned if the key is missing. You can also test to see if a key is in a dictionary using the in operator. Note that this only checks for the existence a key; it doesn't check for a value. >>> 'a' in d 1 >>> 'c' in d 0 >>> 'aardvark' in d 0 >>> for key in d: print key ... a b >>> The looping statement for x in d loops over the keys. It does the same thing as for x in d.keys(). Q9. Write a little function that will count how many times each element occurs in a sequence. The result should be a dictionary; in each pair, the key should be one of the elements, and the value should be the number of times it occurred. >>> count([3,7,6,5,5,6,7,3,5]) {3: 2, 5: 3, 6: 2, 7: 2} >>> count('bcbabbebcbbabeba') {'a': 3, 'c': 2, 'b': 9, 'e': 2} >>> 6. Regular Expressions The re module lets you search for more interesting patterns in strings, using regular expressions we described in class. A regular expression is a string that specifies a pattern for matching against other strings. Regular expressions use a special syntax (for example, to allow for wildcards). Here are some of the common constructs in regular expressions: .matches any character spammatches the exact string "spam" [abc]matches the character a, b, or c [a-m]matches any lowercase letter from ato m [^aeiou]matches any character except for a lowercase vowel You can specify repetitions or optional parts using the following operators: x*matches zero or any number of repetitions of x x?matches zero or one occurrence of x x+matches at least one repetition of x To make these operators apply to more than one character, you group parts of the expression in parentheses: abc+matches abfollowed by at least one repetition of c (abc)+matches at least one repetition of abc You can also combine parts of the expression: spam|eggsmatches spamor eggs Finally, you can specify whether your pattern has to occur at the beginning or end of the string: ^preswill match any string that starts with pres ing$will match any string that ends with ing There are more features and operators in regular expressions, but these should suffice for now. Here are some examples. [aeiou]+will match the entire string eeeee [aeiou]+will match the first three letters of the string auireu [aeiou]+$will match the last two letters of the string auireu ^[aeiou]+$will not match the string auireu [aeiou]+will match the last two letters of the string zoo ^[aeiou]+will not match the string zoo To use regular expressions in a program, you must import the re module and use it to compile your regular expressions. This will produce a pattern object. The pattern object has a method, search(), that you can then call to search a string for a match. Here are some of the above examples in Python: >>> import re >>> pat = re.compile('[aeiou]+') >>> pat.search('eeeee') <_sre.SRE_Match object at 0x81c2b90> >>> pat.search('auireu') <_sre.SRE_Match object at 0x8193b38> >>> The weird-looking SRE_Match object represents the results of the match: >>> match = pat.search('auireu') >>> match.start() 0 >>> match.end() 3 >>> match.group() 'aui' >>> match = pat.search('zoo') >>> match.start() 1 >>> match.end() 3 >>> match.group() 'oo' >>> The group() method tells you what part matched, and the start() and end() methods return its position in the string. The search() method on a pattern will return None if there is no match. >>> pat = re.compile('^[aeiou]+') >>> print pat.search('zoo') None Patterns also have a method called sub(replacement, string) that will find all occurrences of the pattern in the string and substitute in a replacement. >>> pat = re.compile('[aeiou]+') >>> pat.sub('', 'zozoozieiou') 'zzz' >>> pat.sub('ee', 'zozoozieiou') 'zeezeezee' >>> The replacement string can refer to what was matched in the original string. Every time you use a pair of parentheses to group together part of a regular expression, that part is called a group. When a pattern search is performed, the part of the original string that matches each group is saved in the match object. The first left-parenthesis starts group 1, the second left-parenthesis starts group 2, and so on. Wherever the replacement string contains a backslash followed by a number, the result will substitute a copy of the group referenced by that number. An example will probably help make this clearer: >>> pat = re.compile('(a..) (b..)') >>> pat.sub('\\2 \\1', 'art bat cat ack bop') 'bat art cat bop ack' >>> In the above example, the pattern looks for a three-letter word starting with 'a', followed by a space, followed by a three-letter word starting with 'b'. The pattern matches the string "art bat cat ack bop" twice: it matches "art bat" and also matches "ack bop". Both of these matches are replaced in the result. The replacement string is the second group, followed by a space, followed by the first group. So the effect is to swap the two words "art" and "bat", and to swap the two words "bop" and "ack". The special pattern '\b' matches the boundary at the beginning or end of a word, and the special pattern '\w' matches a character in a word (either a letter or a number). Given this, you can do the Pig Latin transformation of a sentence in just two steps. First, you handle all the words that start with vowels; then you handle all the words that start with consonants. Here's the first step: >>>>> Q10. Try writing the regular expression and substitution for the second step, words that start with consonants. Q11. (Optional, open-ended.) Adjust your regular expression to handle more interesting cases, like words that start with "tr" or "qu". I know regular expressions are kind of hairy-looking. Please feel free to ask me about them if you find them confusing. Onward to the third assignment. If you have any questions about these exercises or the assignment, feel free to send me e-mail at bc zesty ca.
http://zesty.ca/bc/explore-03.html
CC-MAIN-2017-13
refinedweb
2,912
73.37
Minecraft 1.2.5: TOP 5 BEST SEEDS! [Epic Canyons, Strongholds, Villages, awesome Mountains,...] Twitter:... Formspring:... ►Succession: 1.... MineBuilders Server 24/7 cracked non white list Join Plz Website ip:minebuilders.me Minebuilder server setup How to setup a minebuilder server. How to Make Working TV Minecraft! Amazing how to make a working TV in minecraft real! Subscribe For entertainment purposes only MineBuilders Server Sorry For The Fucked Up Music It Whas Long Ago But It's Really Good And It's Cracked :D Join my Minebuilder Server Join my Minnebuilder Server! ip: 10.0.0.5 No Password Server on Friday, Saturda, Sunday Blender 2.5 Quick Tip - How to Instance an object to a Particle System Quickly learn how to Instance (Parent, whatever you want to call it) an object to a particle system, in Blender 2.5. Newbie's First Headshot - DE_dust2 Outtake 1 Newbie gets his first ever headshot! If you like this, please subscribe! More Counter-Strike animations coming soon!... swat vs zombies (pivot) a swat team is taking it easy at their base, when they get attacked by a zombie dropship, that lands outside. will they survive? comment+rate plx a... This is NOT Black Ops Sorry about the text in the middle and the flashes and the lag, those are not in the game. If you want it it is an .exe in a dropbox folder, send m... A simple plane game using Blender by Jason Ege Ozer - HD 720p - This is a simple plane game that I just made in about 1-2 hours, Everything is custom. I invented a new style of plane so this plane doesn't exist.... Robot life Simulation - Blender Game Engine Made using Blender's Logic Bricks and Game Engine. Made this in my spare time, it slowly turned into a RTS which I saved as a different file, so I ... New Phone for Christmas! hey ppls i got a new phone for christmas. it's the samsung impresssion with a touch screen Blender tutorial - 2 player camera setup for game engine ##### Viewports.py ################## viewport needs to know game window height and width # import Rasterizer module import Rasterizer # get gam... blender 2.5 tutorial : how to make an enemy Easy enemy on blender 2.5 with no python script AdventureCraft- Super Mario Bros. A Mario Adventure with Mario based items and levels. This was made in AdventureCraft. I didn't include video footage of the items because I ran out... - 3 months ago Blender 2.5 Planks Physics Game Tutorial - Part 2 Download links in Description!... This is a tutorial to help you get started creating your own interactive planks physics game using Blender 2.5. ... Angry Birds - A sneak peek to the newest adventures! It was a dark and stormy night as the Angry Birds' newest adventure begins. The murky woods has spine-chilling creatures lurking in the shadows, bu... Blender GE tutorial - Health Bar (Simple) Blender Game Engine tutorial: Health Bar Someone on Blender Artists was confused about how to make a health bar using logic bricks. I'll have to u... Blender tutorial how to make armatures here you can learn how to make armatures Green Fluid Flow Water in Blender 2.49b Green Fluid Flow Water Animation in Blender 2.49b / Baking: 1 Hour / Rendering: 11 Hours on Quad PC How to Model a Hand Gun in Blender: Part 2 This video covers the basics of creating your very own hand gun in Blender! Part 2 Link to image I used:...... - 4 months ago Blender 2.5 Tutorial: How to Make Grass (part 1) Part 1 of how to make moving grass in blender 2.5 For more information and a link to download blender 2.5:...... Blender 2.59 tutorial: How to make a menu for your game! How to make a menu in blender2.59 Thanks for watching, hope it helps! Hey do me a favor and send me suggestion for more tutorials thank you :D oh a... - 4 months ago Eenies at Wars Hack Gold + XP YO! time for a new hack on eenies!!!! My ninja saga hack was a great success!!! so decided to make this!Hopefully this will be a success too!! Eenies at Wars Hack Gold + XP YO! time for a new hack on eenies!!!! My ninja saga hack was a great success!!! so decided to make this!Hopefully this will be a success too!! My first Blender game (BGE tutorial) part7 Today we make our enemy setup. Yay! Enemy movement setup : 1:00 - 4 months ago Voxel Editor - Blender 2.6 Game Engine Been a while since I uploaded something, so here's a new video of what I was messing around with lately. I decided to record a bit of "the making o... My first Blender game (BGE tutorial) : part 1 Bored? Introduction : 0:00 Scene setup : 2:04 Logic Brick : 4:36 Motions : 7:45 servo control : 12:35 Introduction to Blender :... Blender Game Tutorial (2.6) --Part 3 (Texturing and Building) Working Blend File:... This is 12 part series is designed for my 7th grade multi-medi... Criando um jogo completo 004 // 1.7.1 - Gameplay Alpha do Carro Branch - carro Aqui mostramos o gameplay em testes do carro do game 1.7.1,muitas coisas ainda serao inseridas e/ou modificadas para tornar o melho... Sheldon gets hacked on World of Warcraft - HD The Big Bang Theory S04E19... Pivot combo tutorial 4 hits New pivot tutorial! I return to youtube and with more vids, If you have ideas for new tots, tell me! PD: I reupload this vid because the bat quali... blast test effect I make this vid following the flash tutorial of ThePewPewClan. The result it's amazing! thanks you, ThePewPewClan , and make more tuts like this!! ... test dancing 3D animation My first 3D animation! 8h of working an that's the result. I made the modeling, rigging, skining, materials, animation and render settings (ALL). P... Kk muzic
http://www.youtube.com/1519kim
crawl-003
refinedweb
998
76.72
I am trying to measure elapsed time in Linux. My answer keeps returning zero which makes no sense to me. Below is the way i measure time in my program. #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> main() { double p16 = 1, pi = 0, precision = 1000; int k; unsigned long micros = 0; float millis = 0.0; clock_t start, end; start = clock(); // This section calculates pi for(k = 0; k <= precision; k++) { pi += 1.0 / p16 * (4.0 / (8 * k + 1) - 2.0 / (8 * k + 4) - 1.0 / (8 * k + 5) - 1.0 / (8 * k + 6)); p16 *= 16; } end = clock(); micros = end - start; millis = micros / 1000; printf("%f\n", millis); //my time keeps being returned as 0 printf("this value of pi is : %f\n", pi); } To start with you need to use floating point arithmetics. Any integer value divided by a larger integer value will be zero, always. And of course you should actually do something between getting the start and end times. By the way, if you have access to gettimeofday it's normally preferred over clock as it has higher resolution. Or maybe clock_gettime which has even higher resolution.
https://codedump.io/share/9YTYOWA24TJo/1/measuring-elapsed-time-in-linux-for-a-c-program
CC-MAIN-2016-50
refinedweb
195
77.74
I'm trying to make a "follow" function on my site for users to follow each other by clicking a "follow" button on a repeating layout. I also want to add a text element that displays the amount of users that are following the user. This is my code so far, but I know that it is wrong: // For full API documentation, including code examples, visit $w.onReady(function () { //TODO: write your page related code here... }); import wixUsers from "wix-users"; import wixData from "wix-data"; export function button20_click() { const followerId = wixUsers.currentUser.id; console.log("followerId: ", followerId); const followeeId = $w("#dataset1").getCurrentItem()._owner; console.log("followeeId: ", followeeId); wixData.insert("Followers_Followees", { "followee": followeeId, "follower": followerId }) .catch((err) => { console.log(err); }); } Thanks in advance to anyone who helps out! I'm VERY bad with Wix Code, so detailed instructions would be nice :) Here is a link to the page on my site where I want the follow buttons: This is beginning to frustrate me. I've been very patient with Wix Code Support, but it is simply too unreliable. I've written countless posts and have gotten little to no help at all. I'm starting to think Wix may not be the greatest platform due to the lack of customer service. I realize that Wix Code is still in Beta, but I know it can't be very hard to have a reliable support team. I've needed help with the above problem for a good month, but have gotten very little to no help and attention. I have a website to manage, but I can't do that if I don't get the help I need. Sorry about this message, but I really need assistance, and if Wix Code can't provide me with that, I will need to completely change to another platform like Squarespace.
https://www.wix.com/corvid/forum/community-discussion/help-please-4
CC-MAIN-2019-47
refinedweb
308
63.19
Swipe cards or elements around with VueSwing VueSwing VueSwing is a Vue.js wrapper for the Swing interface. The swipe-left/swipe-right for yes/no input. As seen in apps like Jelly and Tinder, and many others. Example To start swinging elements around, start by installing the wrapper: install it using the following command: yarn add vue-swing import Vue from 'vue' import VueSwing from 'vue-swing' Vue.component('vue-swing', VueSwing) Example usage in your template <vue-swing @ <div class="box">Toss me! Don't tell the elf!</div> </vue-swing> Use the above options to handle your data: <script> export default { name: 'HelloWorld', data () { return { config: { minThrowOutDistance: 100, // Determine the rotation of the element maxRotation: 80 } } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> .box { border: 2px solid; border-radius: 25px; color: purple; width: 120px; } </style> Props VueSwing takes in one config Object, which can consist of any of these keys: isThrowOutDetermines if element is being thrown out of the stack. allowedDirectionsArray of directions in which cards can be thrown out. throwOutConfidenceInvoked in the event of dragmove. Returns a value between 0 and 1 indicating the completeness of the throw out condition. throwOutDistanceInvoked when card is added to the stack. The card is thrown to this offset from the stack. minThrowOutDistanceIn effect when throwOutDistanceis not overwritten. maxThrowOutDistanceIn effect when throwOutDistanceis not overwritten. rotationInvoked in the event of dragmove. Determine the rotation of the element. Rotation is equal to the proportion of horizontal and vertical offset times the maximumRotationconstant. maxRotationIn effect when rotationis not overwritten. transformInvoked in the event of dragmoveand every time the physics solver is triggered. Uses CSS transform to translate element position and rotation. For more information, look at Swing's documentation This is it! This project's repository is hosted on GitHub for everyone to see.
https://vuejsfeed.com/blog/swipe-cards-or-elements-around-with-vueswing
CC-MAIN-2021-21
refinedweb
307
51.34
Visual. Important: SP1 Beta Installation Notes The SP1 beta released today is still in beta form - so you should be careful about installing it on critical machines. There are a few important SP1 Beta installation notes to be aware of: 1). 2) If you have installed the VS 2008 Tools for Silverlight 2 Beta1 package on your machine, you must uninstall it - as well as uninstall the KB949325 update for VS 2008 - before installing VS 2008 SP1 Beta (otherwise you will get a setup failure). You can find more details on the exact steps to follow here (note: you must uninstall two separate things). It is fine to have the Silverlight 2 runtime on your machine with .NET 3.5 SP1 - the component that needs to be uninstalled is the VS 2008 Tools for Silverlight 2 package. We will release an updated VS 2008 Tools for Silverlight package in a few weeks that works with the VS 2008 SP1 beta. 3). Until then, you need to download this recently updated version of Blend 2.5 to work around this issue. Important Update: If you previously installed a VS 2008 Hotfix, you must run the HotFix Cleanup Utility before installing the VS 2008 SP1 Beta. Click here to download and run this. Improvements for Web Development .NET 3.5 SP1 and VS 2008 SP1 contain a bunch of feature improvements targeted at web application development. The VS Web Dev Tools team has more details (including specific bug fix details) on some of the VS specific work here. Below are more details on some of the work in the web-space: ASP.NET Data Scaffolding Support (ASP.NET Dynamic Data) .NET 3.5 SP1 adds support for a rich ASP.NET data "scaffolding" framework that enables you to quickly build functional data-driven web application. With the ASP.NET Dynamic Data feature you can automatically build web UI (with full CRUD - create, read, update, delete - support) against a variety of data object models (including LINQ to SQL, LINQ to Entities, REST Services, and any other ORM or object model with a dynamic data provider). SP1 adds this new functionality to the existing GridView, ListView, DetailsView and FormView controls in ASP.NET, and enables smart validation and flexible data templating options. It also delivers new smart filtering server controls, as well as adds support for automatically traversing primary-key/foreign-key relationships and displaying friendly foreign key names - all of which saves you from having to write a ton of code. You can learn more more about this feature from Scott Hanselman's videos and tutorials here. ASP.NET Routing Engine (System.Web.Routing) .NET 3.5 SP1 includes a flexible new URL routing engine that allows you to map incoming URLs to route handlers. It includes support for both parsing parameters from clean URLs (for example: /Products/Browse/Beverages), as well as support to dynamically calculate and generate new URLs from route registrations. This new routing engine is used by both ASP.NET Dynamic Data as well as the new ASP.NET MVC framework. It will support both WebForms and MVC based requests. ASP.NET AJAX Back/Forward Button History Support .NET 3.5 SP1 adds new APIs to ASP.NET AJAX to allow you to better control the history list of a browser (enabling you to control the behavior of the back/forward button of the browser). You can learn more about this feature in the article here and the screencast here. ASP.NET AJAX Script Combining Support .NET 3.5 SP1 introduces a new <CompositeScript> element on the <asp:ScriptManager> server control, which allows you to declaratively define multiple script references within it. All the script references within the CompositeScript element are combined together on the server and served as a single script to the client, reducing the number of requests to the server and improving page load time for ASP.NET AJAX applications. The script combining feature supports both path based scripts and assembly resource based scripts, and dynamically serves up the combined scripts using the ScriptResources.axd handler. Visual Studio 2008 Performance Improvements HTML Designer and HTML Source Editor In February we released a HotFix roll-up that included a number of performance improvements and bug fixes for the VS 2008 Web Designer. VS 2008 SP1 includes all of these fixes, as well as a number of additional performance improvements. Visual Studio 2008 JavaScript Script Formatting and Code Preferences Visual Studio has for several releases supported rich source code formatting options for VB and C# (spacing, line breaks, brace positions, etc). VS 2008 SP1 adds richer source code formatting support for JavaScript as well (both inline <script> blocks and .js files). You can now set your Javascript coding preferences using the Tools->Options dialog: These preferences will be automatically used as you type new Javascript code in the source editor. You can also select existing code, right-click, and choose the "Format Selection" option to apply your style preferences to existing JavaScript code. You can learn more about this new feature here. Better Visual Studio Javascript Intellisense for Multiple Javascript/AJAX Frameworks VS 2008 includes Javascript Intellisense support in source view. The intellisense support with the initial VS 2008 release works well with vanilla JavaScript as well as code written using the ASP.NET AJAX JavaScript type patterns. JavaScript is a very flexible language, though, and many JavaScript libraries use this flexibility to full advantage to implement their features - sometimes in ways that prevented the intellisense engine from providing completion support.. Below is an example of using a JQuery startup function with the VS 2008 SP1 JavaScript intellisense engine: Notice below how VS 2008 SP1 can now provide method argument completion even on chained JQuery selectors: Visual Studio Refactoring Support for WCF Services in ASP.NET Projects VS 2008 SP1 adds better refactoring support for WCF services included within both ASP.NET Web Site and ASP.NET Web Application Projects. If you use the refactoring support to rename the class name, interface contract, or namespace of a WCF service, VS 2008 SP1 will now automatically fix up the web.config and SVC file references to it. Visual Studio Support for Classic ASP Intellisense and Debugging Previous versions of Visual Studio included support for intellisense and debugging within classic ASP (.asp) pages. The file and project templates to create classic ASP pages/projects hasn't been in VS for a few releases, though, and with the initial VS 2008 we incorrectly assumed this meant that people weren't still using the classic ASP support. We heard feedback after we shipped that indeed they were. With VS 2008 SP1 this support for classic ASP intellisense and debugging is back: Visual Web Developer Express Edition support for Class Library and Web Application Projects The Visual Web Developer 2008 Express edition (which is free) is being updated in SP1 to add support for both class library and ASP.NET Web Application project types. Previous versions of Visual Web Developer Express only supported ASP.NET web-site projects. Among other benefits, the support of class library and web application projects will enable ASP.NET MVC and Silverlight projects to be built with the free Visual Web Developer 2008 Express. All of the above JavaScript, Dynamic Data, Classic ASP, and AJAX improvements work with Visual Web Developer Express as well. Improvements for Client Development : VS 2008 will then ensure that the project can only reference those assemblies shipped in the client profile installed. If you have a machine that only has the .NET Framework Client Profile installed, and you try and run a .NET application on it that did not mark itself as supporting . ClickOnce Client Application Deployment Improvements .NET 3.5 SP1 includes several improvements for ClickOnce deployment of both Windows Forms and WPF applications. Some of these improvements include: - Support for the .NET Framework Client Profile (all ClickOnce features are supported with it) - ClickOnce applications can now be programmatically installed through a ‘Setup.exe’ while displaying a customized, branded install UX - ClickOnce improvements for generating MSI + ClickOnce application packages - ClickOnce error dialog boxes now support links to application specific support sites on the Web - ClickOnce now has design-time support for setting up file associations - ClickOnce application publishers can now decide to opt out of signing and hashing the ClickOnce manifests as they see appropriate for their scenarios. - Enterprises can now choose to run only Clickonce Applications Authenticode signed by performance improvements. WPF Data Improvements .NET 3.5 SP1 includes several data binding and editing improvements to WPF. These include: - StringFormat support within {{ Binding }} expressions to enable easy formatting of bound values - New alternating rows support within controls derived from ItemsControl, which makes it easier to set alternating properties on rows (for example: alternating background colors) - Better handling and conversion support for null values in editable controls - Item-level validation that applies validation rules to an entire bound item - MultiSelector support to handle multi-selection and bulk editing scenarios -: Note: the Direct3D integration isn't today's SP1 beta release. It will appear in the final SP1 release. VS 2008 for WPF Improvements VS 2008 SP1 includes several significant improvements for WPF projects and the WPF designer. These include: - The debugger has also been updated in SP1 so that runtime errors in XAML markup (for example: referencing styles, datasources and/or other objects that don't exist) will now be better identified within the debugger: Data Development Improvements
https://weblogs.asp.net/scottgu/visual-studio-2008-and-net-framework-3-5-service-pack-1-beta
CC-MAIN-2018-05
refinedweb
1,576
53.1
Summary: In this tutorial, you’ll learn how to quickly removing citations from wikipedia tables so that we can read them to a clean DataFrame. One of the most annoying thing about Wikipedia is citations on its table. Sure, it’s good to see that the data is backed up by numbers and references, but if you try to use Pandas read_html on them, the citation is quickly includes in the values, and we end up with a messy DataFrame. This article will present a simple and quick way to get rid of all citations. Step 1 : Open Devtools With the Wikipedia page opened, you need to right-click in the table and select Inspect Element to open up the Devtools. Step 2 : Remove all references tag Switch to Console tab, paste the following JavaScript to the console and press Enter to run it. This code snippet will remove all <sup> and <sub> tags from the current page. document.body.innerHTML=document.body.innerHTML.replace(/<sup\b[^>]*>(.*?)<\/sup>/gi, "" ); Now you can see that our page is cleaned from references. Step 3 : Save the page Now you can save the page locally and load it into your Notebook, as usual. In this example, we named the file wiki.html. import pandas as pd page_tables = pd.read_html("wiki.html") df = page_tables[0] df You can see that the data is now free from any unnecessary information.
https://monkeybeanonline.com/quickly-clean-up-citations-from-wikipedia-table-with-pandas/
CC-MAIN-2022-27
refinedweb
235
70.02
When applied to large file systems, traditional backup software presents three inherent problems: An alternative is to use the LibSAM library for the Sun StorageTek Storage Archive Manager (SAM), a paradigm for data management that goes beyond backup. Designed to use with Sun StorageTek SAM and Sun StorageTek QFS software, the LibSAM library or API allows you to manage data in a samfs file system from within an application. samfs The model employed is client-server: A client process makes requests to a server process. The server processes the requests and returns the processing status to the client. In the simplest case, as is the case with LibSAM, the server and client run on the same machine. Therefore, all requests are local and translate into system calls to the kernel. Before this article delves into the details of how LibSAM is used to overcome the limitations of traditional backup mechanisms, you should understand some basic concepts associated with each function. This article will first discuss the four major components of the Sun StorageTek SAM archive management system: Archiving, the process of backing up a file by copying it from a file system to archive media, is typically the first component. The archive media can be a removable media cartridge or a disk partition of another file system. Figure 1 shows the basic components of the archiving process. To archive a file managed by a samfs file system, LibSAM provides the function sam_archive. sam_archive #include "/opt/SUNWsamfs/include/lib.h" int sam_archive(const char *path, const char *ops); Given a pathname for a file, sam_archive sets the archive attributes on it, as specified by the ops argument. Typically, this argument is i, implying that the file be archived immediately. Table 1 lists all the archive options. ops i C I d w W n As a best practice, an application should create and maintain four copies of each archive set. These copies should be stored on their own media to protect against data loss. The copy managed directly by the file system is referred to as the on-disk copy, which is stored in the disk cache. Note that you can configure the archiving parameters in the /etc/opt/SUNWsamfs/archiver.cmd file. /etc/opt/SUNWsamfs/archiver.cmd After a period of time during which a file's data has not been accessed or modified, the software lets go of or releases the file's copy on disk. Releasing is the process of making disk cache space available by identifying archived files for which all archive copies have been made and freeing their online disk space. The releaser is the second major component of Sun StorageTek SAM. Figure 2 illustrates the releasing process. This frees disk space to allow creation of other files or retrieval of other file data from the archive media. Note: The releaser can release only files that have at least one active archived copy. To release a file managed by a samfs file system, LibSAM provides the function sam_release. sam_release #include "/opt/SUNWsamfs/include/lib.h" int sam_release(const char *path, const char *ops); Given a pathname for a file, the sam_release function sets the release attributes on it as specified by the ops argument. If this argument is i, the file is released immediately. Table 2 lists all the release options. a p s Staging is the process of copying file data from an archive copy back into the disk cache. When a file whose data blocks have been released is accessed, the staging software automatically copies the file data -- or a portion of it -- back to the online disk cache. The stager is the third major component of Sun StorageTek SAM. Figure 3 illustrates this concept. To stage a file managed by a samfs file system, LibSAM provides the function sam_stage. sam_stage #include "/opt/SUNWsamfs/include/lib.h" int sam_stage(const char *path, const char *ops); Given a pathname for a file, sam_stage sets the staging attributes on a file or directory as specified by the ops argument. If the argument is i, the file is staged immediately. The p argument means to partially stage, allowing you to view sections of a file before it is fully copied in from archive media. This is especially useful if the file is very large. Partial staging causes an offline file's partial blocks to be staged. Partial staging optimizes system resources for better performance while allowing access to part of the file's data. This is particularly useful when you are dealing with very large files. Table 3 shows the full list of staging options. 1,2,3,4 Over a period of time, archived copies can become redundant by their age and can be deleted from archive media to create space for newer versions or copies. Archived file data is stored in a tar format along with other file data. The process of removing redundant archived file data and moving other good archived file data is called recycling. tar Recycling conserves archive media by reclaiming expired archive data, thus making room for additional file data to be archived. Recycling is the fourth and last major component of Sun StorageTek SAM. Figure 4 illustrates this concept. Recycling is a process that typically does not require user interaction. Often, the recycler is invoked through root's crontab file at an off-peak time. However, the recycler can be invoked at any time using the sam-recycler command. For more information, download the man pages. crontab sam-recycler To put the pieces together, consider the example of a hospital, in which large volumes of data about patients are generated and subsequently sit unused for long periods of time. (Download the example program.) A patient's hospital records might have the following data storage history: A patient comes in for surgery, and the physician creates the patient's file. It is placed on disk for the first time and immediately archived to tape. While the patient is in the hospital, the data in the patient's file is accessed multiple times a day and remains on disk. Each time it changes, it is archived. As the tape library fills, tapes are recycled and relabeled, removing access to obsolete copies of the patient's file. In this setting, obsolete archives are not kept, because in medical practice, a current patient file contains the patient's entire history. Everything that was in the obsolete archives will also therefore be in the current files. A week after the patient is discharged, the patient's file is released from disk. A month after the patient is discharged, the patient returns for a follow-up appointment. The patient's file is staged from tape, modified, and archived. When the tape library fills, the tapes containing the last, most current archives of the patient's data are exported, moved to storage, and replaced with empty tape. Years later, when that patient returns to the hospital, the patient's file is accessed and is called up from the storage facility and imported. The file data is then copied from tape back to the disk cache. In current backup methodologies, files are copied repeatedly at each full backup cycle, regardless of whether they have changed. With the Sun StorageTek Storage Archive Manager (SAM) software, a file never needs to be copied again unless it changes, because it is protected by the four copies made to different media. Should a file change after it is archived, the advanced file system in Sun StorageTek SAM software automatically makes new copies to new media or new locations, protecting the new versions of this file again, without having to wait for a full or incremental backup that traditional backup software requires. After the new copy is made successfully, the file's metadata is updated to reflect its new location and media. This technique of automatically copying files only after they have been created or modified effectively eliminates the need for a specific period to back up data and can significantly decrease administrator overhead. In addition, the software features the capability to copy and archive from disk to disk, allowing organizations to develop more resilient disaster-recovery scenarios by copying to remote sites. Restoring a file system protected by Sun StorageTek SAM software is also extremely fast when compared to traditional backup software because only the metadata needs to be restored before the file system can be mounted and used. This can take minutes rather than the hours or days that a full restoration from tape requires. Once the metadata is restored and the file systems mounted, all references to the data are satisfied from the Sun StorageTek SAM archive. Files are migrated back to online storage as they are accessed, providing transparent access to the actual file data from near-line storage. And Sun StorageTek SAM software's read-behind feature enables users to begin reading the file even before it is fully restored, significantly benefiting users who need to access large files. Last but not least, because Sun StorageTek SAM software copies only new and changed files, only the tape space for these files is necessary. The software can easily keep up with the rapid scaling and explosion of data in today's economy by never having to perform a full backup of all old and new data. Not only does this save total cost of ownership by eliminating the need to add media to preserve old and stale data, it also saves valuable time and money by limiting administrator overhead and reducing the number of tape devices that are required to accomplish a full backup within a given time. Enhanced policy-based administration and security features include quotas and access control lists (ACLs) to control space consumption and data access. In addition, Sun StorageTek SAM includes the ability to manage very large files by making use of segments, as well as the ability to extend continuous archiving capabilities to remote sites with SAM Remote, libsamrpc. For an introduction to libsamrpc, download the man pages and refer to the intro_libsam(3) man page. libsamrpc intro_libsam(3) Table 4 shows the LibSAM API's functions and descriptions at a glance. sam_advise sam_rearchive sam_exarchive sam_unarchive sam_unrearch sam_damage sam_undamage sam_cancelstage sam_closecat sam_devstat, sam_ndevstat sam_devstr sam_getcatalog sam_opencat sam_readrminfo sam_request sam_restore_copy sam_restore_file sam_segment sam_segment_stat sam_setfa sam_ssum sam_stat, sam_lstat sam_stat sam_lstat sam_vsn_stat, sam_segment_vsn_stat All the APIs in LibSAM, except for sam_closecat, sam_getcatalog, and sam_opencat, are available for use with 64-bit programs. For more details about each library routine, see the individual corresponding man page for that routine. Library routines contained in LibSAM are found in section 3 of the downloadable man pages. Sun StorageTek SAM is often combined with Sun StorageTek QFS software. With this combination, also known as Sun SAM-QFS, Sun presents a new approach that helps organizations manage information assets according to their business needs. The software enables dynamic archiving, reduced backup windows, and fast recovery to help enhance productivity and improve resource use. It consolidates innovative archiving and backup methodologies in a high-performance file system with virtually unlimited scalability. The software replaces traditional backups to improve storage resource use for applications in which data needs to be available continuously and quickly restored in the event of a business disruption. Administrators can set automatic archiving policies to determine when, where, and how information is stored, ensuring cost-effective management of large volumes of data. Metadata archiving and read-behind features help enterprises recover from business disruptions in minutes or hours, as opposed to days, and they let users begin reading files even before they are fully restored. When you put it all together, Sun StorageTek SAM-QFS software enables enterprises to get great value from their information, meeting demanding business requirements across a wide array of applications, regulations, user needs, and corporate policies, while delivering lower overall costs. Download: LibSAM man pages Download: LibSAM Sun StorageTek SAM documentation Sun StorageTek QFS documentation Sun SAM-QFS project page on OpenSolaris.org Svati Chandra is a staff member of the Sun StorageTek SAM-QFS development team. The Sun StorageTek SAM-QFS development team works toward providing a cost-effective, high-performance, end-to-end solution for information lifecycle management (ILM).
http://developers.sun.com/solaris/articles/libsam.html
crawl-002
refinedweb
2,036
51.68
#include "libavutil/imgutils.h" #include "libavutil/pixdesc.h" #include "avfilter.h" Go to the source code of this file. Definition in file vf_fieldorder.c. full an array with the number of bytes that the video data occupies per line for each plane of the input video Definition at line 90 of file vf_fieldorder.c. can only currently do slices if this filter is doing nothing because this filter is moving picture content, the output slice will contain different video lines than the input slice and that complexity will be added later Definition at line 129 of file vf_fieldorder.c. Move every line up one line, working from the top to the bottom of the frame. The original top line is lost. The new last line is created as a copy of the penultimate line from that field. Move every line down one line, working from the bottom to the top of the frame. The original bottom line is lost. The new first line is created as a copy of the second line from that field. Definition at line 147 of file vf_fieldorder.c. Definition at line 108 of file vf_fieldorder.c. Referenced by avfilter_get_video_buffer(). Definition at line 38 of file vf_fieldorder.c. accept any input pixel format that is not hardware accelerated, not a bitstream format, and does not have vertically sub-sampled chroma Definition at line 64 of file vf_fieldorder.c. Definition at line 116 of file vf_fieldorder.c. Initial value: { .name = "fieldorder", .description = NULL_IF_CONFIG_SMALL("Set the field order."), .init = init, .priv_size = sizeof(FieldOrderContext), .query_formats = query_formats, .inputs = (const AVFilterPad[]) {{ .name = "default", .type = AVMEDIA_TYPE_VIDEO, .config_props = config_input, .start_frame = start_frame, .get_video_buffer = get_video_buffer, .draw_slice = draw_slice, .end_frame = end_frame, .min_perms = AV_PERM_READ, .rej_perms = AV_PERM_REUSE2|AV_PERM_PRESERVE,}, { .name = NULL}}, .outputs = (const AVFilterPad[]) {{ .name = "default", .type = AVMEDIA_TYPE_VIDEO, }, { .name = NULL}}, } Definition at line 215 of file vf_fieldorder.c.
http://ffmpeg.org/doxygen/0.10/vf__fieldorder_8c.html
CC-MAIN-2014-10
refinedweb
298
58.58
Realtime Elm Revisited with Elm 0.17 A few months ago on the Pusher blog I wrote about Making Elm Realtime by using Elm’s port system to integrate an Elm application with messages from PusherJS. When I published that post, the latest Elm version was 0.16 and integrating with Pusher wasn’t as easy as I would have liked it to be. In May Elm 0.17 was released, and one of the biggest changes was the removal of Signal from Elm, and replacing it with Commands and Subscriptions. We suddenly lost one of the most complex features of Elm, and they were replaced with a system that’s much easier to get your head around. It’s great to now be able to work with the higher level concepts of commands and subscriptions. If Elm’s signals put you off, I encourage you to try Elm again. In this post I’ll take the code base from my previous Elm post and upgrade it to Elm 0.17, noting the biggest changes. If you want to jump ahead and see all the changes, you can see the pull request I made on the repository that has all the changes. The great news is that Elm 0.17 includes less code to achieve the same functionality, and it’s definitely much reduced in complexity. Installing the new versions of Elm packages The first change was to update my elm-package.json to reflect all the new version numbers: "dependencies": { "elm-lang/core": "4.0.0 <= v < 5.0.0", "elm-lang/html": "1.0.0 <= v < 2.0.0", "evancz/elm-http": "3.0.1 <= v < 4.0.0" }, "elm-version": "0.17.0 <= v < 0.18.0" I then removed the elm-stuff folder (not required, but I like to ensure I’m starting from a clean slate when I bump versions!) and ran elm package install to get everything installed and up to date. At this point I got a tonne of errors from the Elm compiler. The great thing about Elm is that its compiler is so great; it’s easy to work your way through errors. New Conventions and Types One of the easiest changes is a naming one. Previously we used Action to denote all the events that can happen and how our app reacts to them. Now in Elm 0.17 it’s recommended to use Msg, as things are referred to as messages that flow through a system. This is an easy find and replace! Next up the signature of the view function has changed. Previously it took a Signal with an address to send actions to. Now that’s all handled for us, and the type has become view: Model => Html Msg. You can read that as “a function that takes a model and returns HTML that can generate messages of type Msg“. This dramatically simplifies all your view logic; there’s no need to pass round address now. Event handlers also are simpler, you just give them a Msg to produce: -- BEFORE: button [ onClick address SendMessage ] [...] -- AFTER: button [ onClick SendMessage ] [...] HTML App and Effects The elm-effects library which we used last time to manage our asynchronous events (such as HTTP requests) has been moved into the core, and exists in two parts, commands and subscriptions. We have two new corresponding types: Cmd and Sub. A Cmd is something we can give to Elm that will run in the background, and produce a message. Typically you’ll use Cmd Msg to declare commands that will run and produce messages of type Msg. You can use Sub to create subscriptions, which is useful when you need to be notified when something happens or some data changes. We’ll use these shortly in order to subscribe to some data that’s sent from PusherJS to Elm through a port. Now we’re using Cmd instead of effects, our update function’s signature also changes: update : Msg -> Model -> ( Model, Cmd Msg) Our update function takes the latest message and model and is expected to return a tuple of the new model and any commands that need to run in the background. If you don’t have any commands, you can use Cmd.none to signify that. For example, when we get a NewMessage, we prepend the string and return Cmd.none because there’s no background work to do. case action of NewMessage string -> ( { model | messages = string :: model.messages } , Cmd.none ) ... However, when we receive SendMessage, we return the result of postJson model.field, where postJson (which we will define shortly) is a function that takes in a string (the text typed by the user) and returns a Cmd Msg for Elm to run: case action of ... SendMessage -> ( { model | field = "" }, postJson model.field ) To hook all this together we can use the Elm Architecture. This used to be provided as the Elm Starter App, but now it’s been moved into the Elm HTML package. We can import Html.App as App and use the App.program function to create our app: main = App.program { init = init , view = view , update = update , subscriptions = subscriptions } Along with view and update, which we covered above, there are two other functions to define. init is expected to return ( Model, Cmd Msg ), which is the initial state of our application: initialModel = { messages = [ "Hello World" ], field = "" } init : ( Model, Cmd Msg ) init = ( initialModel, Cmd.none ) And subscriptions has to return a list of subscriptions that we want to listen to (such as mouse movements, keyboard events, or data from ports). This leads us nicely onto talking about the changes to Elm ports in 0.17! Ports in Elm 0.17 There’s been a few changes to ports in Elm 0.17. The first is that you must now explicitly declare any module that contains ports by updating the module declaration, by prepending port to it: port module PusherApp exposing (..) Next, ports now have a different type in Elm 0.17. Our newMessage port now looks like so: port newMessage : (String -> msg) -> Sub msg An Elm port takes a function that can turn the data sent over the port (in our case a string, containing the text of the message) and turn it into a message that can be subscribed to. We use lowercase msg here to indicate that the type can be any type and that whatever type the function produces will create a subscription of that type. You don’t need to worry much about this – it’s an implementation detail in how Elm deals with ports. Once we have our port we can define subscriptions, which takes in a model and returns a subscription: port newMessage : (String -> msg) -> Sub msg subscriptions : Model -> Sub Msg subscriptions model = newMessage NewMessage We call the newMessage port, giving it the NewMessage type, which will take all strings sent through the port and produce a Msg of type NewMessage String that our application can handle. When these are sent, our update function will be called and we’ll get our new message. HTTP The final part of the upgrade puzzle was the HTTP logic for posting the data to the server. Most of this has remained pretty similar but we now have Task.perform that can take a task, run it, and produce Cmd Msg to send through our system. To call it we give it three things: - a function that can take the error response and produce a Cmd Msg - a function that can take the successful response and produce a Cmd Msg - a Taskto run (most often an HTTP request) Our case is a bit of a special one; we don’t really care about the error or success message (ah, the beauty of building a demo app!), so in my call to Task.perform I just map both the error and success to create a NoOp message. The task itself is provided by httpPostMessage, a function I’ve defined that makes the post request to our server. postJson : String -> Cmd Msg postJson str = Task.perform (always NoOp) (always NoOp) (httpPostMessage str) We can call this function from update to kick off the async request in the background: update : Msg -> Model -> ( Model, Cmd Msg ) update action model = case action of ... SendMessage -> ( { model | field = "" }, postJson model.field ) And with that we’re fully up and running with Elm 0.17! Conclusion Elm 0.17 greatly reduces complexity and makes it easier to work with the language. Dealing with async activitites, interopability with ports and user interaction is all vastly improved. If you wrote off Elm previously due to the complexities in its Signals, I highly recommend checking it out again. The best place to start is with the Elm 0.17 Guide, or you could check out my Elm talk from PolyConf. If you’d like to see the changes I discussed in this post, you can find the pull request on GitHub.
https://blog.pusher.com/realtime-elm-revisited-with-elm-0-17/
CC-MAIN-2018-05
refinedweb
1,493
72.46
Tasks. Before I write about extended futures, let me say a few words about the advantages of tasks over threads. The key advantage of tasks over threads is that the programmer has only to think about what has to be done and not how - such as for threads - is has to be done. The programmer gives the system some job to perform and the system takes care that the job will be executed by the C++ runtime as smart as possible. That can mean that the job will be executed in the same process or a separate thread will be started. That can mean that another thread steals the job because it is idle. Under the hood, there is a thread pool that accepts the job and distributes it in a smart way. If that is not an abstraction? I have written a few posts about tasks in the form of std::async, std::packaged_task, and std::promise and std::future. The details are here tasks: But now the future of tasks. The name extended futures is quite easy to explain. Firstly, the interface of std::future was extended; secondly, there are new functions for creating special futures that are compensable. I will start with my first point. std::future has three new methods. An overview of the three new methods. At first, to something quite sophisticated. The state of a future can be valid or ready. Therefore (valid == true) is a requirement for (ready == true). Whom such as me perceive promise and future as the endpoints of a data channel, I will present my mental picture of valid and readiness. You can see a picture in my post Tasks. The future is valid if there is a data channel to a promise. The future is ready if the promise has already put its value into the data channel. Now, to the method then. then empowers you to attach a future to another future. Here it often happens that a future will be packed into another future. To unwrap the outer future is the job of the unwrapping constructor. Before I show the first code snippet, I have to say a few words about the proposal n3721. Most of this post is from the proposal to "Improvements for std::future<T> and Releated APIs". That also holds for my examples. Strange, they often did not use the final get call to get the result from the res future. Therefore, I added to the examples the res.get call and saved the result in a variable myResult. Additionally, I fixed a few typos. 1 2 3 4 5 6 7 8 9 10 11 12 #include <future> using namespace std; int main() { future<int> f1 = async([]() { return 123; }); future<string> f2 = f1.then([](future<int> f) { return to_string(f.get()); // here .get() won’t block }); auto myResult= f2.get(); } There is a subtle difference between the to_string(f.get()) - call (line 7) and the f2.get()-call in line 10: the first call is non-blocking or asynchronous and the second call is blocking or synchronous. The f2.get() - call waits until the result of the future-chain is available. This statement will also hold for chains such as f1.then(...).then(...).then(...).then(...) as it will hold for the composition of extended futures. The final f2.get() call is blocking. There is not so much to say about the extensions of std::async, std::package_task, and std::promise. I have only to add that all three return in C++20 extended futures. Therefore, the composition of futures is more exciting. Now we can compose asynchronous tasks. C++20 gets four new functions for creating special futures. These functions are std::make_ready_future, std::make_exceptional_future, std::when_all, and std::when_any. At first, to the functions std::make_ready_future, and std::make_exceptional_future. Both functions create a future that is immediately ready. In the first case, the future has a value; in the second case an exception. What seems to be strange makes a lot of sense. The creation of a ready future requires in C++11 a promise. That is even necessary if the shared state is immediately available. future<int> compute(int x) { if (x < 0) return make_ready_future<int>(-1); if (x == 0) return make_ready_future<int>(0); future<int> f1 = async([]() { return do_work(x); }); return f1; } Hence, the result must only be calculated using a promise, if (x > 0) holds. A short remark. Both functions are the pendant to the return function in a monad. I have already written about this very interesting aspect of extended futures. My emphasis in this post was more about functional programming in C++20. Now, let's finally begin with future-composition. Both functions have a lot in common. At first, to the input. Both functions accept a pair of iterators to a future range or an arbitrary number of futures. The big difference is that in the case of the pair of iterators the futures have to be of the same type; that holds not in the case of the arbitrary number of futures they can have different types and even std::future and std::shared_future can be used. The output of the function depends if a pair of iterators or an arbitrary numbers of futures (variadic template) was used. Both functions return a future. If a pair of iterators was used, you will get a future of futures in a std::vector: std::future<std::vector<futureR>>>. If you use use a variadic template, you will get a future of futures in a std::tuple: std::future<std::tuple<future<R0>, future<R1>, ... >>. That was it with their commonalities. The future, that both functions return, will be ready, if all input futures (when_all), or if any of (when_any) the input futures is ready. The next two examples show the usage of when_all and when_any. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #include <future> using namespace std; int main() { shared_future<int> shared_future1 = async([] { return intResult(125); }); future<string> future2 = async([]() { return stringResult("hi"); }); future<tuple<shared_future<int>, future<string>>> all_f = when_all(shared_future1, future2); future<int> result = all_f.then([](future<tuple<shared_future<int>, future<string>>> f){ return doWork(f.get()); }); auto myResult= result.get(); } The future all_f (line 9) composes the both futures shared_future1 (line 6) and future2 (Zeile 7). The future result in line 11 will be executed if all underlying futures are ready. In this case, the future all_f in line 12 will be executed. The result is in the future result available and can be used in line 14. The future in when_any can be taken by result in line 11. result provides the information which input future is ready. If you don't use when_any_result, you have to ask each future if it is ready. That is tedious. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 #include <future> #include <vector> using namespace std; int main(){ vector<future<int>> v{ .... }; auto future_any = when_any(v.begin(), v.end()); when_any_result<vector<future<int>>> result= future_any.get(); future<int>& ready_future = result.futures[result.index]; auto myResult= ready_future.get(); } future_any is the future that will be ready if one of the input futures is ready. future_any.get() in line 11 returns the future result. By using result.futures[result.index] (line 13) you have the ready future and thanks to ready_future.get() you can ask for the result of the job. Latches and barriers support it to synchronise threads via a counter. I will present them in the next post. Two years later, the future of the futures changed a lot because of executores. Here are the details of execut this great article.But I couldn't use these new features because I couldn't find header. I tried CLang++ 8, G++ 8 and MSVC 16 (latest version) but none of them contains .How can I try these features? Hunting Today 592 Yesterday 7029 Week 40916 Month 107582 All 7375422 Currently are 151 guests and no members online Kubik-Rubik Joomla! Extensions Read more... opinions. Great blog, styick with it! I'll make sure too bookmark it and come back to read more off yoour helpful info.Thanks for the post. I'll definitely return. But I couldn't use these new features because I couldn't find header. I tried CLang++ 8, G++ 8 and MSVC 16 (latest version) but none of them contains . How can I try these features? I used the HPX () library.
https://modernescpp.com/index.php/std-future-extensions
CC-MAIN-2021-43
refinedweb
1,426
67.86
Java Collection, HashMap Exercises: Remove all the mappings from a map Java Collection, HashMap Exercises: Exercise-4 with Solution Write a Java program to remove all the mappings from a map. Sample Solution:- Java Code: import java.util.*; public class Example4 { public static void main(String args[]) { HashMap <Integer,String> hash_map = new HashMap <Integer,String> (); hash_map.put(1, "Red"); hash_map.put(2, "Green"); hash_map.put(3, "Black"); hash_map.put(4, "White"); hash_map.put(5, "Blue"); // print the map System.out.println("The Original linked map: " + hash_map); // Removing all the elements from the linked map hash_map.clear(); System.out.println("The New map: " + hash_map); } } Sample Output: The Original linked map: {1=Red, 2=Green, 3=Black, 4=White, 5=Blue} The New map: {} Java Code Editor: Contribute your code and comments through Disqus. What is the difficulty level of this exercise? New Content: Composer: Dependency manager for PHP, R Programming
https://www.w3resource.com/java-exercises/collection/java-collection-hash-map-exercise-4.php
CC-MAIN-2019-18
refinedweb
149
52.66
Nepomuk #include <Nepomuk/Service> Detailed Description Base class for all Nepomuk services. A Nepomuk service is intended to perform some kind of operation on the Nepomuk data storage. This can include data gathering, data enrichment, or enhanced data query. Nepomuk services are started and managed by the Nepomuk server. Very much like KDED modules a Nepomuk service has autostart and start-on-demand properties. In addition a Nepomuk service can define an arbitrary number of dependencies which are necessary to run the service. These dependencies name other services. To create a new Nepomuk service one derives a new class from Nepomuk::Service and exports it as a standard KDE module, i.e. plugin. Export it as a Nepomuk service plugin: A desktop file describes the service's properties: The Nepomuk server will automatically export all D-Bus interfaces defined on the service instance. Thus, the simplest way to export methods via D-Bus is by marking them with Q_SCRIPTABLE. - Since - 4.1 Definition at line 87 of file nepomukservice.h. Constructor & Destructor Documentation Destructor. Member Function Documentation - Returns - A wrapper model which provides a connection to the Nepomuk server. A Nepomuk service can make use of a warmup phase in which it is not usable yet. Call this method once your service is fully initialized. Most services do not need to call this method. - Parameters - - See Also - Service::Service.
http://api.kde.org/4.x-api/kdelibs-apidocs/nepomuk/html/classNepomuk_1_1Service.html
CC-MAIN-2014-15
refinedweb
229
50.02
Descripción This plugin has, as input, the GPX file with the track you’ve made and as output it shows the map of the track and an interactive altitude graph (where available). Fully configurable: - Custom colors - Custom icons - Multiple language support Supported charts: - Altitude - Speed - Heart rate - Temperature - Cadence - Grade NextGen Gallery Integration: Display your NextGen Gallery images inside the map! Even if you don’t have a GPS camera, this plugin can retrive the image position starting from the image date and your GPX file. This version is extended by: Stephan Klein and supports displaying all images attached to a post without using NGG. Try this plugin: Support: If you need help, please use: Support Forum Would you like to help fix bugs or further develop the plugin? On Github you can contribuite easly with your code. Translations: Translators are welcome to contribute to the plugin. Please use the WordPress translation website. The language files in the plugin contain 18 translatable texts for 13 languages: - Catalan ca - Dutch nl_NL - English (default) - French fr_FR - Hungarian hu_HU - Italian it_IT - Norwegian nb_NO - Polish pl_PL - Portuguese (Brazilian) pt_BR - Russian ru_RU - Spanish es_ES - Swedish sv_SE - Turkish tr_TR - Bulgarian bg_BG - Slovak cs_CZ - Norwegian nb_NO - Japanese ja_JP (Many thanks to all guys who helped me with the translations) Supported GPX namespaces are: Thanks to:, Icons made by Freepik from is licensed by Creative Commons BY 3.0 Capturas Instalación Use the classic wordpress plugin installer or copy the plugins folder to the /wp-content/plugins/directory Activar el plugin desde el menú «Plugins» de WordPress Add the shortcode [sgpx gpx=»>relative path to your gpx<«] or [sgpx gpx=»><«] Which map types are available? You can use the following map types: - OSM1 = Open Street Map (Default setting) - OSM2 = Open Cycle Map / Thunderforest – Open Cycle Map (API Key required) - OSM3 = Thunderforest – Outdoors (API Key required) - OSM4 = Thunderforest – Transport (API Key required) - OSM5 = Thunderforest – Landscape (API Key required) - OSM7 = Open Street Map – Humanitarian map style - OSM9 = Hike & Bike - OSM10 = Open Sea Map If you use the OpenCycleMap without the API key, a watermark appears on the card: «API Key required». The Thunderforest maps Outdoors, Transport and Landscape are only displayed with an API Key. Which shortcode attributes are available? You can use the following shortcodes: - gpx: Relative path to the GPX file - width: Map width (Value in percent) - mheight: Map height (Value in pixeln) - gheight: Graph height (Value in pixeln) - skipcache: Do not use cache. If TRUE might be very slow (Default is false) - download: Allow users to download your GPX file (Default is false) - summary: Print summary details of your GPX track (Default is false) - summarytotlen: Print total distance in summary table (Default is false) - summarymaxele: Print max elevation in summary table (Default is false) - summaryminele: Print min Elevation in summary table (Default is false) - summaryeleup: Print total climbing in summary table (Default is false) - summaryeledown: Print total descent in summary table (Default is false) - summaryavgspeed: Print average Speed in summary table (Default is false) - summarytotaltime: Print total time in summary table (Default is false) - mtype: Map types - mlinecolor: Map line color (Default is #3366cc) - zoomonscrollwheel: Zoom on map when mouse scroll wheel (Default is false) - waypoints: Print the gpx waypoints inside the map (Default is false) - startIcon: Start track icon - endIcon: End track icon - currentIcon: Current position icon (when mouse hover) - waypointicon: Custom waypoint icon - showele: Show elevation data inside the chart (Default is true) - uom: Distance/altitude unit of measure - 0 = meters/meters (Default setting) - 1 = feet/miles - 2 = meters/kilometers - 3 = meters/nautical miles - 4 = meters/miles - 5 = feet/nautical miles - glinecolor: Altitude line color (Default is #3366cc) - chartFrom1: Minimun value for altitude chart - chartTo1: Maxumin value for altitude chart - showspeed: Show speed inside the chart (Default is false) - glinecolorspeed: Speed line color (Default is #ff0000) - uomspeed: Unit of measure for speed - 0 = m/s (Default setting) - 1 = km/h - 2 = miles/h - 3 = min/km - 4 = min/miles - 5 = Nautical Miles/Hour (Knots) - 6 = min/100 meters - chartFrom2: Minimun value for speed chart - chartTo2: Maxumin value for speed chart - showhr: Show heart rate inside the chart (Default is false) - glinecolorhr: Heart rate line color (Default is #ff77bd) - showatemp: Show temperature inside the chart (Default is false) - glinecoloratemp: Temperature line color (Default is #ff77bd) - showcad: Show cadence inside the chart (Default is false) - glinecolorcad: Cadence line color (Default is #beecff) - showgrade: Show grade inside the chart (Default is false) - glinecolorgrade: Grade line color (Default is #beecff) - nggalleries: NextGen Gallery id or a list of Galleries id separated by a comma - ngimages: NextGen Image id or a list of Images id separated by a comma - attachments: Show all images that are attached to post (Default is false) - dtoffset: The difference (in seconds) between your gpx tool date and your camera date - pointsoffset: Skip points closer than XX meters (Default is 10) - donotreducegpx: Print all the point without reduce it (Default is false) What happening if I’ve a very large GPX files? This plugin will print a small amout of points to speedup javascript and pageload. Is it free? Yes! Reseñas Colaboradores y desarrolladores «WP GPX Maps» es un software de código abierto. Las siguientes personas han colaborado con este plugin.Colaboradores «WP GPX Maps» ha sido traducido a 2 idiomas locales. Gracias a los traductores por sus contribuciones. Traduce «WP GPX.02 - fix admin error 1.7.01 - General: Removed Maptoolkit (code OSM6) map provider. Requested by H.F. (Maptoolkit Managing director) - General: Added new map type «Thunderforest – Outddors» (OSM3) - Admin: Added admin notices in the dashboard - Settings Tab: In the map selection changed to the correct maps provider from «Open Cycle Map»* Settings Tab: to «Thunderforest» - Administration Tab: New Tab with the settings «Editor & Author upload» and «Show update notice» - Help Tab: In the map selection changed to the correct maps provider from «Open Cycle Map» to «Thunderforest» - Output: In the map selection changed to the correct maps provider from «Open Cycle Map» to «Thunderforest» - Output: Fixed in map footer for each map, the corresponding map provider is displayed with URL - Code: Added PHP version notices, WordPress 5.3 requires PHP 5.6.20 - Code: Added Missing entries for add and delete options - Code: Style for output moved in a seperate CSS file - Code: Adjustments a la WPCS - Code: Small CSS design optimizations for the tabs - Code: Upgrade bootstrap-table to 1.13.2 - Code: Removed german language file (now over translate.wordpress.org) 1.7.00 - Added: Authors can upload GPX tracks in a folder called as your user name, inside [../wp-upload dir/gpx/[your user name] (thanks to wildcomputations) - Added: Authors an Admins can see the current values for shortcodes in help tab - Added: Button to instant copy the shortcode of the selected GPX file in the tab track - Added: different size logos for the plugin store (icon.svg, icon128x128.png and icon256x256.png) [inside ../plugins/wp-gpx-maps/assets] - Changed: Settings tab is for non-Admin users is not more visible - Tweak: Help tab is easier to read - Tweak: Plugin is now complete translatable (Backend + Frontend) - Tweak: WordPress coding standards - Upgrade: Leaflet to 1.5.1 - Upgrade: leaflet.fullscreen to 1.4.5 - Upgrade: Chart.min.js to 2.8.0 1.6.07 - resolve admin error 1.6.06 - Added average values under the graph (thanks to cyclinggeorgian) 1.6.04 - NGG gallery is working - Getting HR, Cad and Temp working again (thanks to cyclinggeorgian) - Fix javascript errors - Fix multiple traks gpx 1.6.03 - Fix syntax error causing graph not to display (thanks to nickstabler) 1.6.02 - Resolved errors with start and end icons 1.6.01 - Removed Gogole maps. Leafletjs instead. - — NextGen Gallery is not working, due next gen image format changed — I’ll fix soon 1.5.05 - renamed javascript functions to avoid collision with other plugins - reduced chart line thickness 1.5.04 - fix uom - fix file not found 1.5.03 - fix random error 1.5.02 - Security improvements 1.5.01 - Improved security - Included javascript - Multiple file upload - Implemented sorting in file list - Renamed internal function to improve wp compatibility 1.5.00 - replaced highcharts with chartjs. This is a forced choice due highcharts license issue, view: 1.3.16 - Added Norwegian nb_NO translation (thanks to thordivel) - Added Japanese ja_JP translation (thanks to dentos) 1.3.15 - Switched to HTTPS where possible (thanks to delitestudio) 1.3.14 - Added Thunderforest Api Key on settings: for OpenCycleMap 1.3.13 - Added google maps api key on settings - Removed parameter ‘sensor’ on google maps js - Added unit of measure of speed for swimmers: min/100 meters 1.3.12 - Fix incompatibility with Debian PHP7 (thanks to phbaer) 1.3.10 - Improved german translations (thanks to Konrad) 1.3.9 - Retrieve waypoints in JSON, possibility to add a custom marker (Changed by Michel Selerin) 1.3.8 - Improved Google Maps visualization 1.3.7 - NextGen Gallery’s Attachment support. Thanks to Stephan Klein () 1.3.6 - Fix: remote file download issue - Fix: download file link with WPML - Improved cache with filetime (thanks to David) 1.3.5 - Fix: Garmin cadence again - Fix: WP Tabs 1.3.4 - Fix: Garmin cadence - Infowindows closing on mouseout 1.3.3 - Add feet/Nautical Miles units (thanks to elperepat) - Update OpenStreetMaps Credits - WP Tabs fix 1.3.2 - fix: left axis not visible (downgrade highcharts to v3.0.10) - fix: fullscreen map js error 1.3.1 - fix: http/https javascript registration - fix: full screen map css issue 1.3.0 - Speed improvement - Rewritten js classes - Added Temperature chart - Added HTML5 Gps position (you can now follow the gpx with your mobile phone/tablet/pc) 1.2.6 - Speed improvement 1.2.5 - Added Catalan translation, thanks to Edgar - Updated Spanish translation, thanks to Dani - Added different types of distance: Normal, Flat (don’t consider altitude) and Climb distance 1.2.4 - Added Bulgarian translation, thanks to Svilen Savov - Added possibility to hide the elevation chart 1.2.2 - Smaller map type selector - Fix: Google maps exception for NextGen Gallery 1.2.1 - Fix: NextGen Gallery 1.9 compatibility 1.2.0 - NextGen Gallery 2 support - NextGen Gallery Pro support 1.1.46 - Added meters/miles chart unit of measure - Added Russian translation, thanks to G.A.P 1.1.45 - Added nautical miles as distance (Many thanks to Anders) 1.1.44 - Added Chart zoom feature - Some small bug fixes 1.1.43 - Added Portuguese (Brazilian) translation, thanks to André Ramos - new map: Open Cycle Map – Transport - new map: Open Cycle Map – Landscape 1.1.42 - qTranslate compatible 1.1.41 - Added Polish translation, thanks to Sebastian - Fix: Spanish translation - Minor javascript improvement 1.1.40 - Improved italian translation - Added grade chart (beta) 1.1.39 - Added French translation, thanks to Hervé - Added Nautical Miles per Hour (Knots) unit of measure 1.1.38 - Fix: garmin gpx cadence and heart rate - Updated Turkish translation, thanks to Edip - Added Hungarian translation, thanks to Tami 1.1.36 - Even Editor and Author users can upload their own gpx. Administrators can see all the administrators gpx. The other users can see only their uploads 1.1.35 - Fix: In the post list, sometime, the maps was not displaying correctly ( the php rand() function was not working?? ) - Various improvements for multi track gpx. Thanks to GPSracks.tv - Summary table is now avaiable even without chart. Thanks to David 1.1.34 - 2 decimals for unit of measure min/km and min/mi - translation file updated (a couple of phrases added) - File list reverse order (from the newer to the older) - nggallery integration: division by zero fixed 1.1.33 - Decimals reducted to 1 for unit of measure min/km and min/mi - map zoom and center position is working with waypoints only files - automatic scale works again (thanks to MArkus) 1.1.32 - You can exclude cache (slower and not recommended) - You can decide what show in the summary table - German translation (thanks to Ali) 1.1.31 - Fixed fullscreen map image slideshow 1.1.30 - Multi track gpx support - Next Gen Gallery images positions derived from date. You can adjust the date with the shortcode attribute dtoffset - If you set Chart Height (shortcode gheight) = 0 means hide the graph - Fix: All images should work, independent from browser cache 1.1.29 - Decimal separator is working with all the browsers - minutes per mile and minutes per kilometer was wrong 1.1.28 - Decimal and thousand separator derived from browser language - Added summary table (see settings): Total distance, Max elevation, Min elevation, Total climbing, Total descent, Average speed - Added 2 speed units of measure: minutes per mile and minutes per kilometer 1.1.26 - Multilanguage implementation (only front-end). I’ve implemented the italian one, I hope somebody will help me with other languages.. - Map Full screen mode (I’m sure it’s not working in ie6. don’t even ask!) - Added waypoint custom icon 1.1.25 - Added possibility to download your gpx 1.1.23 - Security fix, please update! 1.1.22 - enable map zoom on scroll wheel (check settings) - test attributes in get params 1.1.21 - google maps images fixed (templates with bad css) - upgrade to google maps 3.9 1.1.20 - google maps images fixed in Yoko theme 1.1.19 - include jQuery if needed 1.1.17 - Remove zero values from cadence and heart rate charts - nextgen gallery improvement 1.1.16 - Cadence chart (where available) - minor bug fixes 1.1.15 - migration from google chart to highcharts. Highcharts are much better than google chart! This is the base for a new serie of improvements. Stay in touch for the next releases! - heart rate chart (where available) 1.1.14 - added css to avoid map bars display issue 1.1.13 - added new types of maps: Open Street Map, Open Cycle Map, Hike & Bike. - fixed nextgen gallery caching problem 1.1.12 - nextgen gallery display bug fixes
https://es.wordpress.org/plugins/wp-gpx-maps/
CC-MAIN-2020-34
refinedweb
2,321
62.58
. Hello, When making my own 4-in-a-row program I struggled with passing these 2d arrays to functions. Eventually caved and just made the array size a "magic number" because thats the only thing that I could figure out. After reading this chapter I still found I didn't know how to properly pass them. Looked something like this in the end: Preferably I would have liked to use a reference or just write the passing statement as a pointer but I got all kinds of errors. Is passing a 2d array something covered in chapter 7, or is there a section I should revise in this chapter? Skimmed the chapter again and could not find any details, only stuff that worked for single arrays. Once again thanks to nascar and Alex, without you the program would never have worked at all, I feel pretty proud that it finally works and its all thanks to you! Hi Barne! * You're using the same name style for types, variables, and functions. This will lead to confusion. > Eventually caved and just made the array size a "magic number" Declare constants. You're allowed to omit the first size specifier of multidimensional arrays, but not the others. > I would have liked to use a reference Or let the compiler do it for you > write the passing statement as a pointer The outer array would have to decay to a pointer to int[7] and the inner array would have to decay to a pointer to int. I don't think both arrays can decay at the same time. Maybe someone else knows more. Use a type alias, it saves you a lot of ugly syntax. Hello nascar, > Declare constants I assume you mean a global constant within a namespace since I can’t use a constant declared within main() in the parameter? I see your use of references, but since I still have to write out the array size I don’t think it helps me too much. Guess there is no easy way of omitting both specifiers? > I assume you mean a global constant within a namespace Correct. > Guess there is no easy way of omitting both specifiers? Type aliases. Saves you from magic numbers and ugly syntax. How to print size of multi dimensional array? Because std::size(array) is not effective for multi dimensional array, it will only return no of rows but not the column. This assumes that every sub-array has the same length. If they have different lengths, you'll need a loop. Thanks Hi I need your help I did'nt get the last program can you explain it? Hi Sourabh, 1) for (int row = 0; row < numRows; ++row) 2) for (int col = 0; col < numCols; ++col) 3) product[row][col] = row * col; first in the outer for loop(line no 1) we are taking row as a multiplier and in the inner for loop we are taking col as a number so lets skip the zero multiplier(row = 0), start with row = 1 once row is initialize with value 1 inner for loop will start iteration. col will be initialized with 0, 1, 2, 3,..., 9 and at line no 3 we are multiplying these value of col with that of row(i.e 1) so in this way we are storing one's table after that row =2 and then it will multiply col by row = 2 and give us the two's table. similarly it will continue till row = 9. and then at printing the table we are excluding 0th row and 0th column because those will only contain zero. how to initialise all elements of s fixed array from console If by console you mean user input, there's no easy way to do this. You're better off initializing to some initial value (e.g. 0) and then use a look to ask the user to provide values, and use assignment to get them into the fixed array. Hi, Do multidimensional arrays allocate more memory than standard arrays? Hi Haider! The standard doesn't force a specific implementation, so there is no general answer to your question. Both arrays can store 10 ints. Assuming x86_64 architecture with sizeof(int)=4 and sizeof(void*)=8; no compiler optimization; and ignoring the compiler-generated information block: One way of implementing multidimensional arrays is: @a takes up 8 bytes for the pointer to the first element and 4 bytes for each element. 8B + (10 * 4B) = 48B @b takes up 8 bytes for the pointer to the first element, each sub-array takes up 8 bytes for the pointer to their first elements, and each int takes up 4 bytes. 8B + (5 * 8B) + (5 * 2 * 4B) = 88B Conclusion: The more sub-arrays there are, the more memory is used. GCC's way of implementing multidimensional arrays is: A multidimensional array is a one-dimensional array. All elements are stored one after the other in memory, resulting the the same memory usage as one-dimensional arrays. Thanks for the explanation! This means, initialize the first elements to 1 and 2, and the rest of the elements "as if they had static storage duration". There is a rule in C saying that all objects of static storage duration, that are not explicitly initialized by the programmer, must be set to zero. i read this here can you please explain this , will it mean the array indices whose default value is set 0 as if static will have file scope? and what else automatically falls into static storage duration ? and does every data type is default 0 in this storage? and why you didn't used {} instead of {0}? sorry for so many questions.. Thanks Nope, because that's a C rule. C++ rules for initialization of arrays are here: In particular: "If the number of initializer clauses is less than the number of members and bases (since C++17) or initializer list is completely empty, the remaining members and bases (since C++17) are initialized by their default initializers, if provided in the class definition, and otherwise (since C++14) by empty lists, in accordance with the usual list-initialization rules (which performs value-initialization for non-class types and non-aggregate classes with default constructors, and aggregate initialization for aggregates)." If you look up value initialization (), you'll see this: "...otherwise, the object is zero-initialized.", which is what happens here for the elements that don't have initializers specified. Can someone explain the output for the below program?? Output: 21 18 21 Hi KKR! @Alex Do you have an explanation for why Line 8 in @KKR's code is a thing? I can't find any information about it. Probably because I don't know what to search for. Thank you nascardriver!! And please post if you find info regarding that syntax. I find it quite weird! Found it! a[b] is *(a + b) and since *(a + b) == *(b + a) a[b] == b[a] Source: Wow nice.. Thanks again!! Wow, I didn't know that was possible. How... weird. :) Hello, why when I make a multidimensional array like this std::array<std::array<int, 3>, 3> arr{ { { 1, 2, 3 },{ 4, 5, 6 },{ 7, 8, 9 } } } I cant access it as in your example std::cout << array[0][1][2] The last one says "Expression must have pointer to object" Hi Will! Two issues, 1] Your array is two-dimensional (3x3), but you're trying to access it like a three-dimensional array. The deepest you can go on a two-dimensional array is arr[x][y], not arr[x][y][z]. 2] You named your variable 'arr' but you're trying the access 'array'. That's what's causing your error. Ahh I see lol I thought I was doing a 3d one Yeah the name I noticed, was only curious about the last one asking for a pointer ^^ Thanks Maybe it's just for education purposes, but otherwise wouldn't you keep it simple and create a "int multiply(int x, int y){}" function and just make it so "array[row][col] = multiply(row, col)" in a for loop? You could, but multiplying 2 integers is such a simple operation I'm not sure why you'd create a function for it. how can I set the value of 2d array from the user? int a, b; cout << "Enter first value : " ; cin >> a ; cout << "Enter second value : " ; cin >> b ; // i will get error int myArray[a][b] You have to use dynamic allocation. I talk about this in a later lesson in this chapter. can we use vectors as multi-dimensional arrays? if yes, how? You could have a vector of vectors. But you're maybe better off allocating a single dimensional vector and use math to map two coordinates down to one. Name (required) Website
https://www.learncpp.com/cpp-tutorial/65-multidimensional-arrays/comment-page-2/
CC-MAIN-2019-13
refinedweb
1,484
70.94
I have a bit of code which pulls in a HTML page from a local SQLite database file in .NET Core 2.0. This code works fine when exicuted in debug mode, but runs extremely slow in production after I have published the app. I used a Stopwatch to diagnose which piece of code is causing the problem and found that connection.QueryFirstOrDefault takes 2ms to find a single row in debug mode, however the same task takes 1.4 seconds after I have published the app. That's about 700 times slower. //initialize connection var connection = new SqliteConnection("Data Source=" + dbName); // Build SQL String string query = @"SELECT * FROM HtmlItems WHERE PostID = 1; // Start Timer var watch = System.Diagnostics.Stopwatch.StartNew(); Submit query HtmlItem = connection.QueryFirstOrDefault<HtmlItem>(query); // End Timer watch.Stop(); var result = watch.ElapsedMilliseconds(); The query maps to an object looking like this public class HtmlItem { public int PostID { get; set; } public string PostTitle { get; set; } public string PostDescription { get; set; } public int PostDate { get; set; } // Unix Timestamp public int Hidden { get; set; } public string Url { get; set; } public string PostHTML { get; set; } } The same database file is used in debug and production, this database file only has three rows. My app should be the only thing trying to access the file. Indexing the SQLite database file dosen't seem to make any speed improvement. I'm wondering how I can identify what's causing my connection to the database to be 700x slower in production. SQLite dosen't seem to be very quick with dapper on .net core when reading the file synchronously. If you read the file using asynchronous then it seems to be much faster. HtmlItem = await connection.QueryFirstOrDefault<HtmlItem>(query);
https://dapper-tutorial.net/knowledge-base/49742811/extremely-slow-sqlite-query-speed-using-dapper-in--net-core
CC-MAIN-2020-40
refinedweb
286
65.73
. Every now and then, one finds oneself in a place where the near-ubiquitous Internet connectivity of today is absent, unusably slow, or prohibitively expensive. Some network functionality (like email) may be worth hassle and expense, while others (like streaming media) are not. Somewhere in between, though, lies reference data, which would be nice to cache locally for offline access, if it were technically feasible. To that end, some "open content" projects, such as OpenStreetMap, make configuring offline access relatively painless, but many others do not. For Wikipedia and the related Wikimedia projects (Wiktionary, Wikivoyage, etc.), the combination of an exceptionally large data set, constant editing, and multiple languages makes for a more challenging target—and a niche has developed for offline Wikipedia access software. Of course, the "correct" solution to providing offline Wikipedia access would arguably be to run a mirror of the real site, which it is certainly possible to do. But, even then, mirrors start with a hefty Wikipedia database dump that requires considerable storage space: around 44GB for the basic text of the English Wikipedia site, without the "talk" or individual user pages. The media content is larger still; around 40TB are currently in Wikimedia's Commons, of which roughly 37TB is still images. Moreover, the database-import method does not allow a mirror to keep up with ongoing edits, although doing so would consume considerable system resources anyway. On the other hand, in many cases, Wikipedia's usefulness as a general-purpose reference does not depend on having the absolute newest version of each article. Wikimedia makes periodic database dumps, which can suffice for weeks or even months at a time, depending on the subject. It is probably no surprise, then, that the most popular offline-Wikipedia tools focus on turning these periodic database releases into an approximation of the live site. Many also take a number of steps to conserve space—usually by storing a compressed version of the data, but in some cases by also omitting major sections of the content as well. There are two actively developed open-source tools for desktop Linux systems at present: XOWA and Kiwix. Both support storing compressed, searchable archives of multiple Wikimedia sites, although they differ on quite a few of the details. Kiwix uses the openZIM file format for its content storage. The Wikipedia database dump is converted into static HTML beforehand, then compressed into the ZIM format. The basic ZIM format includes a metadata index that supports searching article titles, but to enable full-text search, the file must be indexed. The Kiwix project offers both indexed and unindexed archives for download; the indexed files are (naturally) larger, and they also come bundled with the Windows build of Kiwix. The ZIM format is designed with this usage in mind; its development is spearheaded by Switzerland's Wikimedia CH. As far as content availability is concerned, the Kiwix project periodically updates its official ZIM releases for Wikipedia only—albeit in multiple languages (69 at present, not counting image-free variants available for a handful of the larger editions). In addition, volunteers produce ZIM files for other sites, at the moment including Wikivoyage, Wikiquote, Wiktionary, and Project Gutenberg, with TED and other efforts still in the works. Kiwix itself is a GPLv3-licensed, standalone graphical application that most closely resembles a "help browser" or e-book reader. The content displayed is HTML, of course, but the user interface is limited to the content installed in the local "library." Users can search for new ZIM content from within the application as well as check for updates to the installed files. Interestingly enough, there are many more ZIM archives listed within Kiwix's available-files browser than there are listed on the project's web site; why any particular offering is listed in the application is not clear, since some of the options appear to be personal vanity-publishing works. Searching and browsing installed archives is simple and fast; type-ahead search suggestions are available and one can bookmark individual pages. There are also built-in tools for checking the integrity of downloaded archives and exporting pages to PDF. In broad strokes, XOWA offers much the same experience as Kiwix: one installs a browser-like standalone application (AGPL-licensed, in this case), for which individual offline-site archives must be manually installed. Like Kiwix, XOWA can download and install content from its own, official archives. But while Kiwix archives contain indexed, pre-generated HTML, XOWA archives include XML from the original database dumps (stored in SQLite files), which is then dynamically rendered into HTML whenever a new page is opened. In theory, the XML in the Wikipedia database dumps is the original Wiki markup of the articles, so it should be more compact than the equivalent rendered HTML. In practice, though, such a comparison is less simple. The latest Kiwix ZIM file for the English Wikipedia is 42GB with images, 12GB without, whereas the latest XOWA releases are 89.6GB with images and 14.6GB without. But XOWA also makes a point of the fact that in includes not only the basic articles, but also the "Category," "Portal," and "Help" namespaces, as well as multiple sizes of the included images. When comparing the two approaches, it is also important to note that XOWA is specifically designed for use with Wikimedia database dumps, a choice that has both pros and cons. In the pro column, virtually any compatible database dump can be used with the application; XOWA offers Wikipedia for 30 languages and a much larger selection of the related sites (Wiktionary, Wikivoyage, Wikiquote, Wikisource, Wikibooks, Wikiversity, and Wikinews, which are bundled together for most languages). XOWA's releases also tend to be more up-to-date; at present none is older than a few months, while some of the less-popular Kiwix archives are several years old. The downsides, though, start with the fact that only Wikimedia-compatible content is supported. Thus, there is no Project Gutenberg archive available, nor could your favorite Linux news site generate a handy offline article archive should it feel compelled to do so. But perhaps more troubling is the fact that XOWA archives do not support full-text searching. Lookup by title is supported, but that may not always be sufficient for research. The browsing experience of the XOWA application is similar to Kiwix; both HTML renderers use Mozilla's XULRunner. XOWA also supports bookmarking pages and library maintenance. XOWA gains a point for allowing the user to seamlessly jump between installed wikis; a Wikipedia link to a Wiktionary page works automatically in XOWA, while a Kiwix user must return to the "library" screen and manually open up a second archive in order to change sites. On the other hand, XOWA does not support printing or PDF export, and there is a noticeable lag between clicking on a link and seeing the page load. The status bar at the bottom of the window is informative enough to indicate that the delay is due to XOWA's JTidy-based parser; it reports the loading of the page content as well as each template and navigation element used. The parser can also still trip up in its XML-to-HTML conversion. If one is concerned about the accuracy of the conversion, of course, Kiwix's pre-generated HTML offers no guarantees either, but at least its results are static and will not crash on an odd bit of Wiki-markup syntax. Ultimately, though, if the question is whether XOWA or Kiwix generates pages more like those one sees in the web browser from the live Wikimedia site, neither standalone application is perfect. But users may chafe at the very need to run a separate application to read Wikipedia to begin with. Fortunately, both projects are also pursuing another option: serving up their content with an embedded web server, which permits users to access the offline archives from any browser they choose. XOWA's server can be started with: java -jar /xowa/xowa_linux.jar --app_mode http_server --http_server_port 8080 Kiwix's server (which, like Kiwix, is written in C++) can be started from the command line with: kiwix-serve --port=8000 wikipedia.zim or launched from the application's "Tools" menu. A nice touch for those experimenting with both is that Kiwix defaults to TCP port 8000, XOWA to port 8080. The XOWA project also offers a Firefox extension that directs xowa: URIs to the local XOWA web server process. Moving forward, it will be interesting to watch how both projects are affected by changes to Wikimedia's infrastructure. The XOWA internal documentation notes that Wikipedia is, at some point, planning to implement diff-style database update releases in addition to its full-database dumps. Incremental updates are one of the factors that makes OpenStreetMap so usable in offline mode, and Wikipedia's lack of such updates is what contributes the most pain to Kiwix and XOWA usage: waiting for those multi-gigabyte downloads to finish. As unsatisfying as it may seem, neither application emerges as the clear winner for someone inspired to head off to a rustic cabin in the mountains and read Wikipedia at length. At its most basic, the trade-off would seem to be Kiwix's support for non-Wikimedia sites and its full-text search versus XOWA's cross-wiki link support and more predictable update process. Either will likely serve the casual user well. The relationship between CentOS and Red Hat has always been interesting. Red Hat provides the source packages that, after removal of branding elements, are built into the CentOS release. By one measure, CentOS is sustaining freeloaders who want to benefit from Red Hat's work without paying for it. By another, CentOS helps Red Hat by bringing users into its ecosystem; some of those users eventually become paying Red Hat customers. So it is not surprising that users can see the recent acquisition of CentOS by Red Hat in two different lights: it's either an attempt to squash a competing distribution or an effort to sustain that distribution with much-needed support. Either way, changes were always going to happen after the acquisition. CentOS users will certainly be happy about the first of those changes: support for CentOS developers so they can work on the distribution full time, and support for the infrastructure needed to keep CentOS going. But when CentOS project leader Karanbir Singh proposed a change to the seemingly trivial issue of version numbers, users were quick to express their disapproval. Traditionally, CentOS releases have used the same version number as the RHEL release they are based on; CentOS 6.5 is a rebuild of the RHEL 6.5 release, for example. The CentOS developers now want to change to a scheme where the major number matches the RHEL major number, but the minor number is generated from the release date. So, if the CentOS version of RHEL 7.0 were to come out in July 2014, it might have a version number like 7.1407. Derivative releases from CentOS special interest groups (SIGs) would have an additional, SIG-specific tag appended to that number. To the CentOS developers, this change offers a number of advantages. The close tie with RHEL version numbers, it is claimed, can confuse users into believing that a release is supported with security updates when it is not; see this detailed message from Johnny Hughes for an explanation of the reasoning there. Putting the release date into the version number makes the age of a release immediately obvious, presumably inspiring users to upgrade to current releases. This scheme would also make it easier to create releases that are not directly tied to RHEL releases; that is something that the SIGs, in particular, would like to be able to do. Supporting the SIGs is a big part of the project's plan for the future in general. Karsten Wade described it this way: So it seems that CentOS wants to follow Red Hat into the cloud. Simply providing a rebuild of RHEL is not as exciting as it once was, so the project wants to expand into other areas where, it is hoped, more users are to be found. It should be possible to expand in this way as long as the core CentOS distribution remains what it has always been. Unfortunately, some users are worried that things will not be that way. Ljubomir Ljubojevic, the maintainer of the CentOS Facebook page, described his feelings about the change: A large number of "me too" posts made it clear that Ljubomir is not alone in feeling this way. There is a lot of concern that the project might break the core distribution and that adopting a new version numbering scheme looks like a first step in that direction. For their part, the CentOS developers have tried to address that concern. Karanbir stated directly that there is no plan to change how the core distribution is managed: For the most part, the users in the discussion seemed to accept that promise, but that made them no happier about the version numbering change. The date-based numbers, they say, make it harder to know which version of RHEL a CentOS release is based on, and it can make it harder to justify installations (or upgrades) to management. All told, it was hard to find a single supportive voice for this change outside of the CentOS core developers. Those developers have not said anything about what changes, if any, they might make to their plans in response to the opposition on the list. They are in a bit of a difficult position: they want to make changes aimed at attracting a broader set of users, but those changes appear threatening to their existing users, most of whom are quite happy with the distribution as it is now and are not asking for anything different. If the existing users start to feel that their concerns are not being heard, they may start to look for alternatives. In this case, the powers that be at CentOS may want to make a show of listening to those users and finding a way to resolve their version number concerns that doesn't appear to break the strong connection between RHEL and CentOS releases. Page editor: Jonathan Corbet Security Like all computing platforms that allow users to install arbitrary applications, the Tizen project has expended considerable effort designing its security framework. At the 2014 Tizen Developer Conference (TDC), Casey Schaufler and Tomasz Świerczek presented a talk on the latest iteration of Tizen's application-security design, which introduces a privilege-checking service called Cynara. The fundamental problem that Tizen faces in application security, Schaufler said, is that privileges are specified (in documents like the W3C APIs that Tizen supports for app development) with respect to abstract services, such as "telephony," rather than with respect to system components, such as network devices. All security policies attempt to bridge this gap by writing set of rules and exceptions that map the abstracts onto specific devices and filesystem locations. In Tizen 2.x, he explained, the system's security policy was written as a set of Smack rules that attempted to isolate individual applications from each other by creating a separate Smack domain for each installed application. Each app package includes a manifest file detailing the files and directories it creates, and the API privileges it requests. At install time, the system's package manager would read the manifest, create a domain for the new app, and assign a Smack label for that domain to each file and directory installed. It would also compute the new Smack rules that correspond to the new app's combination of privileges and its Smack domain, and add those rules to the system Smack policy. The problem is that this level of granularity resulted in a huge policy database that was difficult to maintain. "It was almost as big as an SELinux policy," Schaufler said; "I had to go apologize to people at the Security Summit." The upcoming Tizen 3.0 changes things dramatically, however—starting with a simplified, three-domain policy model, which puts all installed apps at one basic privilege level, the "User" domain. It also defines a "Floor" domain for static system data that will not change and a "System" domain for basic system services. This model defines a well-known set of Smack rules (such as allowing all processes to access /tmp and /dev/null) that do not need to be appended to for every installed app. The Tizen security team decided to revisit how the app privilege framework was implemented as well, so it held a "policy-off" face-to-face meeting at which representatives from Intel and Samsung offices each presented their ideas. When the two offices presented essentially the same design, they decided to move forward with it. The centerpiece of the new plan is a policy "service" called Cynara. Each installed app is still assigned its own unique Smack label (to protect its private files and directories), but rather than creating a new set of Smack rules and exceptions for each privilege an app requests, Cynara creates a shorter record of the label and its privileges. The complicated mapping between the set of available privileges and the system's resources is created beforehand and is implemented in the Smack rule set, but does not grow for every new app. When a running app requests access to a system component (for example, the current geolocation reading), the component sends a cynara_check() query to Cynara, including the app's Smack label, the user ID that the app is running as, and the name of the privilege the app is requesting. The Cynara service returns either ALLOW or DENY, based on whether the policy database indicates that the combination of Smack label and privilege are allowed. Other return values are also supported, the speakers said, such as "Ask the user," but the essence is that a straightforward yes-or-no question is answered. Thus, the Cynara API is quite simple, but the real benefits come by maintaining the simpler database of allowed privileges. In performance testing, Świerczek said, the average response time was under 10ms, as opposed to more than 30ms for some of the alternative solutions they explored—such as PolKit. He also noted that PolKit performance suffers due to some design decisions, such as its use of D-Bus for communication and its use of JSON and XML to store the policy database. That database format meant that the entire policy had to be read and parsed for every call; Cynara, in contrast, stores its database in SQLite. The two then described the current state of Cynara development and outlined a rough roadmap. The core privilege-checking library is operational, they said, but is not yet working as a full-fledged service. That milestone would likely be reached by the end of June, as would the utilities for updating the policy database. The essential tools necessary for deployment should be in place by the end of July, after which the team would work on adding an asynchronous privilege-checking API and a mechanism for adding extensions to the system's security policy. There were several questions from the audience, many of which concerned how Tizen uses Smack labels. For example, one audience member asked whether there was a possibility that two apps could accidentally or maliciously get assigned the same Smack labels when installed—which would cause several security problems. Schaufler explained that apps do not choose or assign their own Smack labels; the package manager does. In the Tizen 2.2 release, the Smack label is created from the app's cryptographic signature, so it is guaranteed to be unique (barring collisions, of course). Perhaps the most difficult aspect of the system to grasp in a 40-minute conference talk is how the Cynara approach to storing security privileges compares in real-world terms to the older Tizen approach of storing a longer, more convoluted set of Smack rules. Unfortunately, time makes it difficult to compare the approaches in detail, but the real-world test will have to wait for the deployment of actual apps—some of which, no doubt, will test the security framework in ways its creators have not yet contemplated. Cynara, however, promises a simpler way to keep track of privileges and access-control rules, so hopefully it will also make it simpler to catch—and fix—problems. [The author would like to thank the Tizen Association for travel assistance to attend TDC 2014.] Brief items New vulnerabilities Page editor: Jake Edge Kernel development Brief items The 3.16 merge window remains open as of this writing; see the separate summary below for details of what has been merged. Linus noted that, while overlapping the 3.16 merge window with the final 3.15 stabilization worked well enough, he is not necessarily inclined to do it every." Stable updates: 3.14.6, 3.10.42, and 3.4.92 were released on June 7, followed by 3.14.7, 3.10.43, and 3.4.93 on June 11. So perhaps we should be using robust software engineering processes rather than academic peer review as the model for our code review process? If you (vendors [...]) do not want to play (and be explicit and expose how your hardware functions) then you simply will not get power efficient scheduling full stop. There's no rocks to hide under, no magic veils to hide behind. You tell _in_public_ or you get nothing. Kernel development news This is the second installment of our coverage of the 3.16 merge window. See last week's article for a rundown of what happened in the first few days of the window. Since then, Linus Torvalds has returned to the master branch of his repository after merging back 6800 or so non-merge commits from his next branch. At this point, he has merged 8179 patches for 3.16, which is 2831 since last week's article. Here are some of the larger changes visible to users: Kernel developers will see the following changes: We should be most of the way through the merge window at this point, but there may still be merges of interest in the next few days. Stay tuned for next week's thrilling conclusion ... BFQ, which has been developed and used out of tree for some years, is, in many ways, modeled after the "completely fair queuing" (CFQ) I/O scheduler currently found in the mainline kernel. CFQ separates each process's I/O requests into a separate queue, then rotates through the queues trying to divide the available bandwidth as fairly as it can. CFQ does a reasonably good job and is normally the I/O scheduler of choice for rotating drives, but it is not without its problems. The code has gotten more complex over the years as attempts have been made to improve its performance, but, despite the added heuristics, it can still create I/O latencies that are longer than desired. The BFQ I/O scheduler also maintains per-process queues of I/O requests, but it does away with the round-robin approach used by CFQ. Instead, it assigns an "I/O budget" to each process. This budget is expressed as the number of sectors that the process is allowed to transfer when it is next scheduled for access to the drive. The calculation of the budget is complicated (more on this below), but, in the end, it is based on each process's "I/O weight" and observations of the process's past behavior. The I/O weight functions like a priority value; it is set by the administrator (or by default) and is normally constant. Processes with the same weight should all get the same allocation of I/O bandwidth. Different processes may get different budgets, but BFQ tries to preserve fairness overall, so a process getting a smaller budget now will get another turn at the drive sooner than a process that was given a large budget. When it comes time to figure out whose requests should be serviced, BFQ examines the assigned budgets and, to simplify a bit, it chooses the process whose I/O budget would, on an otherwise idle disk, be exhausted first. So processes with small I/O budgets tend not to wait as long as those with large budgets. Once a process is selected, it has exclusive access to the storage device until it has transferred its budgeted number of sectors, with a couple of exceptions. Those are: There is still the question of how each process's budget is assigned. In its simplest form, the algorithm is this: each process's budget is set to the number of sectors it transferred the last time it was scheduled, subject to a systemwide maximum. So processes that tend to do small transfers then stop for a while will get small budgets, while I/O-intensive processes will get larger budgets. The processes with the smaller budgets, which often tend to be more sensitive to latency, will be scheduled more often, leading to a more responsive system. The processes doing a lot of I/O may wait a bit longer, but they will get an extended time slice with the storage device, allowing the transfer of a large amount of data and, hopefully, good throughput. Some experience with BFQ has evidently shown that the above-described algorithm can yield good results, but that there is room for improvement in a number of areas. The current posting of the code has, in response, added a set of heuristics intended to push the behavior of the system in the desired direction. These include: The list of heuristics is longer than this, but one should get the idea: tuning the I/O patterns of a system to optimize for a wide range of workloads is a complex task. From the results posted by BFQ developer Paolo Valente, it seems that a fair amount of success has been achieved. The task of getting this code into the mainline may be just a little bit harder, though. If BFQ does have a slow path into the mainline, it will not be because the kernel developers dislike it; indeed, almost all of the comments have been quite positive. The results speak for themselves, but there was also a lot of happiness about how the scheduler has been studied and all of the heuristics have been extensively described and tested. The CFQ I/O scheduler also contains a lot of heuristics, but few people understand what they are or how they work. BFQ appears to be a cleaner and much better documented alternative. What the kernel developers do not want to see, though, is the merging of another complex I/O scheduler that tries to fill the same niche as CFQ. Instead, they would like to see a set of patches that evolves CFQ into BFQ, leaving the kernel with a single, improved I/O scheduler. As Tejun Heo put it: Changing CFQ in an evolutionary way would also help when the inevitable performance regressions turn up. Finding the source of regressions in BFQ could be challenging; bisecting a series of changes to CFQ would, instead, point directly to the offending change. The BFQ scheduler has been around for a while, and has seen a fair amount of use. Distributions like Sabayon and OpenMandriva ship it, as does CyanogenMod. It seems to be a well-proven technology. All that's needed is some time put into packaging it properly for inclusion into the mainline. Once that has been done, more extensive performance testing can be done. After any issues found there are resolved, this scheduler could replace CFQ (or, more properly, become the future CFQ) in the kernel relatively quickly. (See this paper [PDF] for a lot more information on how BFQ works). At its core, the control group subsystem is simply a way of organizing processes into hierarchies; controllers can then be applied to the hierarchies to enforce policies on the processes contained therein. From the beginning, control groups have allowed the creation of multiple hierarchies, each of which can contain a different mix of processes. So one could, for example, create one hierarchy and attach the CPU scheduler controller to it. Another hierarchy could be created for the memory controller; it could contain the same processes, but with a different organization. That would allow memory usage policy to be applied to different groupings of the same processes. This flexibility has a certain appeal, but it has its costs. It can be expensive for the kernel to keep track of all the controllers that apply to a given process. Controllers also cannot effectively cooperate with each other, since they may be operating on entirely different hierarchies. In some cases (memory and block I/O bandwidth control, for example), better cooperation is needed to effectively control resource use. And, in the end, there has been little real-world use of this feature. So the plan has long been to get rid of the multiple-hierarchy feature, though it has always been known that this change would take a long time to effect fully. Work on the unified control group hierarchy has been underway for some time, with much of the preparatory work being merged into the 3.14 and 3.15 kernels. In 3.16, this feature will be available, but only to users who ask for it explicitly. To use the unified hierarchy, the new control group virtual filesystem should be mounted with a command like: mount -t cgroup -o __DEVEL__sane_behavior cgroup <mount-point> Obviously, the __DEVEL__sane_behavior option is not intended to be a permanent fixture. It may still be some time, though, before the unified hierarchy becomes available as a default feature. It is worth noting that the older, multiple-hierarchy mode continues to work even if the unified hierarchy mode is used; it will be kept around for as long as it seems to be needed. The unified hierarchy can be instantiated alongside older hierarchies, but controllers cannot be shared between the unified hierarchy and any others. The care that has been taken in this area should allow users to experiment with the unified mode while avoiding changes that would break existing systems. In current kernels, controllers are attached to control groups by specifying options to the mount command that creates the hierarchy. In the unified hierarchy world, instead, all controllers are attached to the root of the hierarchy. (Strictly speaking that's not quite true; controllers attached to old-style hierarchies will not be available in the unified hierarchy, but that's a detail that can be ignored for now). Controllers can be enabled for specific subtrees of the hierarchy, subject to a small set of rules. For the purposes of illustrating these rules, imagine a control group hierarchy like the one shown on the right; groups A and B live directly under the root control group, while C and D are children of B. Each control group in the hierarchy has (in its associated control directory) a file called cgroup.controllers that lists the controllers that can be enabled for children of that group. Another file, cgroup.subtree_control, lists the controllers that are actually enabled; writing to that file can turn controllers on or off. It is worth repeating that these files manage the controllers attached to the children of the group; in the unified hierarchy, a control group is thought of as delegating its resources to subgroups for management. There are some interesting implications resulting from this design. One of those is that a control group must apply a controller to all of its children or none. If the memory controller is enabled in B's cgroup.subtree_control file, it will apply to both C and D; there is no way (from B's point of view) to apply the controller to only one of those subgroups. Further, a controller can only be enabled in a specific control group if it is enabled in that group's parent; a controller cannot be enabled in group C unless it is already enabled in group B. That suggests that all controllers that are actually meant to be used must be enabled in the root control group, at which point they will apply to the entire hierarchy. It is, however, possible to disable a controller at a lower level. So, if the CPU controller is enabled in the root, it can be disabled in group A, exempting all of A's descendant groups from CPU control. Another new rule is that the cgroup.subtree_control file can only be used to change the set of active controllers if the associated group contains no processes. So, for example, if group B has controllers enabled in its cgroup.subtree_control file, it cannot contain any processes; those processes must all be placed into group C or D. This rule prevents situations where processes in the parent control group are competing with those in the child groups — situations that current controllers handle inconsistently and, often, badly. The one exception to the "no processes" rule is the root control group. One other control file found in the unified hierarchy is called cgroup.populated; reading it will return a nonzero value if there are any processes in the group (or its descendants). By using poll() on this file, a process can be notified if a control group becomes completely empty; the process would presumably respond by cleaning up and removing the group. Current kernels, instead, create a helper process to provide the notification; this technique has been frowned on for years. The unified hierarchy will allow a privileged process to delegate access to control group functionality by changing the owner of the associated control files. But this delegation only works to an extent: a unprivileged process with access to the control files can create child control groups and move processes between groups, but it cannot change any controller settings. This policy is there partly to keep unprivileged processes from disrupting the system, but the intent is also to restrict access to the more advanced control knobs. These knobs are currently deemed to expose too much information about the kernel's internals, so there is a desire to avoid having applications depend on them. All of this work has been extensively discussed for years, with most of the major users of control groups having had their say. So it should be suitable for most of the known uses today, but that is no substitute for actually seeing things work. The 3.16 kernel will provide an opportunity for interested users to try out the new mode and find out which problems remain; actual migration by users to the new scheme cannot be expected to happen for a few more development cycles at the earliest, though. But, at some point, the control group rework will cease being something that's mostly talked about and become just another big job that eventually got done. Patches and updates Kernel trees Architecture-specific Core kernel code Development tools Device drivers Filesystems and block I/O Memory management Networking Security-related Miscellaneous Page editor: Jonathan Corbet Distributions Having a bunch of people with laptops and smartphones in fairly close proximity (e.g. a user group meeting or family reunion) would seem like an opportunity to share data among them, but that generally is not quite as simple as it ought to be. Without a WiFi access point of some kind, the devices probably won't even talk to each other—besides which, without a server, there's no easy way to actually share the data. An access point connected to the internet might solve both problems, but introduces others—a lack of privacy and anonymity to start with. An access point that can also act as a server, but is not connected to the internet, takes care of those problems—so that's exactly what the PirateBox project has set out to create. The project is not making hardware and, due to the existence of the OpenWrt project, it doesn't actually have to write much software. But pulling together those pieces and adding some tweaks for ease-of-installation and configuration of the services leads to a simple way to get a WiFi mini-server up and running quickly—and cheaply. All that's needed is one of three TP-Link wireless router models and a USB flash drive—all of which can be had for $35 or less. Installing PirateBox is quite straightforward. I tried it on the TP-Link MR3040, which went smoothly. The process is easy to follow, requiring an install_piratebox.zip file and the appropriate squashfs filesystem for the device. Once it is powered up, connecting to the device over ethernet and logging into the administrative interface (which was on 192.168.1.1 for the MR3040, contrary to the PirateBox instructions) allows you to upgrade the firmware using the squashfs image. Once that completes, you can log into the new PirateBox using telnet, set the password (which will enable sshd), and continue on from there. That new installation procedure is one of the headline features for the PirateBox 1.0 release that was made at the end of May. In addition, the "distribution" now includes a Universal Plug and Play (UPnP) media server and a "4chan-style" image and message board. Beyond that, the in-browser chat and file-sharing functionality is still present from earlier versions. All of that comes in a portable, battery-driven package that allows sharing and collaboration in a remote location for up to five hours. There are a few manual steps required to finish the installation, but that is mostly just customization (passwords, UPnP display name, and so forth). The PirateBox is a working OpenWrt installation, so additional customization via new packages is also possible. Ebook library servers, wikis, OpenStreetMap servers, and so on, are all possibilities. It's only a question of what kind of data you want the PirateBox to share. On the MR3040, which is meant to be used with a USB cellular modem, the flash drive that provides the storage for the server occupies the USB interface, which means that the device can't provide its usual service of routing traffic to the internet. That is clearly by design, as the PirateBox is meant to enable anonymity. Users simply connect to the "PirateBox - Share Freely" SSID and open a browser, which will be redirected to the main server page (seen at right). There are no logins or passwords and any names associated with chats or message board postings are completely up to the user. The PirateBox does not log any user information, either. Because it is not connected to the internet, there is no easy way for information to leak, even if personally identifiable information is entered. Many kinds of files can be stored and retrieved from the PirateBox using a variety of mechanisms. The UPnP server allows streaming media (video and audio) directly to devices, either dedicated playback devices or smartphones and computers running UPnP clients. I tried both MediaHouse UPnP/DLNA Browser and Slick UPnP on my Android phone, which seemed to work just fine. Smartphone browsers can connect to the PirateBox too, of course. But perhaps the most interesting smartphone initiative is the PirateBox app for Android. It turns an Android phone into a PirateBox, though without the UPnP server. It is a perfect way to repurpose an old SIM-less Android phone that you may have hanging around. Another possibility is the Raspberry Pi(rate)Box, which puts the PirateBox software onto the ubiquitous Raspberry Pi single-board computer. PirateBox has a forum to discuss both developing and using the tool. The PirateBox team consists of creator David Darts, lead developer Matthias Strubel, and a handful of other core developers. Others are encouraged to participate via the Forum, IRC channel, and PirateBox Camp, which will be held July 12-13 in Lille, France. One area that could use some attention is security updates. There seems to be little mention of that at the PirateBox site. It is based on OpenWrt, which has its own set of package update problems. Reinstalling new versions may be the only sensible route to updating packages with security problems. In any case, explaining that and documenting the process would certainly be helpful. Once you start thinking about uses for the PirateBox, more and more ideas seem to spring up. A FAQ entry lists a number of places where it has been used, including by musicians to share their music at gigs, by emergency response workers to publish information and updates, and by conference organizers for conference materials and local comments. The FAQ also describes efforts to use mesh networking between PirateBox systems; an alpha version of that feature is slated for the next release. Overall, it is an interesting and useful tool that is worth a look for your local file sharing needs. Brief items Newsletters and articles of interest Page editor: Rebecca Sobol Development One of the more entertaining aspects of the 2014 Tizen Developer Conference (TDC) was the opportunity to explore applications written for "wearable" devices. These days, the term "wearable" is often code for "smartwatch"—although as Google Glass shows, other classes of hardware device are certainly possible. The first Tizen-based smartwatch to reach the market is Samsung's Gear 2 series, which is supported by a special version of the project's SDK. Between the SDK and the wearable-devices track at the conference, it is now possible to see what device manufacturers have in mind for smartwatch software development. The focus is primarily on tethering to other devices (starting with smartphones and tablets), but there is also a framework in place for standalone apps—a prospect that probably makes executives in the "health tracker" industry break into a cold sweat. The Tizen SDK for Wearable was first released in beta form in March; the most recent update landed on April 22. As with the other Tizen SDKs, the integrated development environment (IDE) is based on Eclipse, bundled with the appropriate Tizen templates, frameworks, emulator targets, and documentation. While the SDK does include support for the APIs defined in the official Tizen Wearable device profile, developing apps for the Gear 2 smartwatch requires an additional step: installing Samsung's Mobile SDK. It includes the component needed for developing the Android side of apps that tether the Gear 2 to a smartphone or tablet. As one would expect, the Tizen SDK is cross-platform, although the only officially supported Linux options are relatively old Ubuntu releases (12.04 and 12.10). The IDE is also a bit picky about Java releases, preferring Oracle's Java 6, and may require some additional tweaking on newer Ubuntu releases. The licensing of the SDK can also present some issues; it is based primarily on Eclipse (as mentioned above), but it also bundles in several proprietary components from Samsung. The complications that result for free-software developers have been raised in the past, so far without much in the way of resolution. The SDK also includes a suite of sample applications to experiment with, either in the built-in device emulator or on a USB-connected smartwatch. Tizen's wearable apps are entirely HTML5—while the other device profiles include native app frameworks, too, the assumption seems to be that resource constraints of smartwatch hardware make HTML5 the only viable option. At this point, the Tizen Wearable profile uses the WebKit-based web runtime engine that shipped with the most recent Tizen release, version 2.2. Interestingly enough, at TDC, there were several sessions devoted to rolling out a new web runtime called Crosswalk, that is based largely on Google's Blink with several additions pulled in from other projects. The Tizen 3.0 release scheduled for later this year will include the shift to Crosswalk; how this will affect the SDK for wearables is not clear. Wearable devices in Tizen support a rather limited subset of the same HTML5 APIs found in the project's mobile device profile. For example, from the W3C Device APIs (a set that encompasses quite a few interfaces), only the Touch Events, DeviceOrientation, Battery Status, and Vibration APIs are supported. Multimedia support includes both audio and video, and, notably, includes media input via getUserMedia (in order to support smartwatch cameras, which some Gear 2models include). In addition, there are a number of Tizen-specific APIs available, covering alarms, filesystem access, time and time-zone information, and multimedia content discovery. The Tizen project has always maintained that original APIs like these are mere placeholders, and will be replaced with W3C-approved APIs when and if applicable standard APIs are developed. What is a bit less clear is whether that same stance applies to some of the Samsung-specific APIs offered on the Gear 2. At the moment there are three such APIs: one covering motion-sensing data (e.g., for pedometer usage), one covering infrared transmitters (to support the Gear 2's IR LED, which is used by several TV remote-control apps), and the Samsung Accessory Protocol (SAP). For practical purposes, SAP is the most noteworthy of the three, since it encapsulates how the Gear 2 watch communicates with a tethered mobile device. The connection between the devices is run over Bluetooth, but, it should be noted, SAP is not a standard Bluetooth profile. On the second day of TDC, a session delivered by Samsung's Piotr Karny and Konrad Lipner explored the basic SAP functionality and the general landscape of Gear 2 app development. In essence, Samsung has defined three distinct classes of wearable app: Linked, Integrated, and Standalone. The Linked and Integrated classes are the two variations of tethered app, designed to work in concert with a smartphone. A Linked app, they explained, is one with a component that runs on the tethered smartphone and a component that runs on the smartwatch, but in which the watch side of the app merely relays information from the phone side. A simple example would be a missed-call or SMS log: the calls and messages go to the phone, but the information is relayed to the watch for convenience's sake—without the watch, the phone continues to function. In an Integrated app, by contrast, the phone and watch sides are both required. Examples include most of the fitness-monitoring apps, which leverage the motion and heart-rate sensors in the watch; without them, the phone app does not function. But Samsung is also supporting Standalone apps, which run only on the watch. In fact, there are several standalone apps available from Samsung itself: a calendar, calculator, even a music player. Naturally, the limited processing power of a smartwatch restricts what can be expected of a standalone app. Karny and Lipner noted that several of the Samsung-specific APIs found in the Gear 2 were created to fill in for pieces missing from the relevant W3C standards. For example, the Gear 2's camera supports autofocus, which can be accessed through the autoFocus() method of the CameraControl object. SAP, they explained, is designed specifically for data connections between tethered apps. It operates over Bluetooth 4.0 Low Energy, and provides a fixed set of services: pop-up style notifications, alarms, calendar events, file transfer, music playback, and "context" management (which covers the device's motion and position sensors). The Gear 2 also introduces its own user interface framework for apps, named the Tizen Advanced UI (or TAU) framework. The speakers explained that it was designed from scratch to fit the specific needs of smartwatch apps, most notably fast start-up time and usability on the significantly smaller screen size of a watch. On a desktop system, they said, users will forgive a three-second startup time, but on a watch, that same amount of time becomes unbearable. TAU attempts to optimize startup performance by pre-building as many HTML widgets as possible when the app is built in the IDE; the result is a larger HTML5 app package (and one filled with auto-generated <id> and <div> elements), but it starts up much faster than a smartphone app that builds the UI at launch time. They also commented that although TAU was designed initially for small, low-resolution displays on smartwatches, it will be usable on other device profiles, too, including the company's forthcoming line of Tizen-powered TVs. The Gear 2 is, ultimately, a Samsung product, and one should be careful not to generalize too much about Tizen's wearable device profile from it. For instance, other device makers may opt to skip SAP entirely and offer a more general-purpose Bluetooth API. Nevertheless, the Gear 2 is a real-world product already in the hands (or, if one prefers, on the wrists) of consumers all over the world. As such, it is interesting to note how the three classes of app break down. Is the fact that most fitness apps require tethering to a smartphone, for example, simply an artifact of the app vendors' desire to have a presence on every device a person owns? Samsung offers a standalone music-player app for the Gear 2, and recording pedometer and heart-rate data is certainly less intensive than audio playback. Once the smartwatch app marketplace breaks open in a big way, vendors that insist on requiring both devices to be present and running may find themselves at a competitive disadvantage. It is also interesting to note what ideas the smartwatch app developers have come up with so far. Most duplicate functionality already found in smartphone apps (which is not surprising), offering the slight increase in convenience of finding the information on one's wristwatch rather than in one's pocket. On the other hand, there is already a wealth of fitness-related apps that leverage the built-in sensors of a wearable device. If smartwatch prices fall to reasonable levels, that would seem to put the squeeze on vendors who sell standalone fitness trackers like the Fitbit, most of which already require tethering to a phone or connecting to a computer with USB. Fundamentally, of course, the smartwatch is just another generic computing device: here at the beginning stages of its popularity there is a lot of differentiation to be found versus smartphones and other platforms, but surely one day there will be terminal emulators and web servers available for installation as well. Tizen for Wearable, at least, is a nice on-ramp to development for that platform. [The author would like to thank the Tizen Association for travel assistance to attend TDC 2014.] Brief items. How about just signing keys with people you would actually say you know well enough to trust? It's not the Web of Amateur ID Checking. Version 3.0 of the GNU Nettle cryptographic library has been released. This is a major update, incorporating several interface changes that break ABI compatibility with older releases. New interfaces are provided for DSA, AES, and Camellia, providing access to several new parameters and structures. All users are encouraged to study the new release carefully, as ." Full Story (comments: none) Pump.io and StatusNet creator Evan Prodromou writes about the future of pump.io development. Since Prodromou is no longer working full-time on pump.io, the pace of development has slowed, but he has recently been working on reducing the administrative overhead needed for the public pump.io servers, which will ultimately leave more time for coding. "Over the next week, I'm going to take the current state of pump.io and release it as version 0.3 and start the 0.4 development, he says. "In the same time, I'm going to deal with the long list of pull requests and open issues with pump.io. The PRs will either get a reply, get pulled to 0.4, or closed." A 0.4 release could arrive as soon as September. Newsletters and articles Libre Graphics World has an interview with Alexandre Gauthier (the developer behind the open-source video compositor Natron) as well as an overview of the most recent release. Gauthier addresses the at times controversial decision to build an interface similar to that of proprietary applications that also support the OpenFX plugin standard: "when you implement an application which will be used by professionals who potentially have a lot of background in the usage of such software, you want to make sure you don't break all their habits, otherwise they won't bother. When you have an entire keyboard layout in mind and you need to switch to another, this is a lot of pain. When you have to spend afternoons just to find how to configure the same plug-in but on another application this can be very frustrating." Among other topics, the interview also delves into the complex history behind Natron and other OpenFX applications. Page editor: Nathan Willis Announcements Brief items Full Story (comments: none) Articles of interest Calls for Presentations
https://lwn.net/Articles/601379/bigpage
CC-MAIN-2017-30
refinedweb
8,886
57.81
On Mon, Apr 4, 2016 at 7:14 PM, Peter Maydell <address@hidden> wrote: > On 4 April 2016 at 14:39, <address@hidden> wrote: >> From: Vijay <address@hidden> >> >> Set target page size to minimum 4K for aarch64. >> This helps to reduce live migration downtime significantly. >> >> Signed-off-by: Vijaya Kumar K <address@hidden> >> --- >> target-arm/cpu.h | 7 +++++++ >> 1 file changed, 7 insertions(+) >> >> diff --git a/target-arm/cpu.h b/target-arm/cpu.h >> index 066ff67..2e4b48f 100644 >> --- a/target-arm/cpu.h >> +++ b/target-arm/cpu.h >> @@ -1562,11 +1562,18 @@ bool write_cpustate_to_list(ARMCPU *cpu); >> #if defined(CONFIG_USER_ONLY) >> #define TARGET_PAGE_BITS 12 >> #else >> +/* >> + * Aarch64 support minimum 4K page size >> + */ >> +#if defined(TARGET_AARCH64) >> +#define TARGET_PAGE_BITS 12 > > I agree that this would definitely improve performance (both for > migration and for emulated guests), but I'm afraid this breaks > running 32-bit ARMv5 and ARMv7M guests with this QEMU binary, > so we can't do this. If we want to allow the minimum page size to > be bigger than 1K for AArch64 CPUs then we need to make it a > runtime settable thing rather than compile-time (which is not > an entirely trivial thing). Do you mean to say that based on -cpu type qemu option choose the page size at runtime? > >> +#else >> /* The ARM MMU allows 1k pages. */ >> /* ??? Linux doesn't actually use these, and they're deprecated in recent >> architecture revisions. Maybe a configure option to disable them. */ >> #define TARGET_PAGE_BITS 10 >> #endif >> +#endif >> >> #if defined(TARGET_AARCH64) >> # define TARGET_PHYS_ADDR_SPACE_BITS 48 > > thanks > -- PMM
https://lists.gnu.org/archive/html/qemu-devel/2016-04/msg00504.html
CC-MAIN-2018-05
refinedweb
251
55.03
I recently started getting really into home automation and splurged on motorized shades from Hunter Douglas as well as an Amazon Echo Dot. The shades came with a nice physical control device called a “Pebble”, a hub, and a repeater. The setup, hardware, and iPhone app worked really well, but sadly no thanks to hunterdgoulas.com, which is my vote for “most confusing website” of the month. I may be overthinking their user interface, but the word escheresque comes to mind. After everything was setup, I was giddy to hook the shades up with Alexa, only to find out that I couldn’t. Serena from Hunter Douglas customer service correctly informed me that: As of right now the PowerView shades can work with Alexa it would just be done directly through IFITT. There is not a direct connection. As I didn’t want to deal with the sometimes 10 second lag times of IFTTT, my internal response to Serena’s message was: Challenge Accepted! My network, my control!. How hard could it be? (spoiler alert: harder than I thought). Quick initial research: Alexa has no access to my local network After some quick googling, I found out that the shade hub has a REST API and, at least, get a response and a list of rooms and settings. My initial thinking: Alexa is connected to my local network, the shade hub is connected to my local network: Perfect! All I need to do is create a small script to have them talk to each other. That was a dead end. Alexa does not have access to the local network, instead all of her commands need to be sent through the web. So here’s a here’s a list of the pieces I needed. Necessary pieces to Control Hunter Douglas shades through custom Alexa command To create your own Alexa skill, I had to put together the following parts: - A Hunter Douglas PowerView Hub: Hunter Douglas - A web application with a secure REST endpoint: Flask (A Python Microframework) - A local server that allows external connections: Raspberry Pi - AWS Console Access at AWS Management Console - A custom Alexa skill: Different Types of Alexa Skills - Amazon Developer Account at Amazon Developer Services - A Lambda function for a serverless response to your Alexa skill Find your local shade hub’s networking subnet If you don’t already know the subnet of your Hunter Douglas hub (and chances are, you won’t), it’s time to scan your local network for available subnets. A handy tool is nmap, which you can install easy using Homebrew: brew install nmap. For my own case, I knew that I was looking for a subnet in the default range of my router, so I was scanning 192.168.1.*. nmap will list out all the IP addresses that are listening, so you’ll get a list of subnets. Then, you can use send requests to each IP address with any tool, my go-to is Postman. If you send a simple GET request, you’ll get a response if anything is listening. Inspect the response headers and you will find your way to the IP address of your Hunter Douglas hub. Interact with your local Hunter Douglas hub REST API I found most of the information about this from this forum post that describes the endpoints of the Hunter Douglas hub. None of them are official or documented, but they’re still easy to work with. Pretty much everything happens through the /api/scenes endpoint. A GET request to this endpoint will give you all the scenes you have created (scenes is what Hunter Douglas uses for window positions per shade). A request to /api/scenes?sceneid=123456 will move a shade to the according position. Transform all scenes into your own mapping of scenes and rooms Since the data we get from the list of scenes is completely unorganized and uses IDs for rooms and shade positions, there’s no way around trying out every single scene and writing down the id. You can create your own JSON payloads, which we will later use in our Flask application. Here’s an abbreviated version: # Room definition. rooms = { "bedroom": 9999, "livingroom": 3333, } # Scene definition. scenes = { "bedroom": { "halfopen": { "id": 24341, "roomId": 9999, }, "closed": { "id":346345, "roomId": 9999, } }, "livingroom": { "closed": { "id": 12323, "roomId": 3333, } } } No way to interact with Hunter Douglas REST API through the web (Jumping ahead a bit:) If there already is a Hunter Douglas REST endpoint available, why don’t we just use it instead of creating our own web server? Obviously, because it would be way less fun (insert canned laughter here). But also, because there is no official documentation on how to interact with your local hub through the web and no developer SDK available to do that. There is, of course, a way for Hunter Douglas to do that already because their mobile app is talking to my hub. Instead, let’s create our own web server, with a custom API endpoint that we fully control. Setup your own web server on a Raspberry Pi and create a Flask application with a simple, secure API I didn’t have a running server at home, and wanted to find a cheap solution, so a Raspberry Pi for $35 on Amazon is a great option to run your own server. I won’t go too much into the details of setting up your Pi, but instead focus on the server and application. For the application, I picked Flask for its speed and ease of setup. It’s written in Python. I decided to use a simple, encrypted key in the header to authenticate the requests using itsdangerous. The endpoint follows the format /blinds/<room>/<scene> with the name of the room and scene based on our own dictionary. from flask import Flask, url_for, request, abort import requests, json from itsdangerous import URLSafeSerializer app = Flask(__name__) # Constant definition. secret_key = 'yoursecretkey' header_pass = 'yourpassword' # Internal IP address for Hunter Douglas hub. ip = "192.168.1.10" endpoint = "http://" + ip print("Hunter Douglas endpoint is {}".format(endpoint)) # Room definition. rooms = { "bedroom": 9999, "livingroom": 3333, } # Scene definition. scenes = { "bedroom": { "halfopen": { "id": 24341, "roomId": 9999, }, "closed": { "id":346345, "roomId": 9999, } }, "livingroom": { "closed": { "id": 12323, "roomId": 3333, } } } # Find scene for a room and a scene. def find_scene_data(room, scene): return scenes[room][scene] # Move a shade. def move_shade(id): scene_endpoint = endpoint + "/api/scenes?sceneid=" + str(id) r = requests.get(scene_endpoint) data = json.loads(r.text) if (len(data['scene']['shadeIds']) > 0): return True else: return False def authenticate_request(hash): try: s = URLSafeSerializer(secret_key) decrypted = s.loads(hash) if (decrypted == header_pass): return True else: return False except: print('Hash not valid.') return False def verify_trusted_source(): if not authenticate_request(request.headers.get('Auth-Key')): abort(403) @app.route('/blinds/<room>/<scene>') def blinds(room, scene): verify_trusted_source() try: scene_data = find_scene_data(room, scene) except KeyError: return "Scene was not found in this room." success = move_shade(scene_data['id']) print(success) return "Moving the blind {} in the {}. using this data: {}".format(scene, room, scene_data) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0') Problems with this application: too many hardcoded values There are two issues with the application as it is. First, the local IP address of the Hunter Douglas hub is hardcoded. Unfortunately, restarting your router may result in a different IP address for the hub, which requires this code to be adjusted. Secondly, the scene data is hardcoded. This is no problem if you have already defined all the scenes via the Hunter Douglas mobile app. But if you change your scenes after the fact, you need to update your scenes/rooms dictionary with the new IDs. Running your application in debug mode and production mode To test the application, we can use the pre-installed version of Python 3 on our Raspberry Pi using a simple command (assuming you saved the whole application in a file called app.py): sudo python3 app.py This works great for debugging any issues with the application, but we need to setup an actual web server that proxies the requests to our Python application. For that, I’m setting up an NGINX server with uWGSI. The setup is relatively straightforward. You can just follow this tutorial: Python Flask Web Application on Raspberry Pi with NGINX and uWSGI. The service describes how to launch uWSGI on boot, but in some cases, you might have to manually make a change and restart your uWSGI server, which you can do with this command: /usr/local/bin/uwsgi --ini /home/pi/code/hdapp/uwsgi_config.ini --uid www-data --gid www-data --daemonize /var/log/uwsgi.log Modify router NAT rules to forward external traffic to Raspberry Pi We now have a running web server on our Raspberry Pi, but until now we can’t actually connect to it from the outside world. In order for that to change, we need create a rule on our router that forwards traffic from a specific port to our web server on the Raspberry Pi. This doesn’t come without security implications, so if you open up your home network to the web, make sure you know what that means. Here’s an example for a TP-Link router, which I may or may not own: TP-Link Router Port Forwarding | Support | No-IP. Basically, you’re going expose a specific port on your router, and forward the traffic to an internal IP address and port. Then, if you’re lucky and have a static public IP address associated with your network, you can use that public IP address and port. Here’s an example: Your network’s public static IP address is 84.14.11.100. You expose the port 5200 and forward it to the local IP address of your NGINX server 192.168.1.100 and the port you’re running your uWSGI server at 3000. This means we can send a request through the web to, and that request will finds its way to our local Raspberry Pi’s Flask application running on uWSGI. This () will be the endpoint we use for our Lambda function. Create the actual Alexa skill In order to setup your own skill, you should login with your Amazon developer account at Amazon Developer Services. For some reason, Alexa doesn’t live within the regular AWS console, but in it’s own developer section. Keeping it interesting, AWS! Once logged in, follow the instructions to create a custom Alexa skill, as defined here: Build Skills with the Alexa Skills Kit – Amazon Apps & Games Developer Portal. For our custom skill, we use 2 variables, or as Amazon calls them: slots. I had challenges using the predefined AMAZON.Room slot for rooms, as it was never able to detect “living room” correctly. Creating your own slots and putting everything together is relatively straightforward using the Interaction Model Builder, which is currently in beta. Invocation Name for your Alexa dev skill: You’re limited to “ask Alexa” Amazon distinguishes between Alexa skills in dev mode, and published Alexa skills. The only account that can use a dev skill is your own, whereas published skills can be used by anyone. However, publishing a skill and getting it through Amazon’s compliance is a whole different ball game which I will skip altogether. There’s one big issue when creating a dev skill, which isn’t quite apparent from the Amazon documentation: The skill seems to be limited to an invocation name that starts with Ask Alexa to do something. So skills such as Alexa, close the blinds, or Alexa, open the blinds won’t work with a dev skill. With this limitation in mind, I ended on this phrase: Ask the window blinds to <position> in the <room>, Not exactly how I would have worded this, but I can deal with it. Final interaction model for window blinds Alexa skill So here’s my current version for the skill. It doesn’t handle errors quite well yet, but works in most cases. { "intents": [ { "name": "AMAZON.CancelIntent", "samples": [] }, { "name": "AMAZON.HelpIntent", "samples": [] }, { "name": "AMAZON.StopIntent", "samples": [] }, { "name": "moveBlinds", "samples": [ "ask the window blinds to {position} in the {room}", "ask the window blinds to {position} in {room}", "ask window blinds to {position} in {room}", "ask window blinds to {position} in the {room}" ], "slots": [ { "name": "position", "type": "position", "samples": [] }, { "name": "room", "type": "room", "samples": [] } ] } ], "types": [ { "name": "position", "values": [ { "id": "closed", "name": { "value": "closed", "synonyms": [ "close" ] } }, { "id": "halfopen", "name": { "value": "half open", "synonyms": [ "half closed", "half way" ] } }, { "id": "freshair", "name": { "value": "fresh air", "synonyms": [] } }, { "id": "open", "name": { "value": "open", "synonyms": [] } } ] }, { "name": "room", "values": [ { "id": "bedroom", "name": { "value": "bedroom", "synonyms": [] } }, { "id": "livingroom", "name": { "value": "living room", "synonyms": [] } } ] } ] } Entity resolution to map different variations of variables to a single identifier An Alexa skill gives us the option to define slots along with synonyms and a single identifier. We could define an identifier as “halfopen”, but a user might call this “half open” or “half closed”. For our custom Raspberry PI endpoint, we need that single identifier instead of the variations. The Alexa skill will provide us with that data and we can parse it in our Lambda function. The big caveat here is that the skill simulator will allow us to test the skill, but it won’t provide us with the entity resolution data. So when we look at our CloudWatch logs to see what data was sent, we will see different data than when we try the skill on an actual Alexa device. A good testing tool is Alexa Skill Testing Tool – Echosim.io, which allows us to use our laptop to create a virtual Alexa device. In here, we should see the exact same results as when using a physical Alexa device. AWS Lambda function that will serve as the “serverless” endpoint for the Alexa skill The recommended solution for an Alexa skill endpoint is to use a Lambda function. AWS Lambda allows you to run code in a server environment that you pay for by the millisecond. Instead of spinning up a server, you just define the code and then run it in a micro-environment provided by AWS that just exists for several seconds. The Lambda function represents the glue between the Alexa skill and our Raspberry Pi server. It will parse the event that it gets sent from the Alexa skill and forward the request to the Raspberry Pi endpoint. The URL and key are defined as Lambda environment variables so we don’t have to hardcode them in the code. Lambda Function Lambda functions can be written in Java, Node, and Python. Since the rest of our application is already written in Python, I decided to stick with a single language for all applications. Here’s the function: import os from datetime import datetime import urllib.request # URL and user agent, stored in Lambda environment variables. URL = os.environ['url'] USER_AGENT = os.environ['user_agent'] AUTH_KEY = os.environ['auth_key'] # Define default error response. default_error = { 'version': '1.0', 'response': { 'outputSpeech': { 'type': 'PlainText', 'text': 'What you said made no sense to me.', } } } # Define default success message. default_success = { 'version': '1.0', 'response': { 'outputSpeech': { 'type': 'PlainText', 'text': 'You just moved your blinds. Congratulations!', } } } # Determine the target values for the slots. def get_target_values(slots): target_values = {} expected_keys = ['position', 'room'] for key in expected_keys: slot = slots[key] if slot.get("resolutions", {}): # Resolution authorities and resolutions are lists, # but we are just using the first option. if slot['resolutions']['resolutionsPerAuthority'][0]['status']['code'] == "ER_SUCCESS_MATCH": target_values[key] = slot['resolutions']['resolutionsPerAuthority'][0]['values'][0]['value']['id'] else: target_values[key] = slot['value'] return target_values # Lambda handler that will be called during lambda execution. def lambda_handler(event, context): print(event) # Get slot values. slots = event['request']['intent'].get("slots", {}) if not slots: return default_error # Get target values for slots. target_values = get_target_values(slots) target_url = URL + target_values['room'] + '/' + target_values['position'] print(target_url) try: req = urllib.request.Request(target_url,data=None,headers={ 'Auth-Key': AUTH_KEY }) res = urllib.request.urlopen(req) if (res.status != 200): raise Exception('Call failed') except: print('Connection failed!') raise else: print('Connection succeeded!') return default_success finally: print('Completed at {}'.format(str(datetime.now()))) Final thoughts This was a fun mini-project that increased my appetite for creating new, custom Alexa skills. Now that most of the heavy lifting is done (setting up the uWSGI server, exposing it to the web, securing the endpoint, figuring out what’s possible for Alexa dev skills), creating the next custom skill should be much faster. Maybe some sort of integration with Amazon Rekognition – Deep learning-based image analysis.
https://www.danielhanold.com/2017/10/alexa-skill-control-motorized-window-shades-flask-raspberry-pi-aws-lambda/
CC-MAIN-2020-29
refinedweb
2,761
62.58
Originally posted by fengqiao cao: hi, there I found that there is not side effect to define main()with private, protect, or default. is it ture all the time? The follwing code return the same output if i change the "private" to pulbic or portected. public class THIS{ private static void main(String args[]){ int i=1; System.out.println(i); } } Originally posted by Rashmi Gunjotikar: What i understand from the previous discussion is... private static void main(String[]) is allowed by some JVMs. But JLS says that signature should be ... public static void main(String[]) Then in exam, if the correct signature for main is asked then, what should we select? as even private is allowed by some JVM . then the option, private static void main(String[]) is valid or not? Or we shd strictly follow JLS? thanx in advanc. Rashm.
http://www.coderanch.com/t/234873/java-programmer-SCJP/certification/private-main
CC-MAIN-2014-52
refinedweb
142
68.67
Android to Windows 8: Parse XML data Android to Windows 8: Parse XML data Join the DZone community and get the full member experience.Join For Free It’s more than likely that a Windows Store app will need to work with data that resides on the Internet. For example, an app may aggregate data from various news sources using RSS feeds. Consuming this type of data in a Windows Store app is very similar to consuming it in an Android app. In this post I’ll show you how parse XML data from a feed on StackOverflow. The first thing you’ll need to do is decide on an XML feed you want to use in your app. For this section will use a feed from StackOverflow.com that focuses on Windows 8. The feed is available at. Once you’ve identified the feed you’ll want to analyze it to determine which fields are of interest to your app. Below is a sample abstract form the StackOverflow.com feed we’ll be using: <?xml version="1.0" encoding="utf-8"?> <feed xmlns="" xmlns: <title type="text">active questions tagged windows-8 - Stack Overflow</title> ... <entry> ... </entry> <entry> <id></id> <re:rank0</re:rank> <title type="text">Windows Store XML Data</title> <category scheme="" term="c#"/> <category scheme="" term="xml"/> <category scheme="" term="windows-8"/> <category scheme="" term="windows-runtime"/> <author> <name>anonymous</name> <uri></uri> </author> <link rel="alternate" href="" /> <published>1900-01-01T00:00:00Z</published> <updated>1900-01-01T00:00:00Z</updated> <summary type="html"> <p>How do I use XML in Windows Store apps?</p> </summary> </entry> <entry> ... </entry> ... </feed> For the example, we’ll focus on the title, link,and summary elements. The first step is to create a class that represents the data you want to work with in your app. Since we’re focusing on the title, link, and summary elements of the feed, the class will look like the following: public class FeedEntry { public string Title { get; set; } public string Link { get; set; } public string Summary { get; set; } } The next step is to create a class and a method that will be responsible for the parsing. The return type of the method should be a list of FeedEntry objects. A possibility would look like this: public class StackOverflowXmlParser { ... public async Task<List<FeedEntry>> Parse() { ... } ... } Notice that the async modifier has been added to the method and the method is return a Task which has been typed as a list of FeedEntry objects. This allows the method to use the await operator to designate suspension points. The await operator tells the compiler that the async method can’t continue past that point until the awaited asynchronous operation is complete. Additionally, this makes it very easy for calling methods to call the Parse method in an asynchronous manner by simply using the await keyword. The first task in the Parse method will be to instantiate a result set to return to the calling method and check the status of network connectivity using the GetConnectionState method described in the previous section. Because this could be dealing with a large amount of data, we’ll want to make sure that we only try to access the feed if the device is on a non-metered connection: List<FeedEntry> results = new List<FeedEntry>(); //Determine connection state var connectionState = GetConnectionState(); //Proceed if a non-metered connection is detected if (connectionState == ConnectionState.NonMetered) { ... The next thing to do is to determine the method by which the feed will be processed. Because we’re dealing with an XML feed, we have three options in .NET: - The System.Xml namespace - The System.Xml.Linq namespace - The System.ServiceModel.Syndication namespace The System.Xml namespace provides standards-based support for processing XML. It gives you quite a bit of control over how you process XML and allows you to use things like XSD schemas, XPath expressions, and XSLT transformations. It’s a little more power than we need for this particular task. The SyndicationFeed class in the System.ServiceModel.Syndication namespace would actually make our job incredibly simple if we wanted work with all of the fields in the feed. However, since we’re only concerned with three fields we’ll use the System.Xml.Linq namespace. This namespace contains the classes for LINQ (Language INtegrated Query) to XML which serves as an in-memory XML programming interface that enables easy and efficient processing of XML documents. First up when working with LINQ to XML is to create some XName objects that represent the names of the elements we want to work with. These names need to include the local and namespace names. /Atom namespace var atomNamespace = ""; //Create the names of the XML elements including the Atom namespace var entryXName = XName.Get("entry", atomNamespace); var titleXName = XName.Get("title", atomNamespace); var linkXName = XName.Get("link", atomNamespace); var summaryXName = XName.Get("summary", atomNamespace); The next step is to load the XML data into an XElement class asynchronously. To do this, create an HttpWebRequest instance and call its GetResponseAsync() method using the await keyword. The GetResponseStream() of the HttpWebResponse object can then be used in the Load(…) method of the XElement class. //Load the XML data asynchronously var request = HttpWebRequest.CreateHttp(""); var response = await request.GetResponseAsync(); XElement root = XElement.Load(response.GetResponseStream()); Once the XElement object is loaded, we can use LINQ to query for just the entry elements and in the XElement and store them in a list: //Load all "entry" elements from the XML into a list var entries = (from e in root.Elements(entryXName) select e).ToList(); Next we’ll start iterating through the list of entries. The first step in the iteration is to instantiate a new FeedEntry object: //Iterate all "entry" elements foreach (var entry in entries) { //Create a new FeedEntry var feedEntry = new FeedEntry(); ... } Then we’ll assign the value of the FeedEntry’s Title property to the value of the title element: //Get the title var titleElement = (from e in entry.Elements(titleXName) select e).FirstOrDefault(); if (titleElement != null) feedEntry.Title = titleElement.Value; Similarly we’ll assign the value of the Link property to the value of the link element’s href attribute: //Get the link var linkElement = (from e in entry.Elements(linkXName) select e).FirstOrDefault(); if (linkElement != null) { var hrefAttribute = linkElement.Attributes("href").FirstOrDefault(); if (hrefAttribute != null) feedEntry.Link = hrefAttribute.Value; } Next we’ll assign the value of the Summary property to the value of the summary element and add the object to the result set to be returned to the calling method: //Add to the entry to the result set results.Add(feedEntry); The last step is to call the Parse method. Since the Parse method was modified with the async keyword, it can be called asynchronously by using the await operator like so: var parser = new StackOverflowXmlParser(); var entries = await parser.Parse(); //do something with the entries Published at DZone with permission of Adam Grocholski , DZone MVB. See the original article here. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/android-windows-8-parse-xml
CC-MAIN-2019-30
refinedweb
1,190
55.95
Hunting for Objects By The Microsoft Scripting Hunt is On Just Take It WMI is a Good Place to Start Script Center Tools Microsoft Office Other Applications Windows PowerShell Tally-Ho! The Hunt is On One of the questions we get frequently here at the Script Center is something along the lines of this: “Where do I find the objects and methods I need to do what I want to do in my script?” And you know, that’s a great question. Wouldn’t it be nice if we had a great answer for you? Well, we don’t. Instead what we have are a lot of answers, some of them great, some not-so-great. The main problem, which you’ve probably already discovered, is that information on objects and methods is scattered - where you find it depends on the technology you need to use. For example, you’ll find information about Windows Management Instrumentation (WMI) in a different place than you’ll find information about Microsoft Office objects. We know this can be kind of a tough task sometimes, but we’re going to take a shot at helping you out as much as we can. Just Take It We here at the Script Center do not, under any circumstances, encourage, condone, or promote any illegal activities of any kind. We just needed to say that before we tell you that your best bet for finding the classes and properties that will do what you need is to find someone else who’s already found them and then steal their script. Technically it’s not stealing if you find it freely-available on the Internet, but you know what we mean. (Unless you work for certain groups at Microsoft, in which case - we’ll say this once more just for you - the Scripting Guys do not encourage, condone, or promote any sort of theft.) Obviously the best place to start is the Script Center, especially the Script Repository, the Hey, Scripting Guy! archive, the Community-Submitted Scripts Repository, and the Windows 2000 Scripting Guide (still applicable to more recent versions of Windows). But on the off-chance that you don’t find what you need there, just search the Internet, there’s a lot out there if you can find it. Of course, there’s always the possibility that, after all your searching, you’ll still need to find your own solution. For that, you’ll then need some tools to help you out. WMI is a Good Place to Start We tend to work under the assumption that our readers are system administrators. This isn’t the case for everyone, and if you’re not a system administrator don’t worry;, all this will apply to you too. But given that assumption, we’re going to start with some tools that will help you write scripts to manage your Windows systems. In managing Windows you’ll most often work with WMI. There are various tools available for exploring WMI objects, but the one we’re going to focus on first is the Windows Management Instrumentation Tester, more commonly referred to as WbemTest (web-em-test). WbemTest We call this WbemTest rather than WMI Tester for the simple reason that, in order to run this tool, all you need to do is type wbemtest at the command prompt or in the Run box (the Search box in Windows Vista) and WbemTest will run. Here’s what it looks like: WbemTest is a good tool because, like VBScript, WSH, WMI, Notepad, and various other things you can use to write system administration scripts, WbemTest ships with Windows. You don’t need to install anything extra to use it. It is, however, a little intimidating to look at when you first open it up. As you can see, most of the buttons are grayed out. To get started with WbemTest, click the Connect button. That will bring up this dialog box: The main thing to notice here is the Namespace field up at the top. Most of the WMI classes are located in the root\cimv2 namespace. In Windows Vista this field is filled in, by default, with root\cimv2. However, in previous versions of Windows the default namespace is root\default; more often than not, you’ll want to change that to root\cimv2. Click Connect. That will bring you back to the main window, but this time all those disabled buttons are enabled: Click the Enum Classes button. In the Superclass Info dialog box, click the Recursive button, then click OK: This will bring up a dialog box showing the names of all the WMI classes in the root\cimv2 namespace: At this point you’ll mostly want to scroll through the list looking for class names that seem to match what it is you want to do. For most operating system tasks you’ll want to scroll down to the classes that begin with Win32_, as we’ve done here. For example, if we want to find information on the disk drives on a computer, the Win32_DiskDrive class sounds like a good bet. (Not that the Scripting Guys encourage, condone, or promote betting.) Let’s choose that one: double-click on Win32_DiskDrive. Here’s what you should see: Click Hide System Properties to remove some of the clutter. At this point you have a list of all the properties and methods associated with the Win32_DiskDrive class. If, by looking at property and method names, you’re still not sure whether this is the object you’re looking for, you can try clicking the Instances button. That will bring up a dialog box like this: Here we’ve simply queried the local computer for all instances of the Win32_DiskDrive class. As you can see, in our case that returned information on one disk drive. Double-click the drive listed. This will bring up the same window we had previously, the one that showed us all our properties and methods. This time, however, most of the properties have values in them: For example, you can see the BytesPerSector for this disk drive is 512. If that’s the kind of information you were hoping to find, then you obviously chose the right class; if not, it’s back to the drawing board: close this window and go back to the query that listed all the classes and choose another one. Okay, not the easiest way to find what you’re looking for, but sometimes the most successful. Now let’s take a look at another useful tool. More Information To find out more about WbemTest, check out the Scripting Week 1 Webcast WMI Is Not a Four-Letter Word. About 30 minutes in there’s a more in-depth discussion of how to work with WbemTest. For a really thorough explanation and walk-through of WbemTest, see the article Wbem What?. Scriptomatic Scriptomatic is an HTML Application (HTA) you can download from the Script Center that allows you to query for WMI classes and that will build scripts for you in several different scripting languages. Here’s what it looks like: We’re not going to go into a lot of detail about using the Scriptomatic. There’s an entire readme devoted to the Scriptomatic that’s really more a piece of classic literature than a readme file. Okay, not so much classic literature, but it definitely ranks as one of our more entertaining works. But just to give you an idea of what this is all about, the Scriptomatic provides drop-down lists that allow you to select the namespace (no more guessing there) and the WMI class you want to look at. It outputs a script that you can edit right there in the HTA and that you can run (again, right from the HTA, or you can copy and paste it to a script file) to see all the properties and their values on a given computer - local or remote. As you can see, you can also choose from among several scripting languages, and you can choose the format of the output. Again, still a matter of hunting down classes and properties that look right, but the hunt’s at least getting a little more fun, right? Okay, maybe not. WMI Code Creator Okay, one more and we’re done looking at WMI classes. We just want to give a quick mention to the WMI Code Creator, which is also downloadable from the Script Center. It’s a lot like Scriptomatic but it’s a full-blown executable and has a little more functionality. Here’s a glimpse of the WMI Code Creator: Oops, One More Did we say we were done with WMI? Sorry, not just yet. There’s one more place to look for WMI information, and that’s the WMI SDK. SDKs are typically designed for developers and can be a little tough to read for scripters, but we’ve provided a How To article on reading SDKs. Script Center Tools Not to toot our own horn here (we know, too late), but the Script Center has even more freely-downloadable tools that can help you out. Just check out our Scripting Tools and Utilities page to find such inspiring tools as the ADSI Scriptomatic (no, sorry, the ADSI Browser is still not available), Tweakomatic, and HTA Helpomatic. Microsoft Office There are really two places to get information on scripting the Office products (besides that stealing thing we mentioned that isn’t really stealing).One option is to look at the Object Browser in one of the Office products. To do that, you first need to open the Visual Basic Editor. In Office 2003 you do this by selecting Visual Basic Editor under Macro in the Tools menu. In Office 2007 you’ll probably have to do some digging to find this. Once the Visual Basic Editor is open, press F2 to open the Object Browser: Here you’ll get a list of all the classes available to Office products along with their properties and methods (Members). As usual, you’re still trying to find a class name that seems to fit what you want to do, but it’s pretty easy to scroll through and look at everything. Your other option for Office is the Developer Reference. Let’s look at an example: Let’s say you want to change the name of a worksheet within a particular workbook. First you can go to the Excel 2007 Developer Reference; you might even want to just start at the Excel Object Model Reference. From there if you scroll down you’ll eventually find a class named Worksheet. It’s a pretty good bet that if we want to change the name of a worksheet, we’ll need to use a Worksheet object. Under Worksheet you’ll find a property named Name: As you can see (sort of), the Name property “Returns or sets a String value representing the name of the object.” In other words, assign a string value to the Name property to name your worksheet. Pretty simple. Other Applications As with everything else we’ve talked about in this column, finding information on other applications is usually a matter of searching around in the SDK. Unfortunately not everything you find in the SDK will work in a script. Remember, SDKs are typically written for developers, not scripters, so the examples could be a little confusing (they might even be written in C++), and many of the classes aren’t even available to scripts. Oh, but wait…there’s one more thing you can try: Windows PowerShell. Windows PowerShell Now, you might be thinking “Hey, I’m not working with Windows PowerShell, I’m working with [fill in your scripting language of choice here]. Windows PowerShell won’t help me.” (Of course, you might also be thinking “Great, I’m using Windows PowerShell right now.”) Well, guess what? Windows PowerShell can help you whether you’re writing your scripts in Windows PowerShell or not. You can find out all sorts of information about the methods and properties of a class simply by using the Get-Member cmdlet. COM Objects Keep in mind that you still have to go through the sometimes-painful processes we already talked about of hunting down the class you want - Windows PowerShell doesn’t help with that. But once you know the class, PowerShell can tell you all about it. For example, let’s say you want to find out about a regular old COM object like the Wscript.Shell object. Just enter this command in Windows PowerShell: Before we find out about a particular class, we need to create an object reference to that class. That’s why we need to start by using the New-Object cmdlet, a cmdlet that just happens to create an object reference. We pass the -com parameter with a value of wscript.shell to tell the New-Object cmdlet that the object we want to create is a COM object , and that the name of the class is Wscript.Shell. Here’s what PowerShell returns: TypeName: System.__ComObject#{41904400-be18-11d3-a28b-00104bd35090} Name MemberType Definition ---- ---------- ---------- AppActivate Method bool AppActivate (Variant, Variant) CreateShortcut Method IDispatch CreateShortcut (string) Exec Method IWshExec Exec (string) ExpandEnvironmentStrings Method string ExpandEnvironmentStrings (string) LogEvent Method bool LogEvent (Variant, string, string) Popup Method int Popup (string, Variant, Variant, Variant) RegDelete Method void RegDelete (string) RegRead Method Variant RegRead (string) RegWrite Method void RegWrite (string, Variant, Variant) Run Method int Run (string, Variant, Variant) SendKeys Method void SendKeys (string, Variant) Environment ParameterizedProperty IWshEnvironment Environment (Variant) {get} CurrentDirectory Property string CurrentDirectory () {get} {set} SpecialFolders Property IWshCollection SpecialFolders () {get} As you can see, we have a list of all the methods and properties belonging to the Wscript.Shell object, along with the syntax and types of each. Microsoft Office COM Objects We can do the same thing with Office classes, but this gets a little tricky. The reason it gets a little tricky is the point we mentioned already - you need an object reference, not just a class name, in order to get information about the class. As you saw from our VBScript example earlier, it takes several steps to get some of the objects in an Office application. Let’s use our Worksheets object again as an example. You can copy this to a script or you can run each of these lines individually from the PowerShell command line: We first use the New-Object cmdlet to create a reference to the Excel.Application object, storing that object in the variable $a. Next we add a new workbook: Now it’s time to get the object reference to the Worksheet object. We do this by assigning the Item property, with a parameter of 1, of the Worksheets object to the variable $ws. The Item property contains a collection of all the worksheets in a workbook - you reference individual worksheets with the parameter. In this case we’re retrieving a reference to the first (Item 1) worksheet in the collection: Now we simply pipe our Worksheet object reference (stored in the $ws variable) to the Get-Member cmdlet: We then call the Quit method on our Excel application and we’re done. In the meantime, here’s a sampling of what the Get-Member cmdlet has returned: TypeName: System.__ComObject#{000208d8-0000-0000-c000-000000000046} Name MemberType Definition ---- ---------- ---------- Activate Method void Activate () Arcs Method IDispatch Arcs (Variant) Buttons Method IDispatch Buttons (Variant) Calculate Method void Calculate () ChartObjects Method IDispatch ChartObjects (Variant) CheckBoxes Method IDispatch CheckBoxes (Variant) CheckSpelling Method void CheckSpelling (Variant, Variant, Variant, Variant) … Range ParameterizedProperty Range Range (Variant, Variant) {get}} … Maybe that does seem like a lot of work, but remember that we were looking for an object that we needed to spend some time retrieving. If we wanted to retrieve the methods and properties of the Excel.Application object, well, that’s pretty simple: .NET Objects You can also use the Get-Member cmdlet to retrieve information on .NET classes. However, there are various ways of retrieving those objects depending on which class you’re looking at. We’re already pretty far beyond the scope of our typical Sesame Script - retrieving .NET objects is going to have to be a topic for a future Windows PowerShell article. But here’s a very simple example of retrieving properties from a .NET object, in this case the System.Version object: Here we’re once again using the New-Object cmdlet to get a reference to the object. Notice this time, though, that we didn’t use the -com parameter; instead we used the -typename parameter. We then specified the class we want to retrieve a reference to, the System.Version class. Now that we have the object reference we can pipe it to the Get-Member cmdlet, and we have our output: TypeName: System.Version Name MemberType Definition ---- ---------- ---------- Clone Method System.Object Clone() CompareTo Method System.Int32 CompareTo(Object version), System.Int32 CompareTo(Version value) Equals Method System.Boolean Equals(Object obj), System.Boolean Equals(Version obj) GetHashCode Method System.Int32 GetHashCode() GetType Method System.Type GetType() get_Build Method System.Int32 get_Build() get_Major Method System.Int32 get_Major() get_MajorRevision Method System.Int16 get_MajorRevision() get_Minor Method System.Int32 get_Minor() get_MinorRevision Method System.Int16 get_MinorRevision() get_Revision Method System.Int32 get_Revision() ToString Method System.String ToString(), System.String ToString(Int32 fieldCount) Build Property System.Int32 Build {get;} Major Property System.Int32 Major {get;} MajorRevision Property System.Int16 MajorRevision {get;} Minor Property System.Int32 Minor {get;} MinorRevision Property System.Int16 MinorRevision {get;} Revision Property System.Int32 Revision {get;} Tally-Ho! That’s about it for our article on hunting down classes, methods, properties, and so on. No animals were harmed during the making of this article, with the exception of the spider the Scripting Dog just ate. And maybe anyone who happened to hit their head on their desk when they fell asleep reading this article.
http://technet.microsoft.com/library/ee692765.aspx
CC-MAIN-2014-23
refinedweb
3,000
61.26
NAME bus_child_present — ask the bus driver to see if this device is still really present SYNOPSIS #include <sys/param.h> #include <sys/bus.h> #include <machine/bus.h> #include <sys/rman.h> #include <machine/resource.h> int bus_child_present(device_t dev); DESCRIPTION The bus_child_present() function requests that the parent device driver of dev check to see if the hardware represented by dev is still physically accessible at this time. While the notion of accessible varies from bus to bus, generally hardware that is not accessible cannot be accessed via the bus_space*() methods that would otherwise be used to access the device. This does not ask the question “does this device have children?” which can better be answered by device_get_children(9). RETURN VALUES A zero return value indicates that the device is not present in the system. A non-zero return value indicates that the device is present in the system, or that the state of the device cannot be determined. EXAMPLES This is some example code. It only calls stop when the dc(4) device is actually present. device_t dev; dc_softc *sc; sc = device_get_softc(dev); if (bus_child_present(dev)) dc_stop(sc); SEE ALSO device(9), driver(9) AUTHORS This manual page was written by Warner Losh ⟨imp@FreeBSD.org⟩.
http://manpages.ubuntu.com/manpages/precise/man9/bus_child_present.9freebsd.html
CC-MAIN-2016-18
refinedweb
207
57.98
CodePlexProject Hosting for Open Source Software I have an object: public class Foo { [JsonProperty("data")] public Dictionary<string,string> Data {get;set;}� } I need the data to look like this: {"data":{"key1":value1, "key2":value2}} What is the best way to ensure the values of the Dictionary are not in quotes? If you don't want the values in quotes, then you should use the proper type like int. Strings in JSON are quoted. Actually, I figured it out: Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
http://json.codeplex.com/discussions/312412
CC-MAIN-2017-39
refinedweb
115
72.87
After knowing primitive data types and Java rules of Data Type Casting (Type Conversion), let us see the Java style of casting double to short. The double takes 8 bytes of memory and short takes 2 bytes of memory. Assigning 8 bytes of memory to 2 bytes of memory requires explicit casting. Moreover, float takes a mantissa (float-point value) but short does not (it is a whole number). In explicit casting, mantissa part is truncated. The left-side value can be assigned to any right-side value and is done implicitly. The reverse like float to short requires explicit casting. Examples of implicit casting short x = 10; // 2 bytes double y = x; // 2 bytes to 8 bytes byte x = 10; // 1 byte int y = x; // 1 byte to 4 bytes Following program on double to short explains explicit casting, Java style where a double is assigned to a short. public class Conversions { public static void main(String args[]) { double d1 = 10.5; // 8 bytes // short s1 = d1; // 8 bytes value to 2 bytes short s1 = (short) d1; // 8 bytes double value type explicitly casted to 2 bytes short System.out.println("\ndouble value: " + d1); // prints 10.5 System.out.println("Converted short value: " + s1); // prints 10; 0.5 gone } } Output screenshot of double to short Java short s1 = d1; The above statement raises a compilation error "possible loss of precision". short s1 = (short) d1; The double d1 is explicitly type casted to short s1. Observe, the syntax of explicit casting. On both sides, it should be short only. When casted, the precision of 0.5 is lost (for this reason only, compiler does not compile). This is known as data truncation. View all for 65 types of Conversions
https://way2java.com/casting-operations/java-double-to-short/
CC-MAIN-2022-33
refinedweb
289
65.93
Managed Extensions: Using GDI+ Brushes to Draw Text Welcome to this week's installment of .NET Tips & Techniques! Each week, award-winning Architect and Lead Programmer Tom Archer demonstrates how to perform a practical .NET programming task using either C# or Managed C++ Extensions. One of the examples I wrote in Extending MFC Applications with the .NET Framework illustrated how to store and retrieve BLOB (binary large objects) to and from a SQL Server database. These BLOBs were actually image data that was rendered on the dialog when the user selected them. Since then, I've had numerous requests to illustrate more of the GDI+ capabilities from the Managed Extensions to C++ for .NET (MC++). Therefore, in this first in a series of GDI+ articles, I illustrate how to draw text (both hatch and gradient) using GDI+ brushes. Basic Steps to Drawing Text with BrushesProvided with this article is a demo application that allows the user to specify a text value, the font size, whether the text is drawn with a hatch or gradient brush, and the colors to use in drawing the text. Here's a screen shot of that application: Here are some basic steps for drawing either hatched or gradient text using GDI+: - Add an event handler for the control's Paint event. You should do your drawing in this method (or a method called from this method) so that your control is repainted properly. - Obtain a Graphics object. For those of you familiar with drawing on device contexts, the Graphics object is the .NET encapsulation of a drawing surface. When drawing on a control—such as a PictureBox—you could call the PictureBox::CreateGraphics method as it returns a Graphics object for you to draw on. In fact, I've seen this technique on various demo/sample applications on the Web. However, the problem with it is that the Graphics object is not persistent. Therefore, the control doesn't paint itself properly when the user switches to another application and then back again. So you should use the Graphics object of the PaintEventArgs object that is passed to the control's Paint method. private: System::Void picText_Paint(System::Object * sender, System::Windows::Forms::PaintEventArgs * e) { ... Graphics* g = e->Graphics; - Instantiate a Font object. Of the 13 different Font constructors, the most basic one requires that you supply the font type face name and the font size. In the following example, I create a 20 point, regular (as opposed to bold, italic, etc.) font using the "Times New Roman" type face: using namespace System::Drawing; ... Font* font = new Font(S"Times new Roman", 20, FontStyle::Regular); - Measure the text to be rendered. You need to measure the text in order to render it. As I illustrated in my article Managed Extensions: Measuring Strings, you use the Graphics::MeasureString to accomplish this task. This method takes the text to be measured and the font being used and returns a SizeF structure, which simply defines the dimensions needed to draw the text. SizeF textSize = g->MeasureString(S"My Sample Text", font); - Instantiate a Brush object. You can draw with various types of Brush objects, including HatchBrush, LinearGradientBrush, PathGradientBrush, SolidBrush, and TextureBrush. As the parameters to instantiate the various Brush objects are only slightly different, I won't attempt to cover each and every one. Instead, I'll present examples of the two types of Brush objects (HatchBrush and LinearGradientBrush) that are used in this article's demo application, which allows the user to select the Brush type to use in drawing their specified text. // HatchBrush example Brush* brush = new HatchBrush(HatchStyle::Cross, Color::Black, Color::Blue); // LinearGradientBrush example RectangleF* rect = __nogc new RectangleF(PointF(0, 0), textSize); brush = new LinearGradientBrush(*rect, Color::Black, Color::Blue, LinearGradientMode::ForwardDiagonal); - [Optional] Fill the background. You typically need to initialize the background before you draw on it. There are two standard ways of doing this. The easiest is to simply call the Graphics::Clear method and specify the desired color that you will use to fill the entire drawing surface. However, sometimes you need a finer level of control. In those cases, you can use the Graphics::FillRectange method. The Graphics::FillRectange method enables you to specify a Brush object of your choosing as well as the exact rectangular coordinates to use. Regarding the Brush object, you can either instantiate a custom Brush or use the SystemBrushes object, which defines property members that are each a SolidBrush representation of a Windows display element. These are the elements that are defined via the Windows Display Properties and include ActiveBorder, ActiveCaption, and so on: // Use the Windows-defined color for controls // and explicitly state the rectangle coordinates g->FillRectangle(SystemBrushes::Control, picText->Left, picText->Top, picText->Right - picText->Left, picText->Bottom - picText->Top); // Color the entire drawing surface using White g->Clear(Color::White); - Render (Draw) the Text. Once you have all the GDI+ objects instantiated, you need only call the Graphics::DrawString method. Here's an example call to that method where I specify the text to render, the Font and Brush objects to use, and exactly where on the drawing surface I want the text displayed: // Center the text on the drawing surface g->DrawString(txtToDisplay->Text, font, brush, (picText->Width - textSize.Width) / 2, (picText->Height - textSize.Height) / 2);<<
http://www.developer.com/net/cplus/article.php/3423311/Managed-Extensions-Using-GDI-Brushes-to-Draw-Text.htm
CC-MAIN-2015-48
refinedweb
886
53
18 August 2010 15:08 [Source: ICIS news] LONDON (ICIS)--Middle East ammonia prices have risen by $5/tonne (€4/tonne) from the last completed business in the region following a spot sale out of ?xml:namespace> An official with This was up from a sale in early August by Ruwais Fertilizer Industries (Fertil), also to Mitsui, at $340/tonne FOB for shipment in late August/early September. The deal was also $25/tonne higher than Petrochemical Commercial’s last sale at $320/tonne FOB. The deal comes as ammonia prices worldwide are firming as a result of tight prompt availability and good demand ahead of the autumn application seasons. The Petrochemical Commercial official also confirmed that its Pardis I ammonia and urea units, which are located at Assaluyeh, were still shut down following an explosion on 4 August in a gas pipeline. The plants are expected to be off line for at least a month. The Pardis II ammonia and urea plants continue to operate, the official added. ($1 = €0.78)
http://www.icis.com/Articles/2010/08/18/9386282/middle-east-ammonia-rises-to-345tonne-on-iran-spot.html
CC-MAIN-2014-52
refinedweb
172
56.59
JTree: File And Directory Tree - Online Code Description This is a sample code of JTree. By using this code you can make the Tree of Diretories and Files for Example: Windows File Explorer. Source Code import java.awt.*; import java.io.File; import java.util.Collections; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.*; import javax.swing.event.TreeSelectionEvent... (login or register to view full code) To view full code, you must Login or Register, its FREE. Hey, registering yourself just takes less than a minute and opens up a whole new GetGyan experience.
http://www.getgyan.com/show/447/JTree%3A_File_and_Directory_Tree
CC-MAIN-2017-51
refinedweb
103
54.29
A simple, easy access key-value registry for Django. Project description DJ-Registry This is a simple, easy access key-value registry for Django. Sometimes you would like to have some flexibility in your settings. Putting your settings in settings.py or as environment variables also mean an engineer familiar with code or command line is required to alter them. This Django app leverage the built-in Django admin so changing settings is easier as you can use the web interface. Requirements - Python 3 - Django >= 1.11 I only did a quick test with Python 3.6 on Django 1.11 and the latest Django, which is 2.2.6 at the time being. Installation Install DJ-Registry with your favorite Python package manager: (venv)$ pip install dj_registry Add registry to your INSTALLED_APPS settings: INSTALLED_APPS = [ # other apps... 'registry', ] Migrate the database (venv)$ ./manage.py migrate Then, we're all set! Usage Log in to the admin, and create some keys under the Django Registry > Entries section. Let's say, we create mailgun.key and mailgun.domain with the corresponding string type and values. We then create another entry with game.max_score as the key, 10000 as the value and integer as the type. The following example shows you how to access them in code: from registry.helper import reg key = reg['mailgun.key'] # the key that you set domain = reg['mailgun.domain'] # the domain that you set max_score = reg['game.max_score'] # 10000, it is returned as an int You can also use get if you want to have a default and avoid exceptions if the key is not available (not enabled or does not exist) reg.get('game.levels', 10) # return 10 if key not found or disabled reg['game.levels'] # KeyError if key not found or disabled You can set or delete entry if you want reg['game.levels'] = 12 # Set game.levels to 12 (integer) and save del reg['game.levels'] # Delete game.levels Enabled and comment field If you want to disable a key, just toggle the enabled boolean in the admin interface. It would be treated as if the key didn't exist. This is something meant to be used in the admin interface. If you want to manipulate this in the code, you will have to access the raw model like the following: from registry.models import Entry e = Entry.objects.get('game.levels') e.enabled = False e.save() The comment field is also meant to be used in the admin interface. It is a convenient cell for user to put comments regarding to the settings, something like the following: 50: average use case. 9999: maximum special case Types integer, float, string, and boolean are the supported types for now. 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/dj-registry/
CC-MAIN-2021-49
refinedweb
484
69.07
#include <factory.hpp> List of all members. This structure is given to all factory functions, so that they can correctly create the widgets they need to create. Things inside this structure should not change between creating two widgets. Definition at line 188 of file factory.hpp. Definition at line 190 of file factory.hpp. The current eve_client_holder -- keeps all the relevant parts of a view in one location. Originally the factory token was duplication nearly every member of the client_holder as a member itself, so this cleans up factory_token quite a bit. Definition at line 218 of file factory.hpp. Created widgets should be made with respect to this display, and inserted into the given parent by this display. Definition at line 204 of file factory.hpp. The function to call when a button is pressed. This should be called by buttons and button-like widgets when they are hit (and have an action, rather than a state change). Definition at line 225 of file factory.hpp. The current Adam sheet -- this contains all of the cells which widgets might want to bind against. Definition at line 210 of file factory.hpp. Use of this website signifies your agreement to the Terms of Use and Online Privacy Policy. Search powered by Google
https://stlab.adobe.com/structadobe_1_1factory__token__t.html
CC-MAIN-2022-05
refinedweb
212
59.3
Representing a cards: We're going to use the same representation of a card as an int that we did in IC210, summarized below: mainfunction in that class can be used simply as a way to test those functions, not as an interesting program in and of itself. Later on, when we're ready to use these functions in a real program, they just stay in their class ... no copying and pasting, no #includes, no separating .h from .cpp files. Very convenient! public class Card { public static int makeCard(int face, int suit) { return 20*suit + face; } public static int cardToSuit(int card) { return card/20; } public static int cardToFace(int card) { return card%20; } public static String cardToString(int card) { String[] suits = {"\u2663","\u2666","\u2665","\u2660"}; String[] faces = {"","","2","3","4","5","6","7","8","9","10","J","Q","K","A"}; return faces[cardToFace(card)] + suits[cardToSuit(card)]; } public static void main(String[] args) { int c1 = makeCard(10,0); System.out.println(cardToString(c1)); } }Hopefully this code is mostly self-explanatory. Note how the nice Java array-initializer syntax makes it easy to implement cardToString! The mainis there to test our functions, and if you compile and run everything looks good: ~/$ javac Card1.java ~/$ java Card1 10♣The next step is to add functions for making and shuffling decks. That's pretty straightforward. Take a look at the complete version of Card.java. Card.makeCard(3,1)It's a little wordy, of course, but it allows to easily reuse these functions in any Java program we like! So, let's start off our game by creating, shuffling and printing a deck. This is going to be a new class called Game, defined of course in a new file Game.java. So, at this point you have a program that consists of two files Game.javaand Car.java. You compile them both, either individually, or together like this: javac Game.java Card.javaThe order in which you compile them is irrelevent. To run the program, you only specify Game, like this: java GameWhat about Card? Well, here's where Java's organization works nicely. When the JVM exectues the call to function Card.makeDeck(), it knows it needs to load the classfile Card.class, because that's where the class Cardis defined. As long as both classfiles are in the current directory, Java finds them and loads them as needed. public class Player { int card; double money; }Where we put this definition is a bit up to us. We could put it inside the definition of the class Game, where it would actually be a part of Game. In fact, its full name would be Game.Player. [Note: if we do this, the definition will have to be static class Player { ... }. Why this would be needed in this case will be discussed in a few lessons.] Or we could put it in its own file, Player.java, in which case it would be an independent type, not part of or dependent on anything. We'll chose the latter, as it's the more common and straightforward way of doing things. Now we can go ahead and create an object of type player to represent the user or the AI. Remember that Player pu;only declares the reference pu, it doesn't actually create a player object. That's done with a call to new, like this: Player pu = new Player();This is called instantiating and object of type Player. The object itself, i.e. the thing pu refers-to/points-to is said to be an instance of class Player. The class itself is a type, not an object. It is a blueprint for creating Player objects. Only the call to new Player()creates new Player objects. We refer to data members of a Player object with a . like this: pu.money = 5.00;. Here's a program: Once again, we need to compile each .java file, individually or together makes no difference. In fact, Card.javahasn't changed, so it doesn't need to be recompiled. Then we run the program by calling the JVM with Game. The other .class files will be loaded by the JVM as they are needed. ~/$ javac Game.java Player.java ~/$ java Game Player has $5.0 and card K♥
https://www.usna.edu/Users/cs/wcbrown/courses/S16IC211/lec/l03/lec.html
CC-MAIN-2018-22
refinedweb
717
74.9
Internationalization for GitLabInternationalization for GitLab Introduced in GitLab 9.2. For working with internationalization (i18n), GNU gettext is used given it's the most used tool for this task and there are a lot of applications that help us work with it. NOTE: All rake commands described on this page must be run on a GitLab instance, usually GDK. Setting up GitLab Development Kit (GDK)Setting up GitLab Development Kit (GDK) In order to be able to work on the GitLab Community Edition project you must download and configure it through GDK. After you have the GitLab project ready, you can start working on the translation. ToolsTools The following tools are used: gettext_i18n_rails: this gem allow us to translate content from models, views and controllers. Also it gives us access to the following Rake tasks: rake gettext:find: Parses almost all the files from the Rails application looking for content that has been marked for translation. Finally, it updates the PO files with the new content that it has found. rake gettext:pack: Processes the PO files and generates the MO files that are binary and are finally used by the application. gettext_i18n_rails_js: this gem is useful to make the translations available in JavaScript. It provides the following Rake task: rake gettext:po_to_json: Reads the contents from the PO files and generates JSON files containing all the available translations. PO editor: there are multiple applications that can help us to work with PO files, a good option is Poedit which is available for macOS, GNU/Linux and Windows. Preparing a page for translationPreparing a page for translation We basically have 4 types of files: - Ruby files: basically Models and Controllers. - HAML files: these are the view files. - ERB files: used for email templates. - JavaScript files: we mostly need to work with Vue templates. Ruby filesRuby files If there is a method or variable that works with a raw string, for instance: def hello "Hello world!" end Or: hello = "Hello world!" You can easily mark that content for translation with: def hello _("Hello world!") end Or: hello = _("Hello world!") Be careful when translating strings at the class or module level since these would only be evaluated once at class load time. For example: validates :group_id, uniqueness: { scope: [:project_id], message: _("already shared with this group") } This would be translated when the class is loaded and result in the error message always being in the default locale. Active Record's :message option accepts a Proc, so we can do this instead: validates :group_id, uniqueness: { scope: [:project_id], message: -> (object, data) { _("already shared with this group") } } Messages in the API ( lib/api/ or app/graphql) do not need to be externalized. HAML filesHAML files Given the following content in HAML: %h1 Hello world! You can mark that content for translation with: %h1= _("Hello world!") ERB filesERB files Given the following content in ERB: <h1>Hello world!</h1> You can mark that content for translation with: <h1><%= _("Hello world!") %></h1> JavaScript filesJavaScript files In JavaScript we added the __() (double underscore parenthesis) function that you can import from the ~/locale file. For instance: import { __ } from '~/locale'; const label = __('Subscribe'); In order to test JavaScript translations you have to change the GitLab localization to another language than English and you have to generate JSON files using bin/rake gettext:po_to_json or bin/rake gettext:compile. Vue filesVue files In Vue files we make both the __() (double underscore parenthesis) function and the s__() (namespaced double underscore parenthesis) function available that you can import from the ~/locale file. For instance: import { __, s__ } from '~/locale'; const label = __('Subscribe'); const nameSpacedlabel = __('Plan|Subscribe'); For the static text strings we suggest two patterns for using these translations in Vue files: External constants file: javascripts │ └───alert_settings │ │ constants.js │ └───components │ │ alert_settings_form.vue // constants.js import { s__ } from '~/locale'; /* Integration constants */ export const I18N_ALERT_SETTINGS_FORM = { saveBtnLabel: __('Save changes'), }; // alert_settings_form.vue import { I18N_ALERT_SETTINGS_FORM, } from '../constants'; <script> export default { i18n: { I18N_ALERT_SETTINGS_FORM, } } </script> <template> <gl-button {{ $options.i18n.I18N_ALERT_SETTINGS_FORM }} </gl-button> </template> When possible, you should opt for this pattern, as this allows you to import these strings directly into your component specs for re-use during testing. Internal component $optionsobject: <script> export default { i18n: { buttonLabel: s__('Plan|Button Label') } }, </script> <template> <gl-button : {{ $options.i18n.buttonLabel }} </gl-button> </template> In order to visually test the Vue translations you have to change the GitLab localization to another language than English and you have to generate JSON files using bin/rake gettext:po_to_json or bin/rake gettext:compile. Dynamic translationsDynamic translations Sometimes there are some dynamic translations that can't be found by the parser when running bin/rake gettext:find. For these scenarios you can use the N_ method. There is also and alternative method to translate messages from validation errors. Working with special contentWorking with special content InterpolationInterpolation Placeholders in translated text should match the code style of the respective source file. For example use %{created_at} in Ruby but %{createdAt} in JavaScript. Make sure to avoid splitting sentences when adding links. In Ruby/HAML: _("Hello %{name}") % { name: 'Joe' } => 'Hello Joe' In Vue: See the section on Vue component interpolation. In JavaScript (when Vue cannot be used): import { __, sprintf } from '~/locale'; sprintf(__('Hello %{username}'), { username: 'Joe' }); // => 'Hello Joe' If you want to use markup within the translation and are using Vue, you must use the gl-sprintfcomponent. If for some reason you cannot use Vue, use sprintfand stop it from escaping placeholder values by passing falseas its third argument. You must escape any interpolated dynamic values yourself, for instance using escapefrom lodash. import { escape } from 'lodash'; import { __, sprintf } from '~/locale'; let someDynamicValue = '<script>alert("evil")</script>'; // Dangerous: sprintf(__('This is %{value}'), { value: `<strong>${someDynamicValue}</strong>`, false); // => 'This is <strong><script>alert('evil')</script></strong>' // Incorrect: sprintf(__('This is %{value}'), { value: `<strong>${someDynamicValue}</strong>` }); // => 'This is <strong><script>alert('evil')</script></strong>' // OK: sprintf(__('This is %{value}'), { value: `<strong>${escape(someDynamicValue)}</strong>` }, false); // => 'This is <strong><script>alert('evil')</script></strong>' PluralsPlurals In Ruby/HAML: n_('Apple', 'Apples', 3) # => 'Apples' Using interpolation: n_("There is a mouse.", "There are %d mice.", size) % size # => When size == 1: 'There is a mouse.' # => When size == 2: 'There are 2 mice.' Avoid using %dor count variables in singular strings. This allows more natural translation in some languages. In JavaScript: n__('Apple', 'Apples', 3) // => 'Apples' Using interpolation: n__('Last day', 'Last %d days', x) // => When x == 1: 'Last day' // => When x == 2: 'Last 2 days' The n_ method should only be used to fetch pluralized translations of the same string, not to control the logic of showing different strings for different quantities. Some languages have different quantities of target plural forms - Chinese (simplified), for example, has only one target plural form in our translation tool. This means the translator would have to choose to translate only one of the strings and the translation would not behave as intended in the other case. For example, prefer to use: if selected_projects.one? selected_projects.first.name else n__("Project selected", "%d projects selected", selected_projects.count) end rather than: # incorrect usage example n_("%{project_name}", "%d projects selected", count) % { project_name: 'GitLab' } NamespacesNamespaces A namespace is a way to group translations that belong together. They provide context to our translators by adding a prefix followed by the bar symbol ( |). For example: 'Namespace|Translated string' A namespace provide the following benefits: - It addresses ambiguity in words, for example: Promotions|Promotevs Epic|Promote - It allows translators to focus on translating externalized strings that belong to the same product area rather than arbitrary ones. - It gives a linguistic context to help the translator. In some cases, namespaces don't make sense, for example, for ubiquitous UI words and phrases such as "Cancel" or phrases like "Save changes" a namespace could be counterproductive. Namespaces should be PascalCase. In Ruby/HAML: s_('OpenedNDaysAgo|Opened') In case the translation is not found it returns Opened. In JavaScript: s__('OpenedNDaysAgo|Opened') The namespace should be removed from the translation. See the translation guidelines for more details. HTMLHTML We no longer include HTML directly in the strings that are submitted for translation. This is for a couple of reasons: - It introduces a chance for the translated string to accidentally include invalid HTML. - It introduces a security risk where translated strings become an attack vector for XSS, as noted by the Open Web Application Security Project (OWASP). To include formatting in the translated string, we can do the following: In Ruby/HAML: html_escape(_('Some %{strongOpen}bold%{strongClose} text.')) % { strongOpen: '<strong>'.html_safe, strongClose: '</strong>'.html_safe } # => 'Some <strong>bold</strong> text.' In JavaScript: sprintf(__('Some %{strongOpen}bold%{strongClose} text.'), { strongOpen: '<strong>', strongClose: '</strong>'}, false); // => 'Some <strong>bold</strong> text.' In Vue See the section on interpolation. When this translation helper issue is complete, we plan to update the process of including formatting in translated strings. Including Angle BracketsIncluding Angle Brackets If a string contains angles brackets ( </ >) that are not used for HTML, it is still flagged by the rake gettext:lint linter. To avoid this error, use the applicable HTML entity code ( < or >) instead: In Ruby/HAML: html_escape_once(_('In < 1 hour')).html_safe # => 'In < 1 hour' In JavaScript: import { sanitize } from '~/lib/dompurify'; const i18n = { LESS_THAN_ONE_HOUR: sanitize(__('In < 1 hour'), { ALLOWED_TAGS: [] }) }; // ... using the string element.innerHTML = i18n.LESS_THAN_ONE_HOUR; // => 'In < 1 hour' In Vue: <gl-sprintf : // => 'In < 1 hour' Dates / timesDates / times - In JavaScript: import { createDateTimeFormat } from '~/locale'; const dateFormat = createDateTimeFormat({ year: 'numeric', month: 'long', day: 'numeric' }); console.log(dateFormat.format(new Date('2063-04-05'))) // April 5, 2063 This makes use of Intl.DateTimeFormat. In Ruby/HAML, we have two ways of adding format to dates and times: - Through the lhelper, i.e. l(active_session.created_at, format: :short). We have some predefined formats for dates and times. If you need to add a new format, because other parts of the code could benefit from it, you can add it to en.yml file. - Through strftime, i.e. milestone.start_date.strftime('%b %-d'). We use strftimein case none of the formats defined on en.yml matches the date/time specifications we need, and if there is no need to add it as a new format because is very particular (i.e. it's only used in a single view). Best practicesBest practices Minimize translation updatesMinimize translation updates Updates can result in the loss of the translations for this string. To minimize risks, avoid changes to strings, unless they: - Add value to the user. - Include extra context for translators. For example, we should avoid changes like this: - _('Number of things: %{count}') % { count: 10 } + n_('Number of things: %d', 10) Keep translations dynamicKeep translations dynamic There are cases when it makes sense to keep translations together within an array or a hash. Examples: - Mappings for a dropdown list - Error messages To store these kinds of data, using a constant seems like the best choice, however this doesn't work for translations. Bad, avoid it: class MyPresenter MY_LIST = { key_1: _('item 1'), key_2: _('item 2'), key_3: _('item 3') } end The translation method ( _) is called when the class is loaded for the first time and translates the text to the default locale. Regardless of the user's locale, these values are not translated a second time. Similar thing happens when using class methods with memoization. Bad, avoid it: class MyModel def self.list @list ||= { key_1: _('item 1'), key_2: _('item 2'), key_3: _('item 3') } end end This method memorizes the translations using the locale of the user, who first "called" this method. To avoid these problems, keep the translations dynamic. Good: class MyPresenter def self.my_list { key_1: _('item 1'), key_2: _('item 2'), key_3: _('item 3') }.freeze end end Splitting sentencesSplitting sentences Please never split a sentence as that would assume the sentence grammar and structure is the same in all languages. For instance, the following: {{ s__("mrWidget|Set by") }} {{ author.name }} {{ s__("mrWidget|to be merged automatically when the pipeline succeeds") }} should be externalized as follows: {{ sprintf(s__("mrWidget|Set by %{author} to be merged automatically when the pipeline succeeds"), { author: author.name }) }} Avoid splitting sentences when adding linksAvoid splitting sentences when adding links This also applies when using links in between translated sentences, otherwise these texts are not translatable in certain languages. In Ruby/HAML, instead of: - zones_link = link_to(s_('ClusterIntegration|zones'), '', target: '_blank', rel: 'noopener noreferrer') = s_('ClusterIntegration|Learn more about %{zones_link}').html_safe % { zones_link: zones_link } Set the link starting and ending HTML fragments as variables like so: - zones_link_url = '' - zones_link_start = '<a href="%{url}" target="_blank" rel="noopener noreferrer">'.html_safe % { url: zones_link_url } = s_('ClusterIntegration|Learn more about %{zones_link_start}zones%{zones_link_end}').html_safe % { zones_link_start: zones_link_start, zones_link_end: '</a>'.html_safe } In Vue, instead of: <template> <div> <gl-sprintf : <template #link> <gl-linkzones</gl-link> </template> </gl-sprintf> </div> </template> Set the link starting and ending HTML fragments as placeholders like so: <template> <div> <gl-sprintf : <template # <gl-link{{ content }}</gl-link> </template> </gl-sprintf> </div> </template> In JavaScript (when Vue cannot be used), instead of: {{ sprintf(s__("ClusterIntegration|Learn more about %{link}"), { link: '<a href="" target="_blank" rel="noopener noreferrer">zones</a>' }) }} Set the link starting and ending HTML fragments as placeholders like so: {{ sprintf(s__("ClusterIntegration|Learn more about %{linkStart}zones%{linkEnd}"), { linkStart: '<a href="" target="_blank" rel="noopener noreferrer">', linkEnd: '</a>', }) }} The reasoning behind this is that in some languages words change depending on context. For example in Japanese は is added to the subject of a sentence and を to the object. This is impossible to translate correctly if we extract individual words from the sentence. When in doubt, try to follow the best practices described in this Mozilla Developer documentation. Vue components interpolationVue components interpolation When translating UI text in Vue components, you might want to include child components inside the translation string. You could not use a JavaScript-only solution to render the translation, because Vue would not be aware of the child components and would render them as plain text. For this use case, you should use the gl-sprintf component which is maintained in GitLab UI. The gl-sprintf component accepts a message property, which is the translatable string, and it exposes a named slot for every placeholder in the string, which lets you include Vue components easily. Assume you want to print the translatable string Pipeline %{pipelineId} triggered %{timeago} by %{author}. To replace the %{timeago} and %{author} placeholders with Vue components, here's how you would do that with gl-sprintf: <template> <div> <gl-sprintf : <template #pipelineId>{{ pipeline.id }}</template> <template #timeago> <timeago : </template> <template #author> <gl-avatar-labeled : </template> </gl-sprintf> </div> </template> For more information, see the gl-sprintf documentation. Updating the PO files with the new contentUpdating the PO files with the new content Now that the new content is marked for translation, we need to update locale/gitlab.pot files with the following command: bin/rake gettext:regenerate This command updates locale/gitlab.pot file with the newly externalized strings and remove any strings that aren't used anymore. You should check this file in. Once the changes are on master, they are picked up by CrowdIn and be presented for translation. We don't need to check in any changes to the locale/[language]/gitlab.po files. They are updated automatically when translations from CrowdIn are merged. If there are merge conflicts in the gitlab.pot file, you can delete the file and regenerate it using the same command. Validating PO filesValidating PO files To make sure we keep our translation files up to date, there's a linter that is running on CI as part of the static-analysis job. To lint the adjustments in PO files locally you can run rake gettext:lint. The linter takes the following into account: - Valid PO-file syntax - Variable usage - Only one unnamed ( %d) variable, since the order of variables might change in different languages - All variables used in the message ID are used in the translation - There should be no variables used in a translation that aren't in the message ID - Errors during translation. - Presence of angle brackets ( <or >) The errors are grouped per file, and per message ID: Errors in `locale/zh_HK/gitlab.po`: PO-syntax errors SimplePoParser::ParserErrorSyntax error in lines Syntax error in msgctxt Syntax error in msgid Syntax error in msgstr Syntax error in message_line There should be only whitespace until the end of line after the double quote character of a message text. Parsing result before error: '{:msgid=>["", "You are going to delete %{project_name_with_namespace}.\\n", "Deleted projects CANNOT be restored!\\n", "Are you ABSOLUTELY sure?"]}' SimplePoParser filtered backtrace: SimplePoParser::ParserError Errors in `locale/zh_TW/gitlab.po`: 1 pipeline <%d 條流水線> is using unknown variables: [%d] Failure translating to zh_TW with []: too few arguments In this output the locale/zh_HK/gitlab.po has syntax errors. The locale/zh_TW/gitlab.po has variables that are used in the translation that aren't in the message with ID 1 pipeline. Adding a new languageAdding a new language NOTE: Introduced in GitLab 13.3: Languages with less than 2% of translations are not available in the UI. Let's suppose you want to add translations for a new language, let's say French. The first step is to register the new language in lib/gitlab/i18n.rb: ... AVAILABLE_LANGUAGES = { ..., 'fr' => 'Français' }.freeze ... Next, you need to add the language: bin/rake gettext:add_language[fr] If you want to add a new language for a specific region, the command is similar, you just need to separate the region with an underscore ( _). For example: bin/rake gettext:add_language[en_GB] Please note that you need to specify the region part in capitals. Now that the language is added, a new directory has been created under the path: locale/fr/. You can now start using your PO editor to edit the PO file located in: locale/fr/gitlab.edit.po. After you're done updating the translations, you need to process the PO files in order to generate the binary MO files and finally update the JSON files containing the translations: bin/rake gettext:compile In order to see the translated content we need to change our preferred language which can be found under the user's Settings ( /profile). After checking that the changes are ok, you can proceed to commit the new files. For example: git add locale/fr/ app/assets/javascripts/locale/fr/ git commit -m "Add French translations for Value Stream Analytics page"
https://cloud.cees.ornl.gov/gitlab/help/development/i18n/externalization.md
CC-MAIN-2021-31
refinedweb
3,087
53.31
Overview Atlassian SourceTree is a free Git and Mercurial client for Windows. Atlassian SourceTree is a free Git and Mercurial client for Mac. from show import * x = 12 nums = list(range(4)) show(x, nums) yields: x: 12 nums: [0, 1, 2, 3] Output is self-labeled, so you don't spend time doing that yourself. Debug Printing Logging, assertions, unit tests, and interactive debuggers are all great tools. But sometimes you just need to print values as a program runs to see what's going on. Every language has features to print text, but they're rarely customized for printing debugging information. show is. It provides a simple, DRY mechanism to "show what's going on." Sometimes programs print so that users can see things, and sometimes they print so that developers can. show() is for developers, helping rapidly print the current state of variables in ways that easily identify what value is being printed, without a lot of wasted effort. It replaces the craptastic repetitiveness of: print "x: {0!r}".format(x) with: show(x) And if you have a lot of output flowing by, and it's hard to see your debugging output, try: show(x, y, z, style='red') And now you have debug output that clearly stands out from the rest. But "debug printing is so very 1989!" you may say. "We now have logging, logging, embedded assertions, unit tests, ..." Yes, that's true. But wonderful as those things are, just showing your current program values is often what the doctor ordered. And Much More While avoiding a few extra characters of typing and a little extra program complexity is nice (very nice, actually), show does much more. As just a taste, show.changed() displays local values that have changed since it was last run: def f(): x = 4 show.changed() x += 1 retval = x * 3 show.changed() return retval When run will display: x: 4 x: 5 retval: 15 Functions decorated with @show.inout show you input parameters as the function is called, then the return value later.: @show.inout def g(a): b = 3 a += b show.changed() return a g(4) Displays: g(a=4) a: 7 b: 3 g(a=4) -> 7 (If you want this terser, decorate with @show.inout(only='out').) If you run show.prettyprint() after importing, or alternatively if you import with from show.pretty import *, the Pygments syntax highlighter will (if installed), be used to colorize data values. This can significantly help see complex lists and dictionaries. Finally, show does normal output too, just like say (with all of its high-level text formatting): wizard = "Gandalf" show("You have no power here, {wizard}!") Prints: You have no power here, Gandalf! Long story short, show is a strong debugging companion that prints the maximum amount of useful information with the minimum amount of fuss. For more, see the full documentation at Read the Docs. New and Notable Try from show.pretty import *. IPython is now well-supported, either in a terminal window or a Jupyter Notebook. In other words, show now supports interactive usage. (The plain Python REPL is still only marginally supported, given significant weaknesses in its introspection support.) A relatively new capability is to differentially set the formatting parameters on a method by method basis. For example, if you want to see separators in green and function call/return annotations in red: show.sep.set(style='green') show.inout.set(style='red') You could long do this on a call-by-call basis, but being able to set the defaults just for specific methods allows you to get more formatting in with fewer characters typed. This capability is available on a limited basis: primarily for format-specific calls (blanklines, hr, sep, and title) and for one core inspection call (the inout decorator). It will be extended, and mapped back to underlying say and options features over time. Warning There are some outstanding issues with Windows. Also, when evaluating show, do so from a program file or from IPython, not from the plain interactive REPL. show depends on introspection, which the plain REPL simply doesn't provide with any quality.
https://bitbucket.org/jeunice/show/overview
CC-MAIN-2017-34
refinedweb
694
65.12
This action might not be possible to undo. Are you sure you want to continue? AVR microcontroller 3. Overview 3.1. Block Diagram and Architectural Overview 3.2. The Algorithm 4. Implementation 4.1. Sensor Circuit 4.2. Motor Interface and Control Circuit 4.3. Source Code 5. Possible Improvements 6. References and Resources 6.1. Books and Links 6.2. Tools of the trade 6.3. Electronic shops 6.4. Parts and Prices Page 2 of 17 Line Follower Summary The purpose of this document is to help you build a Line Following Robot. Starting with an overview of the system the document would cover implementation details like circuits and algorithms, followed by some suggestions on improving the design. The ‘Reference and Resources’ page has a list of relevant books, websites, electronic shops and commonly used parts & their prices. Page 3 of 17 Line Follower Introduction What is a line follower? Line follower is a machine that can follow a path. The path can be visible like a black line on a white surface (or vice-versa) or it can be invisible like a magnetic field. Why build a line follower?. Prerequisites: Knowledge of basic digital and analog electronics. (A course on Digital Design and Electronic Devices & Circuits would be helpful) C Programming Sheer interest, an innovative brain and perseverance! Background: I started with building a parallel port based robot which could be controlled manually by a keyboard. On the robot side was an arrangement of relays connected to parallel port pins via opto-couplers. The next version was a true computer controlled line follower. It had sensors connected to the status pins of the parallel port. A program running on the computer polled the status register of the parallel port hundreds of times every second and sent control signals accordingly through the data pins. The drawbacks of using a personal computer were soon clear – It’s difficult to control speed of motors As cable length increases signal strength decreases and latency increases. A long multi core cable for parallel data transfer is expensive. The robot is not portable if you use a desktop PC. The obvious next step was to build an onboard control circuit; the options – a hardwired logic circuit or a uC. Since I had no knowledge of uC at that time, I implemented a hardwired logic circuit using multiplexers. It basically mapped input from four sensors to four outputs for the motor driver according to a truth table. Though it worked fine, it could show no intelligence – like coming back on line after losing it, or doing something special when say the line ended. To get around this problem and add some cool features, using a microcontroller was the best option. Page 4 of 17 Line Follower The AVR microcontroller: “Atmel's AVR® microcontrollers have a RISC core running single cycle instructions and a well-defined I/O structure that limits the need for external components. Internal oscillators, timers, UART, SPI, pull-up resistors, pulse width modulation, ADC, analog comparator and watch-dog timers are some of the features you will find in AVR devices. AVR instructions are tuned to decrease the size of the program whether the code is written in C or Assembly. With on-chip in-system programmable Flash and EEPROM, the AVR is a perfect choice in order to optimize cost and get product to the market quickly.” - Apart form this almost all AVRs support In System Programming (ISP) i.e. you can reprogram it without removing it from the circuit. This comes very handy when prototyping a design or upgrading a built-up system. Also the programmer used for ISP is easier to build compared to the parallel programmer required for many old uCs. Most AVR chips also support Boot Loaders which take the idea of In System Programming to a new level. Features like I2C bus interface make adding external devices a cakewalk. While most popular uCs require at least a few external components like crystal, caps and pull-up resistors, with AVR the number can be as low as zero! Cost: AVR = PIC > 8051 (by 8051 I mean the 8051 family) Availability: AVR = PIC <8051 Speed: AVR > PIC > 8051 Built-in Peripherals: This one is difficult to answer since all uC families offer comparable features in their different chips. For a just comparison, I would rather say that for a given price AVR = PIC > 8051. Tools and Resources: 8051 has been around from many years now, consequently there are more tools available for working with it. Being a part of many engineering courses, there is a huge communitiy of people that can help you out with 8051; same with books and online resources. In spite of being new the AVR has a neat tool chain (See ‘References and Resources‘). Availability of online resources and books is fast increasing. Here, 8051 > AVR = PIC Page 5 of 17 Line Follower Overview Block. L4 Left L3 L2 L1 R1 R2 Center Sensor Array R3 R4 Right uC decides the next move according to the algorithm given below which tries to position the robot such that L1 and R1 both read 0 and the rest read 1. L4 1 Left L1 R1 R2 R3 R4 0 0 1 1 1 Center Right Desired State L1=R1=0, and Rest=1 L3 1 L2 1 Page 6 of 17 Line Follower Algorithm: 1. L= leftmost sensor which reads 0; R= rightmost sensor which reads 0. If no sensor on Left (or Right) is 0 then L (or R) equals 0; Ex: L4 L3 L2 L1 R1 R2 R3 R4 1 0 0 1 1 1 1 1 Left Center Right Here L=3 R=0 L4 1 Left 2. If all sensors read 1 go to step 3, else, If L>R Move Left If L<R Move Right If L=R Move Forward Goto step 4 Move Clockwise if line was last seen on Right Move Counter Clockwise if line was last seen on Left Repeat step 3 till line is found. Goto step 1. L3 1 L2 0 L1 R1 R2 0 0 0 Center Here L=2 R=4 R3 0 R4 0 Right 3. 4. Page 7 of 17 Line Follower Implementation Sensor Circuit: To get a good voltage swing , the value of R1 must be carefully chosen. If Rsensor = a when no light falls on it and Rsensor = b when light falls on it. The difference in the two potentials is: Vcc * { a/(a+R1) - b/(b+R1) } Relative voltage swing = Actual Voltage Swing / Vcc = Vcc * { a/(a+R1) - b/(b+R1) } / Vcc = a/(a+R1) - b/(b+R1) Page 8 of 17 Line Follower The sensor I used had a = 930 K and b = 36 K. If we plot a curve of the voltage swing over a range of values of R1 we can see that the maximum swing is obtained at R1= 150 K (use calculus for an accurate value). There is a catch though, with such high resistance, the current is very small and hence susceptible to be distorted by noise. The solution is to strike a balance between sensitivity and noise immunity. I chose value of R1 as 60 K. Your choice would depend on the ‘a’ and ‘b’ values of your sensor. If you found this part confusing, use a 10K resistor straightaway, as long as you are using a comparator it won’t matter much. Motor Interface and Control Circuit: The 8 sensors are connected to PORTA. You need not connect anything to AVCC and AREF, it is required only if ADC is used. Page 9 of 17 Line Follower without frying it. L298 on the other hand works happily at 16V without a heat sink, though it is always better to use one. Internal Schematic of L298 Truth Table for controlling the direction of motion of a DC motor Page 10 of 17 Line Follower Source Code /***************************************************** Project : Line Follower Version : Date : 2/19/2006 Author : Priyank Company : Home Comments: Chip type : ATmega16 Program type : Application Clock frequency : 7.372800 MHz Memory model : Small External SRAM size : 0 Data Stack size : 256 *****************************************************/ //#define debug 1 #include <mega16.h> #include <delay.h> #ifdef debug #include <stdio.h> #endif #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define FWD 0xAA REV 0x55 R 0x22 L 0x88 CW 0x99 CCW 0x66 STOP 0x00 B 0xFF RSPEED OCR1AL LSPEED OCR1BL SPEED0 255 SPEED1 0 SPEED2 0 SPEED3 0 MAX 3 HMAX 1 void move (unsigned char dir,unsigned char delay,unsigned char power); unsigned char i,rdev,ldev,ip,delay,dir,power,dirl,history[MAX],hcount=0,rotpow; #ifdef debug unsigned char rep=0,prev=0; #endif void main(void) { // Input/Output Ports initialization // Port A initialization // Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In Page 11 of 17 Line Follower // State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T PORTA=0x00; DDRA=0x00; // PortB=0x00; DDRB=0x00; // PortC=0x00; DDRC=0xFF; // Port D initialization // Func7=In Func6=In Func5=Out Func4=Out Func3=In Func2=In Func1=In Func0=In // State7=T State6=T State5=0 State4=0 State3=T State2=T State1=T State0=T PORTD=0x00; DDRD=0x30; // Timer/Counter 0 initialization // Clock source: System Clock // Clock value: Timer 0 Stopped // Mode: Normal top=FFh // OC0 output: Disconnected TCCR0=0x00; TCNT0=0x00; OCR0=0x00; // Timer/Counter 1 initialization // Clock source: System Clock // Clock value: 921.600 kHz // Mode: Fast PWM top=00FFh // OC1A output: Non-Inv. // OC1B output: Non-Inv. // Noise Canceler: Off // Input Capture on Falling Edge TCCR1A=0xA1; TCCR1B=0x0A; TCNT1H=0x00; TCNT1L=0x00; ICR1H=0x00; ICR1L=0x00; OCR1AH=0x00; OCR1AL=0xFF; OCR1BH=0x00; OCR1BL=0xFF; // Timer/Counter 2 initialization // Clock source: System Clock // Clock value: Timer 2 Stopped // Mode: Normal top=FFh // OC2 output: Disconnected ASSR=0x00; TCCR2=0x00; Page 12 of 17 Line Follower TCNT2=0x00; OCR2=0x00; // External Interrupt(s) initialization // INT0: Off // INT1: Off // INT2: Off MCUCR=0x00; MCUCSR=0x00; #ifdef debug // USART initialization // Communication Parameters: 8 Data, 1 Stop, No Parity // USART Receiver: On // USART Transmitter: On // USART Mode: Asynchronous // USART Baud rate: 57600 UCSRA=0x00; UCSRB=0x18; UCSRC=0x86; UBRRH=0x00; UBRRL=0x07; #endif // Timer(s)/Counter(s) Interrupt(s) initialization TIMSK=0x00; // Analog Comparator initialization // Analog Comparator: Off // Analog Comparator Input Capture by Timer/Counter 1: Off ACSR=0x80; SFIOR=0x00; while (1){ #ifdef debug if(rep<255) rep++; if(prev!=PINA) { prev=PINA; printf("%u\r",rep); for(i=0;i<8;i++) printf("%u\t",(prev>>i)&0x01); rep=0; } #endif if(PINA!=255){ rotpow=255; ldev=rdev=0; if(PINA.3==0) rdev=1; if(PINA.2==0) rdev=2; if(PINA.1==0) rdev=3; Page 13 of 17 Line Follower if(PINA.0==0) rdev=4; if(PINA.4==0) ldev=1; if(PINA.5==0) ldev=2; if(PINA.6==0) ldev=3; if(PINA.7==0) ldev=4; if(rdev>ldev) move(R,0,195+12*rdev); if(rdev<ldev) move(L,0,195+12*ldev); if(rdev==ldev) move(FWD,0,200); } else { for(i=0,dirl=0;i<MAX;i++) { if(history[i]==L) {dirl++;} } if(rotpow<160) {rotpow=160;} if(rotpow<255) {rotpow++;} if(dirl>HMAX) {move(CW,0,rotpow);} else {move(CCW,0,rotpow);} } }; } void move (unsigned char dir,unsigned char delay,unsigned char power) { PORTC=dir; if(dir==L || dir==R) { hcount=(hcount+1)%MAX; history[hcount]=dir; } LSPEED=RSPEED=255;//power; //delay_ms(delay); } Possible Improvements: -Use of differential steering with gradual change in wheel speeds. -Use of Hysteresis in sensor circuit using LM339 -Use of ADC so that the exact position of the line can be interpolated -Use of Wheel Chair or three wheel drive to reduce traction. -General improvements like using a low dropout voltage regulator, lighter chassis etc Page 14 of 17 Line Follower References and Resources Books: Programming and Customizing the AVR Microcontroller – Dhananjay V. Gadre Parallel Port Complete – Jan Axelson Atmel Corp. Makers of the AVR microcontroller AVRbeginners.net AVR assembler tutorial Tutorial for learning assembly language for the AVR-Single-Chip-Processors AT90Sxxxx from ATMEL with practical examples. One of the best sites AVR sites WinAVR An open source C compiler for AVR PonyProg A widely used programmer. Support for newer chips is added periodically. Can also program PICs and EEPROMS Basic Electronics Williamson Labs Nice animated tutorials, articles and project ideas. Small Robot Sensors Robotics India An Indian site devoted to robotics. Must see Seattle Robotics Society Links: Page 15 of 17 Line Follower Line Follower ROBOT Award winner from VingPeaw Competition 2543, the robot built with 2051, L293D, and four IR sensors. Simple circuit and platform, quick tracking and Easy to understand program using C language. Tools: AVR Studio For writing code in assembly and simulation of code. Current versions has AVR-GCC plug-in to write code in C. Compilers: IAR, Image Craft , Code Vision AVR, WinAVR Programmers: Pony Prog, AVR Dude, AVRISP and many more. Shops: Evaluation Boards: STK200, STK500 from Kanda Systems Motors: 1. Mechtex - Mulund, Mumbai 2. Servo Electronics - Lamington road, Mumbai Phone:56346573 3. Bombay Electronics - Lamington Road, Mumbai Electronics: 1. Visha Electronics - Lamington road, Mumbai [Programmer for 8051, PIC and AVR available] Phone: 23862650 / 23862622 2. Gala Electronics - Lamington road, Mumbai 3. Chip Components - Lamington road, Mumbai Telephone: 56390468 / 56587005 Parts and Prices: Part Approximate Price in Indian Rupees 1.00 5.00 3.00 7.00 0.25 to 2.00 2.00 to 20.00 Or more 0.25 2.50 8.00 40 to 450 40 60 150 120 Visible Light Leds White or Bicoloured IR LED IR Sensor Capacitor (small values) Capacitor (large values / electrolytic) Resistors (1/4 W) Variable Resistor (Preset) Variable Resistor (Pot) Microcontrollers AT89C2051 (8051 Core) AT89C51 (8051 Core) AT89S52 (8051 Core) PIC16F84A (PIC Core) Page 16 of 17 Line Follower ATmega8 (AVR Core) ATmega16 (AVR Core) ATmega32 (AVR Core) ATmega128 (AVR Core) Transistors Low power Eg: BC547 Power Transistor Eg: TIP31C Connectors Optocoupler (MCT2E) Common Tools Soldering Iron Solder metal Solder Flux Desoldering Wick Breadboard Wire Stripper Common ICs Voltage Regulators (78XX), LM324,IC555 etc MAX232 ULN 2003 / ULN 2803 TSOP17XX L298, L293, L293D IC Programmers Homemade (Support fewer devices, support only serial programming, not as rugged) Eg: PonyProg ( ) Readymade (Support many chips, support parallel programming, easy to use, rugged) Wireless Modules Parallel Port / Serial Port Add on Card for PC Universal PCB 700.00 500.00 10.00 to 50.00 90 150 300 425 1.50 to 15 or more 1.50 15.00 1.00 per pin 8.00 150 (typical) to 400 25.00 5.00 5.00 80.00 to 100.00 25.00 5.00 20.00 14.50 17.00 70.00 20.00 to 80.00 2500 to 25000 You may drop your feedback at priyank.patil@gmail.com . Priyank Patil KJ Somaiya CoE – Information Technology VidyaVihar, Mumbai Page 17 of 17 This action might not be possible to undo. Are you sure you want to continue? We've moved you to where you read on your other device. Get the full title to continue listening from where you left off, or restart the preview.
https://www.scribd.com/doc/56846304/Follower
CC-MAIN-2016-30
refinedweb
2,556
62.17
Handling ajax request in WebForms Elegant way to do AJAX in WebForms In case you want to add JQuery Ajax calls to your page, you would basically need to add one more page which will be invoked with Ajax call. In order to reduce number of physical pages you can reuse the same page, but make it act differently for normal GET/POST HTTP request and totally different for Ajax GET/POST HTTP request. To determine whether request is AJAX or not you can use extension method described in this article. The main idea is to render one content for normal and one for AJAX request. For this purpose we use placeholder for rendering AJAX content. Handling of request should be done on Page_Init handle. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Asp.Net; using System.IO; public partial class _Default : System.Web.UI.Page { protected void Page_Init(object sender, EventArgs e) { if (Request.IsAjaxRequest()) { Response.Clear(); StringWriter sw = new StringWriter(); this.phAjaxContent.Visible = true; this.phAjaxContent.RenderControl(new HtmlTextWriter(sw)); Response.Write(sw.ToString()); Response.End(); } } } Extension method IsAjaxRequest is coming from custom library Asp.Net which I build and which is contained in attachment for this article. This extension method is described in this article. You can add it it to you own dll, compile it and use the same way it is used here. Disclaimer Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.
http://dejanstojanovic.net/aspnet/2014/march/handling-ajax-request-in-webforms/
CC-MAIN-2017-34
refinedweb
281
60.82
Re: Exception Handling, DivideByZero .WHAT gives you the actual type, whereas .^name gives you a string that is the name. In Perl6 types are things you can pass around; which is good because you can have more than one with the same name. sub bar (){ my class Foo { } } sub baz (){ my class Foo { } } a necessary no-op I've got a weird one here... a line that looks like it does nothing significant is needed for the code to work. If the line below marked "The Mystery Line" is commented out, you just get the error: ===SORRY!=== Cannot look up attributes in a VMNull type object Augment::Util: class Re: a necessary no-op What jumps out to me is the difference between a normal method and a metamethod; the latter might not do sufficient validation, so you're catching the exception from trying to invoke .gist. And that just happens to do the right thing in your case; if you're getting a VMNull from an Exception Handling, DivideByZero I was just looking into doing some finer-grained exception handling, so I tried this: use v6; try { my $result = 4/0; say "result: $result"; CATCH { #when DivideByZero { say "Oh, you know."; } default { say .WHAT; .Str.say } # (DivideByZero) Re: Exception Handling, DivideByZero Two issues: (1) all standard exceptions are in or under the X:: namespace. (2) .WHAT doesn't show names with their namespaces, whereas .^name does. pyanfar Z$ 6 'my $r = 4/0; say $r; CATCH {default {say .^name}}' X::Numeric::DivideByZero On Mon, Oct 29, 2018 at 1:04 PM Joseph Brenner wrote: Re: Exception Handling, DivideByZero Brandon Allbery wrote: > Two issues: > > (1) all standard exceptions are in or under the X:: namespace. > > (2) .WHAT doesn't show names with their namespaces, whereas .^name does. > > pyanfar Z$ 6 'my $r = 4/0; say $r; CATCH {default {say .^name}}' > X::Numeric::DivideByZero Thanks. I didn't
https://www.mail-archive.com/search?l=perl6-users@perl.org&amp;q=date:20181029
CC-MAIN-2019-22
refinedweb
317
69.52
etree.tostring(): XML pretty printing does not work on non-indented XML files. Bug Description Pretty printing an XML file via lxml.etree. These means no indentation will be applied corresponding lines/elements according to the XML tree depth level. EXAMPLE: from lxm import etree from lxm import objectify xmldoc = """\ <root> <alice /> <bob /> </root> """ root = etree.fromstrin formatted = etree.tostring( expected = """\ <root> <alice /> <bob /> </root> """ assert expected == formatted, "OOPS, fails." # -- VARIANT 2: formatted = etree.tostring( WORKAROUND: Formatting/pretty printing works when you create the "root" object via lxml.objectify. Just replace the following line in the example from above: root = objectify. VERSION-INFO: Python : (2, 6, 6, 'final', 0) lxml.etree : (2, 3, 2, 0) libxml used : (2, 7, 3) libxml compiled : (2, 7, 3) libxslt used : (1, 1, 24) libxslt compiled : (1, 1, 24) From my point of view, you can close the issue (if you don't think it is important). I will use the work-around, that is described above, for my purposes. I just think it is a little bit weird, because "xmllint --format" just provides the desired behavior (xmllint is bundled w/ libxml2). Thanks for the pointer into the FAQ. I must have overlooked it (who is reading the manuals anyway ,-). I must agree that it's quite complicated to have xml pretty printed thanks to lxml. And that's a shame. Even objectify will have cases where some subelement won't be prettified. Sadly, the best solution for me is to pipe result in xmllint --format. I understand the fact unveilled in the FAQ, but it seems quite obvious for me that you won't use the pretty_print fonctionality if space are meaningfull for you. If space is not meaningful to you, you should use the "remove_blank_text" option in the parser and/or use a DTD. It's more of a parser issue than a serialiser issue, really. And lxml can't know during parsing that you are going to ask for pretty printing during serialisation. This doesn't really have much to do with lxml. http:// lxml.de/ FAQ.html# why-doesn- t-the-pretty- print-option- reformat- my-xml- output I'm inclined to close this as "won't fix". While lxml could potentially influence the heuristic here, I don't think there is a right way to do it.
https://bugs.launchpad.net/lxml/+bug/910018
CC-MAIN-2016-18
refinedweb
388
66.03
Hi guys, I'm both new here, and new to c++ so be gentle! Over the past short time we've been looking at c++ on our course, but I don't believe it has been taught too well, and I'm struggling to understand what should really be basic concepts? An assignment we've been issued with asks us to enter the details of 40 hills randomly in the form of a linked list (so the details would automatically be inserted randomly). Then further to that, the linked list trasnferred into an array then sorted. (displayed in the cout) The problem I'm having is I don't know where to start - I've used and modified code from an earlier lab session, but I'm at my wits end trying to understand it and work out how to do what I want. Here is the code from my header file to show the struct I've setup, but I've no idea how to take it to the level that's expected of me. If anyone can help or provide any pointers I'd be very greatful - as I'm really hoping to do well in learning c++ beyond this assisgnemt. #include <iostream> using namespace std; //define a node as a structure struct Hills{ //a structure that can be int hillsize; int gridref; int distanceFromHome; bool climbed; //thought of as a simple class Hills *link; //All fields are public }; class LinkedList{ //now declare the class private: Hills *head; //pointer to the first node Hills *last; //pointer to the last node int count; //number of nodes public: LinkedList(); //constructor void insertNodeAtStart(int newinfo); // inserts a node at start of list void insertNodeAtEnd(int newinfo); // inserts a node at end of list int getNodeCount(); //returns the number of nodes Hills* getFirst(); //returns the pointer to the //the first node - the value of "head" void deleteFirstNode(); //deletes the first node in the list bool findNumber(int number); //Q6 see if "number" is in the list void deleteNode(int number); //Q7 delete a node with "number" as its data }; //end of class declarations. REMEMBER THE SEMICOLON Thanks in advance
https://www.daniweb.com/programming/software-development/threads/121383/linked-list-help
CC-MAIN-2017-09
refinedweb
357
58.59
Problem Formulation and Solution Overview MediTech, a pharmaceutical manufacturing company, is seeking the best way to save its drug test results. They have contacted you to provide possible solutions. Integers to write to a file: Method 1: Use open() This option shows you how to create a new file and save a single integer or list of integers to a flat-text file. Example 1 – Single Integer nums = [32423, 30902, 28153, 31651, 36795, 28939, 26144, 21940] fp = open('nums_method_1a.txt', 'w') fp.write('{}'.format(nums[3])) fp.close() Above, a list of integers is declared ( nums). Then, a new flat-text file ( nums_method_01a.txt) is created and opened in write ( w) mode. Next, the highlighted line uses the format() function to convert the single element ( nums[3]) to a string and write it to the text file indicated above. Finally, fp.close() is called to close the open connection. If successful, nums_method_01a.txt contains the following: Example 2 – Multiple Integers In this example, we break out of the list format and save the results as a string. nums = [32423, 30902, 28153, 31651, 36795, 28939, 26144, 21940] fp = open('nums_method_1b.txt', 'w') tmp = (','.join(str(n)for n in nums)) fp.write('{}'.format(tmp)) fp.close() Above, a list of integers is declared ( nums). Then, a new flat-text file ( nums_method_01b.txt) is created and opened in write ( w) mode. Next, the join() method is called and does the following: - Uses the for loop to iterate through numselements. - Converts each element to a string. - Places a separating comma ( ,) between each. - Returns a formatted string and saves it to tmp. The contents of tmp are written to the text file indicated above. Finally, fp.close() is called to close the open connection. If successful, nums_method_01b.txt contains the following: Method 2: Use NumPy This option calls the NumPy library to save the data to a CSV. Click here for NumPy installation instructions. import numpy as np nums = [32423, 30902, 28153, 31651, 36795, 28939, 26144, 21940] nums.insert(0,'Integers') np.savetxt('nums_method_2a.csv', nums, delimiter=" ", fmt='% s') Above, the first line calls in the NumPy library. Then, a list of integers is declared ( nums). Next, let’s create a header row containing one (1) column for the CSV file and insert it at the first position of nums. The contents of nums is now: Then, the np.savetext() function is called and passed the following arguments: - The file’s name to save the data to ( nums_method_2a.csv). - The array containing the data. In this case, nums. - The delimiter – the string or character separating the columns ( delimiter=" "). - The string format of the converted integers ( fmt='% s'). If successful, nums_method_02a.csv contains the following: 💡Note: The delimiter is not required for this example and produces the same results with or without this argument. Method 3: Use Pandas This option uses the Pandas library csv to create a new file and save it to a CSV. Click here for Pandas installation instructions. import csv nums = [32423, 30902, 28153, 31651, 36795, 28939, 26144, 21940] str_nums = [str(x) for x in nums] with open('method_3a.csv', 'w', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerow(str_nums) Above, the first line calls in csv ( import csv), which is available through the Pandas library. This is needed to write the data to a CSV. Then, a list of integers is declared ( nums). Before continuing, these values need to be converted to strings. A one-liner ( [str(x) for x in nums]) does the trick! The results save to str_nums. Next, the file method_3a.csv is opened in write ( w) mode, assigns the newline character as an empty ( '') string and creates an object ( csvfile). This object is assigned to writer and then the writer.writerow() function is called and passed the argument str_nums. If successful, nums_method_03a.csv contains the following: 💡Note: For this example, only one (1) row was written to the CSV so was used. However, to write more than one (1) line, use writer.writerow() . writer.writerows() Method 4: Use a One-Liner This option uses Python’s infamous One-Liner to convert the nums list into a string and write it to a flat-text file in one fell swoop! nums = [32423, 30902, 28153, 31651, 36795, 28939, 26144, 21940] print(*nums, sep=",", file=open('nums_method_4a.txt', 'w')) Above, the first line declares a list of integers ( nums). Next, the print() statement is called and does the following: - Reads in nums. - Let the print()statement know that the numselements are separated with a comma ( ,) character. - Creates and opens the nums_method_4a.txtfile in write ( w) mode. - Saves all numsstring elements to the above file. If successful, contains the following: nums_method_4a.txt 🌟A Finxter Favorite!
https://blog.finxter.com/how-to-write-integers-to-a-file/
CC-MAIN-2022-33
refinedweb
786
68.77
In-Depth Who among us has ever written an application that didn't consume or save data? If we had a show of hands, I doubt the number would be very high. Except for some UI libraries I wrote about 18 years ago, I can't recall a single application that didn't require me to read data from some source or write data back to some storage system. Agreed, it wasn't always a true relational database like SQL Server, but it was data storage nonetheless. Device applications -- whether kiosk-based or mobile handheld devices -- are typically used as data-collection devices. A handheld device might scan products on a store shelf, and a kiosk could collect data about the interests of users responding to a survey -- or even provide information about the area around the kiosk, from a database of information. To write a useful device application, you'll need to understand how to collect and store data and then how to move it to another location -- a server, for example -- where the data can be used and viewed by others. To accomplish this, we'll use SQL Server 2005 Compact Edition. One of the benefits of using SQL Server Compact Edition is that we can use the same application code in a device application or desktop application. The resulting database file can also be migrated from a mobile application scenario to a desktop scenario that may include a server or multiple users. Earlier versions of mobile SQL database limited the database to a single connection for use only on a device. Theses limitations have since been eliminated; the database can start on a mobile device and used to collect data, and then the entire database file can be moved to the desktop for analysis and sharing on other systems. Another problem with some older versions of SQL mobile databases was that there was no easy way to create and edit the physical database file. You either had to do it via code or by using the query analyzer on the device. Neither of those was a very good option. SQL Server 2005 Compact Edition databases can now be created and managed using the SQL Server Management Studio. But enough background. Open Visual Studio and create a new Windows Mobile 6 Professional application. Once the solution has been built, open SQL Server Management Studio and create a new SQL Server 2005 Compact Edition database. Notice in Figure 1, below, that you have a choice to encrypt the database or to password-protect the data file. If you protect your database with a password, your connection string must include the password in order for a connection to be made. However, data inside the file itself could still be viewed if the file was opened in a text editor. The encrypt option applies 128-bit encryption to the contents of the file, preventing anyone who may get a copy of the file from viewing any of the data. We won't cover how to create the individual field of the database in this article, but a completed database is in the sample code that accompanies this one. The first thing you need to do when using SQL Compact Edition is to build the connection string and then open the connection. The connection string is very simple for an unprotected database; it's no more than the path to the database file, as shown in Listing 1. It might be tempting to hardcode the connection string to a particular location, but that's just looking for trouble. In this code, we get the location of the executing application and append the database name. Now, here's a common question: Do we leave the connection open or do we close it after each call to the database? Previously, due to the single connection limit, it was always best to open a connection, use it and immediately close it so that any other thread could then access the file. With the new multiple connections allowed in Compact Edition, it's possible to leave the connection open for the duration of an application, or at least for more than a single-execute operation. If you wanted to use the connection and immediately close it, the code would look as shown in Listing 2. This is one of those "personal choices" that each developer or company must make. You might even choose to do it differently from application to application. Once the connection has been made and opened, data is retrieved from the database as shown in Listing 3. The SqlServerCe namespace provides a SqlCeResultSet which is the best of both the DataSet and the DataReader. It has the speed of a DataReader, as well as the update and scroll capabilities of the DataSet. Now that you see how easy it is to retrieve data from the database, let's see about putting data back into the database. The first technique uses the SqlCeResultSet class. The class has a CreateRecord method that creates a new, blank record in the recordset which is filled in using a series of Set methods, as shown in Listing 4. If you prefer the more tried-and-true method of T-SQL code, you also have that option, as shown in Listing 5. Those are the basics of using SQL Server 2005 Compact Edition. Of course, there's much more to learn; this article covers only a very small portion of data stored on a device. There are still more details regarding the use of SQL CE on the device, as well as how to implement the Client Factory Data namespace (Patterns and Practices). And once we get data onto the device, how do we, other than copying the database file directly, get the data back to a full SQL Server -- or anywhere else, for that matter? We'll answer these questions and more in the coming weeks.Library I agree to this site's Privacy Policy.
https://visualstudiomagazine.com/articles/2007/08/01/data-data-everywhere-data.aspx
CC-MAIN-2018-51
refinedweb
997
58.92
In many games, tabletop or otherwise, there are a series of positions, board states, or other features that occur in some kind of order. In monopoly, for example, you travel in a circle. Each property is a ‘state’ that your piece (battleship!) can be in. In something like Candyland, Chutes and Ladders, or Mr. Bacon’s Big Adventure, there is a goal state to reach, and you do things (roll die, draw cards, etc.) to try to get there. What makes these more complicated than say, just figuring the combined probability of rolling a certain sum for many die, is that the game states branch. Branching just means that you can reach more than 1 state after your current one. Markov Chains are a powerful tool for analyzing a game’s progress through it states, and this post will show you an example of that, using the game Betrayal at House on the Hill. Markov Chains Markov chains (MCs) are fairly simple in their concept. An MC contains a finite number of states (it doesn’t have to, but we don’t have to worry about that) in its state space. For Monopoly, the state space could be all the spots that you can land on. For Zombie Dice, it could be the number of brains, shotguns, and the set of die in the cup. The other property that an MC needs to have is that it must be ‘memoryless’. By ‘memoryless’, we just mean that the probabilities of transitioning from the current state to a new state do not depend on the sequence of events that got us to the current state. In Monopoly, it doesn’t matter how you got to Park Place. The chances of passing GO are the same no matter what. Markov Chains work in ‘steps’ or ‘turns’. Given a current state, the MC will tell you (with a matrix multiplication) what states you might end up in, and with what probabilities. If you repeat that for several turns, you’ll build a probability distribution of which game states you might end up in. Absorbing Markov Chains It is possible for a state to return to itself with some probability. In Monopoly, there is a chance that you stay in jail a couple of turns. That’s based on the probability of rolling doubles. If a state returns to itself with a probability of 1 (in other words, that state cannot be exited), then it is called absorbing. Absorbing MCs are analyzed in a bit different way. Regular MCs can be used to find a ‘steady state distribution’, which is just the probability of being in every state after an infinite number of moves. Absorbing MCs don’t have a steady state, because after an infinite number of moves, you can only be in one of the absorbing states. What you can find, though, are things like the expected number of moves to ‘absorb’. If you have a game with a goal state, this lets you calculate how many turns it might take to win on average! Some Markov Math Markov chains are built around what is called a transition matrix. For obvious reasons, I like to call that matrix The matrix is an matrix, where is the number of states. The entry represents the probability of moving from state to state . The sum of each row must equal 1: This just follows the rules of probabilities and state spaces. A state cannot have anything other than a probability of 1 to transition during each step. Absorbing states transition only to themselves. The only other thing to cover right now is how to do states. Markov chains use a row vector with entries to represent the probabilities of being in any state. This vector is usually denoted as . The th entry of equals the probability that you are in state . To take a step (from the 0th turn to the 1st turn) in the MC, we just do: This generalizes to, for turns: That covers the real basics. Let’s move on to an actual game! Betrayal! The Rules (that we care about) Full disclosure: I’ve never actually played Betrayal at House on the Hill. From reading about it, though, it looks like a really fun game! There was a question on the boardgame subreddit about the chances of meeting certain conditions on a roll (side note, Reddit user zebraman7 has been asking several game math problems, which you should try on your own!). The question was already solved, but there was a lot of talk about a key mechanic in the game. In Betrayal, players explore rooms (that are drawn from a pile) on their turns. Based on how far they can walk, they can open up new rooms. New rooms contain symbols that direct the player to draw certain kinds of cards and act on them. One set of cards is the ‘Omen’ set. Omens control an important game transition. Every time a player pulls an omen card, they must roll 6 die (each with sides 0,0,1,1,2,2). If the sum is less than the number of omen cards that have been drawn, then the game changes phases (a haunting happens). I was curious about how many turns it might take to reach that phase change. Thinking Markov A Markov chain is a good idea for answering that question because we have the following features in the question: - Probabilities of getting omen cards - Probabilities of not getting omen cards - Probabilities of rolling certain sums (that can cause the game to change - A defined goal state (the state after failing a roll on an omen card) We need to figure out what the states are going to be. It would be incredibly complex (and require defining a strategy) to keep track of each player and worry about the probabilities (or desires) for actually opening up new rooms! To avoid this, we will assume that on every turn, someone opens up a new room. Notice that this means that any estimates for the number of turns will be a lower bounds, relative to real game play. With that assumption, we can define a state as: (number of omen rooms in play, number of rooms in play). With those two values, we can calculate the probability of drawing an omen or non-omen card. Making the States I made the states using the following python code. There are 13 omen rooms in 45 total rooms. I assumed that the starting room the same each time (based on the tutorial on their site), so I knocked down the room count to be 44 draw-able rooms. n_rooms = 44 states = [(0,0)] for state in states: n_omen = state[0] n_cards = state[1] omen_left = 13-n_omen non_omen_left = n_rooms-n_cards-omen_left if omen_left > 1: # then we can draw an omen v = (n_omen+1,n_cards+1) if v not in states: states.append(v) if non_omen_left >= 1: # then we can draw a card v = (n_omen,n_cards+1) if v not in states: states.append(v) states.append("haunting") Once you reach 13 omens you can’t win, so I ignored states with 13 omens. This gives us 417 possible game states! Building the Transition Matrix To build the matrix, I looped over each state and calculated the probabilities of moving to the states that it could move to (add 1 omen and roll high, add 1 room, or add 1 omen and roll low). I used Python’s fractions library to try to avoid the usual floating point errors that plague this sort of thing, but NumPy arrays convert them right to floats. The error is small, so I just ignored it. import numpy as np # Not shown: making the roll_probs dictionary. That dictionary # just contains the probability of rolling a particular sum # ... n_states = len(states) T = np.zeros((n_states,n_states)) for i,u in enumerate(states): if u == "haunting": # this is the absorbing goal state T[i,i] = 1.0 else: # get the probability of drawing an omen card p_omen = fractions.Fraction(13-u[0],n_rooms-u[1]) if u[0] + 1 <= 12: v = (u[0]+1,u[1]+1) p_survive = sum(p for val,p in roll_probs.items() if val >= u[0]+1) j = states.index(v) T[i,j] = p_omen*p_survive # set the probability of the haunt hitting T[i,-1] = p_omen*(1-p_survive) elif u[0]+1 == 13: # then we lose no matter what on an omen draw T[i,-1] = p_omen # the probability of drawing a non-omen room # we can only add non-omen rooms if there are any to add if u[1] + 1 <= n_rooms and u[1] + 1 <= n_rooms-(13-u[0]): v = (u[0],u[1]+1) j = states.index(v) T[i,j] += 1-p_omen Calculation! With the transition matrix in hand, we can start doing estimations of various kinds. Let’s start by finding out where we might be after two turns of drawing rooms. To find this, we do (in math, then code): init_state = np.zeros(n_states) # we put a 1 in the first index to indicate that we are in the first state init_state[0] = 1 final_state = np.dot(init_state,np.linalg.matrix_power(T,2)) These are the results, which show the states that can be reached in 2 steps, along with the probability that we are in those states: End state : Probability ------------------------ (2, 2) : 0.0815 (1, 2) : 0.4254 (0, 2) : 0.4915 'haunting' : 0.0015 Note how unlikely it is to reach the haunting stage this early. It’s also fairly unlikely to draw two omen rooms in a row, since we have a full stack of room cards. We can repeat this for all the possible turn numbers. Remember that we can’t take more than 44 turns. At the 44th turn (if we somehow get there) we would pull an omen room and not be able to win the roll. Using the following code to get the probabilities of being in the final state for each turn length: init_state = np.zeros(n_states) init_state[0] = 1 curr_state = init_state turn_probs = [] for n_turns in xrange(n_rooms+1): next_state = np.dot(curr_state,T) turn_probs.append(next_state[-1]) curr_state = next_state The probabilities that we just got are shown below: It looks like we reach a 50/50 shot of the game phase change around 18 to 19 turns. In other words, after 18 turns you’re nearly equally likely to still be un-haunted as you are likely to have reached the haunted state. Absorption Chances When working with an absorbing MC, there is some nice math that lets us get what is called the matrix. That matrix gives the expected number of visits to a transient (non-absorbing) state j starting from a transient state i (before being absorbed). We use that matrix to get a vector, which is a vector of the expected number of steps it will take to get from state i to absorption (reaching our goal). The first entry of that vector is the expected number of turns to reach the game phase shift. Here’s the code to get that vector: Q = T[:-1,:-1] R = T[:-1,-1].T Ir = np.array([[1]]) N = np.linalg.inv(np.eye(n_states-1)-Q) t = np.dot(N,np.ones(n_states-1)) # the expected number of turns t[0] The result is that we expect 19.38 turns, on average, until the phase shifts. Remember that this is a conservative estimate due to our simplifying rules. We could have also found that number by recognizing that the plot we made above is a Cumulative Distribution Function (CDF). We can convert that to the Probability Mass Function (PMF), because the difference between each CDF point is the PMF value. That gives us this PMF: The expected value of that PMF is 19.38! What’s neat about this is that it shows how the matrix math we just did essentially builds PMFs for each state, and then does the weighted summation to get the expected value. Chances of Reaching Other States The chances of reaching 32 or more turns looks really slim. We can use the chart from above to calculate the chance of reaching one of those turns. All we have to do is recognize that 1 minus the CDF of haunting by a turn is the probability of reaching that turn. Here’s the CDF of probabilities for reaching at least a given turn: Notice that we have a 100% chance of getting more than 1 turn, so we’ve done the math right. We only have a ~10% of getting 28 turns or more. For 32 turns or more, that probability is 2.31%! Finally, let’s get the probability for reaching what is probably a very unlikely state: only omen rooms left in the pile. Using the matrix that the wiki page references, we get the probability of reaching that state to be: 1.926e-11. If you’re seeing that, someone probably stacked the deck. Wrap-Up We’ve seen how Markov Chains can be used to estimate properties of playing games, especially turn counts and probabilities of being in a given state. I think some of the key takeaways are: - It’s OK to simplify a problem to make it tractable by MC methods - The hardest part is defining the states. The rest is just basic probability and some matrix math - Goal states (absorbing chains) are the key to letting us find out things like “how many turns should I expect to take”, which is a big question for planning in games - To be discussed: Markov Chains are best for understanding very low probability events I recommend also simulating with Monte Carlo and comparing the results. It’s also helpful to compare the time it takes to code and run these things, because that’ll help you decide which methods you prefer! Keep in mind things like accuracy and state space coverage. With the probability of having only all the omens left in the stack being so small, how many Monte Carlo runs would it take for you to find it? Finally, let the Markov stuff be a fun project to learn more about your favorite games, but don’t get bogged down in Analysis Paralysis. If you do play with someone who takes forever on a turn, this kind of method might help you plan how long your game will take!
https://phaethonprime.wordpress.com/2015/05/19/computational-methods-for-games-2-markov-chains/
CC-MAIN-2019-13
refinedweb
2,419
70.53
Asynchronous Task Execution Using Redis and Spring Boot Asynchronous Task Execution Using Redis and Spring Boot In this article, we are going to learn how to use Spring Boot 2.x and Redis to execute asynchronous tasks. Join the DZone community and get the full member experience.Join For Free In this article, we are going to learn how to use Spring Boot 2.x and Redis to execute asynchronous tasks, with the final code demonstrating the steps described in this post. You may also like: Spring and Threads: Async Spring/Spring Boot Spring is the most popular framework available for Java application development. As such, Spring has one of the largest open-source communities. Besides that, Spring provides extensive and up-to-date documentation that covers the inner workings of the framework and sample projects on their blog — there are 100K+ questions on StackOverflow. In the early days, Spring only supported XML-based configuration, and because of that, it was prone to many criticisms. Later, Spring introduced an annotation-based configuration that changed everything. Spring 3.0 was the first version that supported the annotation-based configuration. In 2014, Spring Boot 1.0 was released, completely changing how we look at the Spring framework ecosystem. A more detailed timeline can be found here. Redis Redis is one of the most popular NoSQL in-memory databases. Redis supports different types of data structures. Redis supports different types of data structures e.g. Set, Hash table, List, simple key-value pair just name a few. The latency of Redis call is sub-milliseconds, support of a replica set, etc. The latency of the Redis operation is sub-milliseconds that makes it even more attractive across the developer community. Why Asynchronous task execution A typical API call consists of five things - Execute one or more database(RDBMS/NoSQL) queries - One or more operations on some cache systems (In-Memory, Distributed, etc ) - Some computations (it could be some data crunching doing some math operations) - Calling some other service(s) (internal/external) - Schedule one or more tasks to be executed at a later time or immediately but in the background. A task can be scheduled at a later time for many reasons. For example, an invoice must be generated 7 days after the order creation or shipment. Similarly, email notifications need not be sent immediately, so we can make them delayed. With these real-world examples in mind, sometimes, we need to execute tasks asynchronously to reduce API response time. For example, if we delete 1K+ records at once, and if we delete all of these records in the same API call, then the API response time would be increased for sure. To reduce API response time, we can run a task in the background that would delete those records. Delayed Queue Whenever we schedule a task to run at a given time or at a certain interval, then we use cron jobs that are scheduled at a specific time or interval. We can run schedule tasks using different tools like UNIX style crontabs, Chronos, if we’re using Spring frameworks then it’s out of box Scheduled annotation ❤️. Most of the cron jobs find the records for when a particular action has to be taken, e.g. finding all shipments after seven days have elapsed and for which invoices were not generated. Most of these scheduling mechanisms suffer scaling problems, where we do scan database(s) to find the relevant rows/records. In many of the situations, this leads to a full table scan which performs very poor. Imagine the case where the same database is used by a real-time application and this batch processing system. As it's not scalable, we would need some scalable system that can execute tasks at a given time or interval without any performance problems. There are many ways to scale in this way, like run tasks in a batched fashion or operate tasks on a particular subset of users/regions. Another way could be to run a specific task at a given time without depending on other tasks, like serverless function. A delayed queue can be used in such cases where as soon as the timer reaches the scheduled time a job would be triggered. There’re many queuing systems/software available but very few of them provides this feature, like SQS which provides a delay of 15 minutes, not an arbitrary delay like 7 hours or 7 days, etc. Rqueue Rqueue is a message broker built for the spring framework that stores data in Redis and provides a mechanism to execute a task at any arbitrary delay. Rqueue is backed by Redis since Redis has some advantages over the widely used queuing systems like Kafka, SQS. In most of the web applications backend, Redis is used to store either cache data or for some other purpose. In today's world, 8.4% web applications are using the Redis database. Generally, for a queue, we use either Kafka/SQS or some other systems these systems bring an additional overhead in different dimensions e.g money which can be reduced to zero using Rqueue and Redis. Apart from the cost if we use Kafka then we need to do infrastructure setup, maintenance i.e. more ops, as most of the applications are already using Redis so we won’t have ops overhead, in fact, same Redis server/cluster can be used with Rqueue. Rqueue supports an arbitrary delay Message Delivery Rqueue guarantee at-least-once message delivery as long data is not lost in the database. Read about it more at Introducing Rqueue Tools we will need: 1. Any IDE 2. Gradle 3. Java 4. Redis We're going to use Spring Boot for simplicity. We'll create a Gradle project from the Spring Boot initializer at. For dependencies, we will need: 1. Spring Data Redis 2. Spring Web 3. Lombok and any others. The directory/folder structure is shown below: We’re going to use the Rqueue library to execute any tasks with any arbitrary delay. Rqueue is a Spring-based asynchronous task executor, that can execute tasks at any delay, it’s built upon the Spring messaging library and backed by Redis. We’ll add the dependency of Rqueue spring boot starter with com.github.sonus21:rqueue-spring-boot-starter:1.2-RELEASE dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-redis' implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'com.github.sonus21:rqueue-spring-boot-starter:1.2-RELEASE' compileOnly 'org.projectlombok:lombok' annotationProcessor 'org.projectlombok:lombok' providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat' testImplementation('org.springframework.boot:spring-boot-starter-test') { exclude group: 'org.junit.vintage', module: 'junit-vintage-engine' } } We need to enable Redis Spring Boot features. For testing purposes, we will enable WEB MVC as well. Update the application file as: @SpringBootApplication @EnableRedisRepositories @EnableWebMvc public class AsynchronousTaskExecutorApplication { public static void main(String[] args) { SpringApplication.run(AsynchronousTaskExecutorApplication.class, args); } } Adding tasks using Rqueue is very simple. We need to annotate a method with RqueueListener. The RqueuListener annotation has a few fields that can be set based on the use case. For delayed tasks, we need to set delayedQueue="true" and value must be provided; otherwise, it'll be ignored. The value is the name of a given queue. Set deadLetterQueue to push tasks to another queue. Otherwise, the task will be discarded on failure. We can also set how many times a task should be retried using the numRetries field. Create a Java file named MessageListener and add some methods to execute tasks: @Component @Slf4j public class MessageListener { @RqueueListener(value = "${email.queue.name}") (1) public void sendEmail(Email email) { log.info("Email {}", email); } @RqueueListener(delayedQueue = "true", value = "${invoice.queue.name}") (2) public void generateInvoice(Invoice invoice) { log.info("Invoice {}", invoice); } } We will need Invoice classes to store email and invoice data respectively. For simplicity, classes would only have a handful number of fields. Invoice.java: import lombok.Data; @Data @AllArgsConstructor @NoArgsConstructor public class Invoice { private String id; private String type; } import lombok.Data; @Data @AllArgsConstructor @NoArgsConstructor public class Email { private String email; private String subject; private String content; } Task Submissions A task can be submitted using the RqueueMessageSender bean. This has multiple methods to put a task depending on the use case. For example, for retry, use a method retry count, and then use delay for delayed tasks. We need to auto-wire RqueueMessageSender or use the constructor-based injection to inject these beans. Here's how to create a Controller for testing purposes. We're going to schedule invoice generation that can be done in 30 seconds. For this, we'll submit a task with 30000 (milliseconds) delay on the invoice queue. Also, we'll try to send an email that can be executed in the background. For this purpose, we'll add two GET methods, sendEmail and generateInvoice, we can use POST as well. @RestController @RequiredArgsConstructor(onConstructor = @__(@Autowired)) @Slf4j public class Controller { private @NonNull RqueueMessageSender rqueueMessageSender; @Value("${email.queue.name}") private String emailQueueName; @Value("${invoice.queue.name}") private String invoiceQueueName; @Value("${invoice.queue.delay}") private Long invoiceDelay; @GetMapping("email") public String sendEmail( @RequestParam String email, @RequestParam String subject, @RequestParam String content) { log.info("Sending email"); rqueueMessageSender.put(emailQueueName, new Email(email, subject, content)); return "Please check your inbox!"; } @GetMapping("invoice") public String generateInvoice(@RequestParam String id, @RequestParam String type) { log.info("Generate invoice"); rqueueMessageSender.put(invoiceQueueName, new Invoice(id, type), invoiceDelay); return "Invoice would be generated in " + invoiceDelay + " milliseconds"; } } Add the following in application.properties file: Now, we can run this application. Once the application starts successfully, you can browse this link. In the log, we can see the email task is being executed in the background: Below is invoice scheduling after 30 seconds: Conclusion We can now schedule tasks using Rqueue without much boiler code! We made important considerations when configuring and using the Rqueue library. One important thing to keep in mind is: Whether a task is a delayed task or not, by default, it's assumed that tasks need to be executed as soon as possible. The complete code for this post can be found at my GitHub repo. If you found this post helpful, please share it with your friends and colleagues, and don't forget to give it a thumbs up! Further Reading Spring Boot: Creating Asynchronous Methods Using @Async Annotation Spring and Threads: Async Distributed Tasks Execution and Scheduling in Java, Powered by Redis Published at DZone with permission of Sonu Kumar . See the original article here. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/asynchronous-task-executor-using-redis-and-spring
CC-MAIN-2019-51
refinedweb
1,778
57.06
As per the image above, cats and threads do no mix. Python and threads may not mix, either. Whilst thread-safety, dead-locks, queues and other nasties are nasty, Microsoft sees the world of n-cores as a software problem to be solved, not ignored. Both at a low-level and a high-level, well constructed and debugged Parallel libraries are appearing to make the splitting of tasks easier. IronPython implements the Python language on the DLR and subsequently on the CLR, but this does not automagically provide IronPython with threading and parallelism. Nor could I suggest that IronPython is the silver-bullet for clean parallelism with Python. Various projects such as ParallelPython (including cluster support), Stackless Python and the recent python-multiprocessing package are appearing to move CPython into today’s world of n-cores. IronPython does have kissing-cousin languages like F#. From F#, and the Microsoft Parallel Extensions Jun08 CTP – a parallel library is a .dll away. Step 1: create a .dll from Luca’s demonstration from PDC2008 specifically the MathLibrary/StockAnalyzer. Combining both the async/parallel versions of the F# code with the single-threaded version was easy. From IronPython: 1: import clr 2: clr.AddReferenceToFile("MathLibrary.dll") 3: import StockLibrary as StockLibrary 4: import sys, time 5: tickers = ['msft','adbe','aapl','ebay'] Line 1 imports the CLR so your code can import a .NET DLL (clr.AddReferenceToFile). The namespace is StockLibrary. Now methods within this DLL can be called. The fifth line sets up the four test Nasdaq codes we are analyzing. 6: analysersA = StockLibrary.StockAnalyzerParallel.GetAnalyzers (tickers, 365) 7: print ">> starting async" 8: start = time.clock() 9: for a in analysersA: 10: print a.Return 11: print "> seconds taken: ", time.clock() - start 12: print ">> completed" The analysersA instantiates the async/parallel version of the F# methods. Here I have wrapped the code with a simple time.clock() timer 13: analysersP = StockLibrary.StockAnalyzer.GetAnalyzers (tickers, 365) 14: print ">> starting normal" 15: start = time.clock() # get current time in seconds 16: for a in analysersP: 17: print a.Return 18: print "> seconds taken: ", time.clock() - start 19: print ">> completed" The analysersP (p for plain) uses the single-threaded version in the library. On General Melchett, my Intel Quadcore, I was able to execute the parallel version in 0.5s vs 11.0s in single-threaded mode. I suggest the 22x speed improvement comes from the Asyc calls to the network methods more than the calculations involved. More tests would be required to confirm the dramatic difference. In my example I am treating the F# DLL as a simple black box: a list of parameters in and single results out. In the real-world, careful consideration would need to be taken on the immutability of any Python objects/variables passed in; and the resulting factoring of code in F# vs. IronPython. (this was a simple 1 minute demonstration at the Edge of the Web Conference in Perth expanded into a blog post) #light // ASYNC version // note: you need to ensure the project has a reference to FSharp.PowerPack to work // async is difficult, here we change 4 lines, add some curly braces and we have async+parallel open System.Net open System.IO let internal loadPricesAsync ticker = async { // now returns async token let url = "" + ticker + "&d=10&e=3&f=2008&g=d&a=2&b=13&c=1986&ignore=.csv" let req = WebRequest.Create(url) let! resp = req.AsyncGetResponse() // holds the thread waiting for the network, blocked: so parallelize + asynch let stream = resp.GetResponseStream() let reader = new StreamReader(stream) let! csv = reader.AsyncReadToEnd() // holds the thread waiting for the network, blocked: so parallelize + asynch let prices = csv.Split([|'\n'|]) |> Seq.skip 1 |> Seq.map ( fun line -> line.Split([|','|]) ) |> Seq.filter (fun values -> values |> Seq.length = 7 ) |> Seq.map (fun values -> System.DateTime.Parse(values.[0]), float values.[6] ) return prices } // added async to let, add a return, look at places for release control, add bang and call Async versions type StockAnalyzerParallel (lprices, days) = let prices = lprices |> Seq.map snd |> Seq.take days // chop sequence to days static member GetAnalyzers (tickers, days) = tickers |> Seq.map loadPricesAsync |> Async.Parallel // now that loadPrices returns async, parallelize and run; then map |> Async.Run // now run in parallel |> Seq.map (fun prices -> new StockAnalyzerParallel (prices, days)) member s.Return = let lastPrice = prices |> Seq.nth 0 let startPrice = prices |> Seq.nth ( days - 1 ) lastPrice / startPrice - 1.0 member s.StdDev = let logRets = prices |> Seq.pairwise |> Seq.map ( fun (x, y) -> log (x / y)) let mean = logRets |> Seq.average let sqr x = x * x let var = logRets |> Seq.average_by (fun r -> sqr (r - mean)) sqrt var let internal loadPrices ticker = let url = "" + ticker + "&d=10&e=3&f=2008&g=d&a=2&b=13&c=1986&ignore=.csv" // code is identical to C# version as we are using underlying .Net libraries let req = WebRequest.Create(url) let resp = req.GetResponse() let stream = resp.GetResponseStream() let reader = new StreamReader(stream) let csv = reader.ReadToEnd() let prices = // returns a tuple based on comma csv.Split([|'\n'|]) //note [| syntax passes in .Net array to the string.Split method |> Seq.skip 1 |> Seq.map ( fun line -> line.Split([|','|]) ) // fun define anonymous function/lambda expression |> Seq.filter (fun values -> values |> Seq.length = 7 ) // filter out where less than 7 values |> Seq.map (fun values -> System.DateTime.Parse(values.[0]), // get the 0th and 6th column float values.[6] ) prices type StockAnalyzer (lprices, days) = let prices = lprices |> Seq.map snd |> Seq.take days // chop sequence to.0 member s.StdDev = let logRets = prices |> Seq.pairwise // sequence of things, first + second tuple; second + third etc |> Seq.map ( fun (x, y) -> log (x / y)) let mean = logRets |> Seq.average let sqr x = x * x let var = logRets |> Seq.average_by (fun r -> sqr (r - mean)) sqrt var
http://blogs.msdn.com/b/nickhodge/archive/2008/11/12/ironpython-f-parallel-async-a-kittehz-brekfst.aspx
CC-MAIN-2013-48
refinedweb
966
62.14
Key Takeaways - Most production applications need to persist & retrieve data. Prisma is a pretty genius way to achieve that. - With SvelteKit, you get client & server-side data fetching - the best of both worlds. - This all even works if JavaScript is disabled in the browser. - Template GitHub repo: What are you going to learn? We are going to start with a default SvelteKit application. Once initialized, we will learn how to install and configure Prisma before we will use the PrismaClient to perform create, read, update & delete (CRUD) actions against a local SQLite database. Things you need to know In order to get the most out of this post, I expect you are aware of the following technologies: The foundation Let's start with the basics: A SvelteKit demo app. I recommend you first create a GitHub, GitLab or Bitbucket project and start a development environment with Gitpod. Alternatively, you can follow along on your local computer. npm init svelte@next svelte-with-prisma When prompted, select the following options: - "Which Svelte app template?" SvelteKit demo app - "Use TypeScript?" Yes - "Add ESLint for code linting?" No - "Add Prettier for code formatting?" Yes When complete, please follow the "Next steps" listed in the terminal to install dependencies and start the SvelteKit demo app. If you've followed along so far, you can copy & paste the following commands: cd svelte-with-prisma npm install npm run dev -- --open That's how quickly you get started with SvelteKit. In your browser, you notice the "TODOS" navigation item. If you play with this list, items are persisted on svelte.dev and deleted after a while. Next, we are going to add Prisma to persist todo items in a local SQLite database. Add Prisma Prisma.io states "Prisma helps app developers build faster and make fewer errors with an open source ORM for PostgreSQL, MySQL and SQLite." From my personal experience, this statement is certainly true. Let's go and experience it for yourself. Install & initialize Prisma First things first: npm i -D prisma because, well... without dependencies we won't get very far 😉. Next, we are going to initialize Prisma. For that, we use npx to execute commands. npx prisma init ⚠️ This currently overwrites an existing .gitignorefile. Keep an eye on 8496. This creates a prisma directory at the root of the project. In it, you find the schema.prisma file. At this point, I recommend you install the prisma.prisma VS Code extension. It adds syntax highlighting, formatting, auto-completion, jump-to-definition and linting for .prisma files. Define the Todo model Open the prisma/schema.prisma file and add the following model definition to the end of the file: model Todo { uid String @id @default(cuid()) created_at DateTime text String done Boolean } Psst... How do we know what fields to define? Well, we take a peek at the Todo type definition in src/routes/todos/index.svelte 😉. Configure a SQLite database Open the .env file (that file was created by the npx prisma init command earlier). In it, set the DATABASE_URL to "file:./dev.db" We also have to open the prisma/schema.prisma file to update the datasource.db.provider to sqlite. Check the reference docs for more details on the above two values and what other databases are supported. Create the database and tables We're making great progress! Let's now use the Prisma CLI to create our SQLite database and create a schema based on the Todo model we defined earlier. It's easy: npx prisma db push Give that five seconds ⏳. I recommend you read through the console output, I find it highly interesting. For one, it gives us a good deal of detail about what's going on. However, it also contains the following output which is one of the reasons I'm mind-blown by Prisma: ✔ Generated Prisma Client (2.28.0) to ./node_modules/@prisma/client So much goodness! Basically, they use the Todo model to auto-generate a bunch of TypeScript definitions and Javascript code which we are going to import in just a second. In other words, the "Prisma helps app developers build faster and make fewer errors" sentence on the Prisma website is not just some marketing speech, it is truly genius! Ok, I'm done being a fanboy about it, let's move on and thanks for your patience there with me 😅. One last thing, please add prisma/dev.db to your .gitignore file since we don't want to commit the dev database to version control. Use the PrismaClient to interact with the database The SvelteKit demo app nicely encapsulates all API features in the src/routes/todos/_api.ts file. To be more precise, the actual CRUD logic happens at. We are going to modify the _api.ts file slightly to deal with CRUD right there and use the PrismaClient instead of delegating to a backend API. Move the Todo type so we can reuse it First and foremost, let's move the Todo Typescript type. By default, it's defined and used in the src/routes/todos/index.svelte file. However, with the changes we're going to make to the API, we are also going to need that type in the src/routes/todos/_api.ts file. - Cut the Todotype from src/routes/todos/index.svelte - Paste it below the importstatements in src/routes/todos/_api.ts, and prefix it with export - Use the following import in the src/routes/todos/index.sveltefile: import type { Todo } from "./_api"; Update the API to use Prisma Open the src/routes/todos/_api.ts file and add the following import: import { PrismaClient } from '@prisma/client'; Remember? That's the generated code I was so excited about earlier 😀. Next, we need a new instance of the PrismaClient (add this below the import statements): const prisma = new PrismaClient(); Moving right along, it's time to update the api method signature to tell Typescript that the data parameter is of type Todo. export async function api(request: Request<Locals>, resource: string, data?: Todo) { The following code: const res = await fetch(`${base}/${resource}`, { method: request.method, headers: { 'content-type': 'application/json' }, body: data && JSON.stringify(data) }); needs to be replaced with this: let body = {}; let status = 500; switch (request.method.toUpperCase()) { case "DELETE": await prisma.todo.delete({ where: { uid: resource.split("/").pop() } }); status = 200; break; case "GET": body = await prisma.todo.findMany(); status = 200; break; case "PATCH": body = await prisma.todo.update({ data: { done: data.done, text: data.text }, where: { uid: resource.split("/").pop() } }); status = 200; break; case "POST": body = await prisma.todo.create({ data: { created_at: new Date(), done: false, text: data.text, } }); status = 201; break; } We're getting there 💪. In the if statement right below the code we've just added, remove the res.ok && since we no longer have a res variable. Lastly, change the return statement to the following: return { status, body }; Let's test Start your SvelteKit demo app with npm run dev and navigate to in your browser. If you use Gitpod, hold CTRL / CMD pressed and click on the URL in the terminal, it'll open a new browser window with the SvelteKit demo app. Click on the "TODOS" navigation link and add a few todos, rename some, mark others as done. In a new terminal, open the Prisma Studio with npx prisma studio. The studio opens in a new browser tab. Click on the Todo model and validate that the data matches what you see in the SvelteKit demo app. Congratulations 🎉! Bonus - definitely read this Disable JavaScript in your browser and test the todo list again. This is how the web is supposed to work - without JavaScript! We used to develop websites like that, then we spent a decade thinking it's a great idea to move everything into JavaScript and thanks to Svelte & SvelteKit, we now once again develop web applications that work the way the web was intended to work. JavaScript's purpose is to enhance the web experience, not break everything if JavaScript is disabled. Conclusion With a few modifications to a default SvelteKit demo app, we managed to configure Prisma to persist todo items. There is of course a lot more you can do with Prisma, and with SvelteKit for that matter. The source code at should get you a long way towards your own web app. If you found this interesting, you may also like (wow... is this an e-commerce website 😂?!) my current project called Webstone. Webstone is a full-stack web application boilerplate with a CLI to automate tedious tasks like adding new pages, updating the database (of course it uses Prisma 😉). It's in early development, but do hit that star button on GitHub which helps me get motivated to spend more time on the project 🙏. 👋 Discussion (3) Great read Mike! Thanks for sharing Awesome read! Followed! Excited to hear more about Prisma with Svelte + Realtime API . Thanks for sharing this. Hearing so much good stuff about Prisma lately that I have to try this out
https://practicaldev-herokuapp-com.global.ssl.fastly.net/mikenikles/sveltekit-prisma-a-match-made-in-digital-heaven-2g0f
CC-MAIN-2021-39
refinedweb
1,506
67.45
res_query, res_search, res_mkquery, res_send, res_init, dn_comp, dn_expand— #include <sys/types.h> #include <netinet/in.h> #include <arpa/nameser.h> #include <resolv.h>int res_query(const char *dname, int class, int type, unsigned char *answer, int anslen); int res_search(const char *dname,); int res_init(void);); _res. Most of the values have reasonable defaults and can be ignored. Options stored in _res.optionsare defined in <resolv.h>and are as follows. Options are stored as a simple bit mask containing the bitwise OR of the options enabled. RES_INIT res_init() has been called). RES_DEBUG DEBUG. By default on OpenBSD this option does nothing. RES_AAONLY res_send() should continue until it finds an authoritative answer or finds an error. Currently this is not implemented. RES_USEVC RES_PRIMARY RES_IGNTC RES_RECURSE res_send() does not do iterative queries and expects the name server to handle recursion.) This option is enabled by default. RES_DEFNAMES res_search() will append the default domain name to single-component names (those that do not contain a dot). This option is enabled by default. RES_STAYOPEN RES_USEVCto keep the TCP connection open between queries. This is useful only in programs that regularly do many queries. UDP should be the normal mode used. RES_DNSRCH res_search() will search for host names in the current domain and in parent domains; see hostname(7). This is used by the standard host lookup routine gethostbyname(3). This option is enabled by default. RES_INSECURE_1 RES_INSECURE_2 RES_NOALIASES HOSTALIASESfeature. See hostname(7) for more information. RES_USE_INET6 RES_USE_EDNS0 RES_USE_DNSSEC res_init() routine reads the configuration file (if any; see resolv.conf override the search list on a per-process basis. This is similar to the search command in the configuration file. Another environment variable RES_OPTIONScan be set to override certain internal resolver options which are otherwise set by changing fields in the _res structure or are inherited from the configuration file's options command. The syntax of the RES_OPTIONSenvironment variable is explained in resolv.conf(5). Initialization normally occurs on the first call to one of the following routines. The res_query() function provides an interface to the server query mechanism.. Values for the class and type fields are defined in <arpa/nameser.h>. The res_search() routine makes a query and awaits a response like res_query(), but in addition, it implements the default and search rules controlled by the RES_DEFNAMESand RES_DNSRCHoptions._send() routine sends a pre-formatted query and returns an answer. It will call res_init() if RES_INITptrs. res_queryfunction appeared in 4.3BSD.
https://man.openbsd.org/OpenBSD-5.6/resolver.3
CC-MAIN-2018-26
refinedweb
405
61.43
SO, I'm playing around with an idea. I'm trying to convert primitives to and from a char array for file logging. I've got all the details worked out, but I don't understand something.. Take the following case, for example: public static byte[] ToByta (short data) { return new byte[]{ (byte)(data & 0xff), (byte)((data >>> 8) & 0xff) }; } The above converts a short value to a 2-byte byte array using bitwise operators. Let's test it out: 0 yields {0, 0} 10 yields {10, 0} -10 yields {-10, -1} 127 yields {127, 0} 128 yields {-128, 0} 1234 yields {-46, 4} -1234 yields {46, -5} Everything looks normal. Now, lets pass those arrays through the original reverting function: public static short ToShort (byte[] data) { if (data == null) return 0x0; if (data.length != 2) return 0x0; return (short) ( data[0] | data[1] << 8 ); } Can you see anything wrong with that? Maybe. Let's test it out: 0 yields 0 10 yields 10 -10 yields -10 127 yields 127 128 yields -128 1234 yields -46 -1234 yields 1234 As you can see, there's a few issues. I knew it had something to do with the bits, so I played around a bit and came up with this: public static short ToShort (byte[] data) { if (data == null) return 0x0; if (data.length != 2) return 0x0; return (short) ( 0xff & data[0] | data[1] << 8 ); } Which seems to work perfectly. All I added was the 0xff & in the combination sequence.. And I don't know why this works whereas it doesn't work without the 0xff & . Can someone please explain that to me? 10101010 does not equal 11111111 & 10101010 ??? :-|
https://www.daniweb.com/programming/software-development/threads/62594/bitwise-convert-primitives
CC-MAIN-2018-05
refinedweb
277
78.08
#include <stdio.h> int TheDupe(double mark[]); void order(double mark[]); int main(void){ double a, b, c, d, e, mark[5]; int x; printf("Please enter 5 numbers. They can be positive or negative. No duplicates please.\n"); printf("Value 1=> "); scanf_s("%lf", &a); printf("Value 2=> "); scanf_s("%lf", &b); printf("Value 3=> "); scanf_s("%lf", &c); printf("Value 4=> "); scanf_s("%lf", &d); printf("Value 5=> "); scanf_s("%lf", &e); mark[0] = a; mark[1] = b; mark[2] = c; mark[3] = d; mark[4] = e; order(mark); x = TheDupe(mark); if (x = 1) printf("%d Duplicates detected! You are a failure at following even the simplest\ndirections.\n", x); if (x = 0) printf("%d The ascending order of the numbers you've entered is %f\n%f\n%f\n%f\n%f\n", x, mark[0], mark[1], mark[2], mark[3], mark[4]); return(0); } void order(double mark[]){ double temp; int x; int y; int z; for (int i = 1; i<5; i++){ if (mark[0] > mark[i]){ temp = mark[0]; mark[0] = mark[i]; mark[i] = temp; } for (int i = 2; i<5; i++){ if (mark[1] > mark[i]){ temp = mark[1]; mark[1] = mark[i]; mark[i] = temp; } for (int i = 3; i<5; i++){ if (mark[2] > mark[i]){ temp = mark[2]; mark[2] = mark[i]; mark[i] = temp; } for (int i = 4; i<5; i++){ if (mark[3] > mark[i]){ temp = mark[3]; mark[3] = mark[i]; mark[i] = temp; } } } } } } int TheDupe(double mark[]){ int x = 0; for (int i = 0; i < 4; i++) { for (int j = i + 1; j <= 4; j++) { if (mark[i] == mark[j]){ x = 1; return (x); } } } return a first view I found at least two errors: 1. in main the if statements use assignment-operator '=' instead of comparsion operator '=='. This means always the first 'if' is true ( because 'x = 1' == 1) and the second is always false ('x= 0' == 0). 2. in order the outer loop starts with index 1, but in C arrays are always zero-based, so the first element isn't evaluated. Beside this I would suggest to implement the sorting in order in a more convenient way, there's no need to do an extra loop for every element (i.e. your code cannot work for any other size of input array). It is better to implement some common, generic sort algorithms - a good start to find out more about these could be Hope that helps, ZOPPO The way that the sort is coded suggests that the author doesn't really understand arrays and loops. But that's part of what learning to program is all about! The code suggests that if the array contained 100 items the sort would be VERY long! The simplest sort to code is a successive maximum (or successive minimum) sort. It's very inefficient on large volumes of data, but it works and codes easily. Try this, then move to more advanced sorting techniques. Many of them code easily enough for beginners to understand. Good Luck! Kent Open in new window Experts Exchange Solution brought to you by Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.Start your 7-day free trial <Kent> I changed j <= Length to j < Length because it always returned a zero (0) as the first number no matter what numbers were being sorted. for (i = 0; i < Length; ++i) for (j = i+1; j <= Length; ++j) change to: for (i = 0; i < Length-1; ++i) for (j = i+1; j < Length; ++j) The inner loop iterates through the items after the item at *i*, so *i* need never be set to the last item. However, just changing the loop control for *j* sorts the items correctly as that loop exits immediately when *i* is set to the last item. Working from memory here. Guess I should have looked just a bit more carefully before submitting that. :) Thank you both for the help. My son texted me and he thinks he is all set. I will know for sure tonight (hopefully) and will close this question tomorrow. Always nice to be on the other side of helping people and getting help instead when I need it. Thanks again.
https://www.experts-exchange.com/questions/28652059/C-programming-help-for-beginner-sort-routine.html
CC-MAIN-2018-30
refinedweb
719
67.08
Installation and compilation instructions eabase opened this issue · comments It would be fabulous if you could provide some instructions on how to compile and install this awesome simulation. What would be most useful are: - What OS packages are needed? - What libraries are needed? - How to install them using a typical package manager like apt getetc. - Compilation instructions, what tools and flags are needed? Hi @eabase, on a distro based on Ubuntu 21.04 and configured for C++ development, the core dependencies of the simulator should be satisfied by running "sudo apt install cimg-dev". The readme file offers two ways to compile -- either by using Code::Blocks IDE or using a Makefile. Let us know if you have more specific questions about those steps. I David, I think the meaning was create instructions for someone who doesn't know Linux very well, so create instructions that include the exact commands to use to install (including required packages) and then run the the program. I fell into the trap of including the square brackets around the ini file when launching which meant the program wouldn't work. I spent a good 30min trying to investigate before trying without the square brackets. As soon as I did that, it worked fine (so far). Thank you for the docker image @mathematicalmichael @eabase, I saw the instructions in the README for the first time 2 days ago i.e. after you created this issue. Do you think the current README fulfills your list? I was able to install required packages and compile from the current README. @mathematicalmichael , that's a great idea. Thanks for making the image available. @mathematicalmichael my first reaction was "sure, why not?" but then I considered the consequences: some folks might see the link to the docker file and just go grab it without appreciating the full scope and context of the build requirements and components. You might get a lot more support requests if the docker image and a tempting link is free-floating out there without the mandatory walkthrough in the README :) That being said, I think the Docker image option for compilation should be given more emphasis in the README. For example, in my case, I did not understand - at first - that the docker image is a complete compilation environment for this project. I slogged through getting all the requirements installed on Ubuntu 18.04, installed docker-cs and finally ran the container. Only then did I realize that the docker image is all I needed to compile biosim. Highlighting the latter fact - and pointing out that a Linux host is more or less the only way to run biosim - will be useful for most users, I think. Do you think linking to the docker image might have some other benefit? @davidrmiller no problem! thanks for actually making your work open source and being open to contributions! @venzen thanks for that feedback, I think that's a great point re: the lack of clarity. I can try to update the README to be more clear that the docker image is a "compilation and runtime environment" (meaning, it can pretty much stay the same despite new features of biosim4 being added). Regarding upsides: It took a long time to build the image on my m1 mac mini and even more so on my raspberry pi 4 (kicked them off around the same time). I ended up building it on the m1, publishing, and then using the pi to pull the image and run simulations in the background overnight. So in short, compilation was quick, building the image was slow. Therefore the only upside is just a bit of time being saved. I think a lot of people mess with Linux on lower-power hardware so this helps get things up faster there. Some notes: - I took this project as an opportunity to learn how to build multi-arch images (as well as how to get the makefile to support compiling on both platforms! that was new for me and part of the fun of submitting the PR). - Later I learned to use github actions + docker buildx to publish multi-arch images directly to dockerhub, so I can offer to contribute helping maintain the publishing of these images - re: the latter point.. perhaps under a better namespace. though the one I have now is not entirely inappropriate, it would be nice if it were under @davidrmiller's docker username instead but I'm open to keeping helping maintain the image I published. So, I haven't landed on whether or not to link the mindthegrow image in the README, but I think if worded right it could be of help. Something like # Quickstart If you are running any unix/linux-based distribution, the easiest way to get started with reproducing this work is to install `docker` on your system (link here) and run the following in your terminal: ```sh $ git clone $ cd biosim4 $ docker build -t biosim4 . $ docker run --rm -ti -v `pwd`:/app -w `/app` biosim4 make ``` If you want to skip building the `biosim4` image yourself, you can use a community-contributed image by replacing the third step above with ```sh $ docker pull mindthegrow/biosim4 && docker tag mindthegrow/biosim4 biosim4 ``` ## What is the docker image for? The docker image provides all the required dependencies to compile and run biosim4 and avoids you needing to install any packages related to it on your system. <talk more about instructions linked below> Thoughts on the initial pass? No mentions of architecture but I can make it clear that it'll work on both arm64 and amd64 @mathematicalmichael your explanation changed my mind! :) Considering how useful your docker image is, and the effort it takes to create it (them), making it available will be a great service to BioSim enthusiasts. Regarding namespace at DockerHub I want to raise the same concern: placing the images under David's namespace, there, might lead users to direct support issues to him, rather than you, and result in an awkward resolution process. I understand that you probably propose the namespace out of respect for David's work in BioSim, but the docker image is your hard work and merit. Consider this too. :) The README "Quickstart" contents you propose above are clear. I want to suggest: - Under "System Requirements" point out that building and compiling under Windows is problematic and not supported. Keep the the caveat about 20.04 LTS and direct users to the "Bugs"section further down the page. - "Quickstart": the text you posted above is good. I have this link to a guide for installing Docker in Ubuntu 20.04: There might be better guides out there, but it worked for me on 18.04. - The option to build the docker image oneself is great! Link to your Docker images is unavoidable. Perhaps create a new namespace at DockerHub or include under David's as you see fit. - Subsection "What is the docker image for?". Useful and insightful for less experienced users. Mention that an ARM image is available and working on Pi. This will be quite popular, I imagine. Once again, Good Job @mathematicalmichael ! The presence of your docker image inspired me to get my local docker install working and this is the first image I have run. Of course, it enabled me to compile and run biosim4 quickly and effortlessly - which was the reason for coming here in the first place. Yay! \o/ @mathematicalmichael Issue #25 has discussion about a testing methodology using Python3. Some additional modules will have to be installed during the docker build. Specifically, python3-dev, configparser and pybind11. Other modules may join the list as we progress. Should we create a separate Dockerfile to build a container for tests? Is the existing image at mindthegrow/biosim4 suitable for such a build? I'm new to Docker so your advice will be useful. @davidrmiller do you have some input about direction with this? For a testing program, I might have done something like the shell script below or a Python equivalent that has no dependencies other than a standard *nix installation. This is just a quickly-written example of a concept. It invokes the simulator with a pre-prepared config file, then checks stderr and the epoch log to see if the output looks reasonable. This concept example could be expanded to loop over multiple test configs and kill any simulator processes that run too long. Instead of hardcoded expected results like in the example below, it could extract the expected results for each test from a table or from specially-formatted comments inside each config file. It's just a shell script and a config file that ship inside a test directory -- no changes are needed to the simulator or to the config file format, no special compilation, and no outside dependencies. The corresponding config file is attached here with a .txt extension: biosim4-test-1.ini.txt #!/bin/sh # This script tests the biosim4 simulator using the config file named "biosim4-test-1.ini". # Criteria for a successful test are no stderr output and certain values in the last line # of logs/epoch-log.txt. ./bin/Debug/biosim4 ./biosim4-test-1.ini > out 2> err success=1 if test -s err; then echo "The simulator output errors:" head -10 err success=0 fi result=`tail -1 ./logs/epoch-log.txt` generation=`echo $result | cut -d" " -f 1` survivors=`echo $result | cut -d" " -f 2` diversity=`echo $result | cut -d" " -f 3` genomeSize=`echo $result | cut -d" " -f 4` kills=`echo $result | cut -d" " -f 5` if [ $generation -ne 100 ]; then echo "Error: generation number, expected 100, got " $generation success=0 fi if [ $survivors -le 266 -o $survivors -gt 284 ]; then echo "Error: survivors, expected 266 to 284, got " $survivors success=0 fi if [ `expr $diversity \< 0.314` -eq 1 -o `expr $diversity \> 0.551` -eq 1 ]; then echo "Error: diversity, expected 0.314 to 0.551, got " $diversity success=0 fi if [ $genomeSize -ne 64 ]; then echo "Error: genome size, expected 64, got " $genomeSize success=0 fi if [ $kills -ne 0 ]; then echo "Error: number of kills, expected 0, got " $kills success=0 fi if [ $success -eq 1 ]; then echo "Pass." else echo "Fail." fi This shell script works, as is. Shell output: darwin@45c0399df3a1:/app$ ./tests/simtest.sh Pass. Using biosim4-test-1.ini it took about 7 mins to run on my AMD 4-core laptop for this non-deterministic simulation. my advice would be to have testing dependencies in a separate container. It can inherit from (use as its base image) the existing published image and add the couple of extra requirements on top. I can help with the github action, it would be something like a copy/paste of the existing one but referencing a different dockerfile, the workflow being changed to "build the test image, then run docker run <same as now> <shell script> instead of make at the end. This Dockerfile-testing and new .github/workflows/test.yml file should be part of that PR that introduces the testing scripts. seven minutes however... is much too long for testing, the github-actions servers are not really any more powerful than your laptop. fewer generations -> linear decrease in time, as would be fewer timesteps per generation. So if you cut both in half, you'll get something on the order of < 2 minutes, which is long but still tolerable. this can be accomplished with something like running sed on the biosim4.ini file prior to testing, or using a dedicated test-file as you have showed (i'm in favor of running sed and avoiding the clutter of a separate .ini, but it may be too many changes) I appreciate the thoughts about testing. While completely automatic testing would be nice, perhaps GitHub actions are not well suited for this project. They seem to require maintaining non-trivial actions, containers, libraries, and other dependencies for tests that could only run for a limited duration. I'd like to avoid over-engineering something that could be simple. I propose that testing is more easily done locally by a user as needed by invoking a script (cf. the shell script example above). It would execute in the same directory structure in the same container with no additional dependencies. Testing locally would allow any user to invoke only the tests needed and only when needed (single/multi-threaded, fast, long, [non]deterministic, etc). It would allow some tests to run for an extended time, which is valuable. The tests would be easy to invoke, easy to develop, and easy to maintain by anyone. As @mathematicalmichael pointed out, the script could generate the necessary config files when needed so that the entire testing framework could consist of just a single executable script. I mean, adding a few libraries would only add a couple dozen MB or so to the image, so if you want to just jam em in to the image, that's really not a problem, I can update the one I have published to mindthegrow if you ping me when main is updated with a new Dockerfile. But I do like that your shell script doesn't require anything else, that's really appealing. A local testing approach is fine, just have to validate the work of PRs locally. If you don't mind, then yah no use in setting up github actions for testing, having a compilation check is good enough. The discussion about testing is valuable. Digging deeper into the code and having re-watched the biosim4 video a few times, it is evident that @davidrmiller has put a lot of thought into this project. That implies, also. a vision for the project as well as philosophy that steers it. Most of the participants are enthusiastic to contribute because biosim4 inspires thought and creativity. I am slowly coming round to David's values and approach - which is something that all contributors can achieve by reading his comments and posts - they are well-worded and convey his philosophy for the project. Good job by everybody who has contributed, so far. @mathematicalmichael I agree with your approach of separating out tests. @davidrmiller 's idea of simple single-script tests should be the norm, and then those of use who want to run whatever extensive local tests can have another Dockerfile which builds an image with all those arbitrary libraries we require. Such a Dockerfile and contributed files/scripts can live in separate tests directory. The official documented test-script could be in the top-level directory or could reside in the tests directory too. Hi Guys! Thanks for all the feedback. Sorry I have not been available to see the whole discussion earlier. All great work, and I just wanted to add my silly 2 cents in general about docker. To me, I was never a great fan of docker. Although it's extremely easy and useful, the drawback (as implied by someone earlier) is that it masks all the grit needed to build or customize your own system. For me using docker is a bit like saying "Here is the ISO image, just install on your VM and run.", which means you have learned absolutely nothing about the project you're running, nor about any of the tools or technology it uses. Then someone may argue, "You can always go into the config files and see what the image is doing." Well, can you? Probably not without learning docker. (But if you think I'm lost out biking in the forest, I am happy to be corrected!) Just to sketch another use case and give +1 support for docker... @eabase I get your point about androgogy, however, in my case docker is more than a convenience or cop-out. Without it I would not be able to compile or run biosim4. This is due to practical (and resource) limitations: if I upgrade to Ubuntu 21.04 then I will break dependencies for other projects and destroy a finely-tuned desktop environment. I think that his project is of interest to a wide audience: evolutionary biologists, coders, philosophers, and laypeople, etc. Yet, those incidental users who arrive here - but who lack experience of open source and C code compilation - will be out of their depth. The docker image does not allow the user a short-cut because installing docker, setting it up and actually running the image, implies that he has the concomitant skill-set to install dependencies and compile from the command line, anyway. I was actually considering, for the past week, that a few architecture specific docker images with already-compiled binaries might be useful to noobs, but (considering your points and my response) I just convinced myself why that would probably be a futile gesture. :)
https://giters.com/davidrmiller/biosim4/issues/5
CC-MAIN-2022-21
refinedweb
2,806
62.27
Jon Fancey's Blog Server2007-03-15T20:02:00ZUpcoming stuff/community/blogs/jfancey/archive/2008/10/13/upcoming-stuff.aspx2008-10-13T09:28:00Z2008-10-13T09:28:00Z<p>Ok, I've been busy. Now that's out the way, I'll talk about some of the stuff I've been/will be doing.</p> <p>First up, I'll be at PDC next week and am really looking forward to it. There's a ton of new stuff now being 'leaked' from the big house ahead of this event, Oslo, Dublin and Zurich to name a few. Should be a blast.</p> <p>Following quickly on from that I'll be at TechEd Europe during the IT Pro Week (3-7th Nov). I'm doing a session with Steve Smaller from the HIS Product Group on MOSS integration wtih some of the curernt and new stuff coming out of that group. Haven't finalized my travel plans be would expect to be there from Wednesday 5th onwards.</p> <p>I've been digging into MOSS a lot lately, and I think I like it.</p><div style="clear:both;"></div><img src="" width="1" height="1">jon-fancey cat is finally out of the bag.../community/blogs/jfancey/archive/2007/10/30/48899.aspx2007-10-30T20:25:00Z2007-10-30T20:25:00Z<P><A href=""></A></P> <P>:-)</P><div style="clear:both;"></div><img src="" width="1" height="1">jon-fancey BizTalk R2 course coming up/community/blogs/jfancey/archive/2007/10/18/48797.aspx2007-10-18T06:08:00Z2007-10-18T06:08:00Z<P>The spotlight is certainly on BizTalk at the moment both inside and outside Microsoft. What with R2 shipping and the BPM conference at the end of the month there's no shortage of stuff to look at.</P> <P>If you want more, focussed content, on the new features I'll be teaching a public offering of the R2 course in a couple of weeks (beginning 6th Nov) in Waltham, MA near Boston. There's still a couple of slots free if you're quick...</P><div style="clear:both;"></div><img src="" width="1" height="1">jon-fancey MSDN article on BizTalk and IBM technologies/community/blogs/jfancey/archive/2007/08/29/48317.aspx2007-08-29T12:01:00Z2007-08-29T12:01:00Z<P>My latest paper on integrating BizTalk and IBM technologies is now up on <A href="">MSDN</A> covering WebSphere MQ, DB2, Host files and applications. I'm assured it will be HTML'd and added to the library in the not too distant future.</P> <P>feedback always welcome...<BR></P><div style="clear:both;"></div><img src="" width="1" height="1">jon-fancey if you like SOAP and don't like web references? - Redux/community/blogs/jfancey/archive/2007/06/07/47683.aspx2007-06-07T18:00:00Z2007-06-07T18:00:00Z<P><FONT face=Arial size=2>I started the </FONT><A href=""><FONT face=Arial size=2>first </FONT></A><FONT face=Arial size=2>post on this, with "this is interesting, sort of" - well judging by the number of people who've asked me for more details on doing it I think I was wrong. Apologies to all, I've been so busy the last few months that I just haven't had time to get some code examples up there...until now!</FONT></P> <P><FONT face=Arial size=2>Get the code </FONT><A href=""><FONT face=Arial size=2>here</FONT></A></A><FONT face=Arial size=2> to try this for yourself. Essentially, this is an example of what I discussed before, where you can do dynamic sends using the SOAP adapter. For those that haven't tried it, you might be thinking, what's the big deal, but as I mentioned, theres a couple of gotchas which stop this from working as cleanly as with other adapters. </FONT></P> <P><FONT face=Arial size=2>The first is that you can't just set the OutboundTransportLocation from an orchestration (or receive pipeline) as you would do for other dynamic adapters. This is because the Uri scheme (the bit before the address, e.g. HTTP://) is used by BizTalk to lookup the adapter alias from the adm_AdapterAlias table in the management database. As the SOAP adapter only supports SOAP over HTTP you must set the scheme to SOAP:// in order to route it correctly. But this won't work because then the ASMX proxy plumbing (called by the adapter) will fail as it is expecting HTTP:// and will make the call using SOAP:// instead. The way round this is to set the Microsoft.XLANGs.BaseTypes.Address property of the port - which will deliver the message to the SOAP adapter - and then set the OutboundTransportLocation context property in the Send pipeline. The example code shows how to call a Web service using this technique by pulling the Uri to send the message to from the inbound message itself. This dynamic routing is extremely powerful and very useful for Web services.</FONT></P> <P><FONT face=Arial><FONT size=2>The second gotcha is around the use of a proxy. When you add a Web reference to a BizTalk project, similar (but not identical) logic is used to classic ASMX whereby a proxy is generated from the URL you provide in the wizard. The proxy contains the Web methods that map to the operations on the provider's WSDL. The problem is that you end up baking the service interface into the client. Rather than creating a client proxy for each client (which is a pain), what we really want is a generic proxy capable of calling <EM>any </EM>client. Worse than this, ASMX forces the SOAPAction HTTP header (for SOAP 1.1 support) to match the name of this method which makes it very inflexible. Changing this however turns out to be pretty easy using reflection. The code in the download overrides the Invoke method of the <FONT color=#008080>SoapHttpClientProtocol <FONT color=#000000>in the System.Web.Services.Protocols namespace. Normally this method is called by the Webmethod passing the name of the Webmethod itself (which is Dispatch in the sample). Invoke itself then uses reflection to get the method parameters etc to formulate the call to the service implementation. To keep things simple the code here only deals with a single parameter, XmlNode. Of course you could easily extend this if you wanted to but then you'd be wanting to pass multiple Xml docs which kinda goes against the philosophy of doc/lit. The orch's Send port is then configured to use our generic proxy and call the Dispatch method to make this all work.</FONT></FONT></FONT></FONT></P> <P><FONT face=Arial size=2>There are three projects in the solution, BizTalk (with the Send pipeline and Orch), the generic proxy called by the SOAP send adapter and a simple Web service implementation to call. Simply compile everything, deploy the BizTalk project and GAC the generic proxy assembly. Deploying will create all the ports (sorry about the names) - just create a folder c:\webrefsfilein and enlist and start the orch. You can then drop in the xml file in the Test Data folder in the BizTalk project. There is tracing code throughout, so grab the invaluable sysinternals (sorry, Microsoft) tool, Debug Viewer </FONT><A href=""><FONT face=Arial size=2>here</FONT></A><FONT face=Arial size=2>. Run the solution (with the Web service as the default startup). When you drop the file in it should call the Web service (specified in the file) and return a result, logging the call (see pic below). Enjoy!</FONT></P><FONT face=Arial size=2><IMG src=""></FONT><div style="clear:both;"></div><img src="" width="1" height="1">jon-fancey a week/community/blogs/jfancey/archive/2007/03/15/46481.aspx2007-03-16T00:02:00Z2007-03-16T00:02:00Z<P>So, I'm sitting in Sea-Tac airport waiting to return home with <A href="">Charles Young </A>from the MVP Summit. Not only has it been great to meet and put so many faces to names but the whole experience was fantastic. Of course, it pretty much rained all week, but I certainly can't complain about that.</P> <P>A big thanks go out to all the people behind the organization and especially <A href="">Marjan Kalantar</A> from the product group for putting together a great show and giving us plenty to think about.</P> <P>The fact that I am writing this on <A href="">pluralsight </A>rather than <A href="">jonfancey.com </A>is also of course very significant. I've just joined up and will be starting to teach Applied BizTalk alongside my new BizTalk and WF collegues, Jon Flanders, Aaron and Matt over the coming weeks/months. I can't wait.</P><div style="clear:both;"></div><img src="" width="1" height="1">jon-fancey
http://www.pluralsight.com/community/blogs/jfancey/atom.aspx
crawl-002
refinedweb
1,504
61.87
Tutorial: Stream big data into a data warehouse Azure Event Grid is an intelligent event routing service that enables you to react to notifications or events from apps and services. For example, it can trigger an Azure Function to process Event Hubs data that's captured to a Blob storage or Data Lake Storage. This sample shows you how to use Event Grid and Azure Functions to migrate captured Event Hubs data from blob storage to Azure Synapse Analytics, specifically a dedicated SQL pool. Synapse Analytics. In this article, you take the following steps: - Deploy the required infrastructure for the tutorial - Publish code to a Functions App - Create an Event Grid subscription - Stream sample data into Event Hubs - Verify captured data in Azure Synapse Analytics Prerequisites To. - WindTurbineDataGenerator – A simple publisher that sends sample wind turbine data to a capture-enabled event hub - FunctionDWDumper – An Azure Function that receives an Event Grid notification when an Avro file is captured to the Azure Storage blob. It receives the blob’s URI path, reads its contents, and pushes this data to Azure Synapse Analytics (dedicated SQL pool). - Azure Synapse Analytics (dedicated SQL pool) for storing the migrated data Use Azure CLI to deploy the infrastructure. Create an Azure resource group by running the following CLI command: Copy and paste the following command into the Cloud Shell window. Change the resource group name and location if you want. az group create -l eastus -n rgDataMigration Press ENTER. Here is an example: user@Azure:~$ az group create -l eastus -n rgDataMigration { "id": "/subscriptions/00000000-0000-0000-0000-0000000000000/resourceGroups/rgDataMigration", "location": "eastus", "managedBy": null, "name": "rgDataMigration", "properties": { "provisioningState": "Succeeded" }, "tags": null } Deploy all the resources mentioned in the previous section (event hub, storage account, functions app, Azure Synapse Analytics) by running the following CLI command: Copy and paste the command into the Cloud Shell window. Alternatively, you may want to copy/paste into an editor of your choice, set values, and then copy the command to the Cloud Shell. Important Specify values for the following entities before running the command: - Name of the resource group you created earlier. - Name for the event hub namespace. - Name for the event hub. You can leave the value as it is (hubdatamigration). - Name for the SQL server. - Name of the SQL user and password. - Name for the database. - Name of the storage account. - Name for the function app. az deployment group create \ --resource-group rgDataMigration \ --template-uri \ --parameters eventHubNamespaceName=<event-hub-namespace> eventHubName=hubdatamigration sqlServerName=<sql-server-name> sqlServerUserName=<user-name> sqlServerPassword=<password> sqlServerDatabaseName=<database-name> storageName=<unique-storage-name> functionAppName=<app-name> Press ENTER in the Cloud Shell window to run the command. This process may take a while since you are creating a bunch of resources. In the result of the command, ensure that there have been no failures. Azure Synapse Analytics dedicated SQL pool. On the Dedicated SQL pool page, in the Common Tasks section on the left menu, select Query editor (preview). Enter the name of user and password for the SQL server, and select OK. If you see a message about allowing your client to access the SQL server, follow these steps: - Select the link: Set server firewall. - On the Firewall settings page, select Add client IP on the toolbar, and then select Save on the toolbar. - Select OK on the success message. - Navigate back to the Dedicated SQL pool page, and select Query editor (preview) on the left menu. - Enter user and password, and then. Update the function runtime version Open another tab in the web browser, and navigate to Azure portal. In the Azure portal, select Resource groups on the left menu. Select the resource group in which the function app exists. Select the function app in the list of resources in the resource group. Select Configuration under Settings on the left menu. Switch to the Function runtime settings tab in the right pane. Update the runtime version to ~3. Select Save on the toolbar. On the Save changes confirmation popup, select Continue. Publish the Azure Functions app Launch Visual Studio. Open the EventHubsCaptureEventGridDemo.sln solution that you downloaded from the GitHub as part of the prerequisites. You can find it in the /samples/e2e/EventHubsCaptureEventGridDemofolder. In Solution Explorer, right-click FunctionEGDWDumper project, and select Publish. If you see the following screen, select Start. In the Publish dialog box, select Azure for Target, and select Next. Select Azure Function App (Windows), and select Next. On the Functions instance tab, select your Azure subscription, expand the resource group, and select you function app, and then select Finish. You need to sign into your Azure account if you haven't already done so. On the Publish page, in the Service Dependencies section, select Configure for Storage. On the Configure dependency page, follow these steps: select the storage account you created earlier, and then select Next. Specify a name for the connection string, and select None for the Save connection string option, and then select Next. Clear the C# code file and Secrets store option, and then select Finish. When Visual Studio has configured the profile, select Publish. In the tab that has the Azure Function page open, select Functions on the left menu. Confirm that the EventGridTriggerMigrateData function shows up in the list. If you don't see it, try publishing from Visual Studio again, and then refresh the page in the portal. Event Hubs namespace from the list of resources. On the Event Hubs Namespace page, select Events on the left menu, and then select + Event Subscription on the toolbar. On the Create Event Subscription page, follow these steps: Enter a name for the event subscription. Enter a name for the system topic. A system topic provides an endpoint for the sender to send events. For more information, see System topics For Endpoint Type, select Azure Function. For Endpoint, select the link. On the Select Azure Function page, follow these steps if they aren't automatically filled. - Select the Azure subscription that has the Azure function. - Select the resource group for the function. - Select the function app. - Select the deployment slot. - Select the function EventGridTriggerMigrateData. On the Select Azure Function page, select Confirm Selection. Then, back on the Create Event Subscription page, select Create. Verify that the event subscription is created. Switch to the Event Subscriptions tab on the Events page for the Event Hubs namespace. Select the App Service plan (not the App Service) in the list of resources in the resource group. Run the app to generate data You've finished setting up your event hub, dedicate SQL pool (formerly. Right-click WindTurbineDataGenerator project, and select Set as Startup project. In the WindTurbineDataGenerator project, open program.cs. Replace <EVENT HUBS NAMESPACE CONNECTION STRING>with the connection string you copied from the portal. Replace <EVENT HUB NAME>with the name of the event hub. private const string EventHubConnectionString = "Endpoint=sb://demomigrationnamespace.servicebus.windows.net/..."; private const string EventHubName = "hubdatamigration"; Build the solution. Run the WindTurbineGenerator.exe application. After a couple of minutes, in the other browser tab where you have the query window open, query the table in your data warehouse for the migrated data. select * from [dbo].[Fact_WindTurbineMetrics] Monitor the solution This section helps you with monitoring or troubleshooting the solution. View captured data in the storage account Navigate to the resource group and select the storage account used for capturing event data. On the Storage account page, select Storage Explorer (preview) on the left menu. Expand BLOB CONTAINERS, and select windturbinecapture. Open the folder named same as your Event Hubs namespace in the right pane. Open the folder named same as your event hub (hubdatamigration). Drill through the folders and you see the AVRO files. Here's an example: Verify that the Event Grid trigger invoked the function Navigate to the resource group and select the function app. Select Functions on the left menu. Select the EventGridTriggerMigrateData function from the list. On the Function page, select Monitor on the left menu. Select Configure to configure application insights to capture invocation logs. Create a new Application Insights resource or use an existing resource. Navigate back to the Monitor page for the function. Confirm that the client application (WindTurbineDataGenerator) that's sending the events is still running. If not, run the app. Wait for a few minutes (5 minutes or more) and select the Refresh button to see function invocations. Select an invocation to see details. Event Grid distributes event data to the subscribers. The following example shows event data generated when data streaming through an event hub is captured in a blob. In particular, notice the fileUrlproperty in the dataobject points to the blob in the storage. The function app uses this URL to retrieve the blob file with captured data. { "topic": "/subscriptions/<AZURE SUBSCRIPTION ID>/resourcegroups/rgDataMigration/providers/Microsoft.EventHub/namespaces/spehubns1207", "subject": "hubdatamigration", "eventType": "Microsoft.EventHub.CaptureFileCreated", "id": "4538f1a5-02d8-4b40-9f20-36301ac976ba", "data": { "fileUrl": "", "fileType": "AzureBlockBlob", "partitionId": "0", "sizeInBytes": 473444, "eventCount": 2800, "firstSequenceNumber": 55500, "lastSequenceNumber": 58299, "firstEnqueueTime": "2020-12-07T21:49:12.556Z", "lastEnqueueTime": "2020-12-07T21:50:11.534Z" }, "dataVersion": "1", "metadataVersion": "1", "eventTime": "2020-12-07T21:50:12.7065524Z" } Verify that the data is stored in the dedicated SQL pool In the browser tab where you have the query window open, query the table in your dedicated SQL pool for the migrated data..
https://docs.microsoft.com/en-gb/azure/event-grid/event-grid-event-hubs-integration
CC-MAIN-2021-49
refinedweb
1,558
58.48