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
In this short post i'll show you how you can place or put Adsense Ads or Ads for any other advertising network,if you prefer,inside your posts. Ad placement is a very important factor if you want to maximize your earning.By experience from many professional publishers out there, placing Ads on content area or inside posts content contribute to a noticeable increase in earning .So if you prefer to put your ads on your post content this is how you can do it. We need to create a Jekyll Liquid tag and then use it wherever you want to place an Ad when writing your post {% place_ads %} The code of this tag is inspired from this gist{:rel="nofollow"} by Sverrir Sigmundarson So lets start by creating a simple Liquid tag Create or navigate into your Jekyll website _plugins folder then create a new Ruby file .lets name place-ads.rb Next just paste the following code module Jekyll class PlaceAds < Liquid::Tag def initialize(tag_name, text, tokens) super @text = text end def render(context) "#{@text}" end end end Liquid::Template.registertag('placeads', Jekyll::PlaceAds) This tag doesn't do anythong for now .All you need to do is modifying the render method to return your ads code module Jekyll class PlaceAds < Liquid::Tag def initialize(tag_name, text, tokens) super @text = text end def render(context) "<div> <script async</script> <ins class="adsbygoogle" style="display:block" data-</ins><script>(adsbygoogle = window.adsbygoogle || []).push({}); </script> </div>" end end end Liquid::Template.registertag('placeads', Jekyll::PlaceAds) You can apply your own CSS styles to the DIV so your ad will be nicely positionned,relatively to your content. Conclusion That's it ! you should be able now to place ads wherever you want inside your post content by just using the tag {% palce_ads %} References Jekyll tags{:rel="nofollow"} Revised Jekyll related posts How to use Jekyll like a pro : building contact forms Best free responsive Jekyll themes
https://www.techiediaries.com/how-to-use-jekyll-place-adsense-in-posts/
CC-MAIN-2017-43
refinedweb
327
57.1
Perl. Pod::POM::Web is a CPAN distribution which turns all of the POD on your system into browsable, linked HTML. I use perldoc all the time; could anything displace it in whole or in part? Installation Pod::POM::Web has few requirements, but the installation wasn’t as clean as I had hoped. For some reason, though the CPAN shell downloaded Alien::GvaScript and built it, it didn’t install correctly. I used the command look Alien::GvaScript to rebuild, re-test, and install the distribution. That worked, and subsequently Pod::POM::Web installed correctly. (I couldn’t figure out what went wrong, so it may have just been a quirk of my environment.) Usage You can run the module in several ways. I declined to start up a full-blown Apache instance on my laptop for testing, so I opted for the standalone server. Running it is easy. The documentation suggests: $ perl -MPod::POM::Web -e "Pod::POM::Web-server"> In a terminal window, that said: Please contact me at: <URL:> Unfortunately, that gave me a blank page in Firefox. I looked at the HTML: <script>location='/index'</script> I have NoScript active, so I changed the URL: This worked better. It produces a three-pane view, with a search box in the upper left (to search perlfunc, perlfaq, modules, or fulltext). The lower left contains a list of pragmas, core documents, and installed modules. Navigation Trouble The module list shows only top level namespace components. That is, there’s no Test::More, but there is Test. This confused me; I expected to click on Test to see a tree expansion. I enabled JavaScript for waterwheel and tried again. No luck. Pod::POM::Web::Help gives instructions, but they didn’t work for me. The documentation for Test links to Test::Harness; clicking that link brings up the documentation. That part works so far. I continued to fiddle with the keyboard shortcuts and mouse clicks and was able to get the tree list to expand somewhat… but it’s still confusing. Even so, I don’t browse looking for modules I have installed very often. Positives Typing module names in the search box works nicely. Even without the JavaScript this is still highly useful. There are links to show source code, AnnoCPAN notes, and CPAN Forum discussions. The documentation display also appears to use Module::CoreList , which shows when and if a module entered the Perl core. Not only is this more featureful than the default view on search.cpan.org, it’s much faster; it’s on my local machine. It is probably the work of a few minutes to write a little shell program to launch the browser and a Firefox tab, given a module name. I might try that instead of perldoc for a week or two at some point in the future. This is a useful module, even for minimal personal use. Also, Pod::Webserver. Oh yes, I like Pod::Webserver. It's Hack #4 in Perl Hacks for a good reason! Personally I'm all for DocPerl which has just had version 1.0 released 4 days ago. Though I could be because I wrote it :-) The main difficulty I see with Pod::Webserver is that it won't notice when new versions of modules get installed. Not sure the best way to do that for the index page, since indexing seems to take at least a few seconds. Maybe a touchfile whose timestamp could be checked whenever the index page is loaded, or every 5 minutes of daemon inactivity, or something. "Pod::POM::Web-server"> <-- There is a misspelling. :-). I quickly became a big fan of Pod::POM::Web. One feature I contributed to it is inlining AnnoCPAN comments via the AnnoCPAN::Perldoc package. Instructions for how to enable that mode are in the Pod::POM::Web docs under "optional features"! Wow, Pod::POM::Web is an awesome work...It even has the code snippets in Pod syntax-highlighted with various colors...And the AJAX stuff works fine in my ubuntu build of firefox. :) The only problem I've met so far is that one of its dependency, Alien::GvaScript 1.03, failed its own pod coverage tests and I had to install it with force. Here is my adventure: installing via CPAN shell. get & install Pod::POM::Web exited with some error (;-) had to install Module::Build look Alien::GvaScript perl Build.PL ./Build ./Build test ./Build install (make test & install didn't work..) now whow! Really cool tool. thanks! :m)
http://www.oreillynet.com/onlamp/blog/2007/05/cpan_module_review_podpomweb.html
crawl-002
refinedweb
760
74.79
Angular 8 is out now and along with that, comes my Angular 8 Tutorial (more like a crash course!) that will beginner's exactly how to get up and running with this powerful frontend javascript framework. Angular allows you to create SPA's (Single Page Apps), SSR's (Server Side Rendered) and PWA's (Progressive Web Apps). For this tutorial, we're going focus just on the basics of building an SPA. You should be comfortable with HTML, CSS and JavaScript fundamentals before proceeding with Angular. Let's get started! First, you will need Node.js in order to install the Angular CLI. Head on over to, download and install it. After installation with the default settings, open up your command line / console and run the following command: > npm -v This should output a version number. If so, you're ready to install the Angular CLI (Command Line Interface), which is a command line tool that allows you to create and manage your Angular 8 projects. To install the Angular CLI, issue the following command: > npm install -g @angular/cli Great, now let's create a new Angular 8 project: > ng new myapp This will prompt you with a couple questions. Answer them according to the answers below: ? Would you like to add Angular routing? Yes ? Which stylesheet format would you like to use? SCSS] Angular routing allows you to create routes between the components in your app. We'll be using Sass (SCSS) as well, so we're adding that too. Let's hop into the folder where our new project is stored: > cd myapp At this point, I usually issue the command: code . which opens up Visual Studio Code (the code editor I use) in the current folder. Awesome, we're ready to rock now! When you're developing your Angular 8 app, you will want to issue the following command in the terminal: > ng serve -o The -o flag is optional, but it opens up your default browser to the development location Now, while you're developing your Angular app, every time you update a file, the browser will automatically reload (hot reloading) so that you can see the app and debug it in near real-time. Note: When you want to deploy your Angular app, you will use a different command. We'll get to that later. It's worth dedicating a little bit of time to outline the important files and folders that you will commonly work in -- and also understand some of the under-the-hood stuff that makes Angular 8 work. The folder and file structure looks like this in an Angular 8 project: > e2e > node_modules > src > app > assets > environments ..index.html ..styles.scss The fundamental building blocks of your Angular app are the components. Components consist of 3 elements: Let's take a look at the component the Angular CLI generated for us to see these 3 areas in action. Open up /src/app/app.component.ts: import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { title = 'myapp'; } As you can see, we have a single import at the top, which is necessary for all Angular components. We also have the @Component({}) decorator, and the component logic at the bottom with the single title property. As we progress, we'll work with all 3 of these concepts to build out the app. Let's add a navbar with a logo and a navigation to the top of our app. Open up /src/app/app.component.html and remove all of the current code. Replace it with the following: <header> <div class="container"> <a routerLink="/" class="logo">CoolApp</a> <nav> <ul> <li><a href="#" routerLink="/">Home</a></li> <li><a href="#" routerLink="/list">List</a></li> </ul> </nav> </div> </header> <div class="container"> <router-outlet></router-outlet> </div> The two important areas that are specific to Angular 8 here are: Next, let's visit the global /app/styles.scss file to provide it with the following rulesets: @import url(''); $primary: rgb(111, 0, 255); body { margin: 0; font-family: 'Nunito', 'sans-serif'; font-size: 18px; } .container { width: 80%; margin: 0 auto; } header { background: $primary; padding: 1em 0; a { color: white; text-decoration: none; } a.logo { font-weight: bold; } nav { float: right; ul { list-style-type: none; margin: 0; display: flex; li a { padding: 1em; &:hover { background: darken($primary, 10%); } } } } } h1 { margin-top: 2em; } Nothing too exciting happening here. After saving, your app should now have a styled navigation bar. Let's use the Angular CLI to generate a couple components for the pages in our app. Issue the following commands from the console: > ng generate component home > ng generate component list This will generate several files for each component. Next, we need to visit /src/app/app-routing.module.ts and add the following code: import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { HomeComponent } from './home/home.component'; // Add this import { ListComponent } from './list/list.component'; // Add this const routes: Routes = [ { path: '', component: HomeComponent }, // Add this { path: 'list', component: ListComponent } // Add this ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } We first import the components that were generated, and then we add them as an object in the Routes array. We left the path: property blank, which signifies the home component that will load by default when the app loads. If you click on the List and Home links in the navigation, they will now display the component template associated with the clicked component! Simple! When you want to communicate data from the component logic to the template (or vice versa), this is called one-way data binding. Open up the /src/app/home/home.component.html file and replace it with the following: <h1>Welcome!</h1> <div class="play-container"> <p>You've clicked <span (click)="countClick()">this</span> {{ clickCounter }} times.</p> </div> We have a few things happening here: Visit the home.component.ts file and add the following code: export class HomeComponent implements OnInit { clickCounter: number = 0; constructor() { } ngOnInit() { } countClick() { this.clickCounter += 1; } } We've defined the property (with TypeScript) and we've set it to 0. Next, we created the function which will increment the clickCounter property by 1. Before we give it a shot, let's give this some style. Visit the home.component.scss file and specify: span { font-weight: bold; background: lightgray; padding: .3em .8em; cursor: pointer; } .play-container { padding: 3em; border: 1px solid lightgray; margin-bottom: 1em; input { padding: 1em; margin-bottom: 2em; } } Save all of the files you just modified, and give it a shot! First, the template is retrieving the clickCounter property from the component. Then, if you click on the span element, it is communicating data from the template to the component! The best way to demonstrate the concept of data binding is to do it with a form element. Visit home.component.html and add the following code: <div class="play-container"> <p> <input type="text" [(ngModel)]="name"><br> <strong>You said: </strong> {{ name }} </p> </div> In order for ngModel to work correctly, we need to import it into our /src/app/app.module.ts: // other imports import { FormsModule } from '@angular/forms'; @NgModule({ ... imports: [ BrowserModule, AppRoutingModule, FormsModule // add this ], providers: [], bootstrap: [AppComponent] }) Next, we have to define the name property in the home.component.ts file: clickCounter: number = 0; name: string = ''; // add this If you save it and begin to type within the textfield, you will see that it displays in the line beneath it in real time. This is two-way data binding because it's both setting and retreiving the property to and from the component/template! What about working with if and else within your templates? We can use ng-template for that. Add the following code at the end of home.component.html: <div class="play-container"> <ng-template [ngIf]="clickCounter > 4" [ngIfElse]="none"> <p>The click counter <strong>IS GREATER</strong> than 4.</p> </ng-template> <ng-template #none> <p>The click counter is <strong>not greater</strong> than 4.</p> </ng-template> </div> First, we use property binding [ngIf] and bind it to an expression clickCounter > 4. If that expression isn't true, it will call upon a template called none with ngIfElse. If that expression is true, it will show the HTML within the initial ng-template block. If not, it shows the template defined by #none beneath it! Give it a shot by clicking the span element until it reaches 5 or more and you will see it work in action. Awesome! Sometimes, you want to modify the appearance of your UI based on events that occur in your app. This is where class and style binding come into play. Modify the last play-container class in our HTML like so: <div class="play-container" [style.background-color]="clickCounter > 4 ? 'yellow' : 'lightgray'"> With inline style binding, you wrap it in brackets (property binding) and specify style. and then the name of the CSS property. You bind them to an expression (we're using clickCounter > 4, or this could be a boolean value too) and then a ternary operator ? where the first value is used if it's true, and the second value after the colon is used for false. If you save, it will initially show the play container block as light gray. If you click our span button a few times, it will turn yellow. What if you wanted to specify multiple CSS properties? Modify the code like this: <div class="play-container" [ngStyle]="{ 'background-color': clickCounter > 4 ? 'yellow' : 'lightgray', 'border': clickCounter > 4 ? '4px solid black' : 'none'} "> Try it out now, and you will notice both CSS properties change. Note: You can specify [ngStyle]="someObject" instead, if you wish to specify that logic in the component instead of the template. Class Binding If you wish to add or remove entire classes that are defined in your CSS, you can do this with class binding. Modify the current .play-container we've been working with, to the following: <div class="play-container" [class.active]="clickCounter > 4"> Visit the home.component.scss and add this ruleset: .active { background-color: yellow; border: 4px solid black; } Give it a shot! It works! We can also set multiple classes with ngClass. Modify the template as shown below: <div class="play-container" [ngClass]="setClasses()"> Let's visit the component file and add the following: setClasses() { let myClasses = { active: this.clickCounter > 4, notactive: this.clickCounter <= 4 }; return myClasses; } We added the notactive class here, so we should define it in the component's CSS file as well: .notactive { background-color: lightgray; } Give it a shot! Awesome stuff! Services are special components that are reusable throughout your app. We're going to create a service for the purpose of communicating with an API to fetch some data and display it on our lists page. Let's generate the service with the Angular CLI: ng g s http Notice "g s", these are just shorthand terms for "generate service". The name we're giving this service is "http". Let's visit the new service file located at /src/app/http.service.ts: import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class HttpService { constructor() { } } It looks similar to a component, except the import is an Injectable instead of a Component, and the decator is based on this @Injectable. Let's create a custom method that other components can access: export class HttpService { constructor() { } myMethod() { return console.log('Hey, what is up!'); } } Next, in /src/list/list.component.ts: export class ListComponent implements OnInit { constructor(private _http: HttpService) { } ngOnInit() { this._http.myMethod(); } } ngOnInit() is a lifecycle hook that is fired when the component loads. So, we're saying, run our .method() from the service when the component loads. If you click to the list link in the navigation and view your console in the web developer tools, you will see "Hey, what is up!" output. We need to integrate the HTTP client within our http service, which will allow us to communicate with a public API. Visit our http.service.ts file and add the following: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class HttpService { constructor(private http: HttpClient) { } getBeer() { return this.http.get('') } } First, we import the HttpClient, then we create an instance of it through dependency injection, and then we create a method that returns the response from the API. Simple! We have to import the HttpClientModule in our /src/app/app.module.ts file: import { HttpClientModule } from '@angular/common/http'; // Add this @NgModule({ imports: [ BrowserModule, AppRoutingModule, FormsModule, HttpClientModule // Add here ], Next, open up the list.component.ts file and add the following: export class ListComponent implements OnInit { brews: Object; constructor(private _http: HttpService) { } ngOnInit() { this._http.getBeer().subscribe(data => { this.brews = data console.log(this.brews); } ); } } The service returns an observable, which means we can subscribe to it within the component. In the return, we can pass the data to our brews object. Next, visit the list template file and add the following: <h1>Breweries</h1> <ul ngIf="brews"> <li * <p class="name">{{ brew.name }}</p> <p class="country">{{ brew.country }}</p> <a class="site" href="{{ brew.website_url }}">site</a> </li> </ul> First, we add an ngIf to only show the UL element if brews exists. Then, we iterate through the array of objects with *ngFor. After that, it's a simple matter of iterating through the results with interpolation! Let's style this with CSS real quickly in this component's .scss file: ul { list-style-type: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; li { background: rgb(238, 238, 238); padding: 1em; margin-right: 10px; width: 20%; height: 200px; margin-bottom: 1em; display: flex; flex-direction: column; p { margin: 0; } p.name { font-weight: bold; font-size: 1.2rem; } p.country { text-transform: uppercase; font-size: .9rem; flex-grow: 1; } } } And here's the result! Let's say that we're happy with our app and we want to deploy it. We first have to create a production build with the Angular CLI. Visit the console and issue the following command: > ng build --prod This will create a /dist folder. We can even run it locally with something like lite-server. To install lite-server: > npm i -g lite-server Hop into the folder: myapp\dist\myapp</strong> and run: > lite-server This will launch the production build in the browser! At this point, you have a number of options for deploying it (Github Pages, Netlify, your own hosting, etc..). We've just scratched the surface here, but you also learned ton. I suggest recreating another app using everything you've learned here before proceeding with more of the intermediate to advance topics. That way, you can really commit the fundamental stuff to memory through repition. Enjoy! angular...
https://morioh.com/p/2002dee64003
CC-MAIN-2020-40
refinedweb
2,488
56.35
Hello fellow programmers! I was going to write a small program for calculating total pay for different periods of time depending on the amount of hours and the salary that the user enters. I managed to make a small bit of the program but when I try to run it and test it I get the following error: Line 33: error: no match for 'operator*' in 'pay * hours_day' I tried doing a google search on this problem but I am really confused on what causes it. here is my full program code: #include <iostream> #include <random> #include <time.h> #include <cstdlib> #include <string> using namespace std; /* *Program Flowchart* - Find out how much a worker gets paid per hour, and then find out how many hours they work a day, and then multiply that to get the total pay in a week or a month or a year. */ // global variables string pay; float hours_day; // function that takes the amount of money and calculates the total pay in a week int total_pay_week() { cout << "Type in your salary per hour." << endl; cin >> pay; cout << "Ok, how many days do you work per day?" << endl; cin >> hours_day; float total_day = pay * hours_day; float total_week = total_day * 7; cout << "Your total pay in a week is " << total_week << "if you worked " << hours_day << " per day. " << endl; } int main() { total_pay_week(); } This is a very early version of my program! I just wanted to know what causes this problem.
http://www.howtobuildsoftware.com/index.php/how-do/buB/c-c-11-no-match-for-operator-error
CC-MAIN-2018-13
refinedweb
238
72.8
On Thu, Aug 15, 2013 at 6:48 PM, Ryan <rymg19 at gmail.com> wrote: > For the naming, how about changing median(callable) to median.regular? > That way, we don't have to deal with a callable namespace. > Hmm. That sounds like a step backwards to me: whatever the API is, a simple "from statistics import median; m = median(my_data)" should still work in the simple case. Mark > > Steven D'Aprano <steve at pearwood.info>): >> ... >> ... >> >> >> In my earlier stats module, I had a single median function that took a argument to choose between alternatives. I called it "scheme": >> >> median(data, scheme="low") >> >>.) >> >> >> > -- > Sent from my Android phone with K-9 Mail. Please excuse my brevity. > > _______________________________________________ > Python-Dev mailing list > Python-Dev at python.org > > Unsubscribe: > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <>
https://mail.python.org/pipermail/python-dev/2013-August/127991.html
CC-MAIN-2022-05
refinedweb
134
68.87
A class definition starts with the class, struct, or union keyword. The difference between a class and a struct is the default access level. (See Section 6.5 later in this chapter for details.) A union is like a struct for which the storage of all the data members overlap, so you can use only one data member at a time. (See Section 6.1.3 later in this section for details.) A class definition can list any number of base classes, some or all of which might be virtual. (See Section 6.4 later in this chapter for information about base classes and virtual base classes.) In the class definition are declarations for data members (called instance variables or fields in some other languages), member functions (sometimes called methods), and nested types. A class definition defines a scope, and the class members are declared in the class scope. The class name itself is added to the class scope, so a class cannot have any members, nested types, or enumerators that have the same name as the class. As with any other declaration, the class name is also added to the scope in which the class is declared. You can declare a name as a class, struct, or union without providing its full definition. This incomplete class declaration lets you use the class name in pointers and references but not in any context in which the full definition is needed. You need a complete class definition when declaring a nonpointer or nonreference object, when using members of the class, and so on. An incomplete class declaration has a number of uses: If two classes refer to each other, you can declare one as an incomplete class, then provide the full definitions of both: class graphics_context; class bitmap { ... void draw(graphics_context*); ... }; class graphics_context { ... bitblt(const bitmap&); ... }; Sometimes a class uses hidden helper classes. The primary class can hold a pointer to an incomplete helper class, and you do not need to publish the definition of the helper class. Instead, the definition might be hidden in a library. This is sometimes called a pimpl (for a number of reasons, one of which is "pointer to implementation"). For example: class bigint { public: bigint( ); ~bigint( ); bigint(const bigint&); bigint& operator=(const bigint&); ... private: class bigint_impl; std::auto_ptr<bigint_impl> pImpl_; }; For a complete discussion of the pimpl idiom, see More Exceptional C++, by Herb Sutter (Addison-Wesley). Example 6-1 shows several different class definitions. #include <string> struct point { double x, y; }; class shape { public: shape( ); virtual ~shape( ); virtual void draw( ); }; class circle : public shape { public: circle(const point& center, double radius); point center( ) const; double radius( ) const; void move_to(const point& new_center); void resize(double new_radius); virtual void draw( ); private: point center_; double radius_; }; class integer { public: typedef int value_type; int value( ) const; void set_value(int value); std::string to_string( ) const; private: int value_; }; class real { public: typedef double value_type; double value( ) const; void set_value(double value); std::string to_string( ) const; private: double value_; }; union number { number(int value); number(double value); integer i; real r; }; Some programming languages differentiate between records and classes. Typically, a record is a simple storage container that lacks the more complex features of a class (inheritance, virtual functions, etc.). In C++, classes serve both purposes, but you can do things with simple classes (called POD, for plain old data) that you cannot do with complicated classes. Basically, a POD class is a structure that is compatible with C. More precisely, a POD class or union does not have any of the following: User-defined constructors User-defined destructor User-defined copy assignment operator Virtual functions Base classes Private or protected nonstatic members Nonstatic data members that are references Also, all nonstatic data members must have POD type. A POD type is a fundamental type, an enumerated type, a POD class or union, or a pointer to or array of POD types Unlike C structures, a POD class can have static data members, nonvirtual functions, and nested types (members that do not affect the data layout in an object). POD classes are often used when compatibility with C is required. In that case, you should avoid using any access specifier labels because they can alter the layout of data members within an object. (A POD class cannot have private or protected members, but you can have multiple public: access specifier labels and still have a class that meets the standard definition of a POD class.) Example 6-2 shows POD types (point1 and info) and non-POD types (point2 and employee). struct point1 { // POD int x, y; }; class point2 { // Not POD public: point2(int x, int y); private: int x, y; }; struct info { // POD static const int max_size = 50; char name[max_size]; bool is_name_valid( ) const; bool operator<(const info& i); // Compare names. }; struct employee : info { // Not POD int salary; }; The virtue of a POD object is that it is just a contiguous area of storage that stores some value or values. Thus, it left uninitialized, but a non-POD object is initialized by calling its default constructor. Similarly, a POD type in a new expression is uninitialized, but a new non-POD object is initialized by calling its default constructor. If you supply an empty initializer to a new expression or other expression that constructs a POD object, the POD object is initialized to 0. A POD class can contain padding between data members, but no padding appears before the first member. Therefore, a pointer to the POD object can be converted (with reinterpret_cast<>) into a pointer to the first element. A goto statement can safely branch into a block, skipping over declarations of uninitialized POD objects. A goto that skips any other declaration in the block results in undefined behavior. (See Chapter 2 for more information about initializing POD objects, and Chapter 4 for more information about the goto statement.) A trivial class is another form of restricted class (or union). It cannot have any of the following: User-defined constructors User-defined destructor User-defined copy assignment operator Virtual functions Virtual base classes Also, all base classes must be trivial, and all nonstatic data members must be trivial or have non-class type. Unlike POD classes, a trivial class can have base classes, private and protected members, and members with reference type. Trivial classes are important only because members of a union must be trivial. Fundamental types are trivial, as are pointers to and arrays of trivial types. A union is like a struct, but with the following restrictions: It cannot have base classes. It cannot be a base class. It cannot have virtual functions. It cannot have static data members. Its data members cannot be references. All of its data members must be trivial. An object of union type has enough memory to store the largest member, and all data members share that memory. In other words, a union can have a value in only one data member at a time. It is your responsibility to keep track of which data member is "active." A union can be declared without a name (an anonymous union), in which case it must have only nonstatic data members (no member functions, no nested types). The members of an anonymous union are effectively added to the scope in which the union is declared. That scope must not declare any identifiers with the same names as the union's members. In this way, an anonymous union reduces the nesting that is needed to get to the union members, as shown in Example 6-3. struct node { enum kind { integer, real, string } kind; union { int intval; double realval; *char strval[8]; }; }; node* makeint(int i) { node* rtn = new node; rtn->kind = node::integer; rtn->intval = i; return rtn; } You can declare a local class, that is, a class definition that is local to a block in a function body. A local class has several restrictions when compared to nonlocal classes: A local class cannot have static data members. Member functions must be defined inline in the class definition. You cannot refer to nonstatic objects from within a local class, but you can refer to local static objects, local enumerators, and functions that are declared locally. A local class cannot be used as a template argument, so you cannot use a local functor with the standard algorithms. Local classes are not used often. Example 6-4 shows one use of a local class. // Take a string and break it up into tokens, storing the tokens in a vector. void get_tokens(std::vector<std::string>& tokens, const std::string& str) { class tokenizer { public: tokenizer(const std::string& str) : in_(str) {} bool next( ) { return in_ >> token_; } std::string token( ) const { return token_; } private: std::istringstream in_; std::string token_; }; tokens.clear( ); tokenizer t(str); while (t.next( )) tokens.push_back(t.token( )); }
http://etutorials.org/Programming/Programming+Cpp/Chapter+6.+Classes/6.1+Class+Definitions/
crawl-001
refinedweb
1,476
51.78
Namespaces in C++ In C++, all identifiers in the global scope must be unique. This may become a problem, especially in larger projects where a programmer uses a lot of components from different libraries. In such cases there's high chance that two components will have the same name in two different libraries, a situation called name collision or conflict. This makes impossible to use those libraries together. In C and some other languages this problem is solved by adding a specific prefix to the names of all identifiers in a specific library. This guarantees that there are no equal identifiers in any two libraries. Unfortunately this increases the length of the identifiers and thus reduces readability and convenience of programming. Namespaces are an elegant solution to the problem. Instead of an immutable prefix to the identifier names, namespaces introduce a new, named scope. From within the namespace, all identifiers are referenced as usual. However, if one wants to refer to the identifiers from outside the namespace, the namespace prefix nmname:: must be prepended, where nmname is the name of the namespace. See the example below: #include <iostream> namespace yyy { void baz() { std::cout << "baz\n"; } void foo() { baz(); } // no need to append the name of the namespace } // namespace yyy namespace zzz { void foo() { std::cout << "foo\n"; } } // namespace zzz int main() { yyy::foo(); // Both functions can be called, even though zzz::foo(); // they have the same name } Output: baz foo Note that the // namespace yyy comments are not required, they are only there only for clarity. [edit] Syntax [edit] Nested namespaces [edit] Importing a namespace One of the features of a namespace is that it's possible to remove the namespace prefix to save a bit of typing. The basic syntax of a namespace import declaration is as follows: using namespace nmspace_name; After such declaration, all names that we would otherwise have referred as nmspace_name::identifier can be used simply as identifier. #include <iostream> namespace yyy { namespace zzz { void baz() { std::cout << "baz"; } } // namespace zzz using namespace zzz; void foo() { baz(); // Can use baz without zzz:: zzz::baz(); // Still can use baz explicitly } } // namespace yyy using namespace yyy; int main() { yyy::foo(); // explicit cal foo(); // yyy was imported // The following four call the same function via different path yyy::zzz::baz(); // Explicit call, this would be needed if we didn't // import the namespaces zzz::baz(); // The contents of namespace yyy were imported into the global namespace yyy::baz(); // The contents of namespace zzz were imported into the yyy namespace baz(); // baz was imported into yyy and then into the global namespace std::cout << "\n"; } Output: bazbazbazbazbazbaz [edit] Alias The verbosity of namespaces can be an advantage as well as an inconvenience. Consider the following example: #include <boost/asio.hpp> int main() { boost::asio::io_service io; boost::asio::ip::tcp::socket s(io_service); return (0); } As you can see, this is getting a little too verbose and can lead to confusion. You could use "using", but you will loose all verbosity. This is where aliases come in handy: #include <boost/asio.hpp> namespace boost_tcp = boost::asio::ip::tcp; int main { boost::asio::io_service io; boost_tcp::socket s(io_service); return (0); } By making a alias, you can clear out your code while still keeping some verbosity. [edit] Conclusion Namespaces are not essential in order to make a functioning program, but it is a good practice and should be considered when writing at least a meduim-sized program, especially if it contains modules or APIs.
https://en.cppreference.com/book/intro/namespaces
CC-MAIN-2018-39
refinedweb
584
53.55
The JavaScript API for embedding Apple maps on your website. SDK - MapKit JS 5.0+ Framework - Map Kit JS Declaration interface mapkit Overview The mapkit object is the main namespace for the MapKit JS framework. Similar to MapKit for apps, you can use the mapkit library to display interactive maps with customized annotations and overlays, and provide directions and search services. Your app can supply step-by-step navigation, and help a user find a location by autocompleting a search query. MapKit JS lets you customize the look of your map. You can choose style details for overlays and annotations, display a standard street map or one that uses satellite imagery, and adjust the visibility of map controls. Additionally, you can customize a map's behavior by providing event handlers that scroll the map or respond when users select items. You can also enable or disable panning, zooming, and rotation.
https://developer.apple.com/documentation/mapkitjs/mapkit
CC-MAIN-2019-47
refinedweb
150
55.03
Code Focused Learn how to create powerful templates that can be called from both client- and server-side code. We're going to look specifically at three pieces of the framework that can be combined to provide a new technique. This technique helps in writing more responsive ASP.NET pages, while at the same time making the code more readable. The three technologies are: XML literals, Windows Communication Foundation (WCF) Factory Services and LINQ. XML literals and LINQ are new in Visual Basic 9 (VB9). LINQ gives us a common syntax for querying just about any data, be it SQL, XML or objects. Even though WCF has been here for a while, the out-of-the-box readiness for building factory services is little-known. Here we'll show you how to create WCF services without changes to config files for endpoints, behaviors and bindings. XML Literals VB9 includes XML literals, an incredibly useful new tool. With XML literals, what used to be an archaic, difficult process of reading and writing raw XML or XHTML has become straight-forward and simple. Type raw XML into the Visual Studio Editor and it understands that you want an XElement. An XML literal on its own is a remarkable piece of technology that can help VB developers in many, many ways. What used to make code difficult to read becomes transparent when using XML literals. For example, using a StringBuilder to write long strings makes writing joined strings easier and more performant: Dim MyText = String.Empty Dim sb As New StringBuilder With sb .Append("This is a String.") .Append(vbCrLf) .Append(vbTab) .Append("You will notice that the whitespace ") .Append("is retained when we use the string.") .Append(vbCrLf) .Append(vbTab) .Append(vbCrLf) .Append(vbTab) .Append("This is just the beginning and is a bit ") .Append("easier to read than StringBuilder, right?") MyText = .ToString End With Reading and writing these in the editor is less productive than if you could just write the whole string and retain the whitespace as follows: <MyString> This is a String. You will notice that the whitespace is retained when we use the string. This is just the beginning and is a bit easier to read than StringBuilder, right? </MyString> Compared to StringBuilder, XML literals are far easier to read and much less to type. Use MyString.Value to get the text inside without the <MyString> tags. The goal here is not to maximize performance in the runtime, but to be more productive. You can actually read the string and don't worry; performance will still be very good. String handling with XML literals is just a side note. For structured elements that really are XML, such as XHTML, there is no comparison. The XML literals approach gives us a highly readable, productivity enhanced solution to writing structured XML in code behind. Consider the following: Dim MyTable = _ <table> <tr> <td> First Cell Contents </td> <td> Second Cell Contents </td> </tr> </table> Reading XHTML in code behind is now remarkably easier. You also get true IntelliSense for the elements that are in a known namespace, which of course means even less typing. XML namespaces are recognized by using Imports statements such as the following for XAML: Imports <xmlns= " winfx/2006/xaml/presentation"> Imports <xmlns:x= " winfx/2006/xaml"> Imports System.Windows.Markup The result of all this is that you can do things the same way for code behind as you are used to doing in ASPX source view. Productivity increases by continuing to write markup this way. You do not have to learn another language or syntax to achieve the same in code behind. Embedded expressions also look very similar to what you are used to seeing in markup: <td><%= [email protected] %></td> An embedded expression lets you access something outside the XML literal and embed it into the result. In this case; [email protected] is an attribute from an item element in another XElement. Additionally, variables aren't limited here; you can use lambdas, functions or anything else available to VB. I know what you're thinking, so I'll go ahead and say it. "If you're loading from XML and returning XML, can't you just use XSLT?" Of course we could, but what fun is that? In fact, I came up with this technique in a project overhaul that was using XSLT in its previous version. During development, it became quite clear that working in XSLT was not the way to go for us. XSLT is a completely different mindset for most of us and has a fairly steep learning curve. In addition, the old system was forcing SQL to return data as XML, which is not exactly optimal. This approach eliminated that issue while dramatically improving performance. Ultimately, using XML literals means you can be productive faster and have more tools at your disposal for debugging, without learning a new language. WCF Factory Services I have a Web site that is currently in production. I need to add some performance features to it and I don't want to retool to accomplish what I need. I could use AJAX and update panels, but then I would need to account for the entire page lifecycle, which in some cases may be quite large. For example, I have a page that contains aggregate information and I wish to display that in a table format. I could put all my aggregates into GridView objects and then place those inside update panels, then … no, no, no. I'm sure you see the trouble here already. If I have more than one update panel on the page, I'm really loading the entire page multiple times, just to get my aggregated information to run asynchronously. How can you achieve this without creating a new project, using PageMethods or something else with a large lifecycle? Enter Windows Communication Foundation (WCF). WCF has always had a lesser-known feature called a factory service. With factory services, you don't have to worry about things like security, as it inherits the same security as the site. As for config settings, there are none. This is a perfect solution when you need to access some information in an AJAX way from client-side code. The factory services are quite similar to WebMethod(), but they're completely WCF compliant. To create a factory service, you simply create a new WCF service. But wait, you said factory service; I don't see any factory service in my Add Items templates. That is correct, to create a configuration-less factory service you need to do it by hand; editing the .SVC file of an AJAX-enabled WCF service. To do this, open the .SVC file with the XML editor and add the following: Factory="System.ServiceModel.Activation. WebScriptServiceHostFactory" Then you have to go and delete the config information. Because this isn't an intuitive way to proceed, I created a template that you can install to do the same thing. Install the template by copying WCF_FactoryService.zip to C:\Users\<yourusername>\Documents\Visual Studio 2008\ Templates\ ItemTemplates\Visual Basic With this template, you can create services that your Web application can use in a very easy way with no bother to the current configuration. If you need to move to a full service with different bindings, it's very easy to change this from a factory service. Simply delete the factory attribute from the .SVC file and add your binding, behavior, service and endpoint configurations to web.config. Something you might be thinking: Why use WCF services and not a regular page that just returns the small amount of data we need? While this approach makes sense in some instances, you still have a full-page lifecycle to deal with. Furthermore, the results aren't as easy to work with when you want to insert them into a portion of an already rendered page with JavaScript. If you used a page you would have to do quite a bit of parsing. In addition to the speed of execution for WCF, there are supporting features that will make life easier. Throwing FaultExceptions is one thing you cannot do with page results. You can throw HttpExceptions, but they aren't handled the same way on the client. Using LINQ LINQ provides the magic you need to glue all this together. Writing markup in code behind is easier to read, while accessing the same code from both the client side and the server side gives you a lot of power. Combining LINQ and embedded expressions in XML literals gives you a better way to handle looping through data. Instead of a table, let's shift to something more demonstrative, the <ul> element. Say you just need to iterate through a group of items and return an unordered list. Unordered lists are great for things like menus and navigation. How is this accomplished with our new toolset? Let's look into that now. In the past you had to do something like the following: Dim ul as New HtmlGenericControl("ul") Dim li As HtmlGenericControl For Each i In items li = New HtmlGenericControl("li") li.InnerHtml = i.Value ul.Controls.Add(li) Now you can do this: Dim MyMenu = <ul><%= From i In items Select <li><%= i.Value %></li>%></ul> The embedded expressions let you insert external data into your elements with much less code. Given the same data, the output is identical. Let's dissect what's happening here. MyMenu is an XElement cast by Option Infer, which is a new feature in VB9 that lets you declare variables without explicitly stating a data type. The compiler infers the data type of a variable from the type of its initialization expression. The <ul> element is outside the LINQ query so it's not repeated. The LINQ query iterates through the items and returns a group of <li> elements inside the <ul> element, with the item's value inserted into the list item. All of this can now be done in one line of easy to read and simple to type code. Anything used for lists of data can be done this way: tables, unordered lists, ordered lists, select inputs (dropdowns), and the like. Have you ever done a view source on a page only to see a dropdown with all the states listed as options in the HTML? Using WCF services with AJAX will keep people from being able to see this with view source. You'll probably get your page to load faster if that was an AJAX call. XML literals give you the power to create data presentation dynamically, in ways that are more productive than many other alternatives. Any LINQ-enabled data, SQL, entities, objects, files, WMI, XML, RSS feeds and the like can be accessed this way. Now that you have all three pieces in place, your Web application is wired up to both client and server sides. Accessing the service from the server is as simple as calling a method. The service is already there and calling it is as simple as Services. GetPresidentsList(). On the client you can use ASP.NET AJAX or jQuery to call the service. Referencing services in ASP.NET AJAX is incredibly easy -- just add a ScriptManager that points to the service as follows: <asp:ScriptManager <Services> <asp:ServiceReference </Services> </asp:ScriptManager> Calling the service in JavaScript is now very easy and completely wired up for us: function getPresidents(){ var ws = new Services.MyService(); ws.GetPresidentsList(getPresidentsComplete); } function getPresidentsComplete(result, eventArgs){ if (result.d !== null){ $find("<%= PresidentsArea.ClientID %>").InnerHtml = result.d;} } This makes an asynchronous call to the service and the result is returned when the service performs a callback to getPresidentsComplete (). You have the ability to call the service both synchronously and asynchronously, depending on what you need to accomplish. Here's the same idea using jQuery: $.ajax({ type: 'POST', url: '/Services/MyFactoryService.svc/' + 'GetPresidentsList', data: '{}', contentType: 'application/json; charset=utf-8', dataType: 'json', success: function(result, eventArgs) { if (result.d !== null){ $("#<%= PresidentsArea.ClientID %>") [0].innerHTML = result.d;} }, error: onServiceError }); The json notation is assigned for the dataType because WCF is returning JSON for the result object. The syntax is a little different, but is still pretty easy to use. jQuery's nice ajax() method does all the work for you, and what you get returned from the service ends up in result.d. I used an anonymous function here to retrieve the result, which we expect to be XHTML into the InnerHtml of our div element target. We can inspect for errors, but you can see that if we threw any FaultExceptions in the WCF service, then another function called onServiceError runs. The Error Handling function is passed to the result object for us to inspect for errors and react accordingly. My normal process for using this in a production application is to define a single function in my master page for calling the service. If you provide accessibility through several shortcuts, getting results from the services and assigning those results become even easier. Here's a sample that I've used: function execMyFactoryService(method, target) { var rval = ''; $.ajax({ type: 'POST', url: '/Services/MyFactoryService.svc/' + method, data: '{}', async: true, contentType: 'application/json; charset=utf-8', dataType: 'json', success: function(result, eventArgs) { if (result.d !== null){ target.innerHTML = result.d; } }, error: function(result) { var msg = ''; if (result.get_message) { msg = 'Error: ' + result.get_message(); } else { msg = result.responseText; if (msg == '') { msg = 'Error: Unknown... missing Service?'; } } alert(msg); target.innerHTML = ''; } }); } Assigning our result to a position on our page is simple. Place a <div> element anywhere on your page and set the innerHTML to the result. Anywhere I'm using that master page; I will have a function that I can use to directly assign the results: execMyFactoryService('GetPresidentsList', $("#<%= PresidentsArea.ClientID %>")[0]); All the error handling and result inspection is handled centrally and when we're assigning results as the response to some action on the Page, this makes understanding what's happening much easier. If we were to use the full $.ajax syntax everywhere we needed to use it, it might make the scripting too verbose to be readable at first glance. jQuery provides a great productivity boost through a superb set of tools for navigating and manipulating DOM objects in JavaScript. Some of the same features are in ASP.NET AJAX, but the two models can be used together to provide even more power for your client-side activities. The Whole Picture Now that I've explained the parts and pieces, how does it all work together? Let's explore this a little further. A complete template looks like this inside the service: <OperationContract()> _ Public Function GetPresidentsTable() As XElement Dim items = XElement.Load(ApplicationPhysicalPath & _ "App_Data/SampleData.xml") Try Dim result = _ <table> <thead> <th>Position</th> <th>Name</th> <th>Began Term</th> <th>Finished Term</th> </thead> <%= From i In items.Elements Select _ <tr> <td><%= [email protected] %></td> <td><%= [email protected] %></td> <td><%= [email protected] %></td> <td><%= [email protected] %></td> </tr> _ %> </table> Return result Catch ex As Exception ' This is not returning a StackTrace, ' it's a shortcut to get the current Method Name Throw New FaultException(New StackTrace() _ .GetFrame(0).GetMethod() _ .Name & ": " & ex.Message) Return Nothing End Try End Function The service is a WCF factory service. These are very simple to create, with the Visual Studio Template included here. I use a Services Folder in my Application for organization and security. Add the Services Folder, and then add a web.config for the folder. This lets us assign different security rights to the services in the folder if we need to limit them by Roles. Adding a New Item to your Web Application looks like Figure 1. The new Template is in the My Templates area at the bottom of the dialog. If you're like me, you probably have many installed Templates you need to scroll through to get to My Templates. When the template creates the service, we can inspect the configuration data using Open With. Choose XML Editor from the list. This will open the .SVC file for us, rather than the code behind that gets opened when you double-click on the file itself. You may see some IntelliSense confusion from the editor, but you can safely ignore it. The generated service is: <%@ ServiceHost Language="VB" Debug="true" Service="Services.MyFactoryService" Factory="System.ServiceModel.Activation. WebScriptServiceHostFactory" CodeBehind="MyService.svc.vb" %> The code behind is: Imports System.ServiceModel Imports System.ServiceModel.Activation Imports System.Web.Script.Serialization Imports System.Runtime.Serialization Namespace Services ''' <summary> ''' This Service provides access to various ''' MyFactoryService procedures through WCF ''' </summary> ''' <remarks></remarks> <ServiceBehavior( _ IncludeExceptionDetailInFaults:=True)> _ <ServiceContract(Namespace:="Services", Name:= _ "MyFactoryService")> _ <AspNetCompatibilityRequirements( _ RequirementsMode:= _ AspNetCompatibilityRequirementsMode.Allowed)> _ Public Class MyService <OperationContract()> _ Public Sub DoWork() End Sub End Class End Namespace All that's left for us to do is enter the code into DoWork(). Usually you'll want to rename this, which is fine, because what's presented here is just a stub to get us started. For debugging we simply add a Try/Catch block to handle anything bad that may cause the template to break. For this example we are just returning Nothing, but we could add very rich error handling here by throwing FaultExceptions. FaultExceptions are handled quite nicely by ASP.NET AJAX and jQuery on the client. You can decide how to handle problems in the service and the client can respond using a combination of results and error handling. Let's talk briefly about what you can do with this in your toolbox. I want to display a bunch of images dynamically. Maybe I want to get the results from a search out on the Web. I could configure something in the client, or I could stay consistent and use our own services. This lets us control everything and not expose possibly sensitive information in the client-side code, such as a password. We won't build that one right now, but think about how useful it could be to control going out to your external service accounts to grab dynamic status or images from social networking services. In our Presidents sample we could go look on an external service for the images of the Presidents. Configuring this is really quite easy now that we have a set of tools to work with that makes this simple. I could use a WebClient to call the external API and work with the results in the service prior to returning them. What if I already have the images? How do I get them from the file system easily? I would create a service method similar to this: <OperationContract()> _ Public Function GetPortrait( _ ByVal value As String) As XElement Dim image = (From FileName In _ My.Computer.FileSystem.GetFiles( _ HttpContext.Current.Server.MapPath( _ "~/Images")) Where FileName.StartsWith(value) Let File = _ My.Computer.FileSystem.GetFileInfo(FileName) Select <img src=<%= HttpContext.Current.Server.MapPath( _ File.FullName) %> title=<%= File.Name %>></img>).First() Return image End Function I have provided a dynamic function to return an image from our file system -- certainly not a daunting task for us now. We can expand this to handle getting the image path any way that suits our needs and we can surround all the proper error handling in the function. I can return either an appropriate fault exception or an empty element to just ignore missing images, so the client doesn't see errors. When designing a template consider what's static and what requires looping. Looping should be done with either LINQ or lambdas in this case. A Do Loop or For Each works just as well, but I find myself replacing them with LINQ since I had no other alternative before. It also makes the code much easier to work with in templates if you use LINQ. Something to consider here is the use of lambda expressions. Lambdas are a new feature in VB9 and can save you a lot of hassle when you need a quick function. LINQ itself is actually a framework built on lambda expressions and are an integral part of how it works. Lambdas in Visual Basic look like this: Function(u) If(u.Age < 18, _ u.ParentPermissionGranted, u.PermissionGranted) This function will evaluate the condition, and then return a different field from the user object based on the condition. The interesting thing here is that we didn't have to tell the lambda what u is, inference will do that for us most of the time. Occasionally inference gets confused and you may need to qualify what u is which you can do with: Function(u As User) I don't want to go on too much about lambdas, you will use them all the time with LINQ. Just about any time you need a Where clause you'll be using lambdas. LINQ hides some of the verbosity for you when you're using the full query syntax, but it's still a lambda. When you use the extension syntax you almost always use lambdas: items.Elements.Where(Function(i) [email protected] = 1) Another reason I bring this up now is to answer the question: What if we need to return complex conditioning to our data when we build the return? This is much easier with lambdas than creating a bunch of functions that may only be used for this specific template. When building our template, maybe we want to change the elements returned based on some criteria in the data. Extended syntax like lambdas make very powerful tools for building templates. Easy Formatting Based on Conditions Because we have a true ternary If() command available to us we can make templates that do this: <%= If(items.Count = 0, _ <tr id="norecords" class="GridRow"> <td style="text-align: left" colSpan="4"> <div>No records to display.</div> </td> </tr>, _ CType(Nothing, XElement)) _ %> <%= -- - continue normal processing -- - %> This template lets us return Nothing when we have real data to work with, or an element describing the lack of data to the user. I can go on and on about the wealth of possibilities you have at your disposal when using all these techniques together. The Bottom Line Currently, nothing else is this flexible and this easy with the out-of-the-box tools we get with Visual Studio 2008. You have complete access to all the features of .NET Framework for building your templates. Calling them from both the client and server is extremely easy, and because you're using WCF, ther's no added page lifecycle overhead. A similar service can be created to return XAML instead of XHTML. This makes migrating or extending your templates extremely easy if you need access from Silverlight or WPF in the future. T4 templates and other code generator-based utilities are great when you can generate everything in advance. This technique goes beyond that to generate during runtime, and we can generate runtime-ready code in any XML derivative such as XAML and XHTML. ASP.NET 4.0 is expected to provide a new template system, but that doesn't change the usefulness of this technique. ASP.NET 4.0 will be using a completely different system, which may or may not be as easy to use and as flexible in what it returns. From what I've seen so far, it looks good, but it still doesn't solve the immediate issues that are addressed by using this technique. XML literals, WCF factory services and LINQ, taken by themselves, are very useful. When these are combined, you get a completely different picture for solving real-world problems. All while maintaining a productive, easy-to-implement style. XML literals provide high productivity and readability when writing structured XML in code behind. It can also help format long or complex strings to make them more readable. Embedded expressions give you the power to insert external data into the XML in a very easy-to-read and -maintain way. WCF factory services allow you to extend the power of the framework to your client-side code without the hassle of all the configuration knobs and buttons that are available to WCF services. Starting with a factory service does not limit you in any way from upgrading to the full configuration format later. A simple change enables a progressive upgrade path when you need this ability. Finally, using LINQ in embedded expressions enables you to insert external data into XML in a way that is easy to read, with much less code to accomplish the task. LINQ allows you to start thinking differently about how you process loops through any data utilizing the same syntax. Now go see what you can do with all this new power and
https://visualstudiomagazine.com/articles/2009/04/01/xml-literals-wcf-and-linq.aspx
CC-MAIN-2020-45
refinedweb
4,146
63.8
Details - Type: Test - Status: Resolved - Priority: Major - Resolution: Fixed - Affects Version/s: 3.0.0-alpha1 - Fix Version/s: 3.0.0-alpha1 - - Labels:None Description HADOOP-9112 has added a requirement for all new test methods to declare a timeout, so that jenkins/maven builds will have better information on a timeout. Hard coding timeouts into tests is dangerous as it will generate spurious failures on slower machines/networks and when debugging a test. I propose providing a custom JUnit4 test runner that test cases can declare as their test runner; this can provide timeouts specified at run-time, rather than in-source. Issue Links - relates to HADOOP-12439 test-patch should -1 for @Tests without a timeout - Reopened Activity - All - Work Log - History - Activity - Transitions As I have commented elsewhere setting a time out in the runtime can be achievable through surefire.timeout property, can it not? setting a time out in the runtime can be achievable through surefire.timeout property, can it not? surefire.timeout is a test process timeout or per test class if fork mode is always, not per test, which is the rationale for HADOOP-9112 in the first place. we can use the @RunWith attribute in a test class to define a custom test runner for it. There is no need to use a custom test runner. org.junit.rules.Timeout is what you want. We can create a common base test class like this. public class TestBase { @Rule public Timeout defaultTimeout = new Timeout(Integer.parseInt( System.getProperty("test.default.timeout", 100000))); ... } Avoiding subclassing of a common test class is one of the main reason people are migrating away from Junit3, IMO. Do we really want to enforce subclassing? As for 'per class' vs 'per testcase': if your test case has timed out then it will terminate the whole class run, won't it? Do we really want to enforce subclassing? No, you can use the @Test(timeout=seconds) just fine. You can add the default per test timeout rule to any test class as well. TestBase with a per test default timeout is just a convenience. if your test case has timed out then it will terminate the whole class run, won't it? Please read the comments on HADOOP-9112 to find out why this is not desirable. Oh right... this is @Rule. Sorry, I misread your comment. Yes, this sounds like a proper way to go. Plus, we need to lose the enforcement in the test-patch - it is no go in the first place. @Luke: if that's all we need to do, that's all we need. - We should be able to put this base test case into hadoop-common test & have it imported by the other projects -which all import the -test JAR. - What name & package? Konstantin: I thought the switch from JUnit3 to JUnit4 was driven by the goal of adding beforeclass/afterclass methods and so setup/teardown miniclusters only once per test class, not per test. The added benefit we get is being able to skip, not just in attributes, but by raising AssumptionViolatedException, either from the assume(), method, or in your own code. I'm using that in some of my tests already. If using a @Rule/MethodRule Timeout I'd suggest 2 additional things: - Have a @TestTimeout annotation as well to be able to set a timeout other than the default for particular test method. - Instead having a system property set the default timeout, lets specify a timeout.ratio, with default 1, by doing this the ratio can be also applied to tests that have a custom timeout Alejandro, the functionality of @TestTimeout exists in JUnit4. It is done through @Test{timeout=<number>} as far as I remember. Konstantin: I thought the switch from JUnit3 to JUnit4 was driven by the goal of adding beforeclass/afterclass methods Partially. However, the most pain has been caused by the need to subclass TestCase all the time. Oftentimes it blocked having a common pieces of the code being isolated in the same superclass for later use in the children, IIRC. @Konstantin: I see. Having a std test base with a timeout rule doesn't stop this provided all test cases add the same timeout rule. We could isolate the timeout extraction logic into a static method in the planned base class; other test cases could use that an their own @Rule declaration Cos, @Test{timeout = <> ) exist, yes, if we can tweak that timeout to take a global ratio into account then we are good. Agree with Steve that subclassing should be a convenience, not a requirement. If you subclass you get the @Rule setting for free, otherwise you have to do it yourself. first cut: test class (without any tests underneath to verify that it works) . The concept seems fine, but the Timeout rule and @Test(timeout=XXX) are not aware of each other. This means that the effective timeout of any test is which ever is smaller. I don't think that this is a real problem, just that the comments and the name of the member variable defaultTimout is slightly misleading. I also don't know if we have any tests that are intended to run for more than 100s. If so they will always timeout after 100s unless they do not extend the HadoopBase, or we set the default to be higher. Also, I don't know if there is anything we can do about this or not, but when we use both timeouts, the Timeout rule's backtrace, when it fails is close to useless. testSleep(org.apache.hadoop.test.TestSomething) Time elapsed: 1091 sec <<< ERROR! java.lang.Exception: test timed out after 1000 milliseconds at java.lang.Object.wait(Native Method) at java.lang.Thread.join(Thread.java:1194) at org.junit.internal.runners.statements.FailOnTimeout.evaluate(FailOnTimeout.java:36) at org.junit.internal.runners.statements.FailOnTimeout$1.run(FailOnTimeout.java:28) It simply says that the code that "timed out" was a thread waiting for the actual test to finish running This is because there are actually two threads monitoring the test, instead of just one. I realize that a lot of my complaints are perhaps things that need to just be addressed by the JUnit, I just want us to be fully aware of them as we go into this and document things appropriately, so we know what is happening when issues arise. I'm happy with having a very long default timeout -as it's purpose is to stop Jenkins hanging. I personally think having any timeouts in individual tests is incredibly brittle for testing on different machines, so people should not be explicitly setting timeouts in tests except in specific cases, where somehow they can't just set the test runner properties to change the global default. - What default do you think the base class should have? 100s is <2 minutes, which should be enough for most tests -are there any which regularly come close to that time on anyone's system? (that's excluding minicluster setup/teardown)/ - What documentation are you thinking of? Is there something on writing and running tests? If not, it may be time. I agree that there should be something about writing and running tests, but I am not aware of it either. I was thinking of just the javadocs for HadoopTestBase, but a dedicated wiki page or a subsection of HowToContribute would probably be better. I agree that having timeout= in the code is brittle, and we probably want to start removing it once this goes in (along with the changes to test-patch.sh). But in a follow on JIRA I was thinking we probably could support something similar to what Luke Lu proposed. It should not be that hard to add in our own timeout test runner that can look for an @Test annotation with a timeout, output a warning about the timeout, and then allow JUnit to run with that timeout. We could also provide an @Timeout annotation that would let us specify a timeout multiplier that is X times the configured base timeout. That way we can keep a 100s timeout and adjust it for tests that do take longer. I am not tied to the idea though, and if it feels like too much work compared simply upping the default to something like 600s works we could do that instead. +1 committed to trunk. Thanks! SUCCESS: Integrated in Hadoop-trunk-Commit #10030 (See) HADOOP-9330. Add custom JUnit4 test runner with configurable timeout (aw: rev 610363559135a725499cf46e256424d16bec98a3) - hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/HadoopTestBase.java Discussions with the Maven Surefire team () imply that we can use the @RunWith attribute in a test class to define a custom test runner for it. This means we can Doing this will obviate the need to place brittle test timeouts in source, and be easy to retrofit to existing test classes. Assuming all future test cases get built off a new base class (possibly with tuned YarnTestBase, HdfsTestBase classes), the base classes would have to go back into branch-1 if there was any goal of backporting new tests from trunk. Unless Ant can be set up to switch to the new test runner, the @RunWith attribute would have to stripped from the backported test cases.
https://issues.apache.org/jira/browse/HADOOP-9330
CC-MAIN-2017-04
refinedweb
1,561
62.07
Just thought Id put this hear for you all to see that it might not be shutting down. [IMG] Thanks. Yes. Can someone provide an example of code of how to set this as a lore of an item? This ever going to be finished? This would remove the need for an external plugin to create npc's tho which would be good This would be awesome. anyone know why Im getting this? Thanks!!!!!! Example of code? Hi, Im working on a bukkit plugin for my network and I need to see if another server is online or offline and if it is online then how many people... Im trying to make a simple NPC spawn but its not working, heres my code: import java.util.List; import java.util.logging.Level; import... It worked, thanks for your help it does but how would I see what the block is? like this? @EventHandler public void onPlayerMove(PlayerMoveEvent event) { Player... Separate names with a comma.
https://dl.bukkit.org/members/ledship.90866370/recent-content
CC-MAIN-2020-24
refinedweb
164
83.56
Interfacing between Neo-6m gps sensor with Fipy Hello Team, We are trying to interface the neo-6m gps sensor with fipy board using default and undefault UART connections. How to interface neo-6m gps with Fipy using serial. Thank You @archana-kadam I looke dagain at you request. What I cannot understand is, why you do not simple set the respberry Pi to 115200 baud. Besides that, you can free UART0 from the REPL and reconfigure it to any speed you like, e.g. for 9600 baud: import uos from machine import UART uos.dupterm(None) uart0 = UART(0, 9600) Be aware, that after the "uos.dupterm(None)", the REPL and print etc. is on telnet only. Hello Team, Kindly any one can reply to the above question Thank you @robert-hh Ok thank you @archana-kadam I'm a user like you and not a PyCom member. My time slots for tests are evenings and weekends. I will surely look into your question, maybe this evening. @robert-hh Kindly reply for the above question Thank you @robert-hh We have checked with the code which you had provided, but the need is we are have connected gps sensor at uart1 which works at baudrate of 9600, and raspberry pi we have connected to uart0.But the problem is uart0's baudrate is 115200 so only we are not receiving the gps data as it is at uart0. Basically we need both the uart to be setup at 9600. How to to it?? Screen shot of the data output from fipy as well as raspberry is attached. This image is about raspberry pi output connected to the Uart 0. This image is about Gps output connected to the Uart 1 Thank You @archana-kadam I'll verify this night, but in your code the order of statements seem wrong. I suggest it is: import time from machine import UART import machine import os msg = '' os.dupterm(None) uart0 = UART(0, baudrate=115200) uart1 = UART(1, baudrate=9600) while True: time.sleep(3) msg = uart1.readall() print(msg) uart0.write(str(msg)) If it is just to print the data form the GPS sensor, you can simply keep REPL and use print. P.S.: For code to look nicely, enclose it in lines with three backquotes (```). P.P.S.: I upvoted three of your comments, such that you can pretty print code and respond faster. @robert-hh Hello, Am using below code to read on both the uarts of fipy, on uart0 i have connected GPS sensor and on uart1 i have connected raspberry pi, am reading the GPS data from uart0 and writing the same data on the uart1 i,e on raspberry pi. But the below code is not working as i wanted. Kindly help with this. import time from machine import UART import machine import os msg = '' uart1 = machine.UART(0, baudrate=115200) os.dupterm(None) uart1 = UART(1, baudrate=9600, pins=('P1','P0')) uart = UART(1, baudrate=9600) while True: msg = uart1.readall() time.sleep(3) print(msg) uart.write(str(msg)) print(msg) Thank You @robert-hh can you send the full code to disconnect REPL from uart0 and use it to read any uart sensor. And also after disconnecting on what baudrate it will work. @archana-kadam UART0 is connected to the REPL. If you want to disconnect REPL from UART0, you have to use the statement os.dupterm(None). After that, you can use it like UART1 and configure it as needed. For REPL, you may then use Telnet. @robert-hh Hello, We have already checked with the linked you have suggested, but in that they have only explained about the uart 1 example. Can you provide us the example of how to read both the uart 0 and uart 1 in the same code. Also how to change the default baud rate of uart1 and uart 0. Thank You Hello Team We are using two UART sensor, we have connected UART 0 and UART 1 i,e UART 0 (pins G1 and G2) and UART 1 (pins G11 and G24) How we can get the readings of both the UART connections in a single code and how we can set the boudrate of Fipy UART Connection. Please reply as soon as possible Thank you Hello Team, Can u share the interfacing between Neo-6m gps sensor with Fipy using serial communication. Thank You
https://forum.pycom.io/topic/3437/interfacing-between-neo-6m-gps-sensor-with-fipy/10
CC-MAIN-2019-39
refinedweb
741
72.76
Developers can convert an image to a byte array in C# since bitmaps and other images are made up of bytes. Converting an image to bytes is useful in many scenarios. A byte arrays can be easily compared, compressed, stored, or converted to other data types. For example, programmers can convert an image into a byte array and then convert the array to a string, thus converting an image to a string. Converting a bitmap into a byte array is simple with built-in .NET Framework functions. However there is more than one way to do it. We are going to cover two ways to transform a .NET image into a bunch of bytes. It is important to know how each method works to use it properly.. public static byte[] ImageToByte(Image img) { ImageConverter converter = new ImageConverter(); return (byte[])converter.ConvertTo(img, typeof(byte[])); } The thing to remember about ImageConverter, is that the image will be directly converted into bytes. Thus an image in bmp format and the same image in png format will NOT have the same byte array. So if you want to the compare two images for example, you would have to make sure they are first in the same format before comparing their byte arrays. The second method takes a little more C# code, but it is potentially more reliable. As you may already know, any .NET Image or Bitmap object has a Save function. The Save function is important because it allows programmers to save an image to a file in any image format supported by the .NET Framework. Even better is that an overload of the Save function allows developers to write to a stream instead of a file. The trick is to create a MemoryStream from the System.IO namespace. We then call the Save function on the MemoryStream object, while specifying an image format. Since the object is in memory, it can easily be converted into a byte array with the ToArray function from the MemoryStream object: public static byte[] ImageToByte2(Image img) { byte[] byteArray = new byte[0]; using (MemoryStream stream = new MemoryStream()) { img.Save(stream, System.Drawing.Imaging.ImageFormat.Png); stream.Close(); byteArray = stream.ToArray(); } return byteArray; } This method is advantageous since we can specify the image format before converting the image to a byte array. That way developers can ensure which format the byte array will be in, making comparisons for example more reliable. Once an image has been converted to a byte array, as mentioned before, programmers can do many things with it. A byte array is easy to save, convert to other types, and compare with other byte arrays.
http://www.vcskicks.com/image-to-byte.php
CC-MAIN-2018-05
refinedweb
441
55.54
I know this was asked a lot of times probably .. but it is very often answered wrong. What I want is: Use a custom icon for specific components/scripts in the Inspector (e.g. Figure 2 and Figure 3) and the Assets window (e.g. Figure 1) What I do so far: For each component/script that shall have the icon I have an accroding Icon file in the folder Assets/Gizmos/<Path>/<To>/<Namespace>/<ClassName> icon This is working fine. However, I wondered if there is really no better way having to have a unique Icon file for each script. This makes the project/UnityPacke unnecessary huge. Also if I rename a class I always have to rename the according icon file as well ... Therefore my question: Is there any better way to have those icons for scripts/components? Preferably scripted and reusing ONE single icon file instead of having the same icon in multiple differently named files. !NOTE! What I definitely do NOT want: Show the Icon also in the Editor view for all GameObjects having those components attached (e.g. Figure 4). This is caused by either selecting the icon for this script via the Inspector as in Figure 5 (as allways suggested e.g. in this post or here and even by Unity - Assign Icons ) or using OnDrawGizmos or DrawGizmo have you taken a look at the meta file? I think its the place the icon is defined. with some scripting of that it might be possible last screenshot. did you ever press the "other" button next to the icon color gizmos ;) ? Yes I did .. but this is useless ;) .. I do not want that everyone using my imported scripts has to manually disable the Gizmos in the SceneView. ... Unfortunately Unity is using the word "Gizmo" a little unconsequently and until now I didn't even find any documentation how the thing with the Gizmos folder works ... I have it from this community ;) last screenshot. did you ever press the "other" button next to the icon color gizmos ;) ? have you taken a look at the meta file? I think its the place the icon is defined. with some scripting of that it might be possible Hm yes I know that the icons are stored there ... but I'm not sure how I can change them by script ... Or do you mean I should change them all one by one? have you taken a look at the meta file? I think its the place the icon is defined. with some scripting of that it might. Unity3d how to access Gizmos Tab in scene view via code 0 Answers How do I fit the bounds of custom gizmos in the Scene View? 0 Answers Can't add script: The script is an editor script 1 Answer Custom icons for custom Monobehaviours in custom namespaces 1 Answer how do i draw something in the scene for a property 0 Answers
https://answers.unity.com/questions/1528115/is-there-a-better-way-to-have-custom-script-icons.html?sort=oldest
CC-MAIN-2020-24
refinedweb
490
73.37
. 1. Introduction It is advised to read some documentation if you are not yet acquainted with Apache Kafka Messaging. There is quite a lot of documentation available which is also similar to each other. A good starting point is the official Apache Kafka documentation which can be found here. Another good reference is from Kevin Sookocheff, it contains duplicate information compared to the official documentation but it has a nice section about partitions, which we will cover at the end of this post. As mentioned before, this post will not be a theoretical exercise, but we are going to try to get more acquainted with Apache Kafka Messaging from a more practical point of view. The sources that are being used can be found at GitHub. 2. Run Kafka An easy way to run a Kafka cluster on your local machine, is to use the Wurstmeister Kafka Docker Compose file. Download the git repository or clone it to your local machine. We will be using Ubuntu 18.04. Also make sure that you have installed Docker Compose. We will run a Kafka cluster with a single broker, therefore, we first need to edit the file docker-compose-single-broker.yml. We need to alter the environment variable KAFKA_ADVERTISED_HOST_NAME to localhost. Change the line: KAFKA_ADVERTISED_HOST_NAME: 192.168.99.100 into: KAFKA_ADVERTISED_HOST_NAME: localhost We can start the Kafka cluster now, make sure that you execute the following command from the directory where the docker-compose-single-broker.yml file resides: $ docker-compose -f docker-compose-single-broker.yml up -d Starting kafka-docker-master_kafka_1 ... done Starting kafka-docker-master_zookeeper_1 ... done We now have a running Kafka cluster. In order to stop the cluster, we can issue the following command (again, make sure that this command is executed from the directory where the docker-compose-single-broker.yml file resides): $ docker-compose stop 3. Send and Receive Messages by Means of CLI Now that we have a running Kafka cluster, we are already able to send and receive messages. When starting the Kafka cluster with Docker Compose, a topic test was automatically created. The official binary download contains scripts which, for example, makes it possible to send and receive messages. First, download the Kafka binary here. We have been using version kafka_2.12-2.3.0. In order to send messages to a topic, we need to create a Producer. We do so by means of the kafka-console-producer.sh script in the bin directory of the Kafka binary download. $ ./kafka-console-producer.sh --broker-list localhost:9092 --topic test Parameter broker-list indicates the Kafka cluster we are connecting to, parameter topic indicates to which topic we want to send messages to. In order to receive messages from a topic, we need to create a Consumer. We do so by means of the kafka-console-consumer.sh script in the bin directory of the Kafka binary download. Start this command in another terminal window. $ ./kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning Parameter bootstrap-server indicates the Kafka cluster we are connecting to, parameter topic indicates from which topic we want to receive the messages, parameter from-beginning indicates that we want to receive all messages present in the topic, also those that are sent to the topic before we connected to the topic. At this moment, it is possible to enter messages in the Producer terminal window and to receive them in the Consumer terminal window. When you terminate the Consumer, and then connect again, you will see that all messages are received again because of the from-beginning parameter. 4. Send and Receive Messages by Means of Java In this section, we will send and receive messages by means of a Java application. We will do so based on the JavaDoc for the KafkaProducer and the JavaDoc for the KafkaConsumer. We are going to create a Maven multi-module project with Java 11 containing the following modules: mykafkaproducerplanet: a Spring Boot application which will send messages to the topic; mykafkaconsumerplanet: a Spring Boot application which will receive messages from the topic. 4.1 The Kafka Producer The Kafka Producer will send 100 messages to the topic when a URL is invoked. We will make use of Spring Web MVC in order to do so. Therefore, we add the dependency spring-boot-starter-web to the pom and also the dependency kafka-clients in order to access the Java classes for sending messages to the topic. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.apache.kafka</groupId> <artifactId>kafka-clients</artifactId> <version>2.3.0</version> </dependency> The REST endpoint will be provided by a KafkaProducerController. The explanation about the properties can be found in the KafkaProducer JavaDoc. The controller will be executed when the URL is being invoked. A hundred messages are sent to the my-kafka-topic. We also added a callback function which prints the offset of the message to the console. This way, we have some kind of feedback when the message has been sent to the topic. @RestController public class KafkaProducerController { private int counter; @RequestMapping("/sendMessages/") public String-kafka-topic", Integer.toString(counter), Integer.toString(counter)), (metadata, e) -> { if(e != null) { e.printStackTrace(); } else { System.out.println("The offset of the record we just sent is: " + metadata.offset()); } } ); counter++; } producer.close(); return "Messages sent"; } } 4.2 The Kafka Consumer The Kafka Consumer will poll the topic and consume the messages when they are available in the topic. In order to use the Kafka Consumer classes, we also need to add the kafka-clients dependency to the pom. The MyKafkaConsumerApplication subscribes to the topic my-kafka-topic, see the JavaDoc of the KafkaConsumer for the explanation of the properties. When subscribed, the topic is being polled every 100ms. A message is being printed to the console when messages are available and consumed. @SpringBootApplication public class MyKafkaConsumerApplication { public static void main(String[] args) { SpringApplication.run(MyKafkaConsumerApplication.class, args); Properties props = new Properties(); props.setProperty("bootstrap.servers", "localhost:9092"); props.setProperty("group.id", "mykafkagroup");("my-kafka-topic")); while (true) { ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100)); for (ConsumerRecord<String, String> record : records) System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value()); } } } 4.3 Test the Java Application In order to test the Java application, we first need to create the topic. Ensure that the Kafka cluster is running and execute the following command from the bin directory from the Kafka binary download. This command will create the my-kafka-topic with 1 partition for us. $ ./kafka-topics.sh --create --bootstrap-server localhost:9092 --replication-factor 1 --partitions 1 --topic my-kafka-topic Check whether the topic has been created successfully: $ ./kafka-topics.sh --list --bootstrap-server localhost:9092 __consumer_offsets my-kafka-topic test Start the Kafka Producer by executing the following command from the mykafkaproducerplanet directory: mvn spring-boot:run At this point, we first check whether we can send messages to the topic by invoking the URL. The response ‘Messages sent’ is received and in the console output we can verify that 100 messages have been sent (the offsets can differ from what you see in your console): The offset of the record we just sent is: 601 The offset of the record we just sent is: 602 The offset of the record we just sent is: 603 The offset of the record we just sent is: 604 ... Start the Kafka Consumer by executing the following command from the mykafkaconsumerplanet directory: mvn spring-boot:run After successful startup of the application, the 100 messages present in the topic are printed to the console: offset = 601, key = 0, value = 0 offset = 602, key = 1, value = 1 offset = 603, key = 2, value = 2 offset = 604, key = 3, value = 3 ... 5. Something about Partitions Up till now, we made use of a topic with one partition, one producer and one consumer. The producer sends data to the partition of the topic, the consumer consumes all data from the one partition. But what happens when we have another consumer? And what happens when we have two partitions? 5.1 One Partition, Two Consumers In order to see what happens when we have two consumers belonging to the same consumer group (i.e. we have one logical consumer), we just start a second consumer application at another port. mvn spring-boot:run -Dspring-boot.run.arguments="--server.port=8083" Now invoke the URL again in order to send another 100 messages. What we see now, is that all messages are consumed by the second consumer. Stop the second consumer (the one that consumed the messages) and send another 100 messages. Now the first consumer is consuming the messages. When we start the second consumer again and send another 100 messages, the messages are consumed by the second consumer again. This confirms what is stated in the documentation that a consumer consumes from exactly one partition. In our case, the other consumer, which is not consuming the messages, is taking over when the consuming consumer crashes. 5.2 Two Partitions, Two Consumers In order to see what happens when we have two consumers belonging to the same consumer group and a topic with two partitions, we will first create another topic my-kafka-topic-2-partitions. $ ./kafka-topics.sh --create --bootstrap-server localhost:9092 --replication-factor 1 --partitions 2 --topic my-kafka-topic-2-partitions In the Kafka Producer and Consumer Java application, we replace the topic name with this new name. See branch feature/multiple-partitions. Start the producer and two consumers just like we did before. Invoke the URL in order to send 100 messages to the topic. We now can see that approximately half of the messages are sent to each partition. Each consumer is subscribed to one of the partitions and consumes the messages from that partition. Snippet of log of first consumer: offset = 96, key = 1, value = 1 offset = 97, key = 3, value = 3 offset = 98, key = 4, value = 4 offset = 99, key = 7, value = 7 ... Snippet of log of second consumer: offset = 104, key = 0, value = 0 offset = 105, key = 2, value = 2 offset = 106, key = 5, value = 5 offset = 107, key = 6, value = 6 ... 6. Conclusion We showed how you can easily start a Kafka cluster on a local machine and how messages can be sent and received by means of CLI. Also, a producer and consumer Java application is created for sending and receiving messages. At the end, we took a closer look at how partitions are used in combination with more than one consumers.
https://mydeveloperplanet.com/2019/09/25/kafka-messaging-explored/
CC-MAIN-2022-05
refinedweb
1,781
55.13
I noticed that there is a Python port, so I decided to test it out(since we've just finished our Python course at uni). I made a little Pong game, but there are some rendering issues... When drawing the paddles, there seems to some tearing with the blending. Here's my paddle drawing code: def draw(self): # Fill al_draw_filled_rounded_rectangle(self.x, self.y, self.x + self.w, self.y + self.h, 6, 6, self.color) # Highlight al_draw_filled_rounded_rectangle(self.x+2, self.y+2, self.x + self.w/2, self.y + self.h-5, 6, 6, al_map_rgba_f(0.2,0.2,0.2,0.2)) Here's my current output: {"name":"605076","src":"\/\/djungxnpq2nug.cloudfront.net\/image\/cache\/a\/8\/a83044138b031d1b775b0f0c6f3f844e.png","w":800,"h":600,"tn":"\/\/djungxnpq2nug.cloudfront.net\/image\/cache\/a\/8\/a83044138b031d1b775b0f0c6f3f844e"} Any ideas why this is happening? The width of your rounded rectangle is smaller than the sum of the radii of the rounds. Here's a blowup of what is happening: {"name":"605078","src":"\/\/djungxnpq2nug.cloudfront.net\/image\/cache\/e\/9\/e9ab6bf8d8ebbcaf59133c3e206e3b2c.png","w":404,"h":330,"tn":"\/\/djungxnpq2nug.cloudfront.net\/image\/cache\/e\/9\/e9ab6bf8d8ebbcaf59133c3e206e3b2c"} I'd just decrease the radius of the rounds (to like 5 or 4 or something). Thanks, that fixed it!
https://www.allegro.cc/forums/print-thread/608774
CC-MAIN-2018-05
refinedweb
211
52.97
iLightingInfo Struct ReferenceThis interface is implemented by mesh objects that have some kind of lighting system. More... [Mesh plugins] #include <imesh/lighting.h> Inheritance diagram for iLightingInfo: Detailed DescriptionThis interface is implemented by mesh objects that have some kind of lighting system. It has features to initialize lighting, to read it from a cache, ... Main creators of instances implementing this interface: - Several mesh objects implement this. Main ways to get pointers to this interface: Main users of this interface: - The 3D engine plugin (crystalspace.engine.3d). Definition at line 50 of file lighting.h. Member Function Documentation Disconnect all lights from this mesh. Initialize the lighting information to some default (mostly black). If clear is true then the lighting is really cleared to black. Otherwise the lighting system is just warned that lighting information is going to be added. This is useful in case a single light is added. Thus the first call to this function should use a clear of true. Indicate that some light has changed. This function will be called by the lighting system whenever a light that affects this mesh is changed in some way. Indicate that some light no longer affects this mesh. Finally prepare the lighting for use. This function must be called last. Read the lighting information from the cache. Call this instead of InitializeDefault(). Returns false if there was a problem. This function will read the data from the current VFS dir. Write the lighting information to the cache. Returns false if there was a problem. This function will write the data to the current VFS dir. The documentation for this struct was generated from the following file: - imesh/lighting.h Generated for Crystal Space 1.0.2 by doxygen 1.4.7
http://www.crystalspace3d.org/docs/online/api-1.0/structiLightingInfo.html
CC-MAIN-2015-22
refinedweb
291
69.79
Before. This post will give you clear idea on setting up Spark Multi Node cluster on CentOS with Hadoop and YARN. Before moving forward I assume that you are aware about how to install Java 7 and Apache Hadoop with YARN on CentOS cluster, - Steps to Install Java 7 On CentOS (Installation process is same as Java 8) - Steps to Install Apache Hadoop with YARN Step 1. Download Apache Spark using below commands Step 2. Configuration in spark-env.sh Create /home/spark-1.0.1-bin-hadoop2/conf/spark-env.sh and add below lines to the file Create /home/spark-1.0.1-bin-hadoop2/conf/spark-defaults.conf and add below lines to the file. Append hostnames of all the slave nodes in /home/spark-1.0.1-bin-hadoop2/conf/slaves file [Repeat same above step 1 and 2 on other slave nodes (slave1.backtobazics.com in our case)] Step 3. Start/Stop Spark using below commands Step 4. Start Spark shell using YARN Step 5. Creating a sample text file on HDFS for WordCount example Create a simple text file sample.txt with following content. Put above file on HDFS using following command. Step 6. Execute following steps of word count example After you put your sample text file on HDFS, execute following set of commands which will perform word count on Spark Cluster. That’s it….. You are done. 🙂 You can access SPARK UI in Browser by below URL Spark Master URL: Check my post related to Building Spark Application JAR using Scala and SBT for more information on Submitting Spark job on YARN cluster. Thank you for reading this post…..!!!!! n Stay tuned for more such posts….. October 20, 2015 at 5:06 am Thanks for your tutorial. 1. Do you think the settings are same for ubuntu 12.04. 2. Do I have to install spark on other hadoop slave nodes or just the master node. October 20, 2015 at 9:30 am Thanks for reading Ahmad. Here are your answers… 1. Yes steps and settings are same on ubuntu as well. 2. Of course you have to install spark on slave nodes. Slave nodes are where your spark worker nodes will run. As i mentioned under Step 2, you need to repeat step 1 and 2 in all of your slave nodes. October 20, 2015 at 10:08 pm My installation is complete. Thanks a lot. Now, when I run following command ./bin/spark-submit –class my.main.Class –master yarn-cluster Error: Must specify a primary resource (JAR or Python or R file) FYI: I created this direcorty sudo mkdir -p /data/WordCount/src/main/scala/com/backtobazics/spark/wordcount after that using chown command change the owner of directory. created following file at above path WordCount.Scala package com.backtobazics.spark.wordcount import org.apache.spark.{SparkConf, SparkContext} import org.apache.spark.SparkContext._ object ScalaWordCount { def main(args: Array[String]) { val logFile = “hdfs://maroof:9000/user/hduser/samples/pg20417.txt” val sparkConf = new SparkConf().setAppName(“Spark Word Count”) val sc = new SparkContext(sparkConf) val file = sc.textFile(logFile) val counts = file.flatMap(_.split(“\\|”)).map(word => (word, 1)).reduceByKey(_ + _) counts.saveAsTextFile(“hdfs://maroof:9000/user/root/output”) } } October 21, 2015 at 9:57 am Hi Ahmad, I have done some modifications in my current post so please go through it once. And I have tried to answer all of your questions in my recent post Building Spark Application JAR using Scala and SBT. I hope you will get all of your answers there….. October 22, 2015 at 11:14 pm Thank you for your help. I will read them and if you don’t mind, consult you in case on any issues. Thanks Again!!! December 17, 2015 at 5:19 pm Thank for your intersted article , I like to make a real example of creating Multi Node (up to 10 nodes) Hadoop 2.6.0 Cluster with YARN with SPARK on ubuntu with an java example of word count example. I have another question, i have to make a genetic algorithm to run on hadoop and apache spark , you know that genetic algorithm is iterative with its nature. my genetic algorithm will have and extensive read/worte of many file that contains sentences, what is you idea to make this. December 18, 2015 at 3:44 pm Thanks Sulaiman…. In case of your query regarding generic algorithm, can you be more specific in terms of what exactly you need to do? February 28, 2016 at 5:37 pm Hi varun, I am trying to install spark on my system, bu i am getting “bash: spark-shell: command not found….” could you please provide any solution for this.. i am not able to resolve this. Thanks, Girish February 29, 2016 at 8:53 pm Hi Girish, Can you tell me exactly at which point you are getting this error? It might be possible that you are directly executing spark-submit command without setting $SPARK_HOME/bin to your $PATH variable. Please try to execute following commands, 1) $SPARK_HOME/bin/spark-shell –master yarn-client OR 2) Set path variable and execute the command – export $PATH=$PATH:$SPARK_HOME/bin/ – spark-shell –master yarn-client where $SPARK_HOME = [spark installation directory]
https://backtobazics.com/big-data/6-steps-to-setup-apache-spark-1-0-1-multi-node-cluster-on-centos/
CC-MAIN-2019-35
refinedweb
880
67.15
Hi there.Following this guide come to an error at step 5. Any help/advice would be greatly appreciated 1. [done] git clone. [done] cd allegro 3. [skipped] git checkout 5.0 4. [done] cmake -G Xcode - .. 5. [failed] xcodebuild allegro5/addons/audio/openal.c:12:10: fatal error: 'OpenAL/al.h' file not found #include <OpenAL/al.h> Additional information ** BUILD FAILED ** The following build commands failed: CompileC build/addons/audio/ALLEGRO.build/RelWithDebInfo/allegro_audio.build/Objects-normal/x86_64/openal.o addons/audio/openal.c normal x86_64 c com.apple.compilers.llvm.clang.1_0.compiler You are missing the OpenAL dependency. Allegro's addons need quite some dependencies to do their work (it is mentioned in the article you use). You could get these dependencies via homebrew, for example. But then you could also just install Allegro5 itself via homebrew ("allegro" formula), without compiling yourself. Unfortunately, the wiki does not seem to be up-to-date with this, sorry. The wiki is open for editing. Feel free to fix it if you know what you're talking. Polybios - just used the brew installall is good thanks The wiki is open for editing. Feel free to fix it if you know what you're talking about. I still don't have a Google account and I currently don't intend to get one.
https://www.allegro.cc/forums/thread/616953/1031200
CC-MAIN-2017-47
refinedweb
223
54.18
432 questions 493 answers 182,919 users Hi guys, I tried to install and run the latest Jevois 1.11.0 on Ubuntu 18.04 and met some problems. Although I solved it, I still don't know why. So I would like to ask here to get some ideas. With a fully new installed Ubuntu 18.04, I used the method mentioned on to install all Jevois packages. The exact command I used was 'sudo apt-get install jevois-sdk-dev'. And everything went on well. At this step, I assume that everything should be installed on my computer. Then I went to my Jevois module (it was written by my colleague, so I am sure it could be built) and run './rebuild-platform'. But an error was issued, which is list below, /var/lib/jevois-build/usr/include/jevoisbase/Components/ObjectDetection/Yolo.H:24:10: fatal error: nnpack.h: No such file or directory #include <nnpack.h> ^~~~~~~~~~ compilation terminated. From my understanding, it means that there is no "nnpack.h" file on my computer. The question is that I have already used 'apt-get install' to install Jevoisbase package. Shouldn't the packages/dependencies including "nnpack,h" also be installed on my computer? I solved this issue by cloning Jevoisbase repository and went to /jevoisbase/Contrib to execute ./reinstal.sh. After this, my project could be built without errors. To make my question clear, why "apt-get install jevoisbase" does not install packages including "nnpack.h" and why do I have to go to jevoisbase source folder to install these manually? I am very new to this area, if I asked some very basic or stupid questions, please correct me. Thanks in advance.
http://jevois.org/qa/index.php?qa=2518&qa_1=error-nnpack-h-no-such-file-or-directory&show=2524
CC-MAIN-2019-26
refinedweb
285
69.68
11.1. Using urllib¶ A URL or Universal Resource Locator is an address on the World Wide Web. In a Python program that address will be in the form of a string such as: The Python urllib module is a module that opens a communication link with a URL. The link can then be used to download the raw content of the web site. import urllib thisurl = "" handle = urllib.urlopen(thisurl) html_gunk = handle.read() If no errors have occurred, the variable handle (line 5) is set to a Python socket object which contains information about the communication link that has been set up with the website and can be used to make further requests. As data consumers, we will mostly be interested in just downloading an entire web page and extracting information from it. This is done by setting the variable html_gunk to the result of calling the read method on handle (line 7). The variable html_gunk is now set to the string downloaded from the webpage, which contains a sequence of commands in Hyper Text Markup Language (HTML). HTML is a language which, in many cases, is used to specify the content and appearances of web pages. A web page written in HTML usually signals that fact to web browsers by having a URL ending in the extension ”.htm” or ”.html”. The first few characters of our example look like this: Most people downloading data from the web are not interested in looking at HTML. They are interested only extracting the content expressed in it. This is the job of the HTML parser discussed in the next section.
https://gawron.sdsu.edu/python_for_ss/course_core/book_draft/web/urllib.html
CC-MAIN-2018-09
refinedweb
269
69.21
Importing External Files in JavaScript Importing External Files in JavaScript a JavaScript application grows, navigation on the code becomes hellish. It comes to mind how useful it would be to have the ability to include JavaScript files. For example, thanks to include/require statements we can build an expressive file structure in PHP. Let’s say following PSR-0 standards we have one class per file (or one prototype object per file in JavaScript) and the class name (namespace) reflects the location of the file where it belongs. Well, on the server side (e.g. with NodeJS) that is achievable with CommonJS. Of course you have to export every object of a single file as a module, which is often not a module at all. As for the client side, modular JavaScript implies that all the dependent modules load asynchronously and separately. If every object makes a module to load that sounds nothing like a good idea. Dmitry Sheiko , 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/importing-external-files
CC-MAIN-2018-34
refinedweb
186
65.12
What will the new year bring to us? Fact is that we already have the Visual Studio release of 2008 including .Net 3.5. This big improved development environment is a guarantee that 2008 will bring a lot of happy coding experiencing some new language improvements like Linq and improved WPF. Be carefully if you intend to do some fireworks, sow you don't need to code with less fingers next year. I wish all the best and a good health for all of you in 2008. Till next year. Posted On Monday, December 31, 2007 12:40 AM | Feedback (1) I think, most of us who have the gift to own a creative mind, can agree with me that time is like an enemy. While wishing to get all those things done that run around through your head, again and again, with the realistic knowledge back in your mind, that it's never could be possible, seems the 24 hours in a day too less sometimes. Love it and hate it. I would never mis it anyway, but more grip on time and more rest in my head as a result of that is welcome for me. Sometimes you need to search for things and sometimes they come right to you as 'Hello, this is what you need!'. While reading, organize and clean the new E-mail messages in my inbox like I do usually every morning, an article introducing an e-book was included in one of them. Because I'm full of enthousiasm about the contents of that e-book and think that the things discussed in it can make some value, I would share this e-book and recommend to read it to the creative mindz with us. You can download it from here. Posted On Wednesday, December 26, 2007 9:03 PM | Feedback (0) Do you recognize the picture below as your mp3 music library? Then read on and download for free! I've made a small tool that can help you organise your mp3 files just like you want. MapMP3 creates a folder tree like artist - album -title.mp3 for every mp3 file in the folder where it is executing. In first case the tool reads the required information from the ID3 TAG's in your files, but if there was no ID3 TAG found on a file, or it was simply not providing all the required information, than it tries to extract the missing information from the current file name. The tool is simple, fast and powerfull. After installing it you can just call it on a command prompt window, everywhere, in any location. It can handle directories with +7000 files located in it without any trouble. Options are no option. It's just that simple. Just run, and reorganise your music archive as you ever wanted it should be. See the picture below for the results. MapMP3 is build on the .Net Framework (2.0). That's the only prerequisite it takes. Most times this Framework is already installed if you run Windows Updates regular, but for the case it isn't I have deployed MapMP3 in to setup variants. One including the .Net Framework (2.0) and the other one without. See the links below to download. Posted On Monday, December 10, 2007 10:53 AM | Feedback (0) Ever wanted to synchronize your outlook with your Google Calendar? The solution is here. I have developed an Outlook add-in that wil synchronize the scheduler of it with Google Calendar and backward. The process takes place in the background every time your Outlook is executing the Send/Receive operation. Setup is easily. After installing the add-in, Outlook shall prompt the options dialog of the plugin at it's next startup. (See the image below) Fill in your gmail address, password and the calendar feed of your Google Calendar account. Select which type of synchronization you want and it's all done. The plugin shall take care of the rest. The current release is Beta 1, so don't blame me for any bugs or missing features. Just come back frequently to this blog to check for updates. The current version is availlable here. Any feedback is welcome. Have fun. Posted On Saturday, November 10, 2007 2:45 PM | Feedback (2) A. Posted On Thursday, November 01, 2007 12:53 PM | Feedback (0) Do you recognize it: Every morning that buzz, beep, or maybe a radio that is getting you out of your sweat dreams? Or for some of us it does a try (me included). Near it is just innatural to get waked by sounds, it's not the most pretty manner to get waked too. Because I'm struggling with a wake-up problem for my whole life. Expecially when I'm out of regular rhytm by stress, or just long days I make somethimes due the combination of a fulltime job and do some school in evening, near my always being busy life, getting awake in the morning is going from worse to very bad. I decided to buy a wake-up light today. Near the integrated light of 400 lux and a digital FM radio, it's featured with 3 natural sounds (whistling birds, seashore and forest animals). Because it's medical proven that a good day/night rhytm is ruled by light and you will have more energy when you're getting awaked by shining light, I have some serious hope on this new device. Tomorrow morning I'll try the forest animals, so neighbours, I'm sorry if you're getting waked by monkies and elefants. But, it's always better than the hard beep that I used before, isn't it? Posted On Friday, October 26, 2007 10:34 AM | Feedback (2) There's allready been a lot written about the Provider Model pattern. But in my opinion this pattern is more powerfull than most people realize. That's my reason to do a contribution on sharing some knowledge about this pattern. The Provider Model pattern was born while Microsoft was developping version 2.0 of the ASP.Net framework (Whidbey). The name was given somewhere in the summer of 2002. The pattern was designed to give developers the abillity to have complete control over the internal implementation for a specified API. Because it is currently only supplied within the ASP.Net framework and not in the whole .Net framework, I think that there is a mis understanding about the concept. In my opinion is the pattern more valuable than most people assume. So let's have a deeper look into what the pattern really ships to us.. See the picture below for an illustration of this. A provider implementation must always derive from an abstract base provider, which is used to define the contract for a particular feature of an API. The base provider class must always derive from the ProviderBase class, which can be found in the .Net framework under the System.Configuration.Providers namespace. The ProviderBase class is used to mark implementers as a provider and forces the implementation of a required method and property common to all providers. The picture below illustrates this inheritance chain. Now we have exposed how the Provider Model pattern can help us from decoupling API interfaces and their implementations, it is the next step to show up the broad range we can use this decoupling for. Posted On Saturday, October 20, 2007 2:02 AM | Feedback (0) The stereotype image of an ict worker who has no social skills except with his computer is not true. Out of results of an investigation of the American jobsite appeared that 47 percent of the ict workers has kissed a co-worker. The investigators are expecting that of all respondents, the men are more honest in their response than the interrogated woman. When also the not ict-worker should be included than the result should be not more than a small 39 percent. The chance that you, as an ict-worker are drinking some alcohol on your desk (or under) is 25 percent according the investigation. Otherwise, this is not more than in other industries or positions. After all this drinking facts are almost 50 percent of the respondented male ict-workers saying that they do some sleep sometime in working hours. The female ict-worker is only good for a small 35 percent. source: computeridee ___ You see, I always sayed that people have the wrong image of me. Im not a boring computer-nerd. Now the facts are here! Posted On Saturday, October 06, 2007 1:24 AM | Feedback (0) Many times I've been called "The tool-guy" or something like that. That's because people around me know that I love tools, and have a lot of them. And if they don't know it yet, they will know after they come to me with a particular issue. But still, many times I wonder that people do not know the tools, or simply not use them. Practical experiences have given me the knowledge that a good tool is serious valuable. What makes a tool a tool? A tool can be defined as an instrument that helps solving an issue in any kind of way. This can be done by providing information that provides a better knowledge of a working environment, or speed up a particular process, or taking the responsibility of boring repetitive tasks, or help you to manage something in the creative process. Anyway, a tool is a piece of equipment which typically provides an advantage in accomplishing a task, or provides the ability that is not naturally available to the user of the tool. In response to this deeper understanding of the definition of a tool, it's directly possible to conclude that many available tools are not a tool in fact. Simply because they don't make any value to accomplish a task. In worst cases, they delay the process, or disturb it in other kind of way. That makes it necessary to critical select a tool for a particular task. My own experience tells me that many software developers seem to have a lack on good tools. How many of you guys are using snippets in VS2005? The reason for this lack can be found in what I’ve told above. The existence of many bad tools that bring nothing valuable, but only headaches. Especially for them who are not satisfied yet from the value a good tool can deliver, I've selected a bunch of good tools that a software developer’s life really makes easier. Reflector A great tool for exploring API's in an assembly and helping to provide a better understanding of how an assembly really works. GhostDoc Do you like to write all those XML comments that frequently return? FX Cop Analyzer for strict usage of design guide lines like naming conventions, security, localization and more... VS2005 Snippets A large collection of frequently used code that can be called by typing a few letters from intellisence. WireShark World's most popular network protocol analyzer. CLR Profiler A good tool for profiling your code so you can face the points where optimizing is required. Ants Profiler Same as CLR Profiler but the 2 important differences are that this one is much better and costs $249,- instead of free. Posted On Sunday, September 30, 2007 2:10 AM | Feedback (0) Posted On Friday, September 14, 2007 10:56 AM | Feedback (0)
http://geekswithblogs.net/mario/Default.aspx
crawl-003
refinedweb
1,923
72.16
Logging is hard. Here is my advice: Use debug module. Module debug is extremely useful because it allows to dynamically turn on messages from various modules. All my NPM modules use it with convention DEBUG='module name' to turn on messages for a particular module. By default the above program prints nothing. But if we turn on debug logging for module foo we see one log line By default, if the terminal supports it, debug uses terminal colors to highlight log messages coming from different files, making visual scanning the logs a breeze. Format statements Instead of letting debug or console.log pick the "best" representation of the arguments, explicitly set the format for each. For example: Main format placeholders to remember (see Node documentation): %s- String. %d- Number (integer or floating point value). %i- Integer. %f- Floating point value. %j- JSON. Replaced with the string '[Circular]' if the argument contains circular references. %o- Object. A string representation of an object with generic JavaScript object formatting. If in doubt - use %j to print value serialized as JSON. Another format I like is %o that outputs argument as a JavaScript object, which to me is easier to quickly scan. Control the nesting depth If an object has properties nested deeper than default threshold, %o serialization can cut it off Luckily, debug module can read environment variable DEBUG_DEPTH to control the depth threshold Do not use console.log So console.log has a problem with %o - it does not override depth threshold using an environment variable, and also it does NOT print the entire message on a single line. I will make the property names artificially long to show the problem Compare the first message from debug to the second message from console.log Notice how console.log has split the output into 2 lines. This is bad for external logging tools - because they will treat separate lines as separate messages, breaking context and search. Replace console.log with debug There are two differences between console.log and debug. First, debug by default writes to STDERR stream, while console.log writes to STDOUT stream. This usually is not very crucial. Second, console.log messages are ON by default, while debug messages are only enabled via an environment variable (or programmatically). Thus we need a way to always print some messages using debug API. Luckily this is easy to do. Running with DEBUG=foo environment variable prints everything Running without DEBUG environment variable prints the second message only Log details under namespace In addition to module messages, you can log details useful to debugging using namespaces. For example By default we log high level debug messages only But if there is some problem, we can debug it printing the value x Finally, we can print all messages with foo prefix using a wildcard Expose debug function as a module method To simplify debugging, if a file exports an object, you can attach the debug function to that object. This will significantly simplify unit testing. Make sure to call debug via method reference and not directly. Now you can easily spy / stub api.debug from your unit tests using sinon.js for example. Log promise from promise chains To better log intermediate values in promise chains, I usually use R.tap with an extra function to ensure logging the entire object in a single line. If you use Bluebird promise library, it already has .tap and .tapCatch methods on its promises Log values from tests To simplify debugging failed tests I use namespace test inside unit and end-to-end tests. Whenever the test fails, I can run it with DEBUG=test npm t to see the result variable. I do not care much for single line output because these logs are only used for debugging tests and not for production. I will also consider switching from human-readable to JSON-by-default format using super fast pino logger, especially because it has debug compatible module pino-debug
https://glebbahmutov.com/blog/good-logging/index.html
CC-MAIN-2019-22
refinedweb
664
56.66
The Samba configuration file, called smb.conf by default, uses the same format as the Windows ini files. If you have ever worked with such a file on a Microsoft client, you will find smb.conf easy to create and modify. And even if you haven't, you will find the format to be simple and easy to learn. Here is an example of a Samba configuration file: [global] ## core networking options netbios name = RAIN workgroup = GARDEN encrypt passwords = yes ## netbios name service settings wins support = yes ## logging log level = 1 max log size = 1000 ## default service options read only = no [homes] browseable = no [test] comment = For testing only, please path = /export/tmp This configuration file, based on the one we created in Chapter 2, sets up a workgroup in which Samba authenticates users using encrypted passwords and the default user-level security method. WINS server support is enabled and to be provided by the nmbd daemon. We've configured very basic event logging to use a logfile not to exceed 1 MB in size and added the [homes] share to allow Samba to export the home directory of each user who has a Unix account on the server. Let's take another look at this configuration file, this time from a higher level: [global] ... [homes] ... [test] ... The names inside the square brackets delineate unique sections of the smb.conf file; the section name corresponds to the name of each share (or service) as viewed by CIFS clients. For example, the [test] and [homes] sections are unique disk shares; they contain options that map to specific directories on the Samba server. All the sections defined in the smb.conf file, with the exception of the [global] section, are available as a file or printer share to clients connecting to the Samba server. These sections help to group settings together by defining the scope of a parameter. There are two types of parameter scope: Global Global options must appear in the [global] section and nowhere else. These options apply to the behavior of the Samba server itself and not to any of its shares. Share or service Share options can appear in share definitions, the [global] section, or both. If they appear in the [global] section, they define a default behavior for all services, unless a specific share overrides the option with a value of its own. The remaining lines of our smb.conf example are individual configuration options for each section. An option's specific scope continues until a new section is encountered or until the end of the file is reached. Because parameters are parsed in a top-down fashion, if you set the same option more than once in the same section, the last value specified is the only one that will be applied. Each configuration option follows a simple format: option = value Options in the smb.conf file are set by assigning a value to them. Some of the option names are self-explanatory. Others might require consulting the smb.conf manpage. For example, read only is self-explanatory and is typical of many recent Samba options. In many cases, the common settings are easily understood. Parameter values in smb.conf fall into five categories: Boolean Yes/No, True/False, 1/0. Integer The maximum value of the integer depends on the use of the parameter. Note that some options accept a range of valid integers such as a minimum and maximum uid. Certain values, such as 0, may have special meaningsin this case, to not apply the option at all. Character string or list Aside from boolean, this is the most common parameter type. Strings are often free-form, such as comment fields, lists of users and groups, or directory paths. Enumerated types Some parameters accept a value from discrete list of possibilities. The most common option of this type is the security parameter, which accepts values of share, user, server, domain, or ads. Anything other than the values in this list are reported as syntax errors and the parameter reverts to its default value. Plug-ins These are predominately new to Samba 3.0. Several smb.conf settings accept the name of an internal or external module. For example, user account information can be stored in an smbpasswd file or in an LDAP directory. The storage location is controlled by the plug-in value for the passdb backend parameter. The testparm utility verifies only the syntax of parameter names and Boolean parameter values. It is not smart enough to know whether values such as an arbitrary string or a director path are valid. Parameter names are case- and whitespace-insensitive. For example, READONLY is the same as Read Only or read only. For consistency, option names in this book are usually lowercase and usually follow the spacing conventions as they appear in the smb.conf manpage. The rules are a little less clear when dealing with parameter values. Generally, the whitespace and capitalization rules are defined by the use of the value. For example, case does not matter for Boolean values: YES is the same as Yes. But string or list values might be case-sensitive, and at a minimum should be assumed to be case-preserving. Consider the case of a directory path on disk. Common Unix filesystems honor case in file and directory names. This means that /EXPORT is not the same path as /export. However, what if Samba were sharing a FAT filesystem in which case does not matter? What about user or group names? Should they be considered case-sensitive in smb.conf? Normally Unix does treat account names as case-sensitive strings. The bottom line is that string values are case-sensitive when the underlying system that makes use of them is case-sensitve. When a string is used by Samba itself or as a value transmitted to Windows clients, it can generally be considered as case-preserving but case-insensitive. The comment option for a share is a good example here. The [test] in our smb.conf specifies: comment = For testing only, please Samba strips away the spaces up to the first F in For. The remainder of the string is seen as it is by Windows clients. The character case here is only cosmetic. If an option accepts multiple strings such as a list of usernames or groups, there are two issues of which you must be aware. The first is knowing which characters Samba will interpret as entry delimiters. The standard delimiting characters in smb.conf are: Whitespace Comma (,) Semicolon (;) New line (\n) Carriage return (\r) You haven't been introduced to a parameter that accepts a list of values yet, but imagine a list of users. All of the following lists of three items are semantically the same: rose, smitty, foo rose smitty, foo rose; smitty foo So this brings us to to the second question: how can we define a list entry that contains one of these delimiting characters? The most common example is a username that contains a space. The answer is that we explicitly group the tokens in an entry together by surrounding the string with double quotes. "Alex Rose", smitty, foo However, never use quotation marks around an option name; Samba will treat this as an error. smb.conf section names are case-insensitive, but the whitespace does matter when a client attempts to access the share. For this reason, many admins find it easier to avoid share names with whitespace in them. Some older Windows clients, such as Windows 9x, cannot access shares with names longer than 12 characters. single-line comments in the smb.conf configuration file (not to be confused with the comment parameter) by starting a line with either a hash (#) or a semicolon (;). For example, the first three lines in the following example would be considered comments: # Export the home directory for a each user ; Pulls the home directory path via the getpwnam( ) call ; (e.g. a lookup in /etc/passwd) [homes] browseable = no Samba ignores all comment lines in its configuration file; there are no limitations to what can be placed on a comment line after the initial hash mark or semicolon. Note that the line continuation character (\) is not honored on a commented line. Like the rest of the line, it is ignored. Samba does not allow mixing of comment lines and parameters. Be careful not to put comments on the same line as anything else, such as: path = /data # server's data partition Errors such as this, where the parameter value is defined with a string, can be tricky to notice. The testparm program won't complain. The only clues you'll receive from testparm are that it reports the value of the path parameter as /data # server's data partition. Failures result when clients attempt to access the share. You can modify the smb.conf configuration file and any of its options at any time while the Samba daemons are running. The question when they will take effect on the server (and be seen by clients) requires a detailed response. When changing core NetBIOS or networking settings, such as modifying the name of the server or joining a domain, it is best to assume that a restart of all Samba daemons is necessary. For other global parameters and most changes to shares, apply these rules: When a new connection is received, the main smbd process spawns a child process to handle the incoming request. The new child rereads smb.conf upon startup, and therefore sees the change. Once started, Samba daemons check every three minutes to determine whether any configuration files have been modified, and if so, reload and act on the parameters. An administrator can force an immediate reload of smb.conf by sending the smbd process the Hangup (HUP) signal or by sending a reload-config message via the smbcontrol utility. Scanning for new printers in the underlying printing system (e.g., CUPS or /etc/printcap) is controlled by the printcap cache time parameter, which specifies the monitoring interval in seconds. Be wary of editing smb.conf on a live system. This is an easy way to introduce syntax errors in smb.conf that are unintentionally propagated to client connections. A good practice is to update a copy of the server's smb.conf and then move it to the existing configuration only after you have verified that it has no syntax errors or unintended changes. It is also a good idea to apply some type of version control to server configuration files such as smb.conf. The next question that should be asked is what happens to active client connections when you restart Samba. The daemon that directly handles client connections is smbd. smbd's architecture uses a fork-on-connect model of handling incoming TCP connections. If you kill the main smbd process, all child processes continue until the client disconnects, and each smbd exits normally. However, until the parent is restarted, the host machine does not allow additional incoming CIFS connections. If an smbd child that is handling an active connection is killed, all files and shares that the client had open become invalid. Windows clients will automatically reconnect to the server as soon as the user attempts to access one of these previously valid resources. In many instances, the user will never know that the connection was dropped and reestablished. There are a few exceptions: If the server does not support encrypted passwords, current releases of Windows cannot reauthenticate the user, because they cache only the hash of the user's password and not the clear text. Many applications, when stored on a remote system and run from a network drive, crash when the connection is dropped. However, local applications simply accessing datafiles or documents on a network drive frequently experience no problems during the reconnection. Because a new copy of the smbd daemon is created for each connecting client, each client can have its own customized configuration file. Samba allows a limited yet useful form of variable substitution in the configuration file to allow information about the Samba server and the client to be included in the configuration at the time the client connects. A variable in the configuration file consists of a percent sign (%), followed by a single upper- or lowercase letter. Variables can be used only on the right side of a configuration option (i.e., after the equal sign). An example is: [pub] path = /home/ftp/pub/%a The %a stands for the client system's architecture and is replaced according to Table 4-1. Client operating system ("architecture") Replacement string Windows for Workgroups WfWg Windows 95, 98 and Millenium Win95 Windows NT WinNT Windows 2000 Win2K Windows XP WinXP Windows Server 2003 Win2K3 OS/2 OS2 Samba Linux CIFS filesystem client CIFSFS All other clients UNKNOWN In this example, Samba assigns a unique path for the [pub] share to client systems based on what operating system they are running. The path that each client would see as its share differ according to the client's architecture: more than 20 variables, shown in Table 4-2. Variable Definition Client variables %a Client's architecture (see Table 4-1) %i IP address of the interface on the server to which the client connected %I Client's IP address (e.g., 172.16.1.2) %m Client's NetBIOS name %M Client's DNS name (defaults to the value of %I if hostname lookups = no) User variables %u Current Unix username (requires a connection to a share) %U Username transmitted by the client in the initial authentication request %D User's domain (e.g., the string DOM-A in DOM-A\user) %H Home directory of %u %g Primary group of %u %G Primary group of %U Share variables %S Current share's name %P Current share's root directory %p Automounter's path to the share's root directory, if different from %P Server variables %d Current server process ID %h Samba server's DNS hostname %L Samba server's NetBIOS name sent by the client in the NetBIOS session request %N Home directory server, from the automount map %v Samba version Miscellaneous variables %R The SMB protocol level that was negotiated %T The current date and time %$(var) The value of environment variable var Here's another example of using variables: suppose that you do not want to share the user's Unix home directory, but prefer instead to keep a separate set of home directories specifically for SMB/CIFS clients. You can do this by defining a path in the [homes] service that includes the %U variable. [homes] path = /export/smb/home/%U ... People often wonder what the difference is between %U and %u. The value of %U is derived from the username sent during the CIFS session setup request covered in Chapter 1. This occurs before a connection to any share. The %u variable is expanded from the uid assigned to a user in the context of a file share. This can change depending on the share. More about this issue is explained in Chapter 6, when we discuss the force user option. When user rose connects to the UNC path \\RAIN\homes, the path statement expands to /export/smb/home/rose. Samba does not automatically create this directory if it does not already exist. One way to solve this this problem is to instruct Samba to run an external program or script when a user connects to a specific share. More about this technique is discussed in Chapter 6.
https://flylib.com/books/en/2.335.1.30/1/
CC-MAIN-2021-25
refinedweb
2,599
61.97
Jul 31, 2009 08:11 PM|mbanavige|LINK You could place them in either a Class or a Module - and yes you could put them all in a single namespace if that's what you want. Jul 31, 2009 08:37 PM|mbanavige|LINK You cannot place methods directly into a namespace. They must be in either a class or a module. Jul 31, 2009 09:21 PM|renasis|LINK OK. Is there a way where I don't have to write the class each time I call the method? I am planning on placing my shared functions inside a class, which resides in a namespace with the same name. Like so, Namespace Utility Public Class Utility shared function getsomething() end function end class end namespace Then I want to be able to use the getsomething function in another class. Based on an example on the web(), it indicates that I can import the namespace I just created an access the function by its name alone, but I can't seem to get it to work. This is what I am trying to do. imports Utility public class x dim x as string = getsomething 'VS needs Utility. before getsomething end class Contributor 7421 Points Jul 31, 2009 09:23 PM|Danny117|LINK Quick simple pseudo code. Have fun without namespaces you can never do implements and really design code that others write for you. First you need some code in a file seperate from the form or web page in the app_code folder. Just type namespace at the top of your code I recomend starting with two levels then the class name is the third level. namespace whatever.whatever class dosomething. end class end namespace 'then your webpage or form imports whatever.whatever 'Using whatever.whatever; 'then you can just access the class in your code. dosomething(visitorid)'; 'or write it out whatever.whatever.dosomething(visitorid)'; Jul 31, 2009 10:29 PM|mbanavige|LINK renasisaccess the function by its name alone in vb.net, you can place the function in a module instead of a class 7 replies Last post Jul 31, 2009 10:31 PM by renasis
https://forums.asp.net/t/1453950.aspx?Namespaces+and+shared+functions
CC-MAIN-2021-43
refinedweb
358
72.36
We are about to switch to a new forum software. Until then we have removed the registration on this forum. I'll try and keep this short and snappy. I have this code that will give me a simple black silhouette on Processing 2.0 using the Kinect unfortunately it's stuck at 640 x 480. I know this is because the Kinect can only detect things at this size but I really need to make the dimensions and size of this larger. Maybe not necessarily full screen but at least 1280x720. I am a beginner of a beginner at all this and it is actually just for a graphic design project at uni that I'm doing it. So try and keep it basic so my simple mind can understand. import SimpleOpenNI.*; SimpleOpenNI context; int[] userMap; PImage rgbImage; PImage userImage; color pixelColor; void setup() { size(640, 480); context = new SimpleOpenNI(this); context.enableRGB(); context.enableDepth(); context.enableUser(); userImage = createImage(width, height, RGB); } void draw() { background(255,255,255); context.update(); rgbImage=context.rgbImage(); userMap=context.userMap(); for(int y=0;y<context.depthHeight();y++){ for(int x=0;x<context.depthWidth();x++){ int index=x+y*640; if(userMap[index]!=0){ pixelColor=rgbImage.pixels[index]; userImage.pixels[index]=color(0,0,0); }else{ userImage.pixels[index]=color(255); } } } userImage.updatePixels(); image(userImage,0,0); } I'd also like to mention that I am using a v1 Kinect. Any help would be so, so appreciated. Dan
https://forum.processing.org/two/discussion/13215/how-do-i-make-this-full-screen-or-at-least-increase-the-dimensions
CC-MAIN-2021-10
refinedweb
246
51.55
I'd like to write a plugin that hooks into the CVS commit (similar to the the CommitLog plugin) and (optionally) performs additional CVS operations (specifically cvs tag operations) once the commit is completed. I know the CVS plugin is the only VCS plugin that is not open-sourced (any chance of changing that, BTW), but would it be possible to include the netbeans CVS library in my plugin distro and use it as sort of a standalone library? Thanks! Todd I'd like to write a plugin that hooks into the CVS commit (similar to the the CommitLog plugin) and (optionally) performs additional CVS operations (specifically cvs tag operations) once the commit is completed. The netbeans CVS library is part of the CVS integration plugin with IntelliJ. Therefore, if you make your plugin dependent on the CVS integration plugin, then you are guaranteed to have the netbeans CVS library available to use at runtime. For development compile time, just add the CVS integration plugin jars (cvsIntegration.jar and javacvs-src.jar) to your IntelliJ SDK. The reason to do this instead of adding it as a regular jar dependency is so that it won't be copied into your plugin jar for distribution. My CVSRevisionGraph plugin is opensource and does some tagging operations down at the netbeans library level. You can look at its source to get some help. I am not sure how to hook into the CVS commit, though. I decompiled the CVS integration plugin to figure out how to do what I wanted. I would suggest that. Thanks, Shawn. That's exactly the info I was looking for. I'll take a look at CVSRevisionGraph. I've got the CVS commit hook working, so I just need to clean up my code a bit and change the dependency as you described. Todd I finally got around to adding the dependency to the CVS Integration plugin. I added the plugin jars to my project as described (cvsIntegration.jar and javacvs-src.jar). However, not all of the NetBeans CVS library appears to be included. Specifically, the following imports can not be located: import org.netbeans.lib.cvsclient.connection.PasswordsFile; import org.netbeans.lib.cvsclient.Client; import org.netbeans.lib.cvsclient.CVSRoot; import org.netbeans.lib.cvsclient.event.CVSAdapter; import org.netbeans.lib.cvsclient.event.MessageEvent; import org.netbeans.lib.cvsclient.event.FileUpdatedEvent; import org.netbeans.lib.cvsclient.event.BinaryMessageEvent; import org.netbeans.lib.cvsclient.event.FileAddedEvent; import org.netbeans.lib.cvsclient.event.FileToRemoveEvent; import org.netbeans.lib.cvsclient.event.FileRemovedEvent; import org.netbeans.lib.cvsclient.event.FileInfoEvent; import org.netbeans.lib.cvsclient.event.TerminationEvent; import org.netbeans.lib.cvsclient.event.ModuleExpansionEvent; import org.netbeans.lib.cvsclient.admin.StandardAdminHandler; When I had a dependency to the NB CVS library jar that I downloaded from NetBeans, all of these imports were available. Thanks! Todd
https://intellij-support.jetbrains.com/hc/en-us/community/posts/206136829-Plugin-that-performs-CVS-operations
CC-MAIN-2019-18
refinedweb
475
51.95
digitalmars.D.learn - Error: no property 'opCall' for type 'app1.ReturnContent' - Suliman (14/14) Oct 24 2012 import std.stdio;... - Jonathan M Davis (23/42) Oct 24 2012 It means exactly what it says.... import std.stdio; void main() { ReturnContent(); } public class ReturnContent { void ReturnContent() { writeln("hello"); } } Why I am getting this error? D2 Oct 24 2012 On Wednesday, October 24, 2012 12:00:11 Suliman wrote:import std.stdio; void main() { ReturnContent(); } public class ReturnContent { void ReturnContent() { writeln("hello"); } } Why I am getting this error? D2 It means exactly what it says. ReturnContent is a class, so when you use ReturnContent(), you're trying to call the function operator on the type ReturnContent. That's not going to work unless you overloaded opCall on ReturnContent and made it static. e.g. public class ReturnContent { static void opCall() { writeln("static opCall"); } } Your ReturnContent function inside of ReturnContent is only ever going to be callable on instances of ReturnContent, not on the type, so you must create an instance of it first. e.g. auto rc = new ReturnContent; rc.ReturnContent(); However, it's incredibly bizarre to name a member function the same name as the type. In D, constructors are named this, and member functions are most frequently named with camelCase - e.g. returnType - whereas types are most frequently named with PascalCase - e.g. ReturnType. So, naming a function the same as the type is odd and confusing. - Jonathan M Davis Oct 24 2012
http://www.digitalmars.com/d/archives/digitalmars/D/learn/Error_no_property_opCall_for_type_app1.ReturnContent_40548.html
CC-MAIN-2015-11
refinedweb
243
57.47
Building ASP.NET 2.0 Web Sites Using Web Standards Stephen Walther SuperExpert.com Applies to: Microsoft ASP.NET 2.0 Microsoft Visual Studio 2005 Microsoft Visual Web Developer Note: A document that includes accessibility information for versions 2.0 through 4 of ASP.NET is available as the topic Accessibility in Visual Studio and ASP.NET in the ASP.NET 4 documentation. That document includes updated information about accessibility guidelines, which have changed significantly since this document was published. Summary: Microsoft ASP.NET 2.0 has many features to help you design and build Web sites that are compliant with XHTML and accessibility standards. This article looks at how and why you should be building these standards-compliant sites. (78 printed pages) Contents Introduction Building XHTML Web Sites Versions of the XHTML Standard Creating XHTML Pages XHTML and ASP.NET Controls Validating XHTML Pages XHTML and DOCTYPE Switching XHTML and MIME Types Configuring XHTML Conformance Accessibility Standards Accessibility Improvements in ASP.NET 2.0 Creating Accessible Images Creating Accessible Forms Creating Accessible Navigation Creating Accessible Data Creating Accessible XHTML Creating Accessible Scripts Validating Pages for Accessibility Accessing the Amazon Web Services The Default Page XHTML Features of the Default Page Accessibility Features of the Default Page The Search Page XHTML Features of the Search Page Accessibility Features of the Search Page The Master Page XHTML Features of the Master Page Accessibility Features of the Master Page Introduction Web standards enable you to build Web sites that are accessible to the broadest possible audience with the least amount of work. The promise of Web standards is that you can design a page once and have the page appear and function in exactly the same way in any modern browser. For example, when built against standards, a page that was designed to display a certain way in Microsoft Internet Explorer can appear the same way in other browsers, such as Mozilla Firefox, Netscape Navigator, Opera, Camino, and Safari, without requiring you to perform any additional work. An additional benefit of Web standards is that they make your Web sites more easily accessible to persons with disabilities. This is a broad audience that includes everyone from a middle-aged person with failing eyesight, to a person who just broke his or her arm while skiing, to a person who is completely blind. Standards prevent you from unintentionally blocking persons with temporary or permanent disabilities from your Web pages. The Microsoft ASP.NET 2.0 framework was designed to be the best framework for building Web sites that meet public Web standards. In particular, every control in the ASP.NET 2.0 framework was extensively reviewed and tested against both XHTML and accessibility standards. Furthermore, Microsoft Visual Studio 2005 includes new tools for validating your Web pages against both XHTML and accessibility standards. The purpose of this paper is to provide you with an overview of XHTML and accessibility standards, and explain how you can take advantage of ASP.NET 2.0 and Visual Studio 2005 to meet these standards. At the end of this paper, you are provided with a step-by-step walkthrough for creating an ASP.NET 2.0 Web site that satisfies both XHTML and accessibility standards. Building XHTML Web Sites HTML is officially outdated. The World Wide Web Consortium (W3C) published the first version of XHTML as a recommendation on January 26, 2000. The XHTML standard is intended as a replacement for HTML. According to the W3C, "XHTML is the successor of HTML" (). The framers of the XHTML standard have two broad goals: - Create a cleaner separation between document structure and presentation. - Reformulate HTML as an application of XML. In pursuit of the first goal, the W3C has been steadily removing purely presentational elements and attributes from HTML (a process that they started with HTML 4.0). For example, XHTML 1.0 Strict does not include elements such as the <font> tag, or attributes such as the bgcolor attribute, because these elements and attributes are used solely to describe the appearance of a document, and they have nothing to do with a document's structure. The W3C has been attempting to wean Web site designers and developers away from the idea that any particular tag should have any particular appearance. For example, you might think that the purpose of an <h1> tag (the heading tag) is to render large, bold text in a page. That would be wrong. The <h1> tag is used to mark a heading in a document, and nothing else. It is up to the browser to determine how the heading tag should be rendered. A screen reader used by a person with reduced eyesight might read aloud the contents of a heading tag with a booming, authoritative voice. A PDA, which doesn't support multiple font sizes, might render the contents of a heading tag with blinking text. You should not attempt to use page elements, such as the <h1> tag, to control the appearance of a Web page. Instead, you should indicate the appearance of a Web page through the use of Cascading Style Sheets. Preferably, the Cascading Style Sheets should be external Cascading Style Sheets. Use tags and attributes to mark up the structure of a document, and use Style Sheets to control the document's presentation. The second goal of XHTML is to enforce the stricter rules of XML on HTML developers. In the words of the W3C, "XHTML 1.0 is a reformulation of HTML 4.01 as an XML 1.0 application" (). In other words, when you build a Web page using XHTML, you are actually creating an XML document. An XML document has a much stricter syntax than an HTML document. For example, XML is case-sensitive, all XML attributes must be quoted, and XML tags cannot overlap. Forcing Web site developers and designers to follow the rules of a more demanding language has many benefits. One benefit is that pages written with XHTML markup are more cross-browser, cross-device, and cross-operating system compatible. If you open a traditional HTML page in a browser, the browser will make every effort to render the page. The browser will attempt to render the page even if your HTML is a total mess. For example, Internet Explorer (and Firefox and Opera) will display the following HTML page just fine. <i><B>this is bold and italic</I> and this is bold </body></HTML> Internet Explorer happily displays this page, even though the page is missing opening <html> and <body> tags, the <b> tag has no matching closing tag, and the case of the opening and closing <i> tags is inconsistent. All major browsers will accommodate almost any "tag soup" of HTML tags and desperately attempt to render something. This accommodating behavior of browsers is dangerous, because different browsers (or future versions of the same browser, or the same browser running on a different operating system) might render garbled HTML in different ways. In point of fact, the latest versions of Internet Explorer, Mozilla Firefox, and Opera are surprisingly consistent in the way that they render invalid HTML. However, once you start to play outside of the rules, there are no guarantees. If you write your Web pages with the stricter rules of XHTML, however, there is more of a chance that your Web pages will work consistently with current browsers, and that they will continue to work with new versions of current browsers introduced in the future. Few companies have the resources to test their Web sites against every browser running on every operating system and every device. If you write your pages against Web standards, you don't have to. Versions of the XHTML Standard There are three versions of XHTML 1.0, which correspond to the three versions of HTML 4.01: - XHTML 1.0 Transitional - XHTML 1.0 Strict - XHTML 1.0 Frameset XHTML 1.0 Transitional contains all of the tags and attributes from HTML 4.01 Transitional. The XHTML 1.0 Transitional standard was introduced to enable existing HTML designers and developers to migrate to XHTML without experiencing too much shock and pain. XHTML 1.0 Strict differs from XHTML 1.0 Transitional by enforcing a cleaner separation between document structure and presentation. Unlike XHTML 1.0 Transitional, XHTML 1.0 Strict forces you to use Cascading Style Sheets to control the appearance of your pages. XHTML 1.0 Frameset documents are intended to be documents that use the <frameset> tag to partition a browser into multiple frames (XHTML 1.0 Transitional and Strict pages cannot contain the <frameset> tag). The W3C has also published XHTML 1.1 as a recommendation (on May 31, 2001). XHTML 1.1 is very similar to XHTML 1.0 Strict. The primary difference is that XHTML 1.1 can be extended with additional modules in order to support new elements. You can, for example, build XHTML 1.1 pages that also include elements from the MathML (the Mathematical Markup Language), or SVG (the Scalable Vector Language), or a custom module of your own creation. Finally, the W3C is working on a recommendation for XHTML 2.0. Because XHTML 2.0 is still in the draft stage, and no Web browser currently supports this standard, we won't discuss it in this paper. The ASP.NET 2.0 framework and Visual Studio 2005 are targeted at XHTML 1.0 Transitional. This is the least restrictive of the XHTML standards, and it is the standard that is the most compatible with existing HTML pages. However, you can also build ASP.NET 2.0 pages that target the XHTML 1.0 Strict standard or even the XHTML 1.1 standard (see the later section, Configuring XHTML Conformance). Creating XHTML Pages Unlike an HTML page, an XHTML page must be a well-formed and valid XML document. The differences between HTML and XHTML are summarized in Section 4 of the XHTML 1.0 recommendation. Here's a list of the most important requirements for building a valid XHTML page: - The page must include a valid XHTML DOCTYPE..1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" ""> Adding a DOCTYPE to a page has an impact on how the page is rendered in a browser. See the section below entitled XHTML and DOCTYPE Switching. - The root element must refer to the XHTML namespace The opening <html> tag of an XHTML page must specify a default namespace of. Here's a sample of a valid opening <html> tag for an XHTML 1.0 Transitional page. <html xmlns="" xml: - All element and attribute names must be lowercase. XML is case-sensitive. Therefore, there is a difference between the <p> tag and the <P> tag. Only the former is a valid XHTML paragraph tag. - Attribute values must always be quoted.. - All non-empty elements that have an opening tag must have a matching closing tag./>. - There must be no overlapping tags. You can nest tags, but you are not allowed to overlap tags. For example, the following XHTML is valid. <b><i>This is bold and italic</i></b> However, the following XHTML is invalid. <i><b>This is bold and italic</i></b> - There must be no attribute minimization. All attributes must have a value, even when it looks a little strange. For example, the tag <input type="checkbox" checked /> is invalid XHTML, because the checked attribute does not have a value. The tag should be written <input type="checkbox" checked="checked" />. - The id attribute must be used instead of the name attribute.. - The contents of <script> and <style> elements must be wrapped in CDATA sections.. XHTML and ASP.NET Controls Every ASP.NET control included in the ASP.NET 2.0 framework renders valid XHTML by default. In other words, you don't need to do anything special to generate valid XHTML markup when adding ASP.NET controls to a page. For example, if you add a GridView control to a page, the GridView control will generate valid XHTML markup. Three points need to be clarified here. First, the source code of a page that contains ASP.NET controls will not validate as XHTML. When validating an ASP.NET page, you need to validate the rendered content of the page (everything that you see when you select View Source in Internet Explorer) and not the source of the page. Second, there is nothing that prevents you from writing invalid XHTML when creating an ASP.NET page. You can, of course, add any tag to an ASP.NET page that you want. For example, if you add a <font> tag to your page, then your page will not validate as XHTML 1.0 Strict. Finally, there are no guarantees when you use custom ASP.NET controls. If you buy a third-party ASP.NET control—for example, a super enhanced DataGrid control—the control may or may not render valid XHTML. It's the control vendor's responsibility to do the right thing. Validating XHTML Pages Visual Studio 2005 and Visual Web Developer automatically validate your Web pages as you build the pages. Validation problems are indicated in Source view by either green or red squiggles under the offending content. Red squiggles correspond to validation errors such as a missing closing tag. Green squiggles correspond to validation warnings such as the use of deprecated tags. You can hover your mouse over any squiggle to view a ToolTip that contains the validation error or warning message (see Figure 1). Alternatively, you can view a list of validation errors and warnings in the Error List window (select View, Other Windows, Error List). Figure 1. Validating an XHTML document (Click the graphic for a larger image.) By default, Visual Studio 2005 and Visual Web Developer are configured to validate pages against the Internet Explorer 6.0 schema. If you want to validate your pages against an XHTML schema, then you need to select one of the XHTML schemas from the drop-down list in the toolbar, or you can select Tools, Options, Validation to select a target schema. As an alternative, you can validate your ASP.NET pages by using the W3C validation service. The W3C validation service enables you to validate a page by supplying a URL or by uploading the source of an XHTML page. XHTML and DOCTYPE Switching Specifying a DOCTYPE for a Web page impacts the way in which the page is rendered by a browser. Internet Explorer, Mozilla Firefox, and Opera all support a feature called DOCTYPE Switching (also called DOCTYPE Sniffing). DOCTYPE Switching was introduced to enable browsers to render both standards-compliant and legacy Web sites correctly. Most Web sites were developed to render HTML pages and not XHTML pages. Browsers use the presence of a DOCTYPE to determine when a page should be rendered by using standards. Internet Explorer 6+ supports two rendering modes, called Quirks mode and Standards mode. When Internet Explorer renders a page that contains a valid XHTML (or HTML 4.0) DOCTYPE, it renders the page in Standards mode; otherwise, it renders the page in Quirks mode (for details, see CSS Enhancements in Internet Explorer 6). The Opera browser (Opera 7+) supports the same two rendering modes (Quirks and Standards) as Internet Explorer (for details, see). Mozilla Firefox 1+ supports three rendering modes: Quirks mode, Almost Standards mode, and Standards mode. Firefox's Almost Standards mode corresponds to Internet Explorer's and Opera's Standards mode. When a page contains a valid XHTML 1.0 Transitional DOCTYPE (and it is served with a text/html MIME type), Firefox renders the page in Almost Standards mode. When a page contains either an XHTML 1.0 Strict or XHTML 1.1 DOCTYPE (or the page is served with an XML MIME type), the page is rendered in Standards mode (for details, see). You can determine a browser's current rendering mode by temporarily adding the following client-side script to a page (this script works in the latest versions of Internet Explorer, Firefox, and Opera). <script type="text/javascript"> alert( document.compatMode ); </script> You need to care about the browser rendering mode, because it affects the way in which Cascading Style Sheets are applied to the page. If you convert your existing HTML pages into XHTML pages, they might look very different when you open them in your browser. For example, Internet Explorer calculates the size of page elements in different ways, depending on the rendering mode (it uses a different CSS Box Model). In Quirks mode, the width of an element is calculated by summing the width of the element's content, padding, borders, and margins. In Standards mode, the width of an element is calculated by taking into account only the width of the element's content. For example, consider the following two <div> tags. <div style="width:400px;border:solid 1px black"> First Box </div> <div style="width:400px;border:solid 1px black;padding:10px"> Second Box </div> The two <div> elements are the same, except for the second <div> element's additional padding. In Quirks mode (see Figure 2), the two <div> elements appear to be the same size, because the additional padding of the second <div> element is taken into account when calculating its width (the total width of both elements is 400px). In Standards mode (see Figure 3), the second <div> element appears wider than the first <div> element, because padding is not taken into account when calculating the width of an element (the total width of both elements is wider than 400px). Figure 2. Quirks mode Figure 3. Standards mode This is only one example of browser differences in Quirks mode. In Quirks mode, each browser implements the W3C Cascading Style Sheet standards in significantly different ways. The beautiful thing about switching to Standards mode is that it forces almost all modern browsers to interpret the W3C standards in a very similar way (not exactly the same, but much better). If you want your Web pages to appear in the same way across browsers, then it is a good idea to trigger Standards mode (in Internet Explorer and Opera) and Almost Standards mode (in Firefox), by including an XHTML 1.0 Transitional DOCTYPE. Fortunately, Visual Studio 2005 and Visual Web Developer automatically add this DOCTYPE, by default, to every new page ASP.NET page. XHTML and MIME Types When a Web browser requests a page from a Web server, the Web server serves the page with a certain MIME type (also called a Content type). For example, an HTML page is served with the text/html MIME type, a GIF image is served with an image/gif MIME type, and a Microsoft Word document is served with an application/msword MIME type. A browser uses the MIME type to determine how a page (or other resource) should be handled. For instance, if a browser gets a file from a Web server that has a recognizable image MIME type, the browser attempts to interpret and render the file as an image. If a browser gets a file that has an application/msword MIME type, the browser might automatically open Microsoft Word to display the document (the exact behavior here depends on the browser and how it is configured). The W3C has introduced a MIME type for XHTML documents. This new MIME type is application/xhtml+xml. The W3C recommends that you use the application/xhtml+xml MIME type when serving XHTML documents, because XHTML pages should be interpreted in a stricter way than legacy HTML pages. You can serve an ASP.NET page with a particular MIME type by including the ContentType attribute in a page directive. For example, including the following directive at the top of an ASP.NET page causes the page to be served as application/xhtml+xml. <%@ ContentType="application/xhtml+xml" %>. There are three ways that you can work around this problem. You can serve your XHTML pages by using the text/html MIME type, you can serve your XHTML pages by using the application/xml (or text/xml) MIME type, or you can use content negotiation. Let's explore each of these options. The first option, serving your pages as text/html, is the easiest option. An ASP.NET page is served with this MIME type by default. Better yet, the W3C recommends this option when serving pages to existing HTML browsers (see). If you are creating XHTML 1.0 Transitional pages, and the primary audience for your Web application is using a browser that does not understand the application/xhtml+xml MIME type, then serving your pages as text/html seems perfectly sensible. After all, the XHTML 1.0 Transitional standard was introduced to make it easier for developers to migrate existing HTML pages to XHTML. This claim is controversial. For example, Ian Hickson argues that XHTML pages should never be served as text/html, because this option promotes sloppy, broken XHTML pages (see). He recommends that authors stick to HTML 4.0 until more browsers completely support XHTML standards. The second option is to serve your XHTML pages as XML, using either the application/xml or text/xml MIME type. When Internet Explorer is served an XML document, the document is parsed as an XML document and rendered to the browser. (The document is represented by the XML DOM exposed by the document.XMLDocument object.) The advantage of serving an XHTML document as XML is that any problems with the XHTML document will be caught by Internet Explorer's XML parser. For example, if your document contains overlapping tags, or if the value of an attribute is not wrapped in quotation marks, then the document is not rendered, and an error message is displayed (see Figure 4). XHTML purists consider this behavior a good thing, because it prevents you from writing malformed XHTML. Figure 4. Displaying XML in Internet Explorer The problem with this approach is that Internet Explorer, by default, renders the source of an XML document. So, if you serve an XHTML document as XML, your Web site visitors will see the source of your XHTML documents and not the desired rendered output. The W3C suggests a "trick" for getting around this problem (see): If you transform an XHTML document into HTML by using an XSLT transformation, then your document will be parsed as XML and displayed as HTML. For example, the ASP.NET page in Listing 1 will be served as an XML document but transformed into an HTML document. The resulting page displays correctly in Internet Explorer, Opera, and Firefox. Listing 1. XMLPage.aspx <%@ Page <html xmlns="" > <head runat="server"> <title>My Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox </div> </form> </body> </html> The page directive causes this page to be rendered as text/xml. The second line in the listing refers to an XSLT style sheet, named copy.xsl, that performs an identity transformation on the current document. In other words, it does absolutely nothing, except copy all of the elements from the original XML document into a new HTML document. The source for copy.xsl is contained in Listing 2. Listing 2. Copy.xsl <stylesheet version="1.0" xmlns=""> <template match="/"> <copy-of </template> </stylesheet> This solution works, but it doesn't seem very elegant. You do get the extra validation step when the XML document is parsed. However, if you are building your ASP.NET pages in Visual Studio 2005 or Visual Web Developer, the same validation is performed by the development environment in Source view. At the end of the day, Internet Explorer receives the same document as it would get if you had sent it text/html. The third option, content negotiation, best combines the spirit of the W3C recommendations with the greatest degree of browser compatibility (see). When you use content negotiation, you serve an ASP.NET page with different MIME types to different browsers. If a browser claims that it supports XHTML, then you serve it XHTML; otherwise, you serve the browser the page with the text/html MIME type. The Global.asax in Listing 3 contains the necessary code for serving different MIME types to different browsers. If you add this file to your Web project, then the MIME type of every ASP.NET page will be modified with each request. When a page is served to Firefox or Opera, the page will be served as application/xhtml+xml. Internet Explorer 6, on the other hand, will receive text/html pages. Listing 3. Global.asax <script runat="server"> Sub Application_PreSendRequestHeaders(ByVal s As Object, _ ByVal e As EventArgs) If Array.IndexOf(Request.AcceptTypes, _ "application/xhtml+xml") > -1 Then Response.ContentType = "application/xhtml+xml" End If End Sub </script> Configuring XHTML Conformance The default behavior of the ASP.NET 2.0 framework is to render pages that validate against XHTML 1.0 Transitional. Most developers building Web sites will want to target this standard, because it is the standard that is the most compatible with existing HTML pages. However, there are situations in which this standard might be either too lax or too strict. For example, if you are feeling ambitious, you might decide to build an XHTML 1.0 Strict, or even an XHTML 1.1, Web site. After all, the goal of the XHTML 1.0 Transitional standard is to act as a springboard to these more restrictive standards. Because, by default, the ASP.NET 2.0 framework targets XHTML 1.0 Transitional, some of the ASP.NET controls will render attributes that are not compatible with XHTML 1.0 Strict or XHTML 1.1. Alternatively, you might discover that the XHTML 1.0 Transitional standard is too restrictive. Microsoft had to make several changes to existing ASP.NET 1.1 controls in order to comply with the XHTML 1.0 Transitional standard. Some of these changes might break an existing ASP.NET 1.1 Web site. In order to keep everyone happy, Microsoft created a new configuration option, named xhtmlConformance, that you can set in your Web site's configuration file. The new configuration option enables you to specify the level of XHTML conformance of your Web pages. It looks like this. <configuration> <system.web> <xhtmlConformance mode="transitional" /> </system.web> </configuration> By default, xhtmlConformance is set to the value transitional. However, you can also set this option to the value strict or legacy. If you set the xhtmlConformance option to strict, then certain attributes will no longer be rendered by the standard ASP.NET controls. For example, the ASP.NET <form> control will no longer render a name attribute. Unless your ASP.NET pages contain (non-standards-compliant) client-side scripts, you won't notice any changes when switching from transitional to strict mode. If you set the xhtmlConformance option to legacy, then the ASP.NET framework will revert to ASP.NET 1.1 rendering behavior for some elements and attributes (but not all). In this case, the ASP.NET framework will render content that is not compatible with any XHTML standard, and your pages will no longer validate against the XHTML standards. For example, in legacy mode, the <br> tag is not rendered with its required XHTML closing slash (<br />). Setting xhtmlConformance to legacy mode only makes sense when you run into a problem migrating an existing ASP.NET 1.1 application to ASP.NET 2.0. Building Accessible ASP.NET Web Sites The benefit of following public Web standards is that they make your Web pages accessible to the greatest number of people with the least amount of work. In particular, accessibility standards enable you to build Web sites that can be more easily accessed by persons with disabilities. It is worth emphasizing, once again, that a broad audience of Web site users has one form of disability or another. Think of the members of your own family and consider how many of them would have trouble interacting with a Web page. I have aging relatives who are blind or who are losing their motor coordination. My guess is that many readers of this paper also have aging parents or grandparents who would find it challenging to use most Web sites. There are many good reasons for building accessible Web sites: financial, moral, legal, and so on. Let's concentrate, however, on the legal motivations. In the United States, any Web site developed by a federal agency is required by Section 508 of the Rehabilitation Act to be accessible to persons with disabilities. This law applies to federal agencies and companies that contract with federal agencies (see). Other countries have similar requirements. For example, in Canada, the Treasury Board Common Look and Feel Standards require that Web sites developed by federal agencies be accessible. In Australia, the Disability Discrimination Act requires that all Web sites hosted on Australian servers (regardless of whether or not it is a government Web site) be accessible. (For more details on accessibility laws, see.) I don't know any Web site developer who would intentionally build a Web site that is not accessible to persons with disabilities. The problem is that most developers are not familiar with the various accessibility standards. In the following sections of this paper, you'll be provided with an overview of the two most important accessibility standards: the WCAG and Section 508 standards You'll also learn how to build accessible Web pages by using ASP.NET controls. Finally, you'll learn how to "validate" your Web pages for accessibility. Accessibility Standards Almost all accessibility standards and laws derive from the W3C Web Content Accessibility 1.0 Guidelines (WCAG). These guidelines were first published by the World Wide Web Consortium as a recommendation on May 5, 1999 (see). The WCAG consists of 14 guidelines. Each guideline, in turn, consists of one or more checkpoints that further clarify the guideline. Each checkpoint is ranked with a priority between 1 and 3. To make it easier to implement the guidelines, the W3C has published a set of documents that contain techniques for following the guidelines (see). You can claim different levels of conformance with the WCAG guidelines. If you claim that your Web site satisfies all priority 1 checkpoints, then you can display a logo that claims Conformance Level A. When a Web site meets all priority 1 and 2 checkpoints, the Web site can display a logo for Conformance Level Double-A. Finally, a Web site that satisfies all checkpoints can display the logo for Conformance Level Triple-A (see). The Section 508 guidelines derive from the WCAG guidelines. In the United States, federal agencies (and companies who contract with federal agencies) need to be most concerned with this set of guidelines, because these guidelines have the force of law. You can read the complete text of the Section 508 guidelines at the Section 508 Web site. The ASP.NET 2.0 framework was designed to enable you to meet all WCAG priority 1 and priority 2 checkpoints, and all Section 508 guidelines. These guidelines were taken very seriously. Every developer working on the ASP.NET 2.0 framework was required to review and test every ASP.NET control for accessibility. Furthermore, every developer had a screen reader installed on his or her desktop so that pages could be tested against the guidelines. Accessibility Improvements in ASP.NET 2.0 This paper focuses on six areas of accessibility improvements in the ASP.NET 2.0 framework. In the following sections, you learn how to use ASP.NET controls to display accessible images, forms, navigation, data, and XHTML. At the end of this section, we'll also consider accessibility issues related to using client-side scripts in ASP.NET pages. Creating Accessible Images You should not assume that everyone who interacts with your Web site can actually see your Web site. If someone is blind or has low vision, that person might need to use either a screen reader or a Braille display to visit your Web pages. A screen reader reads the text in your Web pages by using a speech synthesizer. A Braille display transforms the text in your pages into a Braille representation. Images and other non-text page elements, such as Java, Shockwave, and Flash content, is useless content for someone who cannot see. If you want to make your Web site accessible to people who have low-vision or who are blind, then you need to provide text equivalents for all non-textual content in your Web pages. Each and every image in a Web page should include an alt attribute. The alt attribute is used to represent alternate text read by a screen reader or other assistive device. Here's how you use the alt attribute. <img src="Products23.gif" alt="Image of Products" /> The alt attribute should contain a description of the image. It should never, under any circumstances, simply contain the filename of the image. The purpose of the alt attribute is to convey the same information to someone who is blind as the image conveys to someone who is sighted. Writing the value of an alt attribute requires human interpretation of the meaning of the element. For this reason, the process of creating alt attributes cannot be automated. Every ASP.NET control that displays an image includes a method for supplying alternate text for the image. For example, the ASP.NET Image control includes an AlternateText property. If you use an Image control, then you need to set the AlternateText attribute to a meaningful value. <asp:Image If an image is used only as a design element, then you should set its alt attribute to an empty string. If an image has no useful information to convey, then there is no reason to clutter up a screen reader's narration of the page. <img src="PageDivider.gif" alt="" /> Special measures had to be taken in the ASP.NET 2.0 framework to enable you to render empty AlternateText. If you assign empty text to an attribute of an ASP.NET control, then the ASP.NET control will not render the attribute at all. For example, imagine that you add the following ASP.NET Image control to a page. <asp:Image In this case, the following tag is rendered. <img src="PageDivider.gif" style="border-width:0px;" /> Notice that the alt attribute has disappeared. This is the default behavior of all ASP.NET control attributes. When you do not assign an attribute a value, it is not rendered. Unfortunately, in this case, we really want to render an empty value for the alt attribute. To work around this problem, a new property was introduced into the ASP.NET 2.0 framework to enable you to display empty alternate text with an Image control: the GenerateEmptyAlternateText property. <asp:Image If you use the GenerateEmptyAlternateText property, then an alt="" attribute is correctly rendered. When an image represents something truly complicated, such as an organizational chart, then you cannot use the alt attribute to provide an alternate text description. When you need to provide a long description of the meaning of an image, then you need to use the longdesc attribute. The longdesc attribute accepts either a relative or absolute URL for its value. The URL should link to a page that contains a textual description of the contents of the image. Here's a sample of how you can use this attribute with the <img> tag. <img src="OrgChart.gif" alt="Company Organization Chart" longdesc="/OrgChartDescription.aspx" /> The ASP.NET Image control includes a property, named DescriptionUrl, that corresponds to the HTML longdesc attribute. Here's a sample of how you can use this property. <asp:Image Creating Accessible Forms Web page forms can create problems for persons with low vision and for persons with reduced motor coordination. If you access a Web page form through a screen reader, then it might be difficult to associate form fields with their corresponding labels. For example, imagine that a Web page contains the following form. <table> <tr> <td>First Name:</td> <td><input name="txtFirstName" /></td> </tr> <tr> <td>Last Name:</td> <td><input name="txtLastName" /></td> </tr> </table> This form displays input fields for a person's first name and last name. In this case, because the form is displayed in a table, it might be difficult for a user of a screen reader to associate the proper label with the proper form field. In HTML 4.0, a new tag was introduced to enable you to associate a form field label with a form field: the <label> tag. Here's how the previous form should be written using a <label> tag. <table> <tr> <td><label for="txtFirstName">First Name:</label></td> <td><input name="txtFirstName" id="txtFirstName" /></td> </tr> <tr> <td><label for="txtLastName">Last Name:</label></td> <td><input name="txtLastName" id="txtLastName" /></td> </tr> </table> The <label> tag explicitly associates the form field labels with their corresponding form fields. Notice that the <input> fields include an id attribute, because the value of the for attribute must be an input field's id and not its name attribute. Normally, the ASP.NET Label control generates a <span> tag. However, if you provide an AssociatedControlId property when declaring an ASP.NET Label control, then the control renders a <label> tag. Here's how you can generate an accessible form with ASP.NET Label and TextBox controls. <table> <tr> <td><asp:LabelFirst Name:</asp:Label></td> <td><asp:TextBox</td> </tr> <tr> <td><asp:LabelLast Name:</asp:Label></td> <td><asp:TextBox</td> </tr> </table> When providing a label for an ASP.NET control, you should use the ASP.NET Label control instead of the HTML <label> tag. When you assign an ID to an ASP.NET control such as the TextBox control, the ID that is rendered to the browser might be a different ID than the ID that you assigned to the control. Therefore, if you use a <label> tag, the ID in the <label> tag might not match the ID of the rendered TextBox control. If, on the other hand, you use the ASP.NET Label control, you don't have to worry about this issue. The ASP.NET CheckBox, RadioButton, CheckBoxList, and RadioButtonList controls automatically render <label> tags. Be careful, when using these controls, to use the Text attribute to label the text of the control. You should not do the following. <asp:CheckBox Include Gift Wrap Instead, do the following. <asp:CheckBox Large forms can also create problems for individuals interacting with a Web page through a screen reader. When listening to a large form, it is easy to lose track of the section of the form that you are listening to. When displaying a large form, it is a good idea to divide the form into bite-sized chunks. You can divide a single form into multiple sections by using the <fieldset> tag. Here's a sample of how you can use this tag. <form id="form1" runat="server"> <div> <fieldset> <legend>Contact Information</legend> ... form fields </fieldset> <fieldset> <legend>Payment Information</legend> ... form fields </fieldset> </div> </form> This form is divided into two subforms, using the <fieldset> tag. The <legend> tag is used to label the purpose of the subforms. When displayed in Internet Explorer, Firefox, and Opera, the subforms are visually divided into separate areas by a border (see Figure 5). However, it is important to keep in mind that the primary purpose of the <fieldset> tag is accessibility. If you don't like the visual appearance of the <fieldset> tag, then you can modify the appearance of the tag through a style sheet rule, or you can completely hide the tag by using the CSS display or visibility attribute. Figure 5. The <fieldset> tag People with low vision are not the only users of a Web page who might find a Web form challenging. Individuals who have reduced motor coordination can also experience difficulty when interacting with a form. When building a Web form, it is always a good idea to include accesskey and tabindex attributes for each of the form fields. The accesskey attribute enables someone who cannot use a mouse to navigate directly to any form field. The tabindex attribute enables you to control the tabbing order of the form fields. Both attributes make life easier for someone who must interact with your page through a keyboard (or an assistive device that acts like a keyboard). Here's a sample form that uses both the accesskey and tabindex attributes. <asp:Label<u>F</u>irst Name</asp:Label> <asp:TextBox <br /> <asp:Label<u>L</u>ast Name</asp:Label> <asp:TextBox The tabindex attribute is used to control the tab order of the form fields. Because the first form field has a tabindex value of 1, any other elements in the page that appear before the form are skipped when the user first hits the TAB key. When using Internet Explorer or Firefox, pressing ALT+F automatically moves focus to the First Name text box. If you press ALT+L, then focus is automatically moved to the Last Name text box. When using Opera, you must first press SHIFT+ESC before selecting an access key. Notice that the first letter of both the First Name and Last Name labels are underlined. Underlining the letter provides the user of the Web site with a visual indication of the access keys. This is the standard way to mark access keys in Microsoft Windows applications. However, there are other proposed methods for indicating access keys in a form (see). One problem with using underlines to indicate access keys is the fact that you cannot underline characters in a button, and hyperlinks are already underlined. For example, the following Button control does not work as you would expect and hope. <asp:Button When this ASP.NET Button control is rendered, the actual text <u>S</u>ubmit is displayed, instead of an underlined S character. The ASP.NET Button control renders an HTML <input type="submit"> tag, and, unfortunately, the <input type="submit"> tag does not support underlining. You might think that you could get around this problem by using a style rule. Unfortunately, there currently is no cross-browser compatible method of underlining a single character in an <input type="submit"> tag using Cascading Style Sheets. You can get around this problem if you are willing to use client-side JavaScript in the page. The page in Listing 4 contains JavaScript that displays or hides all of the access keys, depending on whether the ALT key is held down. When you hold down the ALT key, boxes pop up, displaying the access key keyboard combinations (see Figure 6). This script works in both Internet Explorer and Firefox (Opera does not use the ALT key to select access keys). Figure 6. AccessKeys.aspx Listing 4. AccessKeys.aspx <%@ Page <html xmlns="" > <head id="Head1" runat="server"> <title>Contact Form</title> <style type="text/css"> .accessKey { display:none; position:absolute; z-index:5000; padding:3px; border:solid 1px black; background-color: #ffffe0 } </style> <script type="text/javascript"> /* <![CDATA[ */ window.onload = function() { document.onkeydown = displayAccessKeys; } function displayAccessKeys(e) { if (!e) e = window.event; if (e.keyCode == 18) { toggleAccessKeys(); document.onkeydown = null; document.onkeyup = hideAccessKeys; } } function hideAccessKeys(e) { if (!e) e = window.event; if (e.keyCode == 18) { toggleAccessKeys(); document.onkeyup = null; document.onkeydown = displayAccessKeys; } } function toggleAccessKeys() { var spans = document.getElementsByTagName('span'); for (var k=0;k<spans.length;k++) if (spans[k].className == 'accessKey' ) { if ( 'inline' != spans[k].style.display) spans[k].style.display = 'inline'; else spans[k].style.display = 'none'; } } /* ]]> */ </script> </head> <body> <form id="form1" runat="server"> <div> <table> <tr> <td> <asp:LabelFirst Name</asp:Label> </td> <td> <asp:TextBox <span class="accessKey">access key is f</span> </td> </tr> <tr> <td> <asp:LabelLast Name:</asp:Label> </td> <td> <asp:TextBox <span class="accessKey">access key is l</span> </td> </tr> <tr> <td colspan="2"> <asp:Button <span class="accessKey">access key is s</span> </td> </tr> </table> </div> </form> </body> </html> The page in Listing 4 contains a style sheet and client-side JavaScript. The style sheet hides the contents of any <span> tag identified by the accessKey class. The JavaScript detects when the ALT key has been pressed, and reveals the contents of the <span> tags. Note that this page will function even when style sheets and JavaScript are disabled on a Web browser. In that case, the access key help will always be displayed (see Figure 7). Figure 7. AccessKeys.aspx degrading gracefully Creating Accessible Navigation I hate calling customer support numbers and following the automated systems. I feel myself slowly age as the computer voice announces each and every option in its droning voice. If you press one wrong key, you end up lost forever in the depths of the automated computer system. Unfortunately, if you are forced to use a screen reader, this is precisely your experience when you visit almost any Web page. Most Web sites include on every page a navigation bar that contains a list of links to the various sections of the Web site. If you are using a screen reader, then you must listen to each of these navigation links, one at a time, whenever you open a page. With one simple modification to a navigation bar, you can dramatically improve the accessibility of your Web pages. You simply need to add a method for someone to skip all of the navigation links. You can do this with a "Skip Navigation link." For example, the CNN Web site includes a navigation bar that lists the different sections of the CNN Web site (World, U.S., Weather, and so on). However, the designers of the CNN Web site have done something smart. If you view the source of the page, you'll notice that the following link appears above the navigation bar. <a href="#ContentArea"><img src="" alt="Click here to skip to main content." width="10" height="1" border="0" align="right"></a> When you view the home page of the CNN Web site, you never see this link. The image contained in the link is a transparent single-pixel image. However, if you access this page with a screen reader, then the alternate text associated with the image is read. A person who is blind can choose to skip all of the navigation links and move directly to the main content area of the Web page (The equivalent of pressing 0 in an automated voice system and navigating directly to the operator). Skip Navigation links have been integrated into several of the standard ASP.NET 2.0 controls. In particular, the Menu, TreeView, SiteMapPath, Wizard, and CreateUserWizard controls all support Skip Navigation links. For example, the page in Listing 5 includes an ASP.NET Menu control. This control is used to display a list of links to other pages in the Web site. Listing 5. SiteMenu.aspx <%@ Page <html xmlns="" > <head> If you view the source of the page in Listing 5, you'll see that the following link appears;" /> This link contains a zero-width and zero-height image that does not appear when you view the page. However, someone accessing this page through a screen reader can select the Skip Navigation link to skip to the end of the menu. By default, the Skip Navigation link contains the text Skip Navigation Links. You can modify this value by changing the Menu control's SkipLinkText property. Creating Accessible Data The ASP.NET 2.0 framework includes a rich set of controls for displaying database data. These controls include the GridView, DetailsView, DataList, FormView, and Repeater controls. By default, the GridView, DetailsView, and DataList controls display database records in an HTML table. Presenting information in HTML tables, if not done right, can create accessibility problems. When the content of an HTML table is read aloud, you can easily lose track of your current position in the table. For example, imagine that you use an HTML table to display a list of product information. When the content of the table is read by a screen reader, you can easily get confused about whether a certain table cell represents information about the product name, the number of products on order, or a code for the warehouse that stores the products. When you look at an HTML table, you can determine the meaning of a particular cell by glancing at either the column or row heading. In order to make tables accessible to persons who are using screen readers, you need to explicitly mark the table headings, and explicitly associate the headings with each cell. When you create a table to display data, you should always use the proper tags to mark the column and row headings. A table heading should always be marked with the <th> tag, as follows. <table> <thead> <tr> <th>Product Name</th> <th>Price</th> </tr> </thead> <tbody> <tr> <td>Milk</td> <td>$2.33</td> </tr> <tr> <td>Cereal</td> <td>$5.61</td> </tr> </tbody> </table> In this example, the <th> tag is used to mark the two column headings: Product Name and Price. Some designers avoid using the <th> tag because they do not like the default visual appearance of it. In most browsers, the contents of a <th> tag are centered and bolded. However, it is important to remember that tags should never be used to control presentation. If you want the column headings to look like normal table cells, then you should add a style rule such as the following. <style type="text/css"> th {text-align:left;font-weight:normal} </style> In order to make a table accessible, you should also explicitly indicate the heading or headings associated with each cell. There are several attributes that you can use for this purpose: scope, headers, and axis. The scope attribute can be used to indicate whether a table heading> This table contains the schedule for the Boston subway Red Line (see Figure 8). Notice that each of the column headings include a scope="col" attribute, and each of the row headings include a scope="row" attribute. Figure 8. Simple subway schedule The scope attribute works great for simple tables. However, in the case of more complicated tables, you need to use the headers attribute. For example, a nested table might have three or more headings associated with a single cell. The headers attribute enables you to mark each cell with its associated headings. The axis attribute enables you to categorize a table heading. For example, in the subway schedule table, the attribute axis="location" could be added to each heading that represents a location (the Alewife and Braintree headings). The axis attribute accepts a comma delimited list of categories. The page in Listing 6 contains a more complicated version of the Boston subway schedule that uses both the headers and axis attributes (see Figure 9). Figure 9. Complicated subway schedule Listing 6. Subway.aspx <%@ Page <html xmlns="" > <head> Notice that each table cell contains a headers attribute. The headers attribute represents a space delimited list of IDs that correspond to column and row headings. Each cell in the subway schedule table has an associated location, day, and train heading. Also, notice that each <th> tag has an axis attribute that is used to represent the category associated with the heading. For example, the Weekday and Saturday headings are both associated with the day axis. The First Train and Last Train headings are associated with the train axis. Finally, notice that the table in Listing 6 contains both a summary attribute and a <caption> tag. The summary attribute works very much like the alt attribute. You can use the summary attribute to provide a description of the table that is not rendered by the browser. The contents of the <caption> tag, on the other hand, are rendered by the browser. You should use the <caption> tag to label the purpose of a table. If you use the ASP.NET 2.0 GridView or DetailsView controls to display database data in an HTML table, then the generated HTML table is accessible by default. For example, Listing 7 contains an ASP.NET page that displays the contents of the Titles database table by using a GridView control. Listing 7. DisplayTitles.aspx <%@ Page <html xmlns="" > <head runat="server"> <title>Display Titles</title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView <asp:SqlDataSource </div> </form> </body> </html> In Listing 7, the GridView control is bound to a SqlDataSource control that represents the records from the Titles database table. When the ASP.NET page in Listing 7 is opened in a browser, the contents of the Titles database table is displayed in an HTML table (see Figure 10). Figure 10. DisplayTitles.aspx (Click the graphic for a larger image.) Notice that the GridView control automatically generates <th> tags for each of the column headers. Furthermore, if you select View Source in your browser, you can see that scope="col" attributes are automatically generated for each column heading. The GridView control supports several additional properties relevant to accessibility: - Caption and CaptionAlign—Use these properties to add a caption to the HTML table generated by the GridView control. - RowHeaderColumn—Use this property to indicate a row header (as opposed to a column header). Set this property to the name of a column returned from the data source (such as title_id). - UseAccessibleHeader—Use this property to indicate whether column headings should be rendered with <th scope="col"> tags or <td> tags. By default, this property has the value true. Notice that the GridView control does not have a Summary property. However, like most ASP.NET controls, the GridView control supports expando attributes. You can declare any attribute you please when you declare the GridView control, and the attribute will be rendered to the browser. So, if you want to add a summary to a GridView, declare the summary attribute as follows. <asp:GridView The default behavior of the GridView control is great for displaying a simple table of data in an accessible manner. However, if you need to display a more complicated table, such as a set of nested tables, then you must perform additional work. Imagine, for example, that you want to display a list of product categories and, under each category, you want to display a list of matching products. In other words, you want to create a single page Master/Detail form (see Figure 11). In that case, you'll need to include the headers attribute for each table cell. Figure 11. Nested Repeater controls The page in Listing 8 illustrates how you can nest one Repeater control in a second Repeater control and generate a complicated table that meets the requirements of the accessibility guidelines. Listing 8. NestedRepeaters.aspx <%@ Page <script runat="server"> Private dtblProducts As New DataTable Sub Page_Load() Dim dad As New SqlDataAdapter("SELECT * FROM PRODUCTS", _ "Server=localhost;Trusted_Connection=true;Database=Northwind") dad.Fill(dtblProducts) End Sub Function GetProducts(ByVal CategoryID As Integer) As DataView Dim view As DataView = dtblProducts.DefaultView view. <head runat="server"> <title>Untitled Page</title> <style type="text/css"> .categoryRow {background-color:yellow} </style> </head> <body> <form id="form1" runat="server"> <div> <asp:Repeater <HeaderTemplate> <table> <thead> <th id="hdrID">ID</th> <th id="hdrName">Name</th> <th id="hdrPrice">Price</th> </thead> <tbody> </HeaderTemplate> <ItemTemplate> <tr class="categoryRow"> <th colspan="3" id='<%# GetCategoryHeader(Container.ItemIndex) %>'> <%# Eval("CategoryName") %> </th> </tr> <asp:Repeater <ItemTemplate> <tr> <th id='<%# GetProductHeader(Eval("ProductID")) %>'> <%# Eval("ProductID") %> </th> <td headers='<%# GetHeaders(Container, "hdrName") %>'> <%#Eval("ProductName")%> </td> <td headers= '<%# GetHeaders(Container, "hdrPrice") %>'> <%#Eval("UnitPrice", "{0:c}")%> </td> </tr> </ItemTemplate> </asp:Repeater> </ItemTemplate> <FooterTemplate> </tbody> </table> </FooterTemplate> </asp:Repeater> <asp:SqlDataSource </div> </form> </body> </html> In Listing 8, the outer Repeater control is used to list the product categories, and the inner Repeater control is used to list the matching products. Two helper functions are used to generate the id values for the Category Name and Product ID headers: the GetProductHeader and GetCategoryHeader functions. A separate helper function, named GetHeaders, is used to generate the values used with the headers attribute. The ASP.NET page in Listing 8 generates an HTML table that looks like this. <table> <thead> <th id="hdrID">ID</th> <th id="hdrName">Name</th> <th id="hdrPrice">Price</th> </thead> <tbody> <tr class="categoryRow"> <th colspan="3" id='hdrCategory0'> Beverages </th> </tr> <tr> <th id='hdrProduct1'> 1 </th> <td headers='hdrCategory0 hdrProduct1 hdrName'> Chai 2 </td> <td headers='hdrCategory0 hdrProduct1 hdrPrice'> $18.55 </td> </tr> <tr> <th id='hdrProduct2'> 2 </th> <td headers='hdrCategory0 hdrProduct2 hdrName'> Chang </td> <td headers='hdrCategory0 hdrProduct2 hdrPrice'> $19.00 </td> </tr> .... remainder of the table Notice that each <td> tag contains a proper headers attribute. Creating Accessible XHTML One common theme that is shared by many of the accessibility guidelines is the idea that Web pages should be standards compliant in order to be accessible. According to the guidelines, you should strive to use the latest W3C standards, such as the latest versions of XHTML and Cascading Style Sheets, when building Web sites. In particular, when designing Web pages, you should separate the structure of a document from its presentation. Use tags to represent the structure of your Web pages, and use Cascading Style Sheets to control the appearance of your Web pages. For example, never use the <blockquote> element purely to indent a block of text. The purpose of the <blockquote> element is to create a citation for a source. If you want to indent text, you should use the Cascading Style Sheet margin attribute instead. You should also strive to use <table> tags only when representing tables of data. While using <table> tags to layout a Web page is currently a common practice, try to use <div> tags instead. For example, the page in Listing 9 has a three-column layout, but does not contain a single <table> tag (see Figure 12). Figure 12. Tableless page layout (Click the graphic for a larger image.) Listing 9. Tableless.aspx <%@ Page <html xmlns="" > <head runat="server"> <title>Tableless Layout</title> <style type="text/css"> #content { margin-left:auto; margin-right:auto; width:800px; } #leftColumn { float:left; width:150px; border:1px solid black; padding:10px; } #middleColumn { float:left; width:430px; padding:10px; } #rightColumn { float:right; width:150px; border:1px solid black; padding:10px; } </style> </head> <body> <form id="form1" runat="server"> <div id="content"> <div id="leftColumn"> Left column contents... Left column contents... Left column contents... Left column contents... Left column contents... Left column contents... Left column contents... Left column contents... Left column contents... Left column contents... </div> <div id="middleColumn"> Middle column contents... Middle column contents... Middle column contents... Middle column contents... Middle column contents... Middle column contents... Middle column contents... Middle column contents... Middle column contents... </div> <div id="rightColumn"> Right column contents... Right column contents... Right column contents... Right column contents... Right column contents... Right column contents... Right column contents... Right column contents... </div> </div> </form> </body> </html> The page in Listing 9 contains four <div> tags. The first <div> tag, named content, is used to specify the width of the page's content area. The remaining three <div> tags—named left, middle, and right—divide the content area into three columns. This page displays correctly in Internet Explorer 6, Firefox, and Opera 8. (To view some really beautiful pages that do not use HTML tables for layout, see.) The WCAG guidelines recognize that it is not always possible to avoid using <table> tags to create page layouts, because older browsers do not fully support the Cascading Style Sheet standards (see WCAG Guideline 5). In those cases in which you cannot avoid using tables for layout, you should verify that the content of the tables makes sense when linearized (that is, read in table-cell order). Because the ASP.NET framework must be compatible with browsers both old and new, some of the ASP.NET controls do, in fact, use <table> tags for layout. For example, the ASP.NET 2.0 Login control uses the <table> tag to control the layout of the user name and password input fields. Creating Accessible Scripts One, quite severe, restriction included in both the WCAG and Section 508 guidelines concerns client-side scripts. According to a priority 1 checkpoint in the WCAG 1.0 guidelines: 6.3 Ensure that pages are usable when scripts, applets, or other programmatic objects are turned off or not supported. If this is not possible, provide equivalent information on an alternative accessible page. [Priority 1] The Section 508 guidelines include a similar requirement: (l) When pages utilize scripting languages to display content, or to create interface elements, the information provided by the script shall be identified with functional text that can be read by assistive technology. The problem is that several ASP.NET controls require client-side JavaScript in order to function. The prime example of this is the ASP.NET LinkButton control. The LinkButton control uses JavaScript to submit the form containing the control to the Web server. There is no good solution to this problem. If you are required to build a Web site that meets all accessibility guidelines, then you need to be very careful about using client-side scripts. You might need to avoid using certain ASP.NET controls that depend on JavaScript, such as the LinkButton control. Unfortunately, this guideline is difficult to follow when building a modern Web site. The assumption seems to be that Web sites are more like magazines than applications. Modern Web sites tend to include dynamic, client-side content. For example, many real estate Web sites include a JavaScript mortgage calculator. It is not clear what the text equivalent of a JavaScript mortgage calculator would look like. Validating Pages for Accessibility There is no such thing as a completely automated validator for accessibility in the same way as there is a completely automated validator for XHTML. There can't be an automated validator for accessibility, because judging the accessibility of a page requires human interpretation. For example, in order to make a Web page accessible, every image in the page must contain meaningful alternate text. Currently, no machine can determine whether a fragment of text has the same meaning as an image. At best, an accessibility validator can only provide you with a list of things that you should check. Visual Studio 2005 (but not Visual Web Developer) includes an Accessibility Checker. You can open the Accessibility Checker from the toolbar. or you can select the menu option Tools, Check Accessibility (see Figure 13). Figure 13. Visual Studio 2005 Accessibility Checker (Click the graphic for a larger image.) The Accessibility Checker provides you with options for validating your Web site against WCAG Priority 1 checkpoints, WCAG Priority 2 checkpoints, or Section 508 guidelines. You can view the results of validating your Web site by opening the Error List (select the menu option View, Other Windows, Error List). The Visual Studio 2005 Accessibility Checker also provides you with the option of displaying a "manual checklist" of accessibility issues. If you select this option, the same static list of accessibility issues is displayed in the Error List window whenever you validate your Web site for accessibility. This checklist contains issues that cannot be automatically validated by the Accessibility Checker. If you are building Web sites with Visual Web Developer, you can also check your Web pages for accessibility. To do this, you'll need to use one of the online Accessibility Checkers. Here are links to two of the most popular online accessibility checkers: Sample Application: An Accessible XHTML ASP.NET Web Site In this final section, we'll build an ASP.NET 2.0 Web site from start to finish. The source code for this sample Web site is included with this whitepaper. You can download the source code for the sample Web site, and open the Web site in either Visual Web Developer or Visual Studio 2005. The goal is to create a Web site that is completely standards compliant. Our Web site will validate as XHTML 1.0 Strict (and even XHTML 1.1). Furthermore, the Web site will be accessible to persons with disabilities. It will satisfy both section 508 and WCAG (priority 1 and priority 2) accessibility requirements. We will build an online bookstore called the Super Super Bookstore Web site. We'll retrieve all of our book listings for our bookstore through the Amazon E-Commerce Web services. The Amazon E-Commerce Web services provide us with plenty of free sample data to play with (for more information about the Amazon Web Services, see). To keep things simple, our Web site will consist of only two ASP.NET pages: - Default.aspx—This page displays a list of books in a specified category. - Search.aspx—This page enables you to search for all books that meet a certain search criterion. Behind the scenes, the Web site uses several new features of the ASP.NET 2.0 framework. For example, the Web site uses a Master Page to create a common page layout, and a Theme to create a common page style. Finally, the sample site uses the new GridView and ObjectDataSource controls for data access. Accessing the Amazon Web Services The Super Super Bookstore uses a common class, named Amazon, to retrieve book information and perform searches against the Amazon catalog of books. This class is contained in Listing 10. Listing 10. Amazon.vb Imports Microsoft.VisualBasic Public Class Amazon Const SubscriptionId As String = "1CD1NYF3YQ830DG7AM02" ''' <summary> ''' Attempts to get books in category from cache. ''' If not in cache, call Amazon Web service ''' </summary> Public Function GetBooks(ByVal CategoryId As String) _ As AmazonServices.Item() Dim context As HttpContext = HttpContext.Current Dim Books As AmazonServices.Item() If IsNothing(context.Cache(CategoryId)) Then Books = GetBooksFromAmazon(CategoryId) context.Cache(CategoryId) = Books Else Books = CType(context.Cache(CategoryId), _ AmazonServices.Item()) End If Return Books End Function ''' <summary> ''' Retrieves books in certain category from Web service ''' </summary> Public Function GetBooksFromAmazon(ByVal CategoryId As String) _ As AmazonServices.Item() Dim service As New AmazonServices.AWSECommerceService() ' Initialize Request Dim searchRequest As New AmazonServices.ItemSearchRequest With searchRequest .SearchIndex = "Books" .Sort = "salesrank" .ResponseGroup = New String() {"Medium"} .BrowseNode = CategoryId End With Dim search As New AmazonServices.ItemSearch With search .SubscriptionId = SubscriptionId .Request = New AmazonServices.ItemSearchRequest() _ {searchRequest} End With ' Get Response Dim response As AmazonServices.ItemSearchResponse = Nothing Try service.Timeout = 5000 response = service.ItemSearch(search) Catch End Try If IsNothing(response) Then Return Nothing End If Return response.Items(0).Item End Function ''' <summary> ''' Searches for books by calling Amazon Web service ''' </summary> Public Function SearchBooksFromAmazon(ByVal Author As String, _ ByVal Title As String, ByVal Keywords As String, _ ByVal PowerSearch As String) As AmazonServices.Item() ' Don't search if nothing to search for If IsNothing(PowerSearch) And IsNothing(Author) And _ IsNothing(Title) And IsNothing(Keywords) Then Return Nothing End If ' Initialize Request Dim service As New AmazonServices.AWSECommerceService() Dim searchRequest As New AmazonServices.ItemSearchRequest With searchRequest .SearchIndex = "Books" .ResponseGroup = New String() {"Medium"} If Not IsNothing(PowerSearch) Then .Power = PowerSearch Else If Not IsNothing(Author) Then .Author = Author End If If Not IsNothing(Title) Then .Title = Title End If If Not IsNothing(Keywords) Then .Keywords = Keywords End If End If End With Dim search As New AmazonServices.ItemSearch With search .SubscriptionId = SubscriptionId .Request = New AmazonServices.ItemSearchRequest() _ {searchRequest} End With ' Get Response Dim response As AmazonServices.ItemSearchResponse Try service.Timeout = 5000 response = service.ItemSearch(search) Catch End Try If IsNothing(response) Then Return Nothing End If Return response.Items(0).Item End Function ''' <summary> ''' The Amazon Author property represents a list of authors. ''' Therefore, we create a comma separated list ''' </summary> Public Shared Function FormatAuthor(ByVal Authors As String()) _ As String If Not IsNothing(Authors) Then Return String.Join(", ", Authors) Else Return "Not Listed" End If End Function ''' <summary> ''' Formats Amazon ListPrice into US currency ''' </summary> Public Shared Function FormatPrice(ByVal Price As String) As String If Not IsNothing(Price) Then Return "$" & Price.Insert(Price.Length - 2, ".") Else Return "Not Listed" End If End Function ''' <summary> ''' Formats tooltip for the link to the book details ''' </summary> Public Shared Function _ FormatDetailsTooltip(ByVal Title As String) As String If Not IsNothing(Title) Then Return String.Format("Link to {0} details", Title) Else Return "Link to details" End If End Function ''' <summary> ''' If there is no book cover, we fall back to displaying our image ''' </summary> Public Shared Function FormatBookCover(ByVal Url As String) _ As String If Not IsNothing(Url) Then Return Url Else Return "Images/NoBookCover.gif" End If End Function End Class The two most important functions in the class are called GetBooksFromAmazon and SearchBooksFromAmazon. The first function is called from the Default.aspx page to display the book listings by category. The second function is called from the Search.aspx page to enable users to search for books. Both functions use a Web Service proxy class named AmazonServices. This proxy class was created by selecting the menu option Web site, Add Web Reference, and entering the URL. This is the proper URL for accessing United States Amazon data. The Default Page The Default.aspx page displays a list of book categories, and a list of matching books for the selected category (see Figure 14). The Default.aspx page is contained in Listing 11. Figure 14. The default page (Click the graphic for a larger image.) Listing 11. Default.aspx <%@ Page Sub Page_Load() Dim categoryIndex As Integer = 0 If Not IsNothing(Request("index")) Then categoryIndex = Int32.Parse(Request("index")) End If MenuCategories.Items(categoryIndex).Selected = True End Sub </script> <asp:Content <h1>Book Listings</h1> <hr /> <div id="leftColumn"> <asp:Menu <Items> <asp:MenuItem <asp:MenuItem <asp:MenuItem <asp:MenuItem <asp:MenuItem <asp:MenuItem </Items> </asp:Menu> <="GetBooks" Runat="server"> <SelectParameters> <asp:ControlParameter </SelectParameters> </asp:ObjectDataSource> </div> </asp:Content> This page uses two ASP.NET controls to display the book listings: the Menu control and the GridView control. The Menu control is used to display the list of book categories, and the GridView control is used to display the list of books. The GridView control is bound to an ObjectDataSource control. The ObjectDataSource control, in turn, calls the GetBooks() method from the Amazon class, to retrieve the list of books. XHTML Features of the Default Page One goal, when building XHTML pages, is to cleanly separate a document's structure from its presentation. To reach this goal, no formatting properties are set on any of the ASP.NET controls in the Default.aspx page. The page formatting is encapsulated in an external style sheet that is associated with the page through an ASP.NET Theme. ASP.NET 2.0 Themes make it easier to follow web standards, because they enable you to separate all of your presentational content from your pages. The sample site includes a Theme, named SiteTheme, that contains a single style sheet. This Theme is automatically associated with every page, using the following configuration setting in the Web.Config file. <pages styleSheetTheme="SiteTheme" masterPageFile="SiteMaster.master" /> You should notice that HTML tables are not used to create the page layout. Although neither the XHTML standard nor accessibility standards prohibit you from using tables for page layout, both standards encourage you to avoid it. In the sample site, the page layout is completely determined by the external style sheet. The page itself is divided into two columns by two <div> elements. The external style sheet contains rules for positioning the two <div> elements. Finally, the sample site uses content negotiation when serving pages. When a page is requested from the Web site, using a browser that understands the application/xhtml+xml MIME type, the page is served with this MIME type; otherwise, the page is served as text/html. The content negotiation is accomplished with the following event handler in the Global.asax file. Sub Application_PreSendRequestHeaders(ByVal s As Object, _ ByVal e As EventArgs) If Array.IndexOf(Request.AcceptTypes, _ "application/xhtml+xml") > -1 Then Response.ContentType = "application/xhtml+xml" End If End Sub Accessibility Features of the Default Page Both the WCAG and Section 508 accessibility guidelines prohibit client-side JavaScript when a text equivalent of the JavaScript cannot be provided. In order to satisfy these guidelines, the Default.aspx page does not depend on client-side JavaScript. The page works even when you turn off JavaScript in your browser. In order to satisfy this requirement, extra work had to be done when implementing the menu. By default, the ASP.NET Menu control renders JavaScript for each menu item to handle the client click event. However, when a menu item is provided with a NavigateUrl property, the menu item no longer uses JavaScript. In the sample site, each menu item is provided with a NavigateUrl property that points back to the Default.aspx page. When you click a menu item, the Default.aspx page is reloaded. The Page_Load event handler is used to detect which menu item was clicked, and this subroutine updates the menu with the current menu selection. The advantage of using a Menu control is that a Menu control automatically generates a Skip Navigation link. If you tab through each of the elements in the Default.aspx page, you'll notice (if you look at your browser's status bar) that there is a hidden link that skips the contents of the menu. The Menu control enables you to automatically satisfy the WCAG and Section 508 guidelines that require you to provide a method of skipping repetitive navigation links. The Search Page The search page contains a form that enables users of the Web site to search for books by supplying the book author, book title, book keywords, or by supplying a complex query (see Figure 15). The results of the query are displayed in a GridView control. The Search.aspx page is contained in Listing 12. Figure 15. The search page (Click the graphic for a larger image.) Listing 12. Search.aspx <%@ Page Protected Sub btnQuickSearch_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) txtPowerSearch.Text = String.Empty End Sub Protected Sub btnPowerSearch_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) txtAuthor.Text = String.Empty txtTitle.Text = String.Empty txtKeywords.Text = String.Empty End Sub </script> <asp:Content <h1>Search Books</h1> <hr /> <div id="leftColumn"> <fieldset class="quickSearch"> <legend>Quick Search</legend> <asp:Label <asp:TextBox <span class="accessKey">access key is a</span> <br /> <asp:Label <asp:TextBox <span class="accessKey">access key is t</span> <br /> <asp:Label <asp:TextBox <span class="accessKey">access key is k</span> <br /> <asp:Button <span class="accessKey">access key is s</span> </fieldset> <br /> <fieldset class="powerSearch"> <legend>Power Search</legend> <asp:Label <asp:TextBox <span class="accessKey">access key is q</span> <br /> <asp:Button <span class="accessKey">access key is p</span> </fieldset> <="SearchBooksFromAmazon" Runat="server"> <SelectParameters> <asp:ControlParameter <asp:ControlParameter <asp:ControlParameter <asp:ControlParameter </SelectParameters> </asp:ObjectDataSource> </div> </asp:Content> XHTML Features of the Search Page The search page, just like the default page, contains no presentational elements or attributes. The style and layout of the search page is completely encapsulated in an external style sheet associated with the page through an ASP.NET Theme. Again, like the default page, the search page uses content negotiation. If someone requests the search page with a browser that recognizes the application/xhtml+xml MIME type, then the page is served with this MIME type; otherwise, the page is served as text/html. Accessibility Features of the Search Page The search page includes a form. Or, more accurately, the page contains a single form divided into two subforms. It includes a Quick Search form and a Power Search form. Notice that the form is divided into subforms with the HTML <fieldset> tag. The <fieldset> tag enables you to group logically related form elements. The accessibility guidelines require you to use the <fieldset> tag when working with complex forms (see WCAG 12.3). Notice, furthermore, that each form field is explicitly associated with its label. Each ASP.NET control includes an AssociatedControlID property that points to its corresponding form field. These explicit associations between labels and fields help users of screen readers determine the purpose of particular form fields. Finally, notice that each Label control is assigned an access key. The access keys enable you to easily navigate the form fields without using a mouse. For example, if you press ALT+A, you can enter the name of an author. If you then press ALT+S, the Quick Search form is submitted, and the results are displayed in the GridView. In other words, you can easily perform searches without touching the mouse. If you press the ALT key, the access keys are automatically displayed (see Figure 16). This is accomplished through JavaScript. Notice that there is a <span> tag that appears after each form field. For example, the Title search field is implemented with the following code. <asp:Label <asp:TextBox <span class="accessKey">access key is t</span> When you press the ALT key, client-side JavaScript executes, and the contents of the <span> tag are displayed. Figure 16. Search form access keys You might worry about this functionality, because, according to the accessibility guidelines, the page must continue to work when JavaScript and style sheets are turned off (WCAG guideline 6). Fortunately, the page does work when both JavaScript and style sheets are disabled. In that case, the contents of the <span> tags are no longer hidden, and the access keys are always displayed (see Figure 17). Figure 17. Search form degrading gracefully The Master Page The sample Web site uses an ASP.NET 2.0 Master Page, named SiteMaster.master, behind the scenes. Master Pages enables you to include the same content and create the same layout in multiple pages in a Web site. The Master Page is associated with every page in the sample Web site through the following configuration setting in the Web.Config file. <pages styleSheetTheme="SiteTheme" masterPageFile="SiteMaster.master" /> The contents of the Master Page are contained in Listing 13. Listing 13. SiteMaster.master <%@ Master <script runat="server"> ''' <summary> ''' Select style sheet to display ''' </summary> Sub Page_Load() If Not IsNothing(Request("large")) Then Profile.AccessibleStyleSheet = True End If If Not IsNothing(Request("normal")) Then Profile.AccessibleStyleSheet = False End If If Profile.AccessibleStyleSheet Then lnkAccessibleStyle.Visible = True lnkStyle. <head runat="server"> <title>Super Super Books</title> <script type="text/javascript" src="Scripts/AccessKeys.js"></script> <link id="lnkAccessibleStyle" type="text/css" rel="Stylesheet" href="~/Styles/Accessible.css" runat="server" /> </head> <body> <form id="form1" runat="server"> <div id="content"> <img id="SiteLogo" src="Images/SiteLogo.png" alt="SSB Web site logo image" /> <div id="banner"> <asp:HyperLink <br /> <asp:Menu <Items> <asp:MenuItem <asp:MenuItem </Items> </asp:Menu> </div> <hr /> <asp:contentplaceholder <hr /> <a href="" title="Explanation of XHTML 1.0 Conformance"> <img src="" alt="Valid XHTML 1.0 icon" class="icon"/></a> <a href="" title="Explanation of CSS Conformance"> <img src="" alt="Valid CSS icon" class="icon" /></a> <a href="" title="Explanation of Level Double-A Conformance"> <img height="32" width="88" src="" alt="Level Double-A conformance icon, W3C-WAI Web Content Accessibility Guidelines 1.0" class="icon" /></a> </div> </form> </body> </html> XHTML Features of the Master Page By taking advantage of Master Pages, you can easily supply the right DOCTYPE for all of the pages in your Web site. The SiteMaster.master page includes the XHTML 1.0 Strict DOCTYPE. The benefit of specifying the DOCTYPE in a Master Page is that you only need to change it in one location if you ever need to change the DOCTYPE for all the pages in a Web site in the future. For example, some day soon, you might want to migrate to an XHTML 1.1 Web site and modify the DOCTYPE to reflect the change. The Master Page also includes a series of conformance logos, which appear in the footer of every page in the sample Web site. The conformance logos advertise that the Web site conforms to XHTML, CSS, and WCAG 1.0 Web standards (see Figure 18). Figure 18. Conformance logos Accessibility Features of the Master Page Every page in the sample Web site includes a link at the top of the page that can be used to switch the style sheet used to display the page. Each page can be displayed in one of two versions: a Normal Text version and a Large Text version. When the Large Text version is selected, the size of all of the text in the Web site is increased to a more readable size (see Figure 19). Figure 19. Large text size A user needs to make this selection only once. If someone selects the Large Text version of the Web site, this preference is automatically recorded and used whenever the person returns to the Web site. This functionality is implemented by taking advantage of yet another new feature of the ASP.NET 2.0 framework: Profiles. A Profile enables you to store user settings across multiple visits to a Web site. The Profile is defined in the Web.Config file. <anonymousIdentification enabled="true"/> <profile> <properties> <add name="AccessibleStyleSheet" type="Boolean" defaultValue="false" /> </properties> </profile> This Profile defines a Boolean property named AccessibleStyleSheet. Once the property is defined in the Web.Config file, you can read or set the property in any ASP.NET page, through the Profile property exposed by the Page class. For example, to set the AccessibleStyleSheet property to the value True, and display the Large Text version of the Web site, you would write the following. Profile.AccessibleStyleSheet = true The Master Page includes all of the logic for selecting the Normal Text or Large Text version of the Web site. A HyperLink control is used to enable Web site visitors to make this selection. After the HyperLink is clicked, the Page_Load event handler detects the user's selection and sets the AccessibleStyleSheet Profile property. The code here would have been simpler if a LinkButton control could have been used instead of a HyperLink control. Once again, however, the accessibility guidelines prevent us from doing this, because a LinkButton control depends on client-side JavaScript. When the Large Text version is selected, a reference to an additional style sheet is added to the page. The style sheet includes a single rule. body { font-size: x-large; } This rule sets the body font size to the value x-large. Because all of the fonts specified in the primary style sheet (contained in the SiteTheme folder) use relative sizes, modifying the font size of the body element automatically increases the font size of all elements in the Web site. Conclusion Web standards are a good thing. By following Web standards, you can make your Web sites accessible to the broadest possible audience with the least amount of work. Your Web sites will be compatible with more browsers, and they will be more likely to continue to work in the future. The ASP.NET 2.0 framework was designed to enable you to easily build Web sites that satisfy Web standards. The framework enables you to easily build XHTML Web sites. In the ASP.NET 2.0 framework, all ASP.NET controls render XHTML elements and attributes by default. Furthermore, Visual Studio 2005 and Visual Web Developer allow you to automatically validate your pages against the XHTML standards while you build them. The ASP.NET 2.0 framework also makes it easier to build Web sites that are accessible to persons with disabilities. The controls in the ASP.NET 2.0 framework include a host of new properties designed with accessibility in mind. For example, every ASP.NET control that renders an image enables you to render alternate text for the image. Furthermore, all the new navigation controls include Skip Navigation links to make it easier for persons with disabilities to navigate your Web site. About the author Stephen Walther wrote the best-selling book on ASP.NET, ASP.NET Unleashed. He was also the architect and lead developer of the ASP.NET Community Starter Kit, a sample ASP.NET application produced by Microsoft. He has provided ASP.NET training to companies across the United States, including NASA and Microsoft, through his company Superexpert.
http://msdn.microsoft.com/en-us/library/aa479043.aspx
CC-MAIN-2013-20
refinedweb
14,087
56.45
Gridview sorting and filtering In this article I'm trying to explain how to sort and filter gridview data using DataView in ASP.net. using DefaultView of DataView you can able to get the result into DataView object. Now, I tried to explain how to sort and filter data with step by step. Gridview sorting and filtering: In this article I'm trying to explain how to sort and filter gridview data using DataView in ASP.net. Now, I tried to explain how to sort and filter data with step by step. Description: DataView selectively sorting and filtering datatable data and displayed in controls. First off all DataTable data to be stored in temporary table and using DefaultView of DataView you can able to get the result into DataView object. Once you got that table information then you can able to sort and filter the data based on your requirement. Sample code to achieve your goal. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; public partial class ASPnet_GridviewSortFilter : System.Web.UI.Page { DataTable dt = new DataTable(); DataRow dr; DataRow dr1; DataRow dr2; DataRow dr3; protected void Page_Load(object sender, EventArgs e) { dt.Columns.Add("Emp_Id"); dt.Columns.Add("Ename"); dt.Columns.Add("Sal"); dr = dt.NewRow(); dr["Emp_Id"] = "1"; dr["Ename"] = "Naveen"; dr["Sal"] = "20000"; dt.Rows.Add(dr); dr1 = dt.NewRow(); dr1["Emp_Id"] = "4"; dr1["Ename"] = "Rajesh"; dr1["Sal"] = "25000"; dt.Rows.Add(dr1); dr2 = dt.NewRow(); dr2["Emp_Id"] = "3"; dr2["Ename"] = "Karthi"; dr2["Sal"] = "30000"; dt.Rows.Add(dr2); dr3 = dt.NewRow(); dr3["Emp_Id"] = "2"; dr3["Ename"] = "Pawan"; dr3["Sal"] = "10000"; dt.Rows.Add(dr3); DataView dv = dt.DefaultView; dv.Sort = "Emp_Id ASC"; dv.RowFilter = "Sal like '%0000'"; GridView1.DataSource = dv; GridView1.DataBind(); } } Using above code I just try to sort the datatable information based on Emp_Id in ascending order and filter employee details based on his Salary like above. Output: Conclusion: This articel will help you how to perform sorting and filtering DataTabel data while displayed in gridview control.
https://www.dotnetspider.com/resources/45416-Gridview-sorting-filtering.aspx
CC-MAIN-2020-05
refinedweb
348
62.04
Hello all as a Linux sort of newbie (used Unix about 10 years ago and tried SUSE 5), now using Cassandra, I decided to try and get back into C and C++. I wrote the usual Hello program in C, hello.c, then gcc hello.c. The program compiled and ran ok. I then tried C++, hello.cpp. #include <iostream> int main(void) { cout << "Hello"; cout << "\n"; return 0; } In this case, gcc hello.cpp gave the following : hello.cpp: In function ‘int main()’: hello.cpp:6: error: ‘cout’ was not declared in this scope iostream defines cout as external ostream. can anyone tell me where I have gone wrong ? I am sure it is something really basic that I should have done. TIA stuart
http://forums.linuxmint.com/viewtopic.php?f=18&t=3449&p=22985
CC-MAIN-2014-15
refinedweb
128
86.1
$ cnpm install @gsongsong like styling, and dedicated support. Other General Support Issues File format support for known spreadsheet data formats:js angular 2 / 4 / 5 / 6 and ionic knockout meteor react and react-native vue 2.x and weex XMLHttpRequest and fetch nodejs server databases and key/value stores typed arrays and math Bundlers and Tooling browserify fusebox parcel requirejs rollup systemjs typescript webpack 2.x Platforms and Integrations electron application nw.js application Chrome / Chromium extensions Adobe ExtendScript Headless Browsers canvas-datagrid Swift JSC and other engines "serverless" functions internet explorer } Since the library uses functions like Array#forEach, older browsers require shims to provide missing functions. To use the shim, add the shim before the script tag that loads xlsx.js: <!-- add the shim first --> <script type="text/javascript" src="shim.min.js"></script> <!-- after the shim is referenced, add the library --> <script type="text/javascript" src="xlsx.full.min.js"></script> The script also includes IE_LoadFile and IE_SaveFile for loading and saving files in Internet Explorer versions 6-9. The xlsx.extendscript.js script bundles the shim in a format suitable for Photoshop and other Adobe products.. The primary focus of the Community Edition is correct data interchange, focused on extracting data from any compatible data representation and exporting data in various formats suitable for any third party interface. */ readFile wraps the File logic in Photoshop and other ExtendScript targets. The specified path should be an absolute path: #include "xlsx.extendscript.js" /* Read test.xlsx from the Documents folder */ var workbook = XLSX.readFile(Folder.myDocuments + '/' + 'test.xlsx'); /* DO SOMETHING WITH workbook HERE */ The extendscript demo includes a more complex example. The table_to_book and table_to_sheet utility functions take a DOM TABLE element and iterate through the child nodes. var workbook = XLSX.utils.table_to_book(document.getElementById('tableau')); /* DO SOMETHING WITH workbook HERE */ Multiple tables on a web page can be converted to individual worksheets: /* create new workbook */ var workbook = XLSX.utils.book_new(); /* convert table 'table1' to worksheet named "Sheet1" */ var ws1 = XLSX.utils.table_to_sheet(document.getElementById('table1')); XLSX.utils.book_append_sheet(workbook, ws1, "Sheet1"); /* convert table 'table2' to worksheet named "Sheet2" */ var ws2 = XLSX.utils.table_to_sheet(document.getElementById('table2')); XLSX.utils.book_append_sheet(workbook, ws2, "Sheet2"); /* workbook now has 2 worksheets */ Alternatively, the HTML code can be extracted and parsed: var htmlstr = document.getElementById('tableau').outerHTML; var workbook = XLSX.read(htmlstr, {type:'string'}); Note: for a more complete example that works in older browsers, check the demo at. The xhr demo); The oldie demo shows an IE-compatible fallback scenario. More specialized cases, including mobile app file processing, are covered in the included demos Note that older versions of IE do not support HTML5 File API, so the Base64 mode is used for testing. On OSX you can get the Base64 encoding with: $ <target_file base64 | pbcopy On Windows XP and up you can get the Base64 encoding using certutil: > certutil -encode target_file target_file.b64 (note: You have to open the file and remove the header and footer lines) to generate file names: sheet and XLSX.utils.book_append_sheet to append the sheet to the workbook: var new_ws_name = "SheetJS"; /* make worksheet */ var ws_data = [ [ "S", "h", "e", "e", "t", "J", "S" ], [ 1 , 2 , 3 , 4 , 5 ] ]; var ws = XLSX.utils.aoa_to_sheet(ws_data); /* Add the worksheet to the workbook */ XLSX.utils.book_append_sheet(wb, ws, ws_name); The workbook object contains a SheetNames array of names and a Sheets object mapping sheet names to sheet objects. The XLSX.utils.book_new utility function creates a new workbook object: /* create a new blank workbook */ var wb = XLSX.utils.book_new(); The new workbook is blank and contains no worksheets. The write functions will error if the workbook is empty._txtgenerates UTF16 Formatted Text XLSX.utils.sheet_to_htmlgenerates HTML XLSX.utils.sheet_to_jsongenerates an array of objects XLSX.utils.sheet_to_formulaegenerates a list of formulae For writing, the first step is to generate output data. The helper functions write and writeFile will produce the data in various formats suitable for dissemination. The second step is to actual share the data with the end point. Assuming workbook is a workbook object: XLSX.writeFile uses fs.writeFileSync in server environments: if(typeof require !== 'undefined') XLSX = require('xlsx'); /* output format determined by filename */ XLSX.writeFile(workbook, 'out.xlsb'); /* at this point, out.xlsb is a file that you can distribute */ writeFile wraps the File logic in Photoshop and other ExtendScript targets. The specified path should be an absolute path: #include "xlsx.extendscript.js" /* output format determined by filename */ XLSX.writeFile(workbook, 'out.xlsx'); /* at this point, out.xlsx is a file that you can distribute */ The extendscript demo includes a more complex example.); XLSX.writeFile wraps a few techniques for triggering a file save: URLbrowser API creates an object URL for the file, which the library uses by creating a link and forcing a click. It is supported in modern browsers. msSaveBlobis an IE10+ API for triggering a file save. IE_FileSaveuses VBScript and ActiveX to write a file in IE6+ for Windows XP and Windows 7. The shim must be included in the containing HTML page. There is no standard way to determine if the actual file has been downloaded. /* output format determined by filename */ XLSX.writeFile(workbook, 'out.xlsb'); /* at this point, out.xlsb will have been downloaded */ XLSX.writeFile techniques work for most modern browsers as well as older IE. For much older browsers, there are workarounds implemented by wrapper libraries. FileSaver.js implements saveAs. Note: XLSX.writeFile will automatically call saveAs if available. /* bookType can be any supported output type */ var wopts = { bookType:'xlsx', bookSST:false, type:'array' }; var wbout = XLSX.write(workbook,wopts); /* the saveAs call downloads a file on the local machine */ saveAs(new Blob([wbout],{type:"application/octet-stream"}), "test.xlsx"); Downloadify uses a Flash SWF button to generate local files, suitable for environments where ActiveX is unavailable: Downloadify.create(id,{ /* other options are required! read the downloadify docs for more info */ filename: "test.xlsx", data: function() { return XLSX.write(wb, {bookType:"xlsx", type:'base64'}); }, append: false, dataType: 'base64' }); The oldie demo shows an IE-compatible fallback scenario. The included demos cover mobile apps and other special deployments.. XLSX.stream.to_jsonis the streaming version of XLSX.utils.sheet_to_json. var output_file_name = "out.csv"; var stream = XLSX.stream.to_csv(worksheet); stream.pipe(fs.createWriteStream(output_file_name)); /* to_json returns an object-mode stream */ var stream = XLSX.stream.to_json(worksheet, {raw:true}); /* the following stream converts JS objects to text via JSON.stringify */ var conv = new Transform({writableObjectMode:true}); conv._transform = function(obj, e, cb){ cb(null, JSON.stringify(obj) + "\n"); }; stream.pipe(conv); conv.pipe(process.stdout);. XLSX.write(wb, write_opts) attempts to write the workbook wb XLSX.writeFile(wb, filename, write_opts) attempts to write wb to filename. In browser-based environments, it will attempt to force a client-side download.. sheet_add_aoaadds an array of arrays of JS data to an existing worksheet. sheet_add_jsonadds an array of JS objects to an existing worksheet. Exporting: sheet_to_jsonconverts a worksheet object to an array of JSON objects. sheet_to_csvgenerates delimiter-separated-values output. sheet_to_txtgenerates UTF16 formatted text. objects are plain JS objects with keys and values following the convention:. The raw value is stored in the v value property, interpreted based on the t type property. This separation allows for representation of numbers as well as numeric text. There are 6 valid cell types:. The library does not correct for this error. Type s is the String type. Values are explicitly stored as text. Excel will interpret these cells as "number stored as text". Generated Excel files automatically suppress that class of error, but other formats may elicit errors. Type z represents blank stub cells. They are generated in cases where cells have no assigned value but hold comments or other metadata. They are ignored by the core library data processing utility functions. By default these cells are not generated; the parser sheetStubs option must be set to true. property.Views is an array of workbook view objects which have the keys: wb.Workbook.WBProps holds other workbook properties:: widthfield if available wpxpixel width if available wchcharacter count if available: hpxpixel height if available hptpoint height if available. Links where the target is a cell or range or defined name in the same workbook ("Internal Links") are marked with a leading hash character: ws['A2'].l = { Target:"#E2" }; /* link to cell E2 */. To mark a comment as normally hidden, set the hidden property: if(!ws.A1.c) ws.A1.c = []; ws.A1.c.push({a:"SheetJS", t:"This comment is visible"}); if(!ws.A2.c) ws.A2.c = []; ws.A2.c.hidden = true; ws.A2.c.push({a:"SheetJS", t:"This comment will be hidden"});. The workbook code name is stored in wb.Workbook.WBProps.CodeName. By default, Excel will write ThisWorkbook or a translated phrase like DieseArbeitsmappe. Worksheet and Chartsheet code names are in the worksheet properties object at wb.Workbook.Sheets[i].CodeName. Macrosheets and Dialogsheets are ignored. The readers and writers preserve the code names, but they have to be manually set when adding a VBA blob to a different workbook.. codepageis applied to BIFF2 - BIFF5 files without CodePagerecords and to CSV files without BOM in type:"binary". BIFF8 XLS always defaults to 1200. WTF:1forces those errors to be thrown. Strings can be interpreted in multiple ways. The type parameter for read tells the library how to parse the data argument::
https://developer.aliyun.com/mirror/npm/package/@gsongsong/xlsx
CC-MAIN-2020-24
refinedweb
1,556
51.34
Archived:Basic PySymbian app - series2 The first article in this series was very important because it focused mainly on how to guide your application by using a proper architecture. In that article there were the basic things to consider when building a PySymbian application. Now it is time to go more technical and learn about other important fundamentals application development. In PySymbian, a developer should always keep in mind that application s/he is designing should always exit properly when the user wants to do so. This article will help in understanding this point. A Simple Application Consider the code snippet written below: import appuifw appuifw.note(u"HI","info") When someone runs this application on a device, it simply shows a note saying HI. One important thing to notice is that the application displays the note for a few seconds, and then it vanishes automatically without user intervention. Next Important Step Now consider another important code snippet below: import appuifw,e32 def quit(): print u"exit key pressed" app_lock.signal() def main(): appuifw.note(u"HI","info") appuifw.app.title = u"Main" main() appuifw.app.exit_key_handler = quit app_lock = e32.Ao_lock() app_lock.wait() In this example, our application has Main as its title and it displays a note. One important thing to notice is that this application does not exit automatically. This application exits only when the user presses the right soft key (i.e. the exit key). Explanation Some important things about the previous code snippet: - we have used two modules: one is the e32 module and the other is the appuifw module. - We have used a function named exit_key_handler which is a member of the app object of the appuifw module. - Whatever callback function we assign to exit_key_handler is called when the right soft key is pressed. - We have used an object from the e32 module, Ao_lock. This object is mainly responsible for creating a lock for the application. - The Ao_lock object has two functions named wait and signal. - When we call the function wait, a lock is created on the application. The lock is released when the corresponding signal function is called. - So we have called the signal function in a callback function quit which the exit_key_handler function calls. - This makes our application user-controlled, which means that whenever the user presses the exit button, the application exits. Conclusion This is a very important concept one should always keep in mind when designing an application.
http://developer.nokia.com/community/wiki/Basic_PySymbian_Application:_Series2
CC-MAIN-2014-10
refinedweb
408
56.96
User:RAHB/Talk Archive) Reap From Sycamore:)— Sir Sycamore (talk) 12:38, 20 August 2008 (UTC) Hey. Just wanted to let you know that Captcha isn't letting me do Pee Reviews or Submit my articles for them. Please fix this.--The Unread 21:58, 21 August 2008 (UTC) - There's a problem with new accounts and capture or something. I've heard about it from Sannse, and some other guy had a problem with it. I can't fix it myself, but I'd ask sannse about it, since she's all "wikia staff" and stuff. -RAHB 22:10, 21 August 2008 (UTC) UnSignpost: August 21st, 2008 Just like Grandma used to make! August 21st, 2008 • Issue Sixteen • The periodical without any junk in its trunk <insert> <insert statement about how that forum topic is one of my all time favorites now> <insert statement that I'm not going to be on Uncyc as much as I want to for a little while> • <14:01, 24 Aug 2008> - <insert statement highlighting the fact that nobody cares> -- Sir Mhaille (talk to me) - <insert statement regarding Mhaille's ego, and how he considers himself to be "so big"> • <15:13, 24 Aug 2008> - <insert statement regarding P.a.n... AAAAA!!! Bu:15, Aug 24 - <insert statement inquiring if this would be a good place to whore my article? No Pun in ten did:18, Aug 24 - <insert statement regarding MrN's whoring capabilities> • <15:30, 24 Aug 2008> - <insert statement about how you're all gonna have to clean up these damn open insert tags on my talk page> -RAHB 21:44, 24 August 2008 (UTC) - </insert statement about how you're all gonna have to clean up these damn open insert tags on RAHBrN's whoring capabilities> - inquiring if this would be a good place to whore my article? No Pun in ten did you P.a.n... AAAAA!!! Bugger!> -haille's ego, and how he considers himself to be "so highlighting the fact that nobody cares> - that Cajek's not going to be on Uncyc as much as I want to for a little while></insert statement about how that forum topic is one of Cajek's all time favorites I think that's closed the lot for you, Mr Adminny RAHB type. No more broken code spilling across My image on VFP needs the help that you say it does. It's just that, well... um... I'm not so good with photoshop. Any one you would know to do some touch ups? ~ Readmesoon - Well, I could give it a shot if you'd like, but I've never been very good at manipulating text in images. You could ask about it at UN:PIC, or get some advice at Uncyclopedia:Reefer Desk. Be aware though, if you're looking for a feature on it, it would be best to ask for advice and do the touching ups yourself, otherwise the person who makes it better will probably get the credit. -RAHB 23:28, 24 August 2008 (UTC) - Well, if I knew what all of the stuff does on photoshop, I could fix it myself, but I don't know that, so if that thing gets featured I have to learn quick or get someone to touch it up. I think I will get someone out there to do something for me. Perhaps you could give me a brief on what I should do?~ Readmesoon - The first thing you should do is dump Photoshop. Maybe not, I mean a lot of the guys here seem to like it. I think Fireworks is a lot easier to use, but then again, Photoshop has a lot more "authentic" sort of effects and stuff in it. Anyways, the second thing is, just fiddle with it. That's really the only way to learn it. Just mess around with effects and see what works here and there. And if it doesn't work? Just undo it and start something else. The Reefer Desk may be able to give you more specific tips on what tools to use and all that other jazz. And quite honestly, I'm not that good of a photoshopper. I'm probably the wrong guy to ask. But The Reefer Desk is the right guy to ask. Or the right place rather. Modus responds to just about everything, and there are other shopping guys who like to comment on occasion as well, but there's some really good advice that goes on there. -RAHB 00:40, 25 August 2008 (UTC) Off? See you soon RAHB. Thanks for clearing out the crap before you left. Have a good:40, Aug 28 - Heh, thanks. And of course I had to check the QVFD one last time ;) -RAHB 08:41, 28 August 2008 (UTC)!! Where'd you go??? We miss being RAHBed on a daily basis! ...come to think of it, where'd I go? • <14:11, 09 Sep 2008> - What he said... where are ya? How's life? Updates? – Sir Skullthumper, MD (criticize • writings • SU&W) 01:33 Sep 14, 2008 - WE NEED OUR:21, Sep 17 - RAHB!!! Where'd you go? Feels like it's been forever since you've been gone. Please come back home. Not your actual home... Just any place with internet access. --00:09, 18 September 2008 (UTC) - I've told you, RAHB will be released once my demands are) Ugh, It's been an arduous process getting internet into my new apartment. I'm at my dad's house posting this message right now. I'll try to keep you guys as updated as possible. Also, woah, when the hell did you come back Skull? How is everybody, anyways? What's new in Uncyc-land that I've been missing? -RAHB 00:44, 20 September 2008 (UTC) UnSignpost: September 11th, 2008 Just like Grandma used to make! September 11th, 2008 • Nineteenth Issue • All your readers are belong to us Hea! I remember you! Welcome back. Hope all:44, Sep 20 - Unfortunately I'm not back yet =( I'm just updating some things and checking up while I'm at my dad's place. My apartment still doesn't have internet, so I'm not sure when I'm gonna really be "back." Hope it's soon though. I miss all you crazy uncyc guys. -RAHB 00:46, 20 September 2008 (UTC) - We need our daily dose of:46, Sep 20 - RRRAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHHHHHHHHHHHHBBBBB!!! That:54, Sep 20 Social gyroscope Why did you huff this page? Necessary Evil 22:42, 27 September 2008 (UTC) - Because the expand tag on it expired after a month of no edits. -RAHB 03:06, 28 September 2008 (UTC) Talk Bubble Would you mind undeleting it for me? I only put the redirect up on QVFD before Spang moved it back. Thanks. JudgeZarbi TALK 12:13, 28 September 2008 (UTC) - Ah. Thought there was something odd about the fact that it wasn't a redirect of any sort. It's back now =) -RAHB 12:19, 28 September 2008 (UTC) - Thanks a lot, RAHB =) JudgeZarbi TALK 12:21, 28 September 2008 (UTC) why did you remove my page on how to destroy a pc using DOS??? That was a very wikipedia-ish thing to do!!! If I want my shit deleted, I will go to wikipedia instead!! - I removed it because it wasn't funny. Take a look around the damn site. We don't like unfunny stuff. Wikipedia deletes things that aren't notable. They don't like unnotable stuff. There are plenty of places on the internet for you to dump whatever type of shit you like on them. Other sites have standards. This site has standards. Nowhere here does it say "we keep everything forever, no matter how stupid." Get an idea of what the site is before you start bitching about its rules. -RAHB 04:57, 29 September 2008 (UTC) - For giving me my talk bubble back, and being nice. JudgeZarbi TALK 20:10, 30 September 2008 (UTC) UnNews I've noticed that the "Featured UnNews" templates have been left unchanged for a long, long time. I'm not sure what the policy is on those, so is it cool if I start updating them? -:27, 29 September 2008 (UTC) - Yeah, I was wondering about that. Zim ulator used to do it, and then I was assigned for a while after he disappeared. With all the new admin maintenance, I've been having less time to do it, and the last month I was without internet. Seeing as you're a good, respectable user, and a prolific UnNews contributor, I have no problem with you taking over the reins. In fact, I feel rather good about it, so by all means, go on ahead. If anybody gives you any trouble about it, tell them I said it was OK. Let me know if you have any questions about it. -RAHB 22:32, 29 September 2008 (UTC) - /me polishes RAHB's shoulders...:37, Sep 29 huff Hi, sorry I wasn't careful with the double redirect bit - how does it occur or where to read about:13, 2 October 2008 (UTC) - Oh, no worries. A double redirect is when one page redirects to another page that is also a redirect. It most commonly happens when you move a page twice, which is what happened in your case. You see, when you move a page, the old page becomes a redirect to the new page. So when the new page is moved, you end up having a redirect to a redirect. It's fine though, there's a special page I go to a few times a day to look for double redirects, and I can just delete the original redirect in the click of a button. If you know of a double redirect you created, simply list it on QVFD, and somebody will come along and delete it eventually. Hope all that helps. -RAHB 07:30, 2 October 2008 (UTC) Chinese empire um how am i supposed to improve an article thats huffed? at least restore for a short while enought to dump its contents on my userpage so i can write it up later.ㄏㄨㄤㄉㄧ 03:53, 3 October 2008 (UTC) Image:King Penis.jpg I replyed my reason about Image talk:King Penis.jpg. please read and discuss, if you still hae some question. --Brandy Frisky 18:50, 3 October 2008 (UTC) UnSignpost: October 3rd, 2008 Just like Grandma used to make! October 2nd, 2008 • ALL-KITTEN ISSUE • Your #1 source for Cajek ban jokes! You're back for good! We need to do all those things we talked about back in our college days! Oh man: my brain's a-buzzin'! • <5:14, 06 Oct 2008> - Oh yes sir, man. Tomorrow and Tuesday are very busy for me, but I've got all day Wednsday and Thursday, and probably Friday to just do whatever. You can guarantee some good stuff happening. And I happen to have just picked up these SPECTACULAR audio headphones as part of my starting kit here at the school. So I'll be up to the task of all those audios. My creative energy is up in this great environment, so writing is coming back too. What should we get started on first? -RAHB 05:21, 6 October 2008 (UTC) - Start, in your userspace I guess, the "neighborhood" one! Oh man: I can't wait to see the look on the world's face when we unleash a Cajek-RAHB collab! Remember: your old neighborhood had annual animal-fucking festivals, I believe. We need to mention that somewhere in there... Oh, and Polar Express is up for some kind of "vote for highlight" or something, so if you wanted to do the audio for that, now's the time my friend! • <5:28, 06 Oct 2008> - Awesome. I'll try to fit some audio time in tomorrow if I can. And all the Old Neighborhood information can be found right here. Woo! -RAHB 05:36, 6 October 2008 (UTC) Just poppin' by! Hey RAHB, long time no see. That was my fault of course, I've just been lurking around. Anyway, I intend to write a couple articles. Would you mind helping me? You see, I want to write UnNews: There's a pimple on my ass. It's just, I have no clue how to start it. Would you help me? Th basic idea of the story would be thus: In this time of constant news, a completely uninformed journalist can find nothing better to write about than the blemish on his arse. The whole article could be about him assessing the situation. He might even request an interview with his doctor about what he thinks it is: a wart, pimple, tumor, mole, chigger, mosquito bite, or whatever. He could go into gruesome detail about its appearance. What do you think? Should I go through with it? And how should I start it? WIll someone steal my idea and beat me to the punch? Only RAHB knows. :D --Liz muffin 02:17, 8 October 2008 (UTC) - Glad to see you back thinking about writing again Liz. The premise sounds very similar to a lot of "I'm doing something normal" style UnNewses we get around here. However, I could definitely help you take it to the next level. But it'll have to be tomorrow (Wednesday, in Pacific time). But you can definitely count on my assistance. Glad to see you back =D -RAHB 02:53, 8 October 2008 (UTC) Alright, but could we make it, THIS Wednesday? I kinda spaced... oops. I'm sorry. I'll try to actually be there this time... I need to keep up with stuff better. You know what, I'll go ahead and start, and then you can just jack it up, alot. XD --Liz muffin 02:46, 15 October 2008 (UTC) You know what, suck that, I'll just wait on you for your omniscient help. Also, congrats on your article about The Polar Express. I loved it, because in my opinion, it's the worst childrens' book in the history of humanity. --Liz muffin 03:32, 15 October 2008 (UTC) - Well, the Polar Express was Cajek's article... Anyways, yes, I am here now. So...let's get started? -RAHB 19:21, 15 October 2008 (UTC) - Indeed! How would you say is a good way to start this kind of article, I've never done UnNews at all. But you would know that, wouldn't you. I mean, you've overseen me since day 3, I think. Have you any examples of a "doing something normal" article? Or is that just an insult that means this article is not worth spending time on? If that's the case, I'll just find a new concept, or go back to the grousome howto on breeding rats in your bloodstream? I always planned to do that one. Anyway, I figure I could go one way or another. Something really crazy and demented, or something that's likely to turn out stupid, and not really funny. Also, I could have sworn you at least semi-sort of co-author helped or whatever on Polar Express. Ah, well. --Liz muffin 20:48, 15 October 2008 (UTC) -Another question, how do people make these godly signatures? - Well, the concept hardly matters on an article as long as you execute it right. There are several exceptions to that rule, but that's still how I see it. It most closely reminded me of UnNews:My balls itch, a very similar concept. Whatever you feel is the right way to go with it, do it I say. That's what it's all about. As far as the Rats article, I'd be very excited to see that one. That's definitely one you should do eventually, regardless of whether this UnNews is written or not. - The Polar Express article was all Cajek, but you may be thinking of a conversation he and I were having about it a while ago where I was going to do some audio for it. I still haven't gotten around to that yet, but one of these days I plan to. As for your signature, I can help you with that too, if you'd like. Just a little fiddling with code and subpages, and a tick in the preferences area. So your call from here. Type "down" to go south. Type "up" to go north. Type "UnNews" to write an UnNews. Type "Rats" to write about rats. Type "Sig" to get a signature. Type "get" to search for treasure. Type "kill" to commit suicide. -RAHB 21:05, 15 October 2008 (UTC) - This is a toughy, but I think I'm going to have to go with... UnNews. Final Answer. Yes Regis, I FUCKING MEAN IT!!!! THIS IS MY FINAL FUCKING ANSWER!... *dammit*. After I get some positive/negative/homicidal feedback, I think I'll move on to Rats. I'm going to attempt to get a start on that today, I'll place it somewhere in my page, heck, I'll just put it right on there, no one ever does anything to anything I've done, except the bastard who stuck a lame end on my sex story, and it went something like this, "also ima girl. but don't ask you don't wanna know". *sigh* Oh, well. It'll only be there a few days, 'till I submit it. Now, I dunno much about how UnNews works, 'cept just how to submit it on the UnNews sub-site, and how to read it. If you wanna give me a clue, that'd be great. Also, if you'd like to explain how to make attractive and awesomish Signatures, in a nutshell, that's be nice. Also, oh Oz, if you could send me home, that'd be much appreciated.--Liz muffin 04:27, 17 October 2008 (UTC) - ewww! So fuglyplain. - You've just won 32,000 dollars! And you will now not leave here with any less than that. For the rats article, you know you can make userspace articles. To do that, just do User:Liz muffin/Article title, and it'll create the thing in a subpage of your own username. In userspace, you can do whatever the hell you want, so you don't have to worry about deadlines, or immediately high quality or anything. You can just build it up overtime, and it doesn't take your userpage up. Also yeah, just revert any stupid stuff people put on pages like that. I get those showing up on my watchlist a lot. Some articles more than others. UnNews basically works the same way any article does. If you know how to create it, you can copy the format and UnNews templates from any other UnNews article, and then pretty much just write it in the style of any news report, though there are any number of variations you could put on it. Also, when you create a new UnNews page with the little tool on the UnNews main page, it should come stock with some comments in the page that tell you the basic format. That's what helped me early on. That and Zim's welcome template, but he's been gone it seems. I should really start distributing that for him. That's probably why UnNews has been kind of slow lately actually. Damn...anyways, that was me rambling. You can start learning about signatures at UN:SIG, and I can help you further once you get the beginning of it all set up. In conclusion, click your heels together three times and chant "there's no place like home. There's no place like home." -RAHB 06:36, 17 October 2008 (UTC) I don't hate you And for this, you have achieved far more than any user on here in a while. Have a hippie. Ж Kalir hippies! yay! 04:30, 9 October 2008 (UTC) RAHB!!!! Thankee for the MESSAGE!!! But, mine is bigger :D. What's going on now-a-days?!) 17:27, 9 October 2008 (UTC) - Ah, no fair =( yours is green too.... What's going on? What's going on?! WHAT'S GOING ON?!! I'm at this awesome art school right now where I'm majoring in audio production, in this awesome school-sponsored luxury apartment, with awesome rommmates and awesome teachers in my courses who have won awesome awards in the field, like grammys and emmys, and in three years I'm gonna be awesome like them! That's what's going on! What about you? -RAHB 17:40, 9 October 2008 (UTC) - Yes, I win :D. That sounds...awesome! I'm happy for you! I'm uh..late for class. This message was poorly planned...I'll write again later!!) 13:13, 13 October 2008 (UTC) Unsignpost: October 10th 2008 Just like Grandma used to make! October 9th, 2008 • Twenty-First Issue • Bursting with Crunchy Goodness! Frank Zappa Is this week's colonization. Go forth my penis son! ~ 10:57, 12 October 2008 (UTC) Get writing! Let's do this... -RAHB 17:59, 12 October 2008 (UTC) Michelangelo Antonioni Why was my article on Michelangelo Antonioni deleted? For the informed reader it was funnier than a bag full of reptiles wearing pants. ~ User:NathAnonymous 7:07, 15 October 2008 (UTC) - First of all, why the hell did you post this comment halfway up my talk page? Bizarre. Second of all, it had an expand tag on it, I'm not sure if you noticed that. But the tag has long expired and it was my job to clean out the category. If you'd like it back, I can restore it to your userspace, or I can restore it to mainspace with a construction tag. It just needs to be lengthened before it can stand alone. -RAHB 00:32, 16 October 2008 (UTC) - ~ Yeah, I don't use the site enough to have known, I just went for the one that said Talk Bubble. Made sense at the time. I did not notice the Expand Tag, I only got an email today saying it had been modified & upon checking it found it deleted. A construction tag would do nicely. I'll try to find some thyme during work to whip up a nice soufflé de la funny. ~ User:NathAnonymous 7:47, 15 October 2008 (UTC) Template:countryname I am the author of Template:countryname. I have to correct some mistake of it. Please unlock it for me. I will ask you to re-lock it later. Thank You!--Hant (Talk) - For your safety, China Free! - 00:55, 16 October 2008 (UTC) - Modusoperandi have done for me. Thank You!--Hant (Talk) - For your safety, China Free! - 01:34, 16 October 2008 (UTC) sorry...new here you deleted my "apocrypha discordia"...it begins w/ "children of militant enlightenment"...i would like it back for personal reasons & it is unfinished. please. why did u delete it? can u email it back...') English bill of rights I think it was a bit shitty of you to delete my stuff on English William of Rights but I suppose that's the way Uncyclopedia works. MollyTheCat 21:02, 16 October 2008 (UTC) - What I delete is nothing personal, and it's not to be a bitch. I deleted it because there was a maintenance tag on it, and the maintenance tag expired without any edits. That's my job. It's what I do. However, if you'd like it back, I could restore it to your userspace for you. -RAHB 21:06, 16 October 2008 (UTC) - And he doesn't even get paid. Not even any medical benefits. Really, I'm the site's doctor, and all I have at my disposal is a knife, a bunch of used tubing, a rather large hammer, and several barrels of alcohol. Use your imagination. – Sir Skullthumper, MD (criticize • writings • SU&W) 21:09 Oct 16, 2008 I seek help, wise one Hey RAHB, I'm stuck. I need am being forced to want to write articles on Harpoons and Generic Kung-fu Noises, but I'm at a loss for what to say. Can you:50, 17 October 2008 (UTC) - Uh, what exactly is the idea you've got going with it? Kung-Fu parodies are always hilarious. Why don't you get a page started in your userspace and I'll help you out with what you need from there. -RAHB 22:54, 17 October 2008 (UTC) Shut-up and go to rehab! --Jim10271949 02:51, 20 October 2008 (UTC) - Believe me, I've tried. They say even the most powerful medicines in the world can't help me now. -RAHB 03:12, 20 October 2008 (UTC) UnSignpost: 21 October 2008 Just like Grandma used to make! October 16th, 2008 • Twenty-Second Issue • Now with 40% more Batman! Thoughts required So yeah, while the muse was strong with me last night, I had a vague idea, which today became this. Two quick questions: 1. Is it shit? 2. If it's not shit, as an UnTunes expert, any ideas who might be up for recording it? (In the style of Copacabana by the legend that is Barry Manilow, in case you somehow missed it). Alternatively, 2. If it is shit, what is your preferred candy:22, Oct 21 - It's a satire on people stupid enough to vote against him because of his name alone, right? I find that bit clever. The lyrics themselves could probably be spiced up a bit. As is, I can see their purpose, but they don't do well enough in making the concept flow. I wouldn't call myself an UnTunes expert, but I think it would be pretty fun to do it Copacabana style. I might give it a shot during the week, if I get the time. I suppose with a tune, there's a lot of funny that could be added in the actual execution, which is why it sounds appealing to me to make it. So yeah, I'd say give the lyrics a revise, maybe get some sort of instrumental playing in the background when you write so you can further visualize the flow of the song. Other than that, my favorite candy bar is the Nestle Crunch bar. -RAHB 16:22, 21 October 2008 (UTC) - Cool. I did have a couple of listens to the song to try and get the flow, but was at work, so was a tad tricky. May well have a stab at improving the flow shortly. And it's just a general dig at the kind of reasons that are filtering through the news over here about why people are gonna vote against him. Although that said, I think a little white-haired old granny on the news the other day came out with most of them herself. Gotta love her. Anyway, I just liked the idea of a little bigotry set to a jaunty Manilow piano number - I think you're right, the best fun would probably come from the execution. If you wanna give it a shot, go for it, if not, hey, it was fun to mess around with. Gonna shift it to the UnTunes space now. And have you ever encountered such a thing as a Twix:31, Oct 21 God, I hate you. First, you take my article on tits and you move it into my userpsace. And I'm all like, fine, RAHB. Fine. Move my article into my userspace. All that does is give it a funky new namespace. And funky namespaces make me do funky dances. We got a funky new President. With all the basketball and shit. But then you take my article on peas and you slap an OM NOM NOM NOM NOM template on it. Why, RAHB? What did I ever do to you that makes you so inclined to bend me over at the waist and assfuck me repeatedly with your seventeen inch unlubricated thumb? You make me cry, RAHB. Last week, I went to an enchanted forest, and all the tiny woodland creatures were crying, and I asked them why, and they ran away. But if they had been able to speak, they would have said "RAAAAAHHHHHBBB." Because you know all those glittery magical squirrels, RAHB? They cry for you. Well, not for you, so much as because of the fact that you're ass-raping them with your seventeen inch unlubricated thumb. RAHB, I only want the best for you. I'm hoping that one day your current girlfriend or wife moves to Bolivia and they send you a Bolivian supermodel in return. Or boyfriend, if you swing that way. The point is, I hope you're inundated with years of undeserved mind-blowing sex. Sex all the time, RAHB. I'm hoping that soon you'll barely be able to left-click without having sex with a Bolivian supermodel. So why don't you want the same things for me? Why have you got to make it your life's mission to identify whatever parade I might be in, and climb to the top of a tall building, and shit on it? Is it because I once impersonated a gorgeous redhead and asked Mordillo to ban you for your persistent vandalism to my articles? Because, if I could point out a mitigating circumstance, Mordillo didn't buy it. Also, Mordillo rejected that gorgeous redhead on account of her name, so you should probably know that she's still available. And she's just waiting for you, all spread-eagle, right now, in the magical land of DOESN'T FUCKING ADD TEMPLATES TO INEBRIATED'S ARTICLES, if you want to go there and claim her. You'll like it there, RAHB. I have full faith and credit in you, not unlike a clause. In conclusions: brb - Being that that message was absolutely hilarious, and that I have absolutely no way to continue that trend in this talk page section without looking like the less funny of the two, I'll just play it straight. Unless of course we're referring to my sexuality. I don't play straight with that. Because...you know, that's how I really am. So one hot Bolivian supermodel, yes. - Yeah, I have a confession to make. And that is, I don't look at the writers of articles before I tag them. I did however look at yours and say "hey now, from what I can see skimming over this, it might be an OK article, I don't really know, because I don't pay attention to things like that. It just needs some expansion." But hey man, I've seen your funny shine before, again and again on here, in your mysterious, slightly short ways, and how you use every square inch of text appropriately for those undertakings. If the article is complete, go ahead and take the tag off. And being that I continue not to read who the author of these articles are, feel free to do the same with any article of yours I tag in the future. And if somebody else says "WTF NOOB! U TAEK OFF TAG?!", let them know I said "Inebriated is a shining beacon of comedic prowess, and has had the right bestowed upon him to take tags off his short, stubby, hilarious articles." If you say it word for word, you get a free chocolate dipped ice cream when you buy one of equal or greater value. -RAHB 18:18, 23 October 2008 (UTC) - Thank you, anonymous spam reporter! Your efforts make the world a better place! -RAHB 19:05, 23 October 2008 (UTC) Feature Curiosity So when it comes to featuring stuff, how do you choose between two tied articles for feature? I kind of thought it was the one that was older, but am I. 20:40, 23 October 2008 (UTC) - I think I usually choose the one with higher health, myself. The old way was to choose the oldest nomination, but I think we stopped that with the whole VFH Health thing. Or maybe not. But that's what I do. I think. Whichever one comes up first when I click the score sorting button on the VFH template really. -RAHB 20:46, 23 October 2008 (UTC) Your post Nice one, I always knew there was a reason I liked you your penis. ~ 21:52, 24 October 2008 (UTC) - I think the words you used last time were "meaty" and "very well-developed", but the post is a good one too. -RAHB 22:27, 24 October 2008 (UTC) lolwhut See You see how srs biz the only editor is? Naught very srs, amirite? Also it was lolempty. — Sir Manticore 13:57, 26 October 2008 (UTC) Sainsbury's Thanks for not deleting it, something they do lots round here. Nothing like good ol' Illogicopedia!--Rabies Turtle 17:39, 27 October 2008 (UTC) Thanks for the vote From--Sycamore (Talk) 17:25, 1 November 2008 (UTC) - Word, Syc. And thank you for being an awesome Uncyc contributor. The site runs that much smoother when we've got guys like you in the shadows, doing that voodoo that you do. -RAHB 21:31, 1 November 2008 (UTC) Can I Block this Jackass IP -------->86.29.240.79 He was Vandiliziling other pages and removing content from the wiki. I gave him a damn warning, but this dickhead won't stop. NOW HE'S REALLY STARTING TO PISS ME OFF!! But I really don't know how to ban this asshole....can you tell me how? If not, than does an administrator have to????? I don't Know! SOME ONE TELL ME!!!!--BlackSugaBabyGurl 22:52, 1 November 2008 (UTC) Star Wars: TFU So can I move it back out if I take the construction tag off? I'm done with it. I also wanted to know how you did that. Like, how do you move a page into your userspace? --GDawg816 18:13, 3 November 2008 (UTC) - Oh, no problem. Yeah, if it's finished, just go ahead and move it out. I just always move them to userspace because they show up on a maintenance list, and I don't want works in progress to be deleted. There's a button at the top of every page, called "move." Clicking that takes you to a page where you retitle the page you are moving. So, to move things to userspace, you add the "username/" prefix. For you to move it back to main, all you have to do is remove said prefix, and it will be back where it was before. Hope that helps, and happy uncyc-ing! -RAHB 05:14, 4 November 2008 (UTC) - So do I put my username (GDawg816) or just /username? --GDawg816 18:52, 4 November 2008 (UTC) - To move something to userspace, it's GDawg816/articlename. To move it to mainspace, it's just the article name. -RAHB 08:52, 5 November 2008 (UTC):10, Nov 6 SPERM GEYSERS yeah... um I wrote an article and it's actully good this time, I think. So since you like adopted me and shtuff you should read it and then chastize complement me. So yeah thanks ---) - Oh absolutely. I'll give it a look, what's it called? -RAHB 06:54, 7 November 2008 (UTC) - That's strange I thought I linked it... oh whatever. Aha ha---) IRC I'm not sure if IRC is broken, maybe, but it keeps telling me that I'm apparently banned from the #uncyclopedia channel. I don't remember getting banned in the first place, so yeah. I'm confused. -:59, 12 November 2008 (UTC) - I'm equally confused. Nobody in IRC will tell me what's up. But apparently something fucked up in the ban log, I think. Working on fixing it hopefully. -RAHB 22:01, 12 November 2008 (UTC) Cleveland Steamers Hey! I wrote the article for this, and you recently put it in the ICU (I'm guessing because it was rather short at the time). I lengthened it to a point where I think its okay, and the parts that I think are just kind of "eh" I plan on working on the next few days (while adding stuff). I was wondering if you could look at it and maybe take it off? Or if theres something wrong with the quality, let me know whats wrong? Anyways... I thought I'd get to you on that, thanks :-) - Prof. Ahh(to the)Diddums[FUCK-A-DOODLE-DOO!] 04:25, 13 November 2008 (UTC) - Oh yeah, looks a little more fleshed out to me. But if you are still working on it, I recommend putting a construction tag on it, to let people know it's still in progress. Otherwise, it's still a little short, I would normally put an expand tag on it. I guess I'll leave that bit up to you, but I'll remove the ICU for now. Thanks for getting to me on it. -RAHB 04:44, 13 November 2008 (UTC) EUREKA!! So, once again, I wandered away from the Uncyclopedians for a while, but never fear I will be back, just as I always will. I waited a month and twiddled my thumbs over the computer until, as they say on 4chan, "I CHARGED MY LAZERS! BWWAAAAAAAAAAAAAAAAAAH!" and finally, God has blessed me with a gift. Not just A gift, really, but THE gift. Yes, the gift of the intro to INJECTING RATS INTO YOUR BLOODSTREAM!!!! You can check out my progress over the next couple of days right in User:Liz_muffin/The_Workshop -- I think. It should only be a few days until something good happens :D Wish me luck! --Liz muffin 05:23, 13 November 2008 (UTC) - Heh, I kind of figured this was coming, I saw you pop up on my watchlist. Well, it's good to see you're writing it, and you bet I'll be watching in the coming days. If you need any writing advice, you know where to come =D -RAHB 05:31, 13 November 2008 (UTC) - Okay, I'm officially out of juice, can you help? What should be the next step?--Liz muffin 14:37, 18 November 2008 (UTC) UnSignpost: 13th November 2008 Just like Grandma used to make! November 13th, 2008 • Issue 24 • So close to journalism you'll be hard pushed to know the difference! MrN9001 12:52, 13 November 2008 (UTC) Stella Artois I have reviewed the begginers guide and still don't understand why my article has been deleted. Stella Artois is europe's most popular beer, I think it deserves an article plus it was fucking hilarious (not if you're american though... you probably wouldn't get it). Is there any way of recovering what was deleted? --Baina 18:30, 13 November 2008 (UTC) - Well, from what I remember, the main reason I deleted it was it sounded like any generic article we get about anything around here. The main point of your article was that "Stella Artois sucks", for the most part, and as far as anyone is concerned, it sounds more like a grudge or just some guy bitching about how a beer sucks. Same thing happens with schools and cities very often, so I usually just get rid of the articles. But if you'd like to work on it further, I can restore it for you with a construction tag and let you have another shot at it. Let me know. -RAHB 21:20, 13 November 2008 (UTC) Ok, I agree with what you say about how the article was written, but It still needs an article. If you can restore it with the construction tag, I'll re-write it. Let me know on my talk page when it is back up. Thanks.--Baina 19:06, 15 November 2008 (UTC) UnSignpost: 20th November2008 Just like Grandma used to make! November 20th, 2008 • #100/4 • Sucking Journalism's Fat Wang. Badly. Turkey Talk So, RAHB, in my guise as fearless, penetrative reporter for that mighty organ The UnSignpost, I'm thinking of including an article about the Aristocrat's Turkey Day Ball '08. As one of the perpetrators of said event, can I ask you: - Do you have any comments that I can take out of context for comedic effectfor our devoted readership? - Or, if you prefer, do you want to write said article, to avoid me taking massive editorial liberties with the entire thingany chance of error creeping in to our completely unbiased journalism? - If I think of a third question, would you answer it? Pipp:57, Nov 24 - Yes, yes, and yes. When is the new signpost to be delivered? -RAHB 16:36, 24 November 2008 (UTC) - I aim for some point during th 24 "The 3-person judging panel shall individually score each entry using a specified 1-to-10 scoring template not unlike the one used for Pee Review. The elements in question shall include..." - I don't know if it helps, but I've never done it like that. Also, I'm an insufferable old coot. Sir Modusoperandi Boinc! 00:56, 26 November 2008 (UTC) - Well, are you opposed ethically to it or something, or are you just looking to familiarize yourself with it? You've judged a lot of things before, so I don't really have a problem with you doing it whatever way you feel most comfortable with. But if you're curious, the template that's suggested to be used can be found here. Ya damn old geezer. -RAHB 01:00, 26 November 2008 (UTC) - The Pee Review template took all the fun out of peeing for me. This does the same for judging, as I'm a wrath-filled and zealous judge. Rawr! Or, to put it another way: I read all the pages, then read them again, and again, and again. Eventually, they sort themselves into order. It's really quite magical, like unicorns ordering themselves by adorability. Sir Modusoperandi Boinc! 01:30, 26 November 2008 (UTC) - That's fascinating. -RAHB 01:36, 26 November 2008 (UTC) - I know. My memoires are riddled with mind expanding shit like that. Sir Modusoperandi Boinc! 01:44, 26 November 2008 (UTC) - So... It being thursday, any sign of said article, or do I just make something:59, Nov 27 - I've been so damn busy. Sorry I didn't get back to you on that, but if you could improv up a little piece, that'd be much appreciated. If you need any quotes to mangle into pseudo-biased semi-truths, I'll gladly give some up for your editing machines. -RAHB 09:08, 27 November 2008 (UTC) - Fair enough. While I do so, can you drop the banstick on Assss (Talk • Contribs (del) • Editcount • Block (rem-lst-all) • Logs • Groups) please?:11, Nov 27 Whoo! - 01:12, 26 November 2008 (UTC) Thanks for the welcome but... Is my sig that bothersome?--Metalhead94 T C - It's not as much that your sig in particular bothers me in particular. It's that signatures more than fifteen pixels high mess with page formatting, and do bother some users. The uncyc policy is that signatures shouldn't be higher than fifteen pixels, for the sake of civility amongst users in the long run. It's nothing personal, just a policy. -RAHB 01:24, 26 November 2008 (UTC) - Yeah, I get it.--Metalhead94 T C Is this better?--Metalhead94 T C - Still looks a little big. I'd really just stay away from changing font sizes in your sig, I think the default is 15 (though I could be wrong about that). Also, if you'd like an easier way to sign pages, you can create User:Metalhead94/sig and paste your sig code in it, then go to your preferences and paste "{{User:Metalhead94/sig}}" into the signature box, without the quotes, then check the raw signature box. Then all you have to do to sign pages is put -~~~~ and it'll paste your code and a timestamp every time. -RAHB 01:34, 26 November 2008 (UTC) Camred333 Dude why did you delete my article its protected by the ignorable policy wtf cmon! —The preceding unsigned comment was added by Camred333 (talk • contribs) - 1. New stuff on bottom, as it says up there at the top. 2. The title of the article, or a link to where it was would probably help - admins delete a lot of stuff, it's not personal, so they don't remember every deletion off the top of their heads. 3. Which "ignorable" policy would that be? 4. Who changed the channel? I was watching, Nov 26 - I deleted your article because it was a shitty stub about some teacher or something, from what I can tell. We don't allow vanity articles here, and hence I mercilessly huffed it. AND I'D DO IT AGAIN TOO! And God dammit, UU! We SHARE the remote! I've told you a million times, that TV does not belong to you! -RAHB 23:11, 26 November 2008 (UTC) Why Did You Huff My Article? Hello, sorry to bother you, but I'd like to know why you huffed my article. The only reason I can currently think of is the repetition which was in the beginning. I've already read the n00b article, so I don't need to be linked to it. Reply when you get a chance to do so. -- User:Hroþgard 7:50 AM, 2 November 2008 (GMT-8) - It seems I deleted your article because it looked like a lot of gibberish to me. But, since you were so civil about the situation, unlike many of the complaints I get around here, I have no problem restoring it for you if you'd like. Of course, it is a little sloppy, formatting wise, so I'd suggest putting a construction tag on it. Let me know what you think. -RAHB 23:22, 26 November 2008 (UTC) - I would like for you to bring it back. The Rotokas language is, in fact a real language, however, it's spoken by humans (obviously) and it's spoken on some Pacific island somewhere. Most people don't know of it's existence. I'll add the construction template onto it. Also, what noticable formatting problems were there? I'd repair them if I knew what they were. Why are you being of delete article? Halo, my article is great. Your face is not great. In fact, it is very bad. And for deleting mine article, your face is of being very VERY bad. Please say word so I can spit. Your face. I want answer. sir sysrq @ 20:54 Nov 26 - Banned -RAHB 23:23, 26 November 2008 (UTC) No seriously, you suck Yu get so meny msgs, can only meanz you be shitty adminz. fuck off noob. ktxbi. overlordofyourpenis666 You suk bad vandil! Yo ar teh worst vandol I's evar seen why you delet my pages I'm write good bobby says its funy why you delet my pages you suck and shud dy! Just hopping on the bandwagon 21:37, 26 November 2008 (UTC) deletion? hay wher ddi my page on poop sex go????? is was good poop sex page!!! why u so mean 2 me????? --epoirubn penis face thats wut u r, cuz u suk so much dikkKK!~!!!! yea!!!11 stop huffin mah shit!!! stigmatizedvampireguuuurrrllll On a serious note Griebel Stomp just kicked my ass. =D sir sysrq @ 23:44 Nov 26 - Gasp! U heerz mah musak?! OMG! Aye Roxxorz, dont I?!! -RAHB 23:47, 26 November 2008 (UTC) - Seriously though, many thanks. I appreciate it. -RAHB 23:47, 26 November 2008 (UTC) - But I still rock too. -RAHB 23:47, 26 November 2008 (UTC) - Shut up. No you don't -RAHB 23:47, 26 November 2008 (UTC) - Who asked you, anyway? -RAHB 23:47, 26 November 2008 (UTC) - Yeah. I was going to go vandalize your page and I found a link to your musicks. I listened, I rocked out, I cocked out. I added you on Last.fm. (go look up my artist page on Last.fm plz haha) Oh shit, I forgot to finish vandalizing your userpage. Be right back. sir sysrq @ 23:52 Nov 26 - Sweet, I'll take a look/listen. I've been meaning to actually get something put on Last.fm, but I keep slacking off on that. Anyways, if you're interested, I have more music here. And now that I think of it, I should add that to my external links on my user page. And now I'll listen to your stuff. -RAHB 00:00, 27 November 2008 (UTC) - I shall indeed listen. Looks like my cock and I are gonna do some more rockin. Out. sir sysrq @ 00:14 Nov 27 - (FU Edit Conflict!) Every Light In This World is one of the most beautiful things I've ever heard. If you don't get into audio for a career, I will find you and suck the talent you have out of your brain and use it for my own purposes. -RAHB 00:15, 27 November 2008 (UTC) - Wow, really? And yeah, everyone likes that song, including me. I've got a TON of new songs in the works that haven't been mastered but are pretty much finished; those will be going up soon. Thanks for listening. Also, do this, Mr. Admin. EDIT: My audition for getting into the school of music at Baylor University is on January 24th. So yes, I'm pursuing audio as a career. (Composition, specifically.) sir sysrq @ 00:41 Nov 27 - (FU another edit conflit) Oh yeah. I mean, I have a particular soft spot for ambient music, something about the way it can integrate so well in with real life functions. Like, I can be sitting here listening to a rock group, and it'll be cool because I like the song or whatever, but it doesn't mesh with my surroundings (which coincidentally are often dark and somber, for whatever reason) as well as ambient stuff. Yours is produced unbelievably well for someone who's been at it for such a short amount of time. And you've got the ability in these songs to make them emotionally touching. That's one of two areas I strive for in my own music, though I've never actually touched upon. As you can probably tell from my stuff, the redeeming quality is mostly in the fact that everything is weird and undefinable, and not that it's particularly sonically comforting. And yours I find to be very sonically beautiful, even though I know there are other artists who make similar stuff. I also get exposed to the genre a lot, living here in the heart of LA, and going to an art school with plenty other aspiring creative people. One of my greatest life ambitions is to be able to combine those two attributes, the innovative and strange song structure I take so much pride in with my own music, and the sonic perfection that I find in so much of your stuff. I think anyone who can accomplish both simultaneously is instantly one of the greatest musical geniuses there is. -RAHB 00:57, 27 November 2008 (UTC) - Also, admin work...grumble grumble... -RAHB 00:57, 27 November 2008 (UTC) - Yeah, I totally see what you're saying there. I think I try to go for both of those aspects as well, at least I have been moreso in my recent music. The exception would be Resolute, an older song I wrote to help me understand 5/4 time better. But I love the effects and stuff you use in your music, and I've been trying to use more of that in my recent work. I'm off to play my tuba for an hour or so, but I'll check out the rest of your music later tonight. musicalcollabmaybe? Ahem. Excuse me. sir sysrq @ 01:07 Nov 27 - Yeah, I've noticed a good deal of innovative sound in some of these tracks, right now I'm on Interstate, which I definitely like the introduction to so far. I'm baffled by how professional this stuff sounds, I feel like I purchased this record in the store and played it right from the CD. Production quality is another one of those things I'm working on, which I'd say I'm definitely getting better at lately, though I need to begin testing the waters again with some new tracks. And I do love a good collaboration. A fusing of our two styles could be quite the interesting project. Consider me intrigued. -RAHB 01:14, 27 November 2008 (UTC) UnSignpost: 27th November2008 Just like Grandma used to make! November 27th • Issue 26 • The newspaper it's tough to swat flies with W♥v Metallic (band) Heheheheh, told the user who originally created that it'd get huffed. He originally had it tacked onto a redirect page, so I moved it to where it was after consultation with Codeine. Nice to see my prophecies come to be. :-) RabbiTechno 20:39, 30 November 2008 (UTC) WTF why did u delete my Krokodile Shears page? Sure it was a work in progress, but it had some potential. A fictional band page could not be as bad as some of the other crap I see in this site. - Ah, we had a huge deal and subsequent mess with a fictional band a while ago. Other than that, the point isn't there. There's no satire, or jokes we as readers can relate to. If you can make a good satirical article out of it, then it can probably stay. Just try not to make it sound like it's about some high school band that you and your friends made. -RAHB 04:02, 1 December 2008 (UTC) - Hang on a second, I remember you. You were posting links to your "Krokodile Shears" page all over other pages, including to YouTube. Vanity is not appreciated. You'd be better off making fun of something real, I think. (Most articles on "fake" things have too much difficulty resonating with:19, 1 December 2008 (UTC) No, that youtube stuff was from my account getting hacked. I looked like a jackass apologizing for all of that stuff. I had no idea that Krokodile Shears was a real thing. Reform I am now a reformed vandal. I am sorry for my destructive edits, and I will try to help out in the future. 68.32.189.242 05:09, 3 December 2008 (UTC) - Very good to hear. Feel free to register for an account if you feel so inclined. No prejudice here on Mars. -RAHB 06:56, 3 December 2008 (UTC) Any chance of me being be in VFS? What are the chances of having me being nominated for VFS and being accepted as admin? 1 in 100,000? 1 in a million?:03, 3 December 2008 (UTC) - A) Trying to calculate your chances with a calculator would return an error/electrical failure (nothing personal). B) From the admin vote so far, it doesn't look like we're going to be nominating anyone new this month anyways.
http://uncyclopedia.wikia.com/wiki/User:RAHB/Talk_Archive_7
CC-MAIN-2015-06
refinedweb
9,278
82.85
java.lang.Object org.netlib.lapack.SSBEVXorg.netlib.lapack.SSBEVX public class SSBEVX SSBEVX is a simplified interface to the JLAPACK routine ssbev * ======= * * SSBEVX computes selected eigenvalues and, optionally, eigenvectors * of a real symmetric band matrix A. Eigenvalues and eigenvectors can * be selected by specifying either a range of values or a range of * indices for the desired eigenvalues. * *. * *. * * Q (output) REAL array, dimension (LDQ, N) * If JOBZ = 'V', the N-by-N orthogonal matrix used in the * reduction to tridiagonal form. * If JOBZ = 'N', the array Q is not referenced. * * LDQ (input) INTEGER * The leading dimension of the array Q. If JOBZ = 'V', then * LDQ >= max(1,N). * * VL (input) REAL * VU (input) REAL * If RANGE='V', the lower and upper bounds of the interval to * be searched for eigenvalues.) an eigenvector fails to converge, then that column of Z * contains the latest approximation to the eigenvector, and the * index of the eigenvector is returned in IFAIL. * (input) INTEGER * The leading dimension of the array Z. LDZ >= 1, and if * JOBZ = 'V', LDZ >= max(1,N). * * WORK (workspace) REAL array, dimension (7. * * ===================================================================== * * .. Parameters .. public SSBEVX() public static void SSBEVX(java.lang.String jobz, java.lang.String range, java.lang.String uplo, int n, int kd, float[][] ab, float[][] q, float vl, float vu, int il, int iu, float abstol, intW m, float[] w, float[][] z, float[] work, int[] iwork, int[] ifail, intW info)
http://icl.cs.utk.edu/projectsfiles/f2j/javadoc/org/netlib/lapack/SSBEVX.html
CC-MAIN-2016-40
refinedweb
234
57.16
Bug #7437 Array#delete(obj) should return obj when there is an object that is equal in the array Description According to, Array#delete(obj) should return "obj" when there are objects in the array that are "equal to obj" (internally, "==" is used, it seems). Notice that the documentation does not state that the return value is an element of the array itself. However, 1.9.3 and trunk both return a member of the Array, rather than the argument. This issue was raised in #!/usr/bin/env ruby class Foo attr_reader :name, :age def initialize name, age @name = name @age = age end def == other other.name == name end end foo1 = Foo.new "John Shahid", 27 foo2 = Foo.new "John Shahid", 28 array = [foo1] temp = array.delete foo2 # => foo1, not foo2 Associated revisions History #1 Updated by Hiro Asari over 2 years ago - File ruby-7437.patch added Here's the patch. Where should the tests go? RubySpec? #2 Updated by Marc-Andre Lafortune over 2 years ago - Category set to core - Target version set to 2.0.0: diff --git a/array.c b/array.c index df0a0a4..481eebc 100644 --- a/array.c +++ b/array.c @@ -2605,12 +2605,12 @@ rb_ary_keep_if(VALUE ary) /* * call-seq: - * ary.delete(obj) -> obj or nil - * ary.delete(obj) { block } -> obj or nil + * ary.delete(obj) -> element or nil + * ary.delete(obj) { block } -> element or result of block * * Deletes all items from +self+ that are equal to +obj+. * - * If any items are found, returns +obj+, otherwise +nil+ is returned instead. + * Returns the last deleted item, or +nil+ if no matching item is found. * * If the optional code block is given, the result of the block is returned if * the item is not found. (To remove +nil+ elements and get an informative diff --git a/test/ruby/test_array.rb b/test/ruby/test_array.rb index 8d264d9..6466fc3 100644 --- a/test/ruby/test_array.rb +++ b/test/ruby/test_array.rb @@ -598,6 +598,14 @@ class TestArray < Test::Unit::TestCase a = @cls[('cab'..'cat').to_a] assert_equal(99, a.delete('cup') { 99 } ) assert_equal(@cls[('cab'..'cat').to_a], a) + + o = Object.new + def o.==(other); true; end + o2 = Object.new + def o2.==(other); true; end + a = @cls[1, o, o2, 2] + assert_equal(o2, a.delete(42)) + assert_equal([1, 2], a) end def test_delete_at #3 Updated by Yusuke Endoh over 2 years ago - Status changed from Open to Assigned - Assignee set to Marc-Andre Lafortune #4 Updated by Charles Nutter over 2 years ago marcandre (Marc-Andre Lafortune) wrote:: Yes, it appears to have been an explicit behavioral change in the 1.9.1/1.8.7 timeframe that never got reflected in documentation. #5 Updated by Marc-Andre Lafortune over 2 years ago - Status changed from Assigned to Closed Documentation fixed, thanks for bringing this up. Also available in: Atom PDF
https://bugs.ruby-lang.org/issues/7437
CC-MAIN-2015-27
refinedweb
471
69.68
State Management in Corvid State Management in Corvid In this article, we discuss how we can use Redux and MobX with Corvid to better manage the state of components within the frontend of an application. Join the DZone community and get the full member experience.Join For Free When using Wix, when working with Corvid you don’t need to deal with HTML/CSS when developing UI. Instead, you get a full-blown WYSIWYG editor, where you can create the UI for your application. Then, all that’s left to do is write the application logic, which is really what we want to focus on when developing applications. Most examples you’ll see today that connect application logic to the view are similar to old-style jQuery applications. You bind an event handler to UI elements, and in response to those events, you run some logic that updates other UI elements with the result. You may also like: Build, Manage, Deploy, and Scale Your Next Web Project With Corvid. jQuery Style Let’s look at an example. Say you have a view with a text element ( #counter), which displays a counter and two button elements ( #increment and #decrement) that increment or decrement that counter. The Corvid code which implements that logic will be something like: let counter = 0; $w.onReady(function() { $w('#counter').text = `${counter}`; $w('#increment').onClick(function() { counter++; $w('#counter').text = `${counter}`; }); $w('#decrement').onClick(function() { counter--; $w('#counter').text = `${counter}`; }); }); This is a coding style that professional frontend developers cringe, since it reminds them of the old jQuery days when we explicitly updated the UI with the effect of each interaction. In order to understand why this is a bad pattern, let’s try to complicate the example a bit. Let’s say we also have another text element ( #counter2) with its own increment/decrement buttons. This time, we will also use the opportunity to do a small refactor. The logic implementation for this will be something like: let counter = 0, counter2 = 0; function renderCounter() { $w('#counter').text = `${counter}`; } function renderCounter2() { $w('#counter2').text = `${counter2}`; } $w.onReady(function() { renderCounter(); renderCounter2(); $w('#increment').onClick(function() { counter++; renderCounter(); }); $w('#decrement').onClick(function() { counter--; renderCounter(); }); $w('#increment2').onClick(function() { counter2++; renderCounter2(); }); $w('#decrement2').onClick(function() { counter2--; renderCounter2(); }); }); As you can see, in this pattern, after we update some state ( counter/ counter2), and then we go and update the relevant UI component(s) that should be affected by that state change. So, if for example, we add an additional text item calculating the sum of the two counters, we update it in all places: let counter = 0, counter2 = 0; function renderCounter() { $w('#counter').text = `${counter}`; } function renderCounter2() { $w('#counter2').text = `${counter2}`; } function renderSum() { $w('#sum').text = `${counter + counter2}`; } $w.onReady(function() { renderCounter(); renderCounter2(); renderSum(); $w('#increment').onClick(function() { counter++; renderCounter(); renderSum(); }); $w('#decrement').onClick(function() { counter--; renderCounter(); renderSum(); }); $w('#increment2').onClick(function() { counter2++; renderCounter2(); }); $w('#decrement2').onClick(function() { counter2--; renderCounter2(); renderSum(); }); }); Whoops! Did you see the bug? I forgot to call renderSum() when #increment2 was clicked. Well, this is what happens when you wire UI and state manually. This only gets worse as the application gets more complicated and as the behavior of the application change as you add more features. See for example this todo list application, written in Corvid using the jQuery pattern:. We have two bugs there: - If you check the checkbox next to the todo item that marks it as done, the todo description gets strikethrough decoration, which is the expected behavior. But if you check the top checkbox that marks all todo items as done, we forgot to update the todo item description with the strikethrough. - If you check the checkbox next to the todo item which marks it as done, the “items left” counter at the left bottom is updated with the number of remaining items. But, if we delete an uncompleted todo item using the delete button, we forget to update the “items left” counter. Those are annoying and hard to catch bugs. Every jQuery application was full of them, and it made maintaining the code base of jQuery applications complete hell. You can also play with the real app. Just open the corvid-jquery example in the Wix editor (turn on dev mode from the top menu in order to see the code). And Then Came Data Binding Data binding is a pretty neat concept where you no longer need to explicitly update the UI when the state changes. Instead, you define what piece of state goes in each UI element using some framework. Then, when you update the state in that framework, it automatically updates the UI with the relevant changes. Since the framework knows what UI element needs what piece of state, it can make sure to update only the UI elements that care about the part of state that was updated. So what are those framework? Actually there are tons of them. The first widely used framework was actually Angular, but Angular was much more than just a data binding or state management framework. It was coupled with many more concerns, most importantly with how the UI is rendered, which is obviously a problem for us, since we want to render the UI with Corvid. But then something nice happened. React came out and put on its flag to only be opinionated about how UI is rendered; the rest was open for extensibility. Soon, a new generation of state management frameworks appeared, which only gave you a method to manage your state and only needed small adapters to bind the state into the React-based application view. Later versions of Angular also allowed users to easily use such state management instead of the built-in state management that came with Angular. This was great since essentially, you can write almost all of your application logic without really caring what framework you would use for rendering the UI. It means that if you used such a state management framework, you could pretty easily move your application logic from React to Angular or even some other future framework that might come out (like Corvid!), and the only thing that would change is the wiring of the state to the UI. In this article, we will look into my two favorite state management frameworks (Redux and MobX) and see how you can easily connect them to a Corvid application. This also means you can easily take any Redux or MobX-based application and migrate it from React to Corvid! In order to use Redux and MobX, you’ll need to install these external libraries and an additional library called corvid-redux in your Corvid application. Redux In Redux, the main concept is that your state is managed by a reducer and updated by dispatching actions. Basically, that means that every time you want to update the state, you dispatch an action with the needed update. Then, the reducer (which is basically just a function with two arguments) is called with the current state, and the action and is supposed to return the new state. It sounds complicated, but it is really simple. Let’s see the counter example: import { createStore } from 'redux'; const initialState = { counter: 0 }; function reducer(state = initialState, action) { switch (action.type) { case 'INCREMENT': return { counter: state.counter + 1 }; case 'DECREMENT': return { counter: state.counter - 1 }; default: return state; } } const store = createStore(reducer); $w.onReady(function() { store.subscribe(() => $w('#counter').text = `${store.getState().counter}`); $w('#increment').onClick(() => store.dispatch({ type: 'INCREMENT'})); $w('#decrement').onClick(() => store.dispatch({ type: 'DECREMENT'})); }); All that changed here is that instead of incrementing or decrementing the counter ourselves when the buttons are clicked, we dispatch an INCREMENT or DECREMENT action. Redux will then call the reducer with the current state, and the dispatched action and the reducer will return the new state with the incremented or decremented counter according to what action was processed. The most interesting line to focus on now is: store.subscribe(() => $w('#counter').text = `${store.getState().counter}`); In this, we subscribe to changes on the store, and when the state updates, Redux will call our callback, and we will have the opportunity to update the view with the new state. This is nice, but it is not granular enough. Currently, we have just one counter, but in the example before, we had two counters and a sum that will look more like this: import { createStore } from ); $w.onReady(function() { store.subscribe(() => { $w('#counter').text = `${store.getState().counter}`; $w('#counter2').text = `${store.getState().counter2}`; $w('#sum').text = `${store.getState().counter + store.getState().counter2}`; }); $w('#increment').onClick(() => store.dispatch({ type: 'INCREMENT'})); $w('#decrement').onClick(() => store.dispatch({ type: 'DECREMENT'})); $w('#increment2').onClick(() => store.dispatch({ type: 'INCREMENT2'})); $w('#decrement2').onClick(() => store.dispatch({ type: 'DECREMENT2'})); }); Basically, in the subscribe callback, we update all of the UI elements with the new state. This is not very efficient since there is no reason to update the first counter if the second counter is the one that was incremented. For this, we have to add the corvid-redux binding, which ensures just that by making the data bindings more declarative: import { createStore } from 'redux'; import { createConnect } from 'corvid); const {connect, pageConnect} = createConnect(store); pageConnect(() => { connect(state => ({ text: `${state.counter}` }))($w('#counter')); connect(state => ({ text: `${state.counter2}` }))($w('#counter2')); connect(state => ({ text: `${state.counter + state.counter2}` }))($w('#sum')); $w('#increment').onClick(() => store.dispatch({ type: 'INCREMENT'})); $w('#decrement').onClick(() => store.dispatch({ type: 'DECREMENT'})); $w('#increment2').onClick(() => store.dispatch({ type: 'INCREMENT2'})); $w('#decrement2').onClick(() => store.dispatch({ type: 'DECREMENT2'})); }); What we basically say here is that we bind the text property of the respective UI element with the value of the counter/sum. Now, instead of updating all of the UI on state update, the UI will be updated only if the bound value is changed. In order to make this work, all we need to do is use the createConnect method from corvid-redux, which gives us two helpers: pageConnect, which is basically a small wrapper on top of $w.onReady, which we used up until now, and connect, which we use to bind to element properties. Pretty simple, right? Let’s complicate it a bit. Let’s make a simplified todo list. Now, we have a text input ( #input) and an add button ( #add), and we have a repeater ( #repeater), which will display the items that we added. For each item in the repeater, we’ll have a text element displaying the description ( #description) and a delete button to remove it from the list ( #remove). This will look something like this: import { createStore } from 'redux'; import { createConnect } from 'corvid-redux'; let nextId = 0; const initialState = [ { _id: `${++nextId}`, description: 'Task 1' }, { _id: `${++nextId}`, description: 'Task 2' }, { _id: `${++nextId}`, description: 'Task 3' } ]; function reducer(state = initialState, action) { switch (action.type) { case 'ADD_TODO': return [...state, {_id: action.id, description: action.description}]; case 'REMOVE_TODO': return state.filter(todo => todo._id !== action.id); default: return state; } } const store = createStore(reducer); const {connect, pageConnect, repeaterConnect} = createConnect(store); pageConnect(() => { connect(state => ({data: state}))($w('#repeater')); $w('#add').onClick(() => { store.dispatch({type: 'ADD_TODO', id: `${++nextId}`, description: $w('#input').value}); $w('#input').value = ''; }); repeaterConnect($w('#repeater'), ($item, _id) => { connect(state => ({text: state.find(todo => todo._id === _id).description}))($item('#description')); $item('#remove').onClick(() => store.dispatch({type: 'REMOVE_TODO', id: _id})); }); }); Now, this is interesting. Here, we bind an array to the data property of the repeater element ( #repeater). As you can see, the initial state of that array has three todo items; each item has an _id property and a description property. The _id is a unique identifier mandatory for any repeater item, as described in .. The second interesting thing here is repeaterConnect, which we use in order to bind elements inside the repeater to our state. repeaterConnect gets two parameters: the repeater element we want to bind into and a callback. This callback is called for each new item in the repeater (including the initial three items of course) in order to allow it to bind the internal elements of this repeater item to the state. You don’t need to worry about unbinding when items are removed since corvid-redux takes care of that automatically. As you can see, the callback simply receives the $item selector function, which you can use to select internal elements of the item and the _id, which you can use to access the appropriate item in the state. Binding inside repeaterConnect is done using connect, exactly as you would have performed binding outside a repeater. Note that, as always with Redux, we must remember that state is immutable, which means we are not allowed to save references to an item inside the array since that reference will never contain later changes to the state. Instead, we must find the correct item in the array inside the connect callback like so: connect(state => ({ text: state.find(todo => todo._id === _id).description })) ($item('#description')); Since usually we will have multiple such connect calls inside a repeaterConnect probably we can do a small refactor and extract the find part to a function and then the connect part will be somewhat shorter: const find = state => state.find(todo => todo._id === _id); connect(state => ({ text: find(state).description}))($item('#description')) const find = state => state.find(todo => todo._id === _id); connect(state => ({ text: find(state).description })) ($item('#description')); In general, as we learned here, keeping all logic of the state far away from the binding code is always good practice since it allows you to replace view frameworks in the future with small changes to your logic code. I highly recommend reading Redux docs about derived data in order to learn more patterns regarding how to extract data from state. This is actually all we need to know in order to use Redux in Corvid. There are many interesting things to learn about Redux, such as how to add middleware to your store and how to handle asynchronous operations, but the nice thing is that it is all just Redux and isn’t specific to the view technology you use, which in our case just happens to be Corvid. You can read all about those in the Redux docs about advanced topics and try to apply them in your Corvid application. For a live example of a more complicated todo list open the corvid-redux example in the Wix editor (turn on dev mode from the top menu in order to see the code). MobX To be honest, I’m not a big fan of Redux. The boilerplate some patterns introduce are sometimes just too much, and in general I think that for most use cases, the disadvantages of immutability are bigger than the advantages. That’s not to say that I never use Redux; it can sometimes be very helpful. Let’s examine an alternative state management solution, which I mostly prefer to use — MobX. In MobX, the main concept is that you bind to some derived state, and MobX knows to automatically identify your state dependencies and automatically create an observable for it. It then runs your binding again only when the state that you depend on changes. Let’s see MobX in action with our two counters and a sum example: import { autorun, observable } from 'mobx'; const state = observable({ counter: 0, counter2: 0, get sum() { return this.counter + this.counter2; } }); $w.onReady(() => { autorun(() => $w('#counter').text = `${state.counter}`); autorun(() => $w('#counter2').text = `${state.counter2}`); autorun(() => $w('#sum').text = `${state.sum}`); $w('#increment').onClick(() => state.counter++); $w('#decrement').onClick(() => state.counter--); $w('#increment2').onClick(() => state.counter2++); $w('#decrement2').onClick(() => state.counter2--); }); That’s it. The cool thing about MobX is that it will run the autorun methods only when the state that they use has changed. So, when we update counter, the second autorun doesn’t run, and when we update counter2, the first autorun doesn’t run. The third autorun will run in both cases since it depends on sum, which depends both on counter and counter2. Note that instead of having that sum getter function in the observable, we could have done something like: autorun(() => $w('#sum').text = `${state.counter+state.counter2}`); This would have worked just the same, and we wouldn’t have needed the getter. However, as I mentioned before, it is wise to separate the logic from the view because then you can easily reuse your state when changing the view technology. I recommend to always do all calculations in the observable state using getters and leave the view as simple as possible. Let’s try to see how MobX holds up when we try the simplified todo list example. Just to remind you: We have a text input ( #input), an add button ( #add), and we have a repeater ( #repeater), which will display the items that we added. For each item in the repeater, we’ll have a text element displaying the description ( #description) and a delete button to remove it from the list ( #remove). import { autorun, observable } from 'mobx'; let nextId = 0; const state = observable({ tasks: [ { _id: `${++nextId}`, description: 'Task 1', completed: false }, { _id: `${++nextId}`, description: 'Task 2', completed: true }, { _id: `${++nextId}`, description: 'Task 3', completed: false } ], addTodo(description) { this.tasks.push({_id: `${++nextId}`, description, completed: false}) }, removeTodo(id) { this.tasks.remove(this.tasks.find(todo => todo._id === id)); } }); $w.onReady(() => { autorun(() => $w('#repeater').data = state.tasks); $w('#add').onClick(() => { state.addTodo($w('#input').value); $w('#input').value = ''; }); const destroyers = {}; $w('#repeater').onItemReady(($item, {_id}) => { destroyers[_id] = [ autorun(() => $item('#description').value = state.tasks.find(todo => todo._id === _id)) ]; $item('#remove').onClick(() => state.removeTodo(_id)); }); $w('#repeater').onItemRemoved(({_id}) => destroyers[_id].forEach(f => f())); }); All we needed to do, just like with Redux, is to bind an array to the data property of the repeater element ( #repeater). Now, onItemReady will be called for any new item and onItemRemoved for any removed item. Inside onItemReady, we do all of the binding necessary using the $item selector. Notice one special thing, which is very important to understand: the returned values from all of the calls to autorun must be saved as an array in the destroyers map, which is later invoked for each return value when the item is removed. The reason for this is that the return value of an autorun call is actually an unsubscribe method for that specific autorun. In corvid-redux, this is done automatically for us, but in MobX, we must call those unsubscribe methods when the item is removed. One place where MobX is much more comfortable is when you want to do some side effect in the binding of some value (e.g. hiding and showing an element). Let’s say you have some boolean state that specifies if some element should be visible or not. Since visibility in Corvid is controlled through show/hide functions, it is a bit tricky in Redux. In MobX, you would simply do: autorun(() => state.shouldShow ? $w('#element').show() : $w('#element').hide()); Whereas in Redux, corvid-redux needs to supply you with a magical visible property, which behind the scene calls show/hide: For a live example of a more complicated todo list open the corvid-mobx example in the Wix editor (turn on dev mode from the top menu in order to see the code). connect(state => ({visible: state.shouldShow}))($w('#element')); This post originally appeared on Medium. Further Reading Published at DZone with permission of Shahar Talmi . 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/state-management-in-corvid
CC-MAIN-2020-05
refinedweb
3,250
54.73
boost/vmd/is_number.hpp // (C) Copyright Edward Diener 2011-2015 // Use, modification and distribution are subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at //). #if !defined(BOOST_VMD_IS_NUMBER_HPP) #define BOOST_VMD_IS_NUMBER_HPP #include <boost/vmd/detail/setup.hpp> #if BOOST_PP_VARIADICS #include <boost/vmd/detail/is_number.hpp> /* The succeeding comments in this file are in doxygen format. */ /** \file */ /** \def BOOST_VMD_IS_NUMBER(sequence) \brief Tests whether a sequence is a Boost PP number. The macro checks to see if a sequence is a Boost PP number. A Boost PP number is a value from 0 to 256. sequence = a possible number returns = 1 if the sequence is a Boost PP number, 0 if it is not. If the input is not a VMD data type this macro could lead to a preprocessor error. This is because the macro uses preprocessor concatenation to determine if the input is a number once it is determined that the input does not start with parenthesis. If the data being concatenated would lead to an invalid preprocessor token the compiler can issue a preprocessor error. */ #define BOOST_VMD_IS_NUMBER(sequence) \ BOOST_VMD_DETAIL_IS_NUMBER(sequence) \ /**/ #endif /* BOOST_PP_VARIADICS */ #endif /* BOOST_VMD_IS_NUMBER_HPP */
https://www.boost.org/doc/libs/1_60_0/boost/vmd/is_number.hpp
CC-MAIN-2018-30
refinedweb
191
50.43
In preparation for CodeMash, I’ve been writing some more async code and decompiling it with Reflector. This time I’m using the Visual Studio 11 Developer Preview – the version which installs alongside Visual Studio 2010 under Windows 7. (Don’t ask me about any other features of Visual Studio 11 – I haven’t explored it thoroughly; I’ve really only used it for the C# 5 bits.) There have been quite a few changes since the CTP – they’re not visible changes in terms of code that you’d normally write, but the state machine generated by the C# compiler is reasonably different. In this post I’ll describe the differences, as best I understand them. There are still a couple of things I don’t understand (which I’ll highlight within the post) but overall, I think I’ve got a pretty good handle on why the changes have been made. I’m going to assume you already have a reasonable grasp of the basic idea of async and how it works – the way that the compiler generates a state machine to represent an async method or anonymous function, with originally-local variables being promoted to instance variables within the state machine, etc. If the last sentence was a complete mystery to you, see Eduasync part 7 for more information. I don’t expect you to remember the exact details of what was in the previous CTP though :) Removal of iterator block leftovers In the CTP, the code for async methods was based on the iterator block implementation. I suspect that’s still the case, but possibly sharing just a little less code. There used to be a few methods and fields which weren’t used in async methods, but now they’re gone: - There’s no now constructor, so no need for the "skeleton" method which replaces the real async method to pass in 0 as the initial state. - There’s no Dispose method. - There’s no disposing field. It’s nice to see these gone, but it’s not terribly interesting. Now on to the bigger changes… Large structural changes There’s a set of related structural changes which don’t make sense individually. I’ll describe them first, then look at how it all hangs together, and my guess as to the reasoning behind. The state machine is now a struct The declaration of the nested type for the state machine is now something like this: private struct StateMachine : IStateMachine { // Fields common to all async state machines // (with caveats) private int state; private object awaiter; public AsyncTaskMethodBuilder<int> builder; public Action moveNextDelegate; private object stack; // Hoisted local variables // Methods [DebuggerHidden] public void SetMoveNextDelegate(Action action) { … } public void MoveNext() { … } } The caveats around the common field are in terms of the return type of the async method (which determines the type of builder used) and whether or not there are any awaits (if there are no awaits, the stack and awaiter fields aren’t generated). Note that throughout this blog post I’ve changed the names of fields and types – in reality they’re all "unspeakable" names including angle-brackets, just like all compiler-generated names. There’s a new assembly-wide interface As you can see from the code above, the state machine implements an interface (actually called <>t__IStateMachine). One of these is created in the global namespace in each assembly that contains at least one async method or anonymous function, and it looks like this: internal interface IStateMachine { void SetMoveNextDelegate(Action action); } The implementation for this method is always the same, and it’s trivial: public void SetMoveNextDelegate(Action action) { this.moveNextDelegate = action; } Simplified skeleton method The method which starts the state machine, which I’ve been calling the "skeleton" method everywhere, is now a bit simpler than it was. Something like this: { StateMachine machine = new StateMachine(); machine.builder = AsyncVoidMethodBuilder.Create(); machine.MoveNext(); return machine.builder.Task; } In fact if you decompile the IL, you’ll see that it doesn’t explicitly initialize the variable to start with – it just declares it, sets the builder field and then calls MoveNext(). That’s not valid C# (as all the struct’s fields aren’t initialized), but it is valid IL. It’s equivalent to the code above though. Note how there’s nothing to set the continuation – where previously the moveNextDelegate field would be populated within the skeleton method. Just-in-time delegate creation Now that the skeleton method doesn’t create the delegate representing the continuation, it can be done when it’s first required – which is when we first encounter an await expression for an awaitable which hasn’t already completed. (If the awaitable has completed before we await it, the generated code skips the continuation and just uses the results immediately and synchronously). The code for that delegate creation is slightly trickier than you might expect, however. It looks something like this: if (action == null) { Task<int> task = this.builder.Task; action = new Action(this.MoveNext); ((IStateMachine) action.Target).SetMoveNextDelegate(action); } There are two oddities here, one of which I mostly understand and one of which I don’t understand at all. I really don’t understand the "task" variable here. Why do we need to exercise the AsyncTaskMethodBuilder.Task property? We don’t use the result anywhere… does forcing this flush some memory buffer? I have no clue on this one. (See the update at the bottom of the post…) The part about setting the delegate via the interface makes more sense, but it’s subtle. You might expect code like this: Action action = this.moveNextDelegate; if (action == null) { action = new Action(this.MoveNext); this.moveNextDelegate = action; } That would sort of work – but we’d end up needing to recreate the delegate each time we encountered an appropriate await expression. Although the above code saves the value to the field, it saves it within the current value of the state machine… after we’ve boxed that value as the target of the delegate. The value we want to mutate is the one within the box – which is precisely why there’s an interface, and why the code casts to it. We can’t even just unbox and then set the field afterwards – at least in C# – because the unbox operation is always followed by a copy operation in normal C#. I believe it would be possible for the C# compiler to generate IL which unboxed action.Target without the copy, and then set the field in that. It’s not clear to me why the team went with the interface approach instead… I would expect that to be slower (as it requires dynamic dispatch) but I could easily be wrong. Of course, it would also make it impossible to decompile the IL to C#, which would make my talks harder, but don’t expect the C# team to bend the compiler implementation for my benefit ;) (As an aside to all of this, I’ve gone back and forth on whether the "slightly broken" implementation would recreate the delegate on every appropriate await, or only two. I think it would end up being on every occurrence, as even though on the second occurrence we’d be operating within the context of the first boxed instance, the new delegate would have a reference to a new boxed copy each time. It does my head in a little bit, trying to think about this… more evidence that mutable structs are evil and hard to reason about. It’s not the wrong decision in this case, hidden far from the gaze of normal developers, but it’s a pain to reason about.) Single awaiter variable In the CTP, each await expression generated a separate field within the state machine, and that field was always of the exact awaiter type. In the VS11 Developer Preview, there’s always exactly one awaiter field (assuming there’s at least one await expression) and it’s always of type object. It’s used like this: TaskAwaiter<int> localAwaiter; … if (conditions-for-first-time-execution) { // Code before await localAwaiter = task.GetAwaiter(); if (localAwaiter.IsCompleted) { goto Await1Completed; } this.state = 1; TaskAwaiter<int>[] awaiterArray = { localAwaiter }; this.awaiter = awaiterArray; // Lazy delegate creation goes here awaiterArray[0].OnCompleted(action); return; } // Continuation would get into here localAwaiter = ((TaskAwaiter<int>[]) this.awaiter)[0]; this.awaiter = null; this.state = 0; Await1Completed: int result = localAwaiter.GetResult(); localAwaiter = default(TaskAwaiter<int>); I realize there’s a lot of code here, but it does make some sense: - The value of the awaiter field is always either null, or a reference to a single-element array of the awaiter type for one of the await expressions. - A single localAwaiter variable is shared between the two code paths, populated either from the awaitable (on the initial code path) or by copying the value from the array (in the second code path). - The field is always set to null and the local variable is set to its default value after use, presumably for the sake of garbage collection It’s basically a nice way of using the fact that we’ll only ever need one awaiter at a time. It’s not clear to me why an array is used instead of either using a reference to the awaiter for class-based awaiters, or simply by boxing for struct-based awaiters. The latter would need the same "unbox without copy" approach discussed in the previous section – so if there’s some reason why that’s actually infeasible, it would explain the use of an array here. We can’t use the interface trick in this case, as the compiler isn’t in control of the awaiter type (so can’t make it implement an interface). Expression stack preservation This one is actually a fix to a bug in the async CTP, which I’ve written about before. We’re used to the stack containing our local variables (in the absence of iterator blocks, captured variables etc, and modulo the stack being an implementation detail) but it’s also used for intermediate results within a single statement. For example, consider this block of code: int y = 5; int z = x + 50 * y; That last line is effectively: - Load the value of x onto the stack - Load the value 50 onto the stack - Load the value of y onto the stack - Multiply the top two stack values (50 and y) leaving the result on the stack - Add the top two stack values (x and the previously-computed result) leaving the result on the stack - Store the top stack value into z Now suppose we want to turn y into a Task<int>: Task<int> y = Task.FromResult(5); int z = x + 50 * await y; Our state machine needs to make sure that it will preserve the same behaviour as the synchronous version, so it needs the same sort of stack. In the new-style state machine, all of that stack is saved in the "stack" field. It’s only one field, but may need to represent multiple different types within the code at various different await expressions – in the code above, for example, it represents two int values. As far as I can discover, the C# compiler generates code which uses the actual type of the value it needs, if it only requires a single value. If it needs multiple values, it uses an appropriate Tuple type, nesting tuples if it goes beyond the number of type parameters supported by the Tuple<…> family of types. So in our case above, we end up with code a bit like this: Tuple<int, int> tuple; … // Code before the await if (conditions-for-first-time-execution) { … tuple = new Tuple<int, int>(this.x, 50); this.stack = tuple; … } // Continuation would get into here tuple = (Tuple<int, int>) this.stack; // IL copies the values from the tuple onto the stack at this point this.stack = null; … // Both the fast and slow code paths get here eventually this.z = stack0 + stack1 * awaiter.GetResult() I say it’s a bit like this, because it’s hard to represent the IL exactly in C# in this case. The tuple is only created if it’s needed, i.e. not in the already-completed fast path. In that case, the values are loaded onto the stack but not then put into the tuple – execution skips straight to the code which uses the values already on the stack. When the awaitable isn’t complete immediately, then a Tuple<int, int> is created, stored in the "stack" field, and the continuation is handed to the awaiter. On continuation, the tuple is loaded back from the "stack" field (and cast accordingly), the values are loaded onto the stack – and then we’re back into the common code path of fetching the value and performing the add and multiply operations. Conclusion As far as I’m aware, those are the most noticeable changes in the generated code. There may well still be a load more changes in Task<T> and the TPL in general – I wouldn’t be at all surprised – but that’s harder to investigate. I’m sure all of this has been done in the name of performance (and correctness, in the case of stack preservation). The state machine is now much smaller in terms of the number of fields it requires, and objects are created locally as far as possible (including the state machine itself only requiring heap allocation if there’s ever a "slow" awaitable). I suspect there’s still some room for optimization, however: - Both the awaiter and the delegate use careful boxing and either arrays or a mutating interface to allow the boxed value to be changed. I suspect that using unbox with the concrete type, but without copying the value, would be more efficient. I may attempt to work this theory up into a test at some point. - If there’s only one awaiter type (usually TaskAwaiter<T> for some T), that type could be used instead of object, potentially reducing heap optimization - I’ve no idea why the builder.Task property is explicitly fetched and then the results discarded - If there’s only one await expression, the "stack" field can be strongly typed, which would also avoid boxing if only a single value needs to be within that stack - The stack field could be removed entirely when it’s not needed for intermediate stack value preservation. (I believe that would be the case reasonably often.) The use of mutable value types is really fascinating (for me, at least) – I’m sure most people on the C# team would still say they’re evil, but when they’re used in a carefully controlled environment where real developers don’t have to reason about their behaviour, they can be useful. Next time, I’ll hopefully get back to the idea I promised to write up before, about ordering a collection of tasks in completion order… before they’ve completed. (Well, sort of.) Should be fun… Update (January 16th 2012) Stephen Toub got in touch with me after I posted the original version of this blog entry, to explain the use of the Task property. Apparently the idea is that at this point, we know we’re going to return out of the state machine, so the skeleton method is going to access the Task property anyway. However, as we haven’t scheduled the continuation yet we also know that nothing will be accessing the Task property on a different thread. If we access it now for the first time, we can lazily allocate the task in the same thread that created the AsyncMethodBuilder, with no risk of contention. If we can force there to be a task ready and waiting for whatever accesses it later, we don’t need any synchronization in that area. So why might we want to allocate the task lazily in the first place? Well, don’t forget that we might never have to wait for an await (as it were). We might just have an async method which takes the fast path everywhere. If that’s the case, then for certain cases (e.g. a non-generic, successfully completed task, or a Task<bool> which again has completed successfully) we can reuse the same instance repeatedly. Apparently this laziness isn’t yet part of the VS11 Developer Preview, but the reason for the property access is in preparation for this. Another case of micro-optimization – which is fair enough when it’s at a system level :) 7 thoughts on “Eduasync part 18: Changes between the Async CTP and the Visual Studio 11 Preview” > The value of the awaiter field is always either null, or a reference to a single-element array of the awaiter type for one of the await expressions. But in the code, the field is set to localAwaiter, which is a TaskAwaiter, not an array. Is this a typo in the code? @Svick: Apologies, yes – bug in the code. Fixed now, thanks. Man – it took me a *long* time to figure out what you were talking about with that mutating moveNextDelegate stuff, since I didn’t twig to the fact that creating a delegate to a method of a struct caused the target to be set to a boxed copy of the struct (which is obvious in retrospect, of course). I’m not sure if this changes my opinion on mutable structs – are there other situations I won’t figure out until too late? – but at least making delegates to struct methods seems to be a bit bizarre. Also: I wonder if a TypedReference with a 0-length fields array would be any better w/r/t the awaiter array – don’t think so. They have an interesting solution for the evaluation stack variables – though I’m surprised they don’t just convert them to locals – it turns into stfld/ldfld in either case but you don’t need to new and cast Tuples this way. I’d figure some weirdness of their codegen, but I can’t figure out how generating a Tuple to store them in could be easier. Minor nitpick: I don’t think the execution stack and the evaluation stack are related beyond that a deep evaluation stack will eventually spill onto the execution stack. @Simon: Okay, I’ll try to fix up that later on. (I have a larger edit to make anyway.) The evaluation stack variables can’t be changed into *local* variables because they need to be persisted across a continuation. The reason for the object/tuple/etc bit is to avoid having *lots* of instance variables in the state machine, for each bit of evaluation stack needed in each await. Yeah, sorry, I meant before the state-machine transform, so they get turned into StateMachine fields – since it seems to me that that would be simpler and give better results than figuring out what stack variables need to be spilled at that point.
https://codeblog.jonskeet.uk/2012/01/11/eduasync-part-18-changes-between-the-async-ctp-and-the-visual-studio-11-preview/?like_comment=13205&_wpnonce=ffa141d68d
CC-MAIN-2019-43
refinedweb
3,167
56.59
Greg Selected Marcus Fizer, 6'8", PF, Iowa State The L.A. Clippers: "The worst franchise in all of sports." Or so Sports Illustrated termed the woeful Los Angeles team in a recent issue. Donald Sterling, Elgin Baylor, and the Clippers front office have become notorious for making poor personnel decisions, hiring and firing coaches at whim, giving away good players for nothing in return (i.e. letting Lorenzen Wright leave instead of pursuing a sign and trade deal with the Hawks or other suitors), and refusing to pay any player a substantial amount of cash to play for the "other" Los Angeles franchise. With nearly as much free agency money as Orlando and Chicago, playing in one of the top three television markets in the nation (which can, and I emphasize can, mean endorsements for star players), and with perhaps the top prospects in each of the last two drafts (Michael Olowokandi and Lamar Odom) one would think the Clippers are assembling a playoff team. But in fact the Clippers are far from the playoffs, though with a few free agency moves and a good draft they could come a step closer. The Clippers still lack a coach, as Jim Todd is the most recent to say "adios" to Los Angeles. Nuggets' assistant coach John Lucas, Clippers' assistant Dennis Johnson, and even former Georgetown leader John Thompson have been rumored to be heading to the Clippers' bench next season to attempt to succeed where many other coaches have failed: coaxing the Clippers to a winning season. But more important than securing a coach the Clippers' front office must determine who will play on the floor next season for a team that won just 18 percent of its games in 1999-2000. The players locked to the Clippers by contract include Odom, Olowokandi, Tyrone Nesby, Eric Piatkowski, Brian Skinner, and Eric Murdock. Key free agents include Maurice Taylor and Derek Anderson. The following sections are a quick rundown on each of these players, both those under contract as well as the free agents. The Clippers must make some moves in free agency and in the draft to fill the team's holes at point guard and power forward. In the dreams of any Clippers fan the rumors surrounding free agents Tim Duncan, Grant Hill, Jalen Rose, Reggie Miller, Tracy McGrady, Rashard Lewis, Tim Thomas, Austin Croshere, and others would include talks of these potential stars being traded to or signed by the Los Angeles Clippers. And yet these players, at some point all rumored to go to either Orlando and Chicago, the other two teams with all the money, have not been included in discussions about the Clippers' plans for the upcoming year. The draft thus will be the best chance for the Clippers to build their future. The Clippers' draft history has been far from exceptional. 1994 netted them Lamond Murray, followed by a 1995 draft in which the Clippers drafted Antonio McDyess only to trade him away for eventual sixth-man Rodney Rogers and slam-dunk champ Brent Barry. Murray currently is a solid small forward for the Cavaliers, while McDyess dominates the low block as a power forward for the Nuggets. With Barry and Rogers on the Sonics and Suns respectively, the Clippers made perhaps their greatest mistake of recent drafts in trading away the developing star McDyess. In 1996 the Clippers drafted Lorenzen Wright, but the "Sporting News" argues that L.A. "played him more at center than his natural position of power forward. Wright moved on to Atlanta, where he did not fare much better." Then for the third consecutive year in 1997 the Clippers drafted a power forward, Maurice Taylor from Michigan, who will continue the pattern of lost Clippers' power forwards as he will almost undoubtedly sign with another team this summer. Finally, the Clippers selected Olowokandi from the University of the Pacific in 1998 and Odom from Rhode Island in 1999. Olowokandi was selected over the likes of Vince Carter, Mike Bibby, and Antawn Jamison to name a few. However, he was drafted to be a project, and perhaps in a few years he will develop into a solid big man. His hasty appearance as a starter is merely a representation of the desperation the Clippers often face in finding five decent starters year in and year out, week in and week out. Odom was a steal in 1999, as three other teams passed on the youngster who at one point wanted to return to college after declaring for the draft and signing with an agent. His appeal to the NBA to be released and allowed to return to college was rejected, luck indeed for the Clippers who can always use any break that falls in their direction. The Clippers must address their needs at the point guard, shooting guard, and power forward spot with their three picks in the draft. I believe that they will select a power forward first, then a point guard, and then a shooting guard in that order for several reasons. Power forwards bring dominance in the paint, a crucial characteristic of winning teams as the Lakers have proven. Point guard comes next as teams with a back-court leader, a player that can orchestrate an offense, are usually successful in the NBA. What is more is that the Clippers were working with players such as Troy Hudson, Eric Murdock, and Charles Jones- decent individuals, but hardly guys capable of effectively leading an NBA basketball team - at the point guard slot last year and would like to improve at this position. Finally with Anderson leaving the Clippers must hope for a steal with a shooting guard at the 30th spot in the draft or sign a free agent. Player availability also necessitates the order I have set in the previous paragraph. The three best players in this year's draft happen to be power forwards, and the Clippers hold the third pick guaranteeing them one of these three: Kenyon Martin of Cincinnati, Marcus Fizer of Iowa St., or Stromile Swift of LSU. Then point guards will be readily available in the middle of the draft: Mateen Cleaves of Michigan St., Erick Barkley of St. John's, Craig Claxton of Hofstra, Scoonie Penn of Ohio St., Jamal Crawford of Michigan, A.J. Guyton of Indiana, and Kenyon Dooling of Missouri. If the Clippers decide to wait on a point guard until the 30th pick and select a shooting guard at 18, some options might include Quentin Richardson of Depaul, Deshawn Stevenson of Washington Union High School, Morris Peterson of Michigan St., Desmond Mason of Oklahoma St., or Chris Carrawell of Duke. The following is a brief analysis of each of these players, my pick and the reasons behind it, and then a conclusion on the Clippers' options with the 18th pick in the draft. My fellow Clippers GM in crime, Greg Gillette, selected Marcus Fizer with his choice in the 2000 Usenet Mock Draft, the correct third pick I believe under the circumstances. The order in which I list each player in the next three sections is the order in which I believe the players will be selected in the actual draft. Fizer is the third best power forward, so if Martin and Swift go one and two then the Clippers will end up with the big man from Iowa St. With a power forward in hand, my guess is the Clippers will look next to a point guard. The following is a list of players the Clippers will consider with their 18th pick. Listed first are the point guards, and following are the shooting guards. Boston with the 11th pick and Detroit at 14 may also grab point guards, as may Orlando with one of their three picks. Even so, a good point guard, though perhaps not a superstar, will be available for the Clippers to select at 18. Here are some of the possibilities: Should the Clippers choose to pick a replacement for Derek Anderson at 18 these players are the ones who I believe would be high on their list: Marcus Fizer, PF, 6'8",Iowa State I've already touched on some of the rumors surrounding the Clippers. It is important that first and foremost the team sign a coach prior to the draft. Clippers' coaches do not last long, but perhaps they could surprise everyone with a selection this time around. I do not believe that John Thompson is the man best suited to coach the Clippers, and would prefer another high profile college coach (or even maybe the recently fired Butch Carter?). Also Mark Jackson apparently wants to be a player-coach, and would be a perfect fit with the Clippers as an assistant and a point guard. Once the coach is in place and the players selected from the draft are finalized, the Clippers need to make a few moves in free agency. Rumors of Derek Anderson for players like Tariq Abdul-Wahad and Avery Johnson abound, and I believe that the Clippers need to get something in return for a guy as good as Anderson. He can be the second or third scorer on a lot of teams, from the 76ers to the Spurs, so rightfully the Clippers deserve some sort of replacement for Derek. The Clippers thus need to re-sign Anderson with the agreement that he will subsequently be traded to a new team. Finally, the Clippers need to sign at the minimum one free agent, either a power forward to have around while their draft pick develops or a point guard for the same purpose. If they do not fill one of these gaps in a sign-and-trade deal with Anderson, possibilities include Oakley, Scott Pollard, and other post players. The problem of course is that the Clippers have not recently been able to draw high caliber free-agents. The Clippers, I can say, should go after Duncan, Hill, McGrady, Lewis, Rose, or even Reggie Miller. But these players want to play for a "contender," or at least a team that is not the perennial bottom dweller of the Western Conference. The Clippers thus should play the free agent market, but realistically their chances of signing a star are slim. However the Clippers must sign at least one free agent this summer, as their team needs new blood. Well, I have written quite a bit. But then as a Clippers' fan, thoughts run through my head daily about what moves the team should make, who they should draft, and how the possibility exists for them to become a playoff team within the next few years. One can only hope that the stigma surrounding the Clippers - a team of lackluster effort, poor execution, terrible ownership, and an organization that cannot win - will disappear if they make the correct personnel decisions in the near future.
http://www.ibiblio.org/craig/draft/2000_draft/Picks/3_clippers.htm
CC-MAIN-2016-50
refinedweb
1,817
64.44
zzz The invaders are coming and if enough of them make it to Earth they will take over. You are the last hope to stop them. When you shoot at them with your special non-violent weapon you do not kill them, but you send them into a limbo dimension that we call Zzz. They are still alive but probably pretty upset that at being zapped into such a boring dimension with nothing to do except watch fireflys.game XNA Library for using jQuery from GWT and java2script. jQuery bridge is rebuild from jQuery documentation. You get all - autocompletion, refactoring, javadoc. Simple example: import static com.jquery.JQuery.$; public class Main { public static void main(String args) { $("#test").addClass("zzz"); } }gwt j2s java2z zzz zzzz Open source products are scattered around the web. Please provide information about the open source projects you own / you use. Add Projects. Tag Cloud >>
http://www.findbestopensource.com/product/zzz
CC-MAIN-2016-44
refinedweb
149
75.3
Migrating .NET Core projects from project.json This document will cover migration scenarios for .NET Core projects and will go over the following three migration scenarios: - Migration from a valid latest schema of project.json to csproj - Migration from DNX to csproj - Migration from RC3 and previous .NET Core csproj projects to the final format This document is only applicable to older .NET Core projects that still use project.json. It is not applicable for migrating from .NET Framework to .NET Core. Migration from project.json to csproj Migration from project.json to .csproj can be done using one of the following methods: Both methods use the same underlying engine to migrate the projects, so the results will be the same for both. In most cases, using one of these two ways to migrate the project.json to csproj is the only thing that is needed and no further manual editing of the project file is necessary. The resulting .csproj file will be named the same as the containing directory name. Visual Studio 2017 When you open a .xproj file or a solution file which references .xproj files, the One-way upgrade dialog appears. The dialog displays the projects to be migrated. If you open a solution file, all the projects specified in the solution file will be listed. Review the list of projects to be migrated and select OK. Visual Studio will migrate the projects chosen automatically. When migrating a solution, if you don't choose all projects, the same dialog will appear asking you to upgrade the remaining projects from that solution. After the project is migrated, you can see and modify its contents by right-clicking the project in the Solution Explorer window and selecting Edit <project name>.csproj. Files that were migrated (project.json, global.json, .xproj and solution file) will be moved to a Backup folder. The solution file that is migrated will be upgraded to Visual Studio 2017 and you won't be able to open that solution file in previous versions of Visual Studio. A file named UpgradeLog.htm is also saved and automatically opened that contains a migration report. Important The new tooling is not available in Visual Studio 2015, so you cannot migrate your projects using that version of Visual Studio. dotnet migrate In the command-line scenario, you can use the dotnet migrate command. It will migrate a project, a solution or a set of folders in that order, depending on which ones were found. When you migrate a project, the project and all its dependencies are migrated. Files that were migrated (project.json, global.json and .xproj) will be moved to a backup folder. Note If you are using Visual Studio Code, the dotnet migrate command will not modify Visual Studio Code-specific files such as tasks.json. These files need to be changed manually. This is also true if you are using Project Ryder or any editor or Integrated Development Environment (IDE) other than Visual Studio. See A mapping between project.json and csproj properties for a comparison of project.json and csproj formats. Common issues - If you get an error: "No executable found matching command dotnet-migrate": Run dotnet --version to see which version you are using. dotnet migrate requires .NET Core CLI RC3 or higher. You’ll get this error if you have a global.json file in the current or parent directory and the sdk version is set to an older version. Migration from DNX to csproj If you are still using DNX for .NET Core development, your migration process should be done in two stages: - Use the existing DNX migration guidance to migrate from DNX to project-json enabled CLI. - Follow the steps from the previous section to migrate from project.json to .csproj. Note DNX has become officially deprecated during the Preview 1 release of the .NET Core CLI. Migration from earlier .NET Core csproj formats to RTM csproj The .NET Core csproj format has been changing and evolving with each new pre-release version of the tooling. There is no tool that will migrate your project file from earlier versions of csproj to the latest, so you need to manually edit the project file. The actual steps depend on the version of the project file you are migrating. The following is some guidance to consider based on the changes that happened between versions: - Remove the tools version property from the <Project>element, if it exists. - Remove the XML namespace ( xmlns) from the <Project>element. - If it doesn't exist, add the Sdkattribute to the <Project>element and set it to Microsoft.NET.Sdkor Microsoft.NET.Sdk.Web. This attribute specifies that the project uses the SDK to be used. Microsoft.NET.Sdk.Webis used for web apps. - Remove the <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" />and <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />statements from the top and bottom of the project. These import statements are implied by the SDK, so there is no need for them to be in the project. - If you have Microsoft.NETCore.Appor NETStandard.Library <PackageReference>items in your project, you should remove them. These package references are implied by the SDK. - Remove the Microsoft.NET.Sdk <PackageReference>element, if it exists. The SDK reference comes through the Sdkattribute on the <Project>element. - Remove the globs that are implied by the SDK. Leaving these globs in your project will cause an error on build because compile items will be duplicated. After these steps your project should be fully compatible with the RTM .NET Core csproj format. For examples of before and after the migration from old csproj format to the new one, see the Updating Visual Studio 2017 RC – .NET Core Tooling improvements article on the .NET blog.
https://docs.microsoft.com/en-us/dotnet/core/migration/
CC-MAIN-2019-04
refinedweb
961
59.4
Tax Have a Tax Question? Ask a Tax Expert You may either sell OR gift the property to your son - or a combination of both. If you gift......... - while the gift itself is not a taxable income for the donee and is NOT reported on the tax return - the donor might be required to file a gift tax return (form 709) when the gift is above filing threshold ($14,000 per person per year) - but most likely - you will not have any gift tax liability (based on the lifetime exclusion that is above $5,450,000). Let me know if you need any clarification this matter. So far ... . .I appreciate if you take a moment to rate the answer. Experts are ONLY credited when answers are rated positively. If you still have any doubts, need clarification - please be sure to ask. I am here to help you with all tax related issues.
http://www.justanswer.com/tax/9p7ph-husband-purchased-home-va-loan-2011.html
CC-MAIN-2017-09
refinedweb
152
71.55
derived type to existing type, modifying the original type or recompiling the original type. - It provides ability to programmer to add new methods to existing type. - It can be used to add new methods to existing .Net core classes. It is defined as a static method but called with syntax of instance method. - If there is a member method in type class with the same name of extension method then member method will get precedence over extension method. For example Show method is member method of Message class. So if there is any extension method called Show on type Message class is created, always Show member method will get precedence over Show extension method for the type Message. Compiler Signature static class Extensions { public static IEnumerable<T> Where<T>(this IEnumerable<T> sequence, Predicate<T> predicate) { foreach (T item in sequence) { if (predicate(item)) { yield return item; }}}} - The method is static - The first parameter is decorated with modifier “this” . - First parameter is called as Instance Parameter. - A compile time error will encountered to use this modifer with any other parameter than instance parameter. - No other modifers like ref, out etc are allowed with “this” modifer or instance parameter. - The instance parameter can not be a pointer type. - The method is public . - The instance parameter can not have the type of the type parameter. The below is not possible. public static int Obj<T> (this T param) Restrictions - It could only access public memebers of the target type. - If an extension method conflicts with a member method of target type , always member method is get invoked instead of extension method. Implementation and Calling Step1 : Define a static visible class to contain Extension method. Step2: Implement the Extension method as static method. Step 3: The First parameter of method specifies the type method works on Step4 : The First parameter must be preceded by “this” modifer. Step 5: At the client code add namespace of extension method with using directive. Examples - In first example, I will add an Extension method to existing String class. This extension method will remove all the vowel form the string - Modify the class with modifier with public and static of the class extensionmethodcontainer. - Add a extension method with below signature. The First parameter String specifies that this is extension method on the type String. public static String RemoveVowel(this String s) The full code to remove vowel from input string is written in the Extension method. 1 using System; 2 3 using System.Collections.Generic; 4 5 using System.Linq; 6 7 using System.Text; 8 9 namespace ExtensionMethodSample 10 { 11 public static class extensionmethodcontainer 12 { 13 14 public static String RemoveVowel(this String s) 15 { 16 string[] vowels = new 17 18 string[] { “A”, “E”, “I”, “O”, “U” }; 19 20 if (string.IsNullOrEmpty(s)) 21 return string.Empty; 22 23 List<char> chars = new List<char>(s.ToCharArray()); 24 for (int i = chars.Count – 1; i >= 0; i–) 25 { 26 for (int j = 0; j < vowels.Length; j++) 27 { 28 29 if (chars[i].ToString().ToLower() == vowels[j].ToLower()) 30 31 chars.RemoveAt(i); 32 } 33 } 34 35 return new string(chars.ToArray()); 36 37 } 38 39 } 40 41 } 42 - Client code is here Main class - In main class, user is inputting the string and RemoveVowel extension method is being called on the input string to remove vowel from the string. Note: - Here both Extension method and client is in same namespace, so there is no need to include namespace of the extension method. - Extension method is called as any other member method resultString = str.RemoveVowel(); 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 namespace ExtensionMethodSample 6 { 7 class Program 8 { 9 static void Main(string[] args) 10 { 11 String resultString; 12 13 Console.WriteLine(“Enter Input String to Remove all Vowel using Extension Method \n”); 14 15 String str = Console.ReadLine(); 16 17 Console.WriteLine(“After Removing Vowel Input String is \n”); 18 19 resultString = str.RemoveVowel(); 20 21 Console.WriteLine(resultString); 22 23 Console.ReadKey(); 24 } 25 } 26 } 27 } 28
http://debugmode.net/2010/04/
CC-MAIN-2014-52
refinedweb
683
58.79
'just looking' and doing some exploratory data analysis (EDA) it is not so easy to choose a specialized algorithm. So, what algorithm is good for exploratory data analysis? To start, lets' lay down some ground rules of what we need a good EDA clustering algorithm to do, then we can set about seeing how the algorithms available stack up. There are other nice to have features like soft clusters, or overlapping clusters, but the above desiderata is enough to get started with because, oddly enough, very few clustering algorithms can satisfy them all! import numpy as np import matplotlib.pyplot as plt import seaborn as sns import sklearn.cluster as cluster import time %matplotlib inline sns.set_context('poster') sns.set_color_codes() plot_kwds = {'alpha' : 0.25, 's' : 80, 'linewidths':0} Next we need some data. In order to make this more interesting I've constructed an artificial dataset that will give clustering algorithms a challenge -- some non-globular clusters, some noise etc.; the sorts of things we expect to crop up in messy real-world data. So that we can actually visualize clusterings the dataset is two dimensional; this is not something we expect from real-world data where you generally can't just visualize and see what is going on. data = np.load('clusterable_data.npy') So let's have a look at the data and see what we have. plt.scatter(data.T[0], data.T[1], c='b', **plot_kwds) frame = plt.gca() frame.axes.get_xaxis().set_visible(False) frame.axes.get_yaxis().set_visible(False) It's messy, but there are certainly some clusters that you can pick out by eye; determining the exact boundaries of those clusters is harder of course, but we can hope that our clustering algorithms will find at least some of those clusters. So, on to testing ... def plot_clusters(data, algorithm, args, kwds): start_time = time.time() labels = algorithm(*args, **kwds).fit_predict(data) end_time = time.time() palette = sns.color_palette('deep', np.unique(labels).max() + 1) colors = [palette[x] if x >= 0 else (0.0, 0.0, 0.0) for x in labels] plt.scatter(data.T[0], data.T[1], c=colors, **plot_kwds) frame = plt.gca() frame.axes.get_xaxis().set_visible(False) frame.axes.get_yaxis().set_visible(False) plt.title('Clusters found by {}'.format(str(algorithm.__name__)), fontsize=24) plt.text(-0.5, 0.7, 'Clustering took {:.2f} s'.format(end_time - start_time), fontsize=14) Before we try doing the clustering, there are some things to keep in mind as we look at the results. On to the clustering algorithms. K-Means is the 'go-to' clustering algorithm for many simply because it is fast, easy to understand, and available everywhere (there's an implementation in almost any statistical or machine learning tool you care to use). K-Means has a few problems however. The first is that it isn't a clustering algorithm, it is a partitioning algorithm. That is to say K-means doesn't 'find clusters' it partitions your dataset into as many (assumed to be globular) chunks as you ask for by attempting to minimize intra-partition distances. That leads to the second problem: you need to specify exactly how many clusters you expect. If you know a lot about your data then that is something you might expect to know. If, on the other hand, you are simply exploring a new dataset then 'number of clusters' is a hard parameter to have any good intuition for. The usually proposed solution is to run K-Means for many different 'number of clusters' values and score each clustering with some 'cluster goodness' measure (usually a variation on intra-cluster vs inter-cluster distances) and attempt to find an 'elbow'. If you've ever done this in practice you know that finding said elbow is usually not so easy, nor does it necessarily correlate as well with the actual 'natural' number of clusters as you might like. Finally K-Means is also dependent upon initialization; give it multiple different random starts and you can get multiple different clusterings. This does not engender much confidence in any individual clustering that may result. So, in summary, here's how K-Means seems to stack up against out desiderata: But enough opinion, how does K-Means perform on our test dataset? Let's have look. We'll be generous and use our knowledge that there are six natural clusters and give that to K-Means. plot_clusters(data, cluster.KMeans, (), {'n_clusters':6}) We see some interesting results. First, the assumption of perfectly globular clusters means that the natural clusters have been spliced and clumped into various more globular shapes. Worse, the noise points get lumped into clusters as well: in some cases, due to where relative cluster centers ended up, points very distant from a cluster get lumped in. Having noise pollute your clusters like this is particularly bad in an EDA world since they can easily mislead your intuition and understanding of the data. On a more positive note we completed clustering very quickly indeed, so at least we can be wrong quickly. Affinity Propagation is a newer clustering algorithm that uses a graph based approach to let points 'vote' on their preferred 'exemplar'. The end result is a set of cluster 'exemplars' from which we derive clusters by essentially doing what K-Means does and assigning each point to the cluster of it's nearest exemplar. Affinity Propagation has some advantages over K-Means. First of all the graph based exemplar voting means that the user doesn't need to specify the number of clusters. Second, due to how the algorithm works under the hood with the graph representation it allows for non-metric dissimilarities (i.e. we can have dissimilarities that don't obey the triangle inequality, or aren't symmetric). This second point is important if you are ever working with data isn't naturally embedded in a metric space of some kind; few clustering algorithms support, for example, non-symmetric dissimilarities. Finally Affinity Propagation does, at least, have better stability over runs (but not over parameter ranges!). The weak points of Affinity Propagation are similar to K-Means. Since it partitions the data just like K-Means we expect to see the same sorts of problems, particularly with noisy data. While Affinity Propagation eliminates the need to specify the number of clusters, it has 'preference' and 'damping' parameters. Picking these parameters well can be difficult. The implementation in sklearn default preference to the median dissimilarity. This tends to result in a very large number of clusters. A better value is something smaller (or negative) but data dependent. Finally Affinity Propagation is slow; since it supports non-metric dissimilarities it can't take any of the shortcuts available to other algorithms, and the basic operations are expensive as data size grows. So, in summary, over our desiderata we have: sklearn). And how does it look in practice on our chosen dataset? I've tried to select a preference and damping value that gives a reasonable number of clusters (in this case six) but feel free to play with the parameters yourself and see if you can come up with a better clustering. plot_clusters(data, cluster.AffinityPropagation, (), {'preference':-5.0, 'damping':0.95}) The result is eerily similar to K-Means and has all the same problems. The globular clusters have lumped together splied parts of various 'natural' clusters. The noise points have been assigned to clusters regardless of being significant outliers. In other words, we'll have a very poor intuitive understanding of our data based on these 'clusters'. Worse still it took us several seconds to arrive at this unenlightening conclusion. Mean shift is another option if you don't want to have to specify the number of clusters. It is centroid based, like K-Means and affinity propagation, but can return clusters instead of a partition. The underlying idea of the Mean Shift algorithm is that there exists some probability density function from which the data is drawn, and tries to place centroids of clusters at the maxima of that density function. It approximates this via kernel density estimation techniques, and the key parameter is then the bandwidth of the kernel used. This is easier to guess than the number of clusters, but may require some staring at, say, the distributions of pairwise distances between data points to choose successfully. The other issue (at least with the sklearn implementation) is that it is fairly slow depsite potentially having good scaling! How does Mean Shift fare against out criteria? In principle proming, but in practice ... Let's see how it works on some actual data. I spent a while trying to find a good bandwidth value that resulted in a reasonable clustering. The choice below is about the best I found. plot_clusters(data, cluster.MeanShift, (0.175,), {'cluster_all':False}) We at least aren't polluting our clusters with as much noise, but we certainly have dense regions left as noise and clusters that run across and split what seem like natural clusters. There is also the outlying yellow cluster group that doesn't make a lot of sense. Thus while Mean Shift had good promise, and is certainly better than K-Means, it's still short of our desiderata. Worse still it took over 4 seconds to cluster this small dataset! Spectral clustering can best be thought of as a graph clustering. For spatial data one can think of inducing a graph based on the distances between points (potentially a k-NN graph, or even a dense graph). From there spectral clustering will look at the eigenvectors of the Laplacian of the graph to attempt to find a good (low dimensional) embedding of the graph into Euclidean space. This is essentially a kind of manifold learning, finding a transformation of our original space so as to better represent manifold distances for some manifold that the data is assumed to lie on. Once we have the transformed space a standard clustering algorithm is run; with sklearn the default is K-Means. That means that the key for spectral clustering is the transformation of the space. Presuming we can better respect the manifold we'll get a better clustering -- we need worry less about K-Means globular clusters as they are merely globular on the transformed space and not the original space. We unfortunately retain some of K-Means weaknesses: we still partition the data instead of clustering it; we have the hard to guess 'number of clusters' parameter; we have stability issues inherited from K-Means. Worse, if we operate on the dense graph of the distance matrix we have a very expensive initial step and sacrifice performance. So, in summary: Let's have a look at how it operates on our test dataset. Again, we'll be generous and give it the six clusters to look for. plot_clusters(data, cluster.SpectralClustering, (), {'n_clusters':6}) Spectral clustering performed better on the long thin clusters, but still ended up cutting some of them strangely and dumping parts of them in with other clusters. We also still have the issue of noise points polluting our clusters, so again our intuitions are going to be led astray. Performance was a distinct improvement of Affinity Propagation however. Over all we are doing better, but are still a long way from achieving our desiderata. Agglomerative clustering is really a suite of algorithms all based on the same idea. The fundamental idea is that you start with each point in it's own cluster and then, for each cluster, use some criterion to choose another cluster to merge with. Do this repeatedly until you have only one cluster and you get get a hierarchy, or binary tree, of clusters branching down to the last layer which has a leaf for each point in the dataset. The most basic version of this, single linkage, chooses the closest cluster to merge, and hence the tree can be ranked by distance as to when clusters merged/split. More complex variations use things like mean distance between clusters, or distance between cluster centroids etc. to determine which cluster to merge. Once you have a cluster hierarchy you can choose a level or cut (according to some criteria) and take the clusters at that level of the tree. For sklearn we usually choose a cut based on a 'number of clusters' parameter passed in. The advantage of this approach is that clusters can grow 'following the underlying manifold' rather than being presumed to be globular. You can also inspect the dendrogram of clusters and get more information about how clusters break down. On the other hand, if you want a flat set of clusters you need to choose a cut of the dendrogram, and that can be hard to determine. You can take the sklearn approach and specify a number of clusters, but as we've already discussed that isn't a particularly intuitive parameter when you're doing EDA. You can look at the dendrogram and try to pick a natural cut, but this is similar to finding the 'elbow' across varying k values for K-Means: in principle it's fine, and the textbook examples always make it look easy, but in practice on messy real world data the 'obvious' choice is often far from obvious. We are also still partitioning rather than clustering the data, so we still have that persistent issue of noise polluting our clusters. Fortunately performance can be pretty good; the sklearn implementation is fairly slow, but fastcluster provides high performance agglomerative clustering if that's what you need. So, in summary: So, let's see it clustering data. I chose to provide the correct number of clusters (six) and use Ward as the linkage/merge method. This is a more robust method than say single linkage, but it does tend toward more globular clusters. plot_clusters(data, cluster.AgglomerativeClustering, (), {'n_clusters':6, 'linkage':'ward'})
http://nbviewer.jupyter.org/github/lmcinnes/hdbscan/blob/master/notebooks/Comparing%20Clustering%20Algorithms.ipynb
CC-MAIN-2017-22
refinedweb
2,317
53.21
Hi all, I have an app with a MasterDetailsPage that I use for the main navigation. I am using the "hamburger" icon for my menu icon. On Android this works great. I set the Icon property on the MenuPage which is a ContentPage. And the "hamburger" appears. But on iOS nothing shows up no matter what I do. Anyone have any advice on what might be wrong or how to fix this? . Answers bump To help others answer your question, it might be an idea to post the code where you experience an issue. Anywho. Have you added the icon to your "Resources" folder in your iOS project and marked it as "BundleResource"? At least, the Hamburger menu works fine for me personally on iOS. This guide might also provide you a hint of what's wrong. You need to wrap your Detail as a NavigationPage Hope this helps! Ok sorry I was hoping it might have been a simple known issue. Here is the MainPage: Here is the menu page code I think this is the main code that would be in question. From how it works on the Android version its the Icon = "settings.png" That sets the icon to the title bar. And like I said this works find on Android just not on iOS. Thanks. Please let me know if you'd like anything else. @David - So I used that guide initially. However, I found that on iOS 8 that there are separator lines in the slide out menu. So I found another example that I am currently using that uses a TableView and then we overload the renderer to get rid of the lines. But thank you for the suggestion . @MacKenzieMickelsen Did you find solution to the reported problem? I am facing the same issue with iOS. Sorry to leave you hanging so long Mato, was on vacation. What I ended up doing which solved the problem was just implement the MasterDetailPage EXACTLY like it is in this guide. Hope this helps @Mato - in your Menu page constructor, make sure that you set the icon BEFORE anything else. Seems to be some sort of bug if you set the Title first and then the Icon. Hope that helps. in my case it was two things. icon must be set. so a hamburger icon must be present on the resources folder and title property must have a value I recently had a similar problem in a xamarin forms app that uses a NavigationDrawer (not strictly master-detail). The image is loaded in the constructor with hamburgerButton.Image = (FileImageSource)ImageSource.FromFile("hamburger_icon.png"); Android showed the hamburger normally (image in Resources/Drawable). iOS and UWP were blank. The solution for me was: iOS: marking the image file in Resources folder as Build Action = BundleResource (thanks @KimNiebling) UWP: marking the image file in root folder as Build Action = Content I had a similar problem , the solution for me was: Add 2 icons in Resources folder into ios project "itemIcon1.png" (48x48 px) So I've hit the same problem, with a twist that the menu icon does show up on an iPhone 5s. Just not anything later than that. I'm wrapping the Detail page in a NavigationPage, I have the icon (and [email protected], @3x) in the iOS project resources folder, marked as BundleResource, I set the Icon before anything else, and the Title is set. I also have a problem with Toolbar icons not showing up - again, only after the iPhone 5s. Anyone have any ideas what the problem could be? The link posted a couple years back is dead, and I'm at a loss. Especially since it works fine on a iPhone 5s. And to answer my own question, I was able to get it working, with the help of the KickassTwitter Xamarin example by thewissen Basically, I had to use the custom renderer provided in that example to make the image show up. In case it helps others: `[assembly: ExportRenderer(typeof(ToolbarItem), typeof(UntintedToolbarItemRenderer))] namespace StudyHerdMobile.iOS.CustomControls { public class UntintedToolbarItemRenderer : too { public override void ViewDidLoad() { base.ViewDidLoad(); }`
https://forums.xamarin.com/discussion/comment/139141/
CC-MAIN-2020-05
refinedweb
685
73.68
Opened 7 years ago Closed 7 years ago Last modified 6 years ago #4877 closed bug (fixed) Template Haskell panic when splicing an infix expression with a non-variable middle bit Description Simple enough: import Language.Haskell.TH import Language.Haskell.TH.Syntax panic = $(let var = varE . mkName in infixApp (var "x") (appE (var "f") (var "y")) (var "z")) [1 of 1] Compiling Panic ( Panic.hs, interpreted ) ghc: panic! (the 'impossible' happened) (GHC version 7.0.1 for i386-unknown-linux): rnExpr: unexpected expression {6:11-92} f{v} y{v} x{v} z{v} Please report this as a GHC bug: Of course the expression being spliced doesn't make any sense. In fact, I'd think that the only things that make sense in the centre of an infix expression were a single variable or constructor, so that field being of type Exp is arguably way too permissiveP. haskell-src seems to have a data type especially for this purpose - HsQOp with constructors HsQVarOp HsQName and HsQConOp HsQName. Change History (7) comment:1 Changed 7 years ago by comment:2 Changed 7 years ago by comment:3 Changed 7 years ago by This shouldn't crash, I agree. This fixes it Wed Jan 12 17:07:19 GMT 2011 simonpj@microsoft.com * Produce an error message, not a crash, for HsOpApp with non-var operator Fixes Trac #4877. M ./compiler/rename/RnExpr.lhs -2 +6 But you're right that TH.Syntax should really only allow a variable there. I'll add it to the list on Template Haskell Proposal comment:4 Changed 7 years ago by Merged comment:5 Changed 6 years ago by The error message that was added was "Operator application with a non-variable operator" - I got that error message and was very confused (I resorted to reading the source code to figure out what it meant). I think it would be far clearer if it read "Infix application with a non-variable operator" - OpApp is an internal GHC detail which users of Template Haskell aren't aware of - they will have written InfixE. comment:6 Changed 6 years ago by OK I changed the error message as Neil suggests, to read: Infix application with a non-variable operator: <blah> comment:7 Changed 6 years ago by commit 9fc03d37c67098ab9dfa9403ff2c94e640074a76 Author: Simon Peyton Jones <simonpj@microsoft.com> Date: Tue Oct 4 09:26:11 2011 +0100 Change error message slightly in response to Neil's suggestion on Trac #4877 compiler/rename/RnExpr.lhs | 2 +- 1 files changed, 1 insertions(+), 1 deletions(-) Thanks for the report.
https://ghc.haskell.org/trac/ghc/ticket/4877
CC-MAIN-2018-13
refinedweb
430
59.74
I am trying to return a List(Of T) from a function, as follows: Public Class Observers Private Structure Observer Dim Name As String Dim ObsLat As Double Dim ObsLong As Double Dim ObsElev As Integer Dim UTCOffset As Int16 Dim ObsDst As Boolean Dim ObsEmail As String End Structure Public Function loadObservers() As List(Of Observer) 'Error here. Observer is highlighted Dim sr As New StreamReader("Observers.txt") Dim obslist As New List(Of Observer) Dim obsdata As New Observer If File.Exists("Observers.txt") Then Dim s() As String Do s = Split(sr.ReadLine(), ",") obsdata.Name = s(0).Trim obsdata.ObsLat = CDbl(s(1)) obsdata.ObsLong = CDbl(s(2)) obsdata.ObsElev = CInt(s(3)) obsdata.UTCOffset = CShort(s(4)) obsdata.ObsDst = CBool(s(5)) obsdata.ObsEmail = s(6).Trim obslist.Add(obsdata) Loop Until sr.Peek = -1 End If loadObservers = obslist End Function End Class I get an error in the Function Declaration. List(Of Observer). Observer is highlighted, and the errors read: error BC36666: 'SatTransNew.Observers.Public Function loadObservers() As System.Collections.Generic.List(Of Observers.Observer)' is not accessible in this context because the return type is not accessible. error BC30508: 'loadObservers' cannot expose type 'Observer' in namespace 'SatTransNew' through class 'Observers'. I tried moving the Dim obslist As New List(Of Observer) outside the function, but it didn't help. Is it possible to Return a List(Of T), or should I go with an array? Edit: I just tried making the Structure declaration Publlic, and it now compiles. Is that the answer? I was going to keep that private, though thinking about it, I can't see why it matters.\ This post has been edited by lar3ry: 20 November 2012 - 01:44 PM
http://www.dreamincode.net/forums/topic/301000-how-can-i-return-a-listof-t-from-a-function/page__p__1750975
CC-MAIN-2016-07
refinedweb
289
51.34
SJCP Exam Preparation: Language Fundamentals, Part 1 ObjectivesYou are going to be asked to answer questions in the exam regarding the following subjects. So be sure that you understand everything. After reading each article I suggest you write and compile small Java programs. I believe that practice is always better than theory. At the exam, you will be asked to address the following topics[2]. - Identify correctly the construction of a java source file - package declaration - Importing classes, and the declaration of import statements - class declarations - interface declarations - Constructor declarations - Method declarations - main() method and correspondence between the index values and arguments passed to the main() method If you have any questions after studying this document, do not hesitate to drop me an e-mail, and I will try to clarify things as best as I can. You can read more information about SJCP certification from the SJCP Web page [2] and you can download the .pdf file called Sun Certified Programmer for Java 2 Platform Success Guide [3]. The Structure of Java Source Files A java source file consists of class or interface declarations. Every source file has a .java extension and a file name in the form filename.java. After compilation, a valid java byte code file has a .class extension and a file name in the form filename.class. A Java source file can be compiled by the javac executable utililty, to compile a java source file you must use "javac filename.java" command. If there are no compile time errors then a java executable file will be created. The name of this newly created file will be filename.class. This is a Java executable file. We can run this file by typing "java filename.class" in the command prompt. The extension of the source file changes after compilation of a source file but the filename remains the same. There is a correlation between the file name and class names inside the java source file. If there is a class or interface declared as public, then the name of the java source file must match the class or the interface name which has been declared as public. What you should bear in mind is the public accessibility modifier. If the source file doesn't contain any public class or interface then the compiler will not complain. In this case, the file can be given a name which is different from the class or interface name declared inside the source file. Please note, the file name given should have some relevance to whatever the classes function is. We have seen two possible cases for source code declaration. What if we have two or more class declarations in a source file? How should we name the source file in this case? Lets remember the previous rule. If a class declaration has a public accessibility modifier then the name of the source file must match the public class name. This is the only rule that we must bear in mind. The file name of the source code can be anything, if there is no public class declaration at all. This means that we can have more than one class defined in a source file. Because they are not declared as public, we don't care about the class name and the file name. So what if we have a source file which has more than one public class declaration? According to the rule, the file name must match the name of the public class declaration. Because there are more than one public class declarations, the compiler will complain and throw up a compile time exception. There can only be at the most one public class declaration in a source file. A source file cannot have more then one public class declaration. At most only one public class declaration is allowed per source file and the name of the source file must match this public class declaration name. If the accessibility modifier is not declared, which means default accessibility, then any number of classes can be declared in a source file. In this case there is no relation between the name of the source file and the name of the classes. Besides that, it is not allowed to define more than one class, which has the same name, in a source file. The names must be unique or else each class must be declared in a different package. There can be at the most only one public class declaration in a source file. If there is a public class declaration inside the source file then the name of that class must match the name of the source file. A valid Java source code, compilation unit, can have three basic elements. None of these elements are mandatory. The compiler will not complain even if there is an empty source file. But if they are present they must be in the following order. - A package declaration (you can only have one package declaration) - import declarations - class or interface declarations The compiler will complain if the order is not correct. For example, for the following code snippet the compiler will throw a compile time error because the package and import statements are present, but they are not in the correct order thus - package->import(s)->class(es)/interface(s). Declaration of package Packages are used as a naming organization unit. They don't have any relationship to the scope of the variables in the source code. If a package statement is used in a source file, compilation of that source file will create a directory structure that is similar to the package structure. For example, compilation of the following code will create the Flower.class file at the end of the directory structure "com/earthweb/certification". As we can see the directory structure is the same as the package naming structure. There can be at most only one package declaration per source file and if a package name is used it must be the first statement in the source code. Importing classes, and declaration of import statement An import declaration is the first declaration following the package declaration. Contrary to packages, there can be more than one import statement. If there is no package declaration then the import statements can be the first statement(s) in a source file. The compiler ignores duplicate imports. If we import java.util.Date twice the compiler will simply import one and ignore any others. The Java compiler imports java.lang.* package by default. For this reason, there is no need to declare the statement in order to use java.lang.System, java.lang.Math, java.lang.Thread classes which are included in the java.lang.* package. Any classes which fall under the java.lang.* package can be used without declaring the import statement. Note, importing a package does not import sub packages recursively. Importing java.* does not mean that we also import java.util.*. Declaration of class or interface They are called as a top-level class or interface. A top-level class is a class whose declaration is not enclosed by another class. The file name of this source code must be Car.java because, as I am sure you remember from the rule, it is declared as public and the class name must match the file name. Inside of a class we have member methods and member variables. The following code snippets show the use of member variables and member methods. Interfaces only have method names without any implementation of those methods. The following code shows a simple interface declaration. When does a compiler error occur? The compiler will throw a compile time error if a class is imported twice by using its exact name with its package structure. To get rid of this problem, the whole package can be imported instead of the exact class name. The following code snippet shows the solution to the problem. Declaration of a class, which has the same name as the imported class, will cause a compile time error. It is not allowed to use the same class name as the name of the imported class. Declaration of a Class/Interface In a class declaration, there can be member variables, constructors, method declarations & implementations. Multiple inheritance is not allowed in java. For that reason, you can not extend multiple classes. You can only implement multiple interfaces. The general syntax for a class declaration is as follows. A simple example for a sports car class which extends the car class is shown below. Multiple inheritance is not allowed in Java. Since multiple inheritance is not allowed in java, doing so will cause the compiler to throw a compile time error. Contrary to that, Java allows for the implementation of multiple interfaces. As shown in the following code snippet car class implements engine and sports wheels interfaces. It is not mandatory to declare an access modifier. If we do not define any access modifier, this means the default access will be applied. The modifiers are shown below. These modifiers don't suit every case. There are some special conditions for use of these modifiers. As an example, you can not use private, as a top-level class modifier. You can only use the public modifier or no modifier (default access) for this top-level class declaration. The private and the public modifiers can only be used by the member classes. You can read the SCJPE Preparation series Top-level and Inner Classes section to learn more about this topic. An interface declaration may seem like a class declaration. The difference being, an interface can not have a method implementation. They can only have method names and member variables. An interface can extend multiple interfaces. The general syntax of an interface is shown below. I will mention the details of a class, an abstract class and an interface in the following chapters. Here is an example of an interface declaration Method declarations The general structure of a method inside a class is as follows. Methods defined inside classes may have implementations. For example, we have an implementation for the move method of the Car class as follows For interfaces, we can not define method bodies. Interfaces are only to define method signatures as shown below Constructor declarations Inside of the class body we have constructors, variables and method declarations. The syntax of a constructor declaration is like this. As you can see from the above syntax a constructor can never have a return type. Besides that, only the following modifiers can be used as a valid modifier for constructors. The following code snippet shows a class with a valid constructor. An interface can not have a constructor because an interface does not provide the facility for implementations. For that reason, trying to compile the following will cause an error. The main() method Every Java application must have a main() method. The structure of Applets and Servlets are different, for this reason they have special mechanisms to execute the code and they don't need a main() method in order to do this. The structure of the main() method is shown below We can define the argument in various different ways and they are all acceptable with the exception of the last. The signature of the main() method must be the same. Basically the main() method must have a string array argument, must return void , it must be static and have a public modifier. Since main() is a method, you can inherit the main() method. It acts like other methods. The following examples illustrates valid and invalid definitions of the main() method. The main() method can take a string array as an argument. This argument gives us commands entered at the command prompt. For example, we have the given arguments to the Game application at command prompt. We can get the number of arguments by args.length. The first arguments is the first element of the args[] array, which is args[0]. For the previous example args[0] will return param1. It will not return the program name or something else. It will return the first parameter param1. Questions 1.) Which of the following are legal Java programs. Select all the correct answer. a.)// The comments come before the package package com.gamelan.certification; import java.util.*; b.)import java.util.*; package com.gamelan.certification; class Game(); c.)package com.gamelan.certification; import java.util.*; d.)package com.gamelan.certification; package com.gamelan.certification; import java.util.*; class Game(); e.)package com.gamelan.certification; class Game{}; f.)import java.util.*; class Game{}; 2.) Which of the following statements are correct. Select all correct answers. a.) A Java program must have a package statement. b.) A package statement if present must be the first statement of the program c.) An empty file is a valid source file. d.) A Java file without any class or interface definitions can also be compiled. e.) If an import statement is present, it must appear before any class or interface definitions. 3.) Which of these are valid declarations for the main method? Select all correct answers. a.) public static void main(); b.) public static void main(String args[]); c.) static public void main(String); d.) public static char main(String args[]); 4.) What gets printed on the standard output when the class below is compiled and executed by entering "gamelan is the best java source". public class test { public static void main(String args[]) { System.out.println(args.length+" "+args[0]+" "+args[args.length-1]); } } a.) The program will print "5 gamelan java" b.) The program will print "6 gamelan java" c.) The program will throw an exception. d.) The program will print "5 gamelan source" e.) The program will print "6 gamelan source" f.) The program will compile without an exception and will not print anything. Answers I suggest you compile and try other possible combinations by yourself. Practical work is important for the exam. Instead of just looking at the answers try to compile code and learn from the results you receive. 1.) a,c,e,f 2.) b,c,d,e 3.) b 4.) e About the AuthorKoray Guclu works as a freelance writer and software developer. You can reach him at korayguclu@yahoo.com. His Web site is.
http://www.developer.com/java/other/article.php/947391/SJCP-Exam-Preparation-Language-Fundamentals-Part-1.htm
CC-MAIN-2014-10
refinedweb
2,385
66.84
Learn how to build your first Laravel application and add authentication to it. TL;DR: Laravel is a great PHP framework. Currently, it is the most starred PHP project on Github and a lot of companies and people all over the world use it to build amazing applications. In this tutorial, I'll show you how easy it is to build a web application with Laravel and add authentication to it without breaking a sweat. Check out the repo to get the code. Laravel is a free, open-source PHP framework designed for building web applications with an expressive and elegant syntax. Laravel has a high level of abstraction which shields the common developer from complex inner workings. Laravel saves you time and effort because it ships with a lot of features out of the box. These amazing features include: - Database Migrations - Eloquent ORM - Authorization and Policies - Scheduler - Queuing Laravel did not attempt to rewrite a lot of its functionality from scratch, it makes good use of already written and well tested components from the PHP community. Laravel is one of the few frameworks that actually comes with development environments such as Homestead and Valet. The documentation is very detailed and there is a large community based around Laravel. Some of the notable communities are laracasts.com, larajobs.com, laravel-news.com, laravelpodcast.com and larachat.co. "Laravel is one of the few frameworks that actually comes with development environments such as Homestead" TWEET THIS Laravel is currently at version 5.2. Laravel 5.3 is currently in development and is due for release this month. Here is a quick look at some of these new features: - Laravel Echo - I'm actually looking forward to this. It will make building realtime apps with Laravel very painless - Ability to rollback one migration like so php artisan migrate:rollback --step-1 - The Blade foreach/forelse loops now gives you access to a $loopvariable to easily determine first and last iterations - Eloquent collections are cleanly serialized and re-pulled by queued jobs - Queue console output now shows the actual class names - Ability to customize simple paginations in your views - Ability to pass additional values to firstOrCreate Model method - Query Builder will return collections instead of arrays - Ability to load your own migration paths from a service provider We'll be building a simple character listing app with Laravel 5.2. Our app will simply list 10 Game of Thrones characters and their real names. Once we add authentication to the app, all logged-in users will have the privilege of knowing these celebrity characters personally. Let's get started Laravel utilizes Composer to manage its dependencies. So, before using Laravel, make sure you have Composer installed on your machine. We can install Laravel by issuing the Composer create-project command in your terminal like so: composer create-project --prefer-dist laravel/laravel GOT or using the laravel installer. It's actually faster to spin up a new app using the laravel command like so: laravel new GOT . Check out the Laravel docs to learn how to set up the laravel installer. If you used the laravel installer command to create a new app, then you have to run composer install immediately after the previous command to install all the dependencies. Explore Directory Structure Laravel applications follow the Model-View-Controller design pattern. (Source: Self Taught Coders) In a nutshell, - Models query your database and returns the necessary data. - Views are pages that render data - Controllers handle user requests, retrieve data from the Models and pass them unto the views. Read more about MVC here. The app directory is the meat of your Laravel application. It houses the following directories: Console- Contains all your Artisan commands Http- Contains all your controllers, middleware, requests and routes file Providers- Contains all your application service providers. You can read more about Service Providers here Events- Contains all your event classes. Exceptions- Contains your application exception handler and custom exception classes. Jobs- Contains all the jobs queued by your application Listeners- Contains all the handler classes for your events. Policies- Contains the authorization policy classes for your application. Policies are used to determine if a user can perform a given action against a resource. The other directories namely: boostrapcontains your framework autoloading files and generated cache files configcontains your app's configuration files. databasecontains your database migrations and seeds. publiccontains your assets(images, JavaScript, css etc). resourcescontains your views and localization files. storagecontains all your compiled Blade templates, file caches and logs. testscontains all your tests. vendorcontains your app dependencies. Setting Up The Controller Open up your terminal and run the command below to create a ListController. php artisan make:controller ListController Open up app/Http/Controllers/ListController.php and configure it like so: <?php namespace App\Http\Controllers; class ListController extends Controller { public function show() { $characters = [ 'Daenerys Targaryen' => 'Emilia Clarke', 'Jon Snow' => 'Kit Harington', 'Arya Stark' => 'Maisie Williams', 'Melisandre' => 'Carice van Houten', 'Khal Drogo' => 'Jason Momoa', 'Tyrion Lannister' => 'Peter Dinklage', 'Ramsay Bolton' => 'Iwan Rheon', 'Petyr Baelish' => 'Aidan Gillen', 'Brienne of Tarth' => 'Gwendoline Christie', 'Lord Varys' => 'Conleth Hill' ]; return view('welcome')->withCharacters($characters); } } view('welcome')->withCharacters($characters) indicates that we are passing the $characters array to a view called welcome.blade.php. We'll create that view in the later part of this post. Setting Up The Model Laravel Models are stored by default in the root of the app directory. The User model ships with the Laravel framework. Only the User model is needed in this application so we won't create any additional models. However, if you want to create more models, you can simply run the command below like so: php artisan make:model <modelName> where <modelName> represents the name of the Model you want to create. Setting Up The Routes Open up app/Http/routes.php and configure it like so: /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the controller to call when that URI is requested. | */ Route::get('/', 'ListController@show'); Once a request hits the / route, it invokes the show method of the ListController and renders the returned value in the welcome view. We'll configure the welcome view later in this post. Setting Up Authentication One fascinating thing about Laravel is that it comes with authentication out of the box. You just have to configure it. Next, open up your terminal and run this command like so: php artisan make:auth Be careful enough to only do this on fresh applications. As you can see, some files have been copied into our application, the routes have also been updated. The route file has been populated with additional information like so: Route::auth() is a method that cleanly encapsulates all the login and register routes. Now, the views needed for authentication are in the resources/views/auth directory. The base layout for our application has also been configured in the resources/views/layouts directory. All of these views use the Bootstrap CSS framework, but you are free to customize them however you wish. Open up your welcome.blade.php and configure it like so: @extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-10 col-md-offset-1"> <div class="panel panel-success"> <div class="panel-heading">List of Game of Thrones Characters</div> @if(Auth::check()) <!-- Table --> <table class="table"> <tr> <th>Character</th> <th>Real Name</th> </tr> @foreach($characters as $key => $value) <tr> <td>{{ $key }}</td><td>{{ $value }}</td> </tr> @endforeach </table> @endif </div> @if(Auth::guest()) <a href="/login" class="btn btn-info"> You need to login to see the list 😜😜 >></a> @endif </div> </div> </div> @endsection Here, we are looping through the $characters array data passed from the ListController for appropriate rendering in the welcome view. Auth::check() - You can check if a user is authenticated or not via this method from the Auth Facade. It returns true if a user is logged-in and false if a user is not. Check here to know how Facades work in Laravel. Auth::guest() - This does the opposite of Auth::check(). It returns true if a user is not logged-in and false if a user is logged-in. Check here to see all the methods you can call on the Auth Facade. Now that we have all the routes and views setup, your application should look like this: Landing Page Login Page Register Page Run Migrations Migrations are like version control for your database, allowing a team to easily modify and share the application's database schema. In Laravel, they are placed in the database/migrations directory. Each migration file name contains a timestamp which allows Laravel to determine the order of the migrations. Luckily for us, the user migration files comes by default with a fresh Laravel install. Check the database/migrations directory to ensure you have at least two migration files named xxx_create_users_table.php and xxx_create_password_resets_table.php where xxx represents the timestamp. Now, run this command from your terminal: php artisan migrate The users and password_resets table will be created on running this command. Ensure the appropriate database name has been set in your .env file. The value should be assigned to this DB_DATABASE constant. Path Customization Open up AuthController.php in app/Http/Controllers/Auth directory. There is a $redirectTo variable like so: /** * Where to redirect users after login / registration. * * @var string */ protected $redirectTo = '/'; It can be configured to whatever route you want the user to be redirected to just after registration or login. In our case, the user should be redirected to the landing page, so we don't need to change anything. Now, go ahead and register. It should register you successfully and log you in like so: Using the Auth Middleware Middlewares. The app/Http/Middleware directory contains several middleware. Let's check out how the auth middleware works. Add a new route to your routes.php file like so: Route::get('/got', [ 'middleware' => ['auth'], 'uses' => function () { echo "You are allowed to view this page!"; }]); Now, log out, then try to access that route, you will be redirected back to the /login route. The Laravel auth middleware intercepted the request, checked if the user was logged-in, discovered that the user was not logged-in, then redirected the user back to the login page. Aside: Using Auth0 with Laravel Laravel apps with Auth0's Login Page. If you don't already have an Auth0 account, sign up for one now. Navigate to the Auth0 management dashboard, select Applications from the navigational menu, then select the app you want to connect with Laravel. Step 1: Install and Configure Auth0 plugin Follow the instructions here to configure the Auth0 plugin. Step 2: Register the callback Head over to your Auth0 dashboard and register Allowed Callback URLs, Allowed Logout URLs. Open up your routes and add this: Route::get('/auth0/callback', '\Auth0\Login\Auth0Controller@callback'); Step 3: Include the Auth0 Login Page Open up welcome.blade.php and configure it like so: @extends('layouts.app') @section('content') @if(Auth::guest()) <a href="/auth0/login" class="btn btn-primary">login</a> @endif @endsection When the login button is clicked, users are redirected to Auth0's Login Page. Step 4: Configure Routes.php Add this to your routes.php file: Route::get('/auth0/login', function() { $domain = env('AUTH0_DOMAIN'); $clientId = env('AUTH0_CLIENT_ID'); $redirectUri = env('AUTH0_CALLBACK_URL'); $authorizeUrl = sprintf( '', $domain, $clientId, $redirectUri); return redirect($authorizeUrl); }); Now, once a user registers, it stores the user information in your Auth0 dashboard. We can retrieve this info using the Auth0::getUser() method. We can also hook onto the onLogin event using Auth0::onLogin(function(...)). Access can be restricted with Auth0 Middleware, just add this 'auth0.jwt' => 'Auth0\Login\Middleware\Auth0JWTMiddleware' in the $routeMiddleware array in app/Http/Kernel.php. Then use auth0.jwt middleware on your routes. With Auth0, you can have all your users' information stored without having to run your own database. Auth0 provides powerful analytics about users signing up on your platform such as the browser the user logged in with, the location, device, number of logins and more, out of the box! Important API Security Note: If you want to use Auth0 authentication to authorize API requests, note that you'll need to use a different flow depending on your use case. Auth0 idToken should only be used on the client-side. Access tokens should be used to authorize APIs. You can read more about making API calls with Auth0 here. Wrapping Up Well done! You have just built your first app with Laravel. Laravel is an awesome framework to work with. It focuses on simplicity, clarity and getting work done. As we saw in this tutorial, you can easily add authentication to your Laravel apps. This is designed to help you get started on building your own apps with Laravel. You can leverage the knowledge gained here to build bigger and better apps. Please, let me know if you have any questions or observations in the comment section. 😊
https://auth0.com/blog/creating-your-first-laravel-app-and-adding-authentication/
CC-MAIN-2018-47
refinedweb
2,189
55.64
08 April 2005 12:15 [Source: ICIS news] ?xml:namespace> Givaudan, which does not disclose quarterly earnings, said that the fall in revenues compared with the same quarter of 2004 was due to the strong comparable performance last year, lower prices for some natural raw materials and the streamlining of non-core ingredients. Despite a “challenging” first quarter performance, the company is confident that it can “deliver another good result for 2005”, it said in a statement. The fragrances division achieved Q1 sales of SF273.1m, up 0.8% in local currencies and down 1.9% in Swiss francs. Fine fragrances sales were lower year-on-year due in part to several postponed launches. ?xml:namespace> The company said that the European fine fragrance markets had performed below Q1 2004 levels, reflecting destocking of distribution channels and slow consumer demand. North American sales were “sluggish” compared with the same period last year. Consumer products maintained good sales growth in all regions, especially In fragrance ingredients, Givaudan said sales of specialties continued to grow at double digit rates in Q1 2005. Growth is expected to continue in specialty sales, while commodity ingredients will decline further. Sales in the flavour division in Q1 2005 were SF395.6m – down 6.5% in Swiss francs and 3.2% in local currencies. Sales were affected by lower prices for naturals, such as citrus and vanilla, and the streamlining of non-core savoury ingredients relating to the Food Ingredients Specialities portfolio acquired from Nestle in 2002. Sales in Asia-Pacific sales were up strongly on Q1 2004, especially in
http://www.icis.com/Articles/2005/04/08/667399/swiss-givaudans-q1-05-sales-drop-4.7-to-sf668.7m.html
CC-MAIN-2013-48
refinedweb
263
57.47
Real Objects vs. Data Containers Real Objects vs. Data Containers This take on objects and object-oriented programming suggests converting data containers and structures into real objects, then tackles the performance issues involved. Join the DZone community and get the full member experience.Join For Free Delivering modern software? Atomist automates your software delivery experience. After more than three years of working as backend (and mobile) programmer, mostly in the Java Virtual Machine ecosystem, I have realized that no one of those procedural MVC/MVP/MVVM patterns has made me feel comfortable when implementing new features or big changes in a project. Also, ER-ending classes (Controller, Manager, Helper, etc.), which are well-accepted and used in many frameworks, don’t help with that either: they will get bigger and bigger, and you will have to segregate them without any logical criteria. And when that happens, you’re screwed. Maintainability becomes really hard. In the last few months, I have been heavily influenced by Yegor Bugayenko and what he claims is “pure” object-oriented programming. Instead of treating objects as simple (and silly) data containers/data structures, we should give them the power and trust them. Convert them into real objects. Can you see any difference between this Java code: public class User { private String id; private String username; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } } And this C code: struct User{ char id[50]; char username[50]; }; Not at all. Because there is none. However, we write objects like above and are convinced we are object-oriented developers. But we aren’t. We must think of objects as something more than simple in-memory data structures exposing its state to everybody. Objects should wrap its real-life representation. Let’s say we need to write a class File (in Java) with a method, content(), that returns its content in a byte array. A first implementation could be something like this: public class File { private String path; private byte[] content; public File(String path, byte[] content) { this.path = path; this.content = content; } //getters and setters } public class FileSystem { public byte[] getFileContent(String path) { return /* read file bytes from disk */; } } And we would use it this way: FileSystem fs = new FileSystem(); String path = "/tmp/conf.xml"; File confFile = new File(path, fs.getFileContent(path)); Done. To be honest, I think this implementation is a mess. Don’t you? If we change the content of file /tmp/conf.xml, the configFile object becomes inconsistent. The File class is not representing a real file, but a bunch of bytes. It has been reduced to a data container. A C struct. It can’t be considered an object at all. This is a nice implementation for the same class: public interface File { byte[] content(); } public final class FileSystemFile implements File { private final String path; public FileSystemFile(String path) { this.path = path; } @Override public byte[] content() { return /* read file bytes from disk */; } } And we use it this way: File confFile = new FileSystemFile("/tmp/conf.xml"); Much better, right? Now, configFile is a real object. We have converted Filetype in an interface. This way, we can have more implementations like RemoteFile, if needed. You may think that this implementation is not efficient because each time we call the content() method, a disk read is performed. It may be slow, depending on the system and the application requirements. You are right. So now, object composition and the decorator design pattern come into action. We are going to create a class, CachedFile, that wraps a File and caches its content, so just one disk read will be performed: public final class CachedFile implements File { private final File origin; private byte[] cached; public CachedFile(File origin) { this.origin = origin; this.cached = null; } @Override public byte[] content() { if (this.cached == null) { this.cached = origin.content(); //real disk read } return this.cached; } } (This is a very naive cache implementation. Also, you must never use null. I did it just for the example.) And we use it this way: File confFile = new CachedFile(new FileSystemFile("/tmp/conf.xml")); It looks great for me! What if I tell you that this approach can be applied to database objects, too? Let’s go back to the User example. A real, stored in-database User would look like this: public interface User { public String id(); public String username(); } public DatabaseUser implements User { private final String id; private final Database db; public DatabaseUser(String id) { this.id = id; this.db = db; } @Override public String id() { return this.id; } @Override public String username() { return /* SELECT username FROM users WHERE id = this.id */; } } Now, a User is not just a bunch of data. Its state is not being exposed. It is a real object. Again, we can “decorate” it with a cache or whatever we want for throughput optimization. If you liked it this approach of OOP, I strongly recommend you to read Yegor’s posts and his book Elegant Objects. Start automating your delivery right there on your own laptop, today! Get the open source Atomist Software Delivery Machine. Published at DZone with permission of Héctor Valls . 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/oop-real-objects-vs-data-containers?fromrel=true
CC-MAIN-2019-09
refinedweb
894
59.5
IntroductionBackgroundThe TimerTest ProgramResultsConclusions and Comments IntroductionBackgroundThe TimerTest ProgramResultsConclusions and Comments This article collects and analyzes statistics of the Sleep function. The source files contain a console app that runs Sleep with multiple different delays, and with multiple numbers of concurrent threads, and analyzes the results. (see footnote 1) Sleep I recently began some multithreaded projects and found myself using the Sleep function more than I had before. For example, I used Sleep(0) to relinquish the remainder of a thread's timeslice in situations where (on a single processor system) the thread needed a resource locked by another thread. In such situations, there is no real point in continuing the thread, which might as well let other threads run (including the thread that locked the resource) in hopes of getting the resource sooner. (see footnote 2) As another example, I used Sleep with a calculated short delay time, to throttle back on the number of messages being sent by a worker thread to the main thread. Without throttling, too many messages were being sent too quickly, which prevented the main thread from responding to mouse and user input (which, of course, was the entire point in opening a worker thread): Sleep(0) //... in a loop that gets a current line of text (CString tsCurLine) //... uses GetTickCount() to find dwElapsedMilliSec dwMessagesPerSec = 1000*(++dwTotalMessagesPosted)/dwElapsedMilliSec; if (dwMessagesPerSec > dwMaxMessagesPerSec) Sleep( (DWORD)(1000*dwTotalMessagesPosted/dwMaxMessagesPerSec<BR> - dwElapsedMilliSec) ); // // OK, we've waited long enough, so allocate memory for CString and <BR>// post it to main thread Main thread is responsible for deleting memory <BR>//allocation CString* s = new CString (tsCurLine); ::PostMessage(hMainWnd, USER_MESS_ADDITEM, (WPARAM) s, (LPARAM) m_pDoc); // ... continue Everything worked just fine, but in the back of my mind I remembered all those warnings about the granularity and inaccuracy of the various Windows timer functions. Joseph M. Newcomer, in his article entitled "Time Is The Simplest Thing..." provides a great summary of these inaccuracies, and basically advises not to rely on any accuracy at all, and to expect a granularity of around 55 milliSeconds for Win 9x, and a granularity of around 10 milliSeconds for Win NT. So, just what was happening when I called Sleep? I wrote a console application that lets you enter the number of threads to open, and then puts the Sleep function through its paces. Each of 14 different time intervals were tested, ranging in geometrically-spaced increments from Sleep(0) to Sleep(1000). For each time interval, 50 iterations were performed, and statistics collected for each. Sleep(1000) To measure the time interval accurately, I created a CStopWatch class that uses the system performance counter to measure time intervals with sub-milliSecond accuracy. A first version of TimerTest used GetTickCount to measure time, but I grew nervous that my results were corrupted by the inherent inaccuracy of GetTickCount. Later testing showed that the results were virtually the same, and that GetTickCount actually returns accurate times down to 1 msec accuracy. CStopWatch GetTickCount CStopWatch is borrowed heavily from Laurent Guinnard's CDuration class described in his article entitled "Precise Duration Measurement". (see footnote 3) Here are the function declarations; all functions are implemented inline: CDuration class CStopWatch { public: CStopWatch(); virtual ~CStopWatch(); void Start(void); void Stop(void); DWORD GetLapTime() const; // in whole microseconds (less than 214 secs) // -- stopwatch keeps running DWORD GetInterval() const; // in whole microseconds (less than 214 secs) // -- must call Stop() first, or returns zero LONGLONG GetLapTimeLongLong() const; // in whole microseconds -- <BR> // stopwatch keeps running LONGLONG GetIntervalLongLong() const; // in whole microseconds // -- must call Stop() first, or returns zero protected: LARGE_INTEGER m_liStart; LARGE_INTEGER m_liStop; LONGLONG m_llFrequency; }; In the TimerTest program, I allow the user to select the number of threads to open, and the selected number of threads are then started: do{ cout<<"Enter the number of threads (0-5)" << endl; cin>>nThreads; } while ( nThreads>5 || nThreads<0 ); HANDLE hThread; for (kk=1; kk<=nThreads; kk++) { hThread = ::CreateThread(NULL, 0, ThreadFunc, (LPVOID)kk, NULL, &dwID); ::WaitForInputIdle(hThread, INFINITE); } The thread function itself performs mindless work: it simply counts an integer up to nearly its maximum value and then starts over, until a global variable g_bAbort is set to False by the console application: g_bAbort DWORD WINAPI ThreadFunc (LPVOID pvParam) { // a make-work thread -- endlessly performs mindless make-work DWORD dwThreadNum = (DWORD) pvParam; int ii = 0; while ( !g_bAbort ) { ii++; if (ii >= 0x40000000) ii=0; } return (0); } After all requested threads are up and running, the TimerTest program enters its main loop where it exercises the Sleep function. While in the loop, detailed results are written in comma-separated format to a .txt file on the desktop, which later can be opened in Excel to graph and otherwise analyze the results. In addition, the program keeps track of statistics on its own, which it displays to the user as shown in the screen shot above: for ( ii=0; ii<=13; ii++) { s = ss = 0.0; for ( jj=1; jj<=iter; jj++) // iter is nominally set to 50 above the loop { StopWatch.Start(); ::Sleep(stime[ii]); StopWatch.Stop(); interval = StopWatch.GetInterval()/1000.0; // convert to millisecs s = s + interval; ss = ss + interval*interval; oFile << stime[ii] << ", " << interval << endl; } mean = double(s)/double(iter); stdev = sqrt(double(iter*ss - s*s))/double(iter); printf("Sleep = %4d: mean = %8.3f, std dev = %6.3f\n", stime[ii], mean, <BR> stdev); } I ran TimerTest with each of zero to five threads and collected the results into an Excel file that's included with the source files. I also used Excel to graph the results and the graphs are included below. I ran these tests on an older machine: 500 mHz Pentium III, 196 meg ram, Win98SE. A few other programs were running at the same time as the tests. Most notably, since the computer serves as an Internet gateway for our home network, the computer was running the "Personal Web Server" and Internet Connection Sharing (ICS). So, the computer was only moderately stressed. Many of the results were unexpected (at least by me). Let's dive in. The following two tables show the overall statistics of my results. The first table shows the mean (or average) value actually obtained for sleep time, as a function of the requested sleep time and the number of threads. The requested sleep time is in the column all the way on the left, and the mean sleep time actually obtained over the 50 tests is shown in the successive columns under the number of threads that were running. The second table shows the standard deviation (or spread) of the actual sleep times, organized the same way (i.e., requested sleep time in the column on the left, and spread of the actually-received sleep times in successive columns under the number of other threads running). These tables tell a lot about the overall statistics of Sleep. The first thing you notice is that for requested values above around 200 msecs, Sleep does a good job on average in giving your program the amount of sleep requested. Below 200 msecs, Sleep consistently gives higher values of sleep; for one or no threads, Sleep has difficulty giving less than around 9 msecs of sleep, no matter what was requested. For two or more threads, Sleep rarely gives less than 20 msecs of sleep. As might be expected, the best results are obtained when there are no other threads running. Sleep is most consistent then (lowest values for standard deviation), and is able to match the requested amount of sleep most accurately (i.e., the mean matches the requested value of sleep). For one or more threads, Sleep doesn't exactly fall apart, but it's clearly inconsistent (high values for the standard deviation) and it's only at the highest values for requested sleep that you get anything resembling your request. Here's a more detailed discussion of three cases that seemed important: Sleep(0), results with no other threads running, and results with one or more threads running. First, while Sleep(0) performed mostly as expected, there were two notable exceptions (described below). For the most part, Sleep(0) indeed relinquished the remainder of the thread's time slice to another thread. Where there were no other threads, Sleep(0) returned after an extremely short time interval, typically 10-15 microSeconds. Where there were other threads, Sleep(0) didn't return for a much longer period, typically around 100-150 milliseconds, reflecting the fact that Windows didn't give the thread a new time slice for a while. Sleep(0) What were the exceptions? Well, where there no other threads, the first 5-7 calls to Sleep(0) (i.e., the first 5-7 calls in the loop of 50 calls) only returned after an unexpectedly long time of 100-200 milliSeconds. This effect was dramatic and repeatable, such that the statistics shown above exclude the first 5-7 call to Sleep(0). Here's a screen shot of a portion of the spreadsheet output of raw results. The requested Sleep time is in the first column all the way on the left; there are 50 entries for each Sleep time, corresponding to each of the 50 iterations (you can only see the first dozen or so iterations of Sleep(0) in this excerpt). Each column after the first shows the measured sleep time actually received depending on the number of extra threads. The odd behavior is circled in blue: I don't know why this occurred; if anyone has an explanation please post it. For practical programs that rely on Sleep(0), it might be advisable to call it a few times before getting to the real work of the program (although I'm not really sure why a program with no extra threads would ever need Sleep(0)). The second exception involved Sleep(0) where more than just one other thread was running. I expected Sleep(0) to return only after all the other threads had run. So, if the delay with one other thread running was 100 milliSeconds, I expected the delay for two other threads running to be about 200 milliSeconds. That's not what I got. Rather, the delay was remarkably consistent no matter how many other threads were running, and typically was about 110 milliseconds. You can see this behavior in the above excerpted screen shot. When there were no extra threads running, Sleep() did a remarkably good and consistent job at timing. The measured sleep time was extremely close to the requested sleep time (at least for times above around 10 msecs -- see below), and the measured time was remarkably consistent from one call to another. Here's a scatter chart of measured vs. actual sleep time, in a log-log format: For Sleep times below 10 msecs, the accuracy was not great, but the repeatability was. For Sleep below 10 msecs, Sleep consistently gave higher sleep times than requested, but did so with surprisingly good repeatability of about 1.0 to 1.5 msec (one sigma). Sleep When there were extra threads running, Sleep was all over the place. The scatter chart reflects this randomness: Unless you asked for more than about 200 msec of sleep, it was nearly impossible to rely on the amount of sleep actually given. Even at that level, Sleep yielded times that were completely inconsistent from one call to another, such that repeatability was a poor 20 to 25 msec (one sigma). In practical terms, allowing for a plus/minus three sigma variation, and remembering that Sleep almost never gives less than the requested time, that means you should expect an error of anywhere from +150 msecs to -0 msecs, for any one call to Sleep. If you string together many many Sleep's, your results on average will improve, but only slowly. For example, even after stringing together fifty calls to Sleep(1000) with four threads, you still end up with an average value of 1024.612 msecs, or a total elapsed time of 51.230 seconds, in a situation where you only expected 50.000 elapsed seconds (i.e., an overall error of over a second). Clearly, with many threads running, you can't rely on Sleep() if timing is critical. If average performance over the long haul is what you're after, then you might be able to rely on the Law Of Large Numbers to get acceptable performance. Roughly speaking, the Law Of Large Numbers states that performance tends towards the average over the long run. If we think Sleep behaves like a Guassian bell curve, then performance will tend toward the average as the square root of the number of calls. Taking 50 mSecs as an expected standard deviation (it's roughly the largest number in the table above), then you would need 2,500 calls to Sleep before you could expect sub-millisecond performance (on average). Although my results were analyzed extensively for only one machine, I ran TimerTest on a few different machines, with differing loads and with different OS's. (I tried it on Win 95 and Win ME machines, with different speeds and memories, and with diferent loads.) Results similar to those above were obtained, although I did not analyze them as extensively as above. So, given that the results seem to match the documentation, I think that the above results would also apply to you. Finally, here's a wrap-up of the major points in the article. SetTimer WM_TIMER 1. OK, there are at least two legitimate criticisms that can be leveled at this article. First, you might ask, "how in the world can he go on and on about such a mundane topic?" If that's your criticism, go for it!! And read my bio to find a clue into the reason for my verbosity ;) Second, and more seriously, this is a software site, and there's very little software in this article. Moreover, the little software given is not really reusable for your own projects. I recognize this, but felt that the results were interesting enough to justify posting anyway. (return to article) 2. See MSDN article entitled "Sleep" which states that Sleep(0) relinquishes the remainder of a thread's timeslice to another thread of equal or greater priority, or if no such thread exists then does nothing. (return to article) 3. I made one important modification for purposes of this project: I eliminated a call to Sleep(0) in the Start function, since this would cause a thread switch. In the context of the CDuration class, a thread switch was needed to ensure consistent timings, whereas here it would inject an element of predictability not found in real-world situations, hence yielding a poor simulation of them. (return to article) Start 4. The same is probably also true of other types of timers, such as waitable timers. Read Nemanja Trifunovic's article "Timers Tutorial" for a description of various timers available in Windows. (return
http://www.codeproject.com/Articles/3831/Quantifying-The-Accuracy-Of-Sleep?msg=483245
CC-MAIN-2013-48
refinedweb
2,492
58.62
Focus Events, Click Events, and Drag-and Drop in AJAX Using the GWT and Java By Richard G. Baldwin Java Programming Notes # 2556 Preface General Viewing tip Figures Listings Supplementary material General background information Focus events Click events Drag-and-drop Preview Discussion and sample code GwtApp016 - Focus events and click events GwtApp017 - Creating a custom button component GwtApp018 - Drag-and-drop on a custom button component Only half the story Run the program Summary What's next? Complete program listings Download Resources About the author Java Programming Notes # 2556 Historically, the development of Ajax web applications has been a complex process. This is due mainly to the requirement to learn and use a variety of technologies, such as HTML, JavaScript, XML, ASP.NET, Java servlets, various scripting languages, etc. Recently several products have emerged that make it possible to develop Ajax web applications using the Java development environment. Some use exclusively Java, while others use mainly Java. I have discussed several of these new programming environments in previous lessons in this series (see Resources). The Google Web Toolkit (GWT) One development environment that allows you to use mainly Java for the development of web applications is the Google Web Toolkit (GWT) (see Resources and Download), which is the primary topic of this tutorial lesson. Most of the client-side code for a GWT Ajax application can be written in Java. There is no requirement to write JavaScript code. Fourth in a series This is the fourth lesson in a series designed to help you learn how to use the GWT to create rich Ajax web applications. You will find links to the previous lessons in the series in the Resources section. Purpose of the tutorial The main purpose of the tutorial is to teach you how to write the Java code necessary to perform drag-and-drop operations in AJAX using the GWT and Java. In addition, I will teach you hot to use of the FocusListener and ClickListener interfaces. I recommend that you open another copy of this document in a separate browser window and use the following links to easily find and view the figures and listings while you are reading about them. You may also find it useful to open a third browser window at the Resources section near the end of the document. That will make it easy for you to open those resources when they are mentioned in the text. I recommend that you also study the other lessons in my extensive collection of online Java tutorials. You will find a consolidated index at. What is focus? No matter how many applications are running concurrently on a computer and no matter how many GUIs are showing on the desktop, only one component in one GUI belonging to one application can respond to the keyboard at any point in time. The component that can respond to keyboard input is said to have the focus. Focus event handling has a long history Focus events have been available in standard Java since at lease version 1.1 in 1997. With the release of J2SE version 1.4, Sun completely revamped the focus subsystem. Because they added a large number of new capabilities at that time, dealing with focus in standard Java became much more difficult with the release of J2SE version 1.4. Some resources on focus event handling For an explanation of what is currently possible and an indication of the complexity of the Focus subsystem in standard Java, see "The AWT Focus Subsystem" in Resources. For additional information on the use of the revamped focus subsystem in standard Java, see the following tutorials in Resources: Something a little less complicated For a somewhat less complex discussion of focus and the handling of focus events, see my early tutorial named "Event Handling in JDK 1.1, Requesting the Focus" in Resources. That early tutorial was published long before the release of the revamped focus subsystem in version 1.4. However, much of the material in that tutorial maps directly into the GWT focus subsystem, which is much simpler than the revamped focus subsystem in standard Java. The focus subsystem in the GWT looks a lot more like the early focus subsystem in standard Java than the revamped focus subsystem in J2SE v1.4. Handling focus events The programming process for handling focus events in the GWT is essentially the same as the process in standard Java except for the names of a couple of methods and the types of parameters that those methods receive. The programming process for handling focus events in the GWT consists of the following steps: Any GUI component that either defines or inherits the registration method named addFocusListener can fire focus events. This includes at least the following GWT GUI components and possibly some others that I overlooked in my search: The sample applications in this lesson will concentrate on focus events fired by Button, TextBox, and FocusPanel objects. Focus events often occur in pairs Recall that only one component can have the focus at any point in time. When a component gains the focus, it will fire an onFocus event as a result of gaining the focus. If some other component had the focus before, it will fire an onLostFocus event as the result of losing the focus. Therefore, focus events often occur in pairs. Don't always occur in pairs Be aware, however, that there are situations where one component can lose the focus without another component (in the same application at least) gaining the focus. Similarly, there are situations where a component can gain the focus but there was no component in the same application that previously had the focus. An example of this latter situation is the case where the application first starts running and a component gains the focus at startup. Since the application was not previously running, it is not possible that some component belonging to that application could have had the focus. A visual indication of focus Most GUI components provide a visual indication to the user that the component has the focus. (Note the sidebar later in this document that discusses an apparent bug in the GWT regarding the visual indication of focus, or the lack thereof.) The actual visual indicator will depend on the look and feel ascribed to the components being used. Perhaps the most consistent visual indication of focus among all of the GUI components across many operating systems is the existence of a blinking cursor in components that allow the user to enter text into the component. Just about everyone who uses a computer recognizes the blinking cursor as an indication that it is OK to enter text. You will see some visual indications of focus in the sample applications in this tutorial. Focus traversal In most cases, repeatedly pressing the tab key will cause the focus to move among the components in a GUI according to a specified traversal path. Also, in most cases, holding down the Shift key and repeatedly pressing the tab key will cause the focus to move among the same components in the reverse of the specified traversal path. Two ways to establish the traversal path The setTabIndex method A more complicated way of establishing the traversal path is to invoke a method named setTabIndex on each component in the GUI passing an int value as a parameter to the method. According to the GWT documentation, this "Sets the widget's position in the tab index. If more than one widget has the same tab index, each such widget will receive focus in an arbitrary order. Setting the tab index to -1 will cause this widget to be removed from the tab order." "Sets the widget's position in the tab index. If more than one widget has the same tab index, each such widget will receive focus in an arbitrary order. Setting the tab index to -1 will cause this widget to be removed from the tab order." -1 Having set a tab index value on each component, repeatedly pressing the tab key will cause the focus to move among the components in increasing numeric tab-index order. Holding down the Shift key while repeatedly pressing the tab key will reverse the traversal path. What is a click event? A click event is an event that is fired by a component to indicate that a specific action has occurred with respect to the component. The most common way to cause a component to fire a click event is to click it with the mouse (hence the interface name addClickListener and the method name onClick). In addition, some components can fire click events as a result of certain keyboard actions while the component has the focus. Two examples of keyboard actions and click events For example, pressing the space bar when a Button object has the focus will cause the button to fire a click event in the GWT and will cause the button to fire an ActionEvent in standard Java. (A click event in the GWT is analogous to an action event in standard Java.) On the other hand, pressing the Enter key when a standard Java TextField object has the focus will cause it to fire an ActionEvent, but pressing the Enter key when a GWT Textbox object has the focus will not cause it to fire a click event. (The similarity between the two breaks down in this case.) The programming process for handling click events in the GWT is essentially the same as the process in standard Java except for the name of the interface, the name of the single event handling method, and the type of parameter that the event handling method receives. The programming process The programming process for handling click events in the GWT consists of the following steps: Which GUI components can fire click events? Any component that either defines or inherits the registration method named addClickListener can fire a click event. This includes at least the following GWT GUI components and possibly some others that I overlooked during my search: The first sample application in this lesson will concentrate on click events fired by Button and TextBox objects. Credit to Mr. Eric Sessoms The GWT drag-and-drop sample application in this lesson is not a creation of my own design. Rather, the technical information and the ideas behind the sample application were taken (with written permission via Email) from the original author whose name is Eric Sessoms. (See Drag and Drop using the GWT in Resources.) Will defer to Eric Sessoms blog for background information Mr. Sessoms does a much better job than I could do with regard to the General background information on performing drag-and-drop with the GWT. Therefore, I will refer you to his blog for that information. I will content myself with attempting to explain how and why the sample application behaves as it does. Depends heavily on handling mouse events I will point out, however, that the drag-and-drop technique described herein depends heavily on the use of mouse events, the MouseListener interface, and the MouseListenerAdapter class. If you haven't already studied my earlier lesson named "Event driven programming in AJAX using the GWT and Java" (see Resources) where I explain the handling of mouse events in some detail, now would be a good time to do so. Three sample GWT web applications I will present and explain three sample GWT applications in this lesson. The names of the three applications are shown in the following list. This list also shows the primary topic that each application is designed to illustrate. I will discuss the code for the following applications in fragments. A complete listings of each application is provided in Listing 22 through Listing 27 near the end of the lesson. The HTML host pages The HTML host pages used for the applications in this lesson are essentially the same as those used for the applications in my earlier tutorials. Therefore, I won't discuss them in this lesson. However, a complete listing of each HTML host page is provided in Listing 22 through Listing 27 along with the Java source code for the application. The application GUI at startup Figure 1 shows a screen shot of the application named GwtApp016 at startup when running in Internet Explorer 6. Figure 1. The application GUI at startup. The row of Label objects shown at the bottom in Figure 1 contains column headers for three columns that will contain the following information: There is no information showing under those column headers at startup because no component has yet gained the focus, no component has yet lost the focus, and no component has yet fired a click event. The application GUI after clicking the TextBox Figure 2 shows the state of the GUI after the user started the application running and then clicked the TextBox object once with the mouse. Figure 2. The application GUI after clicking the TextBox. The information in the middle column shows that this caused the text box to gain the focus. However, the left column is still blank because at this point, no component lost the focus because no component had the focus at startup. The right column in Figure 2 shows that the text box fired a click event when the user clicked the text box with the mouse. The application GUI after clicking the Right button Figure 3 shows the state of the GUI as a result of the user clicking the Right button while the text box had the focus. Figure 3. The application GUI after clicking the Right button. Gaining the focus with the tab key Figure 4 shows the result of restarting the application and pressing the tab key repeatedly until the Right button gains the focus. Figure 4. Gaining the focus with the tab key. Because of the order in which the components were placed in their container, the forward focus traversal path for the tab key is from left to right across the two buttons and the text box. Thus, when the Right button gained the focus, the text box lost the focus as shown by the information in the two left columns in Figure 4. No click event showing Note that the right column in Figure 4 is still blank because no click events have been fired since the application was restarted. Firing a click event with the space bar Figure 5 shows the result of pressing the space bar while the Right button has the focus as shown in Figure 4. Figure 5. Firing a click event with the space bar. A click event was fired The right column in Figure 5 shows that a click event was fired by the Right button as a result of pressing the space bar on the keyboard while the Right button had the focus. Description of the application This application demonstrates FocusListener, ClickListener, and tool tips. It places two Button objects and a TextBox object in a HorizontalPanel object as shown in Figure 1. Listeners The application defines inner classes (not anonymous inner classes) that implement listener interfaces. One inner class implements the FocusListener interface and the other class implements the ClickListener interface. The application instantiates and registers FocusListener and ClickListener objects on each of the buttons and on the text box. Titles for tooltips The application also sets a title on each button and on the text box to cause each of them to show tooltips whenever the mouse pointer hovers over the component. (Figure 2 shows a tooltip immediately below the Right button. Note however, that the screen shot did not capture the image of the mouse pointer in Figure 2.) A simple table to display event information As shown in Figure 3, the application uses HorizontalPanel objects, Label objects, and a VerticalPanel object to create a simple table that shows which components fired events of the following types (going from left to right in Figure 3): Application testing The application was tested using J2SE 5.0, GWT version 1.2.22, and jakarta-tomcat-5.0.27 running as a localhost server under WinXP. Beginning of the class definition Listing 1 shows the beginning of the class definition and the beginning of the onModuleLoad method for the application named GwtApp016. Listing 1. Beginning of the class definition for GwtApp016. package GwtApp.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.user.client.ui.*; public class GwtApp016 implements EntryPoint{ //These three labels are used for text output. They are // declared as instance variables to make them accessible // by the methods in the inner classes. private Label label20; private Label label21; private Label label22; //This is the entry point method. public void onModuleLoad(){ //Create the basic structure of the GUI. HorizontalPanel topPanel = new HorizontalPanel(); topPanel.setSpacing(5); HorizontalPanel middlePanel = new HorizontalPanel(); middlePanel.setSpacing(5); HorizontalPanel bottomPanel = new HorizontalPanel(); bottomPanel.setSpacing(5); VerticalPanel vertPanel = new VerticalPanel(); vertPanel.add(topPanel); vertPanel.add(middlePanel); vertPanel.add(bottomPanel); I have explained code similar to the code in Listing 1 in numerous sample applications in previous lessons. Therefore, there should be no need for a further explanation of the code in Listing 1 beyond the explanation provided by the embedded comments. Populate the top HorizontalPanel object Listing 2 populates the top HorizontalPanel object with two Button objects and a TextBox object. Listing 2. Populate the top HorizontalPanel object. //Populate the topPanel with two buttons and a TextBox Button button00 = new Button("Left"); TextBox textBox = new TextBox(); textBox.setText("TextBox"); Button button02 = new Button("Right"); //Make the buttons the same width. button00.setWidth("50px"); button02.setWidth("50px"); //Add the three components to the horizontal panel topPanel.add(button00); topPanel.add(textBox); topPanel.add(button02); Once again, there is nothing new in Listing 2, so I won't discuss it further. Some more common code Listing 3 populates the middle and bottom panels using code similar to the code that you have seen in numerous previous sample applications. Therefore, I won't discuss the code in Listing 3 any further. Listing 3. Some more common code. //Populate the middle panel with three labels. These // labels serve simply to explain the contents of the // three labels below them. Label label10 = new Label("Lost Focus"); Label label11 = new Label("Gained Focus"); Label label12 = new Label("Was Clicked"); label10.setWidth("85px"); label11.setWidth("85px"); label12.setWidth("85px"); middlePanel.add(label10); middlePanel.add(label11); middlePanel.add(label12); //Populate the bottom panel with three output labels. // The contents of these three labels are modified by // the code in the event handlers to explain the // events. label20 = new Label(""); label21 = new Label(""); label22 = new Label(""); label20.setWidth("85px"); label21.setWidth("85px"); label22.setWidth("85px"); bottomPanel.add(label20); bottomPanel.add(label21); bottomPanel.add(label22); Set the tooltip text We've finally gotten to some code that is new to this lesson. The code in Listing 4 sets the tooltip text for each of the three components, by invoking the setTitle method on each of the components. Invoking the setTitle method on a component in the GWT is all that is required to cause the component to display a tooltip. Listing 4. Set the tooltip text. button00.setTitle("Left Button"); textBox.setTitle("TextBox"); button02.setTitle("Right Button"); The titles that are set in Listing 4 serve not only as tooltip text, but also serve as text identifiers for the components that gain the focus, lose the focus, and fire click events. These text identifiers are displayed in the table shown in Figure 3. Register listener objects Listing 5 begins by instantiating a listener object of the inner class named FocusLstnr. Then it registers that single common listener object on each of the buttons and on the text box. Listing 5. Register listener objects. //Register a common focus listener on each button and // on the text box. FocusLstnr focusLstnr = new FocusLstnr(); button00.addFocusListener(focusLstnr); textBox.addFocusListener(focusLstnr); button02.addFocusListener(focusLstnr); //Register a common click listener on each button and // on the text box. ClickLstnr clickLstnr = new ClickLstnr(); button00.addClickListener(clickLstnr); textBox.addClickListener(clickLstnr); button02.addClickListener(clickLstnr); //Add the vertical panel to the browser window. The // vertical panel serves as a backbone and the three // horizontal panels serve as ribs. RootPanel.get().add(vertPanel); }//end onModuleLoad method The code in Listing 5 also instantiates a common listener object of the inner class named ClickLstnr. Then it registers that common listener object on each of the buttons and on the text box. As a result, both a focus listener and a click listener are registered on both buttons and on the text box. Add the VerticalPanel to the RootPanel and end the method Finally, the code in Listing 5 adds the populated VerticalPanel object to the RootPanel, thereby completing the construction of the application GUI. Listing 5 also signals the end of the onModuleLoad method. Define the inner class named ClickLstnr As you can see, this class implements the ClickListener interface and defines the onClick method that is declared in that interface. This is the only method that is declared in the ClickListener interface. Listing 6. Define the inner class named ClickLstnr. class ClickLstnr implements ClickListener{ public void onClick(Widget sender){ label22.setText(sender.getTitle()); }//end onClick }//end class ClickLstnr Need to identify the source of the event The onClick method in Listing 6 is executed any time that any of the three components fires a click event. Therefore, it is necessary for the method to identify the component that fired the event. Fortunately, the incoming parameter named sender of type Widget points back to the component that fired the event. The code in Listing 6 invokes the getTitle method on that reference to get the tooltip title that was established for the component earlier. Then it displays that title in the rightmost column in the table in Figure 3 to identify the component that fired the click event. Define member class named FocusLstnr Listing 7 defines the inner (member) class named FocusLstnr. This class implements the interface named FocusListener and defines the two event handler methods declared in that class. As before, this class was made an inner class so that the code in the each method would have direct access to the label used to display results for that method. Listing 7. Define member class named FocusLstnr. class FocusLstnr implements FocusListener{ public void onLostFocus(Widget sender){ label20.setText(sender.getTitle()); }//end onLostFocus //---------------------------------------------------// public void onFocus(Widget sender){ label21.setText(sender.getTitle()); }//end onFocus }//end class FocusLstnr //=====================================================// }//end class GwtApp016 When are the two methods executed? As you probably already know, one of the methods in Listing 7 is executed when a component loses the focus and fires an event whose type corresponds to the onLostFocus method. The other method is executed when a component gains the focus and fires an event whose type corresponds to the onFocus method. The code in each of the methods in Listing 7 is essentially the same as the code in Listing 6, except that the identification of the component that fired the event is displayed in one of the two columns on the left in Figure 3. The end of the class Listing 7 also signals the end of the class named GwtApp016. At this point, you have learned much of what there is to know about the focus subsystem in the GWT. What you have learned will be useful in understanding the next two sample applications. A few things that you haven't learned As indicated earlier, the GWT focus subsystem is much simpler than the focus subsystem in post-v1.4 standard Java. However, there are a few features of the GWT focus subsystem that weren't discussed here. You can learn about them by going to the index in the javadocs, searching for the word "focus" and reading about any interesting methods that you turn up in that process. Do you understand the handling of GWT mouse events? In order to understand the material in this application, you will need to understand quite a lot about the handling of mouse events in the GWT. I explained mouse event handling in the earlier lesson named "Event driven programming in AJAX using the GWT and Java" (see Resources). If you haven't studied that lesson yet, I suggest that you do so at this time. Which components can fire mouse events? Any component that either defines or inherits the registration method named addMouseListener can fire a mouse event. This includes the following GWT GUI components and possibly some others that I may have missed in my search: All in all, that is a rather short list, at least in comparison to the number of GUI components that can fire mouse events in standard Java. Forcing a GUI component to fire mouse events Not restricted to Button objects The technique that I will describe here is not restricted to Button objects. You should be able to use what I am going to show you in this application to force any component to fire mouse events, click events, or focus events. Figure 6 shows the application GUI at startup. The large button in Figure 6 is a custom button that fires mouse events. Figure 6. The application GUI at startup. The output data The five labels below the button show the results of handling mouse events and click events that are fired by the button as the user manipulates the mouse and the keyboard with respect to the button. Each of the labels shows the default values at startup in Figure 6. The five labels display the following information: Figure 7 shows the result of: Figure 7. Firing a click event with the space bar. No mouse events As you can see, the top three labels that are used to show the results of handling mouse events still have their default values in Figure 7. That is because no mouse events had yet been fired when the screen shot was taken. However, using the tab key to cause the custom button to gain the focus and then pressing the space bar caused two components to fire click events as shown by the bottom two labels. Why two components? It is probably time to provide a little more explanation about the two components that fired click events. A you can see, the two components are identified in Figure 7 as: The custom button is actually the composite of a Button object and a FocusPanel object. The button is wrapped in the focus panel, and the composite of the two is considered to be the custom button. However, there are two separate components involved and each has the native ability to fire a click event. The Button referred to in Figure 7 is the ordinary button that is wrapped in the focus panel. The Custom Button that is referred to in Figure 7 is actually the FocusPanel that wraps the Button. These are the two components for which click events are recorded in the bottom two labels in Figure 7. Results for mouse events Figure 8. Results for mouse events. The first label under the button shows that the mouse pointer was In the area occupied by the custom button when the screen shot was taken. The Last Move Location The second label under the button shows the coordinates of the lower-case "n", which was the location of the mouse pointer when the screen shot was taken. The Last Down Location The click event The bottom two labels show the results of the click event that was fired when the mouse button was pressed and then released. This application demonstrates the creation of a custom button that can fire mouse events and otherwise behaves more or less like a standard Button component. One way to establish the contents of a FocusPanel is to pass another object's reference as a parameter to the constructor when the panel is constructed. The application wraps a standard Button object in a FocusPanel object to create the custom button. An object of the FocusPanel that wraps the standard button then behaves more or less like a standard button except that it can fire mouse events in addition to click events and focus events. Set tooltip titles Another use for tooltip titles The titles are also used to identify the component that fires a click event when the mouse button is pressed in the area occupied by the custom button or when the space bar is pressed while the standard button wrapped in the FocusPanel has the focus. When this happens, both the standard button and the custom button fire a click event. Construction of the GUI The application puts the custom button along with five Label objects in a VerticalPanel object as shown in Figure 6. The labels are used to display the fol
http://www.developer.com/java/ent/article.php/3668046
crawl-001
refinedweb
4,814
51.58
In this article, we'll explore how to build a simple working blockchain demo using ** Ruby **. At this stage, we will check the balance and make the transfer. Remittances are additions or subtractions that are made based on your account balance. The HTTP protocols GET and POST are the best way to implement this feature. GET gets the data from the server and POST modifies the data on the server. Here, the UI display does not require the HTML protocol. You can use the Ruby web framework Sinatra to organize URLs and related methods, and use the UE to see the transfer information on the command line. Client-side methods and server-side URLs are very simple. Client: client.rb def create_user(name) … end def get_balance(user) … end def transfer(from, to, amount) ... end Server: hasebcoin.rb get "/balance" ... end post "/users" ... end post "/transfers" ... end Knowledge required for this layer: ruby, HTTP GET, POST, Sinatra The blockchain has a decentralized structure called the "gossip protocol". "Gossip" here is not a rumor, but information that is spread over a distributed network. Let's build a gossip network where movie names are exchanged. client.rb sends a message to the specified port. def self.gossip(port, state) ... Faraday.post("#{URL}:#{port}/gossip", state: state).body ... end gossip.rb receives two parameters, a source port and a destination port. Exchanges information through specific ports on the source side, such as ports 1111 and 2222. In a real distributed network, the two ports are essentially two network nodes. Exchanging information between different local ports represents communication between different nodes in the simulated network. At each node Speak the name of your favorite movie every 3 seconds. every(3.seconds) do … gossip_response = Client.gossip(port, JSON.dump(STATE)) update_state(JSON.load(gossip_response)) ... end Change your favorite movie name every 8 seconds. every(8.seconds) do … update_state(PORT => [@favorite_movie, @version_number]) ... end The server receives and processes the data. post '/gossip' do … update_state(JSON.load(their_state)) … end In a network of 4 people After a while, only four nodes get the peer-end information and the data keeps changing. This is a simple Gossip network. Top-level cryptographic algorithms are the foundation of blockchain. At this layer, asymmetric encryption technology is used to implement blockchain accounts. The RSA algorithm can generate public and private keys and force asymmetric encryption. def generate_key_pair … end def sign(plaintext, raw_private_key) ... end Thanks to the OpenSSL module in the Ruby language, you can quickly implement asymmetric encryption and signature verification. On the blockchain, the public key is the account and the private key is the password. Each key pair will be one blockchain account. Decrypt the ciphertext. def plaintext(ciphertext, raw_public_key) … end Check if the ciphertext is a message. def valid_signature?(message, ciphertext, public_key) … end ** Knowledge required for this layer: Asymmetric encryption algorithm ** At this stage, the proof of work is implemented and blocks are generated for the blockchain. This is a time consuming and tedious process. Hash functions are irreversible and there are no conflicts. The calculation process is simple. You can get the result just by performing a hash operation on the input. The input is information about the remittance, such as the remittance amount, the sender's name, and the recipient's name. There are various algorithms for hash operations. Here we use the SHA256 algorithm. def hash(message) … end If you hash the same information, you will get different results each time. The operation is continued until the obtained result satisfies the feature such as "starting from several digits of 0". Check if the result starts with a few digits of 0. def is_valid_nonce?(nonce, message) hash(message + nonce).start_with?("0" * NUM_ZEROES) end It is not easy to carry out work to satisfy the above conditions. It consumes a lot of time. All such work is called mining. def find_nonce(message) … until is_valid_nonce?(nonce, message) ... end The input contains the result of the previous hash operation. Therefore, each hash operation is affected by the previous hash operation. In other words, this is a chain structure. This is the reason why it is called a blockchain. At this stage, the first block is initialized, the blockchain structure is generated accordingly, and the blockchain is formed. The blockchain is stored in an Array structure. During saving, the block must undergo validation. Initialize the block. def initialize(prev_block, msg) @msg = msg @prev_block_hash = prev_block.own_hash if prev_block mine_block! end The most rewarding task during mining is finding nonces. def mine_block! @nonce = calc_nonce @own_hash = hash(full_block(@nonce)) end The complete block is compressed this way. def full_block(nonce) [@msg, @prev_block_hash, nonce].compact.join end Initialize the blockchain: class BlockChain Just save using Array! def initialize(msg) @blocks = [] @blocks << Block.new(nil, msg) end Add blocks to the chain. The entire blockchain is growing continuously. def add_to_chain(msg) @blocks << Block.new(@blocks.last, msg) puts @blocks.last end You need to rigorously verify that the block is healthy. def valid? @blocks.all? { |block| block.is_a?(Block) } && @blocks.all?(&:valid?) && @blocks.each_cons(2).all? { |a, b| a.own_hash == b.prev_block_hash } end Finally, Blockchain works its magic through harmonious collaboration with all the components in the network. In the first stage, the transfer is a transaction class and you need to use the private key to sign the information. @signature = PKI.sign(message, priv_key) The miner's reward for getting the first block is 500,000 silver coins. def self.create_genesis_block(pub_key, priv_key) genesis_txn = Transaction.new(nil, pub_key, 500_000, priv_key) Block.new(nil, genesis_txn) end Check if the spending charged to your account is valid. def all_spends_valid? compute_balances do |balances, from, to| return false if balances.values_at(from, to).any? { |bal| bal < 0 } end true end Add an unknown node $ PEERS to keep the network growing. if PEER_PORT.nil? # You are the progenitor! $BLOCKCHAIN = BlockChain.new(PUB_KEY, PRIV_KEY) else # You're just joining the network. $PEERS << PEER_PORT end Data processing between nodes loads and updates the blockchain and PEER. # @param blockchain # @param peers post '/gossip' do their_blockchain = YAML.load(params['blockchain']) their_peers = YAML.load(params['peers']) update_blockchain(their_blockchain) update_peers(their_peers) YAML.dump('peers' => $PEERS, 'blockchain' => $BLOCKCHAIN) end The processing of the received block focuses on whether the chain is long. def update_blockchain(their_blockchain) return if their_blockchain.nil? return if $BLOCKCHAIN && their_blockchain.length <= $BLOCKCHAIN.length return unless their_blockchain.valid? $BLOCKCHAIN = their_blockchain end Update PEER until new. def update_peers(their_peers) $PEERS = ($PEERS + their_peers).uniq end When sending money, get the recipient's pub_key and send the money via the sender's pub_key. # @param to (port_number) # @param amount post '/send_money' do to = Client.get_pub_key(params['to']) amount = params['amount'].to_i $BLOCKCHAIN.add_to_chain(Transaction.new(PUB_KEY, to, amount, PRIV_KEY)) 'OK. Block mined!' end Put the blockchain into the gossip network and assemble all the functional components. That's all there is to it. You have successfully created a blockchain. More information about this demo can be found on Github: [](- build-a-blockchain? spm = a2c65.11461447.0.0.30084c44XBVTHc) For more information on blockchain and other innovative technologies, please visit. Recommended Posts
https://linuxtut.com/how-to-build-the-simplest-blockchain-in-ruby-d8bb5/
CC-MAIN-2021-10
refinedweb
1,172
61.33
Subject: [OMPI users] Performance issue of mpirun/mpi_init From: Victor Vysotskiy (victor.vysotskiy_at_[hidden]) Date: 2014-04-10 05:05:43 Dear Developers, I have faced a performance degradation on multi-core single processor machine. Specifically, in the most recent Open MPI v1.8 the initialization and process startup stage became ~10x slower compared to v1.6.5. In order to measure timings I have used the following code snippet: /*-------------------------------------------*/ #include <mpi.h> int main (int argc, char *argv[]) { MPI_Init(&argc,&argv); MPI_Finalize(); return 0; } /*-------------------------------------------*/ The execution wall time has been measured in a trivial way by using the 'time' command, i.e.: time mpirun -np 2 ./a.out Below are given averaged timings for both versions on Linux x86_64 (Intel i7-3630): Default settings: 1.8 : 0.679 s 1.6.5: 1.041 s OMPI_MCA_btl=tcp,self: 1.8 : 0.679 s 1.6.5: 0.041 s The same problem has been detected on Mac OS X v10.9.2. Here I should stress that others MPI distributions perform as the OpenMPI v1.6.5 with the TCP byte transfer layer activated. So, I am wondering whether it is possible to tune v1.8 in order to boost the startup process? The problem is that during the automatic nightly verification of our program we usually spawn parallel binaries a thousands of times. Thank you In advance! Best regards, Victor.
http://www.open-mpi.org/community/lists/users/2014/04/24131.php
CC-MAIN-2014-42
refinedweb
232
69.38
All programming languages have to provide certain capabilities. It must be possible to express the calculations and operations that our code should perform. Programs need to be able to make decisions based on their input. Sometimes we will need to perform tasks repeatedly. These fundamental features are the very stuff of programming, and this chapter will show how these things work in C#. Depending on your background, some of this chapter’s content may seem very familiar. C# is said to be from the “C family” of languages. C is a hugely influential programming language, and numerous languages have borrowed much of its syntax. There are direct descendants such as C++ and Objective-C. There are also more distantly related languages, including Java and JavaScript, that have no compatibility with, but still ape, many aspects of C’s syntax. If you are familiar with any of these languages, you will recognize most of the basic language features we are about to explore. We saw the basic structure of a program in Chapter 1. In this chapter, I will be looking just at code inside methods. C# requires a certain amount of structure: code is made up of statements that live inside a method, which belongs to a type, which is typically inside a namespace, all inside a file that is part of a Visual Studio project contained by a solution. For clarity, most of the examples in this chapter will show the code of interest in isolation, as in Example 2-1. Example 2-1. The code, ... No credit card required
https://www.safaribooksonline.com/library/view/programming-c-50/9781449333416/ch02.html
CC-MAIN-2018-34
refinedweb
261
63.7
cliffwoolley@yahoo.com wrote: > > Fair enough. So let me tone down what I said to simply, "If an APR client > might reasonbly need the same test, we should export our test result." > +1 for using Apache and Subversion as good places to look for an initial > definition of what's "reasonable." If an APR client needs the same test, you might want to look into why APR fails to make the test unnecessary for its clients. For example, the apr_dso_* functions should make the tests for HAVE_DL_H and HAVE_DLFCN_H unnecessary for APR clients. For those HAVE_* macros that really need to be exported, you might want to rename them APR_HAVE_* to stay inside the APR_ namespace.
http://mail-archives.apache.org/mod_mbox/apr-dev/200102.mbox/%3C3A99C60E.403B0CBF@netscape.com%3E
CC-MAIN-2019-18
refinedweb
116
77.77
I probably should have given more details about what I am trying to do. Before I get going, I should mention that I have been using Twisted heavily for 1.5 years and I have, for the most part, learned to play the "Twisted Game." So here is what I am working on: I am developing objects (for scientific computing) that 1) use Twisted to talk over the network and 2) need to be used interactively from a python prompt. This second point is really where the difficult and interesting things are. To allow Twisted-things to be used interactively I have built a version of PyCrust/PyShell that is "Twisted enabled." We have used the standard threadedselectreactor to interleave the Twisted event loop with that of PyShell. We also inject the reactor into the users interactive namespace. Thus, you can use all of Twisted's capabilities from an interactive python prompt. As a side note, this situation is extremely nice for playing around with Twisted and doing interactive debugging of Twisted-using applications.. The implementation of computeSomethingUsingTwisted() is the difficult part: class TwistedEnabledObject(): def connect(addr): self.factory = MyClientFactory() self.connector = reactor.connectTCP(addr[0],addr[1],self.factory) def computeSomethingUsingTwisted(args): d = self.connector.transport.protocol.computeAndReturnDeferred(args) # Now I have a Deferred that will have the result, but I want to wait until # the result or an error is ready and then decide what the result should be result = # what to put here? return result I don't think what I am doing goes against the "Twisted-way." And my needs are not coming from any inability on my part to write proper asynchronous code. The high level stuff here is really bbeing driven by the need to use these object interactively. On 3/10/06, glyph at divmod.com <glyph at divmod.com> wrote: > If you don't mind some vitriol, there is more information here, on my blog: I am familiar with this and other similar "vitriols." I fully agree with most of what you say about threads. But what does my usage case have to do with threads? cheers, Brian Brian Granger Santa Clara University ellisonbg at gmail.com
http://twistedmatrix.com/pipermail/twisted-python/2006-March/012667.html
CC-MAIN-2014-35
refinedweb
365
56.66
HFJ Music Box Page 392 Davy Kelly Ranch Hand Joined: Jan 12, 2004 Posts: 384 posted Nov 18, 2006 08:58:00 0 Hey Guys, been a while, still getting back into it, but on page 392 of the Head First Java , I was doing the Music Box program with GUI. I get an error from the code, and I am not sure why. the 1 error I get is this line of code sequencer.addControllerEventListener(ml, new int[] {127}); i get this error: MiniMusicPlayer3.java:33 addControllerEventListener(javax.sound.midi.ControllerEventListener,int[]) in javax.sound.midi.Sequencer cannot be applied to (MyDrawPanel,int[]) sequencer.addControllerEventListener(ml, new int[] {127}); ^ 1 error I copied the code directly, i fixed other errors I done, but I have been looking at this for over an hour now, and cant get it. here is the full program code: import javax.sound.midi.*; import java.io.*; import javax.swing.*; import java.awt.*; public class MiniMusicPlayer3 { static JFrame f = new JFrame("My First Music Video"); static MyDrawPanel ml; public static void main(String[] args) { MiniMusicPlayer3 mini = new MiniMusicPlayer3(); mini.go(); }//close main method public void setUpGui() { ml = new MyDrawPanel(); f.setContentPane(ml); f.setBounds(30, 30, 300, 300); f.setVisible(true); }//close setUpGui method public void go() { setUpGui(); try { //make and open a sequencer Sequencer sequencer = MidiSystem.getSequencer(); sequencer.open(); sequencer.addControllerEventListener(ml, new int[] {127}); //make a sequence and a track Sequence seq = new Sequence(Sequence.PPQ, 4); Track track = seq.createTrack(); int r = 0; //make a bunch of events to make the notes keep going up for (int i = 0; i < 60; i+= 4) { r = (int)((Math.random() * 50) +1); //call a new makeEvent() method to make the message and event. //then add the result to the track track.add(makeEvent(144, 1, r, 100, i)); /*Here's how we pick up the beat - - we insert our own ControllerEvent (176 says the event type is ControllerEvent) with an argument for event #127. This will do NOTHING! We put it in just so that we can get an event each time a note is played. In other words, its sole purpose is so that something will fire that we can listen for (we can listen for NOTE ON/OFF events). Note that we're making this event happen at the same tick as the NOTE ON. So when the NOTE ON event happens, we'll know about it because out event will fire at the same time. */ track.add(makeEvent(176, 1, 127, 0, i)); track.add(makeEvent(128, 1, r, 100, i + 2)); }//end for loop //start the sequence runnning sequencer.setSequence(seq); sequencer.start(); sequencer.setTempoInBPM(220); }//close try catch (Exception ex) { ex.printStackTrace(); }//close catch }//close go method public MidiEvent makeEvent(int comd, int chan, int one, int two, int tick) { MidiEvent event = null; try { ShortMessage a = new ShortMessage(); a.setMessage(comd, chan, one, two); event = new MidiEvent(a, tick); }//close try catch (Exception e) { }//close catch return event; }//close makeEvent method //inner class class MyDrawPanel1 extends JPanel implements ControllerEventListener { //set the flag to false, only set it to true when we get an event boolean msg = false; public void controlChange(ShortMessage event) { //we got an event set the flag to true and repaint msg = true; repaint(); } public void paintComponent(Graphics g) { if (msg) { //we have to use a flag because other things might trigger a repaint //we only want to pain only there's a controllerEvent); msg = false; }//close if }//close paintComponent method }//close inner class }//close outer MiniMusicPlayer3 class any help will be appreciated. davy [ November 18, 2006: Message edited by: Davy Kelly ] [ November 18, 2006: Message edited by: Davy Kelly ] How simple does it have to be??? Davy Kelly Ranch Hand Joined: Jan 12, 2004 Posts: 384 posted Nov 18, 2006 09:48:00 0 Woo Hoo, I figured it out, because I have another version of MyDrawPanel, I renamed the one in this program as MyDrawPanel1 and I forgot to fix the declerations of them, so some had MyDrawPanel and some had MyDrawPanel1, its all fixed now. it took me a while, but I got there. I think I need a break now. davy I agree. Here's the link: subject: HFJ Music Box Page 392 Similar Threads How LOLbad is this stylistically? MiniMusicPlayer2 class in Head First Java book (Chapter 12) Java Class hangs after run Head First Java problem MiniMusicPlayer HFJ All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/405428/java/java/HFJ-Music-Box-Page
CC-MAIN-2015-18
refinedweb
753
68.6
297 11073 [details] Video showing the clear-screen behavior I've been able). *** Bug 29767 has been marked as a duplicate of this bug. *** Marek? No idea but does this happen for Hello world app too? It appears to be related to the use of color. This does not clear the screen: using System; public class HelloWorld { public static void Main() { Console.WriteLine("Hello, world!"); } } This does: using System; public class HelloWorld { public static void Main() { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Hello, world!"); } } Looks like our SetABackground term info string is not really correct in this case. Activating the color enables the terminfo based terminal to be used, and this can have side effects like this, depending on the TERM setting and the terminal database on the system. We would need the terminfo database for this scenario, and the TERM setting. You can use the "infocmp" command to generate this information. This is still a problem. In addition to color properties, even adding a handler to Console.CancelKeyPress causes the screen to clear. Here is the infocmp output on the affected terminal: # Reconstructed via infocmp from file: /lib/terminfo/c/cygwin cygwin|ansi emulation for Cygwin, am, hs, mir, msgr, xon, colors#8, it#8, pairs#64, acsc=+\020\,\021-\030.^Y0\333`\004a\261f\370g\361h\260j\331k\277l\332m\300n\305o~p\304q\304r\304s_t\303u\264v\301w\302x\263y\363z\362{\343|\330}\234~\376, bel=^G, bold=\E[1m, clear=\E[H\E[J, cr=^M, cub=\E[%p1%dD, cub1=^H, cud=\E[%p1%dB, cud1=,~, knp=\E[6~, kpp=\E[5~, kspd=^Z, nel=^M^J, op=\E[39;49m, rc=\E8, rev=\E[7m, ri=\EM, rmacs=\E[10m, rmcup=\E[2J\E[?47l\E6%t;1%;%?%p7%t;8%;%?%p9%t;11%;m, sgr0=\E[0;10m, smacs=\E[11m, smcup=\E7\E[?47h, smir=\E[4h, smpch=\E[11m, smso=\E[7m, smul=\E[4m, tsl=\E];, u6=\E[%i%d;%dR, u7=\E[6n, u8=\E[?6c, u9=\E[c, vpa=\E[%i%p1%dd, I am able to reproduce this by using git for windows' ssh client to connect to an ubuntu machine. . Hi, I'd like to bump this issue. It has been plaguing me for the better part of a year now and until recently I haven't had the inspiration required to isolate it. I had already written a bug report before I had found this issue, so I'll just include it below: Running this program: ``` using System; namespace ConsoleBug { public class HelloWorld { public static void Main(string[] args) { Console.WriteLine("Hello World1"); Console.WriteLine("Hello World2"); Console.WriteLine("Hello World3"); Console.WriteLine("Hello World4"); Console.WriteLine( Console.ForegroundColor.ToString()); Console.WriteLine("Hello World5"); Console.WriteLine("Hello World6"); Console.WriteLine("Hello World7"); Console.WriteLine("Hello World8"); Console.WriteLine("Done"); } } } ``` Using: - Mono JIT compiler version 4.6.1 (Stable 4.6.1.5/ef43c15 Wed Oct 12 09:10:37 UTC 2016) - Ubuntu 16.04.1 LTS Compile with: `mcs console_bug.cs` Expected behaviour: ``` Hello World1 Hello World2 Hello World3 Hello World4 White Hello World5 Hello World6 Hello World7 Hello World8 Done ``` Actual behaviour: ``` Hello World1 Hello World2 Hello World3 Hello World4 ``` Followed by a one-second pause, then the screen clears, and the following is printed: ``` White Hello World5 Hello World6 Hello World7 Hello World8 Done ``` Diagnosis: This all makes sense when you look at the code and the raw output from `script -q /dev/null -c "mono console_bug.exe" > text.txt; cat -e text.txt`: ``` Hello World1^M$ Hello World2^M$ Hello World3^M$ Hello World4^M$ ^[[6n^[[H^[[JWhite^M$ Hello World5^M$ Hello World6^M$ Hello World7^M$ Hello World8^M$ Done^M$ ^[[39;49m ``` When the `Console.ForegroundColor` getter is invoked, it has a non-idempotent effect of printing: - ^[[6n (query cursor position) - ^[[H (set cursor position to top left) - ^[[J (clear screen below cursor) If we follow the code: - ForeGroundColor getter has non-idempotent effect by calling Init() () - Init() calls GetCursorPosition () - GetCursorPosition() writes "^[[6n" out and timesout the `ConsoleDriver.InternalKeyAvailable` call after one second () - `noGetPosition` is set to true as a result and GetCursor() returns - Init() for some reason then does a `WriteConsole(clear)` because `noGetPosition` is false - **This is the root cause** () This bug is particularly annoying because it happens for me due to a static constructor (hence I can't control it), for a type, in a library that I use, which checks (read only!) the default console foreground color. No other color console functionality is ever used. IMO the Init() method should not have any side effects - especially when it's called from a getter that is querying the default color. At the very least, can it not clear the screen? @miguel any chance for you to look into this
https://xamarin.github.io/bugzilla-archives/29/29770/bug.html
CC-MAIN-2019-35
refinedweb
804
56.86
#include <avr/io.h> #include <config.h> #include <serial_ram.h> #include <spi.h> #include <util/delay_basic.h> #include <util/delay.h> Issue the command to put the M25P16 into power down mode. In Power down mode the device ignores all erase and program instructions. In this mode the device draws 1uA typically. Use the power_up_flash_ram() command to bring the device out of power down mode. Removing power completely will also cancel the Deep power down mode - it will power up again in standby mode. Issue the command to bring the M25P16 out of power down mode. This function has no effect if the device is currently in one of the erase modes. At power up the deice will be in standby mode, there is no need to issue the power_up_flash_ram() command after a power up. Erase the M25P16. This function issues an erase command, then blocks until the command is complete as shown by the status register being zero. Note that the erase actually sets all bits to 1. The page program can set bits to 0, but NOT to 1. Therefore each page should be considered 'write once' between erase cycles. Erase 1 sector of the M25P16. Read exactly 256 bytes from the selected page of the M26P16 to memory. For reads or writes of less than 256 bytes, or non aligned read or writes use the read_write_flash_ram() function instead. Read 3 bytes of ID from the M26P16. These should always be 0x20,0x20,0x15. Select the M25P16 and return 1 byte from the Status register. Perform an arbirary read/write from/to the M26P16. IMPORTANT The M25P16 is a block device. It deals in 256 byte pages. Writes only every take place to a single 256 byte page. If writing >256 bytes, anything other than the last 256 bytes will be overwritten and ignored. If offset is non-zero, then be aware that if offset+bytes_to_readwrite > 255, then any write will wrap back to the beginning of the page. This is unlikely to be what you want. Write exactly 256 bytes to the selected page of the M26P16 from memory. For reads or writes of less than 256 bytes, or non aligned read or writes use the read_write_flash_ram() function instead. Write to the status register on the M25P16.
http://www.cl.cam.ac.uk/teaching/1011/P31/lib/html/serial__ram_8c.html
CC-MAIN-2014-41
refinedweb
380
77.53
The first step in any machine learning project is typically to clean your data by removing unnecessary data points, inconsistencies and other issues that could prevent accurate analytics results. Data cleansing can comprise up to 80% of the effort in your project, which may seem intimidating (and it certainly is if you attempt to do it by hand), but it can be automated. In this post, we’ll walk through how to clean a dataset using Pandas, a Python open source data analysis library included in ActiveState’s Python. All the code in this post can be found in my Github repository. “Cleaning Datasets”_0<< 3. If you click the Get Started button you can choose Python, the OS you are working in, and then add “pandas” and “scikit-learn” from the list of packages available. 4. Once the runtime builds, you can download the State Tool and use it to install your runtime: And that’s it! You now have Python installed with all the required packages in a virtual environment. If you want to read a more detailed guide on how to install ActivePython on Linux, please read here. In this directory, create your first “clean-with-pandas.py” file. Getting Started With Pandas The first step is to import Pandas into your “clean-with-pandas.py” file import pandas as pd Pandas will now be scoped to “pd”. Now, let’s try some basic commands to get used to Pandas. To create a simple series (array) on Pandas, just do: s = pd.Series([1, 3, 5, 6, 8]) This creates a one-dimensional series. 0 1.0 1 3.0 2 5.0 3 6.0 4 8.0 dtype: float64 In most machine learning scenarios, data is presented to you in a CSV file. The great thing about Pandas is that it supports reading and analyzing this kind of data out of the box. Here’s how to read data from a CSV file. df = pd.read_csv('data.csv') A typical machine learning dataset has a dozen or more columns and thousands of rows. To quickly display data, you can use the Pandas “head” and “tail” functions, which respectively show data from the top and the bottom of the file: df.head() df.tail(3) You can either pass in the number of rows to view as an argument, or Pandas will show 5 rows by default. At any time, you can also view the index and the columns of your CSV file: df.index df.columns Choosing A Dataset For the purpose of this tutorial, we will be using a CSV file containing a list of import shipments that have come to a port. You can find it on the Github repository mentioned here. The file includes attributes of the shipment, as well as whether the shipment was “valid” or not, where valid means officers let the shipment through. A quick look at the dataset using “df.columns” shows: Explore columns You can explore the dataset further by looking at the number of features, number of rows, the datatype of each column, and so on. Cleaning A Dataset Dropping Unnecessary Columns A useful dataset is one that has only relevant information in it. As the first step of the data cleaning process, let’s drop columns that: - Are not aligned to the dataset goals. From a practical point of view, a dataset may contain data that is irrelevant to the study being undertaken. However, you don’t want to drop data that may actually be useful. Only drop it if you’re sure it won’t be helpful. In this case, “item,” “importer_id” and “exporter_id” can all be dropped from our dataset. - Have a significant number of empty cells. If a variable is missing 90% of its data points, then it’s probably wise to just drop it all together. - Contain non-comparable values. Oftentimes datasets contain IDs that are not significant from a data perspective. In other words, they cannot be compared or manipulated mathematically. For this reason, we’ll drop “mode_of_transport.” On Hot Encoding Labels The dataset provides routes taken by each shipment. Points along the routes are described using labels, as shown below: Sending route data to a mathematical model in this form has little value. The data first needs to be represented in a numerically comparable way. For example, “asia” and “america” represent two different locations and cannot be represented in the same column. To solve this, we will create a new column for each unique value in the “route” column. This is automatically done by the “get_dummies” function of Pandas: Now the “route” column is no longer necessary. We will drop the “route” column and concatenate the original data with the new columns from the “get_dummies” function. Repeat this for the “country_of_origin” column as well. Summarizing Columns Multiple columns can sometimes convey the same information. In our dataset, “date_of_departure”, “date_of_arrival” and “days_in_transit” all mean the same thing. Additionally, date fields don’t carry much relevance unless represented in a quantifiable way. For this reason, we’ll keep the “days_in_transit” column and drop the two date fields. Normalizing Quantities There are two columns that represent the weight of the shipment: “actual_weight” and “declared_weight.” Any shipment that has a large deviation between these two values could potentially be misdeclared. However, a “heavier” shipment will have a larger deviation than a “lighter” shipment. To normalize these values, we’ll use a scaler from the scikit-learn library. Handling Missing Values Apart from handling irrelevant columns, it is also important to handle missing values for the columns we actually need. There are multiple ways to go about this: - Fill in the missing rows with an arbitrary value: can be performed when there is a known default value that doesn’t corrupt the entire dataset - Fill in the missing rows with a value computed from the data’s statistics: if possible, a better option than number one - Ignore missing rows: only works if the dataset is large enough to afford throwing away some of the rows Formatting The Data Oftentimes datasets are created by humans manually keying in every data point, which is prone to human errors or glitches. For example, a route that goes through the Panama Canal can be represented as “panama” or “Panama Canal” or “panama-canal”. In order to standardize how the Panama Canal appears in the dataset, use the Pandas “replace” function to replace all non-standardized representations. Conclusion A machine learning or AI model can improve significantly if it is trained on the right dataset. In most cases, cleaning data and representing it in a mathematically consumable way leads to higher accuracy rates than just changing the model itself. Though there is no rule-of-thumb when it comes to cleaning data, you should always aim for a dataset that is quantifiable, comparable, and has significant relevance to your output. - To view all the code and processes mentioned in this post, you can refer to my Github repository. - To run the code, you can sign up for a free ActiveState Platform account and either build your own runtime environment or download the pre-built “Cleaning Datasets” runtime. Related Blogs: Introduction to Python Data Types
https://sweetcode.io/how-to-clean-machine-learning-datasets-using-pandas/
CC-MAIN-2021-21
refinedweb
1,205
62.88
Python’s Random Module – Everything You Need to Know to Get Started Life is unpredictable. Sometimes good things happen out of the blue like you find $100 on the floor. And sometimes bad things happen, like your flight being canceled because of bad weather. Most programming languages have a module to deal with randomness. Python is no exception coming with the module named random and in this article, we’ll be looking at the most essential functions you need to use it. The Absolute Basics Before we use any function from the random module, we must import it. import random Because we’re dealing with a computer program, the random numbers are not 100% random. Rather, the module creates pseudo-random numbers using a generator function. The core generator function Python uses is called the Mersenne Twister. It is one of the most extensively tested random number generators in the world. However, the random numbers are predetermined. If someone sees 624 iterations in a row, they can predict, with 100% accuracy, what the next numbers will be. It’s also a repeating sequence. Fortunately, it takes quite a while to repeat itself. You must go through 2**19937 – 1 numbers (a Mersenne prime, hence the name) before you’ll reach the start of the sequence again. Therefore, you should NOT use the random module for anything security-related such as setting passwords. Instead, use Python’s secrets module. It is useful that random doesn’t create 100% random numbers because it allows us to reproduce our results! This is incredibly important for those working in Data Science. But how do we ensure we can reproduce our results? We first have to plant a seed. random.seed() At the start of any work involving randomness, it’s good practice to set a ‘seed’. This can be viewed as the ‘start point’ of our random sequence. To do this we enter any float or int into random.seed(). Let’s set the seed to 1. import random random.seed(1) Now we’ll generate random numbers in the range [0.0, 1.0) by calling the random.random() function a few times. If you do the same, you’ll see that your numbers are identical to mine! >>> random.random() 0.13436424411240122 >>> random.random() 0.8474337369372327 >>> random.random() 0.763774618976614 If we reset the seed and call random.random() again, we will get the same numbers. >>> random.seed(1) >>> seed_1 = [random.random() for i in range(3)] >>> seed_1 [0.13436424411240122, 0.8474337369372327, 0.763774618976614] I used a list comprehension for greater readability but you can manually type it if you prefer. Now we can generate some random numbers. But what would it look like if we generate hundreds of thousands of them and plot them? Plots like that are called distributions. Distributions If we roll one dice, every number from 1 to 6 is equally likely. They all have probability 1/6. We say that these probabilities are uniformly distributed. To remember this, recall that a group of people wearing uniforms all look the same. If we roll two dice and sum their results, the results are not uniformly distributed. The probability of rolling 2 and 12 is 1/36 but 7 has probability 1/6. What’s going on? Not everything is uniformly distributed. To understand what’s going on, let’s roll one dice 100,000 times and two dice 100,000 times then plot the results. We’ll use the random.choice() function to help us. It takes any sequence and returns a randomly chosen element – assuming a uniform distribution. Note: I call sns.set() at the start to use the default Seaborn settings as they look much nicer than matplotlib. Rolling One Dice 100,000 Times import matplotlib.pyplot as plt import seaborn as sns sns.set() # Create our data outcomes = [1, 2, 3, 4, 5, 6] one_dice = [random.choice(outcomes) for i in range(100000)] # Plot our data plt.hist(one_dice, bins=np.arange(1, 8), density=True) plt.show() Here is a perfect example of a uniform distribution. We know that 1/6 = 1.666 and each bar is about that height. Explaining the Code We use list comprehensions to generate 100,000 values. Then plot it using plt.hist(). Set density=True to ensure that the y-axis shows probabilities rather than counts. Finally, set bin=np.arange(1, 8) to create 6 bins of width 1. Each bin is half-open – [1, 2) includes 1 but not 2. The final bin is closed – [6, 7] – but since 7 is not a possible outcome this does not impact our results. We can set bins to an integer but this creates a graph that is harder to interpret as you can see below. Each bar is of width ~ 0.8 and probability 0.2, neither of which we expected or wanted. Thus, it is always best to manually set bins using np.arange(). If you struggle with NumPy arange, check out the full tutorial of NumPy’s arange function on our blog! The random module contains the function random.uniform(a, b) that returns randomly chosen floats in the interval [a, b]. If you draw 100,000 numbers and plot the results you’ll see a similar-looking plot to those above. Rolling Two Dice 100,000 Times The code is almost identical to the first example. outcomes = [1, 2, 3, 4, 5, 6] two_dice = [random.choice(outcomes) + random.choice(outcomes) for i in range(100000)] plt.hist(two_dice, bins=np.arange(2, 14), density=True) plt.show() The shape is very different from our first example and illustrates what we expected. Numbers 2 and 12 have probability 1/36 = 0.0277 and 7 is 1/6 = 1.666. The shape may remind you of one of the most famous distributions in the world: the Normal Distribution. In the Normal Distribution, the values near the center are much more likely to occur than those at the extreme ends. You will see this distribution many times throughout your career as it can be used to model countless random events e.g. height, weight, and IQ. There are many different distributions and any good statistics textbook explains them in detail. Check out the list of 101 free Python books on the Finxter blog and just download one of your choice. The random module has functions that draw values from the most common ones. We will just cover the Normal Distribution here for brevity. Since the Normal Distribution is also called the Gaussian Distribution, random has two functions to generate samples: random.gauss() and random.normalvariate(). Both take two parameters, mu and sigma – the mean and variance of the distribution respectively. For more info check out the Wikipedia page. We will plot both graphs on the same axes using the following code. normal = [random.normalvariate(7.5, 2.35) for i in range(100000)] plt.hist(two_dice, bins=np.arange(2, 14), density=True, alpha=0.7, label='Dice Data') sns.distplot(normal, hist=False, color='r', label='Normal Approx.') plt.legend() plt.show() The normal approximation with mu=7.5 and sigma=2.35 is a very good approximation of rolling two dice. I found these after trying a few random values. We call it 100,000 times using list comprehension and plot using sns.distplot setting hist=False to just show the approximation. This is very useful especially in the field of data science. If we can approximate our data using well-known and well-researched distributions, we instantly know a lot about our data. There is a whole branch of statistics dedicated to approximating data to known distributions. It can be dangerous to infer too much from a small sample of data. The method we used above is not statistically sound but is a good starting point. Note that the Normal Distribution does not have a finite selection of values, nor does it have an upper or lower limit. It is unlikely but random.normalvariate(7.5, 2.35) can generate numbers < 2 and > 12. Thus it is only useful as an approximation and not as a replacement. Three Ideas to Use the Random Module That was a whistle-stop tour of the random module and now you’ve got everything you need to start using it. Given that the best way to learn is through projects, here are some ideas for you to try out: - When web-scraping, use time.sleep()combined with random.uniform()to wait a random amount of time between requests. - Create a ‘guess the number’ game. The computer chooses a random number between 1 and 10 – using random.choice()– and you guess different numbers with the input()command. See this book for more ideas. - Create a list of phone numbers and names of your loved ones. Create another list of loving messages. Use Twilio to send a random loving message to a randomly chosen person each day. Best of luck and may randomness be with you! Attribution! Where to Go From Here? Do you want to become a professional Python coder? Understanding the basics in Python is critical for your success in your professional life! As I know you are a busy person, I’ve created a simple and easy-to-follow email course based on cheat sheets and a daily Python-related email. One Python lesson at-a-time, you’ll become a great Python coder! Join tens of thousands of ambitious Python coders now! Just type your email address into the box below and start your new coding venture: References [1] [2] [3] [4] [5] [6] [7]
https://scripts.codes/2019/11/05/pythons-random-module-everything-you-need-to-know-to-get-started/
CC-MAIN-2019-47
refinedweb
1,607
68.87
On Wed, 12 Feb 2003, Sam Hartman wrote: > Henrique> Huh? All our archs accept, and work with versioned > Henrique> symbols the same way. They use the same toolchain and > Henrique> runtime linker now... > > You'd really like to use a version script similar to > version_1 { > global: > *} > > But you cannot do this because there are symbols included statically > in all shared libraries on some architectures that cannot or should > not be versioned. Because of what I think is a linker bug, things > break badly on these architectures if you version all symbols. Eek. Yeah, that WOULD be a pain. Any of them in the _* hierarchy? Still, linker bugs CAN be fixed, and if we can have a roster of the symbols that must not be versioned, lintian and linda tests added. For SASL2 2.1.7, I was thinking of versioning like this (idea from Antti Salmela <asalmela@iki.fi>): +SASL2_1.7 { + global: + sasl_*; + local: + _*; +}; This won't work with libs that scatter symbols everywhere in the namespace, but... -- "One disk to rule them all, One disk to find them. One disk to bring them all and in the darkness grind them. In the Land of Redmond where the shadows lie." -- The Silicon Valley Tarot Henrique Holschuh
https://lists.debian.org/debian-devel/2003/02/msg00726.html
CC-MAIN-2017-09
refinedweb
208
83.25
Hi guys, as you seem ready to play with simulators to build debian m68k packages,). qemu linux-user mode traps guest (m68k) syscalls to translate them to native ones. It's not perfect. For instance, the clone() syscall seems to not work correctly (at least in one case, gnome-terminal), but you will, at least, be able to rebuild some packages. I don't think it is really usable for a debian buildd, but it can be used to develop and correct build issues. For instance, you can build glibc, kernel and gcc concurrently on one machine in less than a day ;-) The attached script will help you to test this. This script : - checks all needed stuffs are there (I'm not sure of the full list) - clones my qemu-m68k fork and compiles it - debootstrap and configures an etch-m68k root filesystem - configure binfmt to use qemu-m68k to load m68k ELF binaries - creates an LXC container for it run it with "sudo ./create-m68k-lxc.sh". I have tested it on an ubuntu 12.10 x86_64 system, and it seems to work fine. Default installation paths are: - /containers/m68k for the m68k root filesystem - $HOME/qemu-m68k for qemu sources - $HOME/lxc-m68k.conf for the LXC configuration file The name of the LXC container is virtm68k, but you can edit variables at the beginning of the script. Then you can start the container with "sudo lxc-start -n virtm68k", the system console is on the stdio. You can access the linux virtual consoles by running several "sudo lxc-console -n virtm68k". By default, on an Ubuntu 12.10 system, when lxc is installed, there is an interface "lxcbridge" allowing the virtual machine to access to network. By default the bridge is 10.0.3.1 and the virtm68k machine is configured with an eth0 on 10.0.3.128. "openssh-server" is not installed by default, but you can add it from the console with apt-get (don't forget to add a password for root). If you don't like this, you can destroy the container with "sudo lxc-destroy -n virtm68k", but, WARNING, it will also remove the directory ! Have fun, Laurent Note1: "sudo" will not work inside the container as "qemu-m68k" has not the SUID bit. Just log on on an alternate console as root. Note2: you can mount your host home directory using "mount -b /home /container/m68k/home", but don't forget to create your user inside... Attachment: create-m68k-lxc.sh Description: application/shellscript #include <stdio.h> #include <time.h> /* * This is the number of bits of precision for the loops_per_jiffy. Each * bit takes on average 1.5/CLOCKS_PER_SEC seconds. This (like the original) is a little * better than 1% */ #define LPS_PREC 8 static inline void __delay(unsigned long loops) { __asm__ __volatile__ ("1: subql #1,%0; jcc 1b" : "=d" (loops) : "0" (loops)); } int main(void) { unsigned long ticks, loopbit; int lps_precision = LPS_PREC; unsigned long loops_per_jiffy; unsigned long bogomips; loops_per_jiffy = (1<<12); while ((loops_per_jiffy <<= 1) != 0) { ticks = clock(); while (ticks == clock()) ; ticks = clock(); __delay(loops_per_jiffy); ticks = clock() - ticks; if (ticks) break; } /* Round the value and print it */ bogomips = (loops_per_jiffy * 2) / ticks * CLOCKS_PER_SEC; printf("Clocking:\t%1g\n", (double)bogomips * 33 / 26 / 1000000 ); printf("BogoMips:\t%lu.%02lu\n", bogomips / 1000000, (bogomips / 10000 ) % 100); printf("Calibration:\t%ld\n", loops_per_jiffy); return 0; }
https://lists.debian.org/debian-68k/2012/12/msg00062.html
CC-MAIN-2015-40
refinedweb
560
62.58
One of the complaints I often hear about is keeping scope when using controls and/or event listeners. One of my favourite classes is the Delegate class. This class ensures scope is kept by allowing you to specify the scope when calling a method. For example: import mx.utils.Delegate; class Whatever extends MovieClip { private var someClip_mc:MovieClip; function Whatever() { someClip_mc.onRelease = Delegate.create(this, someMethod); } private function someMethod():Void { trace(this); //this will return a reference to the movieclip that is //attached to the Whatever class and not someClip_mc } } Ok, that’s all fine and dandy, now what if you need to pass a paramater to the method you’re targeting. You could extend the Delegate class and allow for this, or you could write your own class that does the same thing but allows for paramaters to be passed. But really, who has time to do that! Below is the same example as above but this time I pass a paramater to the method. import mx.utils.Delegate; class Whatever extends MovieClip { private var someClip_mc:MovieClip; function Whatever() { var myDel = someClip_mc.onRelease = Delegate.create(this, someMethod); myDel.button = someClip_mc; myDel.index = 4; } private function someMethod():Void { var button:MovieClip = arguments.caller.button; var index:Number = arguments.caller.index; trace(button + ' has an index of ' + index); //this will trace out someClip_mc has an index of 4 } } Now you may be wondering where the heck you would use this. Picture this, you are building a menu system from an xml document. You create buttons dynamically based on the amount of data, all buttons call the same method but the method needs to know what button was selected so it can set its selected state and it also needs to know the content id associated to the button selected so the appropriate content is loaded. Instead of having a seperate method for each content id/button or updating your code everytime the data is updated this allows you to write a completely dynamic menu system in the least amount of code. Like I said above, this isn’t the best solution, but it is a solution to the fact the Macromedia forgot to add in the ability to pass an object along to the method being called. Good news is scope is not an issue in AS 3 so the Delegate class isn’t even needed. Tags: Actionscript, Delegate, Flash
http://www.scottgmorgan.com/blog/index.php/tag/delegate/
crawl-001
refinedweb
399
62.07
For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: Single strategy and single position on multi data - partiallycomplex last edited by Hi, I cant properly set a strategy that has multi data feed (ie the components of sp500) and inside of next() method i ahve put a function call to my personal model . in next method I am trying def my_f(self, x): y = randn() #ie my strategy called on data x return y def next(self): if self.order: return ret={} for d in self.datas: ret[d]=self.my_f(d) best_stock = min(ret, key=ret.get) ...... if not self.position: self.buy(data=d,.....) It doesnt work and it use just a small part of the dataset (ie I have data from 2019-2022, but i see only trades on the last 30 days) If i run the strategy for each single data feed it works best
https://community.backtrader.com/topic/5869/single-strategy-and-single-position-on-multi-data/?
CC-MAIN-2022-40
refinedweb
160
67.69
I was exploring Twitter APIs and thought if I can easily add Twitter widgets to Fiori apps. This especially made sense for Marketing and Campaign Fiori apps. I tried it in jsbin and found it to be very simple and wanted to share that experience. Scenario: Consider you are running a marketing campaign and wanted to keep a tab on the twitter stream for a specific search-term. Step1. Generate Code. First thing to do is to create a widget in Twitter site here. Here you need to provide your search term and “Create Widget”. This will create the code for your widget. For the above Search Query it looked like this. As you can see first line is a HTML tag and second and third line here contain javascript code. Step 2. Adding the generated Code to our Fiori app. XML views can be easily enhanced with HTML without any need to encapsulate the code. Add the first line above where ever you want to display the widget. <mvc:View xmlns: <Page id="page1" title="Products by Category" enableScrolling="false"> <content> <html:a#drilling Tweets</html:a> </content> </Page> </mvc:View> Note that I have added ‘html’ namespace to the ‘a’ tag in the original code. Add the javascript code (2nd and 3rd line in this case, without script tag) in the generated code to the “onInit” method of the controller. That is it. You are done. I have not yet enhanced any Fiori app with this, but got it done in a JS Bin. You can check it here. JS Bin – Collaborative JavaScript Debugging Hope it was useful!
https://blogs.sap.com/2015/12/06/enhance-your-fori-app-with-a-twitter-widget/
CC-MAIN-2017-39
refinedweb
270
82.95
This document assumes that you are familiar with the essentials of XML. It provides you with information on the XML module in Qt and explains some often neglected XML features that will help you make the best use of the Qt XML classes. We will however not teach XML basics. If you wish to learn more about XML please refer to other sources, e.g.. The Qt XML Module provides two interfaces for XML: SAX2 and DOM Level 2.. Furthermore the Qt implementation does not include the SAX1 compatibility classes present in the Java interface. For an introduction to Qt's SAX2 classes see "The Qt SAX2 implementation". A code example is discussed in the "tagreader walkthrough". DOM Level 2 is a W3C Recommendation for XML interfaces that maps the constituents of an XML document to a tree structure. Details and the specification of DOM Level 2 can be found at. More information about the DOM classes in Qt is provided in the Qt XML DOM overview. Parts of the Qt XML module documentation assume that you are familiar with XML namespaces. Here we present a brief introduction; skip to "Qt XML documentation conventions" if you occurence have to. Lets clarify matters).
http://doc.trolltech.com/2.3/xml.html
crawl-001
refinedweb
202
65.42
UpFront November 1st, 2007 by Various in UpFront - LJ Index, November 2007 - Frisky N800 Hack - Bring SMS to the Live Web with a FoxBox - From ACCESS to Excess - diff -u: What's New in Kernel Development - Raising the Social Tide - They Said It LJ Index, November 2007 1. Average measured speed in MBps of a broadband connection with “up to 8Mbps” download speed: 2.7 2. Lowest measured speed in KBps of a broadband connection with “up to 8Mbps” download speed: 90 3. Number of consumers out of five who get the broadband speed they signed up for: 1 4. Percent of surveyed consumers who have felt misled by providers' advertising: 30 5. Billions of Internet users in 2006: 1.1 6. Additional millions of Internet users expected by 2010: 500 7. Millions of video streams per day served by YouTube: 100 8. Number of surveillance cameras in London: 200 9. Trillions of bits sent by London surveillance cameras to their data center: 64 10. Terabytes accumulated per day by Chevron: 2 11. Total exabytes of data in 2006: 161 12. Multiple in millions of 2006 data total to all information in all books ever written: 3 13. Percentage of the digital universe that will be created by individuals by 2010: 70 14. Percentage of the current digital universe that is subject to compliance rules and standards: 20 15. Percentage of the current digital universe that is potentially subject to security applications: 30 16. Exabytes of “user-generated content” expected by 2010: 692 17. Total exabytes of data expected by 2010: 988 18. Percentage of the 2010 digital universe for which organizations will be responsible for security, privacy, reliability and compliance: 85 19. Exabyte capacity of media ready to store newly created and replicated data in the 2010 digital universe: 601 20. Year in which the amount of information created will surpass available storage capacity for the first time: 2007 1, 2: which.co.uk, sourced by David Meyer for ZDNet UK 3, 4: moneysupermarket.com, sourced by David Meyer for ZDNet UK 5–20: “Expanding the Digital Universe”, by John F. Gantz, et al., a March 2007 IDC whitepaper Frisky N800 Hack Keijo Lähetkangas has a fun job at Nokia: taking the company's N800 handheld computer (subject of our September 2007 cover story) and turning it into the brains, faces and controllers of Robot pets. His Puppy and a four-wheeled Rover companion were stars in the demo room at this year's Guadec conference in Birmingham (UK). Puppy is remarkably flexible and expressive. It walks, sits, smiles, dances, sleeps and even—how can we put this politely?—lifts one leg (meaning that Puppy is a male, or at least acts like one). Several Guadec attendees compared Puppy with Sony's Aibo, the most notable difference (besides looks) being the Puppy's openness. It's a pure DIY pet—make of him what you like. Also, Aibo had no eyes. Puppy not only has eyes on his display, but he also can look at the world through the N800's built-in camera, which is in a barely noticeable black cylinder that pops out the side of the N800. It got confusing to take pictures of Puppy and Rover while they took pictures of me, which appeared on other N800s over wireless connections. Puppy and Rover's non-N800 hardware is all from the Robotics.com catalog. The controlling software, all open source, is at. You also can see Puppy in action at youtube.com/puppyrobot. Bring SMS to the Live Web with a FoxBox The forces at Acme Systems and KDev, two veteran embedded Linux system and software developers based in Italy, have conspired to bring the world SMS FoxBox. It's a Linux-based box dedicated to sending and receiving SMS messages that can be managed through a Web interface. It can handle up to 30 incoming messages at a time on a common SIM card. It also works as an SMS to TCP/IP gateway, so you can combine SMS messaging with network and user applications. You can SMS to and from e-mail, MySQL, Web scripts, desktop widgets, whatever. Acme's SMS FoxBox SMS FoxBox is ideal for use in Live Web conditions. Broadcasters can use it to interact with their audiences. Emergency services can use it to flow live reports onto Web sites or broadcasts. Lightweight monitoring, alarm sending, trouble ticketing and remote device management can be moved to SMS from other methods. Databases and address books can be kept current. The unit comes with a GSM quad-band modem, an SD/MMC card for storing messages (it comes default with a 512MB card). It runs on the 2.6 Linux kernel, has a BIS module for failover to up to two backup appliances and an internal clock with a backup battery and NTP support. By the way, you might remember Acme as the source not only of the tiny Acme Fox embedded Linux system board, but for its optional Tux Case as well. Today, that also can come with an Acme Fox SBC (single-board computer). With Kdev's FoxServe firmware, it can work as a dynamic Web server (Apache, PHP, SQLite, SSL/TLS and so on). Acme Systems: KDev: Company Visuals: From ACCESS to Excess The first shoe dropped in September 2005, when ACCESS Co. Ltd. of Japan announced that it would acquire Palm OS developer PalmSource for $324 million. The next shoe dropped in February 2006, when PalmSource detailed the ACCESS Linux Platform (ALP), as an environment open to running Palm OS binaries and Java applications, in addition to native Linux apps. Enough other shoes have dropped since then to give the clear message that ALP has legs. The latest was at LinuxWorld Expo in August 2007, when the company showed screenshots of an iPhone-like UI and provided more details around its plan to make Linux the most supportive environment for mobile device and application development. Chief among these is the Hiker Application framework that fills in some of the formerly missing APIs for mobile applications. Hiker originally was available through the MPL (Mozilla Public License), but it reportedly will be dual-licensed with the LGPL (v2) license as well. Looking beyond the superficial resemblances between what ACCESS showed and the now-familiar iPhone, it's clear that the mobile application market will divide between Web-based (iPhone) and native OS-based (ACCESS, OpenMoko, maemo)—with the latter embracing legacy apps developed for other platforms as well. Thus, the pavement gets wider on the road to truly open mobile devices and markets that grow on them. diff -u: What's New in Kernel Development Linus Torvalds has expressed keen interest in finding someone to put together a full git repository of the kernel, going all the way back to version 0.01. He's tried this himself a couple times, and other folks have made various efforts, but it's a hard problem. Certainly, it would not be possible to include every patch that went into the kernel, in the order it was included, because many patches never were sent to any public forum. Even finding the release announcements for all the numbered versions will be difficult, and some official releases are thought to be lost as well. It's a daunting task, but a very valuable one, even if done incompletely. If someone can do it, Linus has offered to comment the various early patches and releases, from memory. Mingming Cao has submitted patches to allow the ext4 filesystem to perform checksum calculations on its journal to make sure that any corruption is identified as quickly as possible. With interest from various folks, including Andrew Morton, it looks like this feature quickly will be adopted into the official tree, although ext4 still remains a fairly experimental filesystem. LinuxConf Europe 2007 (LCE) will host a semi-formal discussion of containers within the kernel. Serge E. Hallyn recently announced plans to arrange for a conference room (including phone lines for anyone who can't be present but still wants to participate) and a series of half-hour presentations. Containers provide a way to cluster processes into specific namespaces that are isolated from the rest of the system and are related to virtualization projects like Xen. Michal Piotrowski has announced the “Linux Kernel Tester's Guide”, translated by Rafael J. Wysocki, at. It is a long document representing much work, it reads like a book, and it clearly explains a lot of material that most discussions on the linux-kernel mailing list tend to assume—for example, how to do a binary search with git to identify precisely when a particular bug was introduced into the tree. Several projects have changed hands recently. Valerie Henson has had to abandon the Tulip driver, and now it looks like Kyle McMartin may become the official maintainer. Wim Van Sebroeck has submitted a patch to make Mike Frysinger the official maintainer of the Blackfin Watchdog driver. Mike Sharkey of Pike Aerospace Research Corporation has volunteered to take over the otherwise unmaintained Parallel Port driver on behalf of his company. And, Anton Vorontsov recently became a co-maintainer of the Power Supply subsystem, along with David Woodhouse. Over time, various features have gone into the kernel to support more and more modern architectures. But, for some of these features that have no serious negative impact on older hardware, such as the 386 processor, there's been no real effort to isolate the unneeded features from that older hardware. Kernels compiled for those systems, therefore, have tended to have larger and larger binaries and to require more and more RAM to run. For the most part, no one notices or cares, because most people don't bother running Linux on the 386 anymore. But, the effect has been there, building gradually. Jonathan Campbell recently started submitting patches to ensure that architectures like the 386 would compile only features that actually would work on those systems. So, things like the Pentium TSC register would not be included in compiled 386 kernel binaries. The result of his work was a much smaller binary, and his patches probably will be adopted into the main kernel tree. This kind of support for legacy systems might have an impact on projects to bring computing resources to third-world countries and impoverished neighborhoods or lower the cost of experimenting with clustered solutions. Raising the Social Tide Brad Fitzpatrick has a long pedigree for a young guy. Besides creating LiveJournal—one of the earliest and most popular blogging services (and an open-source one at that)—he is the creator of OpenID, Perlbal, MogileFS, memcached, djabberd and many other fine hacks. Astute readers may recall “Distributed Caching with Memcached”, which Brad wrote for Linux Journal in 2004. Today, memcached is one of the world's most widely used distributed caching methods, while OpenID is a breakaway leader in the user-centric identity field. In August 2007, Brad published “Thoughts on the Social Graph” (bradfitz.com/social-graph-problem), which presents this problem statement: There are an increasing number of new “social applications” as well as traditional applications that either require the “social graph” or that could provide better value to users by utilizing information in the social graph. What I mean by “social graph” is the global mapping of everybody and how they're related, as Wikipedia describes it (en.wikipedia.org/wiki/Social_graph). Unfortunately, there doesn't exist a single social graph (or even multiple graphs that interoperate) that's comprehensive and decentralized. Rather, there exists hundreds of disperse social graphs, most of dubious quality and many of them walled gardens. At the time, Wikipedia's “social network” entry (same as its “social graph” entry) said, “Social network analysis views social relationships in terms of nodes and ties. Nodes are the individual actors within the networks, and ties are the relationships between the actors.” Elsewhere in Wikipedia, “Graph” is explained as a mathematical concept, “a set of objects called points, nodes, or vertices connected by links called lines or edges”. So, the first idea is to move the center of social networking gravity outside the silo'd sites, each of which impose inconveniences on themselves as well as their members. As Brad says, “People are getting sick of registering and re-declaring their friends on every site.” The process is also silly. Not long after Google's Orkut social network site went up, Rael Dornfest made fun of the friendship-declaring protocol by walking up to people he knew and saying, “You are my friend? Yes or no?” The second idea is to make society itself a platform. Or, in Brad's terms, to “make the social graph a community asset”, and “to build the guts that allow a thousand new social applications to bloom”. Significantly, most social network sites (all but MySpace, I believe) run on Linux. Wikipedia too. If Brad's right, we can equip the rising social network tide that lifts all boats. There should even be plenty of work converting today's silos into tomorrow's arks. For more, visit bradfitz.com/social-graph-problem, or just look up “social graph” on the vast Linux hack called Google. The lucky top result probably will be Brad's. They Said It If our customers buy bandwidth from us, and they want to share it with neighbors, or publicly, that doesn't make them bad customers. —Joe Plotkin, Bway.net, ...the commercial concerns from the very beginning, even when they were small, were really very important. The commercial distributions were what drove a lot of the nice installers, and pushed people to improve usability.......If you have a purely marketing (or customer) driven approach, you end up with crap technology in the end. But I think that something that is purely driven by technical people will also end up as crap technology in the end, and you really need a balance here. It's exciting to go to work each day knowing that scads of companies are using your software, then contacting you to get additional value. It's not easy by any stretch, but it's a lot more efficient and productive than the proprietary
http://www.linuxjournal.com/article/9871
crawl-002
refinedweb
2,376
60.95
Fetch Driver::Succeed With Response/Fail With Network Error always return NS_OK RESOLVED FIXED in Firefox 47 Status () ▸ DOM People (Reporter: jdm, Assigned: Stefan Dye, Mentored) Tracking Firefox Tracking Flags (firefox43 affected, firefox47 fixed) Details (Whiteboard: [lang=c++][good first bug]) Attachments (2 attachments, 4 obsolete attachments) We should give them a void return value instead. Code: dom/fetch/FetchDriver.cpp I'm interested in fixing this bug. Can you please assign it to me? Great! Let me or jdm know if you need help. Assignee: nobody → stefandye Status: NEW → ASSIGNED I'm confused as to what direction to take with this bug fix. I've messaged khuey with this already to apologies for the double post. The fix requested was to have SucceedWIthResponse() and FailWithNetworkError() return nothing, At first glance I though this meant the signatures should be have void return types in dom/fetch/FetchDriver.cpp. However some functions like FetchDriver::BasicFetch() have an nsresult return type and are returning the output of one of these functions (SucceedWIthResponse for this function) in the function definition. What I can think of right away are these two solutions: Option 1 : The most obvious thing to do would be to make the caller's return type void, but that's likely to propagate through many other functions so I have a feeling that's not the right solution. Option 2: Return NS_OK from the caller functions that require an nsresult. I'm unsure if that's a good idea, since the goal of the fix was to eliminate the same issue in SucceedWithResponse() and FaulWithNetworkError(). . However, after reading the fetch specification at, it seems that return a network error which is defined as a 0 response, empty bytes sequence . " A network error is a response whose status is always 0, status message is always the empty byte sequence, header list is always empty, body is always null, and cache state is always "none"". It seems this is handled by line 714 in FetchDriver.cpp : nsRefPtr<InternalResponse> error = InternalResponse::NetworkError(); This would seem to imply that option 2 may work. Is this true? Or if not can you please explain? Any guidance and clarification would be of great help. Thanks, Stefan Flags: needinfo?(josh) The solution here is to move the `return NS_OK` to the callers. This should not cause the same situation because they contain instance of returning non-NS_OK values (the NS_ENSURE_SUCCESS macros contain a hidden return in the error case). Flags: needinfo?(josh) Created attachment 8668760 [details] [diff] [review] FetchDriver.h Message for jdm. Please review. Uploaded FetchDriver.h . (1 of 2 files) Created attachment 8668761 [details] [diff] [review] FetchDriver.cpp Uploaded for review by :jdm . Please review FetchDriver.cpp patch (2 of 2) For future reference, I recommend setting the `review` flag to `?` and adding `:jdm`. That will specifically alert me that there are changes awaiting my review. Also, combining the changes into a single diff file is preferred, if they are part of the same set of changes. Comment on attachment 8668761 [details] [diff] [review] FetchDriver.cpp Review of attachment 8668761 [details] [diff] [review]: ----------------------------------------------------------------- This is generally moving in the right direction, but we need to ensure that we continue to return from the methods at the same time the old code did, otherwise we will end up changing the behaviour of the callers of SucceedWithResponse/FailWithNetwork error. Does that make sense? A good way to verify that these changes are working correctly is to run the appropriate tests: `./mach mochitest dom/tests/mochitest/fetch` ::: dom/fetch/FetchDriver.cpp @@ +208,4 @@ > } > > MOZ_ASSERT_UNREACHABLE("Unexpected main fetch operation!"); > + FailWithNetworkError(); nit: remove the extra space before Fail. @@ +648,5 @@ > MOZ_ASSERT(mResponse); > MOZ_ASSERT(!mResponse->IsError()); > > + SucceedWithResponse(); > +return NS_OK; nit: indent this to match the previous line, please. @@ +699,4 @@ > // Release the ref. > } > > +void //nsresult There's no need for comments like this, since the whole premise of diff files is that they show the before and after changes. @@ +707,5 @@ > mObserver->OnResponseEnd(); > mObserver = nullptr; > } > +// removed NS_OK as this is a now void function, see bug 1204520. > +//since SuccedWithResponse handles the observers internally, NS_OK is not needed. These comments don't really provide any additional information over looking in the file history, so let's remove them. @@ +722,5 @@ > mObserver->OnResponseEnd(); > mObserver = nullptr; > } > +// removed NS_OK as this is a now void function, see bug 1204520 > +// in the case of a failure, the Network error is communicated via an internal response object, therefore the NS_OK return result is not needed. Same here. @@ +1118,4 @@ > } > > } // namespace dom > +} Please revert this change. Attachment #8668761 - Flags: feedback+ Hey jdm, Thanks for providing feedback. I've noted the above comments and am making the changes. Just wish to clarify one point. "but we need to ensure that we continue to return from the methods at the same time the old code did, otherwise we will end up changing the behaviour of the callers of SucceedWithResponse/FailWithNetwork error." Is this a rule of thumb? Just curious because I ran the `./mach mochitest dom/tests/mochitest/fetch` and got zero failures with the previous implementation. But from your statement I'm inferring that other functions that rely on the fetch driver implementation and not covered by this suite of tests may break because of this change? Please elaborate if I'm incorrect. I wouldn't call it a rule of thumb, more like a rule of refactoring :) I admit that I'm extremely surprised that the tests didn't display any failures! Perhaps you're using a release build, not a debug one? shows how to make that switch. I'd like to help what should i do? Hi Dalak! It's been a month since Stefan replied, so you could import the patch attached to this bug and address the review comments from comment 8. Created attachment 8696600 [details] dom mochitest run Hey jdm, I ran sudo ./mach mochitest ./dom/fetch/ got some unexpected fails. Where are the logs stored? I just want to be able to trace where those failures are coming from. Sorry for the delay in replying; I was at a conference all last week that took up all my attention. There are no stored logs by default. You would need to run the mach command with >mochitest.log for that. I'll also point out that it should never be necessary to use sudo with mach. Created attachment 8698327 [details] [diff] [review] FetchDriverPatch Hey jdm, Uploading my patch for review. 39 tests passed. 8 tests failed. I also ran the same test after building the source cleanly and got the same results. So it seems my patch added no new bugs Attachment #8668760 - Attachment is obsolete: true Attachment #8668761 - Attachment is obsolete: true Comment on attachment 8698327 [details] [diff] [review] FetchDriverPatch Review of attachment 8698327 [details] [diff] [review]: ----------------------------------------------------------------- Hi Stefan! Sorry for the long wait; this came at the tail end of week-long conference and then there were holidays, etc. I find it strange that you see test failures before making changes, since the tests are all supposed to be passing. Are you sure you made a build that didn't include any changes before running the tests? Regardless, we're going to need to ensure that every piece of code that used to have `return FailWithNetworkError` or `return SucceedWithResponse` continues to return from the method after these changes. There are a lot of unintentional control flow changes in the current patch. ::: dom/fetch/FetchDriver.cpp @@ +252,4 @@ > > response->SetBody(body); > BeginResponse(response); > + SucceedWithResponse(); This is the bit that really surprises me when you say that you don't get any different test results, given that we used to return from this method, and now fall through to a failure case. We're definitely going to need to change this to continue returning here. Perhaps running `./mach mochitest-plain dom/workers/test/serviceworkers/` or `./mach web-platform-tests testing/web-platform/mozilla/tests/service-workers/service-worker` would expose some errors with these changes... Hey Josh, Apologies for being M.I.A. I had to actually get a new computer! Was finally able to re-checkout the mozilla source and redo the patch. I am no longer seeing the SucceedWithResponse function in FetchDriver.cpp. Running ./mach build now yields no errors. And the fix seems to work. Uploading FetchTests.txt with test results. FetchDriver.cpp and FetchDriver.h patch. Created attachment 8714196 [details] [diff] [review] FetchDriver header and cpp changes, second uploadbnbn Attachment #8698327 - Attachment is obsolete: true Attachment #8714196 - Flags: review?(josh) Created attachment 8714197 [details] FetchTests.txt results of test run Attachment #8696600 - Attachment is obsolete: true Attachment #8714196 - Attachment is patch: true Attachment #8714196 - Attachment mime type: text/x-patch → text/plain Comment on attachment 8714196 [details] [diff] [review] FetchDriver header and cpp changes, second uploadbnbn Review of attachment 8714196 [details] [diff] [review]: ----------------------------------------------------------------- Huh, this code has changed significantly since you originally started looking at this, apparently :) Attachment #8714196 - Flags: review?(josh) → review+ Bug 1204520 - Remove unused return value from FetchDriver::FailWithNetworkError. r=jdm Status: ASSIGNED → RESOLVED Last Resolved: 2 years ago status-firefox47: --- → fixed Resolution: --- → FIXED Target Milestone: --- → mozilla47
https://bugzilla.mozilla.org/show_bug.cgi?id=1204520
CC-MAIN-2018-09
refinedweb
1,520
56.55
In scipy.stats we can find a class to estimate and use a gaussian kernel density estimator, scipy.stats.stats.gaussian_kde. Until recently, I didn’t know how this part of scipy works, and the following describes roughly how I figured out what it does. First, we can look at help to see whether the documentation provides enough information for its use. Here is the first part. >>> help(stats.gaussian_kde) Help on class gaussian_kde in module scipy.stats.kde: class gaussian_kde(__builtin__.object) | Representation of a kernel-density estimate using Gaussian kernels. | | Parameters | ---------- | dataset : (# of dims, # of data)-array | datapoints to estimate from | | Members | ------- | d : int | number of dimensions | n : int | number of datapoints | | Methods | ------- | kde.evaluate(points) : array | evaluate the estimated pdf on a provided set of points | kde(points) : array | same as kde.evaluate(points) | kde.integrate_gaussian(mean, cov) : float | multiply pdf with a specified Gaussian and integrate over the whole domain | kde.integrate_box_1d(low, high) : float | integrate pdf (1D only) between two bounds | kde.integrate_box(low_bounds, high_bounds) : float | integrate pdf over a rectangular space between low_bounds and high_bounds | kde.integrate_kde(other_kde) : float | integrate two kernel density estimates multiplied together | | Internal Methods | ---------------- | kde.covariance_factor() : float | computes the coefficient that multiplies the data covariance matrix to | obtain the kernel covariance matrix. Set this method to | kde.scotts_factor or kde.silverman_factor (or subclass to provide your | own). The default is scotts_factor. | | Methods defined here: | | __call__ = evaluate(self, points) | | __init__(self, dataset) | | covariance_factor = scotts_factor(self) | | evaluate(self, points) | Evaluate the estimated pdf on a set of points. | ... The first two basic methods that I was interested in is the initialization, __init__ just takes a data set as a argument, and then evaluate, or __call__ which takes as function argument the list of points at which we want to evaluated the estimated pdf. Let’s just try this out: First, I get the standard imports: import numpy as np from scipy import stats import matplotlib.pylab as plt then I generate a sample that I can feed to the kde, as usual for continuous variables, I start with a normal distribution: n_basesample = 1000 np.random.seed(8765678) xn = np.random.randn(n_basesample) Now, we create an instance of the gaussian_kde class and feed our sample to it: gkde=stats.gaussian_kde(xn) We need some points at which we evaluate the density funtion for the estimated density function: ind = np.linspace(-7,7,101) kdepdf = gkde.evaluate(ind) and finally we create the plot of the histogram of our data, together with the density that created our sample, the data generating process DGP, and finally the estimated density. plt.figure() # plot histgram of sample plt.hist(xn, bins=20, normed=1) # plot data generating density plt.plot(ind, stats.norm.pdf(ind), color="r", label='DGP normal') # plot estimated density plt.plot(ind, kdepdf, label='kde', color="g") plt.title('Kernel Density Estimation') plt.legend() #plt.show() and this is the graph that we get This graph looks pretty good, when the underlying distribution is the normal distribution, then the gaussian kernel density estimate follows very closely the true distribution, at least for a large sample as we used. Now, to make it a bit more difficult we can look at a bimodal distribution, and see if it is still able to fit so well. As an example, I pick a mixture of two normal distributions, 60% of the sample comes from a normal distribution with mean -3 and standard deviation equal to one, 40% of the observation are from the normal distribution with mean 3 and the same standard deviation. alpha = 0.6 #weight for (prob of) lower distribution mlow, mhigh = (-3,3) #mean locations for gaussian mixture xn = np.concatenate([mlow + np.random.randn(alpha * n_basesample), mhigh + np.random.randn((1-alpha) * n_basesample)]) With the new data set, we can run the same commands as above, except that we have to change the plot of the data generating density to use the mixture density instead: plt.plot(ind, alpha * stats.norm.pdf(ind, loc=mlow) + (1-alpha) * stats.norm.pdf(ind, loc=mhigh), color="r", label='normal mix') The next graph shows what we get in this case. The estimated density is oversmoothing, the peaks of the estimated pdf are too small. So the automatic selection of the smoothing parameter doesn’t work in this case. Now, it’s time to find out how gaussian_kde actually selects the smoothing parameter or bandwith of the kernel. But I’m out of time for today. We dig into this next time. Hello, I work daily with the scipy.stats.kde package and I find it quite useful. If you make some improvements, I would really appreciate to know it! Regards Stefano Hi, I found this tutorial very helpful, thanks! I think that any kde will always broaden distributions somewhat, more so for small sample sizes. I tried to illustrate this point by giving just one sample, but this results in a ValueError. (Btw, giving an array of ints results in a gaussian_kde value of 0, which probably is a bug?) One very clear example of broadening is sampling a uniform distribution within limits 0 to 1 and computing the gaussian_kde, which will always have Gaussian wings below 0 and above 1, where the pdf really was 0. If you find out how the automatic kernel width selection works, whether it is adaptive with position (smaller width in regions of higher sample density) and how it can be influenced by the user, or if it is possible to introduce limits xmin, xmax beyond which the gaussian_kde pdf is 0, please share! Cheers, --Christoph thank you for this tutorial! This fail with 2D data set. How to estimate KDE if you have 2D point (X,Y) ? Thanks for the example code In case you want to fiddle with the bandwidth, you can use the "set_bandwidth" function - it takes a constant or a function or a name of it's inbuilt functions. In some cases you may want to reduce to smoothing - I find it estimates far too high
http://jpktd.blogspot.com/2009/03/using-gaussian-kernel-density.html
CC-MAIN-2015-18
refinedweb
1,013
56.05
I can’t tell if you’re meant to do this kind of thing to vows. I honestly can’t. It’s either a demonstration of the power of the architecture, or it’s a phenomenal hack that shouldn’t be allowed out in broad daylight. Either way, I’m probably thinking too LISP-ily for my own good. Let’s say that you’re trying to test the behaviour of a workflow. Under certain conditions, certain things should happen. The problem is, some of those certain conditions are pretty verbose. In fact, if you’ve got three yes/no decisions to make, you’re left having to set up eight different scenarios (more if you’re testing the intermediate states). Now, in most testing environments, this is what you have “setup” for. However, it only really works if you can have nested setup procedures, like “before” in RSpec. Vows, on the other hand, creates a topic once and then tests run against that one topic. Not really ideal for testing workflows. So, I thought “why not make the topic itself a factory”. That way, I could call the topic in each test and set it up repeatedly. Then it occurred to me that, ideally, later topics should contain instructions on how to get the topic into the correct state, reducing the amount of repetition that we saw in my previous post. Finally it occurred to me that, ultimately, the entire batch specification is just a hash table. So, I wrote a function that rewrites a batch to do workflows: withSetup = (batch) -> setupTopic = (f) -> (topic) -> -> # N.B. The topic is a factory. The setupTopic function returns a factory as well return f() unless topic? # Resolve item # Apply item to topic and return topic t = topic() f(t) t inner = (item) -> # The item is a test # Take the topic, resolve it and run tests in "item" return ((topic) -> item topic()) unless typeof item == 'object' # The item is a batch for k,v of item item[k] = (if k == 'topic' then setupTopic else inner) v item inner batch All you need to do is add withSetup to the addBatch invocation. vows.describe('Guessing Game').addBatch(withSetup({ 'Player is playing a guessing game' : { topic : -> new game.Player(new StubEmitter(), guessingGameFactory) 'should be able to start a game' : (p) -> assert.isFalse p.game? p.client.emit 'message', { action : 'start' } assert.isNotNull p.game assert.equal p.client.data.question, "Guess what number I'm thinking of" 'after game has started' : { topic : (p) -> p.client.emit 'message', { action : 'start' } 'correct guess' : (p) -> p.client.emit 'message', { action : 'answer', answer : 1 } assert.isTrue p.client.data.wasRight 'wrong guess' : (p) -> p.client.emit 'message', { action : 'answer', answer : 2 } assert.isFalse p.client.data.wasRight 'after correct answer' : { topic : (p) -> p.client.emit 'message', { action : 'answer', answer : 1 } 'We're now on the second question' : (p) -> assert.equal p.playerActions.game.currentQuestionCount, 2 } } } })).export module As I say, I can’t figure out if this works because Cloudhead’s really smart or I’m really stupid. One thought on “Hacking State in Vows.js with CoffeeScript” Have you developed this ideas further?If I understand what you are saying here, this is how I’m actually using the Rspec let() feature — for declaring little snippets that end up with a factory. I’m not very happy with how I use it though. What I really want is end up with some sort of auto-discovery testing.
https://colourcoding.net/2010/11/08/hacking-state-in-vows-js-with-coffeescript/
CC-MAIN-2022-21
refinedweb
579
65.42
From: Andy Little (andy_at_[hidden]) Date: 2006-08-20 10:19:59 "Matthias Troyer" <troyer_at_[hidden]> wrote > > On Aug 20, 2006, at 10:42 AM, Andy Little wrote: > >> >> "Janek Kozicki" <janek_listy_at_[hidden]> wrote in message >> news:20060819212430.739b0920_at_absurd... >>> Andy Little said: (by the date of Sat, 19 Aug 2006 13:03:42 <...> >> double var1= 10; // var1 meters >> double var2 = 10 ; // var2 represents meters. >> >> var1 *= var2 ; // var1 now represents an area in square meters. >> >> Of course you cant do this with a fixed_quantity: >> >> quan::length::m var1(10); >> quan::length::m var2(10); >> var1 *= var2 ; // Error >> >> >> I would guess that is an unacceptable restriction for many authors >> of algebra >> libraries. > > Why should this be an unacceptable restriction? If you want the highest performance then in place operations are generally faster ( at least in my admittedly limited experience) than binary operations,at least for UDT's. > All it says is that a > quantity with units is not a field, but that is obvious from the > start. I can multiply a vector (3m, 2m, 1m) by a factor of 5 but not > by a factor of 5m. I see no problem here at all, except if you assume > that the element type of a vector is the same type as the scalar > factor in your expression. It is also possible to multiply a vector quantity by a scalar quantity: #include <quan/three_d/vect.hpp> #include <quan/velocity.hpp> #include <quan/acceleration.hpp> #include <quan/time.hpp> #include <quan/mass.hpp> #include <quan/length.hpp> int main() { typedef quan::acceleration::m_per_s2 accel; typedef quan::velocity::m_per_s velocity; typedef quan::length::m length; using quan::three_d::vect; typedef vect<accel> accel_vect; typedef vect<velocity> velocity_vect; typedef vect<length> distance_vect; accel_vect a(accel(1),accel(2),accel(3)); velocity_vect u(velocity(0),velocity(-1), velocity(0)); quan::time::s t(1); distance_vect s = u * t + 0.5 * a * quan::pow<2>(t); } The above creates a lot of temporaries of course. The fastest way ( at least from my own admittedly limited experiments) to do this seems to be: T s = u; s *= t; T temp = 0.5; temp *= a; temp *= t; temp *= t; s += temp; In fact you can do in place addition of quantities of course, but not multiplication, or at least not without low level manipulations. It sounds like I am arguing against my own library. I'm not, but I am pointing out that there are different considerations when using quantities and you may not ( in fact probably wont) get as good a performance as from using inbuilt floats. Overall Quan is much more fun to use than floats though, and I have enjoyed using it so far where possible.. <...> >> Maybe, if we can get Quan into Boost then we will be in a stronger >> position and >> there may then be interest in creating a linear generic algebra >> library for >> physical quantities, but I suspect that due to the above kind of >> issues, there >> will always be a great divide between a 'raw' linear algebra >> library and one >> that is designed to work with physical quantities. > > I don't agree. For me there is no such thing as 'raw' linear > algebra. All linear algebra concepts work perfectly with quantities > with units. FWIW I do see the difference between using quantities and floats as very coarsely equivalent to the difference between using an assembly language and (say) C. When using quantities you are effectively using a higher level language than standard C ++ using floats. regards Andy Little Boost list run by bdawes at acm.org, david.abrahams at rcn.com, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
http://lists.boost.org/Archives/boost/2006/08/109365.php
crawl-001
refinedweb
610
55.44
Your Python code can be up on a code editor, IDE or a file. And, it won’t work unless you know how to execute your Python script. In this blog post, we will take a look at 7 ways to execute Python code and scripts. No matter what your operating system is, your Python environment or the location of your code – we will show you how to execute that piece of code! Table of Contents - Running Python Code Interactively - How are Python Script is Executed - How to Run Python Scripts - How to Run Python Scripts using Command Line - How to Run Python Code Interactively - Running Python Code from a Text Editor - Running Python Code from an IDE - How to Run Python Scripts from a File Manager - How to Run Python Scripts from Another Python Script Where to run Python scripts and how? You can run a Python script from: - OS Command line (also known as shell or Terminal) - Run Python scripts with a specific Python Version on Anaconda - Using a Crontab - Run a Python script using another Python script - Using FileManager - Using Python Interactive Mode - Using IDE or Code Editor Running Python Code Interactively To start an interactive session for Python code, simply open your Terminal or Command line and type in Python(or Python 3 depending on your Python version). And, as soon as you hit enter, you’ll be in the interactive mode. Here’s how you enter interactive mode in Windows, Linux and MacOS. Interactive Python Scripting Mode On Linux Open up your Terminal. It should look something like $ python Python 3.7.3 (default, Mar 27 2019, 22:11:17) [GCC 7.3.0] :: Anaconda, Inc. on linux Type "help", "copyright", "credits" or "license" for more information. Enter the Python script interactive mode after pressing “Enter”. Interactive Python Scripting Mode On Mac OSX Launching interactive Python script mode on Mac OS is pretty similar to Linux. The image below shows the interactive mode on Mac OS. Interactive Python Scripting Mode On Windows On Windows, go to your Command Prompt and write “python”. Once you hit enter you should see something like this: Running Python Scripts Interactively With interactive Python script mode, you can write code snippets and execute them to see if they give desired output or whether they fail. Take an example of the for loop below. Recommended Python Training For Python training, our top recommendation is DataCamp. Our code snippet was written to print everything including 0 and upto 5. So, what you see after print(i) is the output here. To exit interactive Python script mode, write the following: >>>exit() And, hit Enter. You should be back to the command line screen that you started with initially. There are other ways to exit the interactive Python script mode too. With Linux you can simply to Ctrl + D and on Windows you need to press Ctrl + Z + Enter to exit. Note that when you exit interactive mode, your Python scripts won’t be saved to a local file. How are Python scripts executed? A nice way to visualize what happens when you execute a Python script is by using the diagram below. The block represents a Python script (or function) we wrote, and each block within it, represents a line of code. When you run this Python script, Python interpreter goes from top to bottom executing each line. And, that’s how Python interpreter executes a Python script. But that’s not it! There’s a lot more that happens. Flow Chart of How Python Interpreter Runs Codes. There are some benefits of inspecting bytecode. And, if you aim to turn yourself into a pro level Pythonista, you may want to learn and understand bytecode to write highly optimized Python scripts. You can also use it to understand and guide your Python script’s design decisions. You can look at certain factors and understand why some functions/data structures are faster than others. How to run Python scripts? To run a Python script using command line, you need to first save your code as a local file. Let’s take the case of our local Python file again. If you were to save it to a local .py file named python_script.py. There are many ways to do that: - Create a Python script from command line and save it - Create a Python script using a text editor or IDE and save it Saving a Python script from a code editor is pretty easy. Basically as simple as saving a text file. But, to do it via Command line, there are a couple of steps involved. First, head to your command line, and change your working directory to where you wish to save the Python script. Once you are in the right directory, execute the following command in Terminal: $ sudo nano python_script.py Once you hit enter, you’ll get into a command line interface that looks something like this: Now, you can write a Python code here and easily run it using command line. How to run Python scripts using command line? Python scripts can be run using Python command over a command line interface. Make sure you specify the path to the script or have the same working directory. To execute your Python script(python_script.py) open command line and write python3 python_script.py Replace python3 with python if your Python version is Python2.x. Here’s what we saved in our python_script.py for i in range(0,5): print(i) And, the output on your command line looks something like this Let’s say, we want to save the output of the Python code which is 0, 1, 2, 3, 4 – we use something called a pipe operator. In our case, all we have to do is: $python python_script.py > newfile.txt And, a file named “newfile.txt” would be created with our output saved in it. How to run Python code interactively There are more than 4 ways to run a Python script interactively. And, in the next few sections we will see all major ways to execute Python scripts. Using Import to run your Python Scripts We all use import module to load scripts and libraries extremely frequently. You can write your own Python script(let’s say code1.py) and import it into another code without writing the whole code in the new script again. Here’s how you can import code1.py in your new Python script. >>> import code1 But, doing so would mean that you import everything that’s in code1.py to your Python code. That isn’t an issue till you start working in situations where your code has to be well optimized for performance, scalability and maintainability. So, let’s say, we had a small function inside code1 that draws a beautiful chart e.g. chart_code1(). And, that function is the only reason why we wish to import the entire code1.py script. Rather than having to call the entire Python script, we can simply call the function instead. Here’s how you would typically do it >>> from code1 import chart_code1 And, you should be able to use chart_code1 in your new Python script as if it were present in your current Python code. Next, let’s look at other ways to import Python code. Using and importlib to run Python code import_module() of importlib allows you to import and execute other Python scripts. The way it works is pretty simple. For our Python script code1.py, all we have to do is: import importlib import.import_module(‘code1’) There’s no need to add .py in import_module(). Let’s go through a case where we have complex directory structures and we wish to use importlib. Directory structure of the Python code we want to run is below: level1 | + – __init__.py – level2 | + – __init__.py – level3.py In this case if you think you can do importlib.import_module(“level3”), you’ll get an error. This is called relative import, and the way you do it is by using a relative name with anchor explicit. So, to run Python script level3.py, you can either do importlib.import_module(“.level3”, “level1.level”) or you can do importlib.import_module(“level1.level2.level3”). Run Python code using runpy Runpy module locates and executes a Python script without importing it. Usage is pretty simple as you can easily call the module name inside of run_module(). To execute our code1.py module using runpy. Here’s what we will do. >>> import runpy >>> runpy.run_module(mod_name=”code1”) Run Python Code Dynamically We are going to take a look at exec() function to execute Python scripts dynamically. In Python 2, exec function was actually a statement. Here’s how it helps you execute a Python code dynamically in case of a string. >>> print_the_string = ‘print(“Dynamic Code Was Executed”)’ >>> exec(print_the_string) Dynamic Code Was Executed However, using exec() should be a last resort. As it is slow and unpredictable, try to see if there are any other better alternatives available. Running Python Scripts from a Text Editor To run Python script using a Python Text Editor you can use the default “run” command or use hot keys like Function + F5 or simply F5(depending on your OS). Here’s an example of Python script being executed in IDLE. Source: pitt.edu However, note that you do not control the virtual environment like how you typically would from a command line interface execution. That’s where IDEs and Advanced text editors are far better than Code Editors. Running Python Scripts from an IDE When it comes to executing scripts from an IDE, you can not only run your Python code, but also debug it and select the Python environment you would like to run it on. While the IDE’s UI interface may vary, the process would be pretty much similar to save, run and edit a code. How to run Python scripts from a File Manager What if there was a way to run a Python script just by double clicking on it? You can actually do that by creating executable files of your code. For example, in the case of Windows OS, you can simply create a .exe extension of your Python script and run it by double clicking on it. How to run Python scripts from another Python script Although we haven’t already stated this, but, if you go back up and read, you’ll notice that you can: - Run a Python script via a command line that calls another Python script in it - Use a module like import to load a Python script That’s it! Key Takeaway - You can write a Python code in interactive and non interactive modes. Once you exit interactive mode, you lose the data. So, sudo nano your_python_filename.py it! - You can also run your Python Code via IDE, Code Editors or Command line - There are different ways to import a Python code and use it for another script. Pick wisely and look at the advantages and disadvantages. - Python reads the code you write, translates it into bytecodes, which are then used as instructions – all of that happen when you run a Python script. So, learn how to use bytecode to optimize your Python code. Recommended Python Training For Python training, our top recommendation is DataCamp.
https://www.pythonforbeginners.com/development/how-run-your-python-scripts?utm_source=rss&utm_medium=rss&utm_campaign=how-run-your-python-scripts
CC-MAIN-2021-31
refinedweb
1,892
73.17
On Thu, 7 Mar 2002, Peter Donald wrote: > I vaguely remember we voted against URI namespace support in ant2 and instead > voted for namespace support similar to javas "import" namespace. I am not > sure if that is changed. I vaguely remember W3C voted for namespace support in XML :-) I'm not sugesting that ant should require namespaces, or get into the religious discussion about the meaning of a namespace. I'm just saying they are part of the xml standard, and it's a good idea to design the task factory API with namespace ( in the generic sense ) in mind. If it's going to be a java-style package name or something else - it doesn't matter from the point of view of the factory interface. > > BTW, a 'namespace' is not an XML thing - it's a way to group > > tasks ( same as a package name in java, etc ). Having a flat > > naming for tasks doesn't scale very well. > > Nope - but we don't have to couple to URI directly. Reverse DNS naming of > java packages or C#s namespace seems to work well and is reasonably familiar > to most developers using ant. I agree, the semantic of the namespace is not my issue. The default for ant1 is clearly no namespace, and that should continue to be supported, but for user-defined components ( some maybe using the task factory ) it's important to leave the door open. > > Yes, the factory should return a ProjectComponent - be it a Task or > > DataType. It may return an adapter - i.e. TaskAdapter, or a DataType > > adapter. > > But all adapters extend ProjectComponent, right? Right. I'll change the interface. > > Regarding classloader - there is no need to modify anything else in ant. > > You can plug in a TaskFactory that implements/uses whatever class loader > > and policy it wants - no other piece of ant cares about this as long > > as it is consistent. > > You sure. Thats what I thought until I started to implement it ;) I'm very sure, no need to worry about that. > > It would be very good to have myrmidon and mutant factories wrapped and > > usable with ant1.5 - and I think making this work is essential, so > > if there's anything missing let me know. > > The factory interface as it stands is fine - the tricky bit will be how the > factorys are registered. I don't think your proposal addresses that just yet? Oh, that's trivial. Just 1 method in Project - addProjectComponentHelper(), and all helpers will be called before defaulting the Class. It's exaclty how normal task registation take place - a task like taskdef can register new tasks - or task factories. Well, probably a better solution would be to move all the code from createTask/createType in a DefaultProjectComponentHelper, so Project code will be cleaner and simpler - I'll try this out. Costin -- To unsubscribe, e-mail: <mailto:ant-dev-unsubscribe@jakarta.apache.org> For additional commands, e-mail: <mailto:ant-dev-help@jakarta.apache.org>
http://mail-archives.apache.org/mod_mbox/ant-dev/200203.mbox/%3CPine.LNX.4.33.0203061559500.1968-100000@dyn-62.sfo.covalent.net%3E
CC-MAIN-2013-48
refinedweb
498
63.8
This class creates a dictionary of all the units you want to know. More... #include <Units_UnitsDictionary.hxx> This class creates a dictionary of all the units you want to know. Returns an empty instance of UnitsDictionary. Returns for <aquantity> the active unit. Returns a UnitsDictionary object which contains the sequence of all the units you want to consider, physical quantity by physical quantity. Dumps for a designated physical dimensions <adimensions> all the previously stored units. Dumps only the sequence of quantities without the units if <alevel> is equal to zero, and for each quantity all the units stored if <alevel> is equal to one. Returns the head of the sequence of physical quantities.
https://dev.opencascade.org/doc/occt-7.6.0/refman/html/class_units___units_dictionary.html
CC-MAIN-2022-27
refinedweb
113
57.27
From Silverlight to Javascript and Back Again The Scriptable Attributes Silverlight & IronPython The Scriptable Attributes - Download Visual Studio 2008 Project Using the Scriptable Attributes - Download Compiling C# from the Command Line (batch file) We can call into Silverlight from Javascript using one technique, and a slightly different one for calling from Silverlight into Javascript. Both of them are based on marking classes and methods with .NET attributes. These are useful techniques for creating hybrid applications that are partly written in Silverlight and partially written in Javascript. As Python code running in Silverlight runs faster than Javascript (and Python is a nicer language of course), you could even use Silverlight as an optional accelerator for RIAs (Rich Internet Applications) - falling back to Javascript when Silverlight is unavailable. Unfortunately we can't set attributes from IronPython, so we have to use a bit of C#. Fortunately we can create a stub-class, and then subclass from IronPython. The C# is simple enough that, even if you have never seen C# before, you should be able to understand it. Note As well as the techniques shown in this article, you can add Python event handlers to Javascript, and call Javascript functions, all from within Silverlight and without having to use C#. These techniques can still be useful however. The Scriptable attributes lives in the System.Windows.Browser namespace. C# can be compiled using Visual Studio 2008 (or MonoDevelop). From Visual Studio you will also need Visual Studio tools for Silverlight installed. Fortunately you don't need these installed to compile assemblies for Silverlight - we'll see how in a few moments. Scriptable C# Class C# for a Scriptable class with a Scriptable method that takes and returns a string look like: using System; using System.Windows.Browser; namespace Scriptable { [ScriptableTypeAttribute] public class ScriptableForString { [ScriptableMemberAttribute] public string method(string value) { return this._method(value); } public virtual string _method(string value) { return "override me"; } } } This uses the ScriptableTypeAttribute and ScriptableMemberAttribute attributes We need a class marked as Scriptable with a method marked as Scriptable. The method should call a virtual method that we can override in an IronPython subclass. The Python subclass will still be marked as Scriptable, as will its Scriptable method. If we want to pass and return arguments they need to be statically typed, and can only be a primitive like a string or an integer. This isn't really a problem though because we can pass or return JSON as a string. There is a JSON serializer and deserializer available with Silverlight, and using JSON from Javascript is easy of course! Using from IronPython To use this from IronPython we need to import the class from the assembly we have compiled, adding a reference to it in the normal way (and making sure that it is included in the manifest / xap of course): clr.AddReference("Scriptable") from Scriptable import ScriptableForString class SomeClass(ScriptableForString): def _method(self, string): ... return result some_class = SomeClass() If you are using clr.AddReference to access the assembly then the assembly must be in the application manifest file (AppManifest.xaml). Another alternative is to just include the assembly in the xap but not add it to manifest, and use clr.AddReferenceToFile to add the reference. Registering the Scriptable Object Because our scriptable object needs to be visible from both IronPython and from Javascript we need to register it on the Silverlight control. This is done from IronPython with the following code: HtmlPage.RegisterScriptableObject( "some_class", some_class ) Calling from Javascript Once we have registered the scriptable object, it is then available on the control to be called from Javascript. This is made easier by giving the Silverlight control an id in the object tag in the html. 'SilverlightPlugin' ); result = control.Content.some_class.method( value ); You can only do your hooking up after the Silverlight control has loaded. The easiest way to do this is inside a Javascript function that you specify in the onload parameter of the Silverlight control element: <script> function onload() { control = document.getElementById( 'SilverlightPlugin' ); result = control.Content.some_class.method( value ); } </script> <object id="SilverlightPlugin" data="data:application/x-silverlight," type="application/x-silverlight-2" width="450" height="540"> <param name="source" value="app.xap"/> <param name="onerror" value="onSilverlightError" /> <param name="onload" value="onload" /> ... If you don't want to call the method straight away you can set up a flag inside the onload function that will tell you whether or not you can call into Silverlight. Note Apparently onload is unreliable and can sometimes be fired before the Silverlight engine is ready to execute code. C# Scriptable Event The techniques we have just looked at are fine for calling from Javascript into Silverlight. To go the other way (from Silverlight calling into Javascript) we need to create a scriptable event. using System; using System.Windows.Browser; namespace Scriptable { [ScriptableTypeAttribute] public class ScriptableEvent { [ScriptableMemberAttribute] public event EventHandler Event; public virtual void OnEvent(ScriptableEventArgs e) { Event(this, e); } } } This scriptable event needs to work with scriptable event args. [ScriptableTypeAttribute] public class ScriptableEventArgs : EventArgs { private string _val; [ScriptableMemberAttribute] public string val { get { return _val; } set { _val = value; } } } We need to register this on both the IronPython and the Javascript side. The Javascript needs to attach an event handler to the event we have exposed. When we fire the event from inside Silverlight, the handler will receive the eventargs we pass in from the IronPython side and be able to access the scriptable members we gave it. The Javascript side can modify those members to return values. Using from IronPython No need to subclass this time. # This must also be registered HtmlPage.RegisterScriptableObject( "event", event) args = ScriptableEventArgs() args.val = 'some string' event.OnEvent(args) The Javascript In order to use this event, we have to assign a Java script from Python, the javascript function (some_function) is called and receives the arguments sender and our event args. The Javascript can modify the attributes on the event to return values. After the call returns, IronPython can look at the attributes on the event args to retrieve any return values. Just like with calling from Javascript into Silverlight, we can only hook up the event to its Javascript function once the Silverlight control has loaded and you have registered the event. Again, the usual way to do this is in an onload function with the same caveat as previously. Compiling C# with Notepad Having to download Visual Studio 2008 (and that is one hefty download) just to compile a few lines of C# is a nuisance. Fortunately we can get round this by using the .NET 2 compiler to do it for us. (I think that the compiler, csc.exe, comes with the .NET 2 SDK - but it may even be included in a normal .NET 2 install.) The following batch file tells csc to compile with references to the Sivlerlight DLLs instead of the standard framework ones. It compiles all the C# files in the directory (*.cs) into an assembly specified by the /out argument (/out:SilverlightApp.dll). set sl=C:\Program Files\Microsoft Silverlight\2.0.31005.0 set csc=C:\Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe %csc% /out:Scriptable.dll /t:library /nostdlib+ /noconfig /r:"%sl%\mscorlib.dll" /r:"%sl%\System.dll" /r:"%sl%\System.Core.dll" /r:"%sl%\System.Net.dll" /r:"%sl%\System.Windows.Browser.dll" *.cs pause The lines that start %csc% need to be all on one line - I've split it into multiple lines here for readability. The paths I've included above are the paths that I found csc and the Silverlight assemblies on my machine (Windows Vista). You may need to modify them for yours. I haven't tried this with Mono on the Mac, but I would be interested to hear from anyone who gets it working (or otherwise). From compiling C# for use with IronPython, the next logical step is embedding the IronPython interpreter in a C# Silverlight application: For buying techie books, science fiction, computer hardware or the latest gadgets: visit The Voidspace Amazon Store. Last edited Fri Nov 27 18:32:35 2009. Counter...
http://www.voidspace.org.uk/ironpython/silverlight/scriptable.shtml
CC-MAIN-2018-26
refinedweb
1,348
63.29
Tupalo API Client An interface to Tupalo.com's Easy API. This allows you to - find spots within a certain area - display detailed information about a spot - display spots on a map - post reviews via review widgets - match your spots to our spots - tell us about spots not yet in our database Basically this allows you to build a specialized location-based site or integrate Tupalo.com's content into your page. API access Without an API token you will be limited to 200 requests per month. This has to do with the way we are licensing data from our partners. For the same reason tokenless requests will not include the phone numbers of spots. To get an API token please email api@tupalo.com and let us know what kind of app you have in mind, as well as an estimate on the number of requests you will approximately need per month. Some more guidelines: - Use the API for good and not for evil. - Do not scrape us. - Do not resell our data. - Create something awesome. - Have fun. Creating an API client instance require 'tupalo_api_client' tup = TupaloApiClient.new Alternatively #new can take an options hash with the keys :lang and :token to customize the language and supply your API token. tup = TupaloApiClient.new(:lang => 'nl', :token => 'abc123') Language-wise we currently support English (the default), German, Dutch, Danish, Finnish, Polish, Swedish and French. Spots search Used for retrieving spots in a certain area. tup.spots(:origin => 'Schmalzhofgasse 26, Vienna, Austria', :includecategories => 'restaurant') This will return all restaurants within 0.3km (the default radius) with the Tupalo.com office. The following parameters are supported in the options hash: name: name or part of the name of a spot origin: an address string (example: "Schmalzhofgasse 26, Vienna, Austria") latitude: latitude coordinate longitude: longitude coordinate spot_id: uses the latitude and longitude of the given spot radius: search radius (default 0.3km) excludecategories: comma separated category keys includecategories: comma separated category keys map_size: size of the static map image offset: used for pagination (maximum 40, default 0) limit: number of results to return (maximum 10) token: optional access key token The list of category keys can be found here in JSON format: Spot details Returns detailed information about a spot, including reviews. tup.spot_details(:spot_id => 'gubi') This needs a spot_id which has to be retrieved via #spots first. Review widget Returns an HTML partial for a Tupalo.com review widget that you can use for embedding Tupalo.com reviews in your site. This token-only method is further described in the official API documentation. Matching Used for augmenting spot information on Tupalo.com or pushing new spots into our database. Changes to existing information as well as newly added spots will be manually reviewed before being added to the site. This token-only method is further described in the official API documentation. Error handling In case something goes wrong, an TupaloApiErrors::ClientError (HTTP 4xx) or a TupaloApiErrors::ServerError (HTTP 5xx) get raised. A "HTTP 412 Precondition Failed" status code is returned if you go over your API request limit. Known problems None at the moment. Todo This gem models the current state of Tupalo.com's Easy API. Authors Michael Kohl michi@tupalo.com and Andreas Tiefenthaler andy@tupalo.com License This gem is licensed under the MIT license. See the LICENSE file for details.
https://www.rubydoc.info/gems/tupalo_api_client/1.0.1
CC-MAIN-2019-18
refinedweb
562
57.67
When I inspect mozilla, then go to the <browser> and inspect its contained document, then switch the document pane viewer to the Stylesheets view, it reverts to the old navigator document object instead of the new sub-document for the browser. Mass re-assigning bugs to dom.inspector@extensions.bugs > cmdInspectBrowser: function DVr_CmdInspectBrowser() > { > var node = this.selectedNode; > var n = node && node.localName.toLowerCase(); > if (n == "iframe" || n == "frame" || > (node.namespaceURI == kXULNSURI && (n == "browser" || > n == "tabbrowser" || > n == "editor"))) { > this.subject = node.contentDocument; > } > }, This should update the panel's subject, instead of directly setting this instance's subject. This is a one line fix, but no patch because I don't want my patch for bug 310370 to rot.. Created attachment 493518 [details] [diff] [review] make sure the subject persists by setting the pane's subject instead of the DOM Nodes viewer's own subject Pushed:
https://bugzilla.mozilla.org/show_bug.cgi?id=112674
CC-MAIN-2017-34
refinedweb
144
57.06
Another hard problem when it comes to creating fakes is when the interface contain overloads (i.e. same method name but different parameters) like this: 1: public interface IYetAnotherInterface 2: { 3: int DoSomething(); 4: int DoSomething(int x); 5: } The Fakes utility in VS11 will generate properties like DoSomethingInt32 and DoSometingInt32Int32. Not great names IMHO. So there are three ways I deal with this types of interfaces. The first way, if I have control over the interface and the overloads or more for convenience than anything else, then I avoid overloads in the interface. I make the overloads extension methods on the interface instead. In the example above I would only have the last method. If I have an asynchronous and synchronous method on the same interface I try to just have the asynchronous one and then make the synchronous one an extension method. This way my fakes can be implemented the same way as before. The second way to deal with it is to let my fake just have one handler and make the overloads with fewer arguments just call the one with most arguments. This works in a lot of cases but makes the fake a little smarter than it should really be in some cases. Here is an example of this approach: 6: public class FakeYetAnotherInterface : IYetAnotherInterface 7: { 8: public Func<int, int> DoSomething { get; set; } 9: 10: int IYetAnotherInterface.DoSomething() 11: { 12: Assert.IsNotNull(this.DoSomething, "Unexpected call to DoSomething"); 13: return this.DoSomething(0); 14: } 15: 16: int IYetAnotherInterface.DoSomething(int x) 17: { 18: Assert.IsNotNull(this.DoSomething, "Unexpected call to DoSomething"); 19: return this.DoSomething(x); 20: } 21: } My third option to deal with this is still to have one one handler for all my overloads but at the same time make sure I can easily know which one is being called. In this case I use a special class for the arguments: 22: public class FakeArgument<T> 23: { 24: private T value; 25: 26: public FakeArgument() 27: { 28: } 29: 30: public FakeArgument(T value) 31: { 32: this.Value = value; 33: } 34: 35: public bool HasValue { get; private set; } 36: 37: public T Value 38: { 39: get 40: { 41: Assert.IsTrue(this.HasValue, "Argument not set"); 42: return this.value; 43: } 44: 45: private set 46: { 47: this.value = value; 48: this.HasValue = true; 49: } 50: } 51: 52: public static implicit operator T(FakeArgument<T> arg) 53: { 54: return arg.Value; 55: } 56: } And this is the fake using that class: 57: public class FakeYetAnotherInterface : IYetAnotherInterface 58: { 59: public Func<FakeArgument<int>, int> DoSomething { get; set; } 60: 61: int IYetAnotherInterface.DoSomething() 62: { 63: Assert.IsNotNull( 64: this.DoSomething, "Unexpected call to DoSomething()"); 65: return this.DoSomething(new FakeArgument<int>()); 66: } 67: 68: int IYetAnotherInterface.DoSomething(int x) 69: { 70: Assert.IsNotNull( 71: this.DoSomething, "Unexpected call to DoSomething({0})", x); 72: return this.DoSomething(new FakeArgument<int>(x)); 73: } 74: } And last a test using that fake: 75: [TestMethod] 76: public void UsingFake5() 77: { 78: var fakeThing = new FakeAnotherInterface 79: { 80: DoSomething = arg => 81: { 82: Assert.IsFalse(arg.HasValue, "Wrong overload called"); 83: return 42; 84: } 85: }; 86: IAnotherInterface thing = fakeThing; 87: Assert.AreEqual(42, thing.DoSomething()); 88: } This is however my last resort to deal with overloads in the interfaces needing faking. The first two options are definitely my preferred method.
https://blogs.msdn.microsoft.com/cellfish/2012/07/09/evolution-of-a-hand-rolled-fake-part-4/
CC-MAIN-2017-47
refinedweb
558
57.16
Windows Notepad Finally Supports Unix, Mac OS Line Endings (theregister.co.uk) 291 Microsoft's text editing app, Notepad, which has been shipping with Windows since version 1.0 in 1985, now supports line endings in text files created on Linux, Unix, Mac OS, and macOS devices. "This has been a major annoyance for developers, IT Pros, administrators, and end users throughout the community," Microsoft said in a blog post today. The Register reports:++ ? (Score:5, Interesting) Re: (Score:2) All users caring about line endings had probably migrated to Notepad++ 10 years ago, right ? And yet this is a godsend when working on other people's machines which *don't* have Notepad++ Even wordpad sucks these days. Re: (Score:2) And yet this is a godsend Is it, though? I think it is worse than nothing. The problem is that it will now read LF, but any new line you put into the text will still have a CR+LF. So earlier, when you opened a Unix style text file in Notepad, you would notice that it was LF-based because everything was on one line. So you would open it with Wordpad or something else instead. Now, on the other hand, you will open it, see nothing amiss, modify it, and save it, and because the new lines you made will have CR+LF, it may break the system Re: (Score:2) The problem is that it will now read LF, but any new line you put into the text will still have a CR+LF. So don't edit python scripts. Seriously though if you're doing something sensitive to CR vs CR+LF then Notepad is the wrong thing to use to edit a file and you'll know it's wrong too. The biggest problem with CR vs CR+LF is being unable to read files (a universal problem) and not that the LF will break the system (a problem that affects an incredibly minor set of possible scenarios exposed to an incredible minor part of the userbase and a part of the user base that is a) most equipped to handle it, and b) l Re: (Score:2) That's worse than nothing in my opinion. A typical Microsoft "solution". This typical Microsoft "solution": "New files created within Notepad will use Windows line ending (CRLF) by default, but it will now be possible to view, edit, and print existing files, correctly maintaining the file’s current line ending format." It actually is funny to see prejudice just blow up in people's faces.... [microsoft.com] Re:Notepad++ ? (Score:5, Funny) it is a must have on your usb flash drive of tools and utilities Lol, found the Windows admin. Re: (Score:3) Well yeah actually, because with Unix you either SSH into the box remotely, or your toolkit consists of a single liveUSB. Real Unix Admins(tm) can restore the whole system from deletion [ryerson.ca] with a half-working copy of cat and no filesystem, of course. Re:Notepad++ ? (Score:5, Insightful) it is a must have on your usb flash drive It's faster to download it and run it as a portable than it is to mail a USB drive to the computer you're supporting. Know what's even faster? Having the default text editor able to display text correctly. Re: (Score:2) If you're required to edit plaintext on other people's computers - I feel sorry for you. Not needed for linux setups - you ssh in (or sshmount their fs) and do all work from your own office/computer. No getting used to their keyboard setup or whatever. Well, it's great if that works in your setup. But you don't always have complete control. We have some 10.000 Linux server appliances running within our customers networks. We don't have direct access to most of those. So if we need to troubleshoot anything, we need to ask our customers to grant us access to their local network via TeamViewer or such like and then connect with putty (as practically everyone uses Windows). Re: (Score:2) Next year Microsoft will release their new feature swollen text editor: Notepad#. Re: (Score:2) All users caring about line endings had probably migrated to Notepad++ 10 years ago, right ? Creating a never-ending cycle. Notepad is the only editor you can count on in a workflow, as a result a dependency is built in to a lot of windows apps, and CRLF leaks all over. While on linux/bsd/osx most things obey the EDITOR ev, allowing the user to pick his favorite. As a result if Apple dropped/changed TextEdit, many people may not notice, but if MS drops or changes Notepad, major LOB apps are going to break Re: (Score:2) The first tech book on Unix I owned had a section on how you couldn't rely on this newfangled "vi" thing being available, or working from the console, on every system, and both taught and suggested as a default "ed", which is available everywhere. I have recovered a very minimally-booting system with "ed" in anger. I don't want to have to do it again any time soon. (Also had a great chapter on the joys of booting, and how to use repeated dcheck / icheck iterations to repair filesystems - unless you were on a Re: Notepad++ ? (Score:2) Re: (Score:2) All users caring about line endings had probably migrated to Notepad++ 10 years ago, right ? Nope. I just don’t open up anything but Word documents on my Windows machine. Visual Studio already handles the line endings, though it does always try to convert to Windows line endings. Mac OS and macOS? (Score:2) Wow. How are they different? Re: (Score:3, Informative) Re: (Score:2) And did the line endings change between < 10.0.0 and >= 10.0.0? ProDOS, UNIX, and CP/M newlines (Score:5, Informative) Mac OS 1 through 9 use the same newline as ProDOS on the Apple IIe: $0D. Mac OS X 10.0 through 10.11 and macOS 10.12 to present use the same newline as UNIX: $0A. Traditionally, MS-DOS and Windows have used the same newline as Digital Research's CP/M: $0D $0A. The $0D $0A sequence dates back to the Teletype Model 33 terminal [wikipedia.org], one of the first terminals to use ASCII. It could process a carriage return ($0D) and a line feed ($0A) in parallel, but because a return took longer than a line feed, computers sent the return first, then the line feed, then a split second of pausing before the next character so that it wouldn't get smeared across the page during the return. If your Model 33 had the optional ASR paper tape drive, you might have had to use the delete key to insert the pauses yourself. UNIX relied on terminal drivers to convert a newline to whatever sequence a particular terminal needed. CP/M just encoded what the terminal expected directly into an application. MS-DOS was originally a clone of CP/M (and DR-DOS was forked from authentic CP/M), and Windows was originally a GUI shell around MS-DOS. Though MS-DOS 2 was sophisticated enough to use these sorts of drivers, it had to remain compatible with applications designed for the much more CP/M-like MS-DOS 1. Re: (Score:2) the line demarcating the change isn't exactly clean. Yaz iConfused Re: (Score:2) You can export a tab delimited file from FileMaker today, and still get CRs. It's like, cute and quaint. Ah, fond memories of booting Mac OS X Cheetah (or was it public beta?) on a Quadra 8500 with 130 odd MB of RAM, and it not crashing the whole system whenever an app crashed. Re: (Score:2) No, MacOS is ancient, macOS is new..ish. Yeah.. Re:Mac OS and macOS? (Score:5, Funny) Re: (Score:2) Why has it been an annoyance? (Score:4, Informative) If you want to do something more complex then download a non-minimal text editor. There are loads available for free. Re: (Score:2) Imagine those config files are shared with non-windows computers. Re:Why has it been an annoyance? (Score:5, Interesting) Notepad is a small simple text editor that exists because occasionally you might need to edit some text files (typically for config files or something). These will be in a Windows friendly text format. It doesn't pretend to do anything remotely sophisticated. That's great if you're the one running the editor and doing the editing. What's not so great is when you give a co-worker a bash script, and they open it in Notepad, and then complain to you about all the extra spacing -- forcing you to waste a ton of breath explaining why it's not a problem with the text file, but an issue with their editor. I once had to send a developer at my employer a SQL script intended to be run on Linux, and they did just this. It was unbelievable how long it took me to finally convince them that Notepad was the issue. And it wasn't just the double-spacing; they early had a fit because the file showed up as "ANSI" encoding in Notepad, whereas the spec said the file had to be UTF-8. So not only did I have to convince them (with lots of references) that Notepad was rendering CR/LF as two lines whereas UNIX systems treat them as a single line ending pair, but then I ALSO had to waste a lot of time convincing them that not only is there no such encoding standard as "ANSI" (a very long-standing bug in Notepad Microsoft has never got around to fixing), but that ASCII and UTF-8 are identical for values between 0x00 and 0x7F (which every byte in the document were within). It was extremely annoying, because even with lots of links to references as to why they shouldn't be using Notepad for UNIX text files in the first place (and why you can't trust its encoding field), in the end I couldn't convince them. Our DBA eventually had to tell them the file was just fine as-is. And sadly, this wasn't the first person I've had this problem with. As such, as a non-Windows user I'm rather happy for this change. I can't believe how many developers I run into who have no notion of line termination or the actual details of encoding standards, and who simply trust whatever Notepad tell them. Hopefully it will save me some aggravation in the future. Yaz Re: (Score:2) Significant figures (Score:2) A fraction in ratio notation, such as 1/2, is assumed to be exact unless specified otherwise. A decimal, on the other hand, often represents an interval of real numbers based on significant figure conventions [wikipedia.org]. For example, 0.5 means "anything that rounds to 0.5", namely the interval 0.450 to 0.550, and 0.50 means "anything that rounds to 0.50", namely the interval 0.495 to 0.505. Re: (Score:2) Well Microsoft can't fix stupid people. Look on the bright side, due to this issue someone learned something, even brighter would be if you consulted at the time, because then that also translated to billable hours :) Re: (Score:3) Fuck BOMs Re: (Score:2) You're correct about Notepad rendering CR/LF as a single break, but Unix is not a text editor. Notepad is the only editor I've used in modern times that cannot deal with mixed line breaks. Re: (Score:2) Wordpad is not a text editor. It's a *choke* word processor, and quite easily even more bad at doing its job than Notepad is. Re: (Score:2) Notepad is a small simple text editor that exists because occasionally you might need to edit some text files (typically for config files or something). Just because it's simple and occasionally used doesn't mean it can't be annoying. Also just because there are alternatives doesn't mean I'm going to install them on every computer I touch (or even can install them). ... And Wordpad is now a mess. Re: (Score:2) Re: (Score:2) Nothing really. It just isn't the program it used to be... [wikipedia.org] You can change some settings force it to look like normal, live with the ribbon, but more fundamentally: It isn't the default text editor. None of this is really a problem, it's just irritating: Help some, open explorer, double click, "crap", close notepad, right click, open in word pad, change the view mode and the wordwrap settings, keep doing what it is you were doing in the first place. Notepad not screwing up every Re: (Score:2) I've often encountered downloaded text files which aren't Windows-formatted. While there are many alternatives that do handle line ends correctly (the most readily available in Windows is WordPad), Notepad is a default for various file types and this added support will certainly help. This really isn't something basic, not something sophisticated, and there's no particular reason not to include it. While Microsoft is very late to the party, it's a definite case of 'better late than never'. Re: (Score:2) Notepad is a small simple text editor that exists because occasionally you might need to edit some text files (typically for config files or something) on a machine that is not yours so doesn't have Notepad++ installed. These will be in a Windows friendly text format. It doesn't pretend to do anything remotely sophisticated. If you want to do something more complex then download a non-minimal text editor. There are loads available for free. TFTFY. If you're regularly editing text files, Notepad++ (or a contemporary) is essential. Notepad is for when you don't have anything like Notepad++ CRLF is technically correct (Score:5, Insightful) You want the carriage to return and the paper moved up by one line, not print over the last line (CR only) or continue at the current position one line down (LF only). Imagine that, Microsoft doing something correctly. Re: (Score:2) When printing sure, but most text won't be printed and is just edited electronically. Using a single character makes more sense as it reduces file size, especially if you have short lines. Re: (Score:2) Where can I find this paper version of notepad you're talking about? Re: (Score:2) The deal for me is that, as an old MUD coder in the late 90's, I am so used to the VT100 convention that the Unix way of doing it baffles me. I'm too used to doing \n\r. Re: (Score:2) It's not a order of the characters that matters to me; as former email developer, I'm also used to standardizing on CRLF as per RFC. But there were enough non-standard clients out there that I was used to having to deal with either-or. What fucked it all up were those clients that only send bare LF's. "Be liberal in what you accept" except most of these were spam clients, anyhow. Re:CRLF is technically correct (Score:5, Informative) You want the carriage to return and the paper moved up by one line, not print over the last line (CR only) or continue at the current position one line down (LF only). Imagine that, Microsoft doing something correctly. It's a holdover from the old mechanical printer / typewriter days. Since the LF and CR were handled by separate mechanisms separate commands allowed controlling them independently when needed. While in general you wanted a CR and LF, they also had utility themselves. A LF allowed advancing paper without activating the CR mechanism if a CR was not needed, while a CR allows you to over print and blackout text, such as a password. Re: (Score:2) Specifically, it is a holdover from the Teletype Corporation telegraphs. Previous Murray telegraphs had used a single "Line" code for a new line. The Teletype machines were electro-mechanical and while a character could be typed relatively quickly, the printer's carriage return operation was slow. The "Line" code was split into two codes to allow the printer to keep up! Re: (Score:2) It's not just a holdover: it's also a compromise after different OS builders tried to simplify things the same way without coordinating and whose arbitrary choices happened to conflict. Once you have unixy LF and macish CR in the wild, reviving the old CRLF admixture made an equally unhappy compromised. That compromise was baked into telnet and subsequent protocols. By the time Microsoft brought MS-DOS to market, CRLF looked like the sensible, standards-compliant choice. I am mostly summarizing the old EOLst [rfc-editor.org] Re: (Score:2) Re: (Score:2) Even today it would make a difference on the web. This page that I am typing in is according to a combination of wget and wc 1213 lines long. That is 1.2KB less if using a LF formatted HTML file over a CR/LF formatted one. Multiply that by all the CR/LF formatted files being shoved around the internet and I would imagined it comes to many TB a day. Finally, a reason to upgrade to Windows 10! (Score:5, Funny) Or will this be backported to Windows 7? Notepad a major annoyance for developers (Score:3) You cannot be serious, what professional developer in his right mind would use Notepad? Re: (Score:3) Developers have clients who aren't developers. I don't use Windows, but I'm happy about this change because occasionally I've had clients who wanted to edit one of my files in Notepad and would find it looking broken to them because of lack of line break parsing. Re: (Score:2) You cannot be serious, what professional developer in his right mind would use Notepad? Close to 100% of them. Just not necessarily while developing. Kind of like just because vi is my editor of choice doesn't mean that I don't frequently end up on a test system opening something in nano or *shudders* emacs. Developers especially frequently send files cross platforms onto test systems they don't administer and need to use a standard OS image. God forbid they remotely access a file on another system, or their main OS from another OS. Re: (Score:3) You cannot be serious, what professional developer in his right mind would use Notepad? Any developer having to do a change of an ini file or script on a locked down machine where no user software can be installed, such as a machine in a production environment or factory. And any developer who has to guide a user in such a change over the phone or a remote connection. Making Notepad actually useful is a huge step in reducing the pain of maintaining Windows based automation and enterprise solutions. Re: (Score:2) You cannot be serious, what professional developer in his right mind would use Notepad? Those same senior developers that use pico and nano, I would assume. Wordpad (Score:3) Re: (Score:2) WordPad works on Mac OS files just fine. I use notepad++ if it's available because WordPad defaults to a proportional font, which makes code and script really hard to read...but in a pinch, WordPad will do. Azure (Score:2) Drop the negativity - a good and useful thing has just happened. Thanks. Re: (Score:2) Just wait until notepad corrupts your file when it writes the file back to disk in CR/LF format... and this will be classed as a "feature". Write (Score:2) The funny thing... (Score:5, Informative) Is that edit.exe -- the console-based editor that came out with DOS 5.0 -- *did* support UNIX EOL. Go figger. Re: (Score:2) Reason MS didn't do this earlier is because majority of people were using Windows Re: (Score:2) I have to disagree somewhat. While I will never be guilty of ascribing good things to MS while under Ballmer/Gates, once the web came along, UNIX EOL suddenly became righter -- or at least terribly common. I would have to say it was just sheer hamfisted bluster and pride, moreso than a desire to put the hurt on the (then) microscopic userbase of people like you and me. But, really, barring an internal document showing this, it doesn't really matter what we think the reason was. Yawn (Score:2, Interesting) Wake me up when windows can read EXT4 filesystems, I mean it has only been around for 15 years, is an open standard which could easily have been coded for, and it would be just common sense to do so. Meanwhile linux has been able to read NTFS/FAT/FAT32 for 20+ years. But oh yay, linebreaks, lookit all that progress.. see comment (Score:2) WordPad stock plunges 17%... (Score:4, Funny) ...in after-hours trading. Step one to being usable, done (Score:2) Being able to handle large files by NOT trying to load a huge file into ram and only noticing after two minutes or 10 that it fails will probably take another 40 years. huh? (Score:3) the registry must be a nightmare (Score:2) Why does this need to be disabled ever? How is it ever better to ignore obvious line breaks? Hey wait... (Score:2) I just heard that Windows notepad tried to replace MS-DOS edline (line editor... [wikipedia.org]), but failed as edline is still in Windows 10 !? Re: Odd (Score:2) Re: (Score:2) Ubuntu Server, yes. Anything that relies on the presence of an X server, not quite yet. WSL users trying to run GUI apps have to obtain an X server elsewhere, which usually means a decade-old copy of Xming. Re: (Score:2) It is just odd that they would leave this out forever on purpose and then suddenly fix it. It has been literal decades, and the absence was obviously malicious. Cloud is king and the writing is on the wall. You don't take you lead architects of core products unless your business strategy is changing. This is just another sign of the inevitable. Re: (Score:3) Re: (Score:2) You are a modern human right? So you use Unicode, right? U+2029 Re: (Score:2) Yes this is probably yet another advantage due to the Linux subsystem and therefore (indirectly) Linux. Re: (Score:2) who cares? Millions upon millions of MS Windows admins 'stuck' with Linux systems? It's actually kind of funny to watch them work, they are so used to point-n-click snap-in GUI interfaces that most of them don't even know how to write a script. Recognise a Windows admin worth having a conversation with by the fact that he scripts most of his work using VB or C# rather than sitting there for hours pounding a mouse button working a GUI management tool to do stuff a script can do in 10 minutes. Re:too little, too late (Score:5, Insightful) Yeah, but then.. Notepad++ Re: (Score:2) Re: (Score:2) Do you have a moment to talk about our lord and savior Sublime Text [sublimetext.com]? Re:too little, too late (Score:5, Interesting) Zaelath noted: Yeah, but then.. Notepad++ Personally, I've used Alan Phillips' Programmer's File Editor [lancaster.ac.uk] in place of Notepad for almost 20 years now. MS made it harder when they killed off support for the .hlp helpfile format, but there are ways around that - and, in addition to a pretty useful feature set [lancaster.ac.uk], the program IS free, after all ... Re: (Score:2) Re:too little, too late (Score:4, Informative) Re: (Score:2, Insightful) I call bullshit. How often do you really script something robust in 10 minutes? Do you have proper error handling, have you considered the edge cases, what about notifications of failure and logging output? It can take hours. For one-off jobs a shitty little brittle 10 minute script is fine, but for something of high importance 10 minutes is usually not enough. Personally, I don't see speed as the primary benefit... reproducibility is what I care about. I can spend 10 minutes doing a daily task... or I ca Re: (Score:2, Insightful) Millions upon millions of MS Windows admins 'stuck' with Linux systems? It's not called 'stuck' when you are too stupid to learn how to do your job which includes managing Windows, Linux, BSD, various router and switching platforms, etc... The word you're looking for is 'incompetence'. Millions upon millions of *incompetent* MS Windows admins don't know *how* to work on Linux systems.... Re: (Score:2) > Recognise a Windows admin worth having a conversation with by the fact that he scripts most of his work using VB or C# powershell. they should be scripting in powershell these days, which is kept up to date, has tons of built in functions and available modules for working in AD and just about anything on a wdinwos computer or server already available, and can take advantage of .Net libraries so you dont have to develop in c# to get something that powershell doesnt have as a native cmdlet. VB still has i Re: (Score:2, Troll) Exactly. I'm not going to suddenly start editing text in Windoze. I mean, I'm not going to complain that they started actually ending lines properly, it only took forty-ish years, but they finally figured out how to do it. Meanwhile, TeachText became SimpleText became TextEdit. The Macintosh user interface evolved through many generations. And now, finally, in 2018, MicroShit figures out how to do what they should have been able to do in 1984. Idiots. Re:too little, too late (Score:5, Informative) CR: return to first character of the line.... [wikipedia.org] LF: jump to the next line.... [wikipedia.org] Perhaps you should read those articles (I've only verified the relevant parts so normal Wikipedia cautions apply), understand where the control characters came from, what they were used for and why there are different line endings out there? No "properly" about this. That it have taken this long for MS to change something this trivial is strange though. Guess they always assumed nobody use notepad? Re: (Score:2) If it's good enough for RFC 5321 [ietf.org], it's good enough for me. Re: (Score:2) Guess they always assumed nobody use notepad? Or maybe they are planning on screwing up wordpad even more. :-/ Re: (Score:2) Re: (Score:3) Look, if you want to emulate ancient technology, you'd also better make sure that if you only send carriage-return, your emulation should smear the next character across the paper about 40 positions to the left of the prior character, and that every character past 72 should overwrite that 72nd position, getting darker and darker until the ink starts to spread. And your terminal emulator should make a terrible racket with every printable character, which by the way, only included UPPERCASE letters and run at Re:too little, too late (Score:5, Interesting) Let's be fair here. The correct implementation of a new line in a text file *IS* CRLF. It is the format you need to send a printer to print the text. A single CR would just print all the text on a single line overwriting itself over and over, and a LF would make the text look like a staircase (until it ran off the side of the page). CRLF is therefore the correct way to end lines in a text file (or LF+CR which actually makes more sense, but I wasn't consulted when the standards started). Seriously, just go read any manual that describes the ASCII control characters and there will be no doubt left in your head about what SHOULD be the correct way. Linux got it wrong because it copied it from Unix. Unix got it wrong because it got copied from Multics (some of the original devs working on Unix were also devs on Multics). Multics (most likely) got it wrong because it was a bad performance hack (using a single byte to end lines is easier). Re: (Score:2) who cares? All they have to do now is replace the rest of their OS. And also get notepad to not output CRLF, because we don't need that in the world. I mean if they want their OS to just be for games great, but anyone that can make a choice is selecting anything else. It's a horrible environment to get real work done on. Re: (Score:2) > It's a horrible environment to get real work done on. this is sort of ridiculous, we are stuck on windows 7 at work and I can get all of my work done without an issue--my last job had 8.1 which i liked better, what do you really get out of linux that is so great? I got frustrated with linux a long time ago and have never looked back--to each his own, right? windows is not perfect, and *nix has had several features MS has been stupid slow to incorporate, but come on, to act like it is worthless is just s Re: (Score:2) Re: (Score:2) Good thing you can just read TFA and learn there's an option to retain the old behavior Re: (Score:2) Good thing you can just read TFA and learn there's an option to retain the old behavior I "could" RTFA but then I would not be able to post something stupid. Sigh. I'm just gunna fire up RS5 and play around with it instead :) Re: (Score:2) "man unix2dos" and for good measure "man dos2unix" Re: (Score:2) To be honest, the CR + LF line ending is closer to be a standard for text interchange than any other combination of CR and/or LF. Many IETF RFCs mandate the use of CR + LF. Re: (Score:2) Tis the year that M$ embraces Linux... It is the year of Linux on the Windows Desktop. M$ is now extending its support for all things GNU / Linux in a bid to extinguish GNU / Linux once and for all. Re: (Score:2) Yep, that was the original idea of ASCII control codes to control teletypes and teleprinters over serial communication links.
https://tech.slashdot.org/story/18/05/08/2149216/windows-notepad-finally-supports-unix-mac-os-line-endings
CC-MAIN-2018-22
refinedweb
5,142
70.73
0 Hi, I was wondering how to get around a problem I was having with eval(). I have a list of strings and each one is the name of a python file found in the same directory as the current script. I was it to import these modules to use in the current script, but: eval( "import" + modname ), where 'modname' is the script's name, causes an error. Is there any way to have the script import any found scripts or would I have to explicitly add "import <name>" for each script? Thanks! names = [ "main", "secondary", "tertiary" ] for item in names: eval( "import " + item ) The code above makes sense, but python gives me this instead: import primary ^ SyntaxError: invalid syntax
https://www.daniweb.com/programming/software-development/threads/129532/eval-problems
CC-MAIN-2018-17
refinedweb
120
72.7
Writing plug-ins in Python Learn to write your first plug-in by extending a command-line tool in Python In a previous article for IBM developerWorks I wrote about the joy of creating command-line tools with Python. This article takes the command-line tools to the next level by creating plug-ins to extend them. Both plug-ins and command-line tools offer a convenient way to extend the functionality of existing code. Used together, they can be a very powerful tool. To get started writing the plug-in, you are going to use an open source Python package I wrote called pathtool, which uses generators to walk a filesystem and yield a file object. This library was specifically written to allow developers to extend it by writing their own filters that do something to a file object, and then return the result. The actual Python module code is a bit larger than you would like to see for an article, so I will only post a snippit of the API that you will actually use: Listing 1. pathtool API def path(fullpath, pattern="*", action=(lambda rec: print_rec(rec))): """This takes a path, a shell pattern, and an action callback This function uses the slower pathattr function which calculates checksums """ for rec in pathattr(fullpath): for new_record in match(pattern, rec): #applies filter action(new_record) #Applies lambda callback to generator object Looking at this example, you can tell that the path function takes a mandatory path-positional argument along with a optional pattern keyword argument, and an optional action keyword argument called lambda callback. The default callback for path just print out the filename as an example. A developer would just need to easy_install pathtool. See the resources section for information on using the easy_install command, and then import the module and call the function as follows: from pathtool import path path("/tmp", pattern="*.mp3", action=(lambda rec: print_rec(rec))) Note: I have included the source code for pathtool with this article for added convenience. One thing to point out about this example is the use of lambda. You can read a link to a Python tutorial entry in the resources section about them, but in a nutshell, a lambda is a convenient way to tell a function to "call" another function. Writing an pluggable command-line tool Now that we have a general idea of how to use a path-walking library that includes a callback, it is time to jump into actually writing a command-line tool that is extensible using plug-ins. Look at the finished version first, and then I'll break it down into smaller pieces: Listing 2. Command-line tool with plug-ins #!/usr/bin/env python # encoding: utf-8 """ pathtool-cli.py 0.1 A commandline tool for walking a filesystem. Takes Action callback plugins in a plugin directory action=(lambda rec: print_rec(rec)) """ from pathtool import path import optparse import re import os import sys try: plugin_available = True from plugin import * from plugin import __all__ #note this is the registered plugin list except ImportError: plugin_available = False def path_controller(): descriptionMessage = """ A command line tool for walking a filesystem.\ Takes callback 'Action' functions as plugins.\ example: pathtool_cli /tmp print_path_ext """ p = optparse.OptionParser(description=descriptionMessage, prog='pathtool', version='pathtool 0.1.1', usage= '%prog [starting directory][action]') p.add_option('--pattern', '-p', help='Pattern Match Examples: *.txt, *.iso, music[0-5].mp3\ plain number defaults to * or match all. \ Uses UNIX standard wildcard syntax.', default='*') p.add_option('--list', '-l', action="store_true", help='lists available action plugins', default=False) options, arguments = p.parse_args() if options.list: try: print "Action Plugins Available:" if plugin_available: for p in __all__: print p finally: sys.exit(0) if len(arguments) == 2: fullpath = arguments[0] try: action_plugin = eval(arguments[1]) #note we expect the plugin author to write a method with our naming convention #path(fullpath,options.pattern,action=(lambda rec: move_to_tmp.plugin(rec))) path(fullpath, options.pattern,action=(lambda rec: action_plugin.plugin(rec))) except NameError: sys.stderr.write("Plugin Not Found") sys.exit(1) else: print p.print_help() def main(): path_controller() if __name__ == '__main__': main() Running this example results in the following output: # python pathtool_cli.py Usage: pathtool [starting directory][action] A command line tool for walking a filesystem. Takes callback 'Action' functions as plugins. example: pathtool_cli /tmp print_path_ext Options: --version show program's version number and exit -h, --help show this help message and exit -p PATTERN, --pattern=PATTERN Pattern Match Examples: *.txt, *.iso, music[0-5].mp3 plain number defaults to * or match all. Uses UNIX standard wildcard syntax. -l, --list lists available action plugins From the output of the command, you can see that the tool expects to take a fullpath, and then an "action." The action is a plug-in that a developer creates. I have added a command-line option list that allows the user of the command-line tool to see what plug-ins are available. Look at the output of this: # python pathtool_cli.py -l Action Plugins Available: move_to_tmp print_file_path_ext Without knowing too much about how the tool works, someone can probably guess what an action does by the name of it. Because the print_file_path_ext action I have written just prints the file, path, ext, go ahead and run that and see what it looks like: # python pathtool_cli.py /tmp print_file_path_ext /tmp/foo0.txt | foo0.txt | .txt /tmp/foo1.txt | foo1.txt | .txt /tmp/foo10.txt | foo10.txt | .txt /tmp/foo2.txt | foo2.txt | .txt /tmp/foo3.txt | foo3.txt | .txt /tmp/foo4.txt | foo4.txt | .txt /tmp/foo5.txt | foo5.txt | .txt /tmp/foo6.txt | foo6.txt | .txt /tmp/foo7.txt | foo7.txt | .txt /tmp/foo8.txt | foo8.txt | .txt /tmp/foo9.txt | foo9.txt | .txt I created ten temp files using touch foo{0..10}.txt earlier, and now the command-line tool used a plug-in that it found to print the fullpath, the filename, and the extension, all separated by a "|" character. Simple plug-in architecture explained Up until now, I have been expecting you to trust me, without telling you where these "magic" plug-in actions are coming from. The first thing to look at is the import statement at the top of the module. Try the following: plugin_available = True from plugin import * from plugin import __all__ #note this is the registered plugin list except ImportError: plugin_available = False This import statement gives away the secret to the surprisingly simple plug-in architecture. The official Python documentation generally discourages the use of the syntax "from package import *", but if there is a good reason for it, such as writing plug-ins, then the plug-in author is responsible for creating an entry in the __init__.py file located in the plug-in directory. It should look like this: """Lists all of the importable plugins""" __all__ = ["move_to_tmp", "print_file_path_ext"] By setting this, it allows all of the modules inside of the package, or directory, to be imported as *. Next I import the actual __all__ list to use as a way of showing the user what plug-ins are available. Finally, there is one more small bit of magic. Because the command-line tool doesn't know until runtime what plug-in action to use, use eval to convert the action string on the command-line into a callable function. This is the magic line: action_plugin = eval(arguments[1]) Generally, the use of eval should be used with extreme caution, but in this case, it is reasonable to tell our tool to use plug-in methods. A look at a plug-in Now that you understand how the plug-in architecture is supposed to work, look at an actual plug-in. Note that in order for this architecture to work, there needs to be a plug-in directory in the current working directory or the Python site-packages directory. This particular plug-in is called print_file_path_ext.py, and it has a method called plug-in. This is an expected API that a plug-in developer must conform to: Listing 3. Example plug-in #!/usr/bin/env python # encoding: utf-8 """ prints path, name, ext, plugin """ def plugin(rec, verbose=True): """Moves matched files to tmp directory""" path = rec["path"] filename = rec["filename"] ext = rec["ext"] print "%s | %s | %s" % (path, filename, ext) This plug-in is a very simple function, but it takes a rec parameter that is a dictionary that the pathtool module generates. That dictionary includes the following API: {"path": path, "filename": file, "ext": ext, "size": size, "unique_id": unique_id, "mtime": mtime, "ctime": ctime} In this example, I use the keys of the dictionary to print the values for that particular file object each time it is called. A plug-in author could write many other useful actions that could convert files, rename files, archive files, and more. Summary This article demonstrated a reasonably simple plug-in architecture that can be a useful way to extend command-line tools in Python. There are a few things that should be noted, though. First, there is a more sophisticated plug-in system available with easy_install, which is included in the references. This plug-in system allows a user to create "entry points" that define plug-ins for a particular tool. Second, the way our command-line tools is written only allows for one "action" plug-in. I will leave it as an exercise to the reader to modify the command-line tool such that it could receive a limitless amount of "chainable" callback actions. One potential gotcha with creating chainable plug-ins is that the design must take into account the nature of the API it is using. In our case we are building on a foundation of generators that yields. In order for our tool to continue "chaining" plug-ins together, they must do their work, yet still yield the dictionary record back. I hope this article inspired you to write your own plug-ins for command-line tools, as well. Downloadable resources - PDF of this content - Sample CLI Plug-in Code (cli_plugin_code.zip | 15KB) Related topics - Creating command-line tools in Python (developerWorks, March 2008): Learn how to create a simple command-line tool. - Plug-in: Read the Wikipedia entry for plug-ins. - Firefox Plug-in: Help your browser perform specific functions like viewing special graphic formats or playing multimedia files. - Dynamic Discovery of Services and Plug-ins with Setuptools supports creating libraries that "plug in" to extensible applications and frameworks. - Pathtool is an efficient API to walking a filesystem. - IBM trial software: Build your next development project with software for download directly from developerWorks.
https://www.ibm.com/developerworks/aix/library/au-cli_plugins/
CC-MAIN-2019-47
refinedweb
1,765
53.1
Hubigraph is a Haskell wrapper for Ubigraph, which is a tool for visualizing dynamic graphs. A sample use of hubigraph: import Graphics.Ubigraph r x = initHubigraph "" >>= runHubigraph x main = r $ mkRing 10 mkRing n = do mapM_ (newVertexWithID) all mapM_ (newEdge') all sid <- newVStyle 0 mapM_ (flip setVStyleAttr sid) [VColor "#ff0000", VShape Sphere] mapM_ (changeVStyle sid) all where newEdge' e = newEdge (e, next e) next e = (e+1) `mod` n all = [0..n-1] import Graphics.Ubigraph r x = initHubigraph "" >>= runHubigraph x main = do r $ mapM_ newV [1..3] where newV n = newVertexWithID n >> setVAttr (VCallback url) n url = "" This script runs as CGI program. import Graphics.Ubigraph import Network.XmlRpc.Server r x = initHubigraph "" >>= runHubigraph x draw :: Int -> IO Int draw a = do r $ setVAttr (VColor "#ff0000") a >> return 0 main = cgiXmlRpcServer [("vertex_callback", fun draw)] $ cabal install hubigraph Hubigraph-0.3.2 is now available. 0.3.2 has a fix for the lack of API (Thanks Matei for this contribution). Added some edge attributes (arrow_position, arrow_radius, arrow_length, arrow_reverse). Hubigraph-0.3.1 is now on Hackage. The module name is changed from Hubigraph to Graphics.Ubigraph. A new release of Hubigraph is now available. 0.3 has a fix for the lack of API (Thanks Justin Quillinan). The lack is including a way to remove edges, register callbacks and change styles. Also, 0.3 makes a way to change attributes simpler (with setVAttr & setEAttr functions and VAttr & EAtter data types).
http://ooxo.org/hubigraph/
CC-MAIN-2014-41
refinedweb
241
58.28
0 What i need to do is convert the first letter of ever word into a caps letter. I know that in ASCII the lower case letters are between 97 and 122 and all i need to do it -32 to get the caps version. Now my problem is how do i change that letter to ASCII subtract 32 then print the letter value. This is what i have so far. #include <iostream> using namespace std; //Main int main() { int count; int row; cout << "How many words will be inputed?"; cin >> row; int const ROWS = row; int const SIZE = 30; char word[ROWS][SIZE]; cout << "Please enter a few words and i will change every letter into caps."; for ( count = 0; count < ROWS; count++) cin >> word[count]; cout << "Here is a list of the words you entered with the first letter in caps."; for ( count = 0; count < ROWS; count++) { if (static_cast<int>(word[count][0]) > 97 && static_cast<int>(word[count][0]) < 122) { ***This is where i need help with the conversion*** } } return 0; } im getting a few errors like 'static_cast' : cannot convert from 'char [30]' to 'int'
https://www.daniweb.com/programming/software-development/threads/95154/converting-from-char-to-ascii-to-char
CC-MAIN-2016-50
refinedweb
187
74.53
Controller library for limitlessled/easybulb/milight Wi-Fi LEDs Controller for milight bulbs. Same bulbs are available under multiple different brands, including LimitlessLed, Easybulb, applight, dekolight and iLight. Before using this code, you need to configure your gateway to connect to wifi - there’s multiple iOS and Android apps available for that. After that, configure light groups to the gateway. Configuring remote has nothing to do with configuring the gateway. See github repository for more information. The code is based on the documentation available at limitlessled.com/dev/ Installation pip install ledcontroller Usage import ledcontroller led = ledcontroller.LedController("192.168.1.6") led.off() # Switches all groups off led.set_color("red", 1) # Switches group 1 on and changes color to red. led.white(2) # Group 2 on and color to white. led.set_brightness(50, 2) # Group 2 on and brightness to 50%. led.set_color(150, 2) # set color without using presets. Number must be 0-255 led.disco(3) # Group 3 on and enable disco mode. led.disco_faster(3) # Group 3 on and adjust disco mode speed. led.on(4) # Switch group 4 on. Bulb automatically restores previous color and brightness. Using both white and RGBW bulbs: import ledcontroller # By default, all groups are RGBW bulbs. led = ledcontroller.LedController("192.168.1.6", group_1="white", group_4="white") led.set_group_type(1, "white") # This is same as using constructor keyword group_1. led.on() led.white(2) # Switches RGBW group on and changes color to white. led.white(1) # Turns white group on. led.warmer() # Adjusts all white groups to warmer color. Switches all groups on. led.cooler(1) # Adjusts group 1 white bulbs to cooler color. led.brightness_up() # Adjusts white group brightness up. Does not affect RGBW lights. led.brightness_up(2) # Does nothing to RGBW bulbs. led.brightness_up(4) # Adjusts group 4 brightness. led.set_brightness(50) # Adjusts all RGBW bulbs to 50%. Does not affect white lights. Controller pools: When using multiple controllers, it is important to keep same 100ms pause between each command. Use LedControllerPool class to automate this. import ledcontroller ledpool = ledcontroller.LedControllerPool(["192.168.1.6", "192.168.1.7"]) ledpool.execute(0, "on") ledpool.execute(1, "disco", 3) ledpool.execute(0, "set_color", "red", 1) Notes - There is automatic 100ms pause between each command. Almost every action requires sending more than one command, thus requiring several hundred milliseconds. You can change this with keyword argument “pause_between_commands”. However, decreasing the delay will cause some commands to fail. - As the gateway seems to be rather unreliable, all commands are sent multiple times (three by default). If you want to change this, use “LedController(ip, repeat_commands=n)” to create new lightcontroller instance. It is not possible to retrieve any status information from light bulbs. - If for some reason you need to change gateway port, pass port=n argument to constructor. - Run testsuite with “python setup.py test”. Tests only run the code without checking whether proper commands were sent. - RGBW/white bulb commands differ a bit. Obviously, it is not possible to change color for white bulbs. For white bulbs, there is no absolute brightness settings. Similarly, only white bulbs allow adjusting color temperature (with .cooler and .warmer). There is 10 steps for white bulb brightness and color temperature. - Brightness settings are stored by bulbs. Brightness is saved separately for both white and RGB modes. Furthermore, bulbs store the last color. Sending .on() restores previous brightness and color. Stores and brands - I bought my bulbs, remotes and gateway from LimitlessLED. Unfortunately, they have really expensive shipping ($50 to Finland). Furthermore, when ordering to Finland, taxes and customs were about 30% in top of original price. - milight.com and easybulb.com sell same products with two different brands. These are more expensive than LimitlessLED, but ship from UK. - At least some products from s’luce iLight are exactly the same with different branding. - Beware that at least milight.com and easybulb.com sell older version of the wifi gateway (v3, vs. v4 from LimitlessLED). v3 does not support nightmode, and seems to be less reliable than v4. - Try aliexpress.com with search “milight”. Beware of older versions (RGB bulbs) and non-remote-controlled bulbs sold with same brand. 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/ledcontroller/
CC-MAIN-2017-34
refinedweb
716
62.54
!30727 83 2013/07/27 22:24:4730727 49 + improve configure macros from ongoing work on cdk, dialog, xterm: 50 + CF_ADD_LIB_AFTER - fix a problem with -Wl options 51 + CF_RPATH_HACK - add missing result-message 52 + CF_SHARED_OPTS - modify to use $rel_builddir in cygwin and mingw 53 dll symbols (which can be overridden) rather than explicit "../". 54 + CF_SHARED_OPTS - modify NetBSD and DragonFly symbols to use ${CC} 55 rather than ${LD} to improve rpath support. 56 + CF_SHARED_OPTS - add a symbol to denote the temporary files that 57 are created by the macro, to simplify clean-rules. 58 + CF_X_ATHENA - trim extra libraries to work with -Wl,--as-needed 59 + fix a regression in hashed-database support for NetBSD, which uses 60 the key-size differently from other implementations (cf: 20121229). 61 62 20130720 63 + further improvements for setupterm manpage, clarifying the 64 initialization of cur_term. 65 66 20130713 67 + improve manpages for initscr and setupterm. 68 + minor compiler-warning fixes 69 70 20130706 71 + add fallback defs for <inttypes.h> and <stdint.h> (cf: 20120225). 72 + add check for size of wchar_t, use that to suppress a chunk of 73 wcwidth.h in MinGW port. 74 + quiet linker warnings for MinGW cross-compile with dll's using the 75 --enable-auto-import flag. 76 + add ncurses.map rule to ncurses/Makefile to help diagnose symbol 77 table issues. 78 79 20130622 80 + modify the clear program to take into account the E3 extended 81 capability to clear the terminal's scrollback buffer (patch by 82 Miroslav Lichvar, Redhat #815790). 83 + clarify in resizeterm manpage that LINES and COLS are updated. 84 + updated ansi example in terminfo.tail, correct misordered example 85 of sgr. 86 + fix other doclifter warnings for manpages 87 + remove unnecessary ".ta" in terminfo.tail, add missing ".fi" 88 (patch by Eric Raymond). 89 90 20130615 91 + minor changes to some configure macros to make them more reusable. 92 + fixes for tabs program (prompted by report by Nick Andrik): 93 + corrected logic in command-line parsing of -a and -c predefined 94 tab-lists options. 95 + allow "-0" and "-8" options to be combined with others, e.g.,"-0d". 96 + make warning messages more consistent with the other utilities by 97 not printing the full pathname of the program. 98 + add -V option for consistency with other utilities. 99 + fix off-by-one in columns for tabs program when processing an option 100 such as "-5" (patch by Nick Andrik). 101 102 20130608 103 + add to test/demo_forms.c examples of using the menu-hooks as well 104 as showing how the menu item user-data can be used to pass a callback 105 function pointer. 106 + add test/dots_termcap.c 107 + remove setupterm call from test/demo_termcap.c 108 + build-fix if --disable-ext-funcs configure option is used. 109 + modified test/edit_field.c and test/demo_forms.c to move the lengths 110 into a user-data structure, keeping the original string for later 111 expansion to free-format input/out demo. 112 + modified test/demo_forms.c to load data from file. 113 + added note to clarify Terminal.app's non-emulation of the various 114 terminal types listed in the preferences dialog -TD 115 + fix regression in error-reporting in lib_setup.c (Debian #711134, 116 cf: 20121117). 117 + build-fix for a case where --enable-broken_linker and 118 --enable-reentrant options are combined (report by George R Goffe). 119 120 20130525 121 + modify mvcur() to distinguish between internal use by the ncurses 122 library, and external callers, preventing it from reading the content 123 of the screen which is only nonblank when curses calls have updated 124 it. This makes test/dots_mvcur.c avoid painting colored cells in 125 the left margin of the display. 126 + minor fix to test/dots_mvcur.c 127 + move configured symbols USE_DATABASE and USE_TERMCAP to term.h as 128 NCURSES_USE_DATABASE and NCURSES_USE_TERMCAP to allow consistent 129 use of these symbols in term_entry.h 130 131 20130518 132 + corrected ifdefs in test/testcurs.c to allow comparison of mouse 133 interface versus pdcurses (cf: 20130316). 134 + add pow() to configure-check for math library, needed since 135 20121208 for test/hanoi (Debian #708056). 136 + regenerated html manpages. 137 + update doctype used for html documentation. 138 139 20130511 140 + move nsterm-related entries out of "obsolete" section to more 141 plausible "ansi consoles" -TD 142 + additional cleanup of table-of-contents by reordering -TD 143 + revise fix for check for 8-bit value in _nc_insert_ch(); prior fix 144 prevented inserts when video attributes were attached to the data 145 (cf: 20121215) (Redhat #959534). 146 147 20130504 148 + fixes for issues found by Coverity: 149 + correct FNKEY() macro in progs/dump_entry.c, allowing kf11-kf63 to 150 display when infocmp's -R option is used for HP or AIX subsets. 151 + fix dead-code issue with test/movewindow.c 152 + improve limited-checking in _nc_read_termtype(). 153 154 20130427 155 + fix clang 3.2 warning in progs/dump_entry.c 156 + drop AC_TYPE_SIGNAL check; ncurses relies on c89 and later. 157 158 20130413 159 + add MinGW to cases where ncurses installs by default into /usr 160 (prompted by discussion with Daniel Silva Ferreira). 161 + add -D option to infocmp's usage-message (patch by Miroslav Lichvar). 162 + add a missing 'int' type for main function in configure check for 163 type of bool variable, to work with clang 3.2 (report by Dmitri 164 Gribenko). 165 + improve configure check for static_cast, to work with clang 3.2 166 (report by Dmitri Gribenko). 167 + re-order rule for demo.o and macros defining header dependencies in 168 c++/Makefile.in to accommodate gmake (report by Dmitri Gribenko). 169 170 20130406 171 + improve parameter checking in copywin(). 172 + modify configure script to work around OS X's "libtool" program, to 173 choose glibtool instead. At the same time, chance the autoconf macro 174 to look for a "tool" rather than a "prog", to help with potential use 175 in cross-compiling. 176 + separate the rpath usage for c++ library from demo program 177 (Redhat #911540) 178 + update/correct header-dependencies in c++ makefile (report by Werner 179 Fink). 180 + add --with-cxx-shared to dpkg-script, as done for rpm-script. 181 182 20130324 183 + build-fix for libtool configuration (reports by Daniel Silva Ferreira 184 and Roumen Petrov). 185 186 20130323 187 + build-fix for OS X, to handle changes for --with-cxx-shared feature 188 (report by Christian Ebert). 189 + change initialization for vt220, similar entries for consistency 190 with cursor-key strings (NetBSD #47674) -TD 191 + further improvements to linux-16color (Benjamin Sittler) 192 193 20130316 194 + additional fix for tic.c, to allocate missing buffer space. 195 + eliminate configure-script warnings for gen-pkgconfig.in 196 + correct typo in sgr string for sun-color, 197 add bold for consistency with sgr, 198 change smso for consistency with sgr -TD 199 + correct typo in sgr string for terminator -TD 200 + add blink to the attributes masked by ncv in linux-16color (report 201 by Benjamin Sittler) 202 + improve warning message from post-load checking for missing "%?" 203 operator by tic/infocmp by showing the entry name and capability. 204 + minor formatting improvement to tic/infocmp -f option to ensure 205 line split after "%;". 206 + amend scripting for --with-cxx-shared option to handle the debug 207 library "libncurses++_g.a" (report by Sven Joachim). 208 209 20130309 210 + amend change to toe.c for reading from /dev/zero, to ensure that 211 there is a buffer for the temporary filename (cf: 20120324). 212 + regenerated html manpages. 213 + fix typo in terminfo.head (report by Sven Joachim, cf: 20130302). 214 + updated some autoconf macros: 215 + CF_ACVERSION_CHECK, from byacc 1.9 20130304 216 + CF_INTEL_COMPILER, CF_XOPEN_SOURCE from luit 2.0-20130217 217 + add configure option --with-cxx-shared to permit building 218 libncurses++ as a shared library when using g++, e.g., the same 219 limitations as libtool but better integrated with the usual build 220 configuration (Redhat #911540). 221 + modify MKkey_defs.sh to filter out build-path which was unnecessarily 222 shown in curses.h (Debian #689131). 223 224 20130302 225 + add section to terminfo manpage discussing user-defined capabilities. 226 + update manpage description of NCURSES_NO_SETBUF, explaining why it 227 is obsolete. 228 + add a check in waddch_nosync() to ensure that tab characters are 229 treated as control characters; some broken locales claim they are 230 printable. 231 + add some traces to the Windows console driver. 232 + initialize a temporary array in _nc_mbtowc, needed for some cases 233 of raw input in MinGW port. 234 235 20130218 236 + correct ifdef on change to lib_twait.c (report by Werner Fink). 237 + update config.guess, config.sub 238 239 20130216 240 + modify test/testcurs.c to work with mouse for ncurses as it does for 241 pdcurses. 242 + modify test/knight.c to work with mouse for pdcurses as it does for 243 ncurses. 244 + modify internal recursion in wgetch() which handles cooked mode to 245 check if the call to wgetnstr() returned an error. This can happen 246 when both nocbreak() and nodelay() are set, for instance (report by 247 Nils Christopher Brause) (cf: 960418). 248 + fixes for issues found by Coverity: 249 + add a check for valid position in ClearToEOS() 250 + fix in lib_twait.c when --enable-wgetch-events is used, pointer 251 use after free. 252 + improve a limit-check in make_hash.c 253 + fix a memory leak in hashed_db.c 254 255 20130209 256 + modify test/configure script to make it simpler to override names 257 of curses-related libraries, to help with linking with pdcurses in 258 MinGW environment. 259 + if the --with-terminfo-dirs configure option is not used, there is 260 no corresponding compiled-in value for that. Fill in "no default 261 value" for that part of the manpage substitution. 262 263 20130202 264 + correct initialization in knight.c which let it occasionally make 265 an incorrect move (cf: 20001028). 266 + improve documentation of the terminfo/termcap search path. 267 268 20130126 269 + further fixes to mvcur to pass callback function (cf: 20130112), 270 needed to make test/dots_mvcur work. 271 + reduce calls to SetConsoleActiveScreenBuffer in win_driver.c, to 272 help reduce flicker. 273 + modify configure script to omit "+b" from linker options for very 274 old HP-UX systems (report by Dennis Grevenstein) 275 + add HP-UX workaround for missing EILSEQ on old HP-UX systems (patch 276 by Dennis Grevenstein). 277 + restore memmove/strdup support for antique systems (request by 278 Dennis Grevenstein). 279 + change %l behavior in tparm to push the string length onto the stack 280 rather than saving the formatted length into the output buffer 281 (report by Roy Marples, cf: 980620). 282 283 20130119 284 + fixes for issues found by Coverity: 285 + fix memory leak in safe_sprintf.c 286 + add check for return-value in tty_update.c 287 + correct initialization for -s option in test/view.c 288 + add check for numeric overflow in lib_instr.c 289 + improve error-checking in copywin 290 + add advice in infocmp manpage for termcap users (Debian #698469). 291 + add "-y" option to test/demo_termcap and test/demo_terminfo to 292 demonstrate behavior with/without extended capabilities. 293 + updated termcap manpage to document legacy termcap behavior for 294 matching capability names. 295 + modify name-comparison for tgetstr, etc., to accommodate legacy 296 applications as well as to improve compatbility with BSD 4.2 297 termcap implementations (Debian #698299) (cf: 980725). 298 299 20130112 300 + correct prototype in manpage for vid_puts. 301 + drop ncurses/tty/tty_display.h, ncurses/tty/tty_input.h, since they 302 are unused in the current driver model. 303 + modify mvcur to use stdout except when called within the ncurses 304 library. 305 + modify vidattr and vid_attr to use stdout as documented in manpage. 306 + amend changes made to buffering in 20120825 so that the low-level 307 putp() call uses stdout rather than ncurses' internal buffering. 308 The putp_sp() call does the same, for consistency (Redhat #892674). 309 310 20130105 311 + add "-s" option to test/view.c to allow it to start in single-step 312 mode, reducing size of trace files when it is used for debugging 313 MinGW changes. 314 + revert part of 20121222 change to tinfo_driver.c 315 + add experimental logic in win_driver.c to improve optimization of 316 screen updates. This does not yet work with double-width characters, 317 so it is ifdef'd out for the moment (prompted by report by Erwin 318 Waterlander regarding screen flicker). 319 320 20121229 321 + fix coverity warnings regarding copying into fixed-size buffers. 322 + add throw-declarations in the c++ binding per Coverity warning. 323 + minor changes to new-items for consistent reference to bug-report 324 numbers. 325 326 20121222 327 + add *.dSYM directories to clean-rule in ncurses directory makefile, 328 for Mac OS builds. 329 + add a configure check for gcc option -no-cpp-precomp, which is not 330 available in all Mac OS X configurations (report by Andras Salamon, 331 cf: 20011208). 332 + improve 20021221 workaround for broken acs, handling a case where 333 that ACS_xxx character is not in the acsc string but there is a known 334 wide-character which can be used. 335 336 20121215 337 + fix several warnings from clang 3.1 --analyze, includes correcting 338 a null-pointer check in _nc_mvcur_resume. 339 + correct display of double-width characters with MinGW port (report 340 by Erwin Waterlander). 341 + replace MinGW's wcrtomb(), fixing a problem with _nc_viscbuf 342 > fixes based on Coverity report: 343 + correct coloring in test/bs.c 344 + correct check for 8-bit value in _nc_insert_ch(). 345 + remove dead code in progs/tset.c, test/linedata.h 346 + add null-pointer checks in lib_tracemse.c, panel.priv.h, and some 347 test-programs. 348 349 20121208 350 + modify test/knight.c to show the number of choices possible for 351 each position in automove option, e.g., to allow user to follow 352 Warnsdorff's rule to solve the puzzle. 353 + modify test/hanoi.c to show the minimum number of moves possible for 354 the given number of tiles (prompted by patch by Lucas Gioia). 355 > fixes based on Coverity report: 356 + remove a few redundant checks. 357 + correct logic in test/bs.c, when randomly placing a specific type of 358 ship. 359 + check return value from remove/unlink in tic. 360 + check return value from sscanf in test/ncurses.c 361 + fix a null dereference in c++/cursesw.cc 362 + fix two instances of uninitialized variables when configuring for the 363 terminal driver. 364 + correct scope of variable used in SetSafeOutcWrapper macro. 365 + set umask when calling mkstemp in tic. 366 + initialize wbkgrndset() temporary variable when extended-colors are 367 used. 368 369 20121201 370 + also replace MinGW's wctomb(), fixing a problem with setcchar(). 371 + modify test/view.c to load UTF-8 when built with MinGW by using 372 regular win32 API because the MinGW functions mblen() and mbtowc() 373 do not work. 374 375 20121124 376 + correct order of color initialization versus display in some of the 377 test-programs, e.g., test_addstr.c 378 > fixes based on Coverity report: 379 + delete windows on exit from some of the test-programs. 380 381 20121117 382 > fixes based on Coverity report: 383 + add missing braces around FreeAndNull in two places. 384 + various fixes in test/ncurses.c 385 + improve limit-checks in tinfo/make_hash.c, tinfo/read_entry.c 386 + correct malloc size in progs/infocmp.c 387 + guard against negative array indices in test/knight.c 388 + fix off-by-one limit check in test/color_name.h 389 + add null-pointer check in progs/tabs.c, test/bs.c, test/demo_forms.c, 390 test/inchs.c 391 + fix memory-leak in tinfo/lib_setup.c, progs/toe.c, 392 test/clip_printw.c, test/demo_menus.c 393 + delete unused windows in test/chgat.c, test/clip_printw.c, 394 test/insdelln.c, test/newdemo.c on error-return. 395 396 20121110 397 + modify configure macro CF_INCLUDE_DIRS to put $CPPFLAGS after the 398 local -I include options in case someone has set conflicting -I 399 options in $CPPFLAGS (prompted by patch for ncurses/Makefile.in by 400 Vassili Courzakis). 401 + modify the ncurses*-config scripts to eliminate relative paths from 402 the RPATH_LIST variable, e.g., "../lib" as used in installing shared 403 libraries or executables. 404 405 20121102 406 + realign these related pages: 407 curs_add_wchstr.3x 408 curs_addchstr.3x 409 curs_addstr.3x 410 curs_addwstr.3x 411 and fix a long-ago error in curs_addstr.3x which said that a -1 412 length parameter would only write as much as fit onto one line 413 (report by Reuben Thomas). 414 + remove obsolete fallback _nc_memmove() for memmove()/bcopy(). 415 + remove obsolete fallback _nc_strdup() for strdup(). 416 + cancel any debug-rpm in package/ncurses.spec 417 + reviewed vte-2012, reverted most of the change since it was incorrect 418 based on testing with tack -TD 419 + un-cancel the initc in vte-256color, since this was implemented 420 starting with version 0.20 in 2009 -TD 421 422 20121026 423 + improve malloc/realloc checking (prompted by discussion in Redhat 424 #866989). 425 + add ncurses test-program as "ncurses6" to the rpm- and dpkg-scripts. 426 + updated configure macros CF_GCC_VERSION and CF_WITH_PATHLIST. The 427 first corrects pattern used for Mac OS X's customization of gcc. 428 429 20121017 430 + fix change to _nc_scroll_optimize(), which incorrectly freed memory 431 (Redhat #866989). 432 433 20121013 434 + add vte-2012, gnome-2012, making these the defaults for vte/gnome 435 (patch by Christian Persch). 436 437 20121006 438 + improve CF_GCC_VERSION to work around Debian's customization of gcc 439 --version message. 440 + improve configure macros as done in byacc: 441 + drop 2.13 compatibility; use 2.52.xxxx version only since EMX port 442 has used that for a while. 443 + add 3rd parameter to AC_DEFINE's to allow autoheader to run, i.e., 444 for experimental use. 445 + remove unused configure macros. 446 + modify configure script and makefiles to quiet new autoconf warning 447 for LIBS_TO_MAKE variable. 448 + modify configure script to show $PATH_SEPARATOR variable. 449 + update config.guess, config.sub 450 451 20120922 452 + modify setupterm to set its copy of TERM to "unknown" if configured 453 for the terminal driver and TERM was null or empty. 454 + modify treatment of TERM variable for MinGW port to allow explicit 455 use of the windows console driver by checking if $TERM is set to 456 "#win32con" or an abbreviation of that. 457 + undo recent change to fallback definition of vsscanf() to build with 458 older Solaris compilers (cf: 20120728). 459 460 20120908 461 + add test-screens to test/ncurses to show 256-characters at a time, 462 to help with MinGW port. 463 464 20120903 465 + simplify varargs logic in lib_printw.c; va_copy is no longer needed 466 there. 467 + modifications for MinGW port to make wide-character display usable. 468 469 20120902 470 + regenerate configure script (report by Sven Joachim, cf: 20120901). 471 472 20120901 473 + add a null-pointer check in _nc_flush (cf: 20120825). 474 + fix a case in _nc_scroll_optimize() where the _oldnums_list array 475 might not be allocated. 476 + improve comparisons in configure.in for unset shell variables. 477 478 20120826 479 + increase size of ncurses' output-buffer, in case of very small 480 initial screen-sizes. 481 + fix evaluation of TERMINFO and TERMINFO_DIRS default values as needed 482 after changes to use --datarootdir (reports by Gabriele Balducci, 483 Roumen Petrov). 484 485 20120825 486 + change output buffering scheme, using buffer maintained by ncurses 487 rather than stdio, to avoid problems with SIGTSTP handling (report 488 by Brian Bloniarz). 489 490 20120811 491 + update autoconf patch to 2.52.20120811, adding --datarootdir 492 (prompted by discussion with Erwin Waterlander). 493 + improve description of --enable-reentrant option in README and the 494 INSTALL file. 495 + add nsterm-256color, make this the default nsterm -TD 496 + remove bw from nsterm-bce, per testing with tack -TD 497 498 20120804 499 + update test/configure, adding check for tinfo library. 500 + improve limit-checks for the getch fifo (report by Werner Fink). 501 + fix a remaining mismatch between $with_echo and the symbols updated 502 for CF_DISABLE_ECHO affecting parameters for mk-2nd.awk (report by 503 Sven Joachim, cf: 20120317). 504 + modify followup check for pkg-config's library directory in the 505 --enable-pc-files option to validate syntax (report by Sven Joachim, 506 cf: 20110716). 507 508 20120728 509 + correct path for ncurses_mingw.h in include/headers, in case build 510 is done outside source-tree (patch by Roumen Petrov). 511 + modify some older xterm entries to align with xterm source -TD 512 + separate "xterm-old" alias from "xterm-r6" -TD 513 + add E3 extended capability to xterm-basic and putty -TD 514 + parenthesize parameters of other macros in curses.h -TD 515 + parenthesize parameter of COLOR_PAIR and PAIR_NUMBER in curses.h 516 in case it happens to be a comma-expression, etc. (patch by Nick 517 Black). 518 519 20120721 520 + improved form_request_by_name() and menu_request_by_name(). 521 + eliminate two fixed-size buffers in toe.c 522 + extend use_tioctl() to have expected behavior when use_env(FALSE) and 523 use_tioctl(TRUE) are called. 524 + modify ncurses test-program, adding -E and -T options to demonstrate 525 use_env() versus use_tioctl(). 526 527 20120714 528 + add use_tioctl() function (adapted from patch by Werner Fink, 529 Novell #769788): 530 531 20120707 532 + add ncurses_mingw.h to installed headers (prompted by patch by 533 Juergen Pfeifer). 534 + clarify return-codes from wgetch() in response to SIGWINCH (prompted 535 by Novell #769788). 536 + modify resizeterm() to always push a KEY_RESIZE onto the fifo, even 537 if screensize is unchanged. Modify _nc_update_screensize() to push a 538 KEY_RESIZE if there was a SIGWINCH, even if it does not call 539 resizeterm(). These changes eliminate the case where a SIGWINCH is 540 received, but ERR returned from wgetch or wgetnstr because the screen 541 dimensions did not change (Novell #769788). 542 543 20120630 544 + add --enable-interop to sample package scripts (suggested by Juergen 545 Pfeifer). 546 + update CF_PATH_SYNTAX macro, from mawk changes. 547 + modify mk-0th.awk to allow for generating llib-ltic, etc., though 548 some work is needed on cproto to work with lib_gen.c to update 549 llib-lncurses. 550 + remove redundant getenv() cal in database-iterator leftover from 551 cleanup in 20120622 changes (report by Sven Joachim). 552 553 20120622 554 + add -d, -e and -q options to test/demo_terminfo and test/demo_termcap 555 + fix caching of environment variables in database-iterator (patch by 556 Philippe Troin, Redhat #831366). 557 558 20120616 559 + add configure check to distinguish clang from gcc to eliminate 560 warnings about unused command-line parameters when compiler warnings 561 are enabled. 562 + improve behavior when updating terminfo entries which are hardlinked 563 by allowing for the possibility that an alias has been repurposed to 564 a new primary name. 565 + fix some strict compiler warnings based on package scripts. 566 + further fixes for configure check for working poll (Debian #676461). 567 568 20120608 569 + fix an uninitialized variable in -c/-n logic for infocmp changes 570 (cf: 20120526). 571 + corrected fix for building c++ binding with clang 3.0 (report/patch 572 by Richard Yao, Gentoo #417613, cf: 20110409) 573 + correct configure check for working poll, fixing the case where stdin 574 is redirected, e.g., in rpm/dpkg builds (Debian #676461). 575 + add rpm- and dpkg-scripts, to test those build-environments. 576 The resulting packages are used only for testing. 577 578 20120602 579 + add kdch1 aka "Remove" to vt220 and vt220-8 entries -TD 580 + add kdch1, etc., to qvt108 -TD 581 + add dl1/il1 to some entries based on dl/il values -TD 582 + add dl to simpleterm -TD 583 + add consistency-checks in tic for insert-line vs delete-line 584 controls, and insert/delete-char keys 585 + correct no-leaks logic in infocmp when doing comparisons, fixing 586 duplicate free of entries given via the command-line, and freeing 587 entries loaded from the last-but-one of files specified on the 588 command-line. 589 + add kdch1 to wsvt25 entry from NetBSD CVS (reported by David Lord, 590 analysis by Martin Husemann). 591 + add cnorm/civis to wsvt25 entry from NetBSD CVS (report/analysis by 592 Onno van der Linden). 593 594 20120526 595 + extend -c and -n options of infocmp to allow comparing more than two 596 entries. 597 + correct check in infocmp for number of terminal names when more than 598 two are given. 599 + correct typo in curs_threads.3x (report by Yanhui Shen on 600 freebsd-hackers mailing list). 601 602 20120512 603 + corrected 'op' for bterm (report by Samuel Thibault) -TD 604 + modify test/background.c to demonstrate a background character 605 holding a colored ACS_HLINE. The behavior differs from SVr4 due to 606 the thick- and double-line extension (cf: 20091003). 607 + modify handling of acs characters in PutAttrChar to avoid mapping an 608 unmapped character to a space with A_ALTCHARSET set. 609 + rewrite vt520 entry based on vt420 -TD 610 611 20120505 612 + remove p6 (bold) from opus3n1+ for consistency -TD 613 + remove acs stuff from env230 per clues in Ingres termcap -TD 614 + modify env230 sgr/sgr0 to match other capabilities -TD 615 + modify smacs/rmacs in bq300-8 to match sgr/sgr0 -TD 616 + make sgr for dku7202 agree with other caps -TD 617 + make sgr for ibmpc agree with other caps -TD 618 + make sgr for tek4107 agree with other caps -TD 619 + make sgr for ndr9500 agree with other caps -TD 620 + make sgr for sco-ansi agree with other caps -TD 621 + make sgr for d410 agree with other caps -TD 622 + make sgr for d210 agree with other caps -TD 623 + make sgr for d470c, d470c-7b agree with other caps -TD 624 + remove redundant AC_DEFINE for NDEBUG versus Makefile definition. 625 + fix a back-link in _nc_delink_entry(), which is needed if ncurses is 626 configured with --enable-termcap and --disable-getcap. 627 628 20120428 629 + fix some inconsistencies between vt320/vt420, e.g., cnorm/civis -TD 630 + add eslok flag to dec+sl -TD 631 + dec+sl applies to vt320 and up -TD 632 + drop wsl width from xterm+sl -TD 633 + reuse xterm+sl in putty and nsca-m -TD 634 + add ansi+tabs to vt520 -TD 635 + add ansi+enq to vt220-vt520 -TD 636 + fix a compiler warning in example in ncurses-intro.doc (Paul Waring). 637 + added paragraph in keyname manpage telling how extended capabilities 638 are interpreted as key definitions. 639 + modify tic's check of conflicting key definitions to include extended 640 capability strings in addition to the existing check on predefined 641 keys. 642 643 20120421 644 + improve cleanup of temporary files in tic using atexit(). 645 + add msgr to vt420, similar DEC vtXXX entries -TD 646 + add several missing vt420 capabilities from vt220 -TD 647 + factor out ansi+pp from several entries -TD 648 + change xterm+sl and xterm+sl-twm to include only the status-line 649 capabilities and not "use=xterm", making them more generally useful 650 as building-blocks -TD 651 + add dec+sl building block, as example -TD 652 653 20120414 654 + add XT to some terminfo entries to improve usefulness for other 655 applications than screen, which would like to pretend that xterm's 656 title is a status-line. -TD 657 + change use-clauses in ansi-mtabs, hp2626, and hp2622 based on review 658 of ordering and overrides -TD 659 + add consistency check in tic for screen's "XT" capability. 660 + add section in terminfo.src summarizing the user-defined capabilities 661 used in that file -TD 662 663 20120407 664 + fix an inconsistency between tic/infocmp "-x" option; tic omits all 665 non-standard capabilities, while infocmp was ignoring only the user 666 definable capabilities. 667 + improve special case in tic parsing of description to allow it to be 668 followed by terminfo capabilities. Previously the description had to 669 be the last field on an input line to allow tic to distinguish 670 between termcap and terminfo format while still allowing commas to be 671 embedded in the description. 672 + correct variable name in gen_edit.sh which broke configurability of 673 the --with-xterm-kbs option. 674 + revert 2011-07-16 change to "linux" alias, return to "linux2.2" -TD 675 + further amend 20110910 change, providing for configure-script 676 override of the "linux" terminfo entry to install and changing the 677 default for that to "linux2.2" (Debian #665959). 678 679 20120331 680 + update Ada95/configure to use CF_DISABLE_ECHO (cf: 20120317). 681 + correct order of use-clauses in st-256color -TD 682 + modify configure script to look for gnatgcc if the Ada95 binding 683 is built, in preference to the default gcc/cc (suggested by 684 Nicolas Boulenguez). 685 + modify configure script to ensure that the same -On option used for 686 the C compiler in CFLAGS is used for ADAFLAGS rather than simply 687 using "-O3" (suggested by Nicolas Boulenguez) 688 689 20120324 690 + amend an old fix so that next_char() exits properly for empty files, 691 e.g., from reading /dev/null (cf: 20080804). 692 + modify tic so that it can read from the standard input, or from 693 a character device. Because tic uses seek's, this requires writing 694 the data to a temporary file first (prompted by remark by Sven 695 Joachim) (cf: 20000923). 696 697 20120317 698 + correct a check made in lib_napms.c, so that terminfo applications 699 can again use napms() (cf: 20110604). 700 + add a note in tic.h regarding required casts for ABSENT_BOOLEAN 701 (cf: 20040327). 702 + correct scripting for --disable-echo option in test/configure. 703 + amend check for missing c++ compiler to work when no error is 704 reported, and no variables set (cf: 20021206). 705 + add/use configure macro CF_DISABLE_ECHO. 706 707 20120310 708 + fix some strict compiler warnings for abi6 and 64-bits. 709 + use begin_va_copy/end_va_copy macros in lib_printw.c (cf: 20120303). 710 + improve a limit-check in infocmp.c (Werner Fink): 711 712 20120303 713 + minor tidying of terminfo.tail, clarify reason for limitation 714 regarding mapping of \0 to \200 715 + minor improvement to _nc_copy_termtype(), using memcpy to replace 716 loops. 717 + fix no-leaks checking in test/demo_termcap.c to account for multiple 718 calls to setupterm(). 719 + modified the libgpm change to show previous load as a problem in the 720 debug-trace. 721 > merge some patches from OpenSUSE rpm (Werner Fink): 722 + ncurses-5.7-printw.dif, fixes for varargs handling in lib_printw.c 723 + ncurses-5.7-gpm.dif, do not dlopen libgpm if already loaded by 724 runtime linker 725 + ncurses-5.6-fallback.dif, do not free arrays and strings from static 726 fallback entries 727 728 20120228 729 + fix breakage in tic/infocmp from 20120225 (report by Werner Fink). 730 731 20120225 732 + modify configure script to allow creating dll's for MinGW when 733 cross-compiling. 734 + add --enable-string-hacks option to control whether strlcat and 735 strlcpy may be used. The same issue applies to OpenBSD's warnings 736 about snprintf, noting that this function is weakly standardized. 737 + add configure checks for strlcat, strlcpy and snprintf, to help 738 reduce bogus warnings with OpenBSD builds. 739 + build-fix for OpenBSD 4.9 to supply consistent intptr_t declaration 740 (cf:20111231) 741 + update config.guess, config.sub 742 743 20120218 744 + correct CF_ETIP_DEFINES configure macro, making it exit properly on 745 the first success (patch by Pierre Labastie). 746 + improve configure macro CF_MKSTEMP by moving existence-check for 747 mkstemp out of the AC_TRY_RUN, to help with cross-compiles. 748 + improve configure macro CF_FUNC_POLL from luit changes to detect 749 broken implementations, e.g., with Mac OS X. 750 + add configure option --with-tparm-arg 751 + build-fix for MinGW cross-compiling, so that make_hash does not 752 depend on TTY definition (cf: 20111008). 753 754 20120211 755 + make sgr for xterm-pcolor agree with other caps -TD 756 + make sgr for att5425 agree with other caps -TD 757 + make sgr for att630 agree with other caps -TD 758 + make sgr for linux entries agree with other caps -TD 759 + make sgr for tvi9065 agree with other caps -TD 760 + make sgr for ncr260vt200an agree with other caps -TD 761 + make sgr for ncr160vt100pp agree with other caps -TD 762 + make sgr for ncr260vt300an agree with other caps -TD 763 + make sgr for aaa-60-dec-rv, aaa+dec agree with other caps -TD 764 + make sgr for cygwin, cygwinDBG agree with other caps -TD 765 + add configure option --with-xterm-kbs to simplify configuration for 766 Linux versus most other systems. 767 768 20120204 769 + improved tic -D option, avoid making target directory and provide 770 better diagnostics. 771 772 20120128 773 + add mach-gnu (Debian #614316, patch by Samuel Thibault) 774 + add mach-gnu-color, tweaks to mach-gnu terminfo -TD 775 + make sgr for sun-color agree with smso -TD 776 + make sgr for prism9 agree with other caps -TD 777 + make sgr for icl6404 agree with other caps -TD 778 + make sgr for ofcons agree with other caps -TD 779 + make sgr for att5410v1, att4415, att620 agree with other caps -TD 780 + make sgr for aaa-unk, aaa-rv agree with other caps -TD 781 + make sgr for avt-ns agree with other caps -TD 782 + amend fix intended to separate fixups for acsc to allow "tic -cv" to 783 give verbose warnings (cf: 20110730). 784 + modify misc/gen-edit.sh to make the location of the tabset directory 785 consistent with misc/Makefile.in, i.e., using ${datadir}/tabset 786 (Debian #653435, patch by Sven Joachim). 787 788 20120121 789 + add --with-lib-prefix option to allow configuring for old/new flavors 790 of OS/2 EMX. 791 + modify check for gnat version to allow for year, as used in FreeBSD 792 port. 793 + modify check_existence() in db_iterator.c to simply check if the 794 path is a directory or file, according to the need. Checking for 795 directory size also gives no usable result with OS/2 (cf: 20120107). 796 + support OS/2 kLIBC (patch by KO Myung-Han). 797 798 20120114 799 + several improvements to test/movewindow.c (prompted by discussion on 800 Linux Mint forum): 801 + modify movement commands to make them continuous 802 + rewrote the test for mvderwin 803 + rewrote the test for recursive mvwin 804 + split-out reusable CF_WITH_NCURSES_ETC macro in test/configure.in 805 + updated configure macro CF_XOPEN_SOURCE, build-fixes for Mac OS X 806 and OpenBSD. 807 + regenerated html manpages. 808 809 20120107 810 + various improvments for MinGW (Juergen Pfeifer): 811 + modify stat() calls to ignore the st_size member 812 + drop mk-dlls.sh script. 813 + change recommended regular expression library. 814 + modify rain.c to allow for threaded configuraton. 815 + modify tset.c to allow for case when size-change logic is not used. 816 817 20111231 818 + modify toe's report when -a and -s options are combined, to add 819 a column showing which entries belong to a given database. 820 + add -s option to toe, to sort its output. 821 + modify progs/toe.c, simplifying use of db-iterator results to use 822 caching improvements from 20111001 and 20111126. 823 + correct generation of pc-files when ticlib or termlib options are 824 given to rename the corresponding tic- or tinfo-libraries (report 825 by Sven Joachim). 826 827 20111224 828 + document a portability issue with tput, i.e., that scripts which work 829 with ncurses may fail in other implementations that do no parameter 830 analysis. 831 + add putty-sco entry -TD 832 833 20111217 834 + review/fix places in manpages where --program-prefix configure option 835 was not being used. 836 + add -D option to infocmp, to show the database locations that it 837 could use. 838 + fix build for the special case where term-driver, ticlib and termlib 839 are all enabled. The terminal driver depends on a few features in 840 the base ncurses library, so tic's dependencies include both ncurses 841 and termlib. 842 + fix build work for term-driver when --enable-wgetch-events option is 843 enabled. 844 + use <stdint.h> types to fix some questionable casts to void*. 845 846 20111210 847 + modify configure script to check if thread library provides 848 pthread_mutexattr_settype(), e.g., not provided by Solaris 2.6 849 + modify configure script to suppress check to define _XOPEN_SOURCE 850 for IRIX64, since its header files have a conflict versus 851 _SGI_SOURCE. 852 + modify configure script to add ".pc" files for tic- and 853 tinfo-libraries, which were omitted in recent change (cf: 20111126). 854 + fix inconsistent checks on $PKG_CONFIG variable in configure script. 855 856 20111203 857 + modify configure-check for etip.h dependencies, supplying a temporary 858 copy of ncurses_dll.h since it is a generated file (prompted by 859 Debian #646977). 860 + modify CF_CPP_PARAM_INIT "main" function to work with current C++. 861 862 20111126 863 + correct database iterator's check for duplicate entries 864 (cf: 20111001). 865 + modify database iterator to ignore $TERMCAP when it is not an 866 absolute pathname. 867 + add -D option to tic, to show the database locations that it could 868 use. 869 + improve description of database locations in tic manpage. 870 + modify the configure script to generate a list of the ".pc" files to 871 generate, rather than deriving the list from the libraries which have 872 been built (patch by Mike Frysinger). 873 + use AC_CHECK_TOOLS in preference to AC_PATH_PROGS when searching for 874 ncurses*-config, e.g., in Ada95/configure and test/configure (adapted 875 from patch by Mike Frysinger). 876 877 20111119 878 + remove obsolete/conflicting fallback definition for _POSIX_SOURCE 879 from curses.priv.h, fixing a regression with IRIX64 and Tru64 880 (cf: 20110416) 881 + modify _nc_tic_dir() to ensure that its return-value is nonnull, 882 i.e., the database iterator was not initialized. This case is needed 883 to when tic is translating to termcap, rather than loading the 884 database (cf: 20111001). 885 886 20111112 887 + add pccon entries for OpenBSD console (Alexei Malinin). 888 + build-fix for OpenBSD 4.9 with gcc 4.2.1, setting _XOPEN_SOURCE to 889 600 to work around inconsistent ifdef'ing of wcstof between C and 890 C++ header files. 891 + modify capconvert script to accept more than exact match on "xterm", 892 e.g., the "xterm-*" variants, to exclude from the conversion (patch 893 by Robert Millan). 894 + add -lc_r as alternative for -lpthread, allows build of threaded code 895 in older FreeBSD machines. 896 + build-fix for MirBSD, which fails when either _XOPEN_SOURCE or 897 _POSIX_SOURCE are defined. 898 + fix a typo misc/Makefile.in, used in uninstalling pc-files. 899 900 20111030 901 + modify make_db_path() to allow creating "terminfo.db" in the same 902 directory as an existing "terminfo" directory. This fixes a case 903 where switching between hashed/filesystem databases would cause the 904 new hashed database to be installed in the next best location - 905 root's home directory. 906 + add variable cf_cv_prog_gnat_correct to those passed to 907 config.status, fixing a problem with Ada95 builds (cf: 20111022). 908 + change feature test from _XPG5 to _XOPEN_SOURCE in two places, to 909 accommodate broken implementations for _XPG6. 910 + eliminate usage of NULL symbol from etip.h, to reduce header 911 interdependencies. 912 + add configure check to decide when to add _XOPEN_SOURCE define to 913 compiler options, i.e., for Solaris 10 and later (cf: 20100403). 914 This is a workaround for gcc 4.6, which fails to build the c++ 915 binding if that symbol is defined by the application, due to 916 incorrectly combining the corresponding feature test macros 917 (report by Peter Kruse). 918 919 20111022 920 + correct logic for discarding mouse events, retaining the partial 921 events used to build up click, double-click, etc, until needed 922 (cf: 20110917). 923 + fix configure script to avoid creating unused Ada95 makefile when 924 gnat does not work. 925 + cleanup width-related gcc 3.4.3 warnings for 64-bit platform, for the 926 internal functions of libncurses. The external interface of courses 927 uses bool, which still produces these warnings. 928 929 20111015 930 + improve description of --disable-tic-depends option to make it 931 clear that it may be useful whether or not the --with-termlib 932 option is also given (report by Sven Joachim). 933 + amend termcap equivalent for set_pglen_inch to use the X/Open 934 "YI" rather than the obsolete Solaris 2.5 "sL" (cf: 990109). 935 + improve manpage for tgetent differences from termcap library. 936 937 20111008 938 + moved static data from db_iterator.c to lib_data.c 939 + modify db_iterator.c for memory-leak checking, fix one leak. 940 + modify misc/gen-pkgconfig.in to use Requires.private for the parts 941 of ncurses rather than Requires, as well as Libs.private for the 942 other library dependencies (prompted by Debian #644728). 943 944 20111001 945 + modify tic "-K" option to only set the strict-flag rather than force 946 source-output. That allows the same flag to control the parser for 947 input and output of termcap source. 948 + modify _nc_getent() to ignore backslash at the end of a comment line, 949 making it consistent with ncurses' parser. 950 + restore a special-case check for directory needed to make termcap 951 text files load as if they were databases (cf: 20110924). 952 + modify tic's resolution/collision checking to attempt to remove the 953 conflicting alias from the second entry in the pair, which is 954 normally following in the source file. Also improved the warning 955 message to make it simpler to see which alias is the problem. 956 + improve performance of the database iterator by caching search-list. 957 958 20110925 959 + add a missing "else" in changes to _nc_read_tic_entry(). 960 961 20110924 962 + modify _nc_read_tic_entry() so that hashed-database is checked before 963 filesystem. 964 + updated CF_CURSES_LIBS check in test/configure script. 965 + modify configure script and makefiles to split TIC_ARGS and 966 TINFO_ARGS into pieces corresponding to LDFLAGS and LIBS variables, 967 to help separate searches for tic- and tinfo-libraries (patch by Nick 968 Alcock aka "Nix"). 969 + build-fix for lib_mouse.c changes (cf: 20110917). 970 971 20110917 972 + fix compiler warning for clang 2.9 973 + improve merging of mouse events (integrated patch by Damien 974 Guibouret). 975 + correct mask-check used in lib_mouse for wheel mouse buttons 4/5 976 (patch by Damien Guibouret). 977 978 20110910 979 + modify misc/gen_edit.sh to select a "linux" entry which works with 980 the current kernel rather than assuming it is always "linux3.0" 981 (cf: 20110716). 982 + revert a change to getmouse() which had the undesirable side-effect 983 of suppressing button-release events (report by Damien Guibouret, 984 cf: 20100102). 985 + add xterm+kbs fragment from xterm #272 -TD 986 + add configure option --with-pkg-config-libdir to provide control over 987 the actual directory into which pc-files are installed, do not use 988 the pkg-config environment variables (discussion with Frederic L W 989 Meunier). 990 + add link to mailing-list archive in announce.html.in, as done in 991 FAQ (prompted by question by Andrius Bentkus). 992 + improve manpage install by adjusting the "#include" examples to 993 show the ncurses-subdirectory used when --disable-overwrite option 994 is used. 995 + install an alias for "curses" to the ncurses manpage, tied to the 996 --with-curses-h configure option (suggested by Reuben Thomas). 997 998 20110903 999 + propagate error-returns from wresize, i.e., the internal 1000 increase_size and decrease_size functions through resize_term (report 1001 by Tim van der Molen, cf: 20020713). 1002 + fix typo in tset manpage (patch by Sven Joachim). 1003 1004 20110820 1005 + add a check to ensure that termcap files which might have "^?" do 1006 not use the terminfo interpretation as "\177". 1007 + minor cleanup of X-terminal emulator section of terminfo.src -TD 1008 + add terminator entry -TD 1009 + add simpleterm entry -TD 1010 + improve wattr_get macros by ensuring that if the window pointer is 1011 null, then the attribute and color values returned will be zero 1012 (cf: 20110528). 1013 1014 20110813 1015 + add substitution for $RPATH_LIST to misc/ncurses-config.in 1016 + improve performance of tic with hashed-database by caching the 1017 database connection, using atexit() to cleanup. 1018 + modify treatment of 2-character aliases at the beginning of termcap 1019 entries so they are not counted in use-resolution, since these are 1020 guaranteed to be unique. Also ignore these aliases when reporting 1021 the primary name of the entry (cf: 20040501) 1022 + double-check gn (generic) flag in terminal descriptions to 1023 accommodate old/buggy termcap databases which misused that feature. 1024 + minor fixes to _nc_tgetent(), ensure buffer is initialized even on 1025 error-return. 1026 1027 20110807 1028 + improve rpath fix from 20110730 by ensuring that the new $RPATH_LIST 1029 variable is defined in the makefiles which use it. 1030 + build-fix for DragonFlyBSD's pkgsrc in test/configure script. 1031 + build-fixes for NetBSD 5.1 with termcap support enabled. 1032 + corrected k9 in dg460-ansi, add other features based on manuals -TD 1033 + improve trimming of whitespace at the end of terminfo/termcap output 1034 from tic/infocmp. 1035 + when writing termcap source, ensure that colons in the description 1036 field are translated to a non-delimiter, i.e., "=". 1037 + add "-0" option to tic/infocmp, to make the termcap/terminfo source 1038 use a single line. 1039 + add a null-pointer check when handling the $CC variable. 1040 1041 20110730 1042 + modify configure script and makefiles in c++ and progs to allow the 1043 directory used for rpath option to be overridden, e.g., to work 1044 around updates to the variables used by tic during an install. 1045 + add -K option to tic/infocmp, to provide stricter BSD-compatibility 1046 for termcap output. 1047 + add _nc_strict_bsd variable in tic library which controls the 1048 "strict" BSD termcap compatibility from 20110723, plus these 1049 features: 1050 + allow escapes such as "\8" and "\9" when reading termcap 1051 + disallow "\a", "\e", "\l", "\s" and "\:" escapes when reading 1052 termcap files, passing through "a", "e", etc. 1053 + expand "\:" as "\072" on output. 1054 + modify _nc_get_token() to reset the token's string value in case 1055 there is a string-typed token lacking the "=" marker. 1056 + fix a few memory leaks in _nc_tgetent. 1057 + fix a few places where reading from a termcap file could refer to 1058 freed memory. 1059 + add an overflow check when converting terminfo/termcap numeric 1060 values, since terminfo stores those in a short, and they must be 1061 positive. 1062 + correct internal variables used for translating to termcap "%>" 1063 feature, and translating from termcap %B to terminfo, needed by 1064 tctest (cf: 19991211). 1065 + amend a minor fix to acsc when loading a termcap file to separate it 1066 from warnings needed for tic (cf: 20040710) 1067 + modify logic in _nc_read_entry() and _nc_read_tic_entry() to allow 1068 a termcap file to be handled via TERMINFO_DIRS. 1069 + modify _nc_infotocap() to include non-mandatory padding when 1070 translating to termcap. 1071 + modify _nc_read_termcap_entry(), passing a flag in the case where 1072 getcap is used, to reduce interactive warning messages. 1073 1074 20110723 1075 + add a check in start_color() to limit color-pairs to 256 when 1076 extended colors are not supported (patch by David Benjamin). 1077 + modify setcchar to omit no-longer-needed OR'ing of color pair in 1078 the SetAttr() macro (patch by David Benjamin). 1079 + add kich1 to sun terminfo entry (Yuri Pankov) 1080 + use bold rather than reverse for smso in sun-color terminfo entry 1081 (Yuri Pankov). 1082 + improve generation of termcap using tic/infocmp -C option, e.g., 1083 to correspond with 4.2BSD (prompted by discussion with Yuri Pankov 1084 regarding Schilling's test program): 1085 + translate %02 and %03 to %2 and %3 respectively. 1086 + suppress string capabilities which use %s, not supported by tgoto 1087 + use \040 rather than \s 1088 + expand null characters as \200 rather than \0 1089 + modify configure script to support shared libraries for DragonFlyBSD. 1090 1091 20110716 1092 + replace an assert() in _nc_Free_Argument() with a regular null 1093 pointer check (report/analysis by Franjo Ivancic). 1094 + modify configure --enable-pc-files option to take into account the 1095 PKG_CONFIG_PATH variable (report by Frederic L W Meunier). 1096 + add/use xterm+tmux chunk from xterm #271 -TD 1097 + resync xterm-new entry from xterm #271 -TD 1098 + add E3 extended capability to linux-basic (Miroslav Lichvar) 1099 + add linux2.2, linux2.6, linux3.0 entries to give context for E3 -TD 1100 + add SI/SO change to linux2.6 entry (Debian #515609) -TD 1101 + fix inconsistent tabset path in pcmw (Todd C. Miller). 1102 + remove a backslash which continued comment, obscuring altos3 1103 definition with OpenBSD toolset (Nicholas Marriott). 1104 1105 20110702 1106 + add workaround from xterm #271 changes to ensure that compiler flags 1107 are not used in the $CC variable. 1108 + improve support for shared libraries, tested with AIX 5.3, 6.1 and 1109 7.1 with both gcc 4.2.4 and cc. 1110 + modify configure checks for AIX to include release 7.x 1111 + add loader flags/libraries to libtool options so that dynamic loading 1112 works properly, adapted from ncurses-5.7-ldflags-with-libtool.patch 1113 at gentoo prefix repository (patch by Michael Haubenwallner). 1114 1115 20110626 1116 + move include of nc_termios.h out of term_entry.h, since the latter 1117 is installed, e.g., for tack while the former is not (report by 1118 Sven Joachim). 1119 1120 20110625 1121 + improve cleanup() function in lib_tstp.c, using _exit() rather than 1122 exit() and checking for SIGTERM rather than SIGQUIT (prompted by 1123 comments forwarded by Nicholas Marriott). 1124 + reduce name pollution from term.h, moving fallback #define's for 1125 tcgetattr(), etc., to new private header nc_termios.h (report by 1126 Sergio NNX). 1127 + two minor fixes for tracing (patch by Vassili Courzakis). 1128 + improve trace initialization by starting it in use_env() and 1129 ripoffline(). 1130 + review old email, add details for some changelog entries. 1131 1132 20110611 1133 + update minix entry to minix 3.2 (Thomas Cort). 1134 + fix a strict compiler warning in change to wattr_get (cf: 20110528). 1135 1136 20110604 1137 + fixes for MirBSD port: 1138 + set default prefix to /usr. 1139 + add support for shared libraries in configure script. 1140 + use S_ISREG and S_ISDIR consistently, with fallback definitions. 1141 + add a few more checks based on ncurses/link_test. 1142 + modify MKlib_gen.sh to handle sp-funcs renaming of NCURSES_OUTC type. 1143 1144 20110528 1145 + add case to CF_SHARED_OPTS for Interix (patch by Markus Duft). 1146 + used ncurses/link_test to check for behavior when the terminal has 1147 not been initialized and when an application passes null pointers 1148 to the library. Added checks to cover this (prompted by Redhat 1149 #707344). 1150 + modify MKlib_gen.sh to make its main() function call each function 1151 with zero parameters, to help find inconsistent checking for null 1152 pointers, etc. 1153 1154 20110521 1155 + fix warnings from clang 2.7 "--analyze" 1156 1157 20110514 1158 + compiler-warning fixes in panel and progs. 1159 + modify CF_PKG_CONFIG macro, from changes to tin -TD 1160 + modify CF_CURSES_FUNCS configure macro, used in test directory 1161 configure script: 1162 + work around (non-optimizer) bug in gcc 4.2.1 which caused 1163 test-expression to be omitted from executable. 1164 + force the linker to see a link-time expression of a symbol, to 1165 help work around weak-symbol issues. 1166 1167 20110507 1168 + update discussion of MKfallback.sh script in INSTALL; normally the 1169 script is used automatically via the configured makefiles. However 1170 there are still occasions when it might be used directly by packagers 1171 (report by Gunter Schaffler). 1172 + modify misc/ncurses-config.in to omit the "-L" option from the 1173 "--libs" output if the library directory is /usr/lib. 1174 + change order of tests for curses.h versus ncurses.h headers in the 1175 configure scripts for Ada95 and test-directories, to look for 1176 ncurses.h, from fixes to tin -TD 1177 + modify ncurses/tinfo/access.c to account for Tandem's root uid 1178 (report by Joachim Schmitz). 1179 1180 20110430 1181 + modify rules in Ada95/src/Makefile.in to ensure that the PIC option 1182 is not used when building a static library (report by Nicolas 1183 Boulenguez): 1184 + Ada95 build-fix for big-endian architectures such as sparc. This 1185 undoes one of the fixes from 20110319, which added an "Unused" member 1186 to representation clauses, replacing that with pragmas to suppress 1187 warnings about unused bits (patch by Nicolas Boulenguez): 1188 1189 20110423 1190 + add check in test/configure for use_window, use_screen. 1191 + add configure-checks for getopt's variables, which may be declared 1192 as different types on some Unix systems. 1193 + add check in test/configure for some legacy curses types of the 1194 function pointer passed to tputs(). 1195 + modify init_pair() to accept -1's for color value after 1196 assume_default_colors() has been called (Debian #337095). 1197 + modify test/background.c, adding commmand-line options to demonstrate 1198 assume_default_colors() and use_default_colors(). 1199 1200 20110416 1201 + modify configure script/source-code to only define _POSIX_SOURCE if 1202 the checks for sigaction and/or termios fail, and if _POSIX_C_SOURCE 1203 and _XOPEN_SOURCE are undefined (report by Valentin Ochs). 1204 + update config.guess, config.sub 1205 1206 20110409 1207 + fixes to build c++ binding with clang 3.0 (patch by Alexander 1208 Kolesen). 1209 + add check for unctrl.h in test/configure, to work around breakage in 1210 some ncurses packages. 1211 + add "--disable-widec" option to test/configure script. 1212 + add "--with-curses-colr" and "--with-curses-5lib" options to the 1213 test/configure script to address testing with very old machines. 1214 1215 20110404 5.9 release for upload to 1216 1217 20110402 1218 + various build-fixes for the rpm/dpkg scripts. 1219 + add "--enable-rpath-link" option to Ada95/configure, to allow 1220 packages to suppress the rpath feature which is normally used for 1221 the in-tree build of sample programs. 1222 + corrected definition of libdir variable in Ada95/src/Makefile.in, 1223 needed for rpm script. 1224 + add "--with-shared" option to Ada95/configure script, to allow 1225 making the C-language parts of the binding use appropriate compiler 1226 options if building a shared library with gnat. 1227 1228 20110329 1229 > portability fixes for Ada95 binding: 1230 + add configure check to ensure that SIGINT works with gnat. This is 1231 needed for the "rain" sample program. If SIGINT does not work, omit 1232 that sample program. 1233 + correct typo in check of $PKG_CONFIG variable in Ada95/configure 1234 + add ncurses_compat.c, to supply functions used in the Ada95 binding 1235 which were added in 5.7 and later. 1236 + modify sed expression in CF_NCURSES_ADDON to eliminate a dependency 1237 upon GNU sed. 1238 1239 20110326 1240 + add special check in Ada95/configure script for ncurses6 reentrant 1241 code. 1242 + regen Ada html documentation. 1243 + build-fix for Ada shared libraries versus the varargs workaround. 1244 + add rpm and dpkg scripts for Ada95 and test directories, for test 1245 builds. 1246 + update test/configure macros CF_CURSES_LIBS, CF_XOPEN_SOURCE and 1247 CF_X_ATHENA_LIBS. 1248 + add configure check to determine if gnat's project feature supports 1249 libraries, i.e., collections of .ali files. 1250 + make all dereferences in Ada95 samples explicit. 1251 + fix typo in comment in lib_add_wch.c (patch by Petr Pavlu). 1252 + add configure check for, ifdef's for math.h which is in a separate 1253 package on Solaris and potentially not installed (report by Petr 1254 Pavlu). 1255 > fixes for Ada95 binding (Nicolas Boulenguez): 1256 + improve type-checking in Ada95 by eliminating a few warning-suppress 1257 pragmas. 1258 + suppress unreferenced warnings. 1259 + make all dereferences in binding explicit. 1260 1261 20110319 1262 + regen Ada html documentation. 1263 + change order of -I options from ncurses*-config script when the 1264 --disable-overwrite option was used, so that the subdirectory include 1265 is listed first. 1266 + modify the make-tar.sh scripts to add a MANIFEST and NEWS file. 1267 + modify configure script to provide value for HTML_DIR in 1268 Ada95/gen/Makefile.in, which depends on whether the Ada95 binding is 1269 distributed separately (report by Nicolas Boulenguez). 1270 + modify configure script to add "-g" and/or "-O3" to ADAFLAGS if the 1271 CFLAGS for the build has these options. 1272 + amend change from 20070324, to not add 1 to the result of getmaxx 1273 and getmaxy in the Ada binding (report by Nicolas Boulenguez for 1274 thread in comp.lang.ada). 1275 + build-fix Ada95/samples for gnat 4.5 1276 + spelling fixes for Ada95/samples/explain.txt 1277 > fixes for Ada95 binding (Nicolas Boulenguez): 1278 + add item in Trace_Attribute_Set corresponding to TRACE_ATTRS. 1279 + add workaround for binding to set_field_type(), which uses varargs. 1280 The original binding from 990220 relied on the prevalent 1281 implementation of varargs which did not support or need va_copy(). 1282 + add dependency on gen/Makefile.in needed for *-panels.ads 1283 + add Library_Options to library.gpr 1284 + add Languages to library.gpr, for gprbuild 1285 1286 20110307 1287 + revert changes to limit-checks from 20110122 (Debian #616711). 1288 > minor type-cleanup of Ada95 binding (Nicolas Boulenguez): 1289 + corrected a minor sign error in a field of Low_Level_Field_Type, to 1290 conform to form.h. 1291 + replaced C_Int by Curses_Bool as return type for some callbacks, see 1292 fieldtype(3FORM). 1293 + modify samples/sample-explain.adb to provide explicit message when 1294 explain.txt is not found. 1295 1296 20110305 1297 + improve makefiles for Ada95 tree (patch by Nicolas Boulenguez). 1298 + fix an off-by-one error in _nc_slk_initialize() from 20100605 fixes 1299 for compiler warnings (report by Nicolas Boulenguez). 1300 + modify Ada95/gen/gen.c to declare unused bits in generated layouts, 1301 needed to compile when chtype is 64-bits using gnat 4.4.5 1302 1303 20110226 5.8 release for upload to 1304 1305 20110226 1306 + update release notes, for 5.8. 1307 + regenerated html manpages. 1308 + change open() in _nc_read_file_entry() to fopen() for consistency 1309 with write_file(). 1310 + modify misc/run_tic.in to create parent directory, in case this is 1311 a new install of hashed database. 1312 + fix typo in Ada95/mk-1st.awk which causes error with original awk. 1313 1314 20110220 1315 + configure script rpath fixes from xterm #269. 1316 + workaround for cygwin's non-functional features.h, to force ncurses' 1317 configure script to define _XOPEN_SOURCE_EXTENDED when building 1318 wide-character configuration. 1319 + build-fix in run_tic.sh for OS/2 EMX install 1320 + add cons25-debian entry (patch by Brian M Carlson, Debian #607662). 1321 1322 20110212 1323 + regenerated html manpages. 1324 + use _tracef() in show_where() function of tic, to work correctly with 1325 special case of trace configuration. 1326 1327 20110205 1328 + add xterm-utf8 entry as a demo of the U8 feature -TD 1329 + add U8 feature to denote entries for terminal emulators which do not 1330 support VT100 SI/SO when processing UTF-8 encoding -TD 1331 + improve the NCURSES_NO_UTF8_ACS feature by adding a check for an 1332 extended terminfo capability U8 (prompted by mailing list 1333 discussion). 1334 1335 20110122 1336 + start documenting interface changes for upcoming 5.8 release. 1337 + correct limit-checks in derwin(). 1338 + correct limit-checks in newwin(), to ensure that windows have nonzero 1339 size (report by Garrett Cooper). 1340 + fix a missing "weak" declaration for pthread_kill (patch by Nicholas 1341 Alcock). 1342 + improve documentation of KEY_ENTER in curs_getch.3x manpage (prompted 1343 by discussion with Kevin Martin). 1344 1345 20110115 1346 + modify Ada95/configure script to make the --with-curses-dir option 1347 work without requiring the --with-ncurses option. 1348 + modify test programs to allow them to be built with NetBSD curses. 1349 + document thick- and double-line symbols in curs_add_wch.3x manpage. 1350 + document WACS_xxx constants in curs_add_wch.3x manpage. 1351 + fix some warnings for clang 2.6 "--analyze" 1352 + modify Ada95 makefiles to make html-documentation with the project 1353 file configuration if that is used. 1354 + update config.guess, config.sub 1355 1356 20110108 1357 + regenerated html manpages. 1358 + minor fixes to enable lint when trace is not enabled, e.g., with 1359 clang --analyze. 1360 + fix typo in man/default_colors.3x (patch by Tim van der Molen). 1361 + update ncurses/llib-lncurses* 1362 1363 20110101 1364 + fix remaining strict compiler warnings in ncurses library ABI=5, 1365 except those dealing with function pointers, etc. 1366 1367 20101225 1368 + modify nc_tparm.h, adding guards against repeated inclusion, and 1369 allowing TPARM_ARG to be overridden. 1370 + fix some strict compiler warnings in ncurses library. 1371 1372 20101211 1373 + suppress ncv in screen entry, allowing underline (patch by Alejandro 1374 R Sedeno). 1375 + also suppress ncv in konsole-base -TD 1376 + fixes in wins_nwstr() and related functions to ensure that special 1377 characters, i.e., control characters are handled properly with the 1378 wide-character configuration. 1379 + correct a comparison in wins_nwstr() (Redhat #661506). 1380 + correct help-messages in some of the test-programs, which still 1381 referred to quitting with 'q'. 1382 1383 20101204 1384 + add special case to _nc_infotocap() to recognize the setaf/setab 1385 strings from xterm+256color and xterm+88color, and provide a reduced 1386 version which works with termcap. 1387 + remove obsolete emacs "Local Variables" section from documentation 1388 (request by Sven Joachim). 1389 + update doc/html/index.html to include NCURSES-Programming-HOWTO.html 1390 (report by Sven Joachim). 1391 1392 20101128 1393 + modify test/configure and test/Makefile.in to handle this special 1394 case of building within a build-tree (Debian #34182): 1395 mkdir -p build && cd build && ../test/configure && make 1396 1397 20101127 1398 + miscellaneous build-fixes for Ada95 and test-directories when built 1399 out-of-tree. 1400 + use VPATH in makefiles to simplify out-of-tree builds (Debian #34182). 1401 + fix typo in rmso for tek4106 entry -Goran Weinholt 1402 1403 20101120 1404 + improve checks in test/configure for X libraries, from xterm #267 1405 changes. 1406 + modify test/configure to allow it to use the build-tree's libraries 1407 e.g., when using that to configure the test-programs without the 1408 rpath feature (request by Sven Joachim). 1409 + repurpose "gnome" terminfo entries as "vte", retaining "gnome" items 1410 for compatibility, but generally deprecating those since the VTE 1411 library is what actually defines the behavior of "gnome", etc., 1412 since 2003 -TD 1413 1414 20101113 1415 + compiler warning fixes for test programs. 1416 + various build-fixes for test-programs with pdcurses. 1417 + updated configure checks for X packages in test/configure from xterm 1418 #267 changes. 1419 + add configure check to gnatmake, to accommodate cygwin. 1420 1421 20101106 1422 + correct list of sub-directories needed in Ada95 tree for building as 1423 a separate package. 1424 + modify scripts in test-directory to improve builds as a separate 1425 package. 1426 1427 20101023 1428 + correct parsing of relative tab-stops in tabs program (report by 1429 Philip Ganchev). 1430 + adjust configure script so that "t" is not added to library suffix 1431 when weak-symbols are used, allowing the pthread configuration to 1432 more closely match the non-thread naming (report by Werner Fink). 1433 + modify configure check for tic program, used for fallbacks, to a 1434 warning if not found. This makes it simpler to use additonal 1435 scripts to bootstrap the fallbacks code using tic from the build 1436 tree (report by Werner Fink). 1437 + fix several places in configure script using ${variable-value} form. 1438 + modify configure macro CF_LDFLAGS_STATIC to accommodate some loaders 1439 which do not support selectively linking against static libraries 1440 (report by John P. Hartmann) 1441 + fix an unescaped dash in man/tset.1 (report by Sven Joachim). 1442 1443 20101009 1444 + correct comparison used for setting 16-colors in linux-16color 1445 entry (Novell #644831) -TD 1446 + improve linux-16color entry, using "dim" for color-8 which makes it 1447 gray rather than black like color-0 -TD 1448 + drop misc/ncu-indent and misc/jpf-indent; they are provided by an 1449 external package "cindent". 1450 1451 20101002 1452 + improve linkages in html manpages, adding references to the newer 1453 pages, e.g., *_variables, curs_sp_funcs, curs_threads. 1454 + add checks in tic for inconsistent cursor-movement controls, and for 1455 inconsistent printer-controls. 1456 + fill in no-parameter forms of cursor-movement where a parameterized 1457 form is available -TD 1458 + fill in missing cursor controls where the form of the controls is 1459 ANSI -TD 1460 + fix inconsistent punctuation in form_variables manpage (patch by 1461 Sven Joachim). 1462 + add parameterized cursor-controls to linux-basic (report by Dae) -TD 1463 > patch by Juergen Pfeifer: 1464 + document how to build 32-bit libraries in README.MinGW 1465 + fixes to filename computation in mk-dlls.sh.in 1466 + use POSIX locale in mk-dlls.sh.in rather than en_US (report by Sven 1467 Joachim). 1468 + add a check in mk-dlls.sh.in to obtain the size of a pointer to 1469 distinguish between 32-bit and 64-bit hosts. The result is stored 1470 in mingw_arch 1471 1472 20100925 1473 + add "XT" capability to entries for terminals that support both 1474 xterm-style mouse- and title-controls, for "screen" which 1475 special-cases TERM beginning with "xterm" or "rxvt" -TD 1476 > patch by Juergen Pfeifer: 1477 + use 64-Bit MinGW toolchain (recommended package from TDM, see 1478 README.MinGW). 1479 + support pthreads when using the TDM MinGW toolchain 1480 1481 20100918 1482 + regenerated html manpages. 1483 + minor fixes for symlinks to curs_legacy.3x and curs_slk.3x manpages. 1484 + add manpage for sp-funcs. 1485 + add sp-funcs to test/listused.sh, for documentation aids. 1486 1487 20100911 1488 + add manpages for summarizing public variables of curses-, terminfo- 1489 and form-libraries. 1490 + minor fixes to manpages for consistency (patch by Jason McIntyre). 1491 + modify tic's -I/-C dump to reformat acsc strings into canonical form 1492 (sorted, unique mapping) (cf: 971004). 1493 + add configure check for pthread_kill(), needed for some old 1494 platforms. 1495 1496 20100904 1497 + add configure option --without-tests, to suppress building test 1498 programs (request by Frederic L W Meunier). 1499 1500 20100828 1501 + modify nsterm, xnuppc and tek4115 to make sgr/sgr0 consistent -TD 1502 + add check in terminfo source-reader to provide more informative 1503 message when someone attempts to run tic on a compiled terminal 1504 description (prompted by Debian #593920). 1505 + note in infotocap and captoinfo manpages that they read terminal 1506 descriptions from text-files (Debian #593920). 1507 + improve acsc string for vt52, show arrow keys (patch by Benjamin 1508 Sittler). 1509 1510 20100814 1511 + document in manpages that "mv" functions first use wmove() to check 1512 the window pointer and whether the position lies within the window 1513 (suggested by Poul-Henning Kamp). 1514 + fixes to curs_color.3x, curs_kernel.3x and wresize.3x manpages (patch 1515 by Tim van der Molen). 1516 + modify configure script to transform library names for tic- and 1517 tinfo-libraries so that those build properly with Mac OS X shared 1518 library configuration. 1519 + modify configure script to ensure that it removes conftest.dSYM 1520 directory leftover on checks with Mac OS X. 1521 + modify configure script to cleanup after check for symbolic links. 1522 1523 20100807 1524 + correct a typo in mk-1st.awk (patch by Gabriele Balducci) 1525 (cf: 20100724) 1526 + improve configure checks for location of tic and infocmp programs 1527 used for installing database and for generating fallback data, 1528 e.g., for cross-compiling. 1529 + add Markus Kuhn's wcwidth function for compiling MinGW 1530 + add special case to CF_REGEX for cross-compiling to MinGW target. 1531 1532 20100731 1533 + modify initialization check for win32con driver to eliminate need for 1534 special case for TERM "unknown", using terminal database if available 1535 (prompted by discussion with Roumen Petrov). 1536 + for MinGW port, ensure that terminal driver is setup if tgetent() 1537 is called (patch by Roumen Petrov). 1538 + document tabs "-0" and "-8" options in manpage. 1539 + fix Debian "lintian" issues with manpages reported in 1540 1541 1542 20100724 1543 + add a check in tic for missing set_tab if clear_all_tabs given. 1544 + improve use of symbolic links in makefiles by using "-f" option if 1545 it is supported, to eliminate temporary removal of the target 1546 (prompted by) 1547 + minor improvement to test/ncurses.c, reset color pairs in 'd' test 1548 after exit from 'm' main-menu command. 1549 + improved ncu-indent, from mawk changes, allows more than one of 1550 GCC_NORETURN, GCC_PRINTFLIKE and GCC_SCANFLIKE on a single line. 1551 1552 20100717 1553 + add hard-reset for rs2 to wsvt25 to help ensure that reset ends 1554 the alternate character set (patch by Nicholas Marriott) 1555 + remove tar-copy.sh and related configure/Makefile chunks, since the 1556 Ada95 binding is now installed using rules in Ada95/src. 1557 1558 20100703 1559 + continue integrating changes to use gnatmake project files in Ada95 1560 + add/use configure check to turn on project rules for Ada95/src. 1561 + revert the vfork change from 20100130, since it does not work. 1562 1563 20100626 1564 + continue integrating changes to use gnatmake project files in Ada95 1565 + old gnatmake (3.15) does not produce libraries using project-file; 1566 work around by adding script to generate alternate makefile. 1567 1568 20100619 1569 + continue integrating changes to use gnatmake project files in Ada95 1570 + add configure --with-ada-sharedlib option, for the test_make rule. 1571 + move Ada95-related logic into aclocal.m4, since additional checks 1572 will be needed to distinguish old/new implementations of gnat. 1573 1574 20100612 1575 + start integrating changes to use gnatmake project files in Ada95 tree 1576 + add test_make / test_clean / test_install rules in Ada95/src 1577 + change install-path for adainclude directory to /usr/share/ada (was 1578 /usr/lib/ada). 1579 + update Ada95/configure. 1580 + add mlterm+256color entry, for mlterm 3.0.0 -TD 1581 + modify test/configure to use macros to ensure consistent order 1582 of updating LIBS variable. 1583 1584 20100605 1585 + change search order of options for Solaris in CF_SHARED_OPTS, to 1586 work with 64-bit compiles. 1587 + correct quoting of assignment in CF_SHARED_OPTS case for aix 1588 (cf: 20081227) 1589 1590 20100529 1591 + regenerated html documentation. 1592 + modify test/configure to support pkg-config for checking X libraries 1593 used by PDCurses. 1594 + add/use configure macro CF_ADD_LIB to force consistency of 1595 assignments to $LIBS, etc. 1596 + fix configure script for combining --with-pthread 1597 and --enable-weak-symbols options. 1598 1599 20100522 1600 + correct cross-compiling configure check for CF_MKSTEMP macro, by 1601 adding a check cache variable set by AC_CHECK_FUNC (report by 1602 Pierre Labastie). 1603 + simplify include-dependencies of make_hash and make_keys, to reduce 1604 the need for setting BUILD_CPPFLAGS in cross-compiling when the 1605 build- and target-machines differ. 1606 + repair broken-linker configuration by restoring a definition of SP 1607 variable to curses.priv.h, and adjusting for cases where sp-funcs 1608 are used. 1609 + improve configure macro CF_AR_FLAGS, allowing ARFLAGS environment 1610 variable to override (prompted by report by Pablo Cazallas). 1611 1612 20100515 1613 + add configure option --enable-pthreads-eintr to control whether the 1614 new EINTR feature is enabled. 1615 + modify logic in pthread configuration to allow EINTR to interrupt 1616 a read operation in wgetch() (Novell #540571, patch by Werner Fink). 1617 + drop mkdirs.sh, use "mkdir -p". 1618 + add configure option --disable-libtool-version, to use the 1619 "-version-number" feature which was added in libtool 1.5 (report by 1620 Peter Haering). The default value for the option uses the newer 1621 feature, which makes libraries generated using libtool compatible 1622 with the standard builds of ncurses. 1623 + updated test/configure to match configure script macros. 1624 + fixes for configure script from lynx changes: 1625 + improve CF_FIND_LINKAGE logic for the case where a function is 1626 found in predefined libraries. 1627 + revert part of change to CF_HEADER (cf: 20100424) 1628 1629 20100501 1630 + correct limit-check in wredrawln, accounting for begy/begx values 1631 (patch by David Benjamin). 1632 + fix most compiler warnings from clang. 1633 + amend build-fix for OpenSolaris, to ensure that a system header is 1634 included in curses.h before testing feature symbols, since they 1635 may be defined by that route. 1636 1637 20100424 1638 + fix some strict compiler warnings in ncurses library. 1639 + modify configure macro CF_HEADER_PATH to not look for variations in 1640 the predefined include directories. 1641 + improve configure macros CF_GCC_VERSION and CF_GCC_WARNINGS to work 1642 with gcc 4.x's c89 alias, which gives warning messages for cases 1643 where older versions would produce an error. 1644 1645 20100417 1646 + modify _nc_capcmp() to work with cancelled strings. 1647 + correct translation of "^" in _nc_infotocap(), used to transform 1648 terminfo to termcap strings 1649 + add configure --disable-rpath-hack, to allow disabling the feature 1650 which adds rpath options for libraries in unusual places. 1651 + improve CF_RPATH_HACK_2 by checking if the rpath option for a given 1652 directory was already added. 1653 + improve CF_RPATH_HACK_2 by using ldd to provide a standard list of 1654 directories (which will be ignored). 1655 1656 20100410 1657 + improve win_driver.c handling of mouse: 1658 + discard motion events 1659 + avoid calling _nc_timed_wait when there is a mouse event 1660 + handle 4th and "rightmost" buttons. 1661 + quote substitutions in CF_RPATH_HACK_2 configure macro, needed for 1662 cases where there are embedded blanks in the rpath option. 1663 1664 20100403 1665 + add configure check for exctags vs ctags, to work around pkgsrc. 1666 + simplify logic in _nc_get_screensize() to make it easier to see how 1667 environment variables may override system- and terminfo-values 1668 (prompted by discussion with Igor Bujna). 1669 + make debug-traces for COLOR_PAIR and PAIR_NUMBER less verbose. 1670 + improve handling of color-pairs embedded in attributes for the 1671 extended-colors configuration. 1672 + modify MKlib_gen.sh to build link_test with sp-funcs. 1673 + build-fixes for OpenSolaris aka Solaris 11, for wide-character 1674 configuration as well as for rpath feature in *-config scripts. 1675 1676 20100327 1677 + refactor CF_SHARED_OPTS configure macro, making CF_RPATH_HACK more 1678 reusable. 1679 + improve configure CF_REGEX, similar fixes. 1680 + improve configure CF_FIND_LINKAGE, adding add check between system 1681 (default) and explicit paths, where we can find the entrypoint in the 1682 given library. 1683 + add check if Gpm_Open() returns a -2, e.g., for "xterm". This is 1684 normally suppressed but can be overridden using $NCURSES_GPM_TERMS. 1685 Ensure that Gpm_Close() is called in this case. 1686 1687 20100320 1688 + rename atari and st52 terminfo entries to atari-old, st52-old, use 1689 newer entries from FreeMiNT by Guido Flohr (from patch/report by Alan 1690 Hourihane). 1691 1692 20100313 1693 + modify install-rule for manpages so that *-config manpages will 1694 install when building with --srcdir (report by Sven Joachim). 1695 + modify CF_DISABLE_LEAKS configure macro so that the --enable-leaks 1696 option is not the same as --disable-leaks (GenToo #305889). 1697 + modify #define's for build-compiler to suppress cchar_t symbol from 1698 compile of make_hash and make_keys, improving cross-compilation of 1699 ncursesw (report by Bernhard Rosenkraenzer). 1700 + modify CF_MAN_PAGES configure macro to replace all occurrences of 1701 TPUT in tput.1's manpage (Debian #573597, report/analysis by Anders 1702 Kaseorg). 1703 1704 20100306 1705 + generate manpages for the *-config scripts, adapted from help2man 1706 (suggested by Sven Joachim). 1707 + use va_copy() in _nc_printf_string() to avoid conflicting use of 1708 va_list value in _nc_printf_length() (report by Wim Lewis). 1709 1710 20100227 1711 + add Ada95/configure script, to use in tar-file created by 1712 Ada95/make-tar.sh 1713 + fix typo in wresize.3x (patch by Tim van der Molen). 1714 + modify screen-bce.XXX entries to exclude ech, since screen's color 1715 model does not clear with color for that feature -TD 1716 1717 20100220 1718 + add make-tar.sh scripts to Ada95 and test subdirectories to help with 1719 making those separately distributable. 1720 + build-fix for static libraries without dlsym (Debian #556378). 1721 + fix a syntax error in man/form_field_opts.3x (patch by Ingo 1722 Schwarze). 1723 1724 20100213 1725 + add several screen-bce.XXX entries -TD 1726 1727 20100206 1728 + update mrxvt terminfo entry -TD 1729 + modify win_driver.c to support mouse single-clicks. 1730 + correct name for termlib in ncurses*-config, e.g., if it is renamed 1731 to provide a single file for ncurses/ncursesw libraries (patch by 1732 Miroslav Lichvar). 1733 1734 20100130 1735 + use vfork in test/ditto.c if available (request by Mike Frysinger). 1736 + miscellaneous cleanup of manpages. 1737 + fix typo in curs_bkgd.3x (patch by Tim van der Molen). 1738 + build-fix for --srcdir (patch by Miroslav Lichvar). 1739 1740 20100123 1741 + for term-driver configuration, ensure that the driver pointer is 1742 initialized in setupterm so that terminfo/termcap programs work. 1743 + amend fix for Debian #542031 to ensure that wattrset() returns only 1744 OK or ERR, rather than the attribute value (report by Miroslav 1745 Lichvar). 1746 + reorder WINDOWLIST to put WINDOW data after SCREEN pointer, making 1747 _nc_screen_of() compatible between normal/wide libraries again (patch 1748 by Miroslav Lichvar) 1749 + review/fix include-dependencies in modules files (report by Miroslav 1750 Lichvar). 1751 1752 20100116 1753 + modify win_driver.c to initialize acs_map for win32 console, so 1754 that line-drawing works. 1755 + modify win_driver.c to initialize TERMINAL struct so that programs 1756 such as test/lrtest.c and test/ncurses.c which test string 1757 capabilities can run. 1758 + modify term-driver modules to eliminate forward-reference 1759 declarations. 1760 1761 20100109 1762 + modify configure macro CF_XOPEN_SOURCE, etc., to use CF_ADD_CFLAGS 1763 consistently to add new -D's while removing duplicates. 1764 + modify a few configure macros to consistently put new options 1765 before older in the list. 1766 + add tiparm(), based on review of X/Open Curses Issue 7. 1767 + minor documentation cleanup. 1768 + update config.guess, config.sub from 1769 1770 (caveat - its maintainer put 2010 copyright date on files dated 2009) 1771 1772 20100102 1773 + minor improvement to tic's checking of similar SGR's to allow for the 1774 most common case of SGR 0. 1775 + modify getmouse() to act as its documentation implied, returning on 1776 each call the preceding event until none are left. When no more 1777 events remain, it will return ERR. 1778 1779 20091227 1780 + change order of lookup in progs/tput.c, looking for terminfo data 1781 first. This fixes a confusion between termcap "sg" and terminfo 1782 "sgr" or "sgr0", originally from 990123 changes, but exposed by 1783 20091114 fixes for hashing. With this change, only "dl" and "ed" are 1784 ambiguous (Mandriva #56272). 1785 1786 20091226 1787 + add bterm terminfo entry, based on bogl 0.1.18 -TD 1788 + minor fix to rxvt+pcfkeys terminfo entry -TD 1789 + build-fixes for Ada95 tree for gnat 4.4 "style". 1790 1791 20091219 1792 + remove old check in mvderwin() which prevented moving a derived 1793 window whose origin happened to coincide with its parent's origin 1794 (report by Katarina Machalkova). 1795 + improve test/ncurses.c to put mouse droppings in the proper window. 1796 + update minix terminfo entry -TD 1797 + add bw (auto-left-margin) to nsterm* entries (Benjamin Sittler) 1798 1799 20091212 1800 + correct transfer of multicolumn characters in multirow 1801 field_buffer(), which stopped at the end of the first row due to 1802 filling of unused entries in a cchar_t array with nulls. 1803 + updated nsterm* entries (Benjamin Sittler, Emanuele Giaquinta) 1804 + modify _nc_viscbuf2() and _tracecchar_t2() to show wide-character 1805 nulls. 1806 + use strdup() in set_menu_mark(), restore .marklen struct member on 1807 failure. 1808 + eliminate clause 3 from the UCB copyrights in read_termcap.c and 1809 tset.c per 1810 1811 (patch by Nicholas Marriott). 1812 + replace a malloc in tic.c with strdup, checking for failure (patch by 1813 Nicholas Marriott). 1814 + update config.guess, config.sub from 1815 1816 1817 20091205 1818 + correct layout of working window used to extract data in 1819 wide-character configured by set_field_buffer (patch by Rafael 1820 Garrido Fernandez) 1821 + improve some limit-checks related to filename length in reading and 1822 writing terminfo entries. 1823 + ensure that filename is always filled in when attempting to read 1824 a terminfo entry, so that infocmp can report the filename (patch 1825 by Nicholas Marriott). 1826 1827 20091128 1828 + modify mk-1st.awk to allow tinfo library to be built when term-driver 1829 is enabled. 1830 + add error-check to configure script to ensure that sp-funcs is 1831 enabled if term-driver is, since some internal interfaces rely upon 1832 this. 1833 1834 20091121 1835 + fix case where progs/tput is used while sp-funcs is configure; this 1836 requires save/restore of out-character function from _nc_prescreen 1837 rather than the SCREEN structure (report by Charles Wilson). 1838 + fix typo in man/curs_trace.3x which caused incorrect symbolic links 1839 + improved configure macros CF_GCC_ATTRIBUTES, CF_PROG_LINT. 1840 1841 20091114 1842 1843 + updated man/curs_trace.3x 1844 + limit hashing for termcap-names to 2-characters (Ubuntu #481740). 1845 + change a variable name in lib_newwin.c to make it clearer which 1846 value is being freed on error (patch by Nicholas Marriott). 1847 1848 20091107 1849 + improve test/ncurses.c color-cycling test by reusing attribute- 1850 and color-cycling logic from the video-attributes screen. 1851 + add ifdef'd with NCURSES_INTEROP_FUNCS experimental bindings in form 1852 library which help make it compatible with interop applications 1853 (patch by Juergen Pfeifer). 1854 + add configure option --enable-interop, for integrating changes 1855 for generic/interop support to form-library by Juergen Pfeifer 1856 1857 20091031 1858 + modify use of $CC environment variable which is defined by X/Open 1859 as a curses feature, to ignore it if it is not a single character 1860 (prompted by discussion with Benjamin C W Sittler). 1861 + add START_TRACE in slk_init 1862 + fix a regression in _nc_ripoffline which made test/ncurses.c not show 1863 soft-keys, broken in 20090927 merging. 1864 + change initialization of "hidden" flag for soft-keys from true to 1865 false, broken in 20090704 merging (Ubuntu #464274). 1866 + update nsterm entries (patch by Benjamin C W Sittler, prompted by 1867 discussion with Fabian Groffen in GenToo #206201). 1868 + add test/xterm-256color.dat 1869 1870 20091024 1871 + quiet some pedantic gcc warnings. 1872 + modify _nc_wgetch() to check for a -1 in the fifo, e.g., after a 1873 SIGWINCH, and discard that value, to avoid confusing application 1874 (patch by Eygene Ryabinkin, FreeBSD bin/136223). 1875 1876 20091017 1877 + modify handling of $PKG_CONFIG_LIBDIR to use only the first item in 1878 a possibly colon-separated list (Debian #550716). 1879 1880 20091010 1881 + supply a null-terminator to buffer in _nc_viswibuf(). 1882 + fix a sign-extension bug in unget_wch() (report by Mike Gran). 1883 + minor fixes to error-returns in default function for tputs, as well 1884 as in lib_screen.c 1885 1886 20091003 1887 + add WACS_xxx definitions to wide-character configuration for thick- 1888 and double-lines (discussion with Slava Zanko). 1889 + remove unnecessary kcan assignment to ^C from putty (Sven Joachim) 1890 + add ccc and initc capabilities to xterm-16color -TD 1891 > patch by Benjamin C W Sittler: 1892 + add linux-16color 1893 + correct initc capability of linux-c-nc end-of-range 1894 + similar change for dg+ccc and dgunix+ccc 1895 1896 20090927 1897 + move leak-checking for comp_captab.c into _nc_leaks_tinfo() since 1898 that module since 20090711 is in libtinfo. 1899 + add configure option --enable-term-driver, to allow compiling with 1900 terminal-driver. That is used in MinGW port, and (being somewhat 1901 more complicated) is an experimental alternative to the conventional 1902 termlib internals. Currently, it requires the sp-funcs feature to 1903 be enabled. 1904 + completed integrating "sp-funcs" by Juergen Pfeifer in ncurses 1905 library (some work remains for forms library). 1906 1907 20090919 1908 + document return code from define_key (report by Mike Gran). 1909 + make some symbolic links in the terminfo directory-tree shorter 1910 (patch by Daniel Jacobowitz, forwarded by Sven Joachim).). 1911 + fix some groff warnings in terminfo.5, etc., from recent Debian 1912 changes. 1913 + change ncv and op capabilities in sun-color terminfo entry to match 1914 Sun's entry for this (report by Laszlo Peter). 1915 + improve interix smso terminfo capability by using reverse rather than 1916 bold (report by Kristof Zelechovski). 1917 1918 20090912 1919 + add some test programs (and make these use the same special keys 1920 by sharing linedata.h functions): 1921 test/test_addstr.c 1922 test/test_addwstr.c 1923 test/test_addchstr.c 1924 test/test_add_wchstr.c 1925 + correct internal _nc_insert_ch() to use _nc_insert_wch() when 1926 inserting wide characters, since the wins_wch() function that it used 1927 did not update the cursor position (report by Ciprian Craciun). 1928 1929 20090906 1930 + fix typo s/is_timeout/is_notimeout/ which made "man is_notimeout" not 1931 work. 1932 + add null-pointer checks to other opaque-functions. 1933 + add is_pad() and is_subwin() functions for opaque access to WINDOW 1934 (discussion with Mark Dickinson). 1935 + correct merge to lib_newterm.c, which broke when sp-funcs was 1936 enabled. 1937 1938 20090905 1939 + build-fix for building outside source-tree (report by Sven Joachim). 1940 + fix Debian lintian warning for man/tabs.1 by making section number 1941 agree with file-suffix (report by Sven Joachim). 1942 + continue integrating "sp-funcs" by Juergen Pfeifer (incomplete). 1943 1944 20090829 1945 + workaround for bug in g++ 4.1-4.4 warnings for wattrset() macro on 1946 amd64 (Debian #542031). 1947 + fix typo in curs_mouse.3x (Debian #429198). 1948 1949 20090822 1950 + continue integrating "sp-funcs" by Juergen Pfeifer (incomplete). 1951 1952 20090815 1953 + correct use of terminfo capabilities for initializing soft-keys, 1954 broken in 20090509 merging. 1955 + modify wgetch() to ensure it checks SIGWINCH when it gets an error 1956 in non-blocking mode (patch by Clemens Ladisch). 1957 + use PATH_SEPARATOR symbol when substituting into run_tic.sh, to 1958 help with builds on non-Unix platforms such as OS/2 EMX. 1959 + modify scripting for misc/run_tic.sh to test configure script's 1960 $cross_compiling variable directly rather than comparing host/build 1961 compiler names (prompted by comment in GenToo #249363). 1962 + fix configure script option --with-database, which was coded as an 1963 enable-type switch. 1964 + build-fixes for --srcdir (report by Frederic L W Meunier). 1965 1966 20090808 1967 + separate _nc_find_entry() and _nc_find_type_entry() from 1968 implementation details of hash function. 1969 1970 20090803 1971 + add tabs.1 to man/man_db.renames 1972 + modify lib_addch.c to compensate for removal of wide-character test 1973 from unctrl() in 20090704 (Debian #539735). 1974 1975 20090801 1976 + improve discussion in INSTALL for use of system's tic/infocmp for 1977 cross-compiling and building fallbacks. 1978 + modify test/demo_termcap.c to correspond better to options in 1979 test/demo_terminfo.c 1980 + continue integrating "sp-funcs" by Juergen Pfeifer (incomplete). 1981 + fix logic for 'V' in test/ncurses.c tests f/F. 1982 1983 20090728 1984 + correct logic in tigetnum(), which caused tput program to treat all 1985 string capabilities as numeric (report by Rajeev V Pillai, 1986 cf: 20090711). 1987 1988 20090725 1989 + continue integrating "sp-funcs" by Juergen Pfeifer (incomplete). 1990 1991 20090718 1992 + fix a null-pointer check in _nc_format_slks() in lib_slk.c, from 1993 20070704 changes. 1994 + modify _nc_find_type_entry() to use hashing. 1995 + make CCHARW_MAX value configurable, noting that changing this would 1996 change the size of cchar_t, and would be ABI-incompatible. 1997 + modify test-programs, e.g,. test/view.c, to address subtle 1998 differences between Tru64/Solaris and HPUX/AIX getcchar() return 1999 values. 2000 + modify length returned by getcchar() to count the trailing null 2001 which is documented in X/Open (cf: 20020427). 2002 + fixes for test programs to build/work on HPUX and AIX, etc. 2003 2004 20090711 2005 + improve performance of tigetstr, etc., by using hashing code from tic. 2006 + minor fixes for memory-leak checking. 2007 + add test/demo_terminfo, for comparison with demo_termcap 2008 2009 20090704 2010 + remove wide-character checks from unctrl() (patch by Clemens Ladisch). 2011 + revise wadd_wch() and wecho_wchar() to eliminate dependency on 2012 unctrl(). 2013 + continue integrating "sp-funcs" by Juergen Pfeifer (incomplete). 2014 2015 20090627 2016 + update llib-lncurses[wt] to use sp-funcs. 2017 + various code-fixes to build/work with --disable-macros configure 2018 option. 2019 + add several new files from Juergen Pfeifer which will be used when 2020 integration of "sp-funcs" is complete. This includes a port to 2021 MinGW. 2022 2023 20090613 2024 + move definition for NCURSES_WRAPPED_VAR back to ncurses_dll.h, to 2025 make includes of term.h without curses.h work (report by "Nix"). 2026 + continue integrating "sp-funcs" by Juergen Pfeifer (incomplete). 2027 2028 20090607 2029 + fix a regression in lib_tputs.c, from ongoing merges. 2030 2031 20090606 2032 + continue integrating "sp-funcs" by Juergen Pfeifer (incomplete). 2033 2034 20090530 2035 + fix an infinite recursion when adding a legacy-coding 8-bit value 2036 using insch() (report by Clemens Ladisch). 2037 + free home-terminfo string in del_curterm() (patch by Dan Weber). 2038 + continue integrating "sp-funcs" by Juergen Pfeifer (incomplete). 2039 2040 20090523 2041 + continue integrating "sp-funcs" by Juergen Pfeifer (incomplete). 2042 2043 20090516 2044 + work around antique BSD game's manipulation of stdscr, etc., versus 2045 SCREEN's copy of the pointer (Debian #528411). 2046 + add a cast to wattrset macro to avoid compiler warning when comparing 2047 its result against ERR (adapted from patch by Matt Kraii, Debian 2048 #528374). 2049 2050 20090510 2051 + continue integrating "sp-funcs" by Juergen Pfeifer (incomplete). 2052 2053 20090502 2054 + continue integrating "sp-funcs" by Juergen Pfeifer (incomplete). 2055 + add vwmterm terminfo entry (patch by Bryan Christ). 2056 2057 20090425 2058 + continue integrating "sp-funcs" by Juergen Pfeifer (incomplete). 2059 2060 20090419 2061 + build fix for _nc_free_and_exit() change in 20090418 (report by 2062 Christian Ebert). 2063 2064 20090418 2065 + continue integrating "sp-funcs" by Juergen Pfeifer (incomplete). 2066 2067 20090411 2068 + continue integrating "sp-funcs" by Juergen Pfeifer (incomplete). 2069 This change finishes merging for menu and panel libraries, does 2070 part of the form library. 2071 2072 20090404 2073 + suppress configure check for static/dynamic linker flags for gcc on 2074 Darwin (report by Nelson Beebe). 2075 2076 20090328 2077 + extend ansi.sys pfkey capability from kf1-kf10 to kf1-kf48, moving 2078 function key definitions from emx-base for consistency -TD 2079 + correct missing final 'p' in pfkey capability of ansi.sys-old (report 2080 by Kalle Olavi Niemitalo). 2081 + improve test/ncurses.c 'F' test, show combining characters in color. 2082 + quiet a false report by cppcheck in c++/cursesw.cc by eliminating 2083 a temporary variable. 2084 + use _nc_doalloc() rather than realloc() in a few places in ncurses 2085 library to avoid leak in out-of-memory condition (reports by William 2086 Egert and Martin Ettl based on cppcheck tool). 2087 + add --with-ncurses-wrap-prefix option to test/configure (discussion 2088 with Charles Wilson). 2089 + use ncurses*-config scripts if available for test/configure. 2090 + update test/aclocal.m4 and test/configure 2091 > patches by Charles Wilson: 2092 + modify CF_WITH_LIBTOOL configure check to allow unreleased libtool 2093 version numbers (e.g. which include alphabetic chars, as well as 2094 digits, after the final '.'). 2095 + improve use of -no-undefined option for libtool by setting an 2096 intermediate variable LT_UNDEF in the configure script, and then 2097 using that in the libtool link-commands. 2098 + fix an missing use of NCURSES_PUBLIC_VAR() in tinfo/MKcodes.awk 2099 from 2009031 changes. 2100 + improve mk-1st.awk script by writing separate cases for the 2101 LIBTOOL_LINK command, depending on which library (ncurses, ticlib, 2102 termlib) is to be linked. 2103 + modify configure.in to allow broken-linker configurations, not just 2104 enable-reentrant, to set public wrap prefix. 2105 2106 20090321 2107 + add TICS_LIST and SHLIB_LIST to allow libtool 2.2.6 on Cygwin to 2108 build with tic and term libraries (patch by Charles Wilson). 2109 + add -no-undefined option to libtool for Cygwin, MinGW, U/Win and AIX 2110 (report by Charles Wilson). 2111 + fix definition for c++/Makefile.in's SHLIB_LIST, which did not list 2112 the form, menu or panel libraries (patch by Charles Wilson). 2113 + add configure option --with-wrap-prefix to allow setting the prefix 2114 for functions used to wrap global variables to something other than 2115 "_nc_" (discussion with Charles Wilson). 2116 2117 20090314 2118 + modify scripts to generate ncurses*-config and pc-files to add 2119 dependency for tinfo library (patch by Charles Wilson). 2120 + improve comparison of program-names when checking for linked flavors 2121 such as "reset" by ignoring the executable suffix (reports by Charles 2122 Wilson, Samuel Thibault and Cedric Bretaudeau on Cygwin mailing 2123 list). 2124 + suppress configure check for static/dynamic linker flags for gcc on 2125 Solaris 10, since gcc is confused by absence of static libc, and 2126 does not switch back to dynamic mode before finishing the libraries 2127 (reports by Joel Bertrand, Alan Pae). 2128 + minor fixes to Intel compiler warning checks in configure script. 2129 + modify _nc_leaks_tinfo() so leak-checking in test/railroad.c works. 2130 + modify set_curterm() to make broken-linker configuration work with 2131 changes from 20090228 (report by Charles Wilson). 2132 2133 20090228 2134 + continue integrating "sp-funcs" by Juergen Pfeifer (incomplete). 2135 + modify declaration of cur_term when broken-linker is used, but 2136 enable-reentrant is not, to match pre-5.7 (report by Charles Wilson). 2137 2138 20090221 2139 + continue integrating "sp-funcs" by Juergen Pfeifer (incomplete). 2140 2141 20090214 2142 + add configure script --enable-sp-funcs to enable the new set of 2143 extended functions. 2144 + start integrating patches by Juergen Pfeifer: 2145 + add extended functions which specify the SCREEN pointer for several 2146 curses functions which use the global SP (these are incomplete; 2147 some internals work is needed to complete these). 2148 + add special cases to configure script for MinGW port. 2149 2150 20090207 2151 + update several configure macros from lynx changes 2152 + append (not prepend) to CFLAGS/CPPFLAGS 2153 + change variable from PATHSEP to PATH_SEPARATOR 2154 + improve install-rules for pc-files (patch by Miroslav Lichvar). 2155 + make it work with $DESTDIR 2156 + create the pkg-config library directory if needed. 2157 2158 20090124 2159 + modify init_pair() to allow caller to create extra color pairs beyond 2160 the color_pairs limit, which use default colors (request by Emanuele 2161 Giaquinta). 2162 + add misc/terminfo.tmp and misc/*.pc to "sources" rule. 2163 + fix typo "==" where "=" is needed in ncurses-config.in and 2164 gen-pkgconfig.in files (Debian #512161). 2165 2166 20090117 2167 + add -shared option to MK_SHARED_LIB when -Bsharable is used, for 2168 *BSD's, without which "main" might be one of the shared library's 2169 dependencies (report/analysis by Ken Dickey). 2170 + modify waddch_literal(), updating line-pointer after a multicolumn 2171 character is found to not fit on the current row, and wrapping is 2172 done. Since the line-pointer was not updated, the wrapped 2173 multicolumn character was written to the beginning of the current row 2174 (cf: 20041023, reported by "Nick" regarding problem with ncmpc 2175). 2176 2177 20090110 2178 + add screen.Eterm terminfo entry (GenToo #124887) -TD 2179 + modify adacurses-config to look for ".ali" files in the adalib 2180 directory. 2181 + correct install for Ada95, which omitted libAdaCurses.a used in 2182 adacurses-config 2183 + change install for adacurses-config to provide additional flavors 2184 such as adacursesw-config, for ncursesw (GenToo #167849). 2185 2186 20090105 2187 + remove undeveloped feature in ncurses-config.in for setting 2188 prefix variable. 2189 + recent change to ncurses-config.in did not take into account the 2190 --disable-overwrite option, which sets $includedir to the 2191 subdirectory and using just that for a -I option does not work - fix 2192 (report by Frederic L W Meunier). 2193 2194 20090104 2195 + modify gen-pkgconfig.in to eliminate a dependency on rpath when 2196 deciding whether to add $LIBS to --libs output; that should be shown 2197 for the ncurses and tinfo libraries without taking rpath into 2198 account. 2199 + fix an overlooked change from $AR_OPTS to $ARFLAGS in mk-1st.awk, 2200 used in static libraries (report by Marty Jack). 2201 2202 20090103 2203 + add a configure-time check to pick a suitable value for 2204 CC_SHARED_OPTS for Solaris (report by Dagobert Michelsen). 2205 + add configure --with-pkg-config and --enable-pc-files options, along 2206 with misc/gen-pkgconfig.in which can be used to generate ".pc" files 2207 for pkg-config (request by Jan Engelhardt). 2208 + use $includedir symbol in misc/ncurses-config.in, add --includedir 2209 option. 2210 + change makefiles to use $ARFLAGS rather than $AR_OPTS, provide a 2211 configure check to detect whether a "-" is needed before "ar" 2212 options. 2213 + update config.guess, config.sub from 2214 2215 2216 20081227 2217 + modify mk-1st.awk to work with extra categories for tinfo library. 2218 + modify configure script to allow building shared libraries with gcc 2219 on AIX 5 or 6 (adapted from patch by Lital Natan). 2220 2221 20081220 2222 + modify to omit the opaque-functions from lib_gen.o when 2223 --disable-ext-funcs is used. 2224 + add test/clip_printw.c to illustrate how to use printw without 2225 wrapping. 2226 + modify ncurses 'F' test to demo wborder_set() with colored lines. 2227 + modify ncurses 'f' test to demo wborder() with colored lines. 2228 2229 20081213 2230 + add check for failure to open hashed-database needed for db4.6 2231 (GenToo #245370). 2232 + corrected --without-manpages option; previous change only suppressed 2233 the auxiliary rules install.man and uninstall.man 2234 + add case for FreeMINT to configure macro CF_XOPEN_SOURCE (patch from 2235 GenToo #250454). 2236 + fixes from NetBSD port at 2237 2238 patch-ac (build-fix for DragonFly) 2239 patch-ae (use INSTALL_SCRIPT for installing misc/ncurses*-config). 2240 + improve configure script macros CF_HEADER_PATH and CF_LIBRARY_PATH 2241 by adding CFLAGS, CPPFLAGS and LDFLAGS, LIBS values to the 2242 search-lists. 2243 + correct title string for keybound manpage (patch by Frederic Culot, 2244 OpenBSD documentation/6019), 2245 2246 20081206 2247 + move del_curterm() call from _nc_freeall() to _nc_leaks_tinfo() to 2248 work for progs/clear, progs/tabs, etc. 2249 + correct buffer-size after internal resizing of wide-character 2250 set_field_buffer(), broken in 20081018 changes (report by Mike Gran). 2251 + add "-i" option to test/filter.c to tell it to use initscr() rather 2252 than newterm(), to investigate report on comp.unix.programmer that 2253 ncurses would clear the screen in that case (it does not - the issue 2254 was xterm's alternate screen feature). 2255 + add check in mouse-driver to disable connection if GPM returns a 2256 zero, indicating that the connection is closed (Debian #506717, 2257 adapted from patch by Samuel Thibault). 2258 2259 20081129 2260 + improve a workaround in adding wide-characters, when a control 2261 character is found. The library (cf: 20040207) uses unctrl() to 2262 obtain a printable version of the control character, but was not 2263 passing color or video attributes. 2264 + improve test/ncurses.c 'a' test, using unctrl() more consistently to 2265 display meta-characters. 2266 + turn on _XOPEN_CURSES definition in curses.h 2267 + add eterm-color entry (report by Vincent Lefevre) -TD 2268 + correct use of key_name() in test/ncurses.c 'A' test, which only 2269 displays wide-characters, not key-codes since 20070612 (report by 2270 Ricardo Cantu). 2271 2272 20081122 2273 + change _nc_has_mouse() to has_mouse(), reflect its use in C++ and 2274 Ada95 (patch by Juergen Pfeifer). 2275 + document in TO-DO an issue with Cygwin's package for GNAT (report 2276 by Mike Dennison). 2277 + improve error-checking of command-line options in "tabs" program. 2278 2279 20081115 2280 + change several terminfo entries to make consistent use of ANSI 2281 clear-all-tabs -TD 2282 + add "tabs" program (prompted by Debian #502260). 2283 + add configure --without-manpages option (request by Mike Frysinger). 2284 2285 20081102 5.7 release for upload to 2286 2287 20081025 2288 + add a manpage to discuss memory leaks. 2289 + add support for shared libraries for QNX (other than libtool, which 2290 does not work well on that platform). 2291 + build-fix for QNX C++ binding. 2292 2293 20081018 2294 + build-fixes for OS/2 EMX. 2295 + modify form library to accept control characters such as newline 2296 in set_field_buffer(), which is compatible with Solaris (report by 2297 Nit Khair). 2298 + modify configure script to assume --without-hashed-db when 2299 --disable-database is used. 2300 + add "-e" option in ncurses/Makefile.in when generating source-files 2301 to force earlier exit if the build environment fails unexpectedly 2302 (prompted by patch by Adrian Bunk). 2303 + change configure script to use CF_UTF8_LIB, improved variant of 2304 CF_LIBUTF8. 2305 2306 20081012 2307 + add teraterm4.59 terminfo entry, use that as primary teraterm entry, rename 2308 original to teraterm2.3 -TD 2309 + update "gnome" terminfo to 2.22.3 -TD 2310 + update "konsole" terminfo to 1.6.6, needs today's fix for tic -TD 2311 + add "aterm" terminfo -TD 2312 + add "linux2.6.26" terminfo -TD 2313 + add logic to tic for cancelling strings in user-defined capabilities, 2314 overlooked til now. 2315 2316 20081011 2317 + regenerated html documentation. 2318 + add -m and -s options to test/keynames.c and test/key_names.c to test 2319 the meta() function with keyname() or key_name(), respectively. 2320 + correct return value of key_name() on error; it is null. 2321 + document some unresolved issues for rpath and pthreads in TO-DO. 2322 + fix a missing prototype for ioctl() on OpenBSD in tset.c 2323 + add configure option --disable-tic-depends to make explicit whether 2324 tic library depends on ncurses/ncursesw library, amends change from 2325 20080823 (prompted by Debian #501421). 2326 2327 20081004 2328 + some build-fixes for configure --disable-ext-funcs (incomplete, but 2329 works for C/C++ parts). 2330 + improve configure-check for awks unable to handle large strings, e.g. 2331 AIX 5.1 whose awk silently gives up on large printf's. 2332 2333 20080927 2334 + fix build for --with-dmalloc by workaround for redefinition of 2335 strndup between string.h and dmalloc.h 2336 + fix build for --disable-sigwinch 2337 + add environment variable NCURSES_GPM_TERMS to allow override to use 2338 GPM on terminals other than "linux", etc. 2339 + disable GPM mouse support when $TERM does not happen to contain 2340 "linux", since Gpm_Open() no longer limits its assertion to terminals 2341 that it might handle, e.g., within "screen" in xterm. 2342 + reset mouse file-descriptor when unloading GPM library (report by 2343 Miroslav Lichvar). 2344 + fix build for --disable-leaks --enable-widec --with-termlib 2345 > patch by Juergen Pfeifer: 2346 + use improved initialization for soft-label keys in Ada95 sample code. 2347 + discard internal symbol _nc_slk_format (unused since 20080112). 2348 + move call of slk_paint_info() from _nc_slk_initialize() to 2349 slk_intern_refresh(), improving initialization. 2350 2351 20080925 2352 + fix bug in mouse code for GPM from 20080920 changes (reported in 2353 Debian #500103, also Miroslav Lichvar). 2354 2355 20080920 2356 + fix shared-library rules for cygwin with tic- and tinfo-libraries. 2357 + fix a memory leak when failure to connect to GPM. 2358 + correct check for notimeout() in wgetch() (report on linux.redhat 2359 newsgroup by FurtiveBertie). 2360 + add an example warning-suppression file for valgrind, 2361 misc/ncurses.supp (based on example from Reuben Thomas) 2362 2363 20080913 2364 + change shared-library configuration for OpenBSD, make rpath work. 2365 + build-fixes for using libutf8, e.g., on OpenBSD 3.7 2366 2367 20080907 2368 + corrected fix for --enable-weak-symbols (report by Frederic L W 2369 Meunier). 2370 2371 20080906 2372 + corrected gcc options for building shared libraries on IRIX64. 2373 + add configure check for awk programs unable to handle big-strings, 2374 use that to improve the default for --enable-big-strings option. 2375 + makefile-fixes for --enable-weak-symbols (report by Frederic L W 2376 Meunier). 2377 + update test/configure script. 2378 + adapt ifdef's from library to make test/view.c build when mbrtowc() 2379 is unavailable, e.g., with HPUX 10.20. 2380 + add configure check for wcsrtombs, mbsrtowcs, which are used in 2381 test/ncurses.c, and use wcstombs, mbstowcs instead if available, 2382 fixing build of ncursew for HPUX 11.00 2383 2384 20080830 2385 + fixes to make Ada95 demo_panels() example work. 2386 + modify Ada95 'rain' test program to accept keyboard commands like the 2387 C-version. 2388 + modify BeOS-specific ifdef's to build on Haiku (patch by Scott 2389 Mccreary). 2390 + add configure-check to see if the std namespace is legal for cerr 2391 and endl, to fix a build issue with Tru64. 2392 + consistently use NCURSES_BOOL in lib_gen.c 2393 + filter #line's from lib_gen.c 2394 + change delimiter in MKlib_gen.sh from '%' to '@', to avoid 2395 substitution by IBM xlc to '#' as part of its extensions to digraphs. 2396 + update config.guess, config.sub from 2397 2398 (caveat - its maintainer removed support for older Linux systems). 2399 2400 20080823 2401 + modify configure check for pthread library to work with OSF/1 5.1, 2402 which uses #define's to associate its header and library. 2403 + use pthread_mutexattr_init() for initializing pthread_mutexattr_t, 2404 makes threaded code work on HPUX 11.23 2405 + fix a bug in demo_menus in freeing menus (cf: 20080804). 2406 + modify configure script for the case where tic library is used (and 2407 possibly renamed) to remove its dependency upon ncurses/ncursew 2408 library (patch by Dr Werner Fink). 2409 + correct manpage for menu_fore() which gave wrong default for 2410 the attribute used to display a selected entry (report by Mike Gran). 2411 + add Eterm-256color, Eterm-88color and rxvt-88color (prompted by 2412 Debian #495815) -TD 2413 2414 20080816 2415 + add configure option --enable-weak-symbols to turn on new feature. 2416 + add configure-check for availability of weak symbols. 2417 + modify linkage with pthread library to use weak symbols so that 2418 applications not linked to that library will not use the mutexes, 2419 etc. This relies on gcc, and may be platform-specific (patch by Dr 2420 Werner Fink). 2421 + add note to INSTALL to document limitation of renaming of tic library 2422 using the --with-ticlib configure option (report by Dr Werner Fink). 2423 + document (in manpage) why tputs does not detect I/O errors (prompted 2424 by comments by Samuel Thibault). 2425 + fix remaining warnings from Klocwork report. 2426 2427 20080804 2428 + modify _nc_panelhook() data to account for a permanent memory leak. 2429 + fix memory leaks in test/demo_menus 2430 + fix most warnings from Klocwork tool (report by Larry Zhou). 2431 + modify configure script CF_XOPEN_SOURCE macro to add case for 2432 "dragonfly" from xterm #236 changes. 2433 + modify configure script --with-hashed-db to let $LIBS override the 2434 search for the db library (prompted by report by Samson Pierre). 2435 2436 20080726 2437 + build-fixes for gcc 4.3.1 (changes to gnat "warnings", and C inlining 2438 thresholds). 2439 2440 20080713 2441 + build-fix (reports by Christian Ebert, Funda Wang). 2442 2443 20080712 2444 + compiler-warning fixes for Solaris. 2445 2446 20080705 2447 + use NCURSES_MOUSE_MASK() in definition of BUTTON_RELEASE(), etc., to 2448 make those work properly with the "--enable-ext-mouse" configuration 2449 (cf: 20050205). 2450 + improve documentation of build-cc options in INSTALL. 2451 + work-around a bug in gcc 4.2.4 on AIX, which does not pass the 2452 -static/-dynamic flags properly to linker, causing test/bs to 2453 not link. 2454 2455 20080628 2456 + correct some ifdef's needed for the broken-linker configuration. 2457 + make debugging library's $BAUDRATE feature work for termcap 2458 interface. 2459 + make $NCURSES_NO_PADDING feature work for termcap interface (prompted 2460 by comment on FreeBSD mailing list). 2461 + add screen.mlterm terminfo entry -TD 2462 + improve mlterm and mlterm+pcfkeys terminfo entries -TD 2463 2464 20080621 2465 + regenerated html documentation. 2466 + expand manpage description of parameters for form_driver() and 2467 menu_driver() (prompted by discussion with Adam Spragg). 2468 + add null-pointer checks for cur_term in baudrate() and 2469 def_shell_mode(), def_prog_mode() 2470 + fix some memory leaks in delscreen() and wide acs. 2471 2472 20080614 2473 + modify test/ditto.c to illustrate multi-threaded use_screen(). 2474 + change CC_SHARED_OPTS from -KPIC to -xcode=pic32 for Solaris. 2475 + add "-shared" option to MK_SHARED_LIB for gcc on Solaris (report 2476 by Poor Yorick). 2477 2478 20080607 2479 + finish changes to wgetch(), making it switch as needed to the 2480 window's actual screen when calling wrefresh() and wgetnstr(). That 2481 allows wgetch() to get used concurrently in different threads with 2482 some minor restrictions, e.g., the application should not delete a 2483 window which is being used in a wgetch(). 2484 + simplify mutex's, combining the window- and screen-mutex's. 2485 2486 20080531 2487 + modify wgetch() to use the screen which corresponds to its window 2488 parameter rather than relying on SP; some dependent functions still 2489 use SP internally. 2490 + factor out most use of SP in lib_mouse.c, using parameter. 2491 + add internal _nc_keyname(), replacing keyname() to associate with a 2492 particular SCREEN rather than the global SP. 2493 + add internal _nc_unctrl(), replacing unctrl() to associate with a 2494 particular SCREEN rather than the global SP. 2495 + add internal _nc_tracemouse(), replacing _tracemouse() to eliminate 2496 its associated global buffer _nc_globals.tracemse_buf now in SCREEN. 2497 + add internal _nc_tracechar(), replacing _tracechar() to use SCREEN in 2498 preference to the global _nc_globals.tracechr_buf buffer. 2499 2500 20080524 2501 + modify _nc_keypad() to make it switch temporarily as needed to the 2502 screen which must be updated. 2503 + wrap cur_term variable to help make _nc_keymap() thread-safe, and 2504 always set the screen's copy of this variable in set_curterm(). 2505 + restore curs_set() state after endwin()/refresh() (report/patch 2506 Miroslav Lichvar) 2507 2508 20080517 2509 + modify configure script to note that --enable-ext-colors and 2510 --enable-ext-mouse are not experimental, but extensions from 2511 the ncurses ABI 5. 2512 + corrected manpage description of setcchar() (discussion with 2513 Emanuele Giaquinta). 2514 + fix for adding a non-spacing character at the beginning of a line 2515 (report/patch by Miroslav Lichvar). 2516 2517 20080503 2518 + modify screen.* terminfo entries using new screen+fkeys to fix 2519 overridden keys in screen.rxvt (Debian #478094) -TD 2520 + modify internal interfaces to reduce wgetch()'s dependency on the 2521 global SP. 2522 + simplify some loops with macros each_screen(), each_window() and 2523 each_ripoff(). 2524 2525 20080426 2526 + continue modifying test/ditto.c toward making it demonstrate 2527 multithreaded use_screen(), using fifos to pass data between screens. 2528 + fix typo in form.3x (report by Mike Gran). 2529 2530 20080419 2531 + add screen.rxvt terminfo entry -TD 2532 + modify tic -f option to format spaces as \s to prevent them from 2533 being lost when that is read back in unformatted strings. 2534 + improve test/ditto.c, using a "talk"-style layout. 2535 2536 20080412 2537 + change test/ditto.c to use openpty() and xterm. 2538 + add locks for copywin(), dupwin(), overlap(), overlay() on their 2539 window parameters. 2540 + add locks for initscr() and newterm() on updates to the SCREEN 2541 pointer. 2542 + finish table in curs_thread.3x manpage. 2543 2544 20080405 2545 + begin table in curs_thread.3x manpage describing the scope of data 2546 used by each function (or symbol) for threading analysis. 2547 + add null-pointer checks to setsyx() and getsyx() (prompted by 2548 discussion by Martin v. Lowis and Jeroen Ruigrok van der Werven on 2549 python-dev2 mailing list). 2550 2551 20080329 2552 + add null-pointer checks in set_term() and delscreen(). 2553 + move _nc_windows into _nc_globals, since windows can be pads, which 2554 are not associated with a particular screen. 2555 + change use_screen() to pass the SCREEN* parameter rather than 2556 stdscr to the callback function. 2557 + force libtool to use tag for 'CC' in case it does not detect this, 2558 e.g., on aix when using CC=powerpc-ibm-aix5.3.0.0-gcc 2559 (report/patch by Michael Haubenwallner). 2560 + override OBJEXT to "lo" when building with libtool, to work on 2561 platforms such as AIX where libtool may use a different suffix for 2562 the object files than ".o" (report/patch by Michael Haubenwallner). 2563 + add configure --with-pthread option, for building with the POSIX 2564 thread library. 2565 2566 20080322 2567 + fill in extended-color pair two more places in wbkgrndset() and 2568 waddch_nosync() (prompted by Sedeno's patch). 2569 + fill in extended-color pair in _nc_build_wch() to make colors work 2570 for wide-characters using extended-colors (patch by Alejandro R 2571 Sedeno). 2572 + add x/X toggles to ncurses.c C color test to test/demo 2573 wide-characters with extended-colors. 2574 + add a/A toggles to ncurses.c c/C color tests. 2575 + modify test/ditto.c to use use_screen(). 2576 + finish modifying test/rain.c to demonstrate threads. 2577 2578 20080308 2579 + start modifying test/rain.c for threading demo. 2580 + modify test/ncurses.c to make 'f' test accept the f/F/b/F/</> toggles 2581 that the 'F' accepts. 2582 + modify test/worm.c to show trail in reverse-video when other threads 2583 are working concurrently. 2584 + fix a deadlock from improper nesting of mutexes for windowlist and 2585 window. 2586 2587 20080301 2588 + fixes from 20080223 resolved issue with mutexes; change to use 2589 recursive mutexes to fix memory leak in delwin() as called from 2590 _nc_free_and_exit(). 2591 2592 20080223 2593 + fix a size-difference in _nc_globals which caused hanging of mutex 2594 lock/unlock when termlib was built separately. 2595 2596 20080216 2597 + avoid using nanosleep() in threaded configuration since that often 2598 is implemented to suspend the entire process. 2599 2600 20080209 2601 + update test programs to build/work with various UNIX curses for 2602 comparisons. This was to reinvestigate statement in X/Open curses 2603 that insnstr and winsnstr perform wrapping. None of the Unix-branded 2604 implementations do this, as noted in manpage (cf: 20040228). 2605 2606 20080203 2607 + modify _nc_setupscreen() to set the legacy-coding value the same 2608 for both narrow/wide models. It had been set only for wide model, 2609 but is needed to make unctrl() work with locale in the narrow model. 2610 + improve waddch() and winsch() handling of EILSEQ from mbrtowc() by 2611 using unctrl() to display illegal bytes rather than trying to append 2612 further bytes to make up a valid sequence (reported by Andrey A 2613 Chernov). 2614 + modify unctrl() to check codes in 128-255 range versus isprint(). 2615 If they are not printable, and locale was set, use a "M-" or "~" 2616 sequence. 2617 2618 20080126 2619 + improve threading in test/worm.c (wrap refresh calls, and KEY_RESIZE 2620 handling). Now it hangs in napms(), no matter whether nanosleep() 2621 or poll() or select() are used on Linux. 2622 2623 20080119 2624 + fixes to build with --disable-ext-funcs 2625 + add manpage for use_window and use_screen. 2626 + add set_tabsize() and set_escdelay() functions. 2627 2628 20080112 2629 + remove recursive-mutex definitions, finish threading demo for worm.c 2630 + remove a redundant adjustment of lines in resizeterm.c's 2631 adjust_window() which caused occasional misadjustment of stdscr when 2632 softkeys were used. 2633 2634 20080105 2635 + several improvements to terminfo entries based on xterm #230 -TD 2636 + modify MKlib_gen.sh to handle keyname/key_name prototypes, so the 2637 "link_test" builds properly. 2638 + fix for toe command-line options -u/-U to ensure filename is given. 2639 + fix allocation-size for command-line parsing in infocmp from 20070728 2640 (report by Miroslav Lichvar) 2641 + improve resizeterm() by moving ripped-off lines, and repainting the 2642 soft-keys (report by Katarina Machalkova) 2643 + add clarification in wclear's manpage noting that the screen will be 2644 cleared even if a subwindow is cleared (prompted by Christer Enfors 2645 question). 2646 + change test/ncurses.c soft-key tests to work with KEY_RESIZE. 2647 2648 20071222 2649 + continue implementing support for threading demo by adding mutex 2650 for delwin(). 2651 2652 20071215 2653 + add several functions to C++ binding which wrap C functions that 2654 pass a WINDOW* parameter (request by Chris Lee). 2655 2656 20071201 2657 + add note about configure options needed for Berkeley database to the 2658 INSTALL file. 2659 + improve checks for version of Berkeley database libraries. 2660 + amend fix for rpath to not modify LDFLAGS if the platform has no 2661 applicable transformation (report by Christian Ebert, cf: 20071124). 2662 2663 20071124 2664 + modify configure option --with-hashed-db to accept a parameter which 2665 is the install-prefix of a given Berkeley Database (prompted by 2666 pierre4d2 comments). 2667 + rewrite wrapper for wcrtomb(), making it work on Solaris. This is 2668 used in the form library to determine the length of the buffer needed 2669 by field_buffer (report by Alfred Fung). 2670 + remove unneeded window-parameter from C++ binding for wresize (report 2671 by Chris Lee). 2672 2673 20071117 2674 + modify the support for filesystems which do not support mixed-case to 2675 generate 2-character (hexadecimal) codes for the lower-level of the 2676 filesystem terminfo database (request by Michail Vidiassov). 2677 + add configure option --enable-mixed-case, to allow overriding the 2678 configure script's check if the filesystem supports mixed-case 2679 filenames. 2680 + add wresize() to C++ binding (request by Chris Lee). 2681 + define NCURSES_EXT_FUNCS and NCURSES_EXT_COLORS in curses.h to make 2682 it simpler to tell if the extended functions and/or colors are 2683 declared. 2684 2685 20071103 2686 + update memory-leak checks for changes to names.c and codes.c 2687 + correct acsc strings in h19, z100 (patch by Benjamin C W Sittler). 2688 2689 20071020 2690 + continue implementing support for threading demo by adding mutex 2691 for use_window(). 2692 + add mrxvt terminfo entry, add/fix xterm building blocks for modified 2693 cursor keys -TD 2694 + compile with FreeBSD "contemporary" TTY interface (patch by 2695 Rong-En Fan). 2696 2697 20071013 2698 + modify makefile rules to allow clear, tput and tset to be built 2699 without libtic. The other programs (infocmp, tic and toe) rely on 2700 that library. 2701 + add/modify null-pointer checks in several functions for SP and/or 2702 the WINDOW* parameter (report by Thorben Krueger). 2703 + fixes for field_buffer() in formw library (see Redhat #310071, 2704 patches by Miroslav Lichvar). 2705 + improve performance of NCURSES_CHAR_EQ code (patch by Miroslav 2706 Lichvar). 2707 + update/improve mlterm and rxvt terminfo entries, e.g., for 2708 the modified cursor- and keypad-keys -TD 2709 2710 20071006 2711 + add code to curses.priv.h ifdef'd with NCURSES_CHAR_EQ, which 2712 changes the CharEq() macro to an inline function to allow comparing 2713 cchar_t struct's without comparing gaps in a possibly unpacked 2714 memory layout (report by Miroslav Lichvar). 2715 2716 20070929 2717 + add new functions to lib_trace.c to setup mutex's for the _tracef() 2718 calls within the ncurses library. 2719 + for the reentrant model, move _nc_tputs_trace and _nc_outchars into 2720 the SCREEN. 2721 + start modifying test/worm.c to provide threading demo (incomplete). 2722 + separated ifdef's for some BSD-related symbols in tset.c, to make 2723 it compile on LynxOS (report by Greg Gemmer). 2724 20070915 2725 + modify Ada95/gen/Makefile to use shlib script, to simplify building 2726 shared-library configuration on platforms lacking rpath support. 2727 + build-fix for Ada95/src/Makefile to reflect changed dependency for 2728 the terminal-interface-curses-aux.adb file which is now generated. 2729 + restructuring test/worm.c, for use_window() example. 2730 2731 20070908 2732 + add use_window() and use_screen() functions, to develop into support 2733 for threaded library (incomplete). 2734 + fix typos in man/curs_opaque.3x which kept the install script from 2735 creating symbolic links to two aliases created in 20070818 (report by 2736 Rong-En Fan). 2737 2738 20070901 2739 + remove a spurious newline from output of html.m4, which caused links 2740 for Ada95 html to be incorrect for the files generated using m4. 2741 + start investigating mutex's for SCREEN manipulation (incomplete). 2742 + minor cleanup of codes.c/names.c for --enable-const 2743 + expand/revise "Routine and Argument Names" section of ncurses manpage 2744 to address report by David Givens in newsgroup discussion. 2745 + fix interaction between --without-progs/--with-termcap configure 2746 options (report by Michail Vidiassov). 2747 + fix typo in "--disable-relink" option (report by Michail Vidiassov). 2748 2749 20070825 2750 + fix a sign-extension bug in infocmp's repair_acsc() function 2751 (cf: 971004). 2752 + fix old configure script bug which prevented "--disable-warnings" 2753 option from working (patch by Mike Frysinger). 2754 2755 20070818 2756 + add 9term terminal description (request by Juhapekka Tolvanen) -TD 2757 + modify comp_hash.c's string output to avoid misinterpreting a null 2758 "\0" followed by a digit. 2759 + modify MKnames.awk and MKcodes.awk to support big-strings. 2760 This only applies to the cases (broken linker, reentrant) where 2761 the corresponding arrays are accessed via wrapper functions. 2762 + split MKnames.awk into two scripts, eliminating the shell redirection 2763 which complicated the make process and also the bogus timestamp file 2764 which was introduced to fix "make -j". 2765 + add test/test_opaque.c, test/test_arrays.c 2766 + add wgetscrreg() and wgetparent() for applications that may need it 2767 when NCURSES_OPAQUE is defined (prompted by Bryan Christ). 2768 2769 20070812 2770 + amend treatment of infocmp "-r" option to retain the 1023-byte limit 2771 unless "-T" is given (cf: 981017). 2772 + modify comp_captab.c generation to use big-strings. 2773 + make _nc_capalias_table and _nc_infoalias_table private accessed via 2774 _nc_get_alias_table() since the tables are used only within the tic 2775 library. 2776 + modify configure script to skip Intel compiler in CF_C_INLINE. 2777 + make _nc_info_hash_table and _nc_cap_hash_table private accessed via 2778 _nc_get_hash_table() since the tables are used only within the tic 2779 library. 2780 2781 20070728 2782 + make _nc_capalias_table and _nc_infoalias_table private, accessed via 2783 _nc_get_alias_table() since they are used only by parse_entry.c 2784 + make _nc_key_names private since it is used only by lib_keyname.c 2785 + add --disable-big-strings configure option to control whether 2786 unctrl.c is generated using the big-string optimization - which may 2787 use strings longer than supported by a given compiler. 2788 + reduce relocation tables for tic, infocmp by changing type of 2789 internal hash tables to short, and make those private symbols. 2790 + eliminate large fixed arrays from progs/infocmp.c 2791 2792 20070721 2793 + change winnstr() to stop at the end of the line (cf: 970315). 2794 + add test/test_get_wstr.c 2795 + add test/test_getstr.c 2796 + add test/test_inwstr.c 2797 + add test/test_instr.c 2798 2799 20070716 2800 + restore a call to obtain screen-size in _nc_setupterm(), which 2801 is used in tput and other non-screen applications via setupterm() 2802 (Debian #433357, reported by Florent Bayle, Christian Ohm, 2803 cf: 20070310). 2804 2805 20070714 2806 + add test/savescreen.c test-program 2807 + add check to trace-file open, if the given name is a directory, add 2808 ".log" to the name and try again. 2809 + add konsole-256color entry -TD 2810 + add extra gcc warning options from xterm. 2811 + minor fixes for ncurses/hashmap test-program. 2812 + modify configure script to quiet c++ build with libtool when the 2813 --disable-echo option is used. 2814 + modify configure script to disable ada95 if libtool is selected, 2815 writing a warning message (addresses FreeBSD #114493). 2816 + update config.guess, config.sub 2817 2818 20070707 2819 + add continuous-move "M" to demo_panels to help test refresh changes. 2820 + improve fix for refresh of window on top of multi-column characters, 2821 taking into account some split characters on left/right window 2822 boundaries. 2823 2824 20070630 2825 + add "widec" row to _tracedump() output to help diagnose remaining 2826 problems with multi-column characters. 2827 + partial fix for refresh of window on top of multi-column characters 2828 which are partly overwritten (report by Sadrul H Chowdhury). 2829 + ignore A_CHARTEXT bits in vidattr() and vid_attr(), in case 2830 multi-column extension bits are passed there. 2831 + add setlocale() call to demo_panels.c, needed for wide-characters. 2832 + add some output flags to _nc_trace_ttymode to help diagnose a bug 2833 report by Larry Virden, i.e., ONLCR, OCRNL, ONOCR and ONLRET, 2834 2835 20070623 2836 + add test/demo_panels.c 2837 + implement opaque version of setsyx() and getsyx(). 2838 2839 20070612 2840 + corrected xterm+pcf2 terminfo modifiers for F1-F4, to match xterm 2841 #226 -TD 2842 + split-out key_name() from MKkeyname.awk since it now depends upon 2843 wunctrl() which is not in libtinfo (report by Rong-En Fan). 2844 2845 20070609 2846 + add test/key_name.c 2847 + add stdscr cases to test/inchs.c and test/inch_wide.c 2848 + update test/configure 2849 + correct formatting of DEL (0x7f) in _nc_vischar(). 2850 + null-terminate result of wunctrl(). 2851 + add null-pointer check in key_name() (report by Andreas Krennmair, 2852 cf: 20020901). 2853 2854 20070602 2855 + adapt mouse-handling code from menu library in form-library 2856 (discussion with Clive Nicolson). 2857 + add a modification of test/dots.c, i.e., test/dots_mvcur.c to 2858 illustrate how to use mvcur(). 2859 + modify wide-character flavor of SetAttr() to preserve the 2860 WidecExt() value stored in the .attr field, e.g., in case it 2861 is overwritten by chgat (report by Aleksi Torhamo). 2862 + correct buffer-size for _nc_viswbuf2n() (report by Aleksi Torhamo). 2863 + build-fixes for Solaris 2.6 and 2.7 (patch by Peter O'Gorman). 2864 2865 20070526 2866 + modify keyname() to use "^X" form only if meta() has been called, or 2867 if keyname() is called without initializing curses, e.g., via 2868 initscr() or newterm() (prompted by LinuxBase #1604). 2869 + document some portability issues in man/curs_util.3x 2870 + add a shadow copy of TTY buffer to _nc_prescreen to fix applications 2871 broken by moving that data into SCREEN (cf: 20061230). 2872 2873 20070512 2874 + add 'O' (wide-character panel test) in ncurses.c to demonstrate a 2875 problem reported by Sadrul H Chowdhury with repainting parts of 2876 a fullwidth cell. 2877 + modify slk_init() so that if there are preceding calls to 2878 ripoffline(), those affect the available lines for soft-keys (adapted 2879 from patch by Clive Nicolson). 2880 + document some portability issues in man/curs_getyx.3x 2881 2882 20070505 2883 + fix a bug in Ada95/samples/ncurses which caused a variable to 2884 become uninitialized in the "b" test. 2885 + fix Ada95/gen/Makefile.in adahtml rule to account for recent 2886 movement of files, fix a few incorrect manpage references in the 2887 generated html. 2888 + add Ada95 binding to _nc_freeall() as Curses_Free_All to help with 2889 memory-checking. 2890 + correct some functions in Ada95 binding which were using return value 2891 from C where none was returned: idcok(), immedok() and wtimeout(). 2892 + amend recent changes for Ada95 binding to make it build with 2893 Cygwin's linker, e.g., with configure options 2894 --enable-broken-linker --with-ticlib 2895 2896 20070428 2897 + add a configure check for gcc's options for inlining, use that to 2898 quiet a warning message where gcc's default behavior changed from 2899 3.x to 4.x. 2900 + improve warning message when checking if GPM is linked to curses 2901 library by not warning if its use of "wgetch" is via a weak symbol. 2902 + add loader options when building with static libraries to ensure that 2903 an installed shared library for ncurses does not conflict. This is 2904 reported as problem with Tru64, but could affect other platforms 2905 (report Martin Mokrejs, analysis by Tim Mooney). 2906 + fix build on cygwin after recent ticlib/termlib changes, i.e., 2907 + adjust TINFO_SUFFIX value to work with cygwin's dll naming 2908 + revert a change from 20070303 which commented out dependency of 2909 SHLIB_LIST in form/menu/panel/c++ libraries. 2910 + fix initialization of ripoff stack pointer (cf: 20070421). 2911 2912 20070421 2913 + move most static variables into structures _nc_globals and 2914 _nc_prescreen, to simplify storage. 2915 + add/use configure script macro CF_SIG_ATOMIC_T, use the corresponding 2916 type for data manipulated by signal handlers (prompted by comments 2917 in mailing.openbsd.bugs newsgroup). 2918 + modify CF_WITH_LIBTOOL to allow one to pass options such as -static 2919 to the libtool create- and link-operations. 2920 2921 20070414 2922 + fix whitespace in curs_opaque.3x which caused a spurious ';' in 2923 the installed aliases (report by Peter Santoro). 2924 + fix configure script to not try to generate adacurses-config when 2925 Ada95 tree is not built. 2926 2927 20070407 2928 + add man/curs_legacy.3x, man/curs_opaque.3x 2929 + fix acs_map binding for Ada95 when --enable-reentrant is used. 2930 + add adacurses-config to the Ada95 install, based on version from 2931 FreeBSD port, in turn by Juergen Pfeifer in 2000 (prompted by 2932 comment on comp.lang.ada newsgroup). 2933 + fix includes in c++ binding to build with Intel compiler 2934 (cf: 20061209). 2935 + update install rule in Ada95 to use mkdirs.sh 2936 > other fixes prompted by inspection for Coverity report: 2937 + modify ifdef's for c++ binding to use try/catch/throw statements 2938 + add a null-pointer check in tack/ansi.c request_cfss() 2939 + fix a memory leak in ncurses/base/wresize.c 2940 + corrected check for valid memu/meml capabilities in 2941 progs/dump_entry.c when handling V_HPUX case. 2942 > fixes based on Coverity report: 2943 + remove dead code in test/bs.c 2944 + remove dead code in test/demo_defkey.c 2945 + remove an unused assignment in progs/infocmp.c 2946 + fix a limit check in tack/ansi.c tools_charset() 2947 + fix tack/ansi.c tools_status() to perform the VT320/VT420 2948 tests in request_cfss(). The function had exited too soon. 2949 + fix a memory leak in tic.c's make_namelist() 2950 + fix a couple of places in tack/output.c which did not check for EOF. 2951 + fix a loop-condition in test/bs.c 2952 + add index checks in lib_color.c for color palettes 2953 + add index checks in progs/dump_entry.c for version_filter() handling 2954 of V_BSD case. 2955 + fix a possible null-pointer dereference in copywin() 2956 + fix a possible null-pointer dereference in waddchnstr() 2957 + add a null-pointer check in _nc_expand_try() 2958 + add a null-pointer check in tic.c's make_namelist() 2959 + add a null-pointer check in _nc_expand_try() 2960 + add null-pointer checks in test/cardfile.c 2961 + fix a double-free in ncurses/tinfo/trim_sgr0.c 2962 + fix a double-free in ncurses/base/wresize.c 2963 + add try/catch block to c++/cursesmain.cc 2964 2965 20070331 2966 + modify Ada95 binding to build with --enable-reentrant by wrapping 2967 global variables (bug: acs_map does not yet work). 2968 + modify Ada95 binding to use the new access-functions, allowing it 2969 to build/run when NCURSES_OPAQUE is set. 2970 + add access-functions and macros to return properties of the WINDOW 2971 structure, e.g., when NCURSES_OPAQUE is set. 2972 + improved install-sh's quoting. 2973 + use mkdirs.sh rather than mkinstalldirs, e.g., to use fixes from 2974 other programs. 2975 2976 20070324 2977 + eliminate part of the direct use of WINDOW data from Ada95 interface. 2978 + fix substitutions for termlib filename to make configure option 2979 --enable-reentrant work with --with-termlib. 2980 + change a constructor for NCursesWindow to allow compiling with 2981 NCURSES_OPAQUE set, since we cannot pass a reference to 2982 an opaque pointer. 2983 2984 20070317 2985 + ignore --with-chtype=unsigned since unsigned is always added to 2986 the type in curses.h; do the same for --with-mmask-t. 2987 + change warning regarding --enable-ext-colors and wide-character 2988 in the configure script to an error. 2989 + tweak error message in CF_WITH_LIBTOOL to distinguish other programs 2990 such as Darwin's libtool program (report by Michail Vidiassov) 2991 + modify edit_man.sh to allow for multiple substitutions per line. 2992 + set locale in misc/ncurses-config.in since it uses a range 2993 + change permissions libncurses++.a install (report by Michail 2994 Vidiassov). 2995 + corrected length of temporary buffer in wide-character version 2996 of set_field_buffer() (related to report by Bryan Christ). 2997 2998 20070311 2999 + fix mk-1st.awk script install_shlib() function, broken in 20070224 3000 changes for cygwin (report by Michail Vidiassov). 3001 3002 20070310 3003 + increase size of array in _nc_visbuf2n() to make "tic -v" work 3004 properly in its similar_sgr() function (report/analysis by Peter 3005 Santoro). 3006 + add --enable-reentrant configure option for ongoing changes to 3007 implement a reentrant version of ncurses: 3008 + libraries are suffixed with "t" 3009 + wrap several global variables (curscr, newscr, stdscr, ttytype, 3010 COLORS, COLOR_PAIRS, COLS, ESCDELAY, LINES and TABSIZE) as 3011 functions returning values stored in SCREEN or cur_term. 3012 + move some initialization (LINES, COLS) from lib_setup.c, 3013 i.e., setupterm() to _nc_setupscreen(), i.e., newterm(). 3014 3015 20070303 3016 + regenerated html documentation. 3017 + add NCURSES_OPAQUE symbol to curses.h, will use to make structs 3018 opaque in selected configurations. 3019 + move the chunk in lib_acs.c which resets acs capabilities when 3020 running on a terminal whose locale interferes with those into 3021 _nc_setupscreen(), so the libtinfo/libtinfow files can be made 3022 identical (requested by Miroslav Lichvar). 3023 + do not use configure variable SHLIB_LIBS for building libraries 3024 outside the ncurses directory, since that symbol is customized 3025 only for that directory, and using it introduces an unneeded 3026 dependency on libdl (requested by Miroslav Lichvar). 3027 + modify mk-1st.awk so the generated makefile rules for linking or 3028 installing shared libraries do not first remove the library, in 3029 case it is in use, e.g., libncurses.so by /bin/sh (report by Jeff 3030 Chua). 3031 + revised section "Using NCURSES under XTERM" in ncurses-intro.html 3032 (prompted by newsgroup comment by Nick Guenther). 3033 3034 20070224 3035 + change internal return codes of _nc_wgetch() to check for cases 3036 where KEY_CODE_YES should be returned, e.g., if a KEY_RESIZE was 3037 ungetch'd, and read by wget_wch(). 3038 + fix static-library build broken in 20070217 changes to remove "-ldl" 3039 (report by Miroslav Lichvar). 3040 + change makefile/scripts for cygwin to allow building termlib. 3041 + use Form_Hook in manpages to match form.h 3042 + use Menu_Hook in manpages, as well as a few places in menu.h 3043 + correct form- and menu-manpages to use specific Field_Options, 3044 Menu_Options and Item_Options types. 3045 + correct prototype for _tracechar() in manpage (cf: 20011229). 3046 + correct prototype for wunctrl() in manpage. 3047 3048 20070217 3049 + fixes for $(TICS_LIST) in ncurses/Makefile (report by Miroslav 3050 Lichvar). 3051 + modify relinking of shared libraries to apply only when rpath is 3052 enabled, and add --disable-relink option which can be used to 3053 disable the feature altogether (reports by Michail Vidiassov, 3054 Adam J Richter). 3055 + fix --with-termlib option for wide-character configuration, stripping 3056 the "w" suffix in one place (report by Miroslav Lichvar). 3057 + remove "-ldl" from some library lists to reduce dependencies in 3058 programs (report by Miroslav Lichvar). 3059 + correct description of --enable-signed-char in configure --help 3060 (report by Michail Vidiassov). 3061 + add pattern for GNU/kFreeBSD configuration to CF_XOPEN_SOURCE, 3062 which matches an earlier change to CF_SHARED_OPTS, from xterm #224 3063 fixes. 3064 + remove "${DESTDIR}" from -install_name option used for linking 3065 shared libraries on Darwin (report by Michail Vidiassov). 3066 3067 20070210 3068 + add test/inchs.c, test/inch_wide.c, to test win_wchnstr(). 3069 + remove libdl from library list for termlib (report by Miroslav 3070 Lichvar). 3071 + fix configure.in to allow --without-progs --with-termlib (patch by 3072 Miroslav Lichvar). 3073 + modify win_wchnstr() to ensure that only a base cell is returned 3074 for each multi-column character (prompted by report by Wei Kong 3075 regarding change in mvwin_wch() cf: 20041023). 3076 3077 20070203 3078 + modify fix_wchnstr() in form library to strip attributes (and color) 3079 from the cchar_t array (field cells) read from a field's window. 3080 Otherwise, when copying the field cells back to the window, the 3081 associated color overrides the field's background color (report by 3082 Ricardo Cantu). 3083 + improve tracing for form library, showing created forms, fields, etc. 3084 + ignore --enable-rpath configure option if --with-shared was omitted. 3085 + add _nc_leaks_tinfo(), _nc_free_tic(), _nc_free_tinfo() entrypoints 3086 to allow leak-checking when both tic- and tinfo-libraries are built. 3087 + drop CF_CPP_VSCAN_FUNC macro from configure script, since C++ binding 3088 no longer relies on it. 3089 + disallow combining configure script options --with-ticlib and 3090 --enable-termcap (report by Rong-En Fan). 3091 + remove tack from ncurses tree. 3092 3093 20070128 3094 + fix typo in configure script that broke --with-termlib option 3095 (report by Rong-En Fan). 3096 3097 20070127 3098 + improve fix for FreeBSD gnu/98975, to allow for null pointer passed 3099 to tgetent() (report by Rong-en Fan). 3100 + update tack/HISTORY and tack/README to tell how to build it after 3101 it is removed from the ncurses tree. 3102 + fix configure check for libtool's version to trim blank lines 3103 (report by sci-fi@hush.ai). 3104 + review/eliminate other original-file artifacts in cursesw.cc, making 3105 its license consistent with ncurses. 3106 + use ncurses vw_scanw() rather than reading into a fixed buffer in 3107 the c++ binding for scanw() methods (prompted by report by Nuno Dias). 3108 + eliminate fixed-buffer vsprintf() calls in c++ binding. 3109 3110 20070120 3111 + add _nc_leaks_tic() to separate leak-checking of tic library from 3112 term/ncurses libraries, and thereby eliminate a library dependency. 3113 + fix test/mk-test.awk to ignore blank lines. 3114 + correct paths in include/headers, for --srcdir (patch by Miroslav 3115 Lichvar). 3116 3117 20070113 3118 + add a break-statement in misc/shlib to ensure that it exits on the 3119 _first_ matched directory (report by Paul Novak). 3120 + add tack/configure, which can be used to build tack outside the 3121 ncurses build-tree. 3122 + add --with-ticlib option, to build/install the tic-support functions 3123 in a separate library (suggested by Miroslav Lichvar). 3124 3125 20070106 3126 + change MKunctrl.awk to reduce relocation table for unctrl.o 3127 + change MKkeyname.awk to reduce relocation table for keyname.o 3128 (patch by Miroslav Lichvar). 3129 3130 20061230 3131 + modify configure check for libtool's version to trim blank lines 3132 (report by sci-fi@hush.ai). 3133 + modify some modules to allow them to be reentrant if _REENTRANT is 3134 defined: lib_baudrate.c, resizeterm.c (local data only) 3135 + eliminate static data from some modules: add_tries.c, hardscroll.c, 3136 lib_ttyflags.c, lib_twait.c 3137 + improve manpage install to add aliases for the transformed program 3138 names, e.g., from --program-prefix. 3139 + used linklint to verify links in the HTML documentation, made fixes 3140 to manpages as needed. 3141 + fix a typo in curs_mouse.3x (report by William McBrine). 3142 + fix install-rule for ncurses5-config to make the bin-directory. 3143 3144 20061223 3145 + modify configure script to omit the tic (terminfo compiler) support 3146 from ncurses library if --without-progs option is given. 3147 + modify install rule for ncurses5-config to do this via "install.libs" 3148 + modify shared-library rules to allow FreeBSD 3.x to use rpath. 3149 + update config.guess, config.sub 3150 3151 20061217 5.6 release for upload to 3152 3153 20061217 3154 + add ifdef's for <wctype.h> for HPUX, which has the corresponding 3155 definitions in <wchar.h>. 3156 + revert the va_copy() change from 20061202, since it was neither 3157 correct nor portable. 3158 + add $(LOCAL_LIBS) definition to progs/Makefile.in, needed for 3159 rpath on Solaris. 3160 + ignore wide-acs line-drawing characters that wcwidth() claims are 3161 not one-column. This is a workaround for Solaris' broken locale 3162 support. 3163 3164 20061216 3165 + modify configure --with-gpm option to allow it to accept a parameter, 3166 i.e., the name of the dynamic GPM library to load via dlopen() 3167 (requested by Bryan Henderson). 3168 + add configure option --with-valgrind, changes from vile. 3169 + modify configure script AC_TRY_RUN and AC_TRY_LINK checks to use 3170 'return' in preference to 'exit()'. 3171 3172 20061209 3173 + change default for --with-develop back to "no". 3174 + add XTABS to tracing of TTY bits. 3175 + updated autoconf patch to ifdef-out the misfeature which declares 3176 exit() for configure tests. This fixes a redefinition warning on 3177 Solaris. 3178 + use ${CC} rather than ${LD} in shared library rules for IRIX64, 3179 Solaris to help ensure that initialization sections are provided for 3180 extra linkage requirements, e.g., of C++ applications (prompted by 3181 comment by Casper Dik in newsgroup). 3182 + rename "$target" in CF_MAN_PAGES to make it easier to distinguish 3183 from the autoconf predefined symbol. There was no conflict, 3184 since "$target" was used only in the generated edit_man.sh file, 3185 but SuSE's rpm package contains a patch. 3186 3187 20061202 3188 + update man/term.5 to reflect extended terminfo support and hashed 3189 database configuration. 3190 + updates for test/configure script. 3191 + adapted from SuSE rpm package: 3192 + remove long-obsolete workaround for broken-linker which declared 3193 cur_term in tic.c 3194 + improve error recovery in PUTC() macro when wcrtomb() does not 3195 return usable results for an 8-bit character. 3196 + patches from rpm package (SuSE): 3197 + use va_copy() in extra varargs manipulation for tracing version 3198 of printw, etc. 3199 + use a va_list rather than a null in _nc_freeall()'s call to 3200 _nc_printf_string(). 3201 + add some see-also references in manpages to show related 3202 wide-character functions (suggested by Claus Fischer). 3203 3204 20061125 3205 + add a check in lib_color.c to ensure caller does not increase COLORS 3206 above max_colors, which is used as an array index (discussion with 3207 Simon Sasburg). 3208 + add ifdef's allowing ncurses to be built with tparm() using either 3209 varargs (the existing status), or using a fixed-parameter list (to 3210 match X/Open). 3211 3212 20061104 3213 + fix redrawing of windows other than stdscr using wredrawln() by 3214 touching the corresponding rows in curscr (discussion with Dan 3215 Gookin). 3216 + add test/redraw.c 3217 + add test/echochar.c 3218 + review/cleanup manpage descriptions of error-returns for form- and 3219 menu-libraries (prompted by FreeBSD docs/46196). 3220 3221 20061028 3222 + add AUTHORS file -TD 3223 + omit the -D options from output of the new config script --cflags 3224 option (suggested by Ralf S Engelschall). 3225 + make NCURSES_INLINE unconditionally defined in curses.h 3226 3227 20061021 3228 + revert change to accommodate bash 3.2, since that breaks other 3229 platforms, e.g., Solaris. 3230 + minor fixes to NEWS file to simplify scripting to obtain list of 3231 contributors. 3232 + improve some shared-library configure scripting for Linux, FreeBSD 3233 and NetBSD to make "--with-shlib-version" work. 3234 + change configure-script rules for FreeBSD shared libraries to allow 3235 for rpath support in versions past 3. 3236 + use $(DESTDIR) in makefile rules for installing/uninstalling the 3237 package config script (reports/patches by Christian Wiese, 3238 Ralf S Engelschall). 3239 + fix a warning in the configure script for NetBSD 2.0, working around 3240 spurious blanks embedded in its ${MAKEFLAGS} symbol. 3241 + change test/Makefile to simplify installing test programs in a 3242 different directory when --enable-rpath is used. 3243 3244 20061014 3245 + work around bug in bash 3.2 by adding extra quotes (Jim Gifford). 3246 + add/install a package config script, e.g., "ncurses5-config" or 3247 "ncursesw5-config", according to configuration options. 3248 3249 20061007 3250 + add several GNU Screen terminfo variations with 16- and 256-colors, 3251 and status line (Alain Bench). 3252 + change the way shared libraries (other than libtool) are installed. 3253 Rather than copying the build-tree's libraries, link the shared 3254 objects into the install directory. This makes the --with-rpath 3255 option work except with $(DESTDIR) (cf: 20000930). 3256 3257 20060930 3258 + fix ifdef in c++/internal.h for QNX 6.1 3259 + test-compiled with (old) egcs-1.1.2, modified configure script to 3260 not unset the $CXX and related variables which would prevent this. 3261 + fix a few terminfo.src typos exposed by improvments to "-f" option. 3262 + improve infocmp/tic "-f" option formatting. 3263 3264 20060923 3265 + make --disable-largefile option work (report by Thomas M Ott). 3266 + updated html documentation. 3267 + add ka2, kb1, kb3, kc2 to vt220-keypad as an extension -TD 3268 + minor improvements to rxvt+pcfkeys -TD 3269 3270 20060916 3271 + move static data from lib_mouse.c into SCREEN struct. 3272 + improve ifdef's for _POSIX_VDISABLE in tset to work with Mac OS X 3273 (report by Michail Vidiassov). 3274 + modify CF_PATH_SYNTAX to ensure it uses the result from --prefix 3275 option (from lynx changes) -TD 3276 + adapt AC_PROG_EGREP check, noting that this is likely to be another 3277 place aggravated by POSIXLY_CORRECT. 3278 + modify configure check for awk to ensure that it is found (prompted 3279 by report by Christopher Parker). 3280 + update config.sub 3281 3282 20060909 3283 + add kon, kon2 and jfbterm terminfo entry (request by Till Maas) -TD 3284 + remove invis capability from klone+sgr, mainly used by linux entry, 3285 since it does not really do this -TD 3286 3287 20060903 3288 + correct logic in wadd_wch() and wecho_wch(), which did not guard 3289 against passing the multi-column attribute into a call on waddch(), 3290 e.g., using data returned by win_wch() (cf: 20041023) 3291 (report by Sadrul H Chowdhury). 3292 3293 20060902 3294 + fix kterm's acsc string -TD 3295 + fix for change to tic/infocmp in 20060819 to ensure no blank is 3296 embedded into a termcap description. 3297 + workaround for 20050806 ifdef's change to allow visbuf.c to compile 3298 when using --with-termlib --with-trace options. 3299 + improve tgetstr() by making the return value point into the user's 3300 buffer, if provided (patch by Miroslav Lichvar (see Redhat #202480)). 3301 + correct libraries needed for foldkeys (report by Stanislav Ievlev) 3302 3303 20060826 3304 + add terminfo entries for xfce terminal (xfce) and multi gnome 3305 terminal (mgt) -TD 3306 + add test/foldkeys.c 3307 3308 20060819 3309 + modify tic and infocmp to avoid writing trailing blanks on terminfo 3310 source output (Debian #378783). 3311 + modify configure script to ensure that if the C compiler is used 3312 rather than the loader in making shared libraries, the $(CFLAGS) 3313 variable is also used (Redhat #199369). 3314 + port hashed-db code to db2 and db3. 3315 + fix a bug in tgetent() from 20060625 and 20060715 changes 3316 (patch/analysis by Miroslav Lichvar (see Redhat #202480)). 3317 3318 20060805 3319 + updated xterm function-keys terminfo to match xterm #216 -TD 3320 + add configure --with-hashed-db option (tested only with FreeBSD 6.0, 3321 e.g., the db 1.8.5 interface). 3322 3323 20060729 3324 + modify toe to access termcap data, e.g., via cgetent() functions, 3325 or as a text file if those are not available. 3326 + use _nc_basename() in tset to improve $SHELL check for csh/sh. 3327 + modify _nc_read_entry() and _nc_read_termcap_entry() so infocmp, 3328 can access termcap data when the terminfo database is disabled. 3329 3330 20060722 3331 + widen the test for xterm kmous a little to allow for other strings 3332 than \E[M, e.g., for xterm-sco functionality in xterm. 3333 + update xterm-related terminfo entries to match xterm patch #216 -TD 3334 + update config.guess, config.sub 3335 3336 20060715 3337 + fix for install-rule in Ada95 to add terminal_interface.ads 3338 and terminal_interface.ali (anonymous posting in comp.lang.ada). 3339 + correction to manpage for getcchar() (report by William McBrine). 3340 + add test/chgat.c 3341 + modify wchgat() to mark updated cells as changed so a refresh will 3342 repaint those cells (comments by Sadrul H Chowdhury and William 3343 McBrine). 3344 + split up dependency of names.c and codes.c in ncurses/Makefile to 3345 work with parallel make (report/analysis by Joseph S Myers). 3346 + suppress a warning message (which is ignored) for systems without 3347 an ldconfig program (patch by Justin Hibbits). 3348 + modify configure script --disable-symlinks option to allow one to 3349 disable symlink() in tic even when link() does not work (report by 3350 Nigel Horne). 3351 + modify MKfallback.sh to use tic -x when constructing fallback tables 3352 to allow extended capabilities to be retrieved from a fallback entry. 3353 + improve leak-checking logic in tgetent() from 20060625 to ensure that 3354 it does not free the current screen (report by Miroslav Lichvar). 3355 3356 20060708 3357 + add a check for _POSIX_VDISABLE in tset (NetBSD #33916). 3358 + correct _nc_free_entries() and related functions used for memory leak 3359 checking of tic. 3360 3361 20060701 3362 + revert a minor change for magic-cookie support from 20060513, which 3363 caused unexpected reset of attributes, e.g., when resizing test/view 3364 in color mode. 3365 + note in clear manpage that the program ignores command-line 3366 parameters (prompted by Debian #371855). 3367 + fixes to make lib_gen.c build properly with changes to the configure 3368 --disable-macros option and NCURSES_NOMACROS (cf: 20060527) 3369 + update/correct several terminfo entries -TD 3370 + add some notes regarding copyright to terminfo.src -TD 3371 3372 20060625 3373 + fixes to build Ada95 binding with gnat-4.1.0 3374 + modify read_termtype() so the term_names data is always allocated as 3375 part of the str_table, a better fix for a memory leak (cf: 20030809). 3376 + reduce memory leaks in repeated calls to tgetent() by remembering the 3377 last TERMINAL* value allocated to hold the corresponding data and 3378 freeing that if the tgetent() result buffer is the same as the 3379 previous call (report by "Matt" for FreeBSD gnu/98975). 3380 + modify tack to test extended capability function-key strings. 3381 + improved gnome terminfo entry (GenToo #122566). 3382 + improved xterm-256color terminfo entry (patch by Alain Bench). 3383 3384 20060617 3385 + fix two small memory leaks related to repeated tgetent() calls 3386 with TERM=screen (report by "Matt" for FreeBSD gnu/98975). 3387 + add --enable-signed-char to simplify Debian package. 3388 + reduce name-pollution in term.h by removing #define's for HAVE_xxx 3389 symbols. 3390 + correct typo in curs_terminfo.3x (Debian #369168). 3391 3392 20060603 3393 + enable the mouse in test/movewindow.c 3394 + improve a limit-check in frm_def.c (John Heasley). 3395 + minor copyright fixes. 3396 + change configure script to produce test/Makefile from data file. 3397 3398 20060527 3399 + add a configure option --enable-wgetch-events to enable 3400 NCURSES_WGETCH_EVENTS, and correct the associated loop-logic in 3401 lib_twait.c (report by Bernd Jendrissek). 3402 + remove include/nomacros.h from build, since the ifdef for 3403 NCURSES_NOMACROS makes that obsolete. 3404 + add entrypoints for some functions which were only provided as macros 3405 to make NCURSES_NOMACROS ifdef work properly: getcurx(), getcury(), 3406 getbegx(), getbegy(), getmaxx(), getmaxy(), getparx() and getpary(), 3407 wgetbkgrnd(). 3408 + provide ifdef for NCURSES_NOMACROS which suppresses most macro 3409 definitions from curses.h, i.e., where a macro is defined to override 3410 a function to improve performance. Allowing a developer to suppress 3411 these definitions can simplify some application (discussion with 3412 Stanislav Ievlev). 3413 + improve description of memu/meml in terminfo manpage. 3414 3415 20060520 3416 + if msgr is false, reset video attributes when doing an automargin 3417 wrap to the next line. This makes the ncurses 'k' test work properly 3418 for hpterm. 3419 + correct caching of keyname(), which was using only half of its table. 3420 + minor fixes to memory-leak checking. 3421 + make SCREEN._acs_map and SCREEN._screen_acs_map pointers rather than 3422 arrays, making ACS_LEN less visible to applications (suggested by 3423 Stanislav Ievlev). 3424 + move chunk in SCREEN ifdef'd for USE_WIDEC_SUPPORT to the end, so 3425 _screen_acs_map will have the same offset in both ncurses/ncursesw, 3426 making the corresponding tinfo/tinfow libraries binary-compatible 3427 (cf: 20041016, report by Stanislav Ievlev). 3428 3429 20060513 3430 + improve debug-tracing for EmitRange(). 3431 + change default for --with-develop to "yes". Add NCURSES_NO_HARD_TABS 3432 and NCURSES_NO_MAGIC_COOKIE environment variables to allow runtime 3433 suppression of the related hard-tabs and xmc-glitch features. 3434 + add ncurses version number to top-level manpages, e.g., ncurses, tic, 3435 infocmp, terminfo as well as form, menu, panel. 3436 + update config.guess, config.sub 3437 + modify ncurses.c to work around a bug in NetBSD 3.0 curses 3438 (field_buffer returning null for a valid field). The 'r' test 3439 appears to not work with that configuration since the new_fieldtype() 3440 function is broken in that implementation.
http://ncurses.scripts.mit.edu/?p=ncurses.git;a=blob;f=NEWS;h=2df834e68bf3b450c1a0dc2cf6534e6e4323aed9;hb=7087871f804c061d339994964269f3c20e88f547
CC-MAIN-2022-33
refinedweb
25,590
66.23
Present in RC1 (200711131200), in beta2 this works. When using Insert Code -> Constructor in class that is inherited from other class that have some other than default constructor - the generated code does not contain call to superconstructor so it is not compilable. This works in beta2. Example: public class MyClass1 { public MyClass1(String s){} } public class MyClass2 extends MyClass1 { //try to insert constructor here //the generated code will be //public MyClass2(String s) { //} } Sorry, but I do not think this qualifies as P1. Caused by fix of issue #103642. Hopefully fixed now. Tests for both this issue and issue #103642 are pending. Checking in VeryPretty.java; /cvs/java/source/src/org/netbeans/modules/java/source/pretty/VeryPretty.java,v <-- VeryPretty.java new revision: 1.73; previous revision: 1.72 done *** Issue 122625 has been marked as a duplicate of this issue. *** Can we expect that this fix being integrated in release 60? We don't have currently any workaround for it and it breaks our code generation. JF. Petre, can you verify the fix? Thanks Ok now. The fix has been ported into the release60_fixes branch. Checking in VeryPretty.java; /cvs/java/source/src/org/netbeans/modules/java/source/pretty/VeryPretty.java,v <-- VeryPretty.java new revision: 1.71.4.1; previous revision: 1.71 done Verified in
https://netbeans.org/bugzilla/show_bug.cgi?id=122377
CC-MAIN-2019-22
refinedweb
218
53.78
Hi, SAP sourcing wave 7 has IDE which can support 32kb chars and wave 7 with SP6 and above supports 64kb chars. We have faced in few instances where our code has breached 64 kb limitation. The approach to reduce the size of variable names( char length of variable names), method name used in our development. This will have cost impact as far as maintainability of the code is concerned. SAP has provided a means overcome this limitation by following approach. This requires Admin access to the system and file system access to the server. 1. Create a java file 2. Put all /part of the code into a java file. 3. Compile and create a jar file. 4. Using Sourcing config tool , create .sca file 5. Deploy the .sca file into Sourcing thru JSPM. Once done , 1. In the sourcing ENV , import the java class which is deployed in the previous step 2. Instantiate the java class and call/use the method . Elaboration : I have created a java project and a method which has two parameter one RFX doc and session as below. The method it is printing a message to the document description in the RFX doc. The method signature is as follows. Create a jar file for this java project. I have used Apache Maven build to create a jar file ( you can use any other build utility like ANT which you are familiar with) The jar file name is MyFirstSourcingCode-0.1.jar Now I need to create a .SCA file before deploying this jar file . The steps to create .SCA file 1. Go to the Server file system and open a command prompt ( or put this in .BAT file and run the bat file) Set APPSERVER=NETWEAVER set JAVA_HOME=D:\usr\sap\<SID>\SYS\exe\jvm\NTAMD64\sapjvm_5.1.024\sapjvm_5\jre set PATH=%PATH%;%JAVA_HOME%\bin \esourcing70\bin\configure.exe This will open the configure tool Click on Next method Check the following check boxes as shown in the below picture and click on install ( Click only Custom Jar Files and Update WAR, EAR and SCA files) Select the J00 folder – (/usr/sap/<SID>/J00 folder) and click on Next Select the Jar file which you wish to deploy , in this case “MyFirstSourcingCode-0.1.jar” and click on Next . Click on Install. Click on Done to complete the .sca file creation. Now .sca file is created with the name <Application Context>Server.sca file which is present the following folder \esourcing70\fsapp Second part is deploying this .sca file into the Sorucing ENV. 1. Copy the <Application Context>Server.sca to the following folder \usr\sap\trans\EPS\in 2. Run the JSPM( Java Support package manager ) tool using command prompt \usr\sap\<SID>\J10\j2ee\JSPM\go.bat 3. Login as Administrator 1. Select “Single support packages and Patches( Advanced users only) and click on Next Cliclick on Next This is the Java file information which we deployed into Sourcing ENV using JSPM Package Name : com.temp Java Class Name : MyFirstSourcingCode Method Name : myFirstSourcingMethod( IapiSessionContextIfc session, RfxDocIBeanIfc doc) Go to the Sourcing system open the Script on the target business object as RFX. For simplicity sake , I am creating a tool bar script . Login to Sourcing system Go to Setup >> Script Definition >> select toolbar in the wizard step 1 as shown in the below picture. Click on continue. Enter the values as appropriate in your case Enter the code in the script section import com.temp.*; // Instantiate the class object MyFirstSourcingCode customJarObj = new MyFirstSourcingCode(); //call the method to print the value “Printing from the MyFirstSourcingCode jar file” into document description customJarObj.myFirstSourcingMethod( session, doc) ; Save the script and open an RFX doc and run the tool bar script to verify whether it is printing value from the java method. Conclusion : By creating a custom jar and adding all the additional code into the java file we can over come the Sourcing script defintion limitation of 64kb. The advantage : · Code secured and not visible to all as it is a compiled code. · Consuming third party Web service caqn be done using this approach The challenging issues is · Every time you want to modify any code in the java side , you need to follow this tedious task. So before moving any code onto the java side, test it thoroughly and move it only it really required. I I a Hello Prashanth, First of all, thanks a lot for this great post. It has been really helpful. But I would need support by the following situation: I’ve followed the actions described by you and I’ve tried to call this class through the toolbar script but following error is raised: “Source file: inline evaluation of: “import com.temp.*; // Instantiate the class object MyFirstSourcingCode customJarObj =…\’\’: Typed variable declaration: Class: MyFirstSourcingCode not found in namespace” Therefore, I guess that I’ve done something wrong or there are some steps pending to be done. Could you please answer to the following questions: – Before to start these actions, should I stop the E-Sourcing server through NWA? – Before to deploy the SCA file, should I undeploy existing SCA file by following statement? UNDEPLOY name=E-Sourcing-Server vendor=sap.com on_undeploy_error=stop Thanks in advance and best regards, Isaac Thanks Isaac, Going by the error , it seems like jar is not deployed into the server. As it is not able to identify the MyFirstSourcingCode class. After the deployment .sca file , server needs to be restarted. My server is configured in such way that it restarts automatically once the .sca file is deployed. If your server is not restarted after the deployment, please restart the server. Hope this may resolved the issue. I have gone thru once again on the blog if I have missed any key steps. did not find anything missing – Before to start these actions, should I stop the E-Sourcing server through NWA? No – Before to deploy the SCA file, should I undeploy existing SCA file by following statement? It will overwrite the existing SCA file. regards pkiran Hello Prashanth, Thanks a lot for your quick answer. Just to clarify it: when you say server needs to be restarted: do you mean restart the server (machine) where E-Sourcing is installed instead of START & STOP the E-Sourcing Java application, isn’t it? Because I’ve already done a START & STOP E-Sourcing Java application after .SCA deployment and it is still no working. So I guess that what I need to do next is to restart the machine (server) where E-Soucing is installed, isn’t it? Thanks again for your support. Best regards, Isaac Hello Prashanth, Both of SAP Server and machine has been restarted but same result. Any idea on how it could be solved? Thanks a lot and best regards, Isaac Hi , As said earlier , it seems like the runtime is unable to recognize the class in the system. In this case I would look at the very instance of jar deployment part. I have done this many times during the development phase, not even once it failed and the behavior is very consistent. so please look keenly on the deployment part steps. regards pkiran Hi Prashanth, Thanks again for your answers. I’ve deeply analyze deployment steps and I’ve followed them according to your comments but same results. I’ve seen that your steps are executed to include custom JAR files on eSourcing 7. I’m executing these steps on eSourcing 9. Could it be the reason? Maybe the steps to be executed for eSourcing 9 are a little bit different? Thanks again and best regards, Hi Isaac, This works on wave 7 but not sure whether it works on wave 9. But there is one more blog on this on wave 9. can you please check with that blog. Sorry I do not have the link , otherwise would have pasted the link. regards pkiran Hi again Prashanth, Thanks again for your quick response. I’m working in parallel with following blog: Are you referring to that one? Anyway and according to that blog, I’ve modified .EAR file and i will execute following steps: 1. Telnet command: UNDEPLOY name=E-Sourcing-Server vendor=sap.com on_undeploy_error=stop 2. Telnet command: DEPLOY <esoserver.ear file path> version_rule=all Hopefully, it will deploy it into the SAP NW. Please, don’t hesitate to let me know your thoughts. Thanks and best regards, Isaac Hi Prashanth, Tested also with TELNET command and it is not working. It leads me to the question: the JAR file… needs to be created in a special way? Currently I’m creating it using ECLIPSE IDE. Should it be created by a special way? Thanks again and best regards, Isaac Sorry was busy with regular work , did not get a chance to look into it. I have created the Jar file using NDWS using Maven build utility. I do not think it will have any difference on this . May be I will write a blog on this topic to help others who are struggling on this type of issues. in your case , that should not be a problem whether you create a jar file using eclipse or NWDS. regards pkiran I’m not sure where this process is going wrong. But there is no need to use command line tools to deploy the SCA file. (NOT EAR file). Also ther is no need to manually manipulate the archive. You can simply build a new custom jar and add it to the deployment using the supplied configure utility in the sourcing root /bin directory. It will build the new SCA file for deployment using the standard Neytweaver deployment tool. I have not used Wave 9 , not sure about the process to do this activity. This blog is for wave 7. regards pkiran
https://blogs.sap.com/2013/10/08/how-to-overcome-64kb-chars-script-definition-limitation-in-sap-sourcing/
CC-MAIN-2017-43
refinedweb
1,645
75
Firstly, apologies for the cross-posting, particularly giving the fact that I am including code, but this message contains issues relevant to both automake and autoconf. For a while I have been thinking that it would be nice to be able to support "include" in autoconf/automake Makefiles. This would be particularly nice with automake which generates very large repetitious Makefiles. Currently there are three ways to do inclusion that I can think of (AC_SUBST_FILE, the Makefile:include.mk hack and automake's include) but all these result in full expansion of the included file in the final Makefile. I am talking about a real include that is done by Make and not by auto{conf|make}. A big motivation for me, is to use this with automake. I have at least one project which has a large number of Makefiles and uses a single include file to add extra rules. The big problem with the current setup is a single change to the include file means rerunning automake/config.status on _every_ Makefile. Using an include mechanism it should be possible to just regenerate the include file and have everything worked out. The problem is of course, that not all makes do include the same way. There are basically two flavours. #SYSV and GNU make include file #BSD make (although most of the later BSD makes seem to support include) .include "file" And while I cannot actually find a version of make that doesn't support include in some form, for safety we probably want to support some sort of hack that does an inline expansion of the include file if there is no Make support. To this end I have hacked up some autoconf macro's that do a check to see if include is supported and emulate it if it isn't. You use it this way: In your Makefile do: #Lots of lovely make rules ... @INCLUDE@ @INCLUDE_QUOT@@top_srcdir@/address@hidden@ (Yes I know the syntax is ugly and hard to read, but it is the easiest way to do it without having to dig through autoconf internals). Then in your configure.ac do: AC_CONFIG_MAKEFILES(include.mk Makefile) Which automatically calls AC_PROG_MAKE_INCLUDE to check for include support (if it hasn't already been called). I have a reasonable amount of comments in the code, so it should be easy enough to follow, and it seems to work on all the systems I have access to. I have tried to avoid using autoconf internals wherever possible. It is a hack and a bit fragile in places, but as a proof of concept it is probably a good start. Better support would probably require some access to automake internals. For example, you would tend to want to have a single include.mk with all the address@hidden@ stuff and include this from all the other Makefiles so it makes sense to have the @INCLUDE@ subsitution very close to the top of the sed commands list to avoid having to run through all the other substitutions. This would speed up config.status for a lot of files. This might also make it easier to address the problem of recursive Makefiles in automake by doing the following: Generate top level include with all the common stuff. Generate directory specific stuff in a per-directory include file Generate directory specific Makefile including top-level and per-directory include Generate top-level Makefile with directory specific and all the per-directory files included. This allows you to still do "cd foo; make" when that make sense. Of course resolving the namespace issues here would be non-trivial. Any comments, suggestions? acmakeinclude.m4 Description: acmakeinclude.m4
http://lists.gnu.org/archive/html/automake/2001-06/msg00163.html
CC-MAIN-2014-42
refinedweb
612
63.09
Content-type: text/html swapctl - Manages the system swap space #include <sys/stat.h> #include <sys/swap.h> int swapctl( int cmd, void *arg ); Specifies the operation to be performed. Options include adding a resource, deleting a resource, removing a resource, or returning the number of swap resources. Specifies a pointer to a structure. See the DESCRIPTION section for information on this structure. The swapctl function manages the system swap space by adding, deleting, or returning information about swap resources. The cmd parameter that you select determines the value of the arg parameter. The following sections discuss the available commands and command arguments. The swapctl function adds, removes, or returns information on the system swap space using the following values for the cmd parameter: Includes a new resource in the swap list. Provides a list of the resources available for swapping. Removes a resource from the swap list. Counts and returns the number of swap resources With the exception of the SC_GETSNSWP command, each of these commands returns information in a structure pointed to by the arg parameter. The next sections discusses the information that is contained in these structures after a successful return. The value of the arg parameter is specific to the type of command specified by the cmd parameter. This section highlights the value for the arg parameter as it pertains to the commands. If either the SC_ADD or SC_REMOVE command is specified, the arg parameter is a pointer to the following swapres structure: typdef struct swapres { char sr_name; off_t sr_start; off_t sr_length; } swapres_t; The fields are defined as follows: Provides the pathname of the resource that is being added or removed. Specifies in 512-byte blocks, the offset of the resource area from the start. Specifies in 512-byte blocks, the length of the swap area. When using the SC_ADD and SC_REMOVE commands, the calling process fails if the appropriate privileges do not exist for the operation. If the SC_LIST command is specified, the arg parameter is a pointer to the following swaptable structure: int swt_n; struct swapent swt_ent []; In this structure, the field swt_n specifies the maximum entries that will be returned by the swapctl function. The swt_ent field is an array of swt_n swapents. The swapent structure is as follows: typdef struct swapwent { char *ste_path; off_t ste_start; off_t ste_length; long ste_pages; long ste_free; long ste_flags; } swapwent_t; Before the swapctl(2) is issued, allocate memory to all of the ste_path pointers. Ensure that each of the areas allocated is at least MAXPATHLEN bytes long. MAXPATHLEN is defined in <sys/param.h>. The fields are defined as follows: Specifies the name of the swap file. Specifies the starting block to begin swapping. Specifies in 512-byte blocks, the length of the swap area. Specifies the number of pages available for swapping. Specifies the number of pages that are free. Sets the ST_INDEL bit if the swap file is being deleted. On success, the swapctl function returns zero (0) when used with the SC_ADD or SC_REMOVE commands. For the SC_LIST command, the number of struct swapent entries actually returned indicates success, and for SC_GETNSWP, the number of swap resources in use is returned upon success. On error, the swapctl function returns a value of -1 and sets errno to indicate the error. If the swapctl function fails, errno is set to one of the following: Indicates that the range specified by the sr_start and sr_length fields for the SC_ADD command is already in use for swapping. Specifies that the structure pointed to by the arg parameter, or one of the fields sr_name or ste_path is outside the allocated address space. Specifies one of the following: The command value is not valid. The path used with the SC_REMOVE command is not a swap resource. The range indicated by the sr_start and sr_length fields for the SC_ADD command is outside the resource specified. The indicated swap area is less than one page for the SC_ADD command. Indicates that the path used with the SC_ADD command is not a directory. Indicates that the pathname used with the SC_ADD or SC_REMOVE commands has too many symbolic links to correctly translate the pathname. Indicates that the length or path used with the SC_ADD or SC_REMOVE command exceeds the maximum allowed with {_POSIX_NO_TRUNC} in effect. Indicates that a nonexisting pathname was specified with either the SC_ADD or SC_REMOVE commands. Specifies one of the following: Not enough struct swapent structures exist for the SC_LIST command. Sufficient system storage resources were not available during an SC_ADD or SC_REMOVE operation. Not enough swap space would exists after an SC_REMOVE operation. Indicates that the pathname specified for a SC_ADD or SC_REMOVE operation is not a filename or special block device. Specifies that the pathname used with the SC_ADD or SC_REMOVE commands contained a component in the path that was not a directory. Indicates that insufficient privileges do not exist for the operation. Indicates that a read-only file system was specified by the path for the SC_ADD command.
http://backdrift.org/man/tru64/man2/swapctl.2.html
CC-MAIN-2017-09
refinedweb
831
63.7
> >Am I off base to insist on _not_ using loadable modules. > > No, and maybe:-). It really depends. > > One school of thought says that it's _Always_ better to secure a > firewall in absolutely every way possible, and that all other things > being equal simpler is more secure, so doing away with the whole > module-loading subsystem is a win. Likewise statically link all the > binaries you don't delete and do away with ld.so and all the shared > library stuff. > > Another school of thought says to stick close to stock releases and > don't do a lot of unnecessary custom hacking; leverage as much as > possible off mainstream upgrades and patches for tracking security > fixes, and only go non-standard where needed to fix known security > holes. Agreed. Although not using modules may save you memory: each modules takes a certain amount of pages, a page being 4Kb of memory. So on average you waste 2 Kb of memory per module loaded. This is most probably not much, but on a small 386 managing a 64 Kb ISDN line, you may put a firewall with only 8 megs (it's not trivial to find a 386 with more than that...), and then those few Ks wasted mean less memory availlable for network buffers. This may or may not be an issue, depending on your hardware and network speed. > I've never heard of any remote-exploitable bug with dynamic module > loading. If you've allowed an intruder to log in to your firewall you've > already lost the game; I don't worry nearly as much about > exploitable-after-you're-logged-in holes as I do about > remote-exploitable holes. There's one issue with firewalls allowing module loading: if an attacker gets root, he may load a module that will prevent the administrator to detect the intrusion, such as hide the network connection in netstat, hide the additional processes, hide the additional module... Regards, -- Christophe Dupre Analyste de systemes, RISQ inc. ;-) 1801 McGill College, suite 800 Tel: (514) 840-1235, ext 6971 Montreal, QC CANADA FAX: (514) 840-1244 "Nous ne sommes pas libres de ne pas etre libres, nous sommes obliges de l'etre" - Fernando Savater #include <disclaimer.h>
http://www.greatcircle.com/lists/firewalls/mhonarc/firewalls.199803/msg00272.html
CC-MAIN-2013-20
refinedweb
373
59.03
Hi, I have this simple file that is supposed to create a Node struct to form a linked list. Basically what I want is for the user to be able to enter as many strings as he or she wants and for each new string the program creates a new "Node" and assigns 'nvalue' to the string and the 'ptr' of the last node, which is a node pointer, to point to the new node. Here is the code that I have implemented so far (just testing out basics), but it won't compile: Error:Error:Code: #include <cstdlib> #include <iostream> #include <string> using namespace std; struct Node { string nvalue; Node *ptr; } int main(int argc, char *argv[]) { // line 14 Node myNode; cin >> myNode.nvalue; cout << "You inputted: " << myNode.nvalue; System("Pause"); return 0; } Code: 14 test.cpp new types may not be defined in a return type 14 test.cpp extraneous `int' ignored 14 test.cpp `main' must return `int' 14 test.cpp return type for `main' changed to `int'
https://cboard.cprogramming.com/cplusplus-programming/94451-linked-list-problems-printable-thread.html
CC-MAIN-2017-26
refinedweb
171
78.79
How to convert Byte array to String and vice versa in Java There are some scenarios in which we have the data in the String format and we want to change it to the byte[] or vice versa. In this tutorial, we are gonna cover how to do these conversions. Conversion from String to byte[] There are 2 different approaches that we are gonna discuss for this Using – String.getBytes(…) There is String.getBytes() which uses the platform default encoding to encode a string to byte[] and other versions String.getBytes(Charset) which converts String to byte[] using the provided charset. I generally prefer to use the one where we define the charset as it makes it platform-independent and we can be sure that the code is gonna behave in the same manner everywhere. Using Base64.Decoder Base64 class is available since Java 8 version. As you might be aware – Base64 is designed to represent arbitrary sequences of octets in a form that allows the use of both upper- and lowercase letters but that need not be human-readable, while UTF-8 and UTF-16 are ways to encode Unicode text data. So if you need to encode Base64 data as text, Base64 class is the way to go. Example to convert String to Byte[] import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Base64; public class ConvertStringToByteArray { public static void main(String[] args) { // var is the feature of Java 10 var validString = "Codingeek.com"; // Using getBytes method byte[] usingGetBytes = validString.getBytes(StandardCharsets.UTF_8); // USing Base64 Decoder // First encode a String to Base64 format var base64EncodedString = Base64.getEncoder().encodeToString(validString.getBytes()); byte[] usingBase64Encoder = Base64.getDecoder().decode(base64EncodedString); System.out.println( "Are both arrays equal -> " + Arrays.equals(usingGetBytes, usingBase64Encoder)); } } Output:- Are both arrays equal -> true Conversion from String to byte[] There are 2 different approaches that we are gonna discuss for this as well String constructor – new String(byte[]) String class has a constructor that takes a byte[] as the input parameter and that constructor can be safely used to convert byte[] to String. Using Base64.Encoder As we have already discussed regarding the Base64 data above. - Base64 class has an encoder class that accepts the byte[] and returns Base64 encoded string. - This String then can be converted to byte[] using the Base64.getDecoder() that we discussed above. - Then we again use the new String(byte[]) to convert it to proper String. Example to convert Byte[] to String import java.util.Base64; public class ConvertByteArrayToString { public static void main(String[] args) { // var is the feature of Java 10 var validString = "Codingeek.com"; // Using new String(byte[] ) var byteArray = validString.getBytes(); System.out.println("Using String constructor -> " + new String(byteArray)); // When the string is base64 encoded var base64EncodedString = Base64.getEncoder().encodeToString(byteArray); var base64DecodedByteArray = Base64.getDecoder().decode(base64EncodedString); System.out.println("\nBase64 encoded string -> " + base64EncodedString); System.out.println("Using with base -> " + new String(base64DecodedByteArray)); } } Output:- Using String constructor -> Codingeek.com Base64 encoded string -> Q29kaW5nZWVrLmNvbQ== Using with base -> Codingeek.com An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding. Do not forget to share and Subscribe. Happy coding!! 😊
https://www.codingeek.com/java/convert-byte-array-to-string-and-vice-versa/
CC-MAIN-2020-50
refinedweb
538
57.98
- Write a program in Java to print up-side down pyramid pattern of stars. In Reverse pyramid star pattern of N rows, ith row contains (i-1) space characters followed by (2*i - 1) star(*) characters. Check below mentioned inverted pyramid pattern of 4 rows. Sample Output for 4 rows ******* ***** *** * Algorithm to print inverted pyramid star pattern using loop This C program is similar to pyramid star pattern, except here we are printing the rows in reverse order. This C program is similar to pyramid star pattern, except here we are printing the rows in reverse order. - We first take the number of rows in the pattern as input from user and store it in an integer variable "rows". - One iteration of outer for loop will print a row of inverted pyramid. - For any row i, inner for loop first prints i-1 spaces followed by a while loop which prints (2*i - 1) star character. Java program to print inverted pyramid star pattern package com.tcc.java.programs; import java.util.*; public class InvertedPyramidPattern { public static void main(String args[]) { int rows, i, space, star=0;; Scanner in = new Scanner(System.in); System.out.println("Enter number of rows in pattern"); rows = in.nextInt(); for(i = rows;i >= 1; i--) { // Printing spaces for(space = 0; space <= rows-i; space++) { System.out.print(" "); } // Printing stars star = 0; while(star != (2*i - 1)) { System.out.print("*"); star++; } System.out.print("\n"); } } }Output Enter number of rows in pattern 6 *********** ********* ******* ***** *** * Recommended Posts
https://www.techcrashcourse.com/2016/04/java-program-print-inverted-pyramid-pattern.html
CC-MAIN-2020-05
refinedweb
250
58.38
Microsoft just released a new security update to be automatically applied to machines configured to use Microsoft Update. The security bulletin is available here: Unfortunately, some ASP.NET MVC 3 and 4 VS projects can no longer build after the update is applied. These projects will fail with the following error: Could not locate the assembly “System.Web.Mvc,Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35,processorArchitecture=MSIL”. This happens when your project references assemblies from the GAC or the Reference Assemblies folder. Project references to System.Web.Mvc.dll are no longer resolved because the assembly version of System.Web.Mvc.dll was incremented. The problem can be resolved by implemented one of the following solutions: 1. (Preferred) Install Microsoft.AspNet.Mvc from the NuGet gallery (this will install a binding redirect in your web.config). You can do this from the NuGet package manager or the NuGet console inside Visual Studio: >Install-Package Microsoft.AspNet.Mvc -Version <version> -Project PROJECTNAME MVC 4 version: 4.0.40804.0 MVC 3 version: 3.0.50813.1 2. Manually update the reference to System.Web.MVC.dll (don’t use the one in the GAC). Try the Add Reference -> Assemblies -> Extensions dialog box. In either case ensure that the Copy Local project property for the assembly is set to true so it ends up in your bin folder which is needed for deployment. There is a known NuGet bug that resets the Copy Local flag: For MVC projects built prior to VS 2012 references to MVC assemblies were added from either the GAC or the Assembly References folder. Most recent MVC templates add references to assemblies installed via NuGet packages, this is why option No.1 above is preferred. The NuGet gallery has become very popular. As a side note, a similar issue may occur when creating a new MVC 3 project in Visual Studio 2010, this is documented in the security bulletin: MVC 3.0 RTM is installed on my system and after installing the update I can no longer create a new project in Visual Studio 2010, how can I correct this?. Finally, the decision to increment the assembly version was to secure those applications that were deployed on servers owned by third parties, in this case the vulnerable assembly may be in the GAC. In order to ensure the application runs the secure assembly, the assembly version had to be incremented. Some ASP.NET MVC 5 projects may also be affected by a somewhat related issue. When you run your application within Visual Studio it might fail with an error that looks like the following: Compiler Error Message: CS0234: The type or namespace name ‘Ajax’ does not exist in the namespace ‘System.Web.Mvc’ (are you missing an assembly reference?) This is because the assembly Copy Local flag has been reset most likely due to the NuGet bug mentioned previously. A variation of this problem, affecting all versions of MVC, is that your assembly is no longer deployed with your application from within Visual Studio. Visual Studio sets the Copy Local flag to false by default when the assembly is installed in the GAC, for reference see these MSDN articles: and. Manually setting the Copy Local flag to true fixes these issues. Another problem affecting MVC 4 applications can generate an error that looks like the following: Could not load file or assembly ‘Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed’ or one of its dependencies. This is not a build-specific issue and happens because the MVC assemblies are now installed in the GAC, the Newtonsoft.Json.dll assembly can no longer be resolved; copying the assembly to the application’s probing path (bin or equivalent folder) resolves this problem. You can get Newtonsoft.Json 4.5.6 from the NuGet gallery. If your application does not have any custom logic for loading assemblies it is likely it is running a pre-release version of MVC which did not have a dependency on Newtonsoft.Json; in this case you are strongly advised to upgrade your application to a supported release of MVC. Join the conversationAdd Comment A related but seemingly slightly different issue? stackoverflow.com/…/5056 I say slightly different as I was referencing a nuget package and not the GAC Yes and it seems to be worth mentioning that there's no reason to think this issue is restricted to devs or local "builds". Anyone with a subsequently installed running website will find that the entire website will stop working, for the same reason. Hi, Actually my point was that I believe existing web applications *are* broken. Unfortunately, I know this first-hand… as all of our deployed web sites that were working perfectly, but have just had a Windows update, are now broken. Yes, this is the same issue and only happens at build time or deployment if copy local is not fixed. Existing web applications are not affected. @Panda, can you share the error you get? thank you! Hi, Actually apologies for recent assertion about website breaking. It appears we have a client breaking, not a website. It's something to do with referencing libraries such System.Net.Http which must somehow be referencing MVC GAC/referenced assemblies… will let you know when I get to the bottom of it. But these installed clients did immediately break because of this security update. Based on timing, I assume this is related: umbraco.com/…/getting-a-systemwebhttpapicontroller-error @Panda – sounds more like your issue even if you aren't using Umbraco, so you might try the resolutions noted there. Thanks for this blog post. We too had our build broken by the update. However, even after adding the correct dll to our references, we still cannot run FxCop because of indirect references to older MVC dlls (for instance, RazorGenerator has a reference to System.Web.Mvc.dll version 3.0.0.0). Do you have any advice for this situation? We currently "fixed" the build by disabling FxCop but that's not really a preferable solution. Thanks for the blog – as a developer with hundreds of engineers depending on a build – releasing a breaking change like this is appalling behaviour from Microsoft. Just to answer my earlier comment, we solved our FxCop issues using the solution described in this blog post:…/how-to-pass-parameters-to-fxcop-from-visual-studio-or.aspx I undertand that the logic behind the version change was that there was such a big security hole, that we can't afford to wait for third parties to install this new update so we better deploy the web-site with this patched dll included. Strange indeed. For our team, one unlucky developer was pushed this update. It did not break the BUILD of our application but it does blow up when executing. His error message is identical to the one presented here: stackoverflow.com/…/after-windows-update-the-type-or-namespace-name-html-does-not-exist-in-the-na There's no question that folks have fixed this by updating NuGet packages, but the project was at ASP.NET MVC 5 (System.Web.Mvc.dll is at 5.0.11001.0) and the team wasn't thrilled about changing the solution so close to release. The preferred behavior would be that this patch "just worked" and the solution still ran as it did before. Is this going to be possible? Does the team HAVE to update NuGet packages for ASP.NET MVC? My machine hasn't been pushed the update yet, so we're also unclear what the criteria was for receiving it on what is generally a dev machine? The bulletin answered that from the point of view of a server administrator, not necessarily a developer. DLL hell has returned…what is MSFT doing to fix this? Chris, it is recommended that developers update their VS solutions with the NuGet update as explained in this blog, this is to ensure applications are deployed with the secure assembly. Awesome! Tens of thousands of developers spent their Wednesday trying to figure out why everything gone crazy. thanks for the clear explanation on how to fix this problem Just for the record, our error was: Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. And this happened on many installed clients, immediately after this Windows update. The client software uses some system.net.http.xxx libraries which are effected in the web of dependencies. We've have to deploy a new executable for affected users with updated NuGet packages, basically. But to repeat, this is not restricted to developer builds – client software on running machines, stopped working after this Windows update. I suspect this wasn't anticipated? We appear to have been hit by an issue with this patch too; though the cause appears to be that System.Web.MVC is not copied to our bin folder since the patch. This is possibly caused by CopyLocal=true being ignored because the DLL is now in the GAC (it was not before). I've posted full details here; and we're incredibly concerned we can't protect ourselves against this breaking again on your next "non-breaking-change security update" :-/ stackoverflow.com/…/25124 Thanks Microsoft, I was faced with another boring day of getting stuff done and getting paid for it, now I get to chase down obscure chains of dependencies on our dev servers to find out why the new code with the 3.0.0.1 library totally fails to run when deployed! Thanks for your post. Have followed your instructions to the letter and our builds now work. But when publishing we are now missing a handful of dlls e.g. System.Web.dll, System.Web.Http.WebHost.dll etc. We didn't have 'Copy Local' set on these before the patch and I don't see why I should have to do it now until I have a clear understanding of what's going on. Any ideas? @afh, this is explained in the blog: A variation of this problem is that your assembly is no longer deployed with your application. Visual Studio sets the Copy Local flag to false by default when the assembly is installed in the GAC, for reference see these MSDN articles: msdn.microsoft.com/…/vslangproj.reference.copylocal.aspx and msdn.microsoft.com/…/ez524kew%28VS.80%29.aspx. Manually setting the Copy Local flag to true fixes these issues. Yes Miguell. Yes I had noted that and it indeed it solves my issue. Still doesn't explain why I didn't need to do this before the patch. Thanks anyway. I'm not sure what I'm missing from your question but let me try to clarify: you didn't need to do that before the patch because the default value for the Copy Local flag was true, once the assembly is installed in the GAC the default is set to false so you need to explicitly set it to true to fix the problem. I'm running into this error on one server, as a result of this update: The type 'System.Web.Mvc.ViewMasterPage' is ambiguous: it could come from assembly 'C:MyWebsitebinSystem.Web.Mvc.DLL' or from assembly 'C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Web.Mvcv4.0_3.0.0.0__31bf3856ad364e35System.Web.Mvc.dll'. Please specify the assembly explicitly in the type name. The part highlighted in the error message is in my MVC master page, in the Master directive Inherits="System.Web.Mvc.ViewMasterPage" I'm using MVC 3.0. And I have CopyLocal=true. The version of System.Web.Mvc.dll in my BIN directory is 3.0.50813.1 which I believe is the updated version from this security update. My guess is an older version is in the GAC, but I'm not able to run Windows Updates on the server for at least 1 week (more specifically we cannot reboot the server for 1 week). I also have the below bindingRedirect setup in the web.config folder – something I added back when the website was first created. Is there something I can add to the web.config file, or elsewhere, so the website knows to use the System.Web.Mvc.dll in the BIN directory and not get confused with the version in the GAC? > Hi Miguell, I've excatlly the same problem as described by @afh. The following 6 .dll and .xml files are now missing from published folder via the File system publish method after applying the patch. System.Net.Http.Formatting.dll + .xml System.Web.Http.dll + .xml System.Web.Http.WebHost.dll + .xml Here is the snippet of project file BEFORE.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <Private>True</Private> <HintPath>..packagesMicrosoft.AspNet.Mvc.4.0.30506> Here is the snippet of project file AFTER.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <Private>True</Private> <HintPath>..packagesMicrosoft.AspNet.Mvc.4.0.40804> As you can see there is no change made to project file for these 3 .dll files. I am wondering why the behaviour is changed for these dlls after applying the patch. We have an old VS2010, ASP.NET web app (.NET 4.0) that won't build – References->System.Web.MVC is marked as missing. We'd had not used NuGet back when we wrote it. When I try to install Microsoft.AspNet.Mvc, I get an error: "Could not load file or assembly 'TTVSAddinDotNet.resources.module' or one of its dependencies" When I try to add the reference directly, using VS2010's Add Reference Dialog, System.Web.MVC does not show up in the .NET tab (filtered to .NET Framework 4). So now what do I do? @Miguel, it doesn't look like the update added anything to the GAC, just the mvc assemblies folder, which had the same effect. Post-update, my build outputs were missing System.Net.Http.Formatting.dll. As a test, I removed that file from "C:Program Files (x86)Microsoft ASP.NETASP.NET MVC 4Assemblies", then reran the build. The dll showed up in the build drop folder again. When I re-add that dll to the local assemblies folder and run another build, the dll is again missing. As a followup: I found the new DLL in the .net framework folder, stuck it in a folder in my project, added it as a reference, and set it as "Copy Always". VS2010 would then compile, but when I run the aspnet_compiler, it gives me errors: warning CS1702: Assuming assembly reference 'System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' matches 'System.Web.Mvc, Version=3.0.0.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35', you may need to supply runtime policy So next I updated the version number for System.Web.MVC, in the web.config to 3.0.0.1 (in <compilation><assemblies> and in <runtime><assemblyBinding><dependentAssembly?, and I get the same errors. Still confused. @Panda what version of system.net.http.xxxx do you use in your application? How does your application load them? @Ben Amanda Ben, how did you get your app's bin folder updated? if you did it manually then you also need to update the binding redirect in your web.config to look like this: <bindingRedirect oldVersion="1.0.0.0-3.0.0.1" newVersion="3.0.0.1" /> If you have a VS solution, you can use NuGet Manager to update your MVC 3 package (3.0.50813.1), it will automatically update the web.config for you. @hammy, @afh Observe that in your project file you have the following metadata in the Reference item for System.Web.Mvc: <Private>true</Private> This is added when you set the Copy Local flag explicitly. In the absence of this metadata, Visual Studio infers the value of the flag differently depending on whether the assembly is in the GAC (false) or not (true). The missing assemblies you listed were not in the GAC before (default Copy Local == true), the patch installed them in the GAC (default Copy Local == false). Once you set the Copy Local flag to true the item metadata is added so VS does not have to infer it anymore. hope this clarifies. @Jeff Dege Jeff, you should clean up your solution and update the NuGet package, you can get the update from the NuGet console by running the following command: >Install-Package Microsoft.AspNet.Mvc -Version 3.0.50813.1 this should update the binding redirect in your web.config automatically then you can redeploy your application. See my reply to @Ben Amanda which has a similar issue. @SuperDuper The MVC 4 update should have installed System.Net.Http.Formatting.dll in the GAC along with other assdemblies, if this is not your case then something must have gone wrong with the installation. You can check by running the following command: >gacutil -l system.net.http.formatting Microsoft (R) .NET Global Assembly Cache Utility. Version 4.0.30319.33440 Copyright (c) Microsoft Corporation. All rights reserved. The Global Assembly Cache contains the following assemblies: system.net.http.formatting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL Number of items = 1 For the deployment problem, please look at my previous post explaining the problem to @hammy, @afh I have to commend you on your effort here. So thank you. It's really one of those WTF moments for, well, probably thousands of devs out there and you're unfortunately (unfairly) probably going to hear it. Not your fault, but it is what it is. Hopefully there are lessons here for MSFT. • You can't afford another "dll hell" mark, it's already been mentioned (alas) and it'll probably reverberate…. • Worse, we (devs) don't want battles with IT on what Windows Updates should/shouldn't be installed, on which boxes, etc. • It damages efforts to decouple ASP.Net releases with framework and tooling releases – IINM, that's what NUGET brings to the table (and why ASP.Net latest is distributed/made available through it). Quoted from nuget.codeplex.com/…/4344 "Whether this is an MVC/WindowsUpdate or NuGet issue; someone needs to take responsibility for ensuring something is put in place to stop this happening again. If Microsoft starts breaking production apps with Windows Updates (which are typically done by ops teams, and shouldn't need dev teams to fix the resulting issues) it'll reduce the frequency at which they install Windows updates (or worse, they'll just have a bad impression of your platform and migrate away)." Thanks Miguell As VS becomes more and more abstract, it becomes more and more complex and riddled with bugs. Keep it simple and rock solid. We need to develop software, not spend all of our time working around issues in the development environment. Actually, on top of also being plagued by this security update, and having to pull my dev resources out of critical projects to re-stabilize our production web applications & development environment, I keep hearing about NuGet. We purposely extracted NuGet from our dev environment, because the last thing I want is for one of my developers to auto-magically get a new version of a dll, and deploy a build to production that might have required a significant QA test cycle to get re-certified. So please be mindful when recommending NuGet to the masses. Yes, NuGet can keep your dll's fresh, but can also easily introduce bugs during production app enhancements. NuGet is not the answer we are looking for – we need MS to be more diligent with their updates. My 2 cents… @danob7 nuget IS the answer you are looking for. You're just choosing to stick your head in the sand. There is nothing inherently different from nuget and add reference except the user experience is drastically better with nuget. Nuget is one of the best things Microsoft has done for .NET Where can one find a download for the MVC 3.0.1 tooling refresh for Visual Studio 2010? MVC 3.1 Tooling update:…/details.aspx Note that there's a known issue with NuGet 1.2 and 1.3, if you have one of these versions installed in the machine you need to remove it before installing the MVC 3.1 tooling update, then you can install the latest version of NuGet. Thanks Microsoft I spend all the morning to find out how to resolve this problem in all enterprise visual studio projects. I also had to replace the copy of the *System.Web.Mvc.dll* file in my project's *_bin_deployableAssemblies* folder. That "MVC 3.1 Tooling update" seems to be the same "ASP.NET MVC Tools Update" one from 3 years ago. How is it going to fix the MVC 3 templates that stop working in Visual Studio 2010 once the security patch is applied? @Sylvain Chamberland In fact it won't, it will avoid the problem for future development. After changing all references to MVC 3.0.0.1 I now have an issue with intellisense in my Razor views. It won't work anymore, very anoying! I've tried reinstalling the nuget package with no result. Reinstalling the MV 3 update, same result. Since the issue also appears on a different machine with the same project, I suspected the link to System.Web.WebPages.Razor could be broken (It's still on 1.0.0.0), but I can't seem to find the correct version. Any ideas? This issue has plagued me since I ran Windows Update on my development PC. Had to fix my project reference. Needed to debug on a server which skipped the update and had to locate the KBs and update the server manually. Our TeamCity build box couldn't run CI and needed to be patched. Our auto deployed test server couldn't run the application and needed to be patched. Then I find out nuget once again reset my references to CopyLocal = false after wonder why it once again wasn't running on our servers. I worked around this issue an entirely different way. I did the following: Go to: WindowsMicrosoft.NETassemblyGAC_MSILSystem.Web.Mvc Back up v4.0_4.0.0.1__31bf3856ad364e35 to BACKUP.v4.0_4.0.0.1__31bf3856ad364e35 Then I copied from a lucky co-worker's PC: v4.0_4.0.0.0__31bf3856ad364e35 Builds are happy again. Microsoft, your "solution" / "workaround" is entirely unacceptable. Sorry for the incomplete answer. That worked well for the compile, but at runtime, there's a binding redirect to the new version that no longer exists. That needs to be removed. To do that, merely: Rename: WindowsassemblyGAC_MSILpolicy.4.0.System.Web.Mvc4.0.0.1__31bf3856ad364e35 To: WindowsassemblyGAC_MSILpolicy.4.0.System.Web.MvcBACKUP.4.0.0.1__31bf3856ad364e35 I made an update as everyone else at the company, I have sadly made 3 repairs of my Visual studio installation and it feels like microsoft hell has come and visited me, first I couldn't make any C++ projects to build, but now I can't make any C#/MVC projects, while the C++ are working again. I'm kind of wondering if microsoft do know what they are doing or not. Really upset with this issue, I need to fix a bunch of project we have right now. Time is money what a bad update. The article says, . " Where is the "MVC 3.0.1 tooling refresh for Visual Studio 2010" Hi, We're having a strange issue. We have a couple of assemblies which are coming from a Nuget package "Microsoft.AspNet.WebApi.Client". These assemblies are not getting copied to production server when the deploy happens from TFS using MSBUILD. I have uninstalled thsi package and installed it again, checked the copy local flag=true, installed the latest version of nuget.exe to the Enable Package restore but nothing works. This is breaking my head as I think I have tried every thing but to no avail. Anybody any suggestions? Thanks, Venky Hi Friends, Just I have created one MVC application in my system. But am getting floods of exception (are you missing an assembly reference) while build my code. Can you please anyone guide me what I need to do to resolved this. Thanks in Advance.
https://blogs.msdn.microsoft.com/webdev/2014/10/16/microsoft-asp-net-mvc-security-update-ms14-059-broke-my-build/
CC-MAIN-2017-22
refinedweb
4,062
57.87
I have read every blog post and thread I can find on multiprocessing with arcpy and none of the fixes in them have fully addressed my problem. I'm trying to do a relatively simple watershed calculation using multiprocessing. The 'worker' function looks like this:? I'm trying to do a relatively simple watershed calculation using multiprocessing. The 'worker' function looks like this: def multi_watershed(pnts, branchID, flowdir, flowacc, scratchWks): direc = tempfile.mkdtemp(dir = scratchWks) # If called in a pll process, needs to write to seperate directories arcpy.env.scratchWorkspace = direc polylist = [] for i, p in enumerate(pnts): pnt = arcpy.PointGeometry(arcpy.Point(p.x, p.y, ID=i)) #Convert the shapely point to an arcpy point pourpt = sa.SnapPourPoint(pnt, flowacc, 1000) ws = sa.Watershed(flowdir, pourpt) out = os.path.join(direc, "pol_%i"%i) #Generate a filename for the output polygon arcpy.RasterToPolygon_conversion(ws, out) polylist.append(out) #Append the output file to the list to be returned res = (branchID, polylist) return res: def watershed_pll(data, flowdir, flowacc, tempfolder, proc=4): """ Calculate the watershed for each station point using parallel processing """ pool = Pool(processes = proc) jobs = [] for key, val in data.iteritems(): jobs.append(pool.apply_async(multi_watershed, (val, key, flowdir, flowacc, temp))) pool.close() pool.join() return jobs? Through spyder, but really the python console is a seperate process, so I doubt spyder is impacting anything. I run other operations using arcpy and multiprocessing with no problem - the difference there is that they are only calling one tool; here there are 3 or 4. My feeling is that arc is attempting to delete/move data inbetween operations that I haven't told it to....although I could be wrong. 1. Environments/folders getting mixed up. The input data is passed as complete filepaths to some raster datasets which are outside of the scratchWorkspace (which is set locally for each process) where intermediate/output data is created. However, I have noticed that Arc may make folders (typically and 'info' folder) in the directories of the input data. Why is that? Can it be prevented, or can I prevent Arc from then trying to delete it? 2. Are there any potential problems with accessing the input raster data sets at the same time? I.e each process will be attempting to open and read from the flow direction and flow accumulation rasters which are passed into the function. However, I have not solved the problem of why the issue occurred. My original 'worker' function called a number of arcpy commands in sequence: - first it converted a point to an arcpy point using Point and PointGeometry - It called the SnapPourPoint tool which output a temporary raster - It called the Watershed tool, which output another temporary raster - It called the RasterToPolygon_conversion tool to create a Polygon object I edited the original code so that the only tool used with parallel processing is the Watershed tool (which is most time consuming). The point conversion and snap pour point tool is called in its own loop separately and the results stored to disk. The watershed calculation is then performed using parallel processing and the resulting rasters stored to disk. The conversion is then performed in a loop on these results. Finally, all those intermediate files The parallel code now looks like this: It looks much bigger - there are now 3 loops instead of one. There is also a lot of dictionary formatting etc to preserve the results format/order for the next loop. This is all a bit more expensive, but happily, the watershed tool is by far the most time consuming and is parallelised. So there is still a significant speed up from single processing. Hopefully, the other 2 loops can also be parallelised independently to give another speed up... I'll look into that next. My only worry is that the intermediate files cannot be deleted each iteration as they need to be used in the next loop..this could potentially be a problem with big data.. I am also unsure what caused the initial problem in the first place, which would be good to know. Similar to you i had a nightmare trying to get scripts to complete correctly, they would often power through 200 rasters or so then simply stop for no reason... The solution i had determined in my case (with rasters) was that if i attempted to write the rasters all to the root folder then it would fail. Thus, i simply had each process generate a new folder with a number on the end which would then become the destination folder. After all my rasters had been processed you can then step through the folders and collect them all into a single merged file at the end. This was the only solution that i could find that worked. The other one was creating "in_memory" versions of the base data each time a process ran. You'll need to manage the data and make sure you delete the files created otherwise you'll run out of memory. I can toss the code up if that would be helpful.. This: and this: were also dead useful I was already generating a new workspace folder for each process so that is not the problem.. Unfortunately my solution above is not the total answer. I have found that for larger data, it will still fail, but usually with an ArcGIS error code stating that it is unable to execute the tool or something (will have to wait til monday to get the exact code). So there is still a problem somewhere... I couldn't debug when running asynchronously, i had to work the kinks of the code before then hope that the multi ran fine. Hi James and Cody I'm currently busy with my Masters Thesis where I'm developing a geostatistical monte carlo model (conditional sequential guassian simulation) to measure uncertainty within stream networks derived from DEM using Arc Hydro D8 algorithm. My simulation requires a 100 simulations of my study area using Arc Hydro. I'm looking to multi-process the Flow Direction and Flow Accumulation process, but battling to figure out how to cut up the DEM as the following processes require the entire dem to generate the flow direction and flow accumulation. Any ideas or advice would be appreciated. Regards Peter, Could you clarify the 100 simulations bit. Are they 100 different versions of the Flow Direction/Accumulation, or is there only one base Flow Direction/Accumulation that your GA model uses? Taking a guess, if your creating something that does flow direction/accumulation it would seem imperative that having the whole raster would be critical to determining the correct information for flow. My other guess would be if you could determine where the watersheds are in the area, and break it down into multiple smaller sections you could split the DEM that way potentially. Hard to say without having an understanding of the data though, so hopefully i can help more in a bit. Cheers. Hi Cody I'l try to explain the workflow of the Monte Carlo Simulation. The Monte Carlo simulation takes a raw hydrological DEM\DTM as input and using statistics generates a new DEM\DTM that represents error, by adjusting the elevation values. The following is repeated a certain amount o times, the more the better to produce a better probability distribution of the error. Each DEM\DTM that is produced from the Monte Carlo simulation is then processed using Arc Hydro Terrain Preprocessing to generate a stream network from the DEM. The Spatial Analyst Hydrology Tools are the same tools (i.e. Flow Direction ; Flow Accumulation ; Stream Definition). My simulation requires that I generate 1000 simulations to produce a new version of the stream network. The 1000 version of the stream network are then compared to quantify where the uncertainty\error is found within the DEM by how many times the stream network is the same for each version and where it differs due to the change in heights introduced by the simulation. The Flow Direction and Flow Acummulation processes are exceptionally computational and currently the tools don't make use of multiprocessing or the the additional memory available as part of the 64bit architecture. I'm looking for a way to split the DEM\DTM and process it using multiprocessing and stick it back together at the end of the process. As you mentioned if there was a way to identify the location of the catchments before hand one could split the DEM\DTM accordingly. Regards My answer at the moment would be to look elsewhere than arcpy/arcgis for numerical modelling. Perhaps arcobject would allow better control, but there are certainly faster algorithms out there that use less memory consumption than arc hydro's offerings. D8 algorithms are not hard to program yourself and you do not need to look at a 'whole raster' at once. D8 algorithms only look at 9 cells at a time - the current cell and it's neighbours. The difficulty is in how to manage edge cases. I did a quick example a while ago for work showing that with python/cython and gdal, you could process large rasters (in a format supported by gdal) far quicker than archydro does it by streaming 3 rows at a time and shipping these out to parallel processes.
https://community.esri.com/thread/89261-issues-with-multiprocessing-and-spatial-analyst
CC-MAIN-2018-43
refinedweb
1,562
60.75