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 reply to Re^2: What is the best way to compare variables so that different types are non-equal?in thread What is the best way to compare variables so that different types are non-equal? My question about overriding the type-blind behavior of eq (#2) was primarily a question about Perl idiom. Before I settled on a solution, I wanted a better understanding of the Perl syntax for handling various definitions of equality. I was also looking ahead to future coding scenarios. Part of good design is anticipating the environment around the design. Part of good testing is understanding exactly what one's test for equality is doing. Once I saw my mistake I was worried about what other magic and 'action at a distance' effects I need to consider when writing tests and developing algorithms that involve testing for equality. So wouldn't it be natural to construct a class "Node", with an overloaded "eq" operator? The code I'm testing is pretty well factored so the actual fix involves exactly two comparisons within a single subroutine. There isn't really a need for a global solution that will be "carried" with a "node object". Also the "node-i-ness" comes from the fact that the datum is part of larger structure, e.g. an array or a hash. It doesn't need an object wrapper to get that trait. If there is no ready-made Perl idiom I will probably have my subroutine call the subroutine below for its two comparisons. The subroutine mentioned above needs a definition of equality that duplicates unoverloaded eq, except for the added constraint that like must be compared to like: sub my_eq { # make sure we are comparing like to like my $xRef = ref($_[0]); return '' unless ($xRef eq ref($_[1])); # compare pure scalars and regex's using 'eq' # compare reference addresses for the rest return ($xRef and ($xRef ne 'Regexp')) ? (Scalar::Util::refaddr($_[0]) == Scalar::Util::refaddr($_[1])) : ($_[0] eq $_[1]); } [download] Best,.
http://www.perlmonks.org/?node_id=781494
CC-MAIN-2016-18
refinedweb
340
52.9
The Practical Client Peter turns the management of his single-page Backbone application over to Backbone itself by integrating Backbone Routers and Events. Plus: How to simplify your TypeScript code with longer namespaces. In my last few columns, I've looked at building a Backbone application with TypeScript and shown how to create a client-side Backbone Model that corresponds to a Customer object on my server (which, in turn, is created from data managed by Entity Framework). To bridge the gap from my server to the client, I use a Web API Web Service that returns several Customer objects when synced with the Backbone Collection that manages my Customer Models. I pass that Backbone Collection of Customers to two Backbone Views that work together to generate an HTML dropdown list (one View is responsible for the <select> element while the other View is responsible for generating an <option> tag for each Customer in the Collection). When my page is first loaded, however, I have quite a lot of code to get Backbone to retrieve the data, build the Models, populate the Collection with those Models and generate HTML from my Views. That code is shown in Listing 1. import som = require("SalesOrderModels"); import sov = require( "SalesOrderViews" ); import cms = som.CustomerModels; import cvs = sov.CustomerViews; import bb = Backbone; $(function () { var cl: cms.CustomerShortList; cl = new cms.CustomerShortList(); var cv: cvs.CustomersSelectView; cv = new cvs.CustomersSelectView(); cv.collection = cl; cv.$el = $("#Customers"); cl.fetch({ success: () => cv.render() }); }); That's a lot of code that would be required, with some variation, on any page where I use Backbone -- I'd prefer to centralize that code so I didn't need to duplicate it through my application's pages. Fortunately, Backbone provides a more integrated way of coordinating Backbone functionality: Routers and Events. This column will start to show how to use those tools with TypeScript. But, first, the usual caveat for this column: Before starting this project, I updated all of my NuGet packages in Visual Studio 2010. This time, I got new versions of the type definition files for jQuery and Backbone, plus an updated version of Require.js (this is definitely not something I'd do in a real, ongoing project). If you're trying this at home, different versions of these NuGet packages could give you different results. The Purpose of Routes If you've used routing in ASP.NET, you'll find defining routing for a Backbone Router looks familiar. In Backbone, a route consists of two parts: a template and a function name. When provided a URL, Backbone scans the list of routes, looking for a template that matches the URL. When Backbone finds a match, it calls the function through an Event (using Events allows a Router to notify any Backbone object about finding the match). Backbone templates, like routes in ASP.NET, also let you extract parameter values from the URL and assign those values to names, which you can use in your methods (see "Defining Templates" at the end of this article for more information about templates). When the user triggers a change to your page you can assign a URL to your page's current state and add that state to your browser's history. In a single page application, think of these URLs as internal "state URLs" rather than "page URLs" that cause you to get a new page from the server. If the user clicks the browser's Back button to retrieve one of these state URLs, the browser will navigate back to the current page's state rather than get a new version of the page. For example, if the user selects customer A123 from a dropdown list on a page named CustomerInfo.html, you would, using Backbone and the Web API, fetch customer A123's information and display it. Backbone will let you add this new state of your page to the browser's history with a URL that might look something like. When the user selects another customer (customer B456, for example), you would add that state to the history as. If, while looking at customer B456, the user hits the browser's Back button, the browser will navigate back to the pervious state,. Leveraging a Router This page state functionality is provided through the Backbone Router class. To create a Router in TypeScript, I first use import statements to reference those TypeScript files I need at compile time but not at runtime (in this case, those are the files containing the definitions of my Models and Views, which I've separated from their actual implementations). The import statements also establish prefixes (cms and cvs, in this case) that I'll use to reference those definitions in my code: import cms = som.CustomerModels; import cvs = sov.CustomerViews; My next step is to use import statements with the require method to tell Require to download to the browser those JavaScript files I need at runtime (the files with the JavaScript code that implements the definitions from my previous files): import som = require("SalesOrderModels"); import sov = require("SalesOrderViews"); I also set up a prefix to refer to Backbone itself (I use standard <script> tags in my HTML page to download the Backbone script file so I don't use the require function here): import bb = Backbone; For more on the import statement see my column on structuring TypeScript modules. I'm now ready to define my router by extending the Router class that comes with Backbone. I've decided to keep all of my routers in a file called CustomerRouters.ts and define this router in a separate module/namespace called CustomerRouters: export module CustomerRouters { export class CustomerSalesOrderRouter extends bb.Router { In the constructor for my class, I load the routes that I want to use on my page. For this example, I define just two routes. The first route has a template matching to a URL consisting of a single literal ("startState"); I tie that route to a method named initializeList. The second template matches to a two-part URL, where the first part of the URL is the string "customer," while the second part is a parameter called cust (whose values must be prefixed with the letters "cid"). I tie that template to a method called getCustomer: constructor() { this.routes = <any>{"startState" :"initializeList", "customer/cid:cust":"getCustomer" super(); } The call to the super is required by TypeScript in the constructor for any class that extends another class. In Backbone that call must follow any routes you've set up. Getting Work Done I'm now ready to set up event handlers for the events raised by the Router. I move the code that loads my dropdown list of customer names out of my start page and into my initializeList event handler. For this example, I'll handle the event through a function added to the router. Here's the code I added to my initializeList function (fired by the router matching a URL): initializeList() { var cl: cms.CustomerShortList; cl = new cms.CustomerShortList(); var cv: cvs.CustomersSelectView; cv = new cvs.CustomersSelectView(); cv.collection = cl; cv.$el = $( "#Customers" ); cl.fetch({success: () => cv.render()}); } For now, in my getCustomer event handler, I'll just display the value of the parameter that the template extracts from the URL. To have that value passed to my method, I just have to give my getCustomer method a parameter with the same name as the parameter in the template: getCustomer( cust: string ) { alert(cust); } Next month, I'll call this method when the user selects a customer from my dropdown list and enhance the method to do something useful. Triggering the Router But the reason that I started down this route was to reduce the code required to initialize my page. In my application's default page, I can leverage the code that I've wrapped up in my Router by calling the Router's navigate method. Prior to calling navigate, however, I have to start the Backbone history processing with this code: bb.history.start(); By default, the navigate method navigates to the required state URL, but it doesn't trigger the event associated with it. Fortunately, the navigate method accepts as its second parameter any object literal that corresponds to the Backbone NavigateOptions interface. That interface includes a trigger property that, when set to true, causes the navigate method to also raise the event associated with the URL and, as a result, execute the corresponding event handler. Here's the code that instantiates my Router, starts the Backbone history processing and calls the navigate method, passing the appropriate URL ("startState") and NavigateOptions: import sor = require( "SalesOrderRouters" ); import bb = Backbone; $(function () { var rtr: sor.CustomerRouters.CustomerSalesOrderRouter; rtr = new sor.CustomerRouters.CustomerSalesOrderRouter; bb.history.start(); rtr.navigate("startState", {trigger: true}); }); Using the navigate method also adds the resulting URL to my browser's history list (unless I suppress it). The address box for the browser now says. If I navigate to another site, either by typing in a new URL or selecting a bookmark, when I hit the browser's Back button I return to just as I left it and without re-executing my initializeList function. By the way: There are all sorts of good reasons why, when using the navigate method, you shouldn't trigger the processing associated with the URL. However, it makes sense (to me, at least) to use the trigger option when navigating to the "first state" of my application. This is much simpler code for starting off my application than the original version. However, TypeScript will let me cut down on some of the verbiage in this code even further by extending my sor prefix to include my CustomerRouters namespace, like this: import sr = require( "SalesOrderRouters" ); import sor = sr.CustomerRouters; import bb = Backbone; $(function () { var rtr: sor.CustomerSalesOrderRouter; rtr = new sor.CustomerSalesOrderRouter; bb.history.start(); rtr.navigate("startState", {trigger: true}); }); Next month, I'll start doing something more useful than just displaying a dropdown list by further integrating Routers and Events: When the user selects a customer from the list, my page will display information for that customer. It's baby steps, people. A Backbone template consists of three things: string literals, parameters and the forward slashes that separate them. By default, templates are matched to the part of the URL that follows a hash sign. While literals are used primarily to match URLs to the right template, parameters are used to extract data from a URL for your application to use. Parameters have names beginning with a colon (:) or an asterisk (*), or are enclosed by parentheses -- everything else (other than forward slashes) is a literal. A parameter that begins with a colon has its name set to the value between the forward slashes; a parameter beginning with an asterisk (a "splat" in Backbone talk) is set to all of the text in the URL beginning at that point in the template and up to the next literal or the end of the URL; a parameter that's enclosed in parentheses is optional. Matching Templates Given a URL, Backbone finds a matching template by looking at two things: the number of literals/parameters in the template and the literals themselves. For example, this template has three parts (two string literals -- "customer" and "salesinfo" -- and one parameter -- ":year"): customer/salesinfo/:year This template will match to any URL that has (following a hash sign), three parts where the first two parts are "customer" and "salesinfo." Whatever is in the third part will be used to assign a value to the parameter called "year." Backbone would match that template to this URL, for example, and set the year parameter to 1989: You can also specify that a parameter begin with specific text by preceding the parameter's colon with the text of the prefix. For example, this template specifies that the year parameter must begin with the letters "yr": customer/salesinfo/yr:year Backbone would match that template to a URL like this, setting the year parameter to 2012: CustomerInfo.html#customer/salesinfo/yr2012 >Optional Parameters and Splats This template uses parentheses around the parameter to indicate that if the URL has only two parts (the two literals), then the template will still match: customer/salesinfo/(:year) With this template, the year parameter will be set to null (not undefined) if no third part is provided in the URL. If you include a trailing slash in your template, the corresponding slash must be present in the URL to match. This template includes a trailing slash, for example: customer/salesinfo/:year/ As a result, the template will match to the first of these two URLs, but not the second: If you can't count on your application or the user generating that final slash, you can make it optional by enclosing it in parentheses: customer/salesinfo/1989(/) The following example uses a splat to create a template that will match to a URL with any number of parts, provided that part of URL after the hash begins with the literal "customer": customer/*custStuff Both of the following URLs begin with "customer" and, because of the splat in the template, the number of parts in each URL after the "customer" literal is irrelevant. As a result, both of these URLs will match to my "splatted" template: For the second URL, the custStuff parameter will be set to "salesinfo/1989". While splats are, effectively, always optional, some care is required to match a URL that omits the splat. For example, the following template includes a forward slash after the customer id and before the splat: customer/cid:cust/*custStuff This URL will not match to my splatted template because it doesn't have a trailing slash required by the template following the customer id: Adding the trailing slash does produce a URL that matches to the template: Alternatively, you could alter the template to make the slash before the splat optional: "customer/cid:cust(/)*custStuff" You can follow a splat with more parameters provided you mark the end of the "splatted area" with a literal. This template uses the literal "report" to mark the end of the splat *years and then accepts another parameter (:report) following the literal: customer/cid:cust/*years/report/:reportType Here's a URL that would match to that template: For this example, the cust parameter will be set to "A123," the years splat to "1980/1985/1990," and the reportType parameter to "sales." One warning: While optional parameters and splats give you a great deal of flexibility, the more splats and optional parameters you use in a template, the more difficult it will become to determine to which URLs your templates will be matched. If you're confident that all of your users are using browsers that support HTML5, then you can eliminate the need for the hash mark when starting the Backbone URL processing by setting the pushState option to true, like this: Backbone.history.start({ pushState: true }) However, the impact on your routes and your code isn't necessarily trivial (none of my examples would work with pushState set to true, for
https://visualstudiomagazine.com/articles/2014/08/01/backbone-routers.aspx
CC-MAIN-2020-50
refinedweb
2,525
56.39
This Flask app tutorial will guide you through the process of localizing Flask applications using Flask-Babel and Phrase. Flask-Babel is a Flask extension that adds internationalization (i18n) and localization (l10n) support to any Flask application. Phrase is a translation management tool that features a powerful in-context-editor, making the process of translating more convenient. Let’s begin by installing the required dependencies: pip install Flask-Babel This will install Flask-Babel, aswell as the pybabel command-line tool. Next, import Flask-Babel and hook it to your app like so: from flask import Flask, [...] from flask.ext.babel import Babel, gettext app = Flask(__name__) babel = Babel(app) In your configuration, add a dictionary named LANGUAGES. In this example, we add two locales, english (‘en’) and german (‘de’). # add to your app.config or config.py file LANGUAGES = { 'en': 'English', 'de': 'Deutsch' } We will use this dictionary for a little helper function that Babel offers: # add to you main app code @babel.localeselector def get_locale(): return request.accept_languages.best_match(app.config['LANGUAGES'].keys()) This convenient tool will automatically choose the best matching locale, based on the Accept-Language header from the incoming request. Hint: for testing purposes, you can directly return a language code, for example: return ‘de’ One more thing! Create a config file for Babel. We will chew through the details later on, but for now, simply create a file named babel.cfg in the top-level directory of you app: [python: **.py] [jinja2: **/templates/**.html] extensions=jinja2.ext.autoescape,jinja2.ext.with_ Tagging Strings Now it’s time to tag all the Strings you want to translate. In a typical Flask app, there will be two types of Strings that require translating. One being hard-coded Strings in your .py files, the other being Strings in your .html Jinja2 templates. Tag them by adding a gettext(‘String’) call to them, like so: slogan = 'This app is awesome.' flash('Login failed') becomes slogan = gettext('This app is awesome.') flash(gettext('Login failed')) For your Jinja2 templates, this is also very straightforward, for example: <b>Free Trial</b> <input type="submit" value="Sign up"/> becomes <b>{{ gettext('Free Trial') }}</b> <input type="submit" value="{{ gettext('Sign up') }}"/> Hint: you can use _() as a shortcut for gettext(). Note that the english string is also the key (msgid) that gettext will use for when looking up the corosponding Translation value (msgstr). Building Locales When all strings are tagged, it is time to build a catalog for the Locales we want to create. Run: pybabel extract -F babel.cfg -o messages.pot This checks all files specified in babel.cfg and searches thru them to find tagged strings and outputs them to messages.pot. Next, run: pybabel init -i messages.pot -d translations -l de This will use the index from messages.pot to build a german (‘de’) locale in our translations directory. Don’t worry, if the directory doesn’t exist yet, pybabel will create it for you. Finally it is time to translate the Strings. With your favorite text editor, open ‘translations/de/LC_MESSAGES/messages.po’. You can now start translating the msgstr values. When you are done editing, there is only one step left, compile all .po files in your translation directory: pybabel compile -d translations Done! Start playing around with your app. Remember, the locale is chosen based on the Accept-Language Header that is being sent by your Browser. Check out our full Flask-Babel example app, a modified version of Flaskr, the official Flask demo app. Explore why app translation can be key to your global business expansion and follow our best practices. Explore why app translation can be key to your global business expansion and follow our best practices.Check out the guide Get Translations With Phrase Phrase provides tools for software translation management. Its WYSIWYG In-Context Editor (Demo) enables you and your copywriters or translators to change translations on your website in any web browser. Let’s integrate the In-Context Editor in our example from above. In order to expose your tagged Strings to the In-Context-Editor, we will be using the Flask-Phrase, a package that you can install via: pip install Flask-Phrase Next, we hook our app to Flask-Phrase and import the gettext provided by Flask-Phrase. Extending the example from above, this would look like this: from flask import Flask, [...] from flask.ext.babel import Babel from flask_phrase import Phrase, gettext app = Flask(__name__) babel = Babel(app) phrase = Phrase(app) Hint: the gettext provided by flask_phrase will simply proxy the call to Flask-Babel when not in editing mode. Next, add the following to your Flask app config: # add to your app.config or config.py file PHRASEAPP_ENABLED = True PHRASEAPP_PREFIX = '{{__' PHRASEAPP_SUFFIX = '__}}' Almost done. In your .html Jinja2 templates, add this JavaScript snippet along with the Project-ID that can be found in the Phrase> That’s it. Make sure PHRASEAPP_ENABLED is set to ‘True’ so that your strings will be rendered in a special format for the Phrase editor. Check out our full example app with Flask-Babel and Phrase built in. Hint: Need support integrating Phrase? Feel free to contact us any time.!
https://phrase.com/blog/posts/python-localization-flask-applications/
CC-MAIN-2020-50
refinedweb
873
66.33
NAS Visualization (Experimental)¶ Built-in Trainers Support¶ Currently, only ENAS and DARTS support visualization. Examples of ENAS and DARTS has demonstrated how to enable visualization in your code, namely, adding this before trainer.train(): trainer.enable_visualization() This will create a directory logs/<current_time_stamp> in your working folder, in which you will find two files graph.json and log. You don’t have to wait until your program finishes to launch NAS UI, but it’s important that these two files have been already created. Launch NAS UI with nnictl webui nas --logdir logs/<current_time_stamp> --port <port> Visualize a Customized Trainer¶ If you are interested in how to customize a trainer, please read this doc. You should do two modifications to an existing trainer to enable visualization: - Export your graph before training, with vis_graph = self.mutator.graph(inputs) # `inputs` is a dummy input to your model. For example, torch.randn((1, 3, 32, 32)).cuda() # If your model has multiple inputs, it should be a tuple. with open("/path/to/your/logdir/graph.json", "w") as f: json.dump(vis_graph, f) - Logging the choices you’ve made. You can do it once per epoch, once per mini-batch or whatever frequency you’d like. def __init__(self): # ... self.status_writer = open("/path/to/your/logdir/log", "w") # create a writer def train(self): # ... print(json.dumps(self.mutator.status()), file=self.status_writer, flush=True) # dump a record of status If you are implementing your customized trainer inheriting Trainer. We have provided enable_visualization() and _write_graph_status() for easy-to-use purposes. All you need to do is calling trainer.enable_visualization() before start, and trainer._write_graph_status() each time you want to do the logging. But remember both of these APIs are experimental and subject to change in future. Last but not least, invode NAS UI with nnictl webui nas --logdir /path/to/your/logdir Limitations¶ - NAS visualization only works with PyTorch >=1.4. We’ve tested it on PyTorch 1.3.1 and it doesn’t work. - We rely on PyTorch support for tensorboard for graph export, which relies on torch.jit. It will not work if your model doesn’t support jit. - There are known performance issues when loading a moderate-size graph with many op choices (like DARTS search space). Feedback¶ NAS UI is currently experimental. We welcome your feedback. Here we have listed all the to-do items of NAS UI in the future. Feel free to comment (or submit a new issue) if you have other suggestions.
https://nni.readthedocs.io/en/v1.6/NAS/Visualization.html
CC-MAIN-2022-05
refinedweb
416
51.24
Source: react design patterns and best practices By Michelle Bertolli Publication time: the first edition in August 2018 (still new) Use react refetch to simplify the api's code for getting data const List = ({data: gists}) => { return ( <ul> {gists.map(gist => ( <li key={gist.id}>{gist.description}</li> ))} </ul> ) } const withData = url => Part => { return class extends Component { state = {data: []} componentDidMount() { fetch(url) .then(response => response.json ? response.json() : response) .then(data => this.setState({data})) } render() { return <Part {...this.state} {...this.props} /> } } } const ListWithGists = withData('')(List) In the above code, we use high-level components to extract the logic of api data acquisition. Next, we use react refetch to simplify the above asynchronous code import { connect as refetchConnect } from 'react-refetch' const List = ({gists}) => { if (gists.pending) { return <div>loading...</div> } else if (gists.rejected) { return <div>{gists.reason}</div> } else if (gists.fulfilled) { return ( gists.fulfilled && <ul> {gists.value.map(gist => ( <li key={gist.id}>{gist.description}</li> ))} </ul> ) } } const ListWithGists = refetchConnect(() => ({gists: ``}))(List) In a moment, it's much more refreshing. By the way, using the properties provided by react refetch, the loading logic is also added Separation of list and project responsibilities Obviously, List component is a component of rendering List. Its duty is to render List. But we also deal with the logic of single Item here. We can separate the duty of List component from List component, while Gist only renders itself const Gist = ({description}) => ( <li> {description} </li> ) const List = ({gists}) => { if (gists.pending) { return <div>loading...</div> } else if (gists.rejected) { return <div>{gists.reason}</div> } else if (gists.fulfilled) { return ( gists.fulfilled && <ul> {gists.value.map(gist => <Gist key={gist.id} {...gist} />)} </ul> ) } } Use react refetch to add functionality to Gist The connect method of react refetch receives a function as a parameter, which returns an object. If the value of the result object is a string, after obtaining the prop, a request will be made for the string. However, if the value is a function, it will not be executed immediately, but will be passed to the component for subsequent use Value is string const connectWithStar = refetchConnect(() => ({gists: ``})) //Value as function const connectWithStar = refetchConnect(({id}) => ({ star: () => ({ starResponse: { url: `{id}/star?${token}`, method: 'PUT' } }) })) const Gist = ({description, star}) => ( <li> {description} <button onClick={star}>+1</button> </li> ) //After processing the Gist component, the star function will be passed to the prop of Gist, and then it can be used in Gist connectWithStar(Gist)
https://programmer.group/a-small-example-of-use-of-react-refetch.html
CC-MAIN-2020-40
refinedweb
408
50.84
What is an abstract class? Why do we do implements at times and extends at times when writing java servlets? What is the difference between these 2? Why do we do public interface .... and public class ... What does interface and class stand for here? Whoa dude...you need to read up on some JAVA BASICS. An abstract class in defined like this: public abstract class MyClass{ } It is just like any other class EXCEPT that you can't create objects from abstract classes. You can only create objects of it's subclasses which 'extend' an abstract class. WHY, have abstract classes? Well, it is used to FORCE the programmers that want to use the abstract class to use certain methods in the subclasses that wanna extend an abstract class. These methods are defined like so, which are inthe abstract class: public abstract void myAbstractMethod(); Just like that...looks strange does it? Where's the { blah; blah; code to use in this method?;} (IE it is missing the curly braces) Hehehe well an abastract method is NOT used in the abstract class, they are used and DEFINED in the subclasses that inheriate them. The subclasses HAVE TO empliment ALL abstract methods of an abstract class or you will get a compile error. Hence, FORCING a certain code structure. Abstract methods MUST be public since all abstract methods in an abstract class that a SUBclass extends MUST be implemented, or an error happends. implements keyword is related to interfaces. An interface is kinda like a very EXTREME abstract class and is defined like so: public interface MyCrap(){} interface is a CLASS but, no class keyword is used. An interface is like an abstract class, except an interface can ONLY have abstract methods. An abstract Class can have BOTH regular methods AND abstract methods. You, cant instantiate an interface. YOu have to create subclasses (ie implement) or (same thing as extend but they decided to make it clear you where extending an interface so they called it implements) You like in an abstarct class MUST implement ALL the methods in an interface. There fore all methods are abstract by default. Think of it as a working template and these parts MUST be used in order for a certain operation to work. "Manika" <manika@mailexcite.com> wrote: > >What
http://forums.devx.com/showthread.php?26961-Abstract-class&p=60330
CC-MAIN-2014-52
refinedweb
384
74.19
Odoo Help This community is for beginners and experts willing to share their Odoo knowledge. It's not a forum to discuss ideas, but a knowledge base of questions and their answers. How do I create a field with a running count? In the product.product module, I wish to create a field (or edit an existing field) which displays an unique numeric value for each product. I want the module to automatically keep count and suggest the next number in the series. For instance, when I create a new product, I want the field to be automatically assigned the number '20000', and when I create the next product the number '20001' etc. Is there an easy way to handle this? Hello philjun, Here you go! You need to follow these two steps. Solution : 1 (In this solution your sequence field will be editable) Step1 : Add sequence record in your module. <!-- Record for your seuqence type --> <record id="your_custom_sequence_type" model="ir.sequence.type"> <field name="name">Label of your sequence code.</field> <field name="code">test.test.code</field> <!-- Unique sequence code.--> </record> <!-- Record for Sequence--> <record id="student_reg_sequence" model="ir.sequence"> <field name="name">Student Unique ID</field> <field name="code">test.test.code</field> <!-- Apply the same you applied above--> <field name="prefix">%(year)s/</field> <!-- optional--> <field name="suffix">%(month)s/</field> <!-- optional--> <field name="number_next_actual">20000</field> <!-- optional, if you not add this field by default 1 will be starting no. --> <field name="padding">5</field> <!-- optional--> <field name="implementation">no_gap</field> </record> Step 2: Add field in your model, in your case product is model _inherit = 'product.product' _columns = { 'sequence':fields.char("Sequence") } _defaults = { 'sequence':lambda self, cr, uid, context:self.pool.get('ir.sequence').get(cr, uid, 'test.test.code'), } Solution : 2 (If you want to make your sequence field readonly than you can follow this solution.) Step 1 : This is same as Solution 1. Step 2 : # inherit model and addd field with readonly attribute _inherit = 'product.product' _columns = { 'sequence':fields.char("Sequence", readonly=True) } def generate_sequence(self, cr, uid, ids, context=None): # This line will generate next sequence number from your seuqence. next_seq = self.pool.get('ir.sequence').get(cr, uid, 'test.test.code') self.write(cr, uid, ids, {'sequence':next_seq}, context=context) return True Step 3: add button in product form <button name="generate_sequence" type="object" string="Generate Sequence"/> There are many more option to create sequence these two solution will satisfied your needs. Hope this will helps you. Regards Anil Kesariya The sequence incrementing 2 ,4 ,6,etc.. .I want to generate 1 ,2 ,3 etc..Then How to change this code Also one more problem is if I am not saving any record its incremented automatically to next id . check you have applied : no_gap Once the sequence is generated is will always move to next sequence, so choose the second option generate it on button click and hide the button once it is generated. Here What is the excecution flow and what is the use of test.test.code means it is sequence code, you can give any name here, make sure that code is unique not used for any other sequence. Thank you, Anil. I have done as specified in option 1, except that I have added the code to the existing product module rather than creating a new module. I have added the field and the default setting to the product.py file. Regarding step 1, adding the sequence record to the module, I have created the file product_sequence.xml with the xml-code you specified, placed the file in the Product-module-folder, and added this file in the 'data' section of the __openerp__.py-file pertaining to the Product-module. Is it necessary to do something else to add the sequence record? In any case, my sequence is still, Nimesh. Do you know if there is a guide to creating and assigning sequences?
https://www.odoo.com/forum/help-1/question/how-do-i-create-a-field-with-a-running-count-72390
CC-MAIN-2016-50
refinedweb
657
59.5
Radio¶ Interaction at a distance feels like magic. Magic might be useful if you’re an elf, wizard or unicorn, but such things only exist in stories. However, there’s something much better than magic: physics! Wireless interaction is all about physics: radio waves (a type of electromagnetic radiation, similar to visible light) have some sort of property (such as their amplitude, phase or pulse width) modulated by a transmitter in such a way that information can be encoded and, thus, broadcast. When radio waves encounter an electrical conductor (i.e. an aerial), they cause an alternating current from which the information in the waves can be extracted and transformed back into its original form. Layers upon Layers¶ If you remember, networks are built in layers. The most fundamental requirement for a network is some sort of connection that allows a signal to get from one device to the other. In our networking tutorial we used wires connected to the I/O pins. Thanks to the radio module we can do away with wires and use the physics summarised above as the invisible connection between devices. The next layer up in the network stack is also different from the example in the networking tutorial. With the wired example we used digital on and off to send and read a signal from the pins. With the built-in radio on the micro:bit the smallest useful part of the signal is a byte. Bytes¶ A byte is a unit of information that (usually) consists of eight bits. A bit is the smallest possible unit of information since it can only be in two states: on or off. Bytes work like a sort of abacus: each position in the byte is like a column in an abacus - they represent an associated number. 0 and 255. The image below shows how this works with five bits and counting from zero to 32: If we can agree what each one of the 255 numbers (encoded by a byte) represents ~ such as a character ~ then we can start website. Addressing¶ The problem with radio is that you can’t transmit directly to one person. Anyone with an appropriate aerial can receive the messages you transmit. As a result it’s important to be able to differentiate who should be receiving broadcasts. The way the radio built into the micro:bit solves this problem is quite simple: - thing is you don’t need to worry about filtering those out. Nevertheless, if someone were clever enough, they could just read all the wireless network traffic no matter what the target address/group was supposed to be. In this case, it’s essential to use encrypted means of communication so only the desired recipient can actually read the message that was broadcast. Cryptography is a fascinating subject but, unfortunately, beyond the scope of this tutorial. Fireflies¶ This is a firefly: It’s a sort of bug that uses bioluminescence to signal (without wires) to its friends. Here’s what they look like when they signal to each other: The BBC have rather a beautiful video of fireflies available online. We’re going to use the radio module to create something akin to a swarm of fireflies signalling to each other. First import radio to make the functions available to your Python program. Then call the radio.on() function to turn the radio on. Since the radio draws power and takes up memory we’ve made it so you decide when it is enabled (there is, of course a radio.off() function). At this point the radio module is configured to sensible defaults that make it compatible with other platforms that may target the BBC micro:bit. It is possible to control many of the features discussed above (such as channel and addressing) as well as the amount of power used to broadcast messages and the amount of RAM the incoming message queue will take up. The API documentation contains all the information you need to configure the radio to your needs. Assuming we’re happy with the defaults, the simplest way to send a message is like this: radio.send("a message") The example uses the send function to simply broadcast the string “a message”. To receive a message is even easier: new_message = radio.receive() As messages are received they are put on a message queue. The receive function returns the oldest message from the queue as a string, making space for a new incoming message. If the message queue fills up, then new incoming messages are ignored. That’s really all there is to it! (Although the radio module is also powerful enough that you can send any arbitrary type of data, not just strings. See the API documentation for how this works.) Armed with this knowledge, it’s simple to make micro:bit fireflies like this: # The import stuff happens in the event loop. First, it checks if button A was pressed and, if it was, uses the radio to send the message “flash”. Then it reads any messages from the message queue with radio.receive(). If there is a message it sleeps a short, random period of time (to make the display more interesting) and uses display.show() to animate a firefly flash. Finally, to make things a bit exciting, it chooses a random number so that it has a 1 in 10 chance of re-broadcasting the “flash” message to anyone else (this is how it’s possible to sustain the firefly display among several devices). If it decides to re-broadcast then it waits for half a second (so the display from the initial flash message has chance to die down) before sending the “flash” signal again. Because this code is enclosed within a while True block, it loops back to the beginning of the event loop and repeats this process forever. The end result (using a group of micro:bits) should look something like this:
https://microbit-micropython-hu.readthedocs.io/hu/latest/tutorials/radio.html
CC-MAIN-2019-30
refinedweb
993
61.56
Hi, I am new to EJBs and JBoss and was wondering if I can call an EJB's local method from a non-EJB Java class. When I try to do it I keep getting the error message like ' not bound' even though I am including the EJB in the deployment file (an ear). You must explicitly identify ejb-refs when one EJB calls another, but what do you do if a non-EJB calls an EJB? Any thoughts would be appreciated. Thanks! Local calls can only be done in the same server. I thonk that means the place where the ejb's live. A local java class is not there. So only the remote stuff will work. grt Patrick Outside of the deployment package of the EJB (an ear in your case), but inside the Application Server, you can lookup the local home in global jndi. By default it is bound at local/<ejb-name> or <local-jndi-name> in jboss.xml to override. Regards, Adrian I finally figured out exactly what you said, I needed to use the name the bean was bound to in the global JNDI namespace (as seen in the JNDI view web page). Thanks for the feedback. I'm cooking now!
https://developer.jboss.org/thread/73902
CC-MAIN-2018-17
refinedweb
207
82.65
I have an application that writes information to file. This information is used post-execution to determine pass/failure/correctness of the application. I'd like to be able to read the file as it is being written so that I can do these pass/failure/correctness checks in realtime. I assume it is possible to do this, but what are the gotchas involved when using Java. If the reading catches up to the writing, will it just wait for more writes up until the file is closed? or will the read throw an exception at this point and then what do I do? My intuition is currently pushing me towards BufferedStreams. Is this the way to go? views:2680 answers:5 Not Java per-se, but you may run into issues where you have written something to a file, but it hasn't been actually written yet - it might be in a cache somewhere, and reading from the same file may not actually give you the new information. Short version - use flush() or whatever the relevant system call is to ensure that your data is actually written to the file. Note I am not talking about the OS level disk cache - if your data gets into here, it should appear in a read() after this point. It may be that the language itself caches writes, waiting until a buffer fills up or file is flushed/closed. I've never tried it, but you should write a test case to see if reading from a stream after you have hit the end will work, regardless of if there is more data written to the file. Is there a reason you can't use a piped input/output stream? Is the data being written and read from the same application (if so, you have the data, why do you need to read from the file)? Otherwise, maybe read till end of file, then monitor for changes and seek to where you left off and continue... though watch out for race conditions. The answer seems to be "no" ... and "yes". There seems to be no real way to know if a file is open for writing by another application. So, reading from such a file will just progress until content is exhausted. I took Mike's advice and wrote some test code: Writer.java writes a string to file and then waits for the user to hit enter before writing another line to file. The idea being that it could be started up, then a reader can be started to see how it copes with the "partial" file. The reader I wrote is in Reader.java. Writer.java public class Writer extends Object { Writer () { } public static String[] strings = { "Hello World", "Goodbye World" }; public static void main(String[] args) throws java.io.IOException { java.io.PrintWriter pw = new java.io.PrintWriter(new java.io.FileOutputStream("out.txt"), true); for(String s : strings) { pw.println(s); System.in.read(); } pw.close(); } } Reader.java public class Reader extends Object { Reader () { } public static void main(String[] args) throws Exception { java.io.FileInputStream in = new java.io.FileInputStream("out.txt"); java.nio.channels.FileChannel fc = in.getChannel(); java.nio.ByteBuffer bb = java.nio.ByteBuffer.allocate(10); while(fc.read(bb) >= 0) { bb.flip(); while(bb.hasRemaining()) { System.out.println((char)bb.get()); } bb.clear(); } System.exit(0); } } No guarantees that this code is best practice. This leaves the option suggested by Mike of periodically checking if there is new data to be read from the file. This then requires user intervention to close the file reader when it is determined that the reading is completed. Or, the reader needs to be made aware the content of the file and be able to determine and end of write condition. If the content were XML, the end of document could be used to signal this. You might also take a look at java channel for locking a part of a file. This function of the FileChannel might be a start lock(long position, long size, boolean shared) An invocation of this method will block until the region can be locked Could not get the example to work using FileChannel.read(ByteBuffer) because it isn't a blocking read. Did however get the code below to work: boolean running = true; BufferedInputStream reader = new BufferedInputStream( new FileInputStream( "out.txt" ) ); public void run() { while( running ) { if( reader.available() > 0 ) { System.out.print( (char)reader.read() ); } else { try { sleep( 500 ); } catch( InterruptedException ex ) { running = false; } } } } Of course the same thing would work as a timer instead of a Thread, but I leave that up to the programmer. I'm still looking for a better way, but this works for me for now. Oh, and I'll caveat this with: I'm using 1.4.2. Yes I know I'm in the stone ages still.
http://ansaurus.com/question/4149-how-do-i-use-java-to-read-from-a-file-that-is-actively-being-written
CC-MAIN-2020-50
refinedweb
812
72.66
Delete a File in C# This tutorial will introduce methods to delete a file at a specific path in C#. Delete a File With the File.Delete(path) Function in C The File.Delete(path) function is used to delete the file inside the path path in C#. The following code example shows us how to delete a file from a specified path with the File.Delete() function in C#. using System; using System.IO; namespace check_whether_a_file_exists { class Program { static void Main(string[] args) { string path = "C:\\filefolder\\file.txt"; bool result = File.Exists(path); if (result == true) { Console.WriteLine("File Found"); File.Delete(path); Console.WriteLine("File Deleted Successfully"); } else { Console.WriteLine("File Not Found"); } } } } Output: File Found File Deleted Successfully We deleted a file inside the C:\\filefolder\\file.txt path with the File.Delete() function in C#. Our program first checks whether a file exists inside the path or not with the File.Exists() function. If the file exists, the program deletes the file with the File.Delete() function. If the file does not exist, the program displays File Not Found. Contribute DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.
https://www.delftstack.com/howto/csharp/delete-file-in-csharp/
CC-MAIN-2021-25
refinedweb
220
70.09
There. Here is list of 4 different ways I am aware of converting Character to String in Java , most of them are quite easy and doesn’t require much code but these Java examples are very helpful if you are new in Java programming. 4 ways to convert Char to String in Java Character to String Example 1: Character.toString Character class provides a convenient toString() method which takes a character and return its String equivalent. toString() is static method in Character class and can be accessed using class name like Character.toString(). here is an example of converting char to String using Character.toString(): char ch = 'U'; String charToString = Character.toString(ch); Character to String Example 2: String concatenation operator In Java + can be used to concatenate String but it can also concatenate an String and a character and can result another String. This is another shortcut you can use to convert Character into String in Java. here is an example of converting character to String in Java: char ch = 'U'; String str = "" + ch; Character to String Example 3: using Anonymous Array Anonymous array in Java can be used to wrap a single character into a char array and than passing that array into String constructor. a new String will be created from that character. see below for char to String example in Java: char ch = 'U'; String fromChar = new String(new char[]{ch}); Character to String Example 4: using String.valueOf() String.valueOf() is another neat and clean way of converting character into String in Java. I like this method because its simple and straightforward or I say neat and clear. see following character to String conversion example in Java char ch = 'U'; String valueOfchar = String.valueOf(ch); Code Example of Converting Char to String in Java This section contains complete code example of converting char to String in Java by using all four methods mentioned above. In my experience concatenation operator seems to be most popular but Character.toString() or String.valueOf() is my favorite way of converting a character to String object in java. public class CharToStringExample { public static void main(String args[]) { char ch = 'U'; // char to string using Character class String charToString = Character.toString(ch); System.out.println("Converting Char to String using Character class: " + charToString); // char to String using String concatenation String str = "" + ch; System.out.println("Converting Char to String using String concatenation: " + str); // char to String using anonymous array String fromChar = new String(new char[] { ch }); System.out.println("Converting Char to String using anonymous array: " + fromChar); // char to String using String valueOf String valueOfchar = String.valueOf(ch); System.out.println("Converting Char to String using String valueOf: " + valueOfchar); } } Output: Converting Char to String using Character class: U Converting Char to String using String concatenation: U Converting Char to String using anonymous array: U Converting Char to String using String valueOf: U That’s all on how to convert Char to String in Java with four different examples. For many of us its trivial operation but for many beginners its quite helpful know various ways to change character into String. Other Java String tutorial you may find interesting 4 comments : Character.toString() is the best option for converting character to String into Java. if you want to convert character array to String than you can directly pass that to String Constructor as: char[] cArray = {'a','b','c'}; System.out.println("Char array to String Java Example: " + new String(cArray)); Character.toString(ch) references String.valueOf(ch) The concatenation method is very useful when the .toString method is not available to you. Thanks for reminding me about this. I learned how to concatenate but forgot how to do so. Thank u very much.This blogspot is very useful to me.I learned character to string conversion.
http://javarevisited.blogspot.com/2012/02/how-to-convert-char-to-string-in-java.html?showComment=1403178215311
CC-MAIN-2015-35
refinedweb
634
54.93
Node.js built-in modules famously are not promise-based. This is for historical reasons, as those modules were created before promises were a thing. We’ve had promisify for quite some time, but I recently found out Node.js provides a new API that’s promise-based. I thought it was new but it’s been introduced in Node.js 10 (2018, it’s been a while!). At the moment it only works for the fs built-in module. I’m not sure if this will be ported to other native modules soon. Here’s how to use it: import * as fs from 'node:fs/promises'; | Note the node:fs convention which can be now used to identify native modules Now you can use any of the fs methods using promises or await: const posts = await fs.readdir('content') Download my free Node.js Handbook!
https://flaviocopes.com/node-fs-await/
CC-MAIN-2022-27
refinedweb
146
75.5
It's sometimes desirable to have a suexec-ed CGI script read a custom environment variable to find out what it is supposed to do. I described my scenario, where a CGI script needed to know which of three RewriteRules called it, at: The problem is that, for good security reasons, suexec strips out all environment variables except for a whitelist consisting of standard ones set by the Web server. I would like a safe, supported convention for passing custom environment variables. (I can stuff them in the HTTP_ namespace, but that's a hack.) Furthermore, internal redirects should not break the convention. The obvious solution is to allocate a new namespace. I previously suggested CGI_, but now I'm thinking SUEXEC_ may be better. REDIRECT_SUEXEC_ vars could either be passed through or renamed to SUEXEC_REDIRECT_ . An interesting additional possibility would be to prepend SUEXEC_ to unsafe variables instead of dropping them; this way, the entire environment would be available to suexec-ed CGI scripts (but not in a form that could subvert them) without any extra work on the Apache side. Seconded. This really is a feature request rather than a bug, so I'm updating the version to reflect head.
https://bz.apache.org/bugzilla/show_bug.cgi?id=46644
CC-MAIN-2020-16
refinedweb
202
60.04
Parsley and APEXsect55 Aug 4, 2014 12:26 PM 1. Re: Parsley and APEXfac586 Aug 4, 2014 12:40 PM (in response to sect55) sect55 wrote: And? 2. Re: Parsley and APEXAquaNX4 Aug 4, 2014 1:43 PM (in response to sect55) If I understand you correctly: - Go to the page where the form resides. - Edit the region of the form. - Place the following in the region header: <script src="jquery.js"></script> <script src="parsley.min.js"></script> <script type="text/javascript"> $('#form').parsley(); </script That should work.. Aqua 3. Re: Parsley and APEXsect55 Aug 4, 2014 1:54 PM (in response to fac586) Fac586, I saved the scripts in the static files and included the scripts in the HTML header: <script src="#WORKSPACE_IMAGES#parsley.min.js"></script> <script src="#WORKSPACE_IMAGES#validator.js"></script> I issued the following in the when page load: $(function() { $(form).attr(id,'form'); $('#form').parsley(); }) This did not work. Robert 4. Re: Parsley and APEXsect55 Aug 4, 2014 1:57 PM (in response to AquaNX4) Thanks for you reply, but... The form has three regions so where should I place it. Also, jquery.js is already defined in APEX. Shouldn't be in the HTML header instead? Robert 5. Re: Parsley and APEXfac586 Aug 4, 2014 2:08 PM (in response to sect55) sect55 wrote: I issued the following in the when page load: $(function() { $(form).attr(id,'form'); $('#form').parsley(); }) Why did you do this? APEX generates one form per page with an ID attribute value of wwvFlowForm: <form action="wwv_flow.accept" method="post" name="wwv_flow" id="wwvFlowForm" novalidate > Have you tried using this existing ID in the selector? This did not work. "Did not work" how? 6. Re: Parsley and APEXAquaNX4 Aug 4, 2014 2:19 PM (in response to sect55) Perhaps this will help: HTML Header Use HTML Header For Include Standard CSS and JavaScript, select Yes to suppress the inclusion of cascading style sheet (CSS) and JavaScript files in the HTML Header. Because suppressing the display of these files breaks typical applications, enabling this attribute is only recommended for advanced developers. HTML Body Attributes Use this attribute to add events when the page is being loaded,# > Incorporating JavaScript into an Application Application Express validations instead of JavaScript. This section contains the following topics: - Referencing Items Using JavaScript - Incorporating JavaScript Functions - Calling JavaScript from a Button See Also:"Understanding Validations" Referencing Items Using JavaScript(){ alert('First Name is ' + document.getElementById('P1_FIRST_NAME').value ); } // or a more generic version would be function displayValue(id){ alert('The Value is ' + document.getElementById(id).value ); } </script> onchange="displayValue('P1_FIRST_NAME');" Incorporating JavaScript Functions There are two primary places to include JavaScript functions: - In the HTML Header attribute of the page - In a .js file in the page template Incorporating JavaScript into the HTML Header AttributeOne way to include JavaScript into your application is to add it to the HTML Header attribute of the page. This is a good approach for functions that are very specific to a page and a convenient way to test a function before you include it in the .jsfile.You can add JavaScript functions to a page by simply entering the code into the HTML Header attribute of the Page Attributes page. In the following example, adding the code would make the testfunction" Including JavaScript in a .js File Referenced by the Page Template In Oracle Application Express, you can reference a .jsfile in the page template. This approach makes all the JavaScript in that file accessible to the application. This is the most efficient approach since a .jsfile loads on the first page view of your application and is then cached by the browser. The following demonstrates how to include a .jsfile in the header section of a page template. Note the line script src=that appears in bold. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>#TITLE#</title> #HEAD# <script src="" type="text/javascript"></script> </head> <body #ONLOAD#>#FORM_OPEN# 7. Re: Parsley and APEXsect55 Aug 4, 2014 3:08 PM (in response to fac586) fac586, I did not see id for form aleady so put $('#wwvFlowForm').parsley(); in the JavaScript > Execute when Page Loades section of th Page Attributes. I tried a max length validation for the registration number page item bu placing data-parsley-maxlength="10" in th HTML Form Element Attributes for the page item. But when I ran the form entering more than 10 characters for registration number, I received NO error messages when I clicked on the APPLY CHANGE button and received the normal ACTION PROCESSED message. Database : Oracle 10.2.0.5.0 APEX: APEX 4.1 8. Re: Parsley and APEXTom Petrus Aug 4, 2014 8:06 PM (in response to sect55)1 person found this helpful What parsley version do you use? The stable and latest build (2.x) requires jquery version 1.8 or higher. Apex only ships with 1.7, so that might be an issue. Edit: I took some time to look into Parsley and played around with it. It's not that hard to get it up and running. However, there is just one tiny thing that requires extra work integrating it into apex. If you want validation as you go, you may want to define Parsley triggers too, which eg fire on keyup or change. The issue why the validation is not firing when the page is submitted is because of how a handler is assigned to the submit event in Parsley. This is the default function: ParsleyForm.prototype = { onSubmitValidate: function (event) { this.validate(undefined, undefined, event); // prevent form submission if validation fails if (false === this.validationResult && event instanceof $.Event) { event.stopImmediatePropagation(); event.preventDefault(); } return this; }, And this is how it is bound: formInstance.$element.on('submit.Parsley', false, $.proxy(formInstance.onSubmitValidate, formInstance)); It doesn't work because of the element it is being bound on: it should be on the apex.gPageContext$ context. I wouldn't really change the parsley source since there is a workaround. We can use the before page submit event for this. (You can use the submit event too, if you bind it correctly but ok) apex.gPageContext$.on("apexbeforepagesubmit", function(){ apex.event.gCancelFlag = !$("form[name=wwv_flow]").parsley().validate(); }); Apex's bind to the before page submit with event.trigger, and event returns a boolean based on the cancel flag. Apex also uses this internally for its DA's. It's not that properly document, but it's obvious from the files. Try the above, should work nice, worked for me! 9. Re: Parsley and APEXsect55 Aug 5, 2014 3:31 PM (in response to Tom Petrus) Tom, Thanks for your time and help. I included the code in the "when page is loaded" section of the page attributes. apex.gPageContext$.on("apexbeforepagesubmit", function(){ apex.event.gCancelFlag = !$("form[name=wwv_flow]").parsley().validate(); }); and still did not work. When I enter more than 10 characters in registration number, and click on Apply Changes, I still get "Action Processed" Robert 10. Re: Re: Parsley and APEXTom Petrus Aug 5, 2014 5:09 PM (in response to sect55)1 person found this helpful Hi Robert, I'll just mention what I have in my tiny test: Page: Javascript URLs: //code.jquery.com/jquery-1.11.0.min.js #WORKSPACE_IMAGES#parsley.js -> jquery CDN, parsley version 2.0.3 (latest stable) Execute when page loads: $("form[name=wwv_flow]").parsley(); apex.gPageContext$.on("apexbeforepagesubmit", function(){ apex.event.gCancelFlag = !$("form[name=wwv_flow]").parsley().validate(); }); One call to instantiate parsley on load, and then the code to run on submit (especially for apex buttons which perform apex.submit() ). Mind that if you only add the apexbeforepagesubmit code then parsley will not be instantiated previously and only at that specific moment. Text item: plain and simple text item, as a test. Element - HTML Form Element Attributes: data-parsley-maxlength="10" data-parsley-required="true" The default namespace is "data-parsley-" so do take care of that. Unless you set the namespace differently then any other attribute setting is never retrieved by parsley. That's it really. You can check my simple page on Login with apex_demo/demo You can inspect the source for more, but there is not happening all that much. 11. Re: Parsley and APEXsect55 Aug 18, 2014 7:41 PM (in response to Tom Petrus) Tom, Been busy on another part of the project as well as other projects, so this is the first time I was able to spend significant time on it. Can you please give me access to the source. I must be missing something that I cannot pinpoint so it would be easier if you give me access to your simple application. Thank you, Robert 12. Re: Parsley and APEXTom Petrus Aug 19, 2014 7:36 AM (in response to sect55)1 person found this helpful Robert, Added a download link on the demo page. 13. Re: Parsley and APEXsect55 Aug 22, 2014 1:31 PM (in response to Tom Petrus) Tom, I downloaded your application and loaded in apex.oracle.com and it doesn't work. Ie., no error message when I put in over 10 characters. Please use apex_demo/apex and test it. Thank you, Robert 14. Re: Parsley and APEXTom Petrus Aug 25, 2014 7:31 AM (in response to sect55) Ah, I forgot the app export would not take the associated static files with it. I see you've added a parsley.js file yourself, but it's a wrong one (the page also has a js error originating in the file). Add the parsley.js file from here Parsley - Download the pieces
https://community.oracle.com/thread/3591854
CC-MAIN-2017-39
refinedweb
1,607
66.03
Fork and Exec The fork system call in Unix creates a new process. The new process inherits various properties from its parent (Environmental variables, File descriptors, etc - see the manual page for details). After a successful fork call, two copies of the original code will be running. In the original process (the parent) the return value of fork will be the process ID of the child. In the new child process the return value of fork will be 0. Here's a simple example where the child sleeps for 2 seconds while the parent waits for the child process to exit. Note how the return value of fork is used to control which code is run by the parent and which by the child. #include <unistd.h> #include <sys/wait.h> #include <iostream> using namespace std; int main(){ pid_t pid; int status, died; switch(pid=fork()){ case -1: cout << "can't fork\n"; exit(-1); case 0 : sleep(2); // this is the code the child runs exit(3); default: died= wait(&status); // this is the code the parent runs } } In the following annotated example the parent process queries the child process in more detail, determining whether the child exited normally or not. To make things interesting the parent kills the child process if the latter's PID is odd, so if you run the program a few times expect behaviour to vary. #include <unistd.h> #include <sys/wait.h> #include <signal.h> #include <iostream> using namespace std; int main(){ pid_t pid; int status, died; switch(pid=fork()){ case -1: cout << "can't fork\n"; exit(-1); case 0 : cout << " I'm the child of PID " << getppid() << ".\n"; cout << " My PID is " << getpid() << endl; sleep(2); exit(3); default: cout << "I'm the parent.\n"; cout << "My PID is " << getpid() << endl; // kill the child in 50% of runs if (pid & 1) kill(pid,SIGKILL); died= wait(&status); if(WIFEXITED(status)) cout << "The child, pid=" << pid << ", has returned " << WEXITSTATUS(status) << endl; else cout << "The child process was sent a " << WTERMSIG(status) << " signal\n"; } } In the examples above, the new process is running the same program as the parent (though it's running different parts of it). Often however, you want the new process to run a new program. When, for example, you type "date" on the unix command line, the command line interpreter (the so-called "shell") forks so that momentarily 2 shells are running, then the code in the child process is replaced by the code of the "date" program by using one of the family of exec system calls. Here's a simple example of how it's done. #include <unistd.h> #include <sys/wait.h> #include <iostream> using namespace std; int main(){ pid_t pid; int status, died; switch(pid=fork()){ case -1: cout << "can't fork\n"; exit(-1); case 0 : execl("/usr/bin/date","date",0); // this is the code the child runs default: died= wait(&status); // this is the code the parent runs } } The child process can communicate some information to its parent via the argument to exit, but this is rather restrictive. Richer communication is possible if one takes advantage of the fact that the child and parent share file descriptors. The popen() command is the tidiest way to do this. The following code uses a more low-level method. The pipe() command creates a pipe, returning two file descriptors; the 1st opened for reading from the pipe and the 2nd opened for writing to it. Both the parent and child process initially have access to both ends of the pipe. The code below closes the ends it doesn't need. #include <unistd.h> #include <sys/wait.h> #include <iostream> #include <sys/types.h> using namespace std; int main(){ char str[1024], *cp; int pipefd[2]; pid_t pid; int status, died; pipe (pipefd); switch(pid=fork()){ case -1: cout << "can't fork\n"; exit(-1); case 0 : // this is the code the child runs close(1); // close stdout // pipefd[1] is for writing to the pipe. We want the output // that used to go to the standard output (file descriptor 1) // to be written to the pipe. The following command does this, // creating a new file descripter 1 (the lowest available) // that writes where pipefd[1] goes. dup (pipefd[1]); // points pipefd at file descriptor // the child isn't going to read from the pipe, so // pipefd[0] can be closed close (pipefd[0]); execl ("/usr/bin/date","date",0); default: // this is the code the parent runs close(0); // close stdin // Set file descriptor 0 (stdin) to read from the pipe dup (pipefd[0]); // the parent isn't going to write to the pipe close (pipefd[1]); // Now read from the pipe cin.getline(str, 1023); cout << "The date is " << str << endl; died= wait(&status); } } In all these examples the parent process waits for the child to exit. If the parent doesn't wait, but exits before the child process does, then the child is adopted by another process (usually the one with PID 1). After the child exits (but before it's waited for) it becomes a "zombie". If it's never waited for (because the parent process is hung, for example) it remains a zombie. In more recent Unix versions, the kernel releases these processes, but sometimes they can only be removed from the list of processes by rebooting the machine. Though in small numbers they're harmless enough, avoiding them is a very good idea. Particularly if a process has many children, it's worth using waitpid() rather than wait(), so that the code waits for the right process. Some versions of Unix have wait2(), wait3() and wait4() variants which may be useful. Double fork One way to create a new process that is more isolated from the parent is to do the following The original process doesn't have to wait around for the new process to die, and doesn't need to worry when it does. Notes - The parent and child share the same code, but they sometimes share the same data segment too, read-only. Only when one of the processes tries to change the data is a copy made. Some systems implement this by default. Sometimes you need to call vfork(). - On some systems there's a clone() command. This lets the parent and child share more resources (it's used when implementing threads). Sometimes they may have the same PID and may only differ by their stack segments and processor register value. - YoLinux Tutorial - "Advanced Programming in the UNIX Environment", W.Richard Stevens, Addison-Wesley, ISBN 0-201-56317-7
http://www-h.eng.cam.ac.uk/help/tpl/unix/fork.html
CC-MAIN-2015-18
refinedweb
1,103
67.99
This is an automated email from the ASF dual-hosted git repository. ivank pushed a commit to branch master in repository The following commit(s) were added to refs/heads/master by this push: new 21a89a7 Require green CI before merge 21a89a7 is described below commit 21a89a7c486b842846ba9c15d6ec52d4486dd74c Author: Ivan Kelly <ivank@apache.org> AuthorDate: Tue Feb 13 17:50:36 2018 +0100 Require green CI before merge CI has been broken since the 2018-02-06, due to a non-green patch being merged. With the recent flake fixes, CI should only go green if there's a good reason. More over, any remaining problems will get fixed faster, if people non-green builds start being a pain for people. So, this patch blocks merging with the merge script, if all checks are not green. It can be overriden by adding a comment with the text "Ignore CI" (case insensitive), on the PR. Author: Ivan Kelly <ivank@apache.org> Reviewers: Dave Rusek <dave.rusek@gmail.com>, Jia Zhai <None>, Enrico Olivelli <eolivelli@gmail.com>, Sijie Guo <sijie@apache.org> This closes #1145 from ivankelly/require-green --- dev/bk-merge-pr.py | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/dev/bk-merge-pr.py b/dev/bk-merge-pr.py index 8c3415e..c5dffe7 100755 --- a/dev/bk-merge-pr.py +++ b/dev/bk-merge-pr.py @@ -476,6 +476,19 @@ def get_reviewers(pr_num): reviewers_emails.append('{0} <{1}>'.format(username.encode('utf8'), useremail)) return ', '.join(reviewers_emails) +def check_ci_status(pr): + status_url = get_json("%s/commits/%s/status" % (GITHUB_API_BASE, pr["head"]["sha"])) + state = status_url["state"] + if state != "success": + ignore_ci_comments = [c for c in comments if c["body"].upper() == "IGNORE CI"] + if len(ignore_ci_comments) > 0: + print "\n\nWARNING: The PR has not passed CI (state is %s)" % (state) \ + + ", but this has been overridden by %s. \n" % (ignore_ci_comments[0]["user"]["login"]) \ + + "Proceed at your own peril!\n\n" + else: + fail("The PR has not passed CI (state is %s)" % (state)) + def ask_release_for_github_issues(branch, labels): print "=== Add release to github issues ===" while True: @@ -643,9 +656,11 @@ def main(): pr = get_json("%s/pulls/%s" % (GITHUB_API_BASE, pr_num)) pr_events = get_json("%s/issues/%s/events" % (GITHUB_API_BASE, pr_num)) pr_reviewers = get_reviewers(pr_num) + check_ci_status(pr) + url = pr["url"] - # 3. repare the title for commit message + # 3. repair the title for commit message pr_title = pr["title"] commit_title = raw_input("Commit title [%s]: " % pr_title.encode("utf-8")).decode("utf-8") if commit_title == "": -- To stop receiving notification emails like this one, please contact ivank@apache.org.
http://mail-archives.apache.org/mod_mbox/bookkeeper-commits/201802.mbox/%3C151854064366.21995.11177047807566475776@gitbox.apache.org%3E
CC-MAIN-2018-13
refinedweb
412
50.33
realmagick.com The shrine of knowledge. Meaning Of Dreams About Safe A selection of articles related to meaning of dreams about safe. Original articles from our library related to the Meaning Of Dreams About Safe. See Table of Contents for further available material (downloadable resources) on Meaning Of Dreams About Safe is described in multiple online sources, as addition to our editors' articles, see section below for printable documents, Meaning Of Dreams About Safe books and related discussion. Suggested Pdf Resources - Dream Meanings, How to Interpret your Dreams, - The dream's meaning should start to come into focus. Sometimes it takes a watch over you and keep you safe during the night. - - Remarks on the Interpretation of Dreams, according to Sigmund - dream, its essential meaning, drawn from the ideas which have not come into .. - bjp.rcpsych.org - Religious images in dreams - of the possible religious meaning of dreams should be a specialized but necessary aspect of counsel- dream tells him it is safe to return (Matt. 2:12-13, 19-22). - - The Meanings of Touch in Psychoanalysis: A Time for Reassessment - is enabling us to readdress the meanings and uses of touch within psychoanalysis. . and cuddling of the child creates a sense of intimacy, love, safety, and well-being. - - The Interpretation of an Architect's Dream: Relational Trauma and Its - concern about the children's safety that her ten year old self would give us the core meanings of the dream. - muse.jhu.edu Suggested Web Resources - Dream dictionary - safe - dream analysis - DREAM ANALYSIS : What is the symbolic meaning of safety and feeling safe in dreams? - - Safe Dream interpretation - meaning of dreams about safes. - The online dream dictionary definition for dreams about safes. What does it mean to dream about safes? What is the symbolic meaning of a safe dream? - - A-Z DREAM DIRECTORY- Free Meanings Of Dreams Directory. - - Dream Moods Dictionary: Words That Begin With S - To see a safe in your dream indicates that you are hiding your sense of self . on the good and bad things that you have done. meanings by DreamMoods. - - Safe Personal Development - DivineCaroline - Sep 6, 2011 The scientific method of dream interpretation is not based on the Dreams must not be interpreted based on the dream interpreter's intuition. - Safe Topics Related searchesamazoness quartet pallapalla erosion gravity erosion chosun ilbo history arms dictionary kuruc philo of byblos bionicle mata nui About - Contact - Advertising
http://www.realmagick.com/meaning-of-dreams-about-safe/
CC-MAIN-2015-18
refinedweb
400
53.71
# Quintet instead of Byte — data storage and retrieval approach Quintet is a way to present atomic pieces of data indicating their role in the business area. Quintets can describe any item, while each of them contains complete information about itself and its relations to other quintets. Such description does not depend on the platform used. Its objective is to simplify the storage of data and to improve the visibility of their presentation. ![](https://habrastorage.org/webt/em/rc/sj/emrcsj86rsey9wacgmk-uj4i9og.gif) **We will discuss an approach to storing and processing information and share some thoughts on creating a development platform in this new paradigm. What for? To develop faster and in shorter iterations: sketch your project, make sure it is what you thought of, refine it, and then keep refining the result.** The quintet has properties: type, value, parent, and order among the peers. Thus, there are 5 components including the identifier. This is the simplest universal form to record information, a new standard that could potentially fit any programming demands. Quintets are stored in the file system of the unified structure, in a continuous homogeneous indexed bulk of data. The quintet data model — a data model that describes any data structure as a single interconnected list of basic types and terms based on them (metadata), as well as instances of objects stored according to this metadata (data). **Half a minute of lyrics** Nowadays there are an infinite number of standards to record data, numerous approaches and rules, the knowledge of which is necessary for working with these records. Standards are described separately and do not directly relate to the corresponding data. In the case of quintets, taking any of them, you can get relevant information about its nature, properties and processing rules in the user’s business area. Its standard is unified and fixed for all areas. The quintet is hidden from the user — metadata and data are available to the latter in a common comprehensible manner. Quintet is not only information, it could also represent executable code. But above all, it is the data that you want to record, store, and retrieve. Since in our case quintets are directly addressable, interconnected and indexed, we will store them in a kind of database. ### Why Quintet instead of Byte? **Not bit or electronic impulse that orient the magnetic spin.** We are accustomed to measure the data in bytes, whether it is a document or photo size, internet traffic limit, or available space on your mobile device. We propose another measure — Quintet — which does not have a fixed size like Byte does, but represents an atomic amount of data, which is of some value to the user. For example, you can say that your database occupies 119 megabytes of the storage or you can state that this database stores 1.37 mega-quintets. You do not care much what a byte is in this context, but you understand that this database contains 1.37 million of your term descriptions, objects, their attributes, links, events, queries with their details, etc. To possess 1.37 million valuable pieces of data sounds sexier than having 119 megabytes of stuff on you. Thus, this is not to replace the way the information is stored on the data medium, but to shift to another level of abstraction. ### Quintet structure The main idea of ​​this article is to replace machine types with human terms and replace variables with objects. Not by those objects that need a constructor, destructor, interfaces, and a garbage collector, but by crystal-clear units of information that a customer handles. That is, if the customer says «Client», then to save the essence of this statement on the medium would not require expertise of a programmer. ![](https://habrastorage.org/r/w1560/webt/e-/ox/u9/e-oxu90oaiouj4zals6mgtnj7zy.png) It makes sense to focus the user’s attention only on the value of the object, while its type, parent, order (among equals in subordination) and identifier should be obvious from the context or simply hidden. This means that the user does not know anything about quintets at all, he simply gives out a task, makes sure that it is accepted correctly, and then starts its execution. ### Basic concepts There is a set of data types everyone understands: string, number, file, text, date, and so on. Such a simple set is quite enough to sketch the solution, and to «program» it along with the terms necessary for its implementation. The basic types represented by quintets may look like this: ![](https://habrastorage.org/r/w1560/webt/ca/zb/7l/cazb7lfkvuldo5anzgnzibqu3oc.png) In this case, some of the components of the quintet are not used, while the quintet itself is used as the basic type. This makes the system kernel easier to navigate when collecting metadata. ### The background Due to the analytic gap between the user and the programmer, a significant deformation of concepts occurs at the stage of outlining a project. The understatement, incomprehensibility and unsolicited initiative often turns a simple and reasonable idea of the customer into a logically impossible mess, if being evaluated from the the user’s point of view. ![](https://habrastorage.org/r/w1560/webt/7p/jb/uz/7pjbuzxfddlosktjv3bs-om0v-8.png) Knowledge transfer should occur without loss and distortion. Furthermore, organizing the storage of this knowledge, you should better get rid of the restrictions imposed by the data management system chosen. ### How we store the data now Typically, there are many databases on the server; each of them contains a description of the data scheme with a specific set of details — logically interconnected data. They are stored on the data medium in a specific order, ideally — optimal to reduce the retrieval efforts. The proposed information storage system is a compromise between various well-known methods: column-oriented, relational and NoSQL. It is designed to solve the tasks usually performed by one of these approaches. For example, the theory of column-oriented DBMS looks beautiful: we read only the desired column, but not all the rows of records as a whole. However, in practice, it is unlikely that data will be placed on the media so that it is convenient to retrieve dozens of different analytic dimensions. Note that attributes and analytical metrics can be added and removed, sometimes faster than we can rebuild our columnar storage. Not to mention that the data in the database can be amended, which will also violate the beauty of the storage schema due to inevitable fragmentation. ### Metadata We introduced a concept — a term — to describe any objects that we operate with: entity, property, request, file, etc. We will define all the terms that we use in our business area. And with their help, we will describe all entities that have details, including the form of relationships between entities. For example, an attribute — a link to a status dictionary entry. The term is written as a quintet of data. A set of term descriptions is metadata like the same represented by the structure of tables and fields in a regular database. For example, there is the following data structure: a service request on some date that has the content (request description) and a status, to which the participants of a production process add comments indicating the date. In a traditional database constructor it will look something like this: ![](https://habrastorage.org/r/w1560/webt/wj/ux/e5/wjuxe5yakm3i0e8-b8qatbsuvv0.png) Since we decided to hide from the user all non-essential details, such as binding IDs, for example, the scheme will be somewhat simplified: the mentions of IDs are removed and the names of entities and their key values ​​are combined. The user «draws» the task: a request from today’s date which has a state (reference value) and to which you can add comments indicating the date: ![](https://habrastorage.org/r/w1560/webt/i7/-e/s0/i7-es0bgiqlj2mjrgaijlsj_nrg.png) Now we see 6 different data fields instead of 9, and the whole scheme offers us to read and comprehend 7 words instead of 13. Although this is not the main thing, of course. The following are the quintets generated by the quintet-processing kernel to describe this structure: ![](https://habrastorage.org/r/w1560/webt/os/55/ms/os55msg7_8xpt2jkcqpnc1xhnls.png) Explanations in place of quintet values ​​highlighted in gray are provided for clarity. These fields are not filled out, because all the necessary information is unambiguously determined by the remaining components. **See how quintets are related** ![](https://habrastorage.org/r/w1560/webt/he/sh/xu/heshxuxlzau8yljqiznxu2ckd-8.png) What we have here: * the attributes with IDs 80, 81, 83 has the same parent — Request * quintet #82 is the attribute of Comment, which is in turn an attribute of Request * attribute #74 is a reference to the type described by quintet #73 and is used as attribute #81 of Request This might look slightly complicated for humans, but the good news is — a human will never see this. The kernel will represent the metadata as comprehensible diagrams and the data as simple flat tables. ### User data Let me show how we store such a data set for the above task: ![](https://habrastorage.org/r/w1560/webt/7r/fo/6g/7rfo6gvbnxz2wahg9vq-8x8wdty.png) The data itself is stored in quintets according to the metadata. We can visualize them the same way we did above: ![](https://habrastorage.org/r/w1560/webt/lc/p4/15/lcp415pjpig8etl3lykjfi2lqca.png) We see a familiar hierarchical structure written down using something like the Adjacency List method. ### Physical storage The data is written to the memory as a sequence of quintet items in bytes of data. In order to search by index the kernel treats those bytes of data according to the data type defined for them by basic types. That’s it: a huge list of five of data items. The storage principles are not much different from the same in RDBMS, which enables us building SQL queries to the data to make data retrieval, JOINs, aggregate functions and other things we like in relational databases. > **To test the prototype of a development platform based on the quintet storage system we use a relational database.** ### Performance The above example is very simple, but what will be when the structure is thousand times more complex and there are gigabytes of data? What we need: 1. The discussed hierarchical structure — 1 pc. 2. B-tree for searching by ID, parent and type — 3 pcs. Thus, all records in our database will be indexed, including both data and metadata. Such indexing is necessary to get the benefits of a relational database — the simplest and most popular tool. The parent index is actually composite (parent ID + type). The index by type is also composite (type + value) for quick search of objects of a given type. Metadata allows us to get rid of recursion: for example, to find all the details of a given object, we use the index by parent ID. If you need to search for objects of a certain type, then we use the index by type ID. Type is an analog of a table name and a field in a relational DBMS. ![](https://habrastorage.org/r/w1560/webt/w0/3y/6_/w03y6_fst_enfkaxmihelbnxjcc.png) In any case, we do not scan the entire data set, and even with a large number of values ​​of any type, the desired value can be found in a small number of steps. ### The basis for the development platform In itself, such a database is not self-sufficient for application programming, and is not complete, as they say, according to Turing. However, we are talking here not only about the database, but are trying to cover all aspects: objects are, among other things, arbitrary control algorithms that can be launched, and they will work. As a result, instead of complex database structures and separately stored source code of control algorithms, we get a uniform information field, limited by the volume of the storage space and governed with metadata. The data itself is presented to the user in an understandable form to him — the structure of the subject area and the corresponding entries in it. The user arbitrarily changes the structure and data, including making bulk operations with them. #### We did not invent anything new: all the data is already stored in the file system and the search in them is carried out using B-trees, either in the file system, or in the database. We just reorganized the presentation of the data so that it is easier and clear to work with. To work with this data representation, you will need a very compact kernel software — our database engine is of the size smaller than a computer BIOS, and, therefore, it can be made if not in hardware, then at least as fast and bug-free as possible. For security reasons, it also could be read-only. Adding a new class to an assembly in my favorite .Net, we can observe the loss of 200-300 MB of RAM only on the definition of this class. These megabytes will not fit into the cache of the proper level, causing the system to swap on disk with all the consequent overhead. A similar situation is with Java. The description of the same class with quintets will take tens or hundreds of bytes, since the class uses only primitive operations for working with data that the kernel already knows. > #### You might think that this approach is already implemented many times in various applications, but that is not true. > > > > We made a deep search in both internet and intellectual property (patents) bases, and no one claims to do exactly the same solution to break the performance limit of constructors, [single-table solutions](https://www.red-gate.com/simple-talk/opinion/opinion-pieces/bad-carma/), and other EAV-based systems. Nevertheless, we put hundreds of gigabytes in such quintet application and found it working quite well. In case you want to see evidences, create and test your own instance, feel free to visit our github account. The prototype of the platform we built has four components: 1. Visual **Type editor** to define the metadata 2. **Data navigation tool** like a simple SQL navigator 3. Visual **Report designer** to build SQL queries to the data 4. A **Template processor** to combine templates with data retrieved by queries ![](https://habrastorage.org/r/w1560/webt/bc/lu/rq/bclurqpevkemespz7aofusqipps.png) As it was intended, working with the prototype no user would think there are quintets inside — this looks just like an ordinary constructor. **You may test a working prototype implementation by the link in the [first comment](https://habr.com/ru/post/468927/#comments) to this article.** **How to deal with different formats: RDBMS, NoSQL, column bases** The discussed approach covers two main areas: RDBMS and NoSQL. When solving problems that take advantage of columnar databases, we need to tell the kernel that certain objects should be stored, taking into account the optimization of mass sampling of the values ​​of a certain data type (our term). Therefore, the kernel will be able to place data on disk in the most profitable way. Thus, for a columnar DB, we can significantly save the space occupied by quintets: use only one or two of its components to store useful data instead of five, and also use the index only to indicate the beginning of data chains. In many cases, only the index will be used for sampling from our analogue of a columnar base, without the need to access the data of the quintet list itself. It should be noted that the idea is not intended to collect all the advanced developments from these three types of databases. On the contrary, the engine of the new system will be reduced as much as possible, embodying only the necessary minimum of functions — everything that covers DDL and DML requests in the concept described here. ### Programming paradigm The described approach is not limited only to the usage of quintets, but promotes a different paradigm than the one that programmers are used to. Instead of an imperative, declarative, or object language, we propose the query language as more familiar to humans and allowing us to set the task directly to the computer, bypassing programmers and the impenetrable layer of existing development environments. **Of course, a translator from a layman user language to a language of clear requirements will still be necessary in most cases.** This topic will be described in more detail in separate articles with examples and existing developments. So, shortly, it works as follows: 1. We once described primitive data types using quintets: string, number, file, text and others, and also trained the kernel to work with them. Training means the correct presentation of data and the implementation of simple operations with them. 2. Now we describe user terms (data types) — in the form of metadata. The description is just specifying a primitive data type for each user type and determining the relations. 3. We enter data quintets according to the structure specified by metadata. Each quintet of data contains a link to its type and parent, which allows you to quickly find it in the data storage. 4. The kernel tasks come down to fetching data and performing simple operations with them to implement arbitrarily complex algorithms defined by the user. 5. The user manages *data* and *algorithms* using a visual interface that presents both of them. The Turing completeness of the entire system is ensured by the embodiment of the basic requirements: the kernel can do sequential operations, conditionally branch, process the data and stop work when a certain result is achieved. For a person, the benefit is simplicity of perception, for example, instead of declaring a cycle involving variables ``` for (i = 0; i ``` a more understandable form is used, like ``` with every A, that match a condition, do something ``` We dream of abstracting from the low-level subtleties of information systems: loops, constructors, functions, manifests, libraries — all these take up too much space in the brain of a programmer, leaving little room for creative work and development. ### Scalability An application is often useless without means of scaling: an unlimited ability to expand the load capacity of an information system is required. In the described approach, taking into consideration the extreme simplicity of data organization, scaling turns out to be organized no more complicated than in existing architectures. In the above example with the service requests, you can separate them, for example, by their ID, making the generation of ID with fixed HIGH bytes for different servers. That is, when using 32 bits for storing ID, the left two-three-four or more bits, as needed, will indicate the server on which these applications are stored. Thus, each server will have its own pool of IDs. The kernel of a single server can function independently of other servers, without knowing anything about them. When creating an object, it will be given a high priority to the server with the minimum number of IDs used, to ensure the even load distribution. Given a limited set of possible variations of requests and responses in such data organization, you will need a fairly compact dispatcher that distributes requests across servers and aggregates their results.
https://habr.com/ru/post/468927/
null
null
3,212
50.46
Hi, would like to use a column on my site as a button that links to another page on my site. Since I understood that function has to be onReady as well as onClick and import to, I'm quite confused and would love some help using JS code to manage this. Thanks Hey Omer, If I understand correctly, you want it so clicking on a Column will navigate to a different page on site? If so, just do the following: Make sure your Property Panel is open Make sure the component is selected Add an onClick function This steps are explained in this video tutorial if you're not sure about any of them. Now as for what code to write, you'll want to use the "to()" method of the wix-location module. If the onClick handler is named "button_click_handler" and the page you want to navigate is called "nameOfYourPage", it will look something like this: Let me know how it went, J. Hi, thanks. import wixLocation from 'wix-location'; function HAIRPRODUCT_click_handler() { wixLocation.to("/Shop"); } Tried changing with/without handler. The prob. is that onClick is defined as export function and doesn't work without the export
https://www.wix.com/corvid/forum/community-discussion/using-column-as-onclick
CC-MAIN-2020-05
refinedweb
199
66.98
20 June 2012 05:29 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> The company’s No 1 residual fluid catalytic cracker (RFCC), which can produce around 375,000 tonnes/year of propylene, was shut on 25 April and was initially scheduled to resume operations at the end of June. Separately, FPCC’s olefins conversion unit (OCU) at the same site – with a propylene nameplate capacity of 250,000 tonnes/year – was earlier slated to restart in late June after it was taken off line for scheduled maintenance on 16 May, he said. The source did not comment on the reason for the extended plant turnarounds. FPCC also runs a No 2 RFCC at Mailiao, which has the same propylene nameplate capacity as the No 1 unit, but it is not scheduled for maintenance this year,
http://www.icis.com/Articles/2012/06/20/9571117/taiwans-fpcc-extends-turnaround-at-propylene-units-until-mid-july.html
CC-MAIN-2014-49
refinedweb
135
62.82
NAME hgrc - configuration files for Mercurial SYNOPSIS or (Windows) <install-dir>\hgrc.d\*.rc or (Windows) HKEY_LOCAL_MACHINE\SOFTWARE\Mercurial Per-installation/system configuration files,. If the pywin32 extensions are not installed, Mercurial will only look for site-wide configuration in C:\Mercurial\Mercurial.ini. SYNTAX). SECTIONS This section describes the different sections that may appear in a Mercurial configuration file, the purpose of each section, its possible keys, and their possible values. alias | xargs -0 rm which will make hg purge delete all unknown files in the repository in the same manner as the purge extension. Shell aliases are executed in an environment where $HG expand to the path of the Mercurial that was used to execute the alias. This is useful when you want to call further Mercurial commands in a shell alias, as was done above for the purge alias. In addition, $HG_ARGS expand to the arguments given to Mercurial. In the hg echo foo call above, $HG_ARGS would expand to echo foo. auth Authentication credentials for HTTP authentication. This section allows you to store usernames and passwords for use when logging into HTTP servers. See the [web] configuration section if you want to configure who can login to your HTTP server. Each line has the following format: <name>.<argument> = <value> where <name> is used to group arguments into authentication entries. Example: foo.prefix = hg.intevation.org/mercurial foo.username = foo foo.password = bar foo.schemes = http https bar.prefix = secure.example.org bar.key = path/to/file.key bar.cert = path/to/file.cert bar.schemes = https Supported arguments: prefix Either * or a URI prefix with or without the scheme part. The authentication entry with the longest matching prefix is used (where * matches everything and counts as a match of length 1). If the prefix doesn't include a scheme, the match is performed against the URI with its scheme stripped as well, and the schemes argument, q.v., is then subsequently consulted. username Optional. Username to authenticate with. If not given, and the remote site requires basic or digest authentication, the user will be prompted for it. Environment variables are expanded in the username letting you do foo.username = $USER. If the URI includes a username, only [auth] entries with a matching username or without a username will be considered. password Optional. Password to authenticate with. If not given, and the remote site requires basic or digest authentication, the user will be prompted for it. key Optional. PEM encoded client certificate key file. Environment variables are expanded in the filename. cert Optional. PEM encoded client certificate chain file. Environment variables are expanded in the filename. schemes Optional. Space separated list of URI schemes to use this authentication entry with. Only used if the prefix doesn't include a scheme. Supported schemes are http and https. They will match static-http and static-https respectively, as well. Default: https. If no suitable authentication entry is found, the user is prompted for credentials as usual if required by the remote.. Everything except for unified is. unified Number of lines of context to show.. method Optional. Method to use to send email messages. If value is smtp (default), use SMTP (see the [smtp] section. charsets.: mq extension will get loaded from Mercurial's path) mq = # (this extension will get loaded from the file specified) myfeature = ~/.hgext/myfeature.py hostfingerprints. The CA chain and web.cacerts is not used for servers with a fingerprint. For example: [hostfingerprints] hg.intevation.org = 38:76:52:7c:87:26:9a:8f:4a:f8:d3:de:08:45:3b:ea:d6:4b:ee:cc This feature is only supported when using Python 2.6 or later.. merge-patterns This section specifies merge tools to associate with particular file patterns. Tools matched here will take precedence over the default merge tool. Patterns are globs by default, rooted at the repository root. Example: [merge-patterns] **.c = kdiff3 **.jpg = myimgmerge merge-tools: priority The priority in which to evaluate this tool. Default: 0. executable Either just the name of the executable or its pathname.] # update working directory after adding changesets changegroup.update = hg update # do not use the site-wide hook incoming = incoming.email = /my/email/hook incoming.autobuild = /my/build/hook Most hooks are run with environment variables set that give useful additional. Parsed command line arguments are passed as $HG_PATS and $HG_OPTS. These contain string representations of the python data internally passed to <command>. $HG_OPTS is a dictionary of options (with unspecified options set to their defaults). $HG_PATS is a list of arguments. Hook failure is ignored. pre-<command> Run before executing the associated command. The contents of the command line are passed as $HG_ARGS. Parsed command line arguments are passed as $HG_PATS and $HG_OPTS. These contain string representations of the data internally passed to <command>. $HG_OPTS is a dictionary of options (with unspecified options set to their defaults). $HG_PATS is a list of arguments.listkeys Run before listing pushkeys (like bookmarks) in the repository. Non-zero status will cause failure. The key namespace is in $HG_NAMESPACE. preoutgoing Run before collecting.. repository.. tag Run after a tag is created. ID of tagged changeset is in $HG_NODE. Name of tag is in $HG_TAG. Tag is local if $HG_LOCAL=1, in repository if $HG_LOCAL=0. update Run after updating the working directory. Changeset ID of first new parent is in $HG_PARENT1. If merge, ID of second new parent is in $HG_PARENT2. If the update succeeded, $HG_ERROR=0. If the. always Optional. Always use the proxy, even for localhost and any entries in http_proxy.no. True or False. Default: False. smtp Configuration for extensions that need to send email messages. host Host name of mail server, e.g. "mail.example.com". port Optional. Port to connect to on mail server. Default: 25. tls Optional. Method to enable TLS when connecting to mail server: starttls, smtps or none. Default: none. username Optional. User name for authenticating with the SMTP server. Default: none. password Optional. Password for authenticating with the SMTP server. If not specified, interactive sessions will prompt the user for a password; non-interactive sessions will fail. Default: none. local_hostname Optional. It's the hostname that the sender can use to identify itself to the MTA. patch Settings used when applying patches, for instance through the 'import' command or with Mercurial Queues extension. eol When set to 'strict' patch content and patched files end of lines are preserved. When set to lf or crlf, both files end of lines are ignored when patching and the result line endings are normalized to either LF (Unix) or CRLF (Windows). When set to auto, end of lines are again ignored while patching but line endings in patched files are normalized to their original setting on a per-file basis. If target file does not exist or has no end of line, patch line endings are preserved. Default: strict.. profiling Specifies profiling format and file output. In this section description, 'profiling data' stands for the raw data collected during profiling, while 'profiling report' stands for a statistical text report generated from the profiling data. The profiling is done using lsprof. format Profiling format. Default: text. text Generate a profiling report. When saving to a file, it should be noted that only the report is saved, and the profiling data is not kept. kcachegrind Format profiling data for kcachegrind use: when saving to a file, the generated file can directly be loaded into kcachegrind. output File path where profiling data or report should be saved. If the file exists, it is replaced. Default: None, data is printed on stderr revsetalias Alias definitions for revsets. See hg help revsets for details. server Controls generic server settings. uncompressed Whether to allow clients to clone a repository using the uncompressed streaming protocol. This transfers about 40% more data than a regular clone, but uses less memory and CPU on both server and client. Over a LAN (100 Mbps or better) or a very fast WAN, an uncompressed streaming clone is a lot faster (~10x) than a regular clone. Over most WAN connections (anything slower than about 6 Mbps), uncompressed streaming is slower, because of the extra data transfer overhead. This mode will also temporarily hold the write lock while determining what data to transfer. Default is True. validate Whether to validate the completeness of pushed changesets by checking that all new file revisions specified in manifests are present. Default is False. subpaths Defines subrepositories source locations rewriting rules of the form: <pattern> = <replacement> Where pattern is a regular expression matching the source and replacement is the replacement string used to rewrite it. Groups can be matched in pattern and referenced in replacements. For instance:(.*)-hg/ =\1/ rewrites into. All patterns are applied in definition order. trusted. users Comma-separated list of trusted users. groups Comma-separated list of trusted groups. ui User interface controls. archivemeta Whether to include the .hg_archival.txt file containing meta data (hashes for the repository base and for tip) in archives created by the hg archive command or downloaded via hgweb. Default True. debug Print debugging information. True or False. Default is False. editor The editor to use during a commit. Default is $EDITOR or vi.. For more information on merge tools see hg help merge-tools. For configuring merge tools see the [merge-tools] section. False. web repository revisions. Default is False. allowgz (DEPRECATED) Whether to allow .tar.gz downloading of repository. The contents of the allow_push list are examined after the deny_push list. is False. allow_read If the user has not already been denied repository access due to the contents of deny_read, this list determines whether to grant repository access to the user. If this list is not empty, and the user is unauthenticated or not present in the list, then access is denied for the user. If the list is empty or not set, then access is permitted to all users by default. Setting allow_read to the special value * is equivalent to it not being set (i.e. access is permitted to all users). The contents of the allow_read list are examined after the deny_read list. allowzip (DEPRECATED) Whether to allow .zip downloading of repository revisions. Default is False. This feature creates temporary files.. The form must be as follows: -----BEGIN CERTIFICATE----- ... (certificate in base64 PEM encoding) ... -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- ... (certificate in base64 PEM encoding) ... -----END CERTIFICATE----- This feature is only supported when using Python 2.6 or later.. To disable SSL verification temporarily, specify --insecure from command line. cache Whether to support caching in hgweb. Defaults to True. contact Name or email address of the person in charge of the repository. Defaults to ui.username or $EMAIL or "unknown" if unset or empty. deny_push Whether to deny pushing to the repository. If empty or not set, push is not denied. If the special value *, all remote users are denied push. Otherwise, unauthenticated users are all denied, and any authenticated user name present in this list is also denied. The contents of the deny_push list are examined before the allow_push list. deny_read Whether to deny reading/viewing of the repository. If this list is not empty, unauthenticated users are all denied, and any authenticated user name present in this list is also denied access to the repository. If set to the special value *, all remote users are denied access (rarely needed ;). If deny_read is empty or not set, the determination of repository access depends on the presence and content of the allow_read list (see description). If both deny_read and allow_read are empty or not set, then access is permitted to all users by default. If the repository is being served via hgwebdir, denied users will not be able to see it in the list of repositories. The contents of the deny_read list have priority over (are examined before) the contents of the allow_read list. descend hgwebdir indexes will not descend into subdirectories. Only repositories directly in the current path will be shown (other repositories are still available from the index corresponding to their containing path). description Textual description of the repository's purpose or contents. Default. logourl Base URL to use for logos. If unset, will be used.. prefix Prefix path to serve from. Default is '' (server root).-2010 Matt Mackall. Free use of this software is granted under the terms of the GNU General Public License version 2 or any later version. AUTHOR Bryan O'Sullivan <bos@serpentine.com> Organization: Mercurial HGRC(5)
http://manpages.ubuntu.com/manpages/oneiric/man5/hgrc.5.html
CC-MAIN-2014-52
refinedweb
2,076
60.31
tag:blogger.com,1999:blog-8712770457197348465.post4413000295713762944..comments2016-04-28T08:39:56.918-07:00Comments on Javarevisited: How to create and initialize Anonymous array in Java ExampleJavin Paul, Anonymous class is quite different than ...@BramVdb, Anonymous class is quite different than anonymous array. Here it refers to adhoc arrays which are created on demand. Javin Paul is no such thing as an "anonymous"...There is no such thing as an "anonymous" and "non-anonymous" array. I think you are trying to draw a parallel here to anonymous classes. And I think it's a really bad one.<br /><br />It's important to realize the difference between classes, instances and fields. A class is like a blueprint that can be instantiated mutliple times, resulting in multiple instances. And a BramVdb Javin , Gr8 Article , one more thing that I wa...Hi Javin ,<br /><br />Gr8 Article , one more thing that I want to add is..There's no such thing as an "anonymous inner array" - what you've got there is simply an array creation expression.<br /><br />To use varargs arrays, you just change the method declaration like this:<br /><br />public class AnnonymousArrayExample {<br /><br /> public static void main(String[] args) {<brSARAL SAXENA
http://javarevisited.blogspot.com/feeds/4413000295713762944/comments/default
CC-MAIN-2016-18
refinedweb
204
57.57
iOS - Play a music or sound with AVAudioPlayer in Swift Wanting to know how to play background music files and sounds with AVAudioPlayer property (from AVFoundation framework) in Swift? Then you've got to the right place. We’ve setup a sample project that looks like this: Ok so let’s start by adding AVFoundation into Linked Frameworks and Libraries section, in the XCode’s General tab. Click on the plus sign and start typing the name of the needed framework: Next, you have to import it on the top of our .swift file, in order to make our app able to use it: import AVFoundation Now you have to create an instance of AVAudioPlayer, you can declare it as a global variable, so just type this line of code below your import statements: var audioPlayer = AVAudioPlayer() In our demo project we have also added a Label that will show our audio player status: @IBOutlet weak var soundStatusLabel: UILabel! All right, now we’ll see how to play our sound when tapping the Play Button: @IBAction func playButton(sender: AnyObject) { var soundURL: NSURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("mySound", ofType: "wav")!)! var error:NSError? audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: &error) audioPlayer.prepareToPlay() audioPlayer.play() soundStatusLabel.text = "Sound is playing" } Just a few lines of code to make the magic, isn’t it great? Before going through the above method line by line, we need to drag a sound file into Supporting Files in XCode. It can be a .wav or .mp3 sound file, in our demo project we’ve used a .wav file and renamed it as “mySound“. Here’s what the play button's method does: - This is our IBAction function. - Here we initialize an url for our sound so XCode will get the sound file we want to play from its path, name and type. - A simple NSError declaration, needed in case something will go wrong with playing the sound file. - We tell our player object to get the sound file by the url previously declared. - Prepare the framework to run - And finally play our sound. - Change text to our label accordingly to the status of the audio player. Here’s the code for the Pause button instead: @IBAction func pauseButton(sender: AnyObject) { audioPlayer.pause() soundStatusLabel.text = "Sound is on pause" } - IBAction instance for the button - Pause the audio player - Update the status Label text And finally our Stop button’s code: @IBAction func stopButton(sender: AnyObject) { audioPlayer.stop() soundStatusLabel.text = "Sound has stopped playing" } - IBAction instance - Our audio player will stop playing music/sound - Update the status label once again Run your project and play with the buttons, enjoy your minimal music player. Thanks for reading, and don't forget to check out our other tutorials! © 2015 cubycode
https://hubpages.com/technology/Play-a-music-or-sound-with-AVAudioPlayer-in-Swift
CC-MAIN-2018-22
refinedweb
461
60.85
You can subscribe to this list here. Showing 1 results of 1 Hi Jeff, Jeff Peery wrote: > Hello, I'm a newbie with py2exe and I'm trying to use it with InnoSetup > and a simple script I wrote. I attached my program. When I run the thing > it can't find the frame1.pyo file... I'm not sure why. any help would be > much appreciated! Thanks! I am not sure what your problem is. Did the following: Frame1.py: commented the import of serial as I don't have that, at least import fails and in OnButton1Button I just put a return in. After this I run py2exe from within Boa (Menu File, last py2exe option for setup.py) but it has problems with some of the innosetup stuff. Removed the "self.compiled_files" from the following. script = InnoScript(appname, lib_dir, dist_dir, self.windows_exe_files, self.lib_files) #, self.compiled_files) At this point it compiles but the Inno stuff is still not completing. If I go to the dist folder I can run "AgSetUnits.exe" and get the same display then if I run it from within Boa. To get the InnoSetup stuff to complete I had to remove the Compression settings and all "{cm" stuff. After that it generates an InnoSetup exe which I can run (did not complete and install, but I guess that would work too). Can you run the exe in the dist folder? See you Werner > > ------------------------------------------------------------------------ > New Yahoo! Messenger with Voice. Call regular phones from your PC > <**> > and save big. > > > ------------------------------------------------------------------------
http://sourceforge.net/p/py2exe/mailman/py2exe-users/?style=flat&viewmonth=200605&viewday=10
CC-MAIN-2015-27
refinedweb
254
77.84
To quote stephane, "I'm back on the topic of coding guidelines." We have a few magic properties in the tool, like build.compiler and other things, to change system behaviour. I would like to propose that any more of these we create are prefixed with a well known namespace, like ant.taskname. e.g ant.javac.build.compiler This would ensure that the addition of any new such magic properties would not impact any build files which are not using properties in the build file beginning with ant. This would be the equivalent to the _ prefix in C for runtime functions and variables. -- 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/200202.mbox/%3C0acb01c1b682$a09c3500$b81c570f@cv.hp.com%3E
CC-MAIN-2016-44
refinedweb
128
57.87
This is a dummy release performed for the following goals: Now depends on Kombu 2.1.5. Django documentation has been moved to the main Celery docs. New celeryd_init signal celerydctl can now be configured on the command line. Like with celeryd it is now possible to configure celery settings on the command line for celeryctl:$ celeryctl --. Autoreload’s inotify support has been improved. Contributed by Mher Movsisyan. The Django broker documentation has been improved. Removed confusing warning at top of routing user guide. See What’s new in Celery 2.5. Since the changelog has gained considerable size, we decided to do things differently this time: by having separate “what’s new” documents for major version changes. Bugfix releases will still be found in the changelog. Periodic task interval schedules were accidentally rounded down, resulting in some periodic tasks being executed early. Logging of humanized times in the celerybeat log is now more detailed. New Brokers section in the Getting Started part of the Documentation This replaces the old Using Celery with Redis/Database as the messaging queue. tutorial, and adds documentation for MongoDB, Beanstalk and CouchDB. . Processes pool: Fixed rare deadlock at shutdown (Issue #523). Fix contributed by Ionel Maries Christian. Webhook tasks issued the wrong HTTP POST headers (Issue #515). The Content-Type header has been changed from application/json ⇒ application/x-www-form-urlencoded, and adds a proper Content-Length header. Fix contributed by Mitar. Daemonization cookbook: Adds a configuration example using Django and virtualenv together (Issue #505). Contributed by Juan Ignacio Catalano. generic init scripts now automatically creates log and pid file directories (Issue #545). Contributed by Chris Streeter. Now supports Python 3. Fixed deadlock in worker process handling (Issue #496). A deadlock could occur after spawning new child processes because the logging library’s mutex was not properly reset after fork. The symptoms of this bug affecting would be that the worker simply stops processing tasks, as none of the workers child processes are functioning. There was a greater chance of this bug occurring with maxtasksperchild_EXPIRES setting. The old CELERY_AMQP_TASK_RESULT_EXPIRES setting has been deprecated and will be removed in version 3.0. Note that this means that the result backend requires RabbitMQ 1.1.0 or higher, and that you have to disable expiration if you are running with an older version. You can do so by disabling the CELERY_TASK_RESULT_EXPIRES setting:CELERY_TASK_RESULT_EXPIRES = None Eventlet: Fixed problem with shutdown (Issue #457). Broker transports can be now be specified using URLs The broker can now be specified as an URL instead. This URL must have the format:transport://user:password@hostname:port/virtual_host for example the default broker is written as:amqp://guest:guest@localhost:5672// The scheme is required, so that the host is identified as setting has been added as an alias to BROKER_HOST. Any broker setting specified in both the URL and in the configuration will be ignored, if a setting is not provided in the URL then the value from the configuration will be used as default. Also, programs now support the -b|--broker option to specify a broker URL on the command line:$ celeryd -b redis://localhost $ celeryctl -b amqp://guest:guest@localhost//e The environment variable CELERY_BROKER_URL can also be used to easily override the default broker used. The deprecated celery.loaders.setup_loader() function has been removed. The CELERY_TASK_ERROR_WHITELIST settingELIST setting has been deprecated, and will be removed completely in version 3.0. Additional Deprecations The following functions has been deprecated and is scheduled for removal in version 3.0: The following settings has been deprecated and is scheduled for removal in version 3.0: No longer depends on pyparsing. Now depends on Kombu 1.4.3. CELERY_IMPORTS can now be a scalar value (Issue #485). It was not saved at exit. This has now been fixed and it should again remember previously revoked tasks when a --statedb is enabled. Adds EMAIL_USE_TLS to enable secure SMTP connections (Issue #418).IZER setting (Issue #435). This means that only the database (django/sqlalchemy) backends currently does not support using custom serializers. Contributed by Steeve Morin Logging calls no longer manually formats messages, but delegates that to the logging system, so tools like Sentry can easier work with the messages (Issue #445). Contributed by Chris Adams. celeryd_multi now supports a stop_verify command to wait for processes to shutdown. Cache backend did not work if the cache key was unicode (Issue #504). Fix contributed by Neil Chintomby. New setting CELERY_RESULT_DB_SHORT_LIVED_SESSIONS added, which if enabled will disable the caching of SQLAlchemy sessions (Issue #449). Contributed by Leo Dirac. All result backends now implements __reduce__ so that they can be pickled (Issue #441). Fix contributed by Remy Noel celeryd-multi did not work on Windows (Issue #472). New-style CELERY_REDIS_* settings now takes precedence over the old REDIS_* configuration keys (Issue #508). Fix contributed by Joshua Ginsberg Generic celerybeat init script no longer sets bash -e (Issue #510). Fix contributed by Roger Hu. Documented that Chords do not work well with redis-server versions before 2.2. Contributed by Dan McGee. The CELERYBEAT_MAX_LOOP_INTERVAL setting was not respected. inspect.registered_tasks renamed to inspect.registered for naming consistency. The previous name is still available as an alias. Contributed by Mher Movsisyan Worker logged the string representation of args and kwargs without safe guards (Issue #480). RHEL init script: Changed celeryd startup did not respect the timeout argument (Issue #512). celerybeat/celeryev’s –workdir option did not chdir file is now sorted alphabetically. Also, as you may have noticed the contributors of new features/fixes are now mentioned in the Changelog. . Improved Contributing guide. If you’d like to contribute to Celery you should read this guide: We are looking for contributors at all skill levels, so don’t hesitate! Now depends on Kombu 1.3.1 Task.request now contains the current worker host name (Issue #460). Available as task.request.hostname. (see celery.app.AppPickler). purge/discard_all was not working correctly (Issue #455). The coloring of log messages didn’t handle non-ASCII data well (Issue #427). [Windows] the multiprocessing pool tried to import os.kill even though this is not available there (Issue #450). Fixes case where the worker could become unresponsive because of tasks exceeding the hard time limit. The task-sent event was missing from the event reference. ResultSet.iterate now returns results as they finish (Issue #459). This was not the case previously, even though the documentation states this was the expected behavior. Retries will no longer be performed when tasks are called directly (using __call__). Instead the exception passed to retry will be re-raised. Eventlet no longer crashes if autoscale is enabled. growing and shrinking eventlet pools is still not supported. py24 target removed from tox.ini. Now requires Kombu 1.2.1 Results are now disabled by default. The AMQP backend was not a good default because often the users were not consuming the results, resulting in thousands of queues. While the queues can be configured to expire if left unused, it was not possible to enable this by default because this was only available in recent RabbitMQ versions (2.1.1+) With this change enabling a result backend will be a conscious choice, which will hopefully lead the user to read the documentation and be aware of any common pitfalls with the particular backend. The default backend is now a dummy backend (celery.backends.base.DisabledBackend). Saving state is simply an noop operation, and AsyncResult.wait(), .result, .state, etc. will raise a NotImplementedError telling the user to configure the result backend. For help choosing a backend please see Result Backends. If you depend on the previous default which was the AMQP backend, then you have to set this explicitly before upgrading:CELERY_RESULT_BACKEND = "amqp" Note For django-celery users the default backend is still database, and results are not disabled by default. The Debian init scripts have been deprecated in favor of the generic-init.d init scripts. In addition generic init scripts for celerybeat and celeryev has been added. Automatic connection pool support. The pool is used by everything that requires a broker connection. For example applying tasks, sending broadcast commands, retrieving results with the AMQP result backend, and so on. The pool is disabled by default, but you can enable it by configuring the BROKER_POOL_LIMIT setting:BROKER_POOL_LIMIT = 10 A limit of 10 means a maximum of 10 simultaneous connections can co-exist. Only a single connection will ever be used in a single-thread environment, but in a concurrent environment (threads, greenlets, etc., but not processes) when the limit has been exceeded, any try to acquire a connection will block the thread and wait for a connection to be released. This is something to take into consideration when choosing a limit. A limit of None or 0 means no limit, and connections will be established and closed every time. Introducing Chords (taskset callbacks). A chord is a task that only executes after all of the tasks in a taskset has finished executing. It’s a fancy term for “taskset callbacks” adopted from Cω). It works with all result backends, but the best implementation is currently provided by the Redis result backend. Here’s an example chord:>>> chord(add.subtask((i, i)) ... for i in xrange(100))(tsum.subtask()).get() 9900 Please read the Chords section in the user guide, if you want to know more. Time limits can now be set for individual tasks. To set the soft and hard time limits for a task use the time_limit and soft_time_limit attributes:import time @task(time_limit=60, soft_time_limit=30) def sleeptask(seconds): time.sleep(seconds) If the attributes are not set, then the workers default time limits will be used. New in this version you can also change the time limits for a task at runtime using the time_limit() remote control command:>>> from celery.task import control >>> control.time_limit("tasks.sleeptask", ... soft=60, hard=120, reply=True) [{'worker1.example.com': {'ok': 'time limits set successfully'}}] Only tasks that starts executing after the time limit change will be affected. Note Soft time limits will still not work on Windows or other platforms that do not have the SIGUSR1 signal. CELERY_ prefix. The old names are still supported but pending deprecation. PyPy: The default pool implementation used is now multiprocessing if running on PyPy 1.5. celeryd-multi: now supports “pass through” options. Pass through options makes it easier to use celery without a configuration file, or just add last-minute options on the command line. Example use: - $ celeryd-multi start 4 -c 2 – broker.host=amqp.example.com - broker.vhost=/ celery.disable_rate_limits=yes celerybeat: Now retries establishing the connection (Issue #419). celeryctl: New list bindings command. Lists the current or all available bindings, depending on the broker transport used. Heartbeat is now sent every 30 seconds (previously every 2 minutes). ResultSet.join_native() and iter_native() is now supported by the Redis and Cache result backends. This is an optimized version of join() using the underlying backends ability to fetch multiple results at once. Can now use SSL when sending error e-mails by enabling the EMAIL_USE_SSL setting. events.default_dispatcher(): Context manager to easily obtain an event dispatcher instance using the connection pool. Import errors in the configuration module will not be silenced anymore. ResultSet.iterate: Now supports the timeout, propagate and interval arguments. with_default_connection -> with default_connection TaskPool.apply_async: Keyword arguments callbacks and errbacks has been renamed to callback and errback and take a single scalar value instead of a list. No longer propagates errors occurring during process cleanup (Issue #365) Added TaskSetResult.delete(), which will delete a previously saved taskset result. Celerybeat now syncs every 3 minutes instead of only at shutdown (Issue #382). Monitors now properly handles unknown events, so user-defined events are displayed. Terminating a task on Windows now also terminates all of the tasks child processes (Issue #384). celeryd: -I|--include option now always searches the current directory to import the specified modules. Cassandra backend: Now expires results by using TTLs. Functional test suite in funtests is now actually working properly, and passing tests. . New signals: after_setup_logger and after_setup_task_logger These signals can be used to augment logging configuration after Celery has set up logging. Redis result backend now works with Redis 2.4.4. celeryd_multi: The --gid option now works correctly. celeryd: Retry wrongfully used the repr of the traceback instead of the string representation. App.config_from_object: Now loads module, not attribute of module. Fixed issue where logging of objects would give “<Unrepresentable: ...>” Now depends on Kombu 1.1.2. Dependency lists now explicitly specifies that we don’t want python-dateutil 2.x, as this version only supports py3k. If you have installed dateutil 2.0 by accident you should downgrade to the 1.5.0 version:pip install -U python-dateutil==1.5.0 or by easy_install:easy_install -U python-dateutil==1.5.0 The new WatchedFileHandler broke Python 2.5 support (Issue #367). Task: Don’t use app.main if the task name is set explicitly. Sending emails did will not interfere with publishing the task result (Issue #365). Defining tasks did not work properly when using the Django shell_plus utility (Issue #366). arguments. socket.error was raised. is renamed or deleted. backends. gevent: Now supports ETA tasks. But gevent still needs CELERY_DISABLE_RATE_LIMITS=True to work. TaskSet User Guide: now contains TaskSet callback recipes. Eventlet: New signals: - eventlet_pool_started - eventlet_pool_preshutdown - eventlet_pool_postshutdown - eventlet_pool_apply See celery.signals for more information. New BROKER_TRANSPORT_OPTIONS setting can be used to pass additional arguments to a particular broker transport. celeryd: worker_pid is now part of the request info as returned by broadcast commands. TaskSet.apply/Taskset.apply_async now accepts an optional taskset_id argument. The taskset_id (if any) is now available in the Task request context. SQLAlchemy result backend: taskset_id and taskset_id columns now have a unique constraint. (Tables need to recreated for this to take affect). Task Userguide: Added section about choosing a result backend. Removed unused attribute AsyncResult.uuid. will receive any after 5 seconds with no worker processes). celerybeat: Now creates pidfile even if the --detach option is not set. eventlet/gevent: The broadcast command consumer is now running in a separate greenthread. This ensures broadcast commands will take priority even if there are many active tasks. Internal module celery.worker.controllers renamed to celery.worker.mediator. celeryd: Threads now terminates the program by calling os._exit, as it is the only way to ensure exit in the case of syntax errors, or other unrecoverable errors. Fixed typo in maybe_timedelta (Issue #352). celeryd: Broadcast commands now logs with loglevel debug instead of warning. AMQP Result Backend: Now resets cached channel if the connection is lost. Polling results with the AMQP result backend was. celeryd: If the message body can’t be decoded, it is now passed through safe_str when logging. This to ensure we don’t get additional decoding errors when trying to log the failure. app.config_from_object/app.config_from_envvar now works for all loaders. Now emits a user-friendly error message if the result backend name is unknown (Issue #349). celery.contrib.batches: Now sets loglevel and logfile in the task request so task.get_logger works with batch tasks (Issue #357). celeryd: is re-enabled as soon as the value is below the limit again. cursesmon: Fixed unbound local error (Issue #303). eventlet/gevent is now imported on demand so autodoc can import the modules without having eventlet/gevent installed. celeryd: Ack callback now properly handles AttributeError. Task.after_return is now always called after the result has been written. Cassandra Result Backend: Should now work with the latest pycassa version. multiprocessing.Pool: No longer cares if the putlock semaphore is released too many times. (this can happen if one or more worker processes are killed). SQLAlchemy Result Backend: Now returns accidentally removed date_done again (Issue #325). Task.request contex is now always initialized to ensure calling the task function directly works even if it actively uses the request context. Exception occuring when iterating over the result from TaskSet.apply fixed. eventlet: Now properly schedules tasks with an ETA in the past. Now depends on Kombu 1.0.3 Task.retry now supports a max_retries argument, used to change the default value. multiprocessing.cpu_count may raise NotImplementedError on platforms where this is not supported (Issue #320). Coloring of log messages broke if the logged object was not a string. Fixed several typos in the init script documentation. A regression caused Task.exchange and Task.routing_key to no longer have any effect. This is now fixed. Routing Userguide: Fixes typo, routers in CELERY_ROUTES must be instances, not classes. celeryev did not create pidfile even though the --pidfile argument was set. Task logger format was no longer used. (Issue #317). The id and name of the task is now part of the log message again. A safe version of repr() is now used in strategic places to ensure objects with a broken __repr__ does not crash the worker, or otherwise make errors hard to understand (Issue #298). Remote control command active_queues: did not account for queues added at runtime. In addition the dictionary replied by this command now has a different structure: the exchange key is now a dictionary containing the exchange declaration in full. The -Q option to celeryd. Celerybeat could not read the schedule properly, so entries in CELERYBEAT_SCHEDULE would not be scheduled. Task error log message now includes exc_info again. The eta argument can now be used with task.retry. Previously it was overwritten by the countdown argument. celeryd-multi/celeryd_detach: Now logs errors occuring when executing the celeryd command. daemonizing cookbook: Fixed typo --time-limit 300 -> --time-limit=300 Colors in logging broke non-string objects in log messages. setup_task_logger no longer makes assumptions about magic task kwargs. Eventlet pool was leaking memory (Issue #308). Deprecated function celery.execute.delay_task was accidentally removed, now available again. BasePool.on_terminate stub did not exist exist. Smarter handling of unicode decod errors when logging errors. Carrot has been replaced with Kombu Kombu is the next generation messaging frameworkzip is able to perform worker remote control commands. Magic keyword arguments pending deprecation. The magic keyword arguments were responsibile for many problems and quirks: notably issues with tasks and decorators, and name collisions in keyword arguments for the unaware. It wasn’t easy to find a way to deprecate the magic keyword arguments, but we think this is a solution that makes sense and it will willators emits a PendingDeprecationWarning with a helpful message urging you to change your code, in version 2.4 this will be replaced with a DeprecationWarning, and in version 3.0 the celery.decorators module will be removed and no longer exist. Similarly, the task.accept_magic_kwargs attribute will no longer have any effect starting from version 3.0. The magic keyword arguments are now available as task.request This is called the context. Using thread-local storage the context contains state that is related to the current request. It is mutable and you can add custom attributes that will -P|--pool argument to celeryd, or globally using the CELERYD_POOL setting. This can be the full name of a class, or one of the following aliases: processes, eventlet, gevent. For more information please see the Concurrency with Eventlet section in the User Guide. Why not gevent? For our first alternative concurrency implementation we have focused on Eventlet, but there are urged to make some noise if you’re currently stuck with Python 2.4. Complain to your package maintainers, sysadmins and bosses: tell them it’s time to move on! Apart from wanting to take advantage of with-statements, coroutines, conditional expressions and enhanced try blocks,ported for as long as there is interest. celeryd: Now supports Autoscaling of child worker processes. The --autoscale option is an extended version of pdb that enables remote debugging of processes that does not have terminal access. Example usage:from celery.contrib import rdb from celery.task import task @task def add(x, y): result = x + y rdb.set_trace() # <- set breakpoint `celeryd` encounters your breakpoint it will log the following information:: [INFO/MainProcess] Got task from broker: will be presented with a ``pdb`` shell:: $ will not be stored until there does not collide with older versions. If you would like to remove the old exchange you can do so by executing the following command:$ camqadm exchange.delete celeryevent celeryd now starts without configuration, and configuration can be specified directly on the command line. Configuration options must appear after the last argument, separated by two dashes: $ celeryd module. timeline. accompanying functions: dmap, dmap_async, and execute_remote. Executing arbitrary code using pickle is a potential security issue if someone gains unrestricted access to the message broker. If you really need this functionality, then you would have to add this to your own project. [Security: Low severity] The stats command no longer transmits the broker password. One would have needed an authenticated broker connection to receive this password in the first place, but sniffing the password at the wire level would have been possible if using unencrypted communication. setting, and tweaked by the CELERY_TASK_PUBLISH_RETRY_POLICY setting. are encouraged to use the more flexible CELERYBEAT_SCHEDULE setting. Built-in daemonization support of celeryd using celeryd-multi is no longer experimental and is considered production quality. See Generic init scripts if you want to use the new generic init scripts. Added support for message compression using the CELERY_MESSAGE_COMPRESSION setting, or the compression argument to apply_async. This can also be set using routers. SIGUSR1 signal. (Does module event. The following fields have been added to all events in the worker class: - sw_ident: Name of worker software (e.g. celeryd). -. option. option. TaskSet.apply_async: Now supports custom publishers by using the publisher argument. Added CELERY_SEND_TASK_SENT_EVENT setting. If enabled an event will be sent with every task, so monitors can track tasks before the workers receive them. scheduled tasks. The configuration module and loader to use can now be specified on the command line. For example:$ celeryd --config=celeryconfig.py --loader=myloader.Loader Added signals: beat_init and beat_embedded_init - celery.signals.beat_init Dispatched when celerybeat starts (either standalone or embedded). Sender is the celery.beat.Service instance. - celery.signals.beat_embedded_init Dispatched in addition to the beat_init signal when celerybeat is started as an embedded process. Sender is the celery.beat.Service instance. Redis result backend: Removed deprecated settings REDIS_TIMEOUT and REDIS_CONNECT_RETRY. CentOS init script for celeryd now available in contrib/centos. Now depends on pyparsing version 1.5.0 or higher. There have been reported issues using Celery with pyparsing 1.4.x, so please upgrade to the latest version. Lots of new unit tests written, now with a total coverage of 95%. celeryev Curses Monitor: Improved resize handling and UI layout (Issue #274 + Issue #276) AMQP Backend: Exceptions occurring while sending task results are now propagated instead of silenced. celeryd will then show the full traceback of these errors in the log. AMQP Backend: No longer deletes the result queue after successful poll, as this should be handled by the CELERY_AMQP_TASK_RESULT_EXPIRES setting instead. AMQP Backend: Now ensures queues are declared before polling results. Windows: celeryd: Show error if running with -B option. Running celerybeat embedded is known not to work on Windows, so users are encouraged to run celerybeat as a separate service instead. Windows: Utilities no longer output ANSI color codes on Windows camqadm: Now properly handles Ctrl+C by simply exiting instead of showing confusing traceback. Windows: All tests are now passing on Windows. Remove bin/ directory, and scripts section from setup.py. This means we now rely completely on setuptools entrypoints. Jython: celeryd now runs on Jython using the threaded pool. All tests pass, but there may still be bugs lurking around the corners. PyPy: celeryd now runs on PyPy. It runs without any pool, so to get parallel execution you must start multiple instances (e.g. using celeryd) Execution options to apply_async now takes precedence over options returned by active routers. This was a regression introduced recently (Issue #244). celeryev curses monitor: Long arguments are now truncated so curses doesn’t crash with out of bounds errors. (Issue #235). celeryd: EMAIL_TIMEOUT setting. celeryev: Now works on Windows (but the curses monitor won’t work without having curses). Unit test output no longer emits non-standard characters. celeryd: The broadcast consumer is now closed if the connection is reset. celeryd: Now properly handles errors occurring while trying to acknowledge the message. encoding. (Issue #286). EagerResult can now be pickled (Issue #288). Fixed deadlocks in timer2 which could lead to djcelerymon/celeryev -c hanging. EventReceiver: now sends heartbeat request to find workers. This means celeryev and friends finds workers immediately at startup. celeryev cursesmon: Set screen_delay to 10ms, so the screen refreshes more often. Fixed pickling errors when pickling AsyncResult on older Python versions. celeryd: prefetch count was decremented by eta tasks even if there were no active prefetch limits. Now working on Windows again. Removed dependency on the pwd/grp modules. snapshots: Fixed race condition leading to loss of events. celeryd:_SOFT_TASK_TIME_LIMIT -> CELERYD_TASK_SOFT_TIME_LIMIT. See issue #214 control command dump_scheduled: was using old .info attribute occurring in the restart command. celeryd: Accidentally tried to use additional command line arguments. This would lead to an error like: got multiple values for keyword argument ‘concurrency’. Additional command line arguments are now ignored, and does not produce this error. However – we do reserve the right to use positional arguments in the future, so please do not depend on this behavior. celerybeat: Now respects routers and task execution options again. celerybeat: Now reuses the publisher instead of the connection. Cache result backend: Using float as the expires argument to cache.set is deprecated by the memcached libraries, so we now automatically cast to int. unit tests: No longer emits logging and warnings in test output. Now depends on carrot version 0.10.7. Added CELERY_REDIRECT_STDOUTS, and CELERYD_REDIRECT_STDOUTS_LEVEL settings. CELERY_REDIRECT_STDOUTS is used by celeryd and celerybeat. All output to stdout and stderr will be redirected to the current logger if enabled. CELERY_REDIRECT_STDOUTS_LEVEL decides the log level used and is WARNING by default. Added CELERYBEAT_SCHEDULER setting.. - cancel_consumer(queue_name)¶ Tells the worker to stop consuming from queue (by queue name). Commands also added to celeryctl and inspect. Example using celeryctl to start consuming from queue “queue”, in exchange “exchange”, of type “direct” using binding key “key”:$ celeryctl inspect add_consumer queue exchange direct key $ celeryctl inspect cancel_consumer queue See celeryctl: Management Utility. Celery is now following the versioning semantics defined by semver. This means we are no longer allowed to use odd/even versioning semantics By our previous versioning scheme this stable release should have. See Django Admin Monitor and Using outside of Django for more information. If you get an error after upgrading saying: AttributeError: ‘module’ object has no attribute ‘system’, Then this is because the celery.platform module has been renamed to celery.platforms to not collide with the built-in platform module.* Added support for expiration of AMQP results (requires RabbitMQ 2.1.0) The new configuration option CELERY_AMQP_TASK_RESULT_EXPIRES sets the expiry time in seconds (can be int or float):CELERY_AMQP_TASK_RESULT_EXPIRES = 30 * 60 # 30 minutes. CELERY_AMQP_TASK_RESULT_EXPIRES = 0.80 # 800 ms. celeryev: Event Snapshots If enabled, celeryd sends messages about what the worker is doing. These messages are called “events”. The events are used by real-time monitors to show what the cluster is doing, but they. See Using outside of Django for information about using this monitor if you’re not using Django. celeryev available, see Running celeryd as a daemon for more information. New command line arguments to celeryev: - -c|--camera: Snapshot camera class to use. - --logfile|-f: Log file - --loglevel|-l: Log level - --maxrate|-r: Shutter rate limit. - --freq|-F: Shutter frequency The --camera argument seconds. See also Django Admin Monitor and Snapshots. broadcast(): Added callback argument, this can be used to process replies immediately as they arrive. celeryctl: New command-line utility to manage and inspect worker nodes, apply tasks and inspect the results of tasks. See also The celeryctl: Management Utility has been expired it will be marked as revoked (celery.exceptions 3rd argument, this will be used for all defined loggers. Remember that celeryd also redirects stdout and stderr to the celery logger, if manually configure logging you also need to redirect the stdouts manually:from logging.config import fileConfig from celery import log def setup_logging(**kwargs): import logging fileConfig("logging.conf") stdouts = logging.getLogger("mystdoutslogger") log.redirect_stdouts_to_logger(stdouts, loglevel=logging.WARNING) celeryd: Added command-line option -I/--include: A comma separated list of (task) modules to be imported. Example:$ celeryd -I app1.tasks,app2.tasks celeryd: now emits a warning if running as the root user (euid is 0). celery.messaging.establish_connection(): Ability to override defaults used using keyword argument “defaults”. celeryd: Now uses multiprocessing.freeze_support() so that it should work with py2exe, PyInstaller, cx_Freeze, etc. celeryd: Now includes more metadata for the STARTED state: PID and host name of the worker that started the task. See issue #181 subtask: Merge additional keyword arguments to subtask() into task keyword arguments. e.g.:>>> s = subtask((1, 2), {"foo": "bar"}, baz=1) >>> s.args (1, 2) >>> s.kwargs {"foo": "bar", "baz": 1} See issue #182. celeryd: Now emits a warning if there is already a worker node using the same name running on the same virtual host. AMQP result backend: Sending of results are now retried if the connection is down.LostError exception occurs (worker process disappeared). celeryd: Store FAILURE result if one of the *TimeLimitExceeded exceptions occurs. Refactored the periodic task responsible for cleaning up results. - - The backend cleanup task is now only added to the schedule if - CELERY_TASK_RESULT_EXPIRES sqla/cache/redis/tyrant backends. (Forget and remove task result). See issue #184. TaskSetResult.join: Added ‘propagate=True’ argument. When set to False exceptions occurring in subtasks will not be re-raised. Added Task.update_state(task_id, state, meta) as a shortcut to task.backend.store_result(task_id, meta, state). The backend interface is “private” and the terminology outdated, so better to move this to Task module. Exceptions occurring in Mediator+Pool callbacks are now caught and logged instead of taking down the worker. Redis result backend: Now supports result expiration using the Redis EXPIRE command. unit tests: Don’t leave threads running at tear down. celeryd: Task results shown in logs are now truncated to 46 chars. This way tasks introspects more like regular functions. Task.retry: Now raises TypeError if kwargs argument is empty. See issue #164. timedelta_seconds: Use timedelta.total_seconds if. - State.freeze_while(fun)¶ With a function to apply, freezes the stream before, and replays the buffer after the function returns. EventReceiver.capture Now supports a timeout keyword argument. celeryd: The mediator thread is now disabled if CELERY_RATE_LIMITS is enabled, and tasks are directly sent to the pool without going through the ready queue (Optimization).. celeryd no longer marks tasks as revoked if CELERY_IGNORE_RESULT is enabled. See issue #207. AMQP Result backend: Fixed bug with result.get() if CELERY_TRACK_STARTED enabled.. celeryd-multi: Added daemonization support. celeryd. celeryd-multi: start command renamed to show. celeryd-multi start will now actually start and detach worker nodes. To just generate the commands you have to use celeryd-multi show. celeryd: Added –pidfile argument. The worker will write its pid when it starts. The worker will not be started if this file exists and the pid contained is still alive. Added generic init.d script using celeryd-multi Added User guide section: Monitoring Added user guide section: Periodic Tasks Moved from getting-started/periodic-tasks and updated. tutorials/external moved to new section: “community”. References has been added to all sections in the documentation. This makes it easier to link between documents. celeryd: Properly handle connection errors happening while closing consumers. celeryd: Events are now buffered if the connection is down, then sent when the connection is re-established. No longer depends on the mailer package. This package had a name space collision with django-mailer, so its functionality was replaced. Redis result backend: Documentation typos: Redis doesn’t have database names, but database numbers. The default database is now 0. inspect: registered_tasks was requesting an invalid command because of a typo. See issue #170. CELERY_ROUTES: Values defined in the route should now have precedence over values defined in CELERY_QUEUES when merging the two. With the follow settings:CELERY_QUEUES = {"cpubound": {"exchange": "cpubound", "routing_key": "cpubound"}} CELERY_ROUTES = {"tasks.add": {"queue": "cpubound", "routing_key": "tasks.add", "serializer": "json"}} The final routing options for tasks.add will become:{"exchange": "cpubound", "routing_key": "tasks.add", "serializer": "json"} This was not the case before: the values in CELERY_QUEUES would take precedence. Worker crashed if the value of CELERY_TASK_ERROR_WHITELIST was not an iterable apply(): Make sure kwargs[“task_id”] is always set. AsyncResult.traceback: Now returns None, instead of raising KeyError if traceback is missing. inspect: Replies did not work correctly if no destination was specified. Can now store result/metadata for custom states. celeryd: A warning is now emitted if the sending of task error emails fails. celeryev: Curses monitor no longer crashes if the terminal window is resized. See issue #160. celeryd: On OS X it is not possible to run os.exec* in a process that is threaded. This breaks the SIGHUP restart handler, and is now disabled on OS X, emitting a warning instead. See issue #152. celery.execute.trace: Properly handle raise(str), which is still allowed in Python 2.4. See issue #175. Using urllib2 in a periodic task on OS X crashed because of the proxy auto detection used in OS X. This is now fixed by using a workaround. See issue #143. Debian init scripts: Commands should not run in a sub shell See issue #163. Debian init scripts: Use the absolute path of celeryd to allow stat See issue #162. getting-started/broker-installation: Fixed typo set_permissions “” -> set_permissions ”.*”. Tasks User Guide: Added section on database transactions. See issue #169. Routing User Guide: Fixed typo “feed”: -> {“queue”: “feeds”}. See issue #169. Documented the default values for the CELERYD_CONCURRENCY and CELERYD_PREFETCH_MULTIPLIER settings. Tasks User Guide: Fixed typos in the subtask example celery.signals: Documented worker_process_init. Daemonization cookbook: Need to export DJANGO_SETTINGS_MODULE in /etc/default/celeryd. Added some more FAQs from stack overflow Daemonization cookbook: Fixed typo CELERYD_LOGFILE/CELERYD_PIDFILE to CELERYD_LOG_FILE / CELERYD_PID_FILE Also added troubleshooting section for the init scripts. Routes: When using the dict route syntax, the exchange for a task could disappear making the task unroutable. See issue #158. Test suite now passing on Python 2.4 No longer have to type PYTHONPATH=. to use celeryconfig in the current directory. This is accomplished by the default loader ensuring that the current directory is in sys.path when loading the config module. sys.path is reset to its original state after loading. Adding the current working directory to sys.path without the user knowing may be a security issue, as this means someone can drop a Python module in the users directory that executes arbitrary commands. This was the original reason not to do this, but if done only when loading the config module, this means that the behavior will only apply to the modules imported in the config module, which I think is a good compromise (certainly better than just explicitly setting PYTHONPATH=. anyway) Experimental Cassandra backend added. celeryd: SIGHUP handler accidentally propagated to worker pool processes. In combination with 7a7c44e39344789f11b5346e9cc8340f5fe4846c this would make each child process start a new celeryd when the terminal window was closed :/ celeryd: Do not install SIGHUP handler if running from a terminal. This fixes the problem where celeryd is launched in the background when closing the terminal. celeryd: Now joins threads at shutdown. See issue #152. Test tear down: Don’t use atexit but nose’s teardown() functionality instead. See issue #154. Debian init script for celeryd: Stop now works correctly. Task logger: warn method added (synonym for warning) Can now define a white list of errors to send error emails for. Example:CELERY_TASK_ERROR_WHITELIST = ('myapp.MalformedInputError') See issue #153. celeryd: Now handles overflow exceptions in time.mktime while parsing the ETA field. LoggerWrapper: Try to detect loggers logging back to stderr/stdout making an infinite loop. Added celery.task.control.inspect: Inspects a running worker. Examples:# Inspect a single worker >>> i = inspect("myworker.example.com") # Inspect several workers >>> i = inspect(["myworker.example.com", "myworker2.example.com"]) # Inspect all workers consuming on this vhost. >>> i = inspect() ### Methods # Get currently executing tasks >>> i.active() # Get currently reserved tasks >>> i.reserved() # Get the current eta schedule >>> i.scheduled() # Worker statistics and info >>> i.stats() # List of currently revoked tasks >>> i.revoked() # List of registered tasks >>> i.registered_tasks() Remote control commands dump_active/dump_reserved/dump_schedule now replies with detailed task requests. Containing the original arguments and fields of the task requested. In addition the remote control command set_loglevel has been added, this only changes the log level for the main process. Worker control command execution now catches errors and returns their string representation in the reply. Functional test suite added celery.tests.functional.case contains utilities to start and stop an embedded celeryd process, for use in functional testing. multiprocessing.pool: Now handles encoding errors, so that pickling errors doesn’t crash the worker processes. The remote control command replies was not working with RabbitMQ 1.8.0’s stricter equivalence checks. If you’ve already hit this problem you may have to delete the declaration:$ camqadm exchange.delete celerycrq or:$ python manage.py camqadm exchange.delete celerycrq A bug sneaked in the ETA scheduler that made it only able to execute one task per second(!) The scheduler sleeps between iterations so it doesn’t consume too much CPU. It keeps a list of the scheduled items sorted by time, at each iteration it sleeps for the remaining time of the item with the nearest deadline. If there are no eta tasks it will sleep for a minimum amount of time, one second by default. A bug sneaked in here, making it sleep for one second for every task that was scheduled. This has been fixed, so now it should move tasks like hot knife through butter. In addition a new setting has been added to control the minimum sleep interval; CELERYD_ETA_SCHEDULER_PRECISION. A good value for this would be a float between 0 and 1, depending on the needed precision. A value of 0.8 means that when the ETA of a task is met, it will take at most 0.8 seconds for the task to be moved to the ready queue. Pool: Supervisor did not release the semaphore. This would lead to a deadlock if all workers terminated prematurely. Added Python version trove classifiers: 2.4, 2.5, 2.6 and 2.7 Tests now passing on Python 2.7. Task.__reduce__: Tasks created using the task decorator can now be pickled. setup.py: nose added to tests_require. Pickle should now work with SQLAlchemy 0.5.x New homepage design by Jan Henrik Helmers: New Sphinx theme by Armin Ronacher: Fixed “pending_xref” errors shown in the HTML rendering of the documentation. Apparently this was caused by new changes in Sphinx 1.0b2. Router classes in CELERY_ROUTES are now imported lazily. Importing a router class in a module that also loads the Celery environment would cause a circular dependency. This is solved by importing it when needed after the environment is set up. CELERY_ROUTES was broken if set to a single dict. This example in the docs should now work again:CELERY_ROUTES = {"feed.tasks.import_feed": "feeds"} CREATE_MISSING_QUEUES was not honored by apply_async. New remote control command: stats Dumps information about the worker, like pool process ids, and total number of tasks executed by type. Example reply:[{'worker.local': 'total': {'tasks.sleeptask': 6}, 'pool': {'timeouts': [None, None], 'processes': [60376, 60377], 'max-concurrency': 2, 'max-tasks-per-child': None, 'put-guarded-by-semaphore': True}}] New remote control command: dump_active Gives a list of tasks currently being executed by the worker. By default arguments are passed through repr in case there are arguments that is not JSON encodable. If you know the arguments are JSON safe, you can pass the argument safe=True. Example reply:>>> broadcast("dump_active", arguments={"safe": False}, reply=True) [{'worker.local': [ {'args': '(1,)', 'time_start': 1278580542.6300001, 'name': 'tasks.sleeptask', 'delivery_info': { 'consumer_tag': '30', 'routing_key': 'celery', 'exchange': 'celery'}, 'hostname': 'casper.local', 'acknowledged': True, 'kwargs': '{}', 'id': '802e93e9-e470-47ed-b913-06de8510aca2', } ]}] Added experimental support for persistent revokes. Use the -S|–statedb argument to celeryd to enable it:$ celeryd --statedb=/var/run/celeryd This will use the file: /var/run/celeryd.db, as the shelve module automatically adds the .db suffix. Celery 2.0 contains backward incompatible changes, the most important being that the Django dependency has been removed so Celery no longer supports Django out of the box, but instead as an add-on package called django-celery. We’re very sorry for breaking backwards compatibility, but there’s also many new and exciting features to make up for the time you lose upgrading, so be sure to read the News section. Quite a lot of potential users have been upset about the Django dependency, so maybe this is a chance to get wider adoption by the Python community as well. Big thanks to all contributors, testers and users! Django integration has been moved to a separate package: django-celery. To upgrade you need to install the django-celery module and change: INSTALLED_APPS = "celery" to: INSTALLED_APPS = "djcelery" If you use mod_wsgi you need to add the following line to your .wsgi file: import os os.environ["CELERY_LOADER"] = "django" The following modules has been moved to django-celery: Importing djcelery will automatically setup Celery to use Django loader. loader. It does this by setting the CELERY_LOADER environment variable to “django” (it won’t change it if a loader is already set.) When the Django loader is used, the “database” and “cache” result backend aliases will point to the djcelery backends instead of the built-in backends, and configuration will be read from the Django settings. The database result backend is now using SQLAlchemy instead of the Django ORM, see Supported Databases for a table of supported databases. The DATABASE_* settings has been replaced by a single setting: CELERY_RESULT_DBURI. The value here should be an SQLAlchemy SQLAlchemy Connection Strings for more information about connection strings. To specify additional SQLAlchemy database engine options you can use the CELERY_RESULT_ENGINE_OPTIONS setting: # echo enables verbose logging from SQLAlchemy. CELERY_RESULT_ENGINE_OPTIONS = {"echo": True} The cache result backend is no longer using the Django cache framework, but it supports mostly the same configuration syntax: CELERY_CACHE_BACKEND = "memcached://A.example.com:11211;B.example.com" To use the cache backend you must either have the pylibmc or python-memcached library installed, of which the former is regarded as the best choice. The support backend types are memcached:// and memory://, we haven’t felt the need to support any of the other backends provided by Django. Default (python) loader now prints warning on missing celeryconfig.py instead of raising ImportError. celeryd raises ImproperlyConfigured if the configuration is not set up. This makes it possible to use –help etc., without having a working configuration. Also this makes it possible to use the client side of celery without being configured:>>> from carrot.connection import BrokerConnection >>> conn = BrokerConnection("localhost", "guest", "guest", "/") >>> from celery.execute import send_task >>> r = send_task("celery.ping", args=(), kwargs={}, connection=conn) >>> from celery.backends.amqp import AMQPBackend >>> r.backend = AMQPBackend(connection=conn) >>> r.get() 'pong' The following deprecated settings has been removed (as scheduled by the deprecation timeline): The celery.task.rest module has been removed, use celery.task.http instead (as scheduled by the deprecation timeline). It’s no longer allowed to skip the class name in loader names. (as scheduled by the deprecation timeline): Assuming the implicit Loader class name is no longer supported, if you use e.g.:CELERY_LOADER = "myapp.loaders" You need to include the loader class name, like this:CELERY_LOADER = "myapp.loaders.Loader" CELERY_TASK_RESULT_EXPIRES now defaults to 1 day. Previous default setting was to expire in 5 days. AMQP backend: Don’t use different values for auto_delete. This bug became visible with RabbitMQ 1.8.0, which no longer allows conflicting declarations for the auto_delete and durable settings. If you’ve already used celery with this backend chances are you have to delete the previous declaration:$ camqadm exchange.delete celeryresults Now uses pickle instead of cPickle on Python versions <= 2.5 cPickle is broken in Python <= 2.5. It unsafely and incorrectly uses relative instead of absolute imports, so e.g.:exceptions.KeyError becomes:celery.exceptions.KeyError Your best choice is to upgrade to Python 2.6, as while the pure pickle version has worse performance, it is the only safe option for older Python versions. celeryev: Curses Celery Monitor and Event Viewer. This is a simple monitor allowing you to see what tasks are executing in real-time and investigate tracebacks and results of ready tasks. It also enables you to set new rate limits and revoke tasks. Screenshot: If you run celeryev with the -d switch it will act as an event dumper, simply dumping the events it receives to standard out:$ celeryev -d -> celeryev: starting capture... casper.local [2010-06-04 10:42:07.020000] heartbeat casper.local [2010-06-04 10:42:14.750000] task received: tasks.add(61a68756-27f4-4879-b816-3cf815672b0e) args=[2, 2] kwargs={} eta=2010-06-04T10:42:16.669290, retries=0 casper.local [2010-06-04 10:42:17.230000] task started tasks.add(61a68756-27f4-4879-b816-3cf815672b0e) args=[2, 2] kwargs={} casper.local [2010-06-04 10:42:17.960000] task succeeded: tasks.add(61a68756-27f4-4879-b816-3cf815672b0e) args=[2, 2] kwargs={} result=4, runtime=0.782663106918 The fields here are, in order: *sender hostname*, *timestamp*, *event type* and *additional event fields*. AMQP result backend: Now supports .ready(), .successful(), .result, .status, and even responds to changes in task state New user guides: celeryd: Standard out/error is now being redirected to the log file. billiard has been moved back to the celery repository. The billiard distribution may be maintained, depending on interest. now depends on carrot >= 0.10.5 now depends on pyparsing celeryd: Added –purge as an alias to –discard. celeryd: Ctrl+C (SIGINT) once does warm shutdown, hitting Ctrl+C twice forces termination. Added support for using complex crontab-expressions in periodic tasks. For example, you can now use: >>> crontab(minute="*/15") or even: >>> crontab(minute="*/30", hour="8-17,1-2", day_of_week="thu-fri") See Periodic Tasks. celeryd: Now waits for available pool processes before applying new tasks to the pool. This means it doesn’t have to wait for dozens of tasks to finish at shutdown because it has applied prefetched tasks without having any pool processes available to immediately accept them. See issue #122. New built-in way to do task callbacks using subtask. See Sets of tasks, Subtasks and Callbacks for more information. TaskSets can now contain several types of tasks. TaskSet has been refactored to use a new syntax, please see Sets of tasks, Subtasks and Callbacks for more information. The previous syntax is still supported, but will be deprecated in version 1.4. TaskSet failed() result was incorrect. See issue #132. Now creates different loggers per task class. See issue #129. Missing queue definitions are now created automatically. You can disable this using the CELERY_CREATE_MISSING_QUEUES setting. The missing queues are created with the following options:CELERY_QUEUES[name] = {"exchange": name, "exchange_type": "direct", "routing_key": "name} This feature is added for easily setting up routing using the -Q option to celeryd:$ celeryd -Q video, image See the new routing section of the User Guide for more information: Routing Tasks. New Task option: Task.queue If set, message options will be taken from the corresponding entry in CELERY_QUEUES. exchange, exchange_type and routing_key will be ignored Added support for task soft and hard time limits. New settings added: - Hard time limit. The worker processing the task will be killed and replaced with a new one when this is exceeded. - CELERYD_SOFT_TASK_TIME_LIMIT Soft time limit. The celery.exceptions.SoftTimeLimitExceeded exception will be raised when this is exceeded. The task can catch this to e.g. clean up before the hard time limit comes. New command line arguments to celeryd added: –time-limit and –soft-time-limit. What’s left? This won’t work on platforms not supporting signals (and specifically the SIGUSR1 signal) yet. So an alternative the ability to disable the feature all together on nonconforming platforms must be implemented. Also when the hard time limit is exceeded, the task result should be a TimeLimitExceeded exception. Test suite is now passing without a running broker, using the carrot in-memory backend. Log output is now available in colors. This is only enabled when the log output is a tty. You can explicitly enable/disable this feature using the CELERYD_LOG_COLOR setting. Added support for task router classes (like the django multi-db routers) - New setting: CELERY_ROUTES This is a single, or a list of routers to traverse when sending tasks. Dictionaries in this list converts to a celery.routes.MapRoute instance. Examples:>>> CELERY_ROUTES = {"celery.ping": "default", "mytasks.add": "cpu-bound", "video.encode": { "queue": "video", "exchange": "media" "routing_key": "media.video.encode"}}>>> CELERY_ROUTES = ("myapp.tasks.Router", {"celery.ping": "default}) Where myapp.tasks.Router could be:class Router(object): def route_for_task(self, task, args=None, kwargs=None): if task == "celery.ping": return "default" route_for_task may return a string or a dict. A string then means it’s a queue name in CELERY) New Task handler called after the task returns: after_return(). on_retry()/ on_failure() as einfo keyword argument. celeryd: Added CELERYD_MAX_TASKS_PER_CHILD / --maxtasksperchild Defines the maximum number of tasks a pool worker can process before the process is terminated and replaced by a new one. Revoked tasks now marked with state REVOKED, and result.get() will now raise TaskRevokedError. celery.task.control.ping() now works as expected. apply(throw=True) / CELERY_EAGER_PROPAGATES_EXCEPTIONS: Makes eager execution re-raise task errors. New signal: ~celery.signals.worker_process_init: Sent inside the pool worker process at init. celeryd -Q option: Ability to specify list of queues to use, disabling other configured queues. For example, if CELERY_QUEUES defines four queues: image, video, data and default, the following command would make celeryd only consume from the image and video queues:$ celeryd -Q image,video celeryd: New return value for the revoke control command: Now returns:{"ok": "task $id revoked"} instead of True. celeryd: Can now enable/disable events using remote control Example usage:>>> from celery.task.control import broadcast >>> broadcast("enable_events") >>> broadcast("disable_events") Removed top-level tests directory. Test config now in celery.tests.config This means running the unit tests doesn’t require any special setup. celery/tests/__init__ now configures the CELERY_CONFIG_MODULE and CELERY_LOADER environment variables, so when nosetests imports that, the unit test environment is all set up. Before you run the tests you need to install the test requirements:$ pip install -r contrib/requirements/test.txt Running all tests:$ nosetests Specifying the tests to run:$ nosetests celery.tests.test_task Producing HTML coverage:$ nosetests --with-coverage3 The coverage output is then located in celery/tests/cover/index.html. celeryd: New option –version: Dump version info and exit. celeryd-multi: Tool for shell scripts to start multiple workers. Some examples:# Advanced example with 10 workers: # * Three of the workers processes the images and video queue # * Two of the workers processes the data queue with loglevel DEBUG # * the rest processes the default' queue. $ celeryd-multi start 10 -l INFO -Q:1-3 images,video -Q:4,5:data -Q default -L:4,5 DEBUG # get commands to start 10 workers, with 3 processes each $ celeryd-multi start 3 -c 3 celeryd -n celeryd1.myhost -c 3 celeryd -n celeryd2.myhost -c 3 celeryd- n celeryd3.myhost -c 3 # start 3 named workers $ celeryd-multi start image video data -c 3 celeryd -n image.myhost -c 3 celeryd -n video.myhost -c 3 celeryd -n data.myhost -c 3 # specify custom hostname $ celeryd-multi start 2 -n worker.example.com -c 3 celeryd -n celeryd1.worker.example.com -c 3 celeryd -n celeryd2.worker.example.com -c 3 # Additionl options are added to each celeryd', # but you can also modify the options for ranges of or single workers # 3 workers: Two with 3 processes, and one with 10 processes. $ celeryd-multi start 3 -c 3 -c:1 10 celeryd -n celeryd1.myhost -c 10 celeryd -n celeryd2.myhost -c 3 celeryd -n celeryd3.myhost -c 3 # can also specify options for named workers $ celeryd-multi start image video data -c 3 -c:image 10 celeryd -n image.myhost -c 10 celeryd -n video.myhost -c 3 celeryd -n data.myhost -c 3 # ranges and lists of workers in options is also allowed: # (-c:1-3 can also be written as -c:1,2,3) $ celeryd-multi start 5 -c 3 -c:1-3 10 celeryd-multi -n celeryd1.myhost -c 10 celeryd-multi -n celeryd2.myhost -c 10 celeryd-multi -n celeryd3.myhost -c 10 celeryd-multi -n celeryd4.myhost -c 3 celeryd-multi -n celeryd5.myhost -c 3 # lists also works with named workers $ celeryd-multi start foo bar baz xuzzy -c 3 -c:foo,bar,baz 10 celeryd-multi -n foo.myhost -c 10 celeryd-multi -n bar.myhost -c 10 celeryd-multi -n baz.myhost -c 10 celeryd-multi -n xuzzy.myhost -c 3INT/Ctrl+C killed the pool, abruptly terminating the currently executing tasks. Fixed by making the pool worker processes ignore SIGINT. Should not close the consumers before the pool is terminated, just cancel the consumers. See execute a task by name? Messages are now acknowledged PostgreSQL:ALTER TABLE celery_taskmeta ALTER COLUMN result DROP NOT This means the tasks may be executed twice if the worker crashes in mid (Issue #95)..consumerRequest ....>]}]Request Request Request (Issue #98). Now handles exceptions with Unicode messages correctly in TaskRequest() Unit tests: Don’t disable the django test database tear down, instead fixed the underlying issue which was caused by modifications to the DATABASE_NAME setting (Issue #82). setting makes it easy to swap out the multiprocessing pool with a threaded pool, or how about a twisted/eventlet pool? Consider the competition for the first pool plug-in started! Debian init scripts: Use -a not && (Issue #82). (Issue #83). acknowledged. Note A patch to multiprocessing is currently being worked on, this patch would enable us to use a better solution, and is scheduled for inclusion in the 2.0.0 release. celeryd now shutdowns cleanly when receiving the SIGTERM signal. celeryd now does a cold shutdown if the SIGINT. Warning If you’re using Celery errors executable. statistics. The CELERY_LOADER environment variable2.0. TaskSet.run has been renamed to TaskSet.apply_async. TaskSet.run has now been deprecated, and is scheduled for removal in v2.0. the CELERY_TASK_RESULT_EXPIRES setting. Message format has been standardized and now uses ISO-8601 format for dates instead of datetime. celeryd now responds to the SIGH.http. With more reflective names, sensible interface, and it’s possible to override the methods used to perform HTTP requests. The results of task sets). Log level for stdout/stderr changed from INFO to ERROR ImportErrors are now properly propag. See Cookbook: Retrying Tasks for more information. celeryd log file when detached the task supports. celery.task.base.Task.on_retry(),: - - AMQP_CONNECTION_RETRY - Set to True to enable connection retries. - - AMQP_CONNECTION_MAX mime-type to “application/json” views.task_status now returns exception if state is RETRY Documented default task arguments. Add a sensible __repr__ to ExceptionInfo for easier debugging Thanks to mikedizon workers. So if you’ve had pool workers mysteriously disappearing, log level (–loglevel=DEBUG). Functions/methods with a timeout argument now works correctly. With an iterator yielding task args, kwargs tuples, evenly distribute the processing of its tasks throughout the time window available. Log message Unknown task ignored... now has log level stale PID files Warning Use with caution! Do not expose this URL to the public without first ensuring that connection emails sent to administrators. Warning emails. doesn’t happen for pure functions yet, only Task classes. autodiscover() now works with zipped eggs. celeryd: Now adds current.
https://celery.readthedocs.org/en/2.3/changelog.html
CC-MAIN-2015-32
refinedweb
9,342
51.44
GWT - Applications Before we start with creating actual "HelloWorld" application using GWT, let us see what are the actual parts of a GWT application are − A GWT application consists of following four important parts out of which last part is optional but first three parts are mandatory. - Module descriptors - Public resources - Client-side code - Server-side code Sample locations of different parts of a typical gwt application HelloWord will be as shown below − Module Descriptors A module descriptor is the configuration file in the form of XML which is used to configure a GWT application. A module descriptor file extension is *.gwt.xml, where * is the name of the application and this file should reside in the project's root. Following will be a default module descriptor HelloWorld.gwt.xml for a HelloWorld application − <?xml version = "1.0" encoding = "utf-8"?> <module rename- <!-- inherit the core web toolkit stuff. --> <inherits name = 'com.google.gwt.user.user'/> <!-- inherit the default gwt style sheet. --> <inherits name = 'com.google.gwt.user.theme.clean.Clean'/> <!-- specify the app entry point class. --> <entry-point <!-- specify the paths for translatable code --> <source path = '...'/> <source path = '...'/> <!-- specify the paths for static files like html, css etc. --> <public path = '...'/> <public path = '...'/> <!-- specify the paths for external javascript files --> <script src = "js-url" /> <script src = "js-url" /> <!-- specify the paths for external style sheet files --> <stylesheet src = "css-url" /> <stylesheet src = "css-url" /> </module> Following is the brief detail about different parts used in module descriptor. Public Resources These are all files referenced by your GWT module, such as Host HTML page, CSS or images. The location of these resources can be configured using <public path = "path" /> element in module configuration file. By default, it is the public subdirectory underneath where the Module XML File is stored. When you compile your application into JavaScript, all the files that can be found on your public path are copied to the module's output directory. The most important public resource is host page which is used to invoke actual GWT application. A typical HTML host page for an application might not include any visible HTML body content at all but it is always expected to include GWT application via a <script.../> tag as follows <html> <head> <title>Hello World</title> <link rel = "stylesheet" href = "HelloWorld.css"/> <script language = "javascript" src = "helloworld/helloworld.nocache.js"> </script> </head> <body> <h1>Hello World</h1> <p>Welcome to first GWT application</p> </body> </html> Following is the sample style sheet which we have included in our host page − body { text-align: center; font-family: verdana, sans-serif; } h1 { font-size: 2em; font-weight: bold; color: #777777; margin: 40px 0px 70px; text-align: center; } Client-side Code This is the actual Java code written implementing the business logic of the application and that the GWT compiler translates into JavaScript, which will eventually run inside the browser. The location of these resources can be configured using <source path = "path" /> element in module configuration file. For example Entry Point code will be used as client side code and its location will be specified using <source path = "path" />. A module entry-point is any class that is assignable to EntryPoint and that can be constructed without parameters. When a module is loaded, every entry point class is instantiated and its EntryPoint.onModuleLoad() method gets called. A sample HelloWorld Entry Point class will be as follows − public class HelloWorld implements EntryPoint { public void onModuleLoad() { Window.alert("Hello, World!"); } } Server-side Code This is the server side part of your application and its very much optional. If you are not doing any backend processing with-in your application then you do not need this part, but if there is some processing required at backend and your client-side application interact with the server then you will have to develop these components. Next chapter will make use of all the above mentioned concepts to create HelloWorld application using Eclipse IDE.
https://www.tutorialspoint.com/gwt/gwt_applications.htm
CC-MAIN-2018-34
refinedweb
658
53.81
React 16 (and 16.2) adds some nice quality of life changes along with some performance gains. Return types and Fragments There's a whole slew of new return types in the render method. You can now return a string or number. const Foo = () => 'string' const Foo = () => 25 Often you end up wrapping a group of items in a div or span tag because React requires a wrapping element. React 16 introduced the ability to return arrays of items. const Foo = () => ([ <p key='a'>1</p>, <p key='b'>2</p>, <p key='c'>3</p>, <p key='d'>4</p>, "Some words" ]) But that kind of sucks as you need to add a key to each item, seperate each item by a comma and text must be wrapped in quotes. Yuck. React 16.2 builds on React.Fragment to make a really nice way to wrap a group of items without the extra DOM node. import React, { Fragment } from 'react' const Foo = () => ( <Fragment> <p>1</p> <p>2</p> <p>3</p> <p>4</p> </Fragment> ) There is also a shorthand way of writing Fragment which doesn't require the import. import React from 'react' const Foo = () => ( <> <p>1</p> <p>2</p> <p>3</p> <p>4</p> </> ) This does look a little funky I'll admit, but I think once we've gotten used to it we won't know how we lived without it! Babel will support the <> shorthand syntax in v7. See this blog post for support in various tools. You can use the imported Fragment component right now on Babel 6.x. One thing to note is that you still need to key Fragments when you map over data and such. The shorthand <> does not accept the key attribute unfortunately. import React, { Fragment } from 'react' const Foo = () => ( <Fragment> {[1, 2, 3].map(n => ( <Fragment key={n}> <span>hello</span> <span>world {n}</span> </Fragment> ))} </Fragment> ) The above code will produce an HTML output of this: <span>hello</span> <span>world 1</span> <span>hello</span> <span>world 2</span> <span>hello</span> <span>world 3</span> Finally no more wrappers cluttering our DOM 🎉 Error Handling Prior to React 16, when something went wrong with a component the whole application could crash and it was only visible in the console. That's why packages like redbox-react get over a million downloads a month! To solve this issue, we now have Error Boundaries using a new componentDidCatch lifecycle event. You can wrap potentially breaking components in Error Boundaries and then configure them to show fallback UI if they do break. I modified a component that the official React blog supplies for an Error Boundary that will work in basically any app. import React from 'react' import PropTypes from 'prop-types' class ErrorBoundary extends React.Component { constructor(props) { super(props) this.state = { hasError: false } } componentDidCatch(error, info) { // Display fallback UI this.setState({ hasError: true }) // You can also log the error to an error reporting service // Remove this if you have no error logging logErrorToMyService(error, info) } render() { const { children, errorMessage } = this.props if (this.state.hasError) { // You can render any custom fallback UI return <h1>{errorMessage}</h1> } return {children} } } ErrorBoundary.defaultProps = { errorMessage: 'Something went wrong.' } ErrorBoundary.propTypes = { children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node ]).isRequired, errorMessage: PropTypes.string } export default ErrorBoundary You then just wrap that around anything you think will fail. const foo = () => ( <div> <ErrorBoundary errorMessage='This component is not working properly'> <UnstableComponent> </ErrorBoundary> </div> ) Remember we can customise the UI, it's not just a message. So you could have some really cool fallback content for components. Things to note: componentDidCatchworks just like a regular old catch {}block - Error Boundaries must be class components - Error Boundaries can only catch errors from their children, not errors from themselves Portals Portals provide us with the ability to render things in other DOM nodes outside of the parents scope. This opens up some really cool possibilites for things like modals, dialog boxes, tooltips etc. I've seen many different systems for modals in React across many projects and I never feel like anyone has gotten in right, and that's likely because React didn't have the tools to do it right. Now with Portals we might be able to solve this problem. There's no more passing a function all the way through your React tree or using context. Portals can be used with the simple ReactDOM.createPortal(child, container) function. import React, { Component } from 'react' import ReactDOM from 'react-dom' const Bar = () => ( <p>Through the portal</p> ) class ContactScreen extends Component { constructor(props) { super(props) this.nav = document.querySelector('nav') } render() { return ReactDOM.createPortal( Bar, this.nav ) } } child can be any valid React component and container can be any DOM node. When using styled components or any other css in js system, you're classnames will end up being all mangled strings. It might be worth adding an ID to these components so you can portal to them should you need it. Of course, this isn't just reserved for existing DOM nodes. You can create one on the fly and insert it yourself into the DOM. Custom DOM attributes Previously, you could only use DOM attributes that actually existed, along with aria- and data- prefixed attributes. Now you can use any custom attribute and it'll get passed through to the real DOM element. <div foo='bar' /> Server Side Rendering Server side rendering is not something I've used personally before, so I won't try to act like I know a lot about it. We did use it at a previous company I worked for, but I wasn't involved in the process. So here's a really good article about what's changed in SSR in React 16. (TLDR: it's more performant) Miscellaneous - It got smaller. React + React DOM is now ~30% smaller than before. - They changed the license to MIT 🎉 Discussion Nick Graf gives a nice overview of some these new features in these free egghead.io videos: He explains portals as well, but in his pro course. I'd also mention for those starting with React 16, why the error boundaries component needs to be a class instead of a stateless functional component. componentDidCatchis a life cycle method and life cycle methods are currently only supported in class components. Great article! Heads up, there's a typo in the Portal section where you wrote styled components. :) Thanks! changed it. Thanks for the overviews, this is really useful. Especially fragments look like something I'll be applying right away!
https://practicaldev-herokuapp-com.global.ssl.fastly.net/mildrenben/react-16-and-162-overview---fragments-portals-and-error-boundaries-49
CC-MAIN-2021-04
refinedweb
1,101
64
21 December 2011 08:25 [Source: ICIS news] SINGAPORE (ICIS)--China’s Hengli Group, the fourth largest polyester maker in China, plans to bring on stream two new purified terephthalic acid (PTA) plants, with a total 4.4m tonne/year capacity, in the third quarter of 2012, a company source said on Wednesday. “We are largely on schedule,” the source said. The company plans to bring on stream its first 2.2m tonne/year PTA unit in July and the second 2.2m tonne/year unit in September-October. The two plants are located at ?xml:namespace> “We’ve obtained environmental impact assessment approval from the government one and a half months ago,” the source said. The source said Hengli has located part of its feedstock paraxylene (PX) supply by contracts, but still need to seek more availability. He did not give any details about the contracts. Half of Hengli’s PTA production will be fed into the company’s own polyester plants in Hengli Group has doubled its polyester capacity to 1.6m tonne/year in 2011, adding two 200,000 tonne/year polyester yarn plants and two 200,000 tonne/year polyethylene terephthalate (PET) bottle chip plants. The company plans to add another 200,000 tonne/year polyester yarn plan in 2012, bringing up its total polyester capacity to 1.8m tonnes/year by then. Please visit the complete ICIS plants and projects database
http://www.icis.com/Articles/2011/12/21/9518320/chinas-hengli-group-eyes-4.4m-tonneyr-new-pta-capacity-by-12.html
CC-MAIN-2014-41
refinedweb
236
74.08
I have a large data set and I want to do a convolution calculation using multiple rows that match a criteria. I need to calculate a vector for each row first, and I thought it would be more efficient to store my vector in a dataframe column so I could try and avoid a for loop when I do the convolution. Trouble is, the vectors are variable length and I can't figure out how to do it. Here's a summary of my data: Date State Alloc P 2012-01-01 AK 3 0.5 2012-01-01 AL 4 0.3 … [P, np.zeros(Alloc), 1-P] df['Test'] = [df['P'], np.zeros(df['Alloc'), 1 – df['P']] So here's the answer. piRSquared was almost right, but not quite. There are several parts here. The apply method partially works. It passes a row to the function and you can do a calculation as shown above. The problem is, you get a "ValueError: Shape of passed values is..." error message. The number of columns returned doesn't match the number of columns in the dataframe. My guess is this is because the return value is a list and Pandas isn't interpreting the result correctly. The workaround is to do the apply on a single column. This single column should contain the P value and Alloc value. Here are the steps: Create the merged column: df['temp'] = df[['P','Alloc']].values.tolist() Write a function: def array_p(x): return [x[0]] + [0]*int(x[1]) + [1 - x[0]] (int is needed because the previous line gives floats. I didn't need np.zeros) Apply the function: df['Array'] = temp['temp'].apply(array_p) This works, but obviously involves more steps than it should. If anyone can provide a better answer, I'd love to hear it.
https://codedump.io/share/9McBQzGtGqLH/1/writing-variable-sized-arrays-to-pandas-cells
CC-MAIN-2017-26
refinedweb
307
76.52
Gregory (Grisha) Trubetskoy wrote: > I think I didn't make it clear in the last message: > > In order for this release to be officially announced, at least a few > people on this list need to try it and send in a +1 indicating that it > worked on their system (along with some desciption of what their system > is). *Anyone* on this list can do this, you don't have to be an official > committer or anything of that sort. > > Doing a test could probably take as little as 10 minutes, and I'd > encourage you to do it sooner than later. > > Looking at the log we've only had one download of the > tgz file so far, which isn't encouraging :-) > > Grisha > > On Tue, 14 Oct 2003, Gregory (Grisha) Trubetskoy wrote: > > >>You can get the sneak preview of 3.1.1 beta here: >> >> >> >>Please download it, then do the usual >> >>$ ./configure --with-apxs=/wherever/it/is >>$ make >>$ (su) >># make install >> >>Then >> >>$ cd test >>$ python test.py >> >>And see if any tests fail. I have tested this on FreeBSD 4.8 and OS X >>10.2.8, but not on Linux, as my Linux box is dead ATM. Also Solaris would >>be nice... (as well as Panther, if you have it). I gave it a try on a FreeBSD 4.8 box with Apache 2.0.47 and Python 2.3.2 installed from the ports. mod_python itself seems ok, but the unittests gave me trouble. First, in test/test.py this section guessed wrong about where my DSOs were: # where other modules might be modpath = os.path.split(os.path.split(HTTPD)[0])[0] modpath = os.path.join(modpath, "modules") That resulted in modpath being set to '/usr/local/modules', which was incorrect. I replaced that with this and got a better result: modpath = os.popen('apxs -q LIBEXECDIR', 'r').read().strip() After that, it still wouldn't run the tests, the logs/error_log showed: ---------- [Wed Oct 15 16:23:41 2003] [alert] (2)No such file or directory: getpwuid: couldn't determine user name from uid 4294967295, you probably need to modify the User directive ----------- I patched test/httpdconf.py to allow for "User" and "Group" directives to be added: --- httpdconf.py.original Wed Oct 15 16:24:55 2003 +++ httpdconf.py Wed Oct 15 16:25:56 2003 @@ -147,6 +147,10 @@ def __init__(self, val): Directive.__init__(self, self.__class__.__name__, val) +class Group(Directive): + def __init__(self, val): + Directive.__init__(self, self.__class__.__name__, val) + class IfModule(ContainerTag): def __init__(self, dir, *args): ContainerTag.__init__(self, self.__class__.__name__, dir, args) @@ -291,6 +295,9 @@ def __init__(self, addr, *args): ContainerTag.__init__(self, self.__class__.__name__, addr, args) +class User(Directive): + def __init__(self, val): + Directive.__init__(self, self.__class__.__name__, val) and then hardcoded in some calls to set those in test/test.py: --- test.py.original Wed Oct 15 16:26:24 2003 +++ test.py Wed Oct 15 16:26:56 2003 @@ -255,6 +254,8 @@ LoadModule("dir_module %s" % quoteIfSpace(os.path.join(modpath, "mod_dir.so")))), ServerRoot(SERVER_ROOT), + User('www'), + Group('www'), ErrorLog("logs/error_log"), LogLevel("debug"), LogFormat(r'"%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined'), Not sure how that should be put in in a non-hardwired fashion, but I'd think it'd be important to be able to test using other userids/groups, since it caused trouble before with the mutex creation/graceful restarts/cleanup (was fixed back in August). After that, the unittests ran and passed OK. I'll see about trying it on a FreeBSD 5.1 box later. Barry
http://mail-archives.us.apache.org/mod_mbox/quetz-mod_python-dev/200310.mbox/%3C3F8DBFB8.6020203@barryp.org%3E
CC-MAIN-2020-29
refinedweb
607
66.94
This C Program checks if a given integer is odd or even. Here if a given number is divisible by 2 with the remainder 0 then the number is even number. If the number is not divisible by 2 then that number will be odd number. Here is source code of the C program which checks a given integer is odd or even. The C program is successfully compiled and run on a Linux system. The program output is also shown below. /* * C program to check whether a given integer is odd or even */ #include <stdio.h> void main() { int ival, remainder; printf("Enter an integer : "); scanf("%d", &ival); remainder = ival % 2; if (remainder == 0) printf("%d is an even integer\n", ival); else printf("%d is an odd integer\n", ival); } advertisements $ cc pgm4.c $ a.out Enter an integer : 100 100 is an even integer $ a.out Enter an integer : 105 105 is an odd integer.
http://www.sanfoundry.com/c-program-integer-odd-or-even/
CC-MAIN-2016-44
refinedweb
158
64.91
This topic document serves to provide guidance on how to handle the pagination of large result sets and the best ways to provide filtering and sorting capabilities in a project’s public REST API. Pagination can be implemented using one or both of two query parameters: Note that the marker need not always be the ID/UUID field of the record; it can be any field or combination of fields that will uniquely identify that record. Using a marker that is not unique will result in overlap or skipped records between paged results. For example: GET /app/items?limit=30 Would return at most 30 items: { } ] } If, we then wanted to request the next 30 items after the last one, we would do: GET /app/items?limit=30&marker=08ec231f6d9a43dda97d4b950c3393df This would return the next (at most) 30 items after the item with ID 08ec231f6d9a43dda97d4b950c3393df. The ability to page through results implies that the items are sorted in a consistent fashion in each request, even if that order is nothing more than the order the items were added to the dataset. If the order of the results changes between requests, the returned pages will not have a meaningful relation to each other. A similar consideration would be how to handle the situation when the item whose ID is the marker value is deleted in between requests. In that event, the response should start with the next item logically. The definition of “logical” is necessarily fuzzy, and will depend on how the data is sorted. There may be some cases, however, where it is not reasonable to try to determine what the next logical item would be. In those cases, a 400 Bad Request response should be returned, with a clear explanation in the error message that the requested marker value does not exist. It is also helpful to users if services generate pagination links and include them in the Links portion of the response body. Providing the following link types will make pagination navigation easier: It is important to note that unless the data being paged is static, these links cannot be guaranteed to be accurate. For example, if some items are deleted, the prev link might contain some items from the current result. For example, a response to: GET /app/items?limit=30&marker=752b0b9997f24be49e5a1d89d1c53279 Would look more akin to: { } ], "links": [ { "rel": "self", "href": "", }, { "rel": "first", "href": "", }, { "rel": "prev", "href": "", }, { "rel": "next", "href": "", }, { "rel": "last", "href": "", } ] } When using links, the links that are included change based on which page the user requested. For example, if the user has requested the first page, then it still makes sense to include first, self, next, and last but not prev. Likewise if it is the last page, then including next is optional but the rest (first, prev, self, last) is sensible. It should also be emphasized that calculating the last link can be costly. In many cases, such link calculation would require querying the entire dataset. Therefore implementing the last link is optional. If services are not including JSON Hyper-Schema links in their responses, or if they cannot include them for some reasons, they should return pagination links in the Link header as defined in RFC 5988 and RFC 6903. Note Adding the Link to responses should not be considered an API contract change that needs a either a minor version bump or a microversion. Because of the nature of HTTP headers and the relationship of REST services with proxies, load balancers and API gateways, HTTP clients must already handle the existence of additional headers that may not be relevant. Consuming pagination is a fundamental operation that is frequently not done on a per-service basis. Requiring a user to undergo a microversion negotiation or minor version is extra per-service work that is both difficult and which carries no value. Users can simply check to see if a Link header exists, and if one does, they can consume the data in it. Filtering can be implemented as a query parameter named for the field to be filtered on, the value should (naturally) be the value you need to filter for. An existing example of filtering in Nova It is notable that Nova doesn’t support OR filters, requiring separate requests per query. A different strategy is to specify query objects and pass them as a single URL-encoded JSON list. This is less client-friendly because it requires extra encoding steps. The simplest way to allow filtering is to map filterable parameters to query parameters. Take the sample object: GET /app/items { "items": [ { "foo": "bar", "baz": "quux", "size": 9 }, { "foo": "buzz", "baz": "honk", "size": 6 } ] } To filter on a field, simply add that field and its value to the query.: GET /app/items?foo=buzz { "items": [ { "foo": "buzz", "baz": "honk", "size": 9 } ] } Multiple filters result in an implicit AND, so in our example /app/items?foo=buzz&baz=quux would provide no results. IN operations are available for single fields, using comma-separated options for the field value and colon separation for the in operator. The value must be in the list of values provided for the query to succeed.: GET /app/items?foo=in:buzz,bar { "items": [ { "foo": "bar", "baz": "quux", "size": 9 }, { "foo": "buzz", "baz": "honk", "size": 6 } ] } If values contain commas, they can be quoted similar to CSV escaping. For example, a query for the value a,bc or d would be ?foo=in:"a,bc",d. If values contain double-quotes, those can be backslashed inside quotes. Newline (“n”) and carriage return (“r”) escapes are also allowed. Actual backslashes must be doubled. For a value a"b\c the query would be ?foo="a\"b\\c". Unquoted values may not contain quotes and backslashes are treated as any other character. So for a value a\b the query would be ?foo=a\b. For queries that need comparisons other than simple equals, operators are supported for membership, non-membership, inequality, greater-than, greater-than-or-equal, less-than, and less-than-or-equal-to. In order, the operators are: in, nin, neq, gt, gte, lt, and lte. Simple equality is the default operation, and is performed as ?param=foo. They can be used in queries compounded with the values they work on. For example, finding objects with a size greater than 8 would be written as ?size=gt:8 and would return: GET /app/items?size=gt:8 { "items": [ { "foo": "bar", "baz": "quux", "size": 9 } ] } Operators must be followed by colons, so the query ?foo=gte searches for the literal string “gte” and searching for “gte:” can be done by quoting the value as ?foo="gte:". TODO: Add guidance on a “LIKE” or regex operator to search text. Paginating responses should be done after applying the filters in a query, because it’s possible for there to be no matches in the first page of results, and returning an empty page is a poor API when the user explicitly requested a number of results. To support filtering based on time intervals such as mentioned in the ISO8601 intervals wikipedia page, it should be possible to express the following use cases through API queries: For instance, the Ironic Inspector project keeps track of node introspection statuses that include the started_at and finished_at fields. While the former value is always present, the latter is present only if the introspection finished: GET /app/item { "items": [ {"id": "item1", "started_at": "2016-10-10T15:00Z", "finished_at": "2016-10-10T15:30Z"}, {"id": "item2", "started_at": "2016-10-10T15:15Z", "finished_at": "2016-10-10T16:00Z"}, {"id": "item3", "started_at": "2016-10-10T15:45Z", "finished_at": null} ] } To obtain items that finished between 15:30 and 16:00 UTC Today use an interval with two boundaries: GET /app/items?finished_at=ge:15:30&finished_at=lt:16:00 { "items": [ {"id": "item1", "started_at": "2016-10-10T15:00Z", "finished_at": "2016-10-10T15:30Z"} ] } To list items that finished any time after 15:30 UTC Today, use an open-ended time interval query: GET /app/items?finished_at=ge:15:30 { "items": [ {"id": "item1", "started_at": "2016-10-10T15:00Z", "finished_at": "2016-10-10T15:30Z"}, {"id": "item2", "started_at": "2016-10-10T15:15Z", "finished_at": "2016-10-10T16:00Z"} ] } Finally, to include items that didn’t finish yet, use the default value equality. Since the queries are implicitly AND-ed, use two requests: GET /app/items?finished_at=ge:16:00 { "items": [ {"id": "item2", "started_at": "2016-10-10T15:15Z", "finished_at": "2016-10-10T16:00Z"} ] } GET /app/items?finished_at=null { "items": [ {"id": "item3", "started_at": "2016-10-10T15:45Z", "finished_at": null} ] } Sorting is determined through the use of the ‘sort’ query string parameter. The value of this parameter is a comma-separated list of sort keys. Sort directions can optionally be appended to each sort key, separated by the ‘:’ character. The supported sort directions are either ‘asc’ for ascending or ‘desc’ for descending. The caller may (but is not required to) specify a sort direction for each key. If a sort direction is not specified for a key, then a default is set by the server. For example: Note that many projects have implemented sorting using repeating ‘sort_key’ and ‘sort_dir’ query string parameters, see [1]. As these projects adopt these guidelines, they should deprecate the older parameters appropriately. [1]:
https://specs.openstack.org/openstack/api-wg/guidelines/pagination_filter_sort.html
CC-MAIN-2020-05
refinedweb
1,540
59.94
Colours can be a powerful visual hint in a data visualisation. A good rule of thumb though is to use them sparingly, only when they add something meaningful to the chart and not just because they are pretty. A good alternative to using many different colours is to use just a range of different shades of one or two colours across our entire dataset. This will highlight visually the differences in “weight” of each datapoint without distracting the user with an infinite rainbow of colours. D3.js makes achieving this goal incredibly easy, allowing us to pass a colour codes to our ranges. We just need to pass the two colour codes we want to use as extremes and we will be good to go. import { scaleLinear } from 'd3-scale'; const ourScale = scaleLinear() .domain([0, 100]) .range([ '#63a6d6', // <= lower bound of our color scale '#124488' // <= upper bound of our color scale ]); D3.js will in turn interpolate the value we pass to our scale function to give us back the appropriate color code. Easy! Here below a working JsFiddle to check how it works live. Cover image is from Markus Spiske, check out his work here. Originally published on my blog. Discussion (0)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/aurelio/interpolating-colours-within-a-range-in-d3-js-5f61
CC-MAIN-2022-05
refinedweb
203
71.55
#include <iostream.h> #include <stdlib.h> #include <vector> class PhoneBook { private: Record vector <class> Records; //syntax error before < public: void add(Record pN); bool search(PhoneNumber pN); //'Record' not declared in scope; parse error before ) void list();// 'PhoneNumber' not declared in scope; parse error before ) PhoneBook();//maybe size as argument }; class PhoneNumber { private: int areaCode; int number; public: Phonenumber(int aC, int n); int getAreaCode(); int getNumber(); void setAreaCode(int area); void setNumber(int num); }; class Record { private: int id; PhoneNumber phoneNumber; public: Record(int i, PhoneNumber pN); int getId(); PhoneNumber getPhoneNumber(); void setID(int iD); void setPhoneNumber(PhoneNumber pN); }; This is JUST the declaration of classes. I also put definitions below the main function as a holder so that it doesn't give me an error because I don't have a matching definition. Anyways, I put the errors in as comments. The idea of the project is I have some kind of "phonebook" where you can add, delete, print the entries. The phonebook is going to be the vector (the vector stores all of the entries). The phonebook class has your main add/delete/print functions. The record class has the id and phone number, as well as funtions to manipulate them. With the Phonenumber class, same story. The "Record(int i, PhoneNumber pN);" is supposed to be a contructor and there is one for each class. Thats one of the things he wants us to practice with the project, and I'm not completely sure I'm doing it right. Any help you can give me is appreciated.
http://www.dreamincode.net/forums/topic/86619-object-oriented-programming-help/
CC-MAIN-2018-05
refinedweb
261
59.33
Sklearn | Feature Extraction with TF-IDF Now, you are searching for tf-idf, then you may familiar with feature extraction and what it is. TF-IDF which stands for Term Frequency – Inverse Document Frequency. It is one of the most important techniques used for information retrieval to represent how important a specific word or phrase is to a given document. Let’s take an example, we have a string or Bag of Words (BOW) and we have to extract information from it, then we can use this approach. The tf-idf value increases in proportion to the number of times a word appears in the document but is often offset by the frequency of the word in the corpus, which helps to adjust with respect to the fact that some words appear more frequently in general. TF-IDF use two statistical methods, first is Term Frequency and the other is Inverse Document Frequency. Term frequency refers to the total number of times a given term t appears in the document doc against (per) the total number of all words in the document and The inverse document frequency measure of how much information the word provides. It measures the weight of a given word in the entire document. IDF show how common or rare a given word is across all documents. TF-IDF can be computed as tf * idf Attention reader! Don’t stop learning now. Get hold of all the important Machine Learning Concepts with the Machine Learning Foundation Course at a student-friendly price and become industry ready. Tf*Idf do not convert directly raw data into useful features. Firstly, it converts raw strings or dataset into vectors and each word has its own vector. Then we’ll use a particular technique for retrieving the feature like Cosine Similarity which works on vectors, etc. As we know, we can’t directly pass the string to our model. So, tf*idf provides numeric values of the entire document for us. To extract features from a document of words, we import – from sklearn.feature_extraction.text import TfidfVectorizer Input : 1st Sentence - "hello i am pulkit" 2nd Sentence - "your name is akshit" Code : Python code to find the similarity measures Output : manhatten cos_sim euclidean 0 2.955813 0.0 1.414214 Dataset: Google Drive link Note: Dataset is large so it’ll take 30-40 second to produce output and If you are going to run as it is, then it’s not gonna work. It only works when you copy this code in your IDE and provide your dataset in tfidf function.
https://www.geeksforgeeks.org/sklearn-feature-extraction-with-tf-idf/?ref=lbp
CC-MAIN-2021-43
refinedweb
430
60.14
import java.lang.String; public class char_array { main main = new main(); String word; // this will be some word the person would be trying to guess like "brady" String x; // this is the letter the operator guesses , so it would be like "b" public char_array(String a, String B)/>{ a = this.word; b = this.x; } public void some_function() { char charArray[]=word.toCharArray(); for(int h=0;h<charArray.length;h++){ System.out.println("Data at ["+h+"]="+charArray[h]);//this is just to test } } } this is the error I get Exception in thread "main" java.lang.NullPointerException at char_array.some_function(char_array.java:15) at main.main(main.java:47) the error doesn't really tell me much. Can you guys help?
http://www.dreamincode.net/forums/topic/317536-error-exception-in-thread-main-javalangnullpointerexception/
CC-MAIN-2016-36
refinedweb
119
61.43
Hello all, I have been working on a huge commercial project and have come to a stop where I am not too familiarized in the mathematical side and conditional statements part of programming in C#. What do I want? My helicopter can travel at speeds and with this speeds I would like a different affect on collision at each speed. My helicopter has been built using Rigidbody, mainly AddForce and AddTorque. I wouldn't even know how to get the speed value of the Rigidbody. I would like the helicopter to be able to collide with the terrain at different speeds. I have gone ahead and made some pseudocode to display to show you all what I am trying to achieve. I imagine I have been stuck for over 7 hours now and I guess all the research I have been doing has not lead me to the correct solution. using UnityEngine; using System.Collections; public class CollisionTerrain : MonoBehaviour { public GameObject terrain; public ParticleSystem PlayP1; public ParticleSystem PlayP2; public ParticleSystem PlayP3; public GameObject WH; void OnCollisionEnter(Collision collision) { if(helicopter.velocity.magnitude > 10); //If Helicopter is faster than a velocity of 10 PlayP1.particleSystem.enableEmission = true; //Helicopter will emit a black smoke and make a damage sound PlayP1.AudioSource.Play(); // Ignore if wrong if(helicopter.velocity.magnitude > 25); //If Helicopter is faster than a velocity of 25 PlayP2.particleSystem.enableEmission = true; { Helicopter will emit a deeper black smoke and make a more intense damage sound} PlayP2.AudioSource.Play(); // Ignore if wrong if(helicopter.velocity.magnitude > 50); //If Helicopter is faster than a velocity of 25 PlayP3.particleSystem.enableEmission = true; { Helicopter will emit a deeper black smoke and make a more intense damage sound} PlayP3.AudioSource.Play(); // Ignore if wrong WH.Instantiate.WreckageObject. //Blown up Helicopter } } Answer by Addyarb · Apr 25, 2015 at 07:48 PM First, lets get the speed of your object. Put this at the top of your script: public float velocity; //The velocity of our object. Vector3 previous; //The previous position of our object. now, lets use the Update function to get the speed of our object. Like so: void Update () { velocity = ((transform.position - previous).magnitude) / Time.deltaTime; previous = transform.position; } next, lets check that velocity if we hit something. void OnTriggerEnter(Collider col){ if (col.tag == "Terrain") { if(velocity > 0 && velocity < 10){ //SlowCrash(); } else{ if(velocity >= 10 && velocity <= 50){ //MediumCrash(): } else{ if(velocity > 50){ //FastCrash(); } } } } } Thank you so much Addyarb! I wasn't looking for OnTriggerEnter though, so I changed it to OnCollisionEnter, just in case anyone else sees this post and wanted it collision with terrain rather than the trigger area. :) Of course! Glad you found a solution. Good luck with your game. :) Answer by siaran · Apr 25, 2015 at 07:50 PM your code is really not that far off. you can call rigidbody.velocity to get a rigidbody's velocity (as a vector3) and you can get the magnitude for a scalar value. the problem in your code snip is mostly that if your speed is > 50, all lines will be called (if something is larger than 50, it is also larger than 10, 25, and 30). a simple way of solving this would be something like void OnCollisionEnter(Collision c){ float speed = helicopter.rigidboy.velocity.magnitude; if(speed > 50) DoHighestEffect(); else if (speed > 25) DoMediumEffect(); else if (speed > 10) DoLowEffect(); else DoMinimumEffect(); } You may want to have a single CollisionEffect(float speed) method instead that takes the speed as a parameter, depending on how you implement having different rigidbody.Addforce doesn't move my bullet. 1 Answer RigidBodies and "Slipping" Prevention 0 Answers RigidBody Script Conflict 1 Answer How to get my child objects to follow the parent? Also, not sure if this is working. 0 Answers
https://answers.unity.com/questions/954550/how-would-i-get-collision-at-different-speeds.html
CC-MAIN-2020-05
refinedweb
625
56.86
- RegCloseKey - RegEnumKeyExA - RegEnumValueA - RegOpenKeyExA - RegQueryInfoKeyA The Windows Registry is where programs, the OS, drivers, and other items store settings and data for later use. Personally for my programs I use the good old fashioned ini files. The Registry is a dangerous place! One small mistake and you could render the OS non bootable. We won't have that issue here as we are only going to read from the Registy. When I first started the Tutorial, it was very complex so I started over and made it very simple. Wasn't good for what I wanted to show, so I settled on somewhat complex. We will use a TreeView and ListView control to display all keys, subkeys, and values under HKEY_CURRENT_USER\Software. You can modify it for any purpose/keys. *** Note *** I do not enumerate all keys and subkeys when loading. When the program starts, we only enumerate the subkeys under HKCU\Software and set a flag if the key has subkeys, we then fill these children in when the TVITEM is expanded. The "splitter" code is nothing fancy, modfiy it at your will. There is a mix of invokes and push/calls, I started with push/calls and go tired of typing so switch to invokes for intellisense. This will be a bit long, so get comfy! We will be using the following structures: TVITEM TV_INSERTSTRUCT TVHITTESTINFO LVITEM and LVCOLUMN The "Magic" happens in our WM_NOTIFY handler of our WindowProc. We will handle 4 messages from the Treeview: TVN_SELCHANGED This is where we will handle displaying the values of selected node from the Registry. TVN_ITEMEXPANDING This is where we will fill all children of node if it has not already been filled. TVN_GETDISPINFO This is where we will change the icon to either an open folder or closed folder depending on action. NM_CLICK This is where we check to see if the item expand button was clicked and select Treeview item. TVN_SELCHANGED First thing we have to do when we get this notification is get the handle of selected item and its parent. ebx will contain our treeview handle If the handle does not equal hRoot, a child was selected; if so, then a parent node was selected and we get the text of the item: No furthure processing is required since the Registry path will be HKEY_CURRENT_USER\Software\TextOfParent so we will go onto displaying the values. If a child was selected, we have to build the registry path from the child all the way back to the parent. For example, if we have a node like so: SomeParent Child1 Child2 Parent2 Child3 and Child3 was selected, we have to scan backwards till we reach the root of the treevew. So after our call to BuildRegPath, the path will be HKCU\Software\SomeParent\Parent2\Child3 then we call ShowInfo. TVN_ITEMEXPANDING As I mentioned earlier, we don't enumerate all subkeys under HKCU\Software only the toplevel keys. When we add a toplevel key to the treeview its lParam will be 0. When we get TVN_ITEMEXPANDING, we check the lParam of selected item, if it is 0 then we enumerate the registry children and set lParam of the item to 1. Same as TVN_SELCHANGED, if it is a child we have to build a reg path before we enumerate: invoke SendMessage, hLVValues, LVM_DELETEALLITEMS, 0, 0 ; parent selected ProcessChild: ; child selected mov tvi._mask, TVIF_TEXT mov tvi.pszText, offset lpszBuffer mov tvi.cchTextMax, MAX_PATH pop tvi.hItem invoke SendMessage, ebx, TVM_GETITEM, 0, addr tvi invoke BuildRegPath, tvi.hItem, offset lpszBuffer ShowValues: invoke RegOpenKeyEx, HKEY_CURRENT_USER, offset szSoftware, NULL, KEY_QUERY_VALUE or KEY_ENUMERATE_SUB_KEYS, addr hKey invoke RegOpenKeyEx, hKey, offset lpszBuffer, NULL, KEY_QUERY_VALUE or KEY_ENUMERATE_SUB_KEYS, addr hSubKey test eax, eax jnz Done invoke ShowInfo, hSubKey invoke RegCloseKey, hSubKey invoke RegCloseKey, hKey jmp Done TVN_GETDISPINFO First we get the state of current item: mov eax, (NMTVDISPINFO ptr [edi]).item.hItem mov tvi.hItem, eax mov tvi._mask, TVIF_STATE invoke SendMessage, ebx, TVM_GETITEM, 0, addr tvi Then we check to see if the TVIS_EXPANDED bit is set mov eax, tvi.state test eax, TVIS_EXPANDED jnz @F If the ZERO flag is not zero, then the item is expanded and we fill in 2 members of the NMTVDISPINFO structure - item.iSelectedImage/iImage with the index of our open folder icon. Otherwise the closed folder icon mov (NMTVDISPINFO ptr [edi]).item.iSelectedImage, ICON_FOLDER_IDX mov (NMTVDISPINFO ptr [edi]).item.iImage, ICON_FOLDER_IDX jmp Done @@: mov (NMTVDISPINFO ptr [edi]).item.iSelectedImage, ICON_FOLDER_OPEN_IDX mov (NMTVDISPINFO ptr [edi]).item.iImage, ICON_FOLDER_OPEN_IDX jmp Done NM_CLICK ; see if the item button was clicked invoke GetCursorPos, addr pt1 invoke ScreenToClient, ebx, addr pt1 m2m tvhti.pt.x, pt1.x m2m tvhti.pt.y, pt1. y invoke SendMessage, ebx, TVM_HITTEST, 0, addr tvhti mov eax, tvhti.flags cmp eax, TVHT_ONITEMBUTTON jne Done ; it was, now select item invoke SendMessage, ebx, TVM_SELECTITEM,TVGN_CARET, tvhti.hItem jmp Done All we do here, is get the position of the cursor, and check if the expand button was clicked. If it was we select the item so we can "fire" the TVN_SELCHANGED code. If we didn't handle this message, then things will get screwed up when we use TVM_GETNEXTITEM/TVGN_CARET. To see what happens, just comment out these lines: cmp dword ptr(NMHDR ptr[edi]).code, NM_CLICK je _NM_CLICK The functions EnumChildren and ShowInfo both require a handle to a reg key to work on. This will be the currently selected Treeview item and as mentioned, if it is not a parent key, then we use BuildRegPath to get the reg path. Then we must open 2 keys: HKCU\Software and with that handle, we call RegOpenKeyEx and the path returned from BuildRegPath. Now for the code that does the work: ShowInfo will enumerate the values in open reg key. Spoiler I will use the register EDI for 0, since it is a smaller opcode to push a register vs. a number. At the beginning of the procedure, I turn of painting/drawing of the listview to speed up inserting items. We do this with a SendMessage and a wParam value of FALSE push edi push edi push WM_SETREDRAW push hLVValues call SendMessage Now for this piece of code, I need to know 2 things about the registry key: - Total values in key - Size of the longest data component among the key's values Since we don't need any other info, we can pass NULL to most of the Parameters of RegQueryInfoKey push edi ; lpftLastWriteTime - N/A push edi ; lpcbSecurityDescriptor - N/A lea eax, lpcMaxValueLen ; push eax ; longest data length push edi ; lpcMaxValueNameLen - N/A lea ecx, lpcValues ; push ecx ; total values in key push edi ; lpcMaxClassLen - N/A push edi ; lpcMaxSubKeyLen - N/A push edi ; lpcSubKeys - N/A push edi ; lpReserved - NULL push edi ; lpcClass - N/A push edi ; lpClass - N/A push hRegKey ; handle of open reg key to query info from call RegQueryInfoKey ; Once the call returns, we check the value of lpcValues and if it is zero, we add a "default" value to the listview. We need a buffer to hold the enumerated data: push lpcMaxValueLen ; create a buffer to hold value data push HEAP_ZERO_MEMORY ; size == length of longest value push hHeap ; call HeapAlloc ; xchg eax, esi ; move pointer to esi Now we can use RegEnumValueEx to enumerate all values in the key. We call it in a loop until it returns ERROR_NO_MORE_ITEMS. When you first call RegEnumValueEx, you need to pass 0 in the dwIndex param and increment it each loop iteration. GetNextValue: mov [esi], edi ; zero buffer mov lpcValueName, MAX_VALNAME + 1 push lpcMaxValueLen pop lpcbData lea eax, lpcbData ; how big our buffer is push eax ; push esi ; pointer to our buffer to hold current enum'd values data lea ecx, lpType ; var to hold values data type push ecx ; push NULL ; lpReserved - NULL lea edx, lpcValueName ; how big our valuename buffer is push edx ; lea eax, lpValueName ; buffer to hold value name push eax ; push ebx ; dwIndex push hRegKey ; handle of open reg key to enumerate values call RegEnumValue ; cmp eax, ERROR_NO_MORE_ITEMS ; any more values? je NoMoreValues ; nope, exit loop cmp lpcValueName, edi ; does key have values? jnz AddValue ; yes, add it When we are done adding values to the listview, we turn back on painting/drawing, we do this with a SendMessage and a wParam value of TRUE: ; turn back on listview drawing push 0 push TRUE push WM_SETREDRAW push hLVValues call SendMessage AddLVItem adds a registry value to listview - Name, Type, and Data Spoiler First thing we do is fill in some members of the LVITEM structure with passed data. When we insert an item into column 0 we use LVM_INSERTITEM and we will use the flags LVIF_TEXT and LVIF_IMAGE to tell the listview we want to set the icon and text of the item. mov lvi.imask, LVIF_TEXT or LVIF_IMAGE push dwItem pop lvi.iItem mov lvi.iSubItem, 0 push pszName pop lvi.pszText Next we see what data type was passed and fill in lvi.iImage accordingly: mov eax, dwType cmp eax, REG_SZ je StringData cmp eax, REG_MULTI_SZ je StringData cmp eax, REG_EXPAND_SZ jne OtherData StringData: mov lvi.iImage, ICON_STRING_IDX jmp AddIt OtherData: mov lvi.iImage, ICON_DATA_IDX Once that is all done, we insert the item into the listview: AddIt: lea eax, lvi ; push eax ; push 0 ; push LVM_INSERTITEM ; push hLVValues ; call SendMessage ; add icon and value name Now to "add" subitems to the listview item we just inserted, we use LVM_SETITEM. We set lvi.iSubitem to the index of the subitem to set. When we first insert an item, lvi.iSubitem is zero so we just increase the value for each subitem: inc lvi.iSubItem For the data type column, we check to see the data type that was grabbed from the registry and use that number as an index into a table of string pointers for the data type: lea esi, RegTypesTable .if dwType > RegTypesSize mov lvi.pszText, offset szUnknown .else mov ecx, dwType mov eax, [esi + 4 * ecx] mov lvi.pszText, eax .endif invoke SendMessage, hLVValues, LVM_SETITEM, 0, addr lvi Now there is one more column to set - data inc lvi.iSubItem If it is one of the string types, we just use the data passed: .if dwType == REG_SZ || dwType == REG_MULTI_SZ || dwType == REG_EXPAND_SZ push lpData pop lvi.pszText invoke SendMessage, hLVValues, LVM_SETITEM, 0, addr lvi If it is one of the DWORD types we create a temp buffer to hold our formated number then convert to hex, convert the dword to string and multicat it all together to get a nicely formated string like this: .elseif dwType == REG_DWORD || dwType == REG_DWORD_BIG_ENDIAN invoke HeapAlloc, hHeap, HEAP_ZERO_MEMORY, 32 mov TempBuf, eax mov ebx, lpData mov ebx, [ebx] invoke dw2hex, ebx, addr HexNum invoke dwtoa, ebx, addr Num invoke szMultiCat, 5, TempBuf, offset szHex, addr HexNum, offset szParenLeft, addr Num, offset szParenRight push TempBuf pop lvi.pszText invoke SendMessage, hLVValues, LVM_SETITEM, 0, addr lvi invoke HeapFree, hHeap, 0, TempBuf If the data type is anything other than the above types, we will treat it as binary and convert it to hex. ConvertToHex is code modified from the MASM32 library - bin2hex to format the string as I need it to be. First we need a buffer to hold our hex string. We take the value in dwDataLen and shift left by 2 to multiply the value by 4 so our buffer is large enough, then we call ConvertToHex to give us a string like this: .else mov eax, dwDataLen shl eax, 2 invoke HeapAlloc, hHeap, HEAP_ZERO_MEMORY, eax mov TempBuf, eax invoke ConvertToHex, lpData, dwDataLen, TempBuf push TempBuf pop lvi.pszText invoke SendMessage, hLVValues, LVM_SETITEM, 0, addr lvi invoke HeapFree, hHeap, 0, TempBuf EnumChildren is called anytime we expand a parent node and it need to be filled Spoiler EnumChildren takes 2 parameters: handle to an open registry key to enumerate and handle to its treeview parent. We use RegEnumKeyEx in a loop until it returns ERROR_NO_MORE_ITEMS. As with RegEnumValue we pass 0 for dwIndex the first time we call it. We are only interested in the currently enumerated key name. lea esi, lpName xor ebx, ebx xor edi, edi GetNextKey: mov [esi], edi mov lpcName, sizeof lpName invoke RegEnumKeyEx, hKey, ebx, esi, addr lpcName, edi, edi, edi, edi cmp eax, ERROR_NO_MORE_ITEMS je Done invoke RegOpenKeyEx, hKey, esi, edi, KEY_QUERY_VALUE, addr hSubKey invoke RegQueryInfoKey, hSubKey, edi, edi, edi, addr lpcSubkeys, edi, edi, edi, edi, edi, edi, edi invoke RegCloseKey, hSubKey invoke AddKeyToTV, hParentNode, esi .if lpcSubkeys > edi ; notify TV item has children so we ; get the expand button mov tvi._mask, TVIF_CHILDREN or TVIF_PARAM mov tvi.lParam, 0 mov tvi.hItem, eax mov tvi.cChildren, 1 invoke SendMessage, hTVKeys, TVM_SETITEM, edi, addr tvi .endif inc ebx jmp GetNextKey Done: ret Once we get a key name from RegEnumKeyEx, we open it with RegOpenKeyEx and get the number of subkeys with RegQueryInfoEx. We add the reg key to the Treeview with AddkeyToTV which returns a handle of the inserted item. Now we check to see if there were subkeys, and if so, we set the tvi.cChildren member to 1 so we get the button to expand the item. Many Registry API functions have a samDesired parameter. This is the desired access right to the key. The calls WILL fail if you request a right that your user account does not have. I see folks using KEY_ALL_ACCESS, WHY?!?!? Some also use KEY_READ for anything having to do with enumerating, reading, querying, etc.. the same with KEY_WRITE. Well I was taught long ago when Windows was a bit more tempermental, to use only the access rights that you need. If I just need to query a value, I will use KEY_QUERY_VALUE. Enumerate keys, then it is KEY_ENUMERATE_SUB_KEYS, if I need to do more, I will OR them together. By using ONLY what you require, you reduce the chances of bugs popping up. PHEW!!! That was a bit long, but worth it I hope! This is what all of that put together looks like: Full source and sample exe Number of downloads: 511
http://www.dreamincode.net/forums/topic/282316-masm-enumerating-the-windows-registry/
CC-MAIN-2016-22
refinedweb
2,338
60.04
tag:blogger.com,1999:blog-61292391086270212542014-10-06T20:21:51.263-04:00Perl and Mac Development BlogDiscussing various topics around Perl and Mac DevelopmentChristopher Humphries and DBIx::Class: Part 1<i>[<a href="">For instructions on the installation of Catalyst, please see the Catalyst Manual page on installation</a>.]</i><br /><br />This is an attempt at introducing DBIx::Class and using it in Catalyst, so you can be familiar with it enough to start using it.<br /><br /><h3>Understanding <abbr title="Object-relational mapping">ORM</abbr></h3><br /><br />First, you'll need to understand the purpose of <a href="">Object-relational mapping</a>. It is what <a href="">DBIx::Class</a> is. To quote <a href="">the wikipedia.org page</A>: <br /><blockquote>Object-Relational mapping (aka O/RM, ORM, and O/R mapping) is a programming technique for converting data between incompatible type systems in databases and Object-oriented programming languages. This creates, in effect, a "virtual object database" which can be used from within the programming language.</blockquote><br /><br /.<br /><br />The basic idea is that you have one controller master class, and then one or more different classes that usually represent each table in the database. The controller master class is where you will specify the database connection information (and other optional settings) and load the table classes. <br /><br /).<br /><br /><h3>Getting to know DBIx::Class</h3><br /><br />Please take a moment to go over <a href="">the examples in the DBIx::Class CPAN page</a>.<br /><br />Then go over the manuals (they're pretty brief and include code to explain everything): <a href="">Intro</a>, <a href="">Example</a>, <a href="">Joining</a>, <a href="">Cookbook</a> with interest on <a href="">prefetch and joins</a>, and <a href="">Troubleshooting</a>.<br /><br />These documents do a much better job at explaining how to use DBIx::Class and all it's specifics than I could do. <a href="">Be sure to check out the documentation map also.</a><br /><br /><h3>Using DBIx::Class in Catalyst</h3><br /><br />Please table a moment to go over <a href="">the Catalyst manual tutorial, the database access with DBIx::Class section</a>. This will get you familiar with the basics.<br /><br />If you already have an existing database schema and it's in a database, you can have <a href="">Catalyst create them for you</a>. It's advised that you just do this once, so that you can save some typing initially (if you already have a database with schema in it... like in this example). First make sure you're in your Catalyst root directory, made with this:<br /><pre>$ catalyst.pl MyTestApp</pre><br />Then you can use the Catalyst create script to create your DBIx::Class classes for you:<br /><pre><br />$ cd MyTestApp<br />$ ./script/mytestapp_create.pl model DB DBIC::Schema DB::Schema create=static dbi:Pg:dbname=ticketingsystem chris<br /> exists "/home/chris/MyTestApp/script/../lib/MyTestApp/Model"<br /> exists "/home/chris/MyTestApp/script/../t"<br />Dumping manual schema for DB::Schema to directory /home/chris/MyTestApp/script/../lib ...<br />Schema dump completed.<br />created "/home/chris/MyTestApp/script/../lib/MyTestApp/Model/DB.pm"<br />created "/home/chris/MyTestApp/script/../t/model_DB.t"<br />$ <br /></pre><br /><br />Ok, now let's take a look at what it created:<br /><pre><br />$ head -13 lib/MyTestApp/Model/DB.pm<br />package MyTestApp::Model::DB;<br /><br />use strict;<br />use base 'Catalyst::Model::DBIC::Schema';<br /><br />__PACKAGE__->config(<br /> schema_class => 'DB::Schema',<br /> connect_info => [<br /> 'dbi:Pg:dbname=ticketingsystem',<br /> 'chris',<br /> <br /> ],<br />);<br />$ <br /></pre><br /><br />Ok, so from looking at the Model class for this database, it seems pretty easy to figure out. It creates a class that is based off <a href="">Catalyst::Model::DBIC::Schema</a> and sets up some configuration values (what the master DBIx::Class is and the database connection information used by DBI). Ok, now lets look at the DB::Schema file:<br /><pre><br />$ cat lib/DB/Schema.pm <br />package DB::Schema;<br /><br /># Created by DBIx::Class::Schema::Loader v0.03009 @ 2007-09-04 19:26:55<br /><br />use strict;<br />use warnings;<br /><br />use base 'DBIx::Class::Schema';<br /><br />__PACKAGE__->load_classes;<br /><br />1;<br /><br />$ <br /></pre><br /><br />Hrm, even simplier right? '__PACKAGE__->load_classes' subroutine loads up all the configured schema classes in the lib/DB/Schema/ directory. Let's look at one:<br /><pre><br />$ cat lib/DB/Schema/Status.pm <br />package DB::Schema::Status;<br /><br /># Created by DBIx::Class::Schema::Loader v0.03009 @ 2007-09-04 19:26:55<br /><br />use strict;<br />use warnings;<br /><br />use base 'DBIx::Class';<br /><br />__PACKAGE__->load_components("PK::Auto", "Core");<br />__PACKAGE__->table("status");<br />__PACKAGE__->add_columns(<br /> "id",<br /> {<br /> data_type => "integer",<br /> default_value => "nextval('status_id_seq'::regclass)",<br /> is_nullable => 0,<br /> size => 4,<br /> },<br /> "name",<br /> {<br /> data_type => "character varying",<br /> default_value => undef,<br /> is_nullable => 0,<br /> size => 40,<br /> },<br />);<br />__PACKAGE__->set_primary_key("id");<br />__PACKAGE__->has_many(<br /> "users_ticket_status_logs",<br /> "DB::Schema::UsersTicketStatusLog",<br /> { "foreign.status_id" => "self.id" },<br />);<br />__PACKAGE__->has_many(<br /> "staff_ticket_status_logs",<br /> "DB::Schema::StaffTicketStatusLog",<br /> { "foreign.status_id" => "self.id" },<br />);<br />__PACKAGE__->has_many(<br /> "tickets",<br /> "DB::Schema::Ticket",<br /> { "foreign.status_id" => "self.id" },<br />);<br /><br />1;<br /></pre><br /><br /:<br /><ul><br /><li><u>load_components</u>: Loads the components you need, which should almost always be the same (PK::Auto and Core) unless you need custom components detailed in <a href="">the DBIx::Class component manual</a>. <i>[technically I guess you don't need PK::Auto as it's in Core now]</i></li><br /><li><u>table</u>: obviously sets the name of the table</li><br /><li><u>add_columns</u>: defines the columns of the table</li><br /><li><u>set_primary_key</u>: sets the primary key of the table</li><br /><li><u>has_many</u>: one of a few relationship definition functions for the table, <a href="">see more about them in detail here</a>.</li><br /></ul><br />It's pretty simple once you read the documentation links I gave. The naming of everything is pretty intuitive, so makes wrapping your brain around what's going on pretty easy.<br /><br /><h3>Summary</h3><br /><br />So you should now have an idea of what DBIx::Class' purpose is and some details about it's use. You should also know where to look for documentation on each part discussed here and have a good general knowledge of DBIx::Class' implementation of <abbr title="Object-relational Mapping">ORM</abbr>. <br /><br />You should have a simple understanding of DBIx::Class and Catalyst. I'll continue in another article on more details and dive more into using DBIx::Class in <a href="">Catalyst Controllers</a> and using multiple databases.<br /><br />Hopefully this was useful to you. I'd like to keep going, yet it's more appropriate to break this up into parts. If I made any mistakes or feel I should have written something in a better way, let me know and I'll be sure to update! <br /><br />Enjoy playing with Catalyst and DBIx::Class!<img src="" height="1" width="1" alt=""/>Christopher Humphries Perl's WWW::MyspaceFor getting information on your <a href="">Myspace</a> page and other people's, posting comments and updates to your profile, or anything inbox related (and some other stuff)... <a href="">WWW::Myspace</a> is a good module to use.<br /><br />In this article, I'll show some examples of how to use some of the functionality of this module. Pretty handy... especially if you just want the information without dealing with the horrible interface that Myspace has (and people's themes and playing songs by default and other annoyances).<br /><br /><h3>Get your friends</h3><br /><br />Get a list of all your friends, maybe handy, maybe not... this is just an example so it doesn't have to be useful! :)<br /><br />Here is how one would get all their friends and what times they last logged in: /># Present list all nice-like<br />foreach my $friend (@friends) {<br /> eval {<br /> print "friend id.: $friend\n";<br /> <br /> my $friend_name = $myspace->friend_user_name($friend);<br /> print "name......: $friend_name\n";<br /> <br /> my $last_login = $myspace->last_login_ymd($friend);<br /> print "last login: $last_login\n\n";<br /> };<br /> if ($@) {<br /> # Usually an error when can't view profile due to "maintenance", yet WWW::Myspace breaks<br /> print "Unable to complete request: $@\n\n";<br /> }<br />}<br /></pre><br /><br /><h3>Get your inbox</h3> <br /><br />This is pretty simple, get all messages from your inbox: /><br />print "Getting inbox...\n";<br />my $inbox = $myspace->inbox;<br /><br />foreach my $message (@{$inbox}) {<br /> print "Sender: " . $message->{sender} . "\n";<br /> print "Status: " . $message->{status} . "\n";<br /> print "messageID: " . $message->{message_id} . "\n";<br /> print "Subject: " . $message->{subject} . "\n\n";<br /><br /> # Note, to read each message do<br /> #my $message_hashref = $myspace->read_message($message->{message_id}); <br /> #print "From: $message_hashref->{'from'}\n"; # Friend ID of sender<br /> #print "Date: $message_hashref->{'date'}\n"; # Date (as formatted on Myspace)<br /> #print "Subject: $message_hashref->{'subject'}\n";<br /> #print "Body: $message_hashref->{'body'}\n\n"; # Message body<br />}<br /></pre><br /><br />Note that it will print out all messages you have. The message details part of the example is commented out due to being very spammy (you can uncomment it out if you wish).<br /><br /><h3>Get the last 5 comments of all your friends</h3><br /><br />This just gets your friends list like before, then goes over each to get their comments on their Myspace page. It reports back the friend name, id and time they posted the comment.<br /> />my %friend_mapping; # key = id, value = name<br /><br /># Present list all nice-like<br />foreach my $friend (@friends) {<br /> eval {<br /> print "friend id.: $friend\n";<br /> <br /> my $friend_name = $myspace->friend_user_name($friend);<br /> print "name......: $friend_name\n";<br /> $friend_mapping{$friend} = $friend_name;<br /><br /> print "Getting last 5 comments.\n";<br /> <br /> my $comments = $myspace->get_comments($friend);<br /> my $max_comments_display = 5;<br /> do {<br /> my $comment = shift @{$comments};<br /> my $CPAN page</a> yourself for more functionality, as I've only covered a small part.<br /><br />A handy little module!<img src="" height="1" width="1" alt=""/>Christopher Humphries Perl's Test::Simple and Test::More<strong>Testing is simple.</strong> You are basically seeing if something is either true or false, usually comparing two values. That's pretty much it. It's that way on purpose.<br /><br />There are two main modules for doing this: <a href="">Test::More</a> and <a href="">Test::Simple</a>.<br /><br />I'd like to show you how to use them to write your own tests.<br /><br /><h3>Test::Simple</h3><br /><br />Test::Simple is perfect in naming as it is simple and runs tests. Well, actually it <strong>only runs one test</strong> multiple times, if you choose to run it multiple times. It only has one subroutine, 'ok()', which will either evaluate an expression to true or false (pass or fail). Here is an example of using Test::Simple.<br /><br />Here is the simple class we'll be testing (that just tests multiples [of 5 and 30]):<br /><pre><br />#!/usr/bin/perl<br />#<br />use strict;<br />use warnings;<br /><br /><br />package MultipleAsker;<br /><br />sub new {<br /> my ($class) = shift;<br /> my $attrs = {};<br /> bless ($attrs, $class);<br /> return ($attrs);<br />}<br /><br /># See if $what is a multiple of $number, return 1/0<br />sub _ofNumber {<br /> my ($self, $number, $what) = @_;<br /> my $ret = 0;<br /> $ret = 1 if (($what % $number) == 0);<br /> return ($ret);<br />}<br /><br />sub ofFive {<br /> my ($self, $what) = @_;<br /> return ($self->_ofNumber(5, $what));<br />}<br /><br />sub ofThirty {<br /> my ($self, $what) = @_;<br /> return ($self->_ofNumber(30, $what));<br />}<br /><br />1;<br /></pre><br /><br />See, the class is pretty simple. It just has two subroutines available: ofFive and ofThirty (_ofNumber is implied <i>private</i>).<br /><br />Now we just need to test those two functions (and if new worked):<br /><pre><br />#!/usr/bin/perl<br />#<br />use strict;<br />use warnings;<br /><br />use Test::Simple tests => 7;<br /><br />use MultipleAsker;<br /><br />my $ma = MultipleAsker->new();<br /><br /># Test of new()<br />ok (defined($ma) && ref $ma eq 'MultipleAsker', 'new worked');<br /><br /># Test ofFive()<br />ok ($ma->ofFive(24) == 0, '24 is not multiple of 5');<br />ok ($ma->ofFive(25) == 1, '25 is multiple of 5');<br />ok ($ma->ofFive(5) == 1, '5 is multiple of 5');<br /><br /># Test ofThirty()<br />ok ($ma->ofThirty(34) == 0, '34 is not multiple of 30');<br />ok ($ma->ofThirty(120) == 1, '120 is multiple of 30');<br />ok ($ma->ofThirty(30) == 1, '30 is multiple of 30');<br /></pre><br /><br />As you can see, only making use of the one function: <em>ok</em>. Notice 'test => 7'. This is how you tell Test::Simple how many tests you're going to run. You should know this when writing your code. Note that the second arguement (the test description) is purely optional.<br /><br />Here is the output of the tests:<br /><pre><br />1..7<br />ok 1 - new worked<br />ok 2 - 24 is not multiple of 5<br />ok 3 - 25 is multiple of 5<br />ok 4 - 5 is multiple of 5<br />ok 5 - 34 is not multiple of 30<br />ok 6 - 120 is multiple of 30<br />ok 7 - 30 is multiple of 30<br /></pre><br /><br />Pretty simple eh?! Yeah it is. <blockquote>So, that seems pretty good, what more does Test::More offer me... other than <em>'more'</em>?!</blockquote><br />It offers you some more methods for testing, that are basically ok() under-the-hood, yet make your tests... erm more <em>'simple'</em>. Yeah, it seems ironic, yet it isn't. It provides your methods of testing things so your first argument to ok() isn't huge for more complex things. It also helps with clarity.<br /><br /><h3>Test::More</h3><br /><br />Let's go right into some code. Here is an example of using Test:More on the MultipleAsker class also:<br /><pre><br />#!/usr/bin/perl<br />#<br />use strict;<br />use warnings;<br /><br />use Test::More tests => 8;<br /><br />use_ok( 'MultipleAsker' ); # Easy to test importing the module<br /><br />my $ma = MultipleAsker->new();<br /><br />## Test of new()<br /># Much cleaner! (third argument is what to call the object)<br />isa_ok ($ma, 'MultipleAsker', 'ma');<br /><br />## Test ofFive()<br /># Compare values as seperate arguments<br />is ($ma->ofFive(24), 0, '24 is not multiple of 5');<br />is ($ma->ofFive(25), 1, '25 is multiple of 5');<br /><br /># Opposite of is, checks that first and second argument are not the same<br />isnt ($ma->ofFive(5), 0, '5 is multiple of 5');<br /><br />## Test ofThirty()<br /><br /># Show how to compare explicitly<br />cmp_ok ($ma->ofThirty(34), '==', 0, '34 is not multiple of 30');<br /><br /># Finish the rest out, can still use ok()<br />ok ($ma->ofThirty(120) == 1, '120 is multiple of 30');<br />ok ($ma->ofThirty(30) == 1, '30 is multiple of 30');<br /></pre><br /><br />Ask you can tell, there are several new methods available to use. Much more handy! Much cleaner and shorter way to test things that are not just an evaluation. While <i>'ok'</i> works, it is not as clear as some of the names of the other methods... you can figure out what is being tested and in what way much easier with Test::More.<br /><br />Oh! I almost forgot, here is the output:<br /><pre>1..8<br />ok 1 - use MultipleAsker;<br />ok 2 - ma isa MultipleAsker<br />ok 3 - 24 is not multiple of 5<br />ok 4 - 25 is multiple of 5<br />ok 5 - 5 is multiple of 5<br />ok 6 - 34 is not multiple of 30<br />ok 7 - 120 is multiple of 30<br />ok 8 - 30 is multiple of 30<br /></pre><br /><br />As you can see, using these modules is very simple. Testing is meant to be very simple and test simple things only. While I'm not sure why anyone would want to use Test::Simple, it is available to you. Test::More is much more standard. <strong>All that really matters is that you do write tests</strong>.<br /><br />Be sure to read the <a href="">CPAN</a> documentation for each module for a more complete description of all it's abilities.<br /><br />Hope you increase your testing percentages if they aren't maxed out already!<img src="" height="1" width="1" alt=""/>Christopher Humphries Perl's Net::SSH::PerlOne important point of Net::SSH::Perl => <strong>no humans required</strong>. Yeah, a BIG win.<br /><br />It's purpose is to provide all the SSH client functionality, yet purely in Perl where the <i>ssh</i> binary is not required. The big feature is that you don't have to type the password manually or setup passwordless ssh trust relationships (usually a bad idea unless you absolutely trust each side).<br /><br />So, it provides an easy way to ssh into machines and run commands (and get stdout, stderr, and exit code), providing the password and username in the code.<br /><br />With SSH 1, each command you run opens up a new session (it's how SSH1 works, yeah it's poo now-a-days), and with SSH 2 each command runs in the same session.<br /><br />One tip you'll <strong>need</strong> to know about is that you should install the <a href="">Math::BigInt::GMP</a> module. Why?! Because it is a fast BigInt implementation that will speed up SSH 2 sessions from like 30 seconds to 1 second.<br /><br />The awesomeness (if not obvious now): logging into machines via ssh and doing stuff in a perl program.<br /><br / <em>could</em> do many of these things via crontab on all servers, people have for years and years. I prefer to do it from one place where changes and new things are much more scalable and reliable.<br /><br />Here is an example of logging into a remote machine and checking it's diskspace, reporting back if it was over a certian amount:<br /><pre><br />#!/opt/local/bin/perl<br />#<br /># checkDiskspace.pl: See if any partitions are greater than a percentage and notify<br />#<br />use strict;<br />use warnings;<br /><br />use Net::SSH::Perl;<br />use Math::BigInt::GMP; # Don't forget this!<br /><br />$| = 1;<br /><br />my $alert_percent = 75;<br />my $server = 'niroze.net';<br />my $username = 'christopher';<br />my $password = '*******************************';<br /><br /><br /># However you wanna notify yourself (like email)<br />sub alert_notify {<br /> my $message = shift;<br /> print "STUB: $message\n";<br />}<br /><br /># Log into server<br />print "Creating ssh object... ";<br />my $ssh = Net::SSH::Perl->new($server); # Error check this<br />print "done\n";<br />print "Logging into server... ";<br />$ssh->login($username, $password); # Error check this<br />print "done\n";<br /><br /># Check df<br />my $Net::SSH::Perl CPAN page</a> for more details.</em><img src="" height="1" width="1" alt=""/>Christopher Humphries Perl's Mac::GlueAre you like me? Did you get a Mac and are in awe of the integration of everything? It was one of the reasons I got a Mac, yet I didn't look into the details of how everything was integrated. How do applications "talk" to one another?<br /><br />No, it was not <i>Appletalk</i> (yet that seems fitting word-wise). It's <a href=""><em>Applescript</em></a>.<br /><br />I may be a Mac newbie, yet I don't like "programming" Applescript at all. It should be natural, yet it isn't. It's actually very frustrating, yet that's just part of learning it. <br /><br />To quote <a href="">devintosh.com FAQ</a> (<a href="">freenode</a> IRC network #macdev channel):<br /><blockquote><strong>I have a problem with my AppleScript, can you help?</strong><br /<br /></blockquote><br /><br />Ok, I got that. Am past it... I still don't like it (thanks to mikeash on #macdev for enlightening me... before I went too far down the wrong rabbit hole).<br /><br />I want a real programming language to be able to do the same things Applescript does. Isn't there a way?! <strong>Yes!</strong> There is <a href="">Mac::Glue</a>, which gives you all the same functionality of Applescript except you can now do it in Perl. Hrm... sounds like a bunch of bologna? Yeah, I agree... till I poked around into learning it. I'd like to share with you what I found.<br /><br />First, install Mac::Glue. It's in <a href="">MacPorts</a> : "<i>sudo /opt/local/bin/gluemac /Applications/iTunes.app</i>". No big deal, just be sure to do it for programs you plan on working with.<br /><br />Second, note this isn't a full coverage of all that Mac::Glue does. This just shows how to port over some Applescript and "talk" to other programs via their bindings.<br /><br />Now, to my favorite part. Some code! <i>[sorry, it's not that impressive -ed.]</i><br /><br />In the first example, lets port over something easy like "/Library/Scripts/Basics/AppleScript Help.scpt". It opens up 'Help Viewer.app', activates it, and then searches looking for 'AppleScript'.<br /><br />Here is the AppleScript code:<br /><pre><br />tell application "Help Viewer"<br /> activate<br /> search looking for "AppleScript"<br />end tell<br /></pre><br /><br />Here is the Perl code:<br /><pre><br />#!/opt/local/bin/perl<br />#<br /># Glue requirement:<br /># * sudo /opt/local/bin/gluemac "/System/Library/CoreServices/Help Viewer.app"<br /># Port of:<br /># * "/Library/Scripts/Basics/AppleScript Help.scpt"<br />#<br />use strict;<br />use warnings;<br /><br />use Mac::Glue;<br /><br /><br />my $glue = new Mac::Glue 'Help_Viewer';<br />$glue->search(looking_for => 'AppleScript');<br /></pre><br /><br />You may be wondering how I knew what subroutine to call. It's in the glue code pod file. Since I'm using MacPorts in these examples, I did this: "<i>perldoc /opt/local/lib/perl5/vendor_perl/5.8.8/Mac/Glue/glues/Help_Viewer.pod</i>". Be sure to look in that directory for help on how to use the "glue".<br /><br />How about a simple adding someone to your address book? <br /><pre><br />#!/opt/local/bin/perl <br /># <br /># Glue requirement: <br /># * sudo /opt/local/bin/gluemac "/Applications/Address Book.app" <br /># Explanation and original code examples from Chris Nandor: <br /># * <a href=""></a> <br /># <br />use strict;<br />use warnings;<br /><br />use Mac::Glue ':all'; # all for 'location'<br /><br />my $glue = new Mac::Glue 'Address_Book';<br /><br />my $me = $glue->make (new => 'person', <br /> with_properties => {<br /> 'first_name' => 'Steve',<br /> 'last_name' => 'Jobs'<br /> }<br /> );<br />$glue->make (new => 'email', at => location(end => $me->prop('emails')),<br /> with_properties => {<br /> 'value' => 'fakestevejobs@gmail.com',<br /> 'label' => 'home'<br /> }<br /> );<br /></pre><br /><br /.<br /><br />Much thanks to <a href="">Chris Nandor</a> and everyone else that may have been involved in Mac::Glue. <br /><br />I still have much to learn, yet at least we both know that we can do what we need in Perl... at least in this respect. In any place you can use AppleScript, try using Mac::Glue instead. I recommend getting the <a href="">FastScripts</a> utility if you can, it's like the regular AppleScripts menu, yet much more flexible as it can run any kind of program and have custom keybindings (very handy).<br /><br /><i>To be fair, before I get complaints in my inbox, the ability to do the same thing exists for Ruby, Objective-C and Python available at <a href=""></a>. I played with it in Python and Ruby and it seems to work very well. So, give it a try if you're not a Perl coder.</i><br /><br />Do you have any cool Mac::Glue examples? If so, post them and happy hacking!<img src="" height="1" width="1" alt=""/>Christopher Humphries Perl's Test::Class for Organized Unit TestingI'm not going to go over the merits of unit testing. I've heard it all and discussed both sides till blue in the face. If you're unsure about unit testing, then please google it or ask some programmers you know about it.<br /><br />What I do want to discuss is <strong>how</strong> one does unit testing in Perl. It's pretty simple, fortunately. <br /><br />In the world of testing classes in <a href="">CPAN</a>, there are a few that you'll actually use: <a href="">Test::Simple</a>, <a href="">Test::More</a>, <a href="">Test::Harness</a>, and <a href="">Test::Class</a>. <i>planning</i> on running). Test::Class manages itself, using Test::Class for tests and to run them (Test::Class allows you to have a plan per Test::Class subclass subroutine... I'll explain in a bit).<br /><br />Today, I'm not going to talk about Test::Harness or Test::Simple. I will some other time. <br /><br />I will talk about Test::More and Test::Class. They're pretty awesome and really really simple to use. Don't believe me?! Let's jump into some code.<br /><br /).<br /><br />Here's the Hotdog Vendor class (<a href="">download here</a>):<br /><pre><br />#<br /># HotdogVendor.pm: Provide a Hotdog Vendor<br />#<br />package HotdogVendor;<br /><br />use strict;<br />use warnings;<br /><br />sub new {<br /> my ($class, $name, $how_many) = @_;<br /> my $attrs = {<br /> franks => $how_many,<br /> buns => $how_many,<br /> mustard => $how_many,<br /> kraut => $how_many,<br /> name => $name<br /> };<br /> bless ($attrs, $class);<br />}<br /><br />sub _use_product {<br /> my ($self, $product, $how_many) = @_;<br /><br /> if (($self->{$product} - $how_many) < 1) {<br /> die "[$self->{name}] use_$product: Unable to processor order, not enough $product (you wanted $how_many, I only got $self->{$product}";<br /> }<br /><br /> $self->{$product} -= $how_many;<br />}<br /><br />sub _has_product {<br /> my ($self, $product) = @_;<br /><br /> if (!defined $self->{$product}) {<br /> die "[$self->{name}] has_$product: undefined product (wrong vendor?!)";<br /> }<br /><br /> return ($self->{$product});<br />}<br /><br /># Franks<br />sub use_franks {<br /> my ($self, $how_many) = @_;<br /><br /> $self->_use_product('franks', $how_many);<br />}<br />sub has_franks {<br /> my ($self) = shift;<br /><br /> return ($self->_has_product('franks'));<br />}<br /><br /># Buns<br />sub use_buns {<br /> my ($self, $how_many) = @_;<br /><br /> $self->_use_product('buns', $how_many);<br />}<br />sub has_buns {<br /> my ($self) = shift;<br /><br /> return ($self->_has_product('buns'));<br />}<br /><br /># Mustard<br />sub use_mustard {<br /> my ($self, $how_many) = @_;<br /><br /> $self->_use_product('mustard', $how_many);<br />}<br />sub has_mustard {<br /> my ($self) = shift;<br /><br /> return ($self->_has_product('mustard'));<br />}<br /><br /># Kraut<br />sub use_kraut {<br /> my ($self, $how_many) = @_;<br /><br /> $self->_use_product('kraut', $how_many);<br />}<br />sub has_kraut {<br /> my ($self) = shift;<br /><br /> return ($self->_has_product('kraut'));<br />}<br /><br /># Name<br />sub name {<br /> my ($self) = shift;<br /><br /> return ($self->{name});<br />}<br /><br />1;<br /></pre><br /><br /><br />As you can see, it saves the name and amount for each product. It then provides subroutines to get the amount of product left, use up some product, and see what the vendor's name is. Pretty simple.. excuse my copy and paste.<br /><br /?).<br /><br />Here is the Hotdog Vendor Test class (<a href="">download here</a>):<br /><pre><br />#<br /># HotdogVendor_Test.pl: HotdogVendor.pm Test (Test::Class, unit testing)<br />#<br /><br />package HotdogVendorTest;<br /><br />use base qw(Test::Class);<br />use Test::More;<br /><br />use HotdogVendor;<br /><br /># Test that name is saved on new vendor creation<br />sub test_name : Test(1) {<br /> my $the "secret" Perl attribute technique. You can look that up yourself.</a>. <br /><br />How do you run the tests? Here is how (<a href="">download here</a>):<br /><pre><br />#!/opt/local/bin/perl<br />#<br />use strict;<br />use warnings;<br /><br />use Test::Class;<br /><br />use HotdogVendorTest;<br /><br /><br />Test::Class->runtests;<br /></pre><br /><br />The output:<br /><pre><br />$ /opt/local/bin/perl run_tests.pl<br />1..9<br />ok 1 - buns amount saved<br />ok 2 - 100 - 60 buns is 40 buns<br />ok 3 - franks amount saved<br />ok 4 - 100 - 60 franks is 40 franks<br />ok 5 - kraut amount saved<br />ok 6 - 100 - 60 kraut is 40 kraut<br />ok 7 - mustard amount saved<br />ok 8 - 100 - 60 mustard is 40 mustard<br />ok 9 - name saved<br /></pre><br /><br /.<br /><br />Comments? Suggestions? This is my first in a big series of Perl and Mac development articles. I'm starting off simple so I have something to build on for later articles. Hrm, now that I think about it... what do you want to know about??<br /><br />Let me know and happy testing!<img src="" height="1" width="1" alt=""/>Christopher Humphries
http://feeds.feedburner.com/PerlAndMacDevelopmentBlog
CC-MAIN-2017-43
refinedweb
4,932
62.38
Worker threads super charged the abilities of JavaScript(Node), as it was formerly not ideal for CPU-intensive operations. This post explores how worker threads work in Node. From conception, JavaScript has been a single-threaded language. Single-threaded in the sense that only one set of commands can be executed at any given time in the same process. By extension, Node.js isn’t a good choice for implementing highly CPU-intensive applications. To solve this problem, an experimental concept of worker threads was introduced in Node v10.5.0 and was stabilized in v12 LTS. The worker_threads module enables the use of threads that execute JavaScript in parallel. It can be accessed with any of the following syntax: worker_threads const worker = require('worker_threads'); // OR import worker_threads; Worker threads work in a different way than traditional multi-threading in other high-level languages. A worker’s responsibility is to execute a piece of code provided by the parent worker. It runs in isolation from other workers, but has the ability to pass information between it and the parent worker. Each worker is connected to its parent worker via a message channel. The child worker can write to the message channel using parentPort.postMessage function, and the parent worker can write to the message channel by calling worker.postMessage() function on the worker instance. parentPort.postMessage worker.postMessage() Now, one might ask how a node worker runs independently, as JavaScript doesn’t support concurrency. The answer: v8 Isolate. A v8 Isolate is an independent instance of Chrome v8 run-time, which has its own JavaScript heap and a micro-task queue. This allows each Node.js worker to run its JavaScript code in complete isolation from other workers. The downside of this is that the workers cannot directly access each other’s heaps directly. Due to this, each worker will have its own copy of libuv event loop, which is independent of other workers’ and the parent worker’s event loops. As earlier pointed out, the worker_thread API was introduced in v10.5.0 and stabilized in v12. If you’re using any version prior to 11.7.0, however, you need to enable it by using the --experimental-worker flag when invoking Node.js. --experimental-worker In our example, we are going to implement the main file, where we are going to create a worker thread and give it some data. The API is event-driven, but it’ll be wrapped into a Promise that resolves in the first message received from the worker: // index.js // run with node --experimental-worker index.js on Node.js 10.x const { Worker } = require('worker_threads') const runService = (workerData) => { return new Promise((resolve, reject) => { const worker = new Worker('./myWorker.js', { workerData }); worker.on('message', resolve); worker.on('error', reject); worker.on('exit', (code) => { if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`)); }) }) } const run = async () => { const result = await runService('world') console.log(result); } run().catch(err => console.error(err)) As you can see, this is as easy as passing the filename as an argument and the data we want the worker to process. Take note that this data is cloned and is not in any shared memory. Then, we wait for the Worker thread to send us a message by listening to the message event. Next, we need to implement the service. const { workerData, parentPort } = require('worker_threads') // You can do any heavy stuff here, in a synchronous way // without blocking the "main thread" parentPort.postMessage({ greetings: workerData }) Here, we need two things. First the workerData that the main app sent to us, and secondly, a way to return information to the main app. This is done with the parentPort that has a postMessage method where we will pass the result of our processing. workerData parentPort postMessage It’s as straightforward as that! This is a somewhat simple example, but we can build more complex things—for example, we could send multiple messages from the worker thread indicating the execution status if we need to provide feedback, or we can send partial results. Imagine that you are processing thousands of images and maybe you want to send a message per image processed, but you don’t want to wait until all of them are processed. Understanding at least the very basics of how they work indeed helps us to get the best performance using worker threads. When writing more complex applications than our example, we need to remember the following two major concerns with worker threads. To overcome the first concern, we need to implement "Worker Thread Pooling." A pool of Node.js worker threads is a group of running worker threads that are available to be used for incoming tasks. When a new task comes in, it can be passed to an available worker via the parent-child message channel. Once the worker completes the task, it can pass the results back to the parent worker via the same message channel. If properly implemented, thread pooling can significantly improve the performance as it reduces the additional overhead of creating new threads. It also worth mentioning that creating a large number of threads is also not efficient, as the number of parallel threads that can be run effectively is always limited by the hardware. The introduction of worker threads has super charged the abilities of JavaScript(Node), as they has effectively taken care of its biggest shortcoming of not being ideal for CPU-intensive operations. For additional information, check out the worker_threads documentation. Writer of all things technical and inspirational, developer and community advocate. In a love-love relationship with JavaScript, a web accessibility nerd.
https://www.telerik.com/blogs/exploring-the-worker-thread-api-in-node
CC-MAIN-2020-34
refinedweb
944
56.86
Very large numbers of particles can be employed at little cost since most cpu time is taken up by the determination of the potential on the grid. [See Sellwood (1997, in "Computational Astrophysics" ed Clarke & West, ASP Conf series v123, p215) for a performance comparison with other codes.] The version of the algorithm used here requires the individual grid cells to be cubic, but the overall grid need not be cubic. The FFTs supplied require the number of mesh spaces in each direction to be (2**n + 1), where the exponent n may be chosen independently for each coordinate direction. As large grids require a great deal of memory (c400 MB for a 257**3 grid), it is recommended that the parameters set in the include file ’rjinclude.h’ be no larger than necessary, although the code will function correctly as long as the actual dimensions used do not exceed those set by the parameter statement at compile time. Time integration follows the standard 2nd order time-centered leap-frog, with the velocities one half a time step out of synchrony with positions. This difference is maintained in the internally stored coordinates and is created and can be undone, by a call to subroutine TMCENT. For output of the particle coordinates at a particular instant, the velocities need to be the average of those before and after the time for the positions. Results, in this public version, are simply the phase space coordinates of all the particles as often as requested, which can create a very large file. The authors therefore do not employ this scheme themselves, preferring instead to measure and save properties of the model as the simulation evolves. An example of this "on the fly" analysis is provided in the routines ICHECK and MEASURE to determine the global integrals (energy, momentum, etc) The grid is set up in subroutine GRDSET using parameters read in from a short ASCII input file (galaxy.dat). The positions and velocities of the particles are read in subroutine LOADUP, from a local file galaxy.ini. The gravitational field is determined by a call to FINDF. The model is integrated forward by a call to STEP. After the desired evolution is completed, the positions and velocities of the particles are saved by a call to UNLOAD. The new 2014 public release of galaxy contains an updated code, including versions of SCF (see scfm(1NEMO) ) and BHTREE (see hackcode1(1NEMO) ). $NEMO/src/nbody/evolve/sellwood source code tree (w/ res2snap & snap2ini)The main files associated with the run are (notice the basename ’galaxy’ is fixed by the code): galaxy.dat ASCII input: grid parameters, length and time scales galaxy.ini ASCII input: initial coordinates of all the particles galaxy.lis ASCII output: a brief summary of progress (appended) galaxy.fin ASCII output: final coordinates of all the particles galaxy.res binary output: coordinates and potentials at intervals (appended) galaxy.tmp short ASCII file (deleted when closed) galaxy.aux large binary file (deleted when closed) Sample galaxy.dat initialization file: 33 33 33 # number of grid cells in (x,y,z) 15.0 # number of grid cells per length unit 0.05 # time step length 0.5 # time between particle outputs 0.1 # time between integral checks 1.00 # end time The format of the ASCII galaxy.ini (and also galaxy.fin) files is: Time Mass Nbody X_1 Y_1 Z_1 VX_1 VY_1 VZ_1 .... X_n Y_n Z_n VX_n VY_n VZ_nThe galaxy.fin can also be used for a restart. Note that the timestep is one more then the last requested time, to prevent that the galaxy.res file will contain a datadump on the restart timestep twice. The new release V15 does not depend on commercial (e.g. NAG) software, and can be compiled using open source tools and libraries. PGPLOT must be installed independantly. #! /bin/csh -f if ($#argv != 2) then echo Usage: res2snap FILE N echo Converts the N-th snapshot from FILE to NEMOs snapshot format exit 0 endif # set command line parameters set file=$1 set n=$2 # get header info set tsnap=‘unfio $file "$n*2-1" float | awk ’{if (NR==1) print $1}’‘ set nbody=‘unfio $file "$n*2-1" int | awk ’{if (NR==2) print $1}’‘ # dump data and convert to snapshot unfio $file "$n*2" float maxbuf=100000 |\ tabtos - ${file:r}.$n.snap "" pos,vel,phi options=wrap times=$tsnap nbody=$nbody James & Sellwood (1978, MNRAS v182, p331) James (1977, J Comp Phys v25, p71). Sellwood (1997, in "Computational Astrophysics" ed Clarke & West, ASP Conf series v123, p215) (full 2014 version) 9-jun-97 V1.0 Sellwood public release/adopted for NEMO JS/PJT 24-jun-97 V1.1 added ICHECK/MEASURE; dtlog to galaxy.dat JS 18-mar-04 fixed bad usage line; refer to rungalaxy now PJT 8-mar-06 V1.3 now installs by default into NEMOBIN PJT 26-jun-2014 notes on the official full public release PJT 10-mar-2017 notes on the new V15 release PJT Table of Contents
http://bima.astro.umd.edu/nemo/man_html/galaxy.1.html
CC-MAIN-2017-47
refinedweb
837
63.8
Int for Updates to install the patch right from the IDE. Otherwise, you’re welcome to download and install the new version from the website. As always, we appreciate your feedback here in comments or directly in our issue tracker. UPDATE: Don’t worry if you notice a confusing message in the Updates dialog saying that you can evaluate the new version for 30 days, or buy a license key or upgrade online. This is a known problem that will go away after you’ve updated. Develop with pleasure! 69 Responses to IntelliJ IDEA 2016.1.1 Update is Out Andrew says:March 31, 2016 Hi! Are this update includes fix for clipboard ignoring in Windows? Andrey Cheptsov says:March 31, 2016 Yes, this problem has been fixed: Andrey Cheptsov says:March 31, 2016 I’m wrong, the fix hasn’t make it to this update. Sorry. Dmitriy says:March 31, 2016 I’m getting reports from my team that this update makes IJ start indexing, and it won’t complete. Pete O'Bryan says:April 4, 2016 It hangs on indexing *.sql files. I marked the “Database” directory where I keep *.sql as Excluded, and it stopped trying to index them. That fixed the issue, but of course now I no longer have an integrated view of my sql files. Scott says:April 6, 2016 Thank you Pete. Excluding my .sql directory finally allowed my indexing to complete. User says:March 31, 2016 Gradle multi module support is still broken! Last time it worked fine was 15.0.5! Fix it ASAP! Dominic North says:April 5, 2016 I am also noticing a problem which is possibly related to this. I have a multi-module Gradle project that I created sometime ago in IntelliJ (15, or even 14). I have just revisited the project, for the first time since I upgraded to 2016, and find that tests now fail running from the IDE, even setting Gradle | Runner ‘Gradle Test Runner’. The failure is due to resources not being found in the classpath by Spring. This worked fine before the upgrade. I should add that I can run the same tests without problem running the Gradle build itself in IntelliJ Dominic North says:April 5, 2016 …. and now I’ve found the answer, which is to remove the (pre-)existing Run Configurations that fail. Having done so, you can create them again run them in JUnit, and they work fine. Murat Berk says:March 31, 2016 It got slow !!! Andrey Cheptsov says:March 31, 2016 Could you please provide more details, e.g. a CPU snapshot? This will help us fix it sooner. Xiujun says:April 1, 2016 It uses very very slow !! Tefa says:April 1, 2016 I don’t think saying that its “very very slow” helps anyone Dobbo says:May 11, 2016 It’s extremely slow. On 2016.1.2. Laptop with Intel Core i7-3720QM @ 2.60Ghz and 32 GB ram. CPU and memory at roughly 10% utilization respectively. Loading Django in python interpreter (not debug) takes roughly 4.5 seconds to start compared to a few milliseconds before the 2016 build. I also noticed some problems with Python Interpreters getting mixed up (Pycharm using other’s projects environments unexpectedly). Sathish Dharma says:March 31, 2016 Unable to compile java classes. It’s throwing Stack Overflow error. Information:Using javac 1.8.0_51 to compile java sources Information:java: The system is out of resources. Information:java: Consult the following stack trace for details. Information:java: at com.sun.tools.javac.util.Position$LineMapImpl.build(Position.java:153) Information:java: at com.sun.tools.javac.util.Position.makeLineMap(Position.java:77) Information:java: at com.sun.tools.javac.parser.JavaTokenizer.getLineMap(JavaTokenizer.java:763) Information:java: at com.sun.tools.javac.parser.Scanner.getLineMap(Scanner.java:127) Information:java: at com.sun.tools.javac.parser.JavacParser.parseCompilationUnit(JavacParser.java:3130) Information:java: at com.sun.tools.javac.main.JavaCompiler.parse(JavaCompiler.java:628) Information:java: at com.sun.tools.javac.main.JavaCompiler.parse(JavaCompiler.java:665) Information:java: at com.sun.tools.javac.main.JavaCompiler.parseFiles(JavaCompiler.java:950) Information:java: at com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:857) Information:java: at com.sun.tools.javac.main.Main.compile(Main.java:523) Information:java: at com.sun.tools.javac.api.JavacTaskImpl.doCall(JavacTaskImpl.java:129) Information:java: at com.sun.tools.javac.api.JavacTaskImpl.call(JavacTaskImpl.java:138) Information:java: at org.jetbrains.jps.javac.JavacMain.compile(JavacMain.java:168) Information:java: at org.jetbrains.jps.incremental.java.JavaBuilder.compileJava(JavaBuilder.java:388) Information:java: at org.jetbrains.jps.incremental.java.JavaBuilder.compile(JavaBuilder.java:289) Information:java: at org.jetbrains.jps.incremental.java.JavaBuilder.doBuild(JavaBuilder.java:197) Information:java: at org.jetbrains.jps.incremental.java.JavaBuilder.build(JavaBuilder.java:168) Information:java: at org.jetbrains.jps.incremental.IncProjectBuilder.runModuleLevelBuilders(IncProjectBuilder.java:1238) Information:java: at org.jetbrains.jps.incremental.IncProjectBuilder.runBuildersForChunk(IncProjectBuilder.java:912) Information:java: at org.jetbrains.jps.incremental.IncProjectBuilder.buildTargetsChunk(IncProjectBuilder.java:984) Information:java: at org.jetbrains.jps.incremental.IncProjectBuilder.buildChunkIfAffected(IncProjectBuilder.java:871) Information:java: at org.jetbrains.jps.incremental.IncProjectBuilder.buildChunks(IncProjectBuilder.java:696) Information:java: at org.jetbrains.jps.incremental.IncProjectBuilder.runBuild(IncProjectBuilder.java:387) Information:java: at org.jetbrains.jps.incremental.IncProjectBuilder.build(IncProjectBuilder.java:194) Information:java: at org.jetbrains.jps.cmdline.BuildRunner.runBuild(BuildRunner.java:137) Information:java: at org.jetbrains.jps.cmdline.BuildSession.runBuild(BuildSession.java:294) Information:java: at org.jetbrains.jps.cmdline.BuildSession.run(BuildSession.java:125) Information:java: at org.jetbrains.jps.cmdline.BuildMain$MyMessageHandler$1.run(BuildMain.java:232) Information:java: at org.jetbrains.jps.service.impl.SharedThreadPoolImpl$1.run(SharedThreadPoolImpl.java:44) Information:java: at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) Information:java: at java.util.concurrent.FutureTask.run(FutureTask.java:266) Information:java: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) Information:java: Errors occurred while compiling module ‘testing’ Information:3/31/16, 4:29 PM – Compilation completed with 1 error and 0 warnings in 5m 59s 47ms Error:java: OutOfMemoryError: insufficient memory Nikolay Chashnikov says:April 1, 2016 How big is your project? Probably the default heap size isn’t sufficient to build it, try increasing “Build process head size” in File | Settings | “Build, Execution, Deployment” | Compiler. Jeremy Barrow says:July 7, 2016 I’m getting the exact same issue. I’ve bumped it up to 2048 MB, and testing it now, but it’s weird because Eclipse can do it with less than 900MB, so I don’t know what’s changed to make it do this. Sathish Dharma says:March 31, 2016 Sorry for typo. It’s OutOfMemoryError. wumin says:April 1, 2016 it become so slow. Tefa says:April 1, 2016 Still no fix for gradle mutli module support. This is really a deal breaker for MANY people to use the new Idea version. Please fix Ivan says:April 1, 2016 Start of Typescript debugger became faster (from 2 minutes to 20 seconds)! Thank you! neuron says:April 1, 2016 the idea 2016 can’t compare files under mac os 10+ neuron says:April 2, 2016 This is not a bug. I found that the diff viewer window is so small, thus I not notice it. Thinks! Dmitry says:April 1, 2016 IntelliJ Idea 2016 was unable to apply the downloaded patch (OutOfMemory error) with thedefault heap size. I had to change it to 2048m manually to resolve it. Unfortunately I haven’t copied the log, and it was overwritten during the last (successful) update. Wayne Wang says:April 1, 2016 Hi~ I’m very glad that the update is out. However, after update my idea to 2016, the idea consume too much CPU that I can hardly work with the new edition. A simple operation may cause the idea use more than 20% cpu even to full cpu. I don’t know why. What I can do is only to downgrade it to 2015. Hope you will fix it soon. john says:April 1, 2016 Did the ‘Find Usages’ functionality just changed? I can only seem to find in-module usage even though it says ‘in Project Files’.. lineNumberConfused says:April 2, 2016 Why intellij idea 2016.1 and 2016.1.1 cannot show line number in run console? Right click in the editor and you can choose to click show line numbers, but the console does not offer the same choice. I’m sure II 2015 or earlier version did offer. used in mac osx 10.11.3! rexebin says:April 2, 2016 The new version somehow become very slow, cannot see cpu or memory pikes, but it is just slow. My computer is a recently purchased top spec desktop, yet I need to wait for 2 sec for the recent files to pop open the first time. When I write code in ts files, the editor is so slow that it cannot follow my typing speed which is not very fast. Something is wrong for sure, reversing back to 11.0.3, everything is so smooth! rexebin says:April 2, 2016 I deleted all my previous version of webstorm and did a clean install of the latest webstorm 2016.1.1, it seemed that the smoothness is back. David Zhao says:April 3, 2016 My PyCharm is consuming 100% CPU after starting – without running any codes. I thought it was due to some updates, so I left it for hours, but it’s still the case. Don’t know what is going on for using so much resources. The editor also gets slow, sometime got stuck when editing the code. blab says:April 4, 2016 Random thought: ‘Optional.get()’ without ‘isPresent()’ check should be weak warning for test code by default, I think. Yann Cébron says:April 5, 2016 You can setup custom inspection severity by scopes. blab says:April 5, 2016 Yep, I know. Just thought maybe it should be considered to be weaker for test-code by default. Personally I see no such cases for test-code, where I would like to avoid getting an error if the element does not exist. Unless I do and I expect it to not exist. Sebastian says:April 4, 2016 Unfortunately Idea is very slow after updating to this patch and I think that it is connected with some enormous disk usage. I see it on performance view of task manager on windows 7 and slowest operations are connected with changing file name or moving package from one place to another or even with creating files. Project is a Gradle project with Java 8. Maybe it is something with caching? Pete O'Bryan says:April 4, 2016 Immediately after upgrading from 2016.1 to 2016.1.1 the IDE began indexing a *.sql file and continued trying to index it, using enough CPU to make my laptop hot. I edited the project properties, marked as “Excluded” the “Database” directory where I keep *.sql files. That fixed the issue, but of course now I no longer have an integrated view of my sql files. Gang Chu says:April 5, 2016 Seems My IntelliJ got slow too. When I typing code, CPU stay hight usages. Now, I roll back to last release(2016.1), which seems released at Mar 17, 2016. And My IntelliJ smooth again when I typing code. PS. My ware: MacBook pro 15 (2.8GHz, 16G RAM), just purchased last month. Andrey Cheptsov says:April 6, 2016 Could you please provide more details, e.g. A CPU snapshot (see)? This will help get it fixed sooner. Paul Bartlett says:April 10, 2016 Hi Andrey, I will also be posting up a CPU Snapshot. I have MBP Retina-Mid 2015 i7 16GB etc and even with the Hello World Java app you cannot type a comment faster that 1 CPS. I have a Mac desktop running same OS version, Java, Everything and it does not run this slow. Marshall says:April 5, 2016 I upgraded to Rubymine 2016.1, and WOW is it ever slow. If I click somewhere, it takes a noticeable amount of time to move the cursor. If I type text into an editor, it can take upwards of a second for it to show up. Changing the active tab is very very slow. It’s not busy indexing, and the used memory varies widely from ~150mb to ~500mb (out of 500mb for the JVM). If I bring the activity monitor up and start using Rubymine, the process spikes the CPU quite frequently. I have a newer Macbook Pro with a Core i7-4870HQ processor, 16gb RAM, and a 500gb SSD. As it is now, it’s unusable on my machine and I’m forced to downgrade to Rubymine 8.0. Andrey Cheptsov says:April 6, 2016 We would appreciate very much a CPU snapshot taken according to this doc: John says:April 6, 2016 When I tried to add a namaspace in the spring configurion xml or springMVC-config xml, I coudn’t get any code hints for the namespace. For example, in the version 15, when I wrote xmlns:context=”context”…..I can got the path of Context’ namespace. And it was the same as xsi:schemaLocation=””, I couldn’t got code completion hints as I got when I use version 15. Please fix it! Yann Cébron says:April 6, 2016 John, most likely the dependency containing the XSD for the namespace is not visible from that XML. Please verify and create a bug if it still doesn’t work: Thanks. Andreas Merkel says:April 6, 2016 This version is unusable. As soon as I start editing a file, Pycharm freezes and CPU usage jumps to 100%. Andrey Cheptsov says:April 6, 2016 Could you please make a CPU snapshot and attach it to an issue in our tracker? This will help us very much to fix the problem. More details on how to do that: Doe says:April 6, 2016 My Pycharm 2016.1.1 hangs with 100% CPU usage after a few minutes. I haven’t identified any triggering event – it occurs when I run familiar scripts that was working fine in 2016.1. Andrey Cheptsov says:April 6, 2016 A CPU snapshot may help us identify the cause. We would appreciate if you could take it and send us. Here is the instruction how to do that: Lukas says:April 6, 2016 Did you try to change project to other one? In my case the same issue occurs on one project only. I think it’s the one I have opened when I made an update. Currently, when I start Pycharm on some other project everything is OK until I switch the project to the one on which the issue occurs. Soon after, Pycharm start to use a lot of CPU and it hangs. I tried to downgrade Pycharm to 2016.1 but without success. I still have excessive CPU usage although previously on this version everything was fine. I suppose that something went wrong during an update process and some project settings are broken which causes this issue. Andrés says:April 8, 2016 I just tried deleting the .idea folder on my project and it seems to be working way faster. I hope it remains that way. Thanks for the idea! Radek Lát says:July 29, 2016 I am experiencing the same kind of problem after upgrading to 2016.2. Deleting the .idea folder worked for me as well. John says:April 11, 2016 (Here I can’t get any hints for completion code. I have to manually write down each key!) When we use “LocalSessionFactoryBean” and finish the property of “hibernateProperties”, we do can get the key from IDEA. ture true update <prop key="hibernate…….." John says:April 11, 2016 In this situation, I can’t get any hints for keys, I have to write them down one by one,word by word, it’s just not smart….sadly ture true update <prop key="hiber…….." John says:April 11, 2016 In this situation, I can’t get any hints for keys, I have to write them down one by one,word by word, it’s just not smart….sadly ture true update <prop key="hiber…….." Pascal Welsch says:April 11, 2016 The font looks a lot bolder than in Android Studio on OSX. And it’s a little bit blurry Hans Adler says:May 5, 2016 After updating today (I had to run IntelliJ as root for the first time for this, and afterwards I had to make /usr/local/bin/idea world-executable again!), IntelliJ tells me it is version 2016.1.0 and keeps asking me to update 2016.1.1. When I try to update again, it downloads and seems to install something (without messing with the rights for /usr/local/bin/idea again), and restarts. Then the same happens again, in an endless loop. Patrick says:May 6, 2016 Why Shift+Esc cannot let cursor go back to editor automatically? I need press Esc let cusor go back to editor first then using Shift+Esc hiding find window, that’s annoying. all previous versions are not like this. Tonni says:May 9, 2016 hi, when I tried to run a html file with bootstrap by intelliJ IDEA 2016.1.1 and it shown me like this: Index file doesn’t exist. 404 not found how can I fix that problem? Thanks David Spiegel says:May 12, 2016 Patches never work. I am running 2016.1 and attempted to install patch, but it pays no attention to my config settings and creates a new .PhpStorm2016.1 folder in my project home directory (~/Projects). My config is setup to use .PhpStorm folder in ~/Projects/apps/.PhpStorm and PhpStorm is located in ~/Projects/apps/PhpStorm2016 folder . So when PhpStorm restarts after patch, it does not see the patch information because IDE is not looking in ~/Projects/.PhpStorm2016.1 for config but in the defined ~/Projects/app/.PhpStorm folder I have configured. No patch files are seen. So I am unable to install patch. This is not first time. It occurred for any previous patches also. iShishir says:May 16, 2016 After upgrade to 2016.1.1 idea is very very slow. You can’t even type code. Even search results are slow. Env Det: running idea64.exe on Win 7 i7@2.7Ghz with 16 GB of RAM iShishir says:May 25, 2016 After upgrading to 2016.1.2 even 32 bit version of exe has dam slow. It has almost became unusable for me. Need immediate attention. iShishir says:May 25, 2016 I have already uploaded the snapshot. thanks iShishir says:May 26, 2016 Can’t wait much I have downgraded to 2015.0.6 and as fast as it was 🙂 Waqar Arshad says:May 17, 2016 Is there any solution for the Slowness of IntelliJ 2016. Andrey Cheptsov says:May 17, 2016 Please send us a CPU snapshot taken according to these instructions: Waqar Arshad says:May 17, 2016 Andy Thank you for the response. We have a team of more than 10 developers and everybody is experiencing the same issue. Kostas says:May 24, 2016 Hi, you used to have a zip download format in previous releases but the URL doesn’t work anymore (). In my corporate network we are not allowed to download executables. Is it possible to make the windows zip file available again? Cheers Andrey Cheptsov says:May 25, 2016 It’s available, but we have change the URL. It’s now Poul says:June 8, 2016 Could you provide any links to previous versions without patch for other platforms ? Entire teams can not work because of your latest update. Could you provide any workaround? When it will be fixed ? Andrey Cheptsov says:June 13, 2016 Why can’t you team work? If you would like to download a previous version not listed at, a workaround would be to replace the version number in the URL manually to one you need, e.g. “-15.0.5” instead of “-15.0.6”. Haojun says:June 16, 2016 Recently I realize that if I’m opening two projects with two separate Intellij windows, it is very slow and sometime it’s even freezing.
https://blog.jetbrains.com/idea/2016/03/intellij-idea-2016-1-1-update-is-out/?replytocom=372941
CC-MAIN-2020-29
refinedweb
3,394
59.7
Opened 3 years ago Closed 3 years ago Last modified 3 years ago #9250 closed defect (wontfix) fresh install rolls back TimingAndEstimationPlugin_Db_Version in system table in sqlite Description to reproduce: - create a new environment with sqlite database - follow setup instructions - trac-admin /some/env upgrade output looks good - run trac-admin /some/env upgrade a second time - upgrade assumes a full install is needed for lack of TimingAndEstimationPlugin_Db_Version - upgrade fails creating the billing table a second time narrowed down cause: - dbhelper::db_table_exists() called by CustomReportManager::upgrade() somehow causes the system table entry for TimingAndEstimationPlugin_Db_Version to be rolled back. - since it's a fresh install there is no custom_report table - dbhelper::db_table_exists() correctly returns false in the response to the exception for select from the non-existent table - but has the side effect of rolling back - absence of the db version entry causes upgrade checks to assume full install is required again FWIW: We will live for now - since we'll be using sqlite for the foreseeable future, we just made dbhelper::db_table_exists() return early as follows: def db_table_exists(env, table): return get_scalar(env, ("select count(*) from sqlite_master where type = 'table' and name = '%s'" % (table))) > 0; Obviously not a viable solution, but could be made conditional if - dbhelper can query database backend - nested transactions as used by dbhelper fail only for sqlite As such it would serve as a work around for many environments Sorry if notation is substandard - spent half as much time looking at python code today as I have in entire my career prior - when I read 'dive into python' years ago ;) Thanks for a plugin worth debugging! Attachments (0) Change History (4) comment:1 follow-up: ↓ 2 Changed 3 years ago by bobbysmith007 comment:2 in reply to: ↑ 1 Changed 3 years ago by anonymous - Priority changed from normal to lowest Replying to bobbysmith007: This should only be rolling back to the save point but... I found a quote on the internet claiming "SAVEPOINT first appeared in SQLITE V 3.6.8" so this is very likely the ultimate cause of the issues. Right on! Just tried a vanilla install with sqlite 3.7.4 and problem did not manifest. I will look at special casing this function for sqlite perhaps, or investigate if this function (table_exists) appears in trac now. Much appreciated - but your reference to version info had me look at sqlite release history and find that - 3.4.2 (used) is over four years old now - 3.6.8 (required) was released over two and half years ago - 3.7.4 (tested) fine is going on a year old I'm not really qualified to guess how common such old installations are, but 4+ years makes me wish I hadn't made an assertion about a potential fix to 'many' installations. If I were the only developer (or one of two/three) on a project and this 'issue' came up, I would probably - recommend that the reporter move on with life every other year or so - note a (quite reasonable) 3.6.8+ requirement for sqlite backed environments in the docs - resolve: wontfix - get back to what I was doing before I got pestered That said, I'm not the developer ... just making sure I don't waste yet more of your time by sending you down a rabbit hole for ticket system public relations' sake ... Thanks much again for your time, and yet again for the plugin! Patrick comment:3 Changed 3 years ago by bobbysmith007 - Resolution set to wontfix - Status changed from new to closed You rock! I updated the docs noting the increased sqlite3 version requirement. Thanks for your verifying the fix and for your understanding, I am heading back to what I was doing :) Cheers, Russ Thanks very much for the detailed bug report! I am unclear on how this could occur, but I will definitely look into it further. This should only be rolling back to the save point but... I found a quote on the internet claiming "SAVEPOINT first appeared in SQLITE V 3.6.8" so this is very likely the ultimate cause of the issues. I will look at special casing this function for sqlite perhaps, or investigate if this function (table_exists) appears in trac now. I'm glad you were able to get it working for you on your version of sqlite Cheers, Russ
http://trac-hacks.org/ticket/9250
CC-MAIN-2014-52
refinedweb
729
51.82
499987 An event class with time and date objects Bütçe N/A i need this by sunday 5/22/11 at noon if possible. 1. Create a project which consists of three classes: an Event class, a Time class, and a Date class. 2. The Event class should have data members that are objects of the Time and Date class. STEP 2: the Event and Time Classes 1. the code for the Event and Time classes should include all necessary function and constructor implementation code. STEP 3: Design a Date Class 1. Design a Date class that has three data members to represent the year, month, and day. 2. Date-class member functions should be able to set the date, return the date, print the date, and add a default constructor and a constructor with parameters. STEP 4: Construct Main Method 1. Construct the main method so that it can test the member functions of each of the classes by creating an Event object and then performing the necessary operations to test all possible behavior. This is what i have so far. #include <iostream> #include <string> using namespace std; class Time { //this is a simple time class to demonstrate the use of one //object within another class (composition) public: void setTime(int, int); void getTime(int&, int&); void printTime() const; void incrementMin(); void incrementHrs(); Time(int, int); // constructor with parameters Time(); // the default constructor private: int hour; int minute; }; class Event { publilc: void setEventData(string eventName, int hour, int minute, int month, int day, int year); // this is the prototype of the function to set the data for // the event void printEventData() const; Event(string eventName = 1, int day = 1, int year = 1900); // Constructor private: string eventName; Time eventTime; // the event object is composed of a time object dateType eventDay //and a date object };
https://www.tr.freelancer.com/projects/php-c-programming/event-class-with-time-date/
CC-MAIN-2018-17
refinedweb
304
63.43
Constants in qml files We are using QT creator because a vendor used it and therefore now we are. There are multiple places where the same constants are used over and over again. Having written C and C++ for a long time I want to get rid of those magic numbers and put in constants. So I added a file named constants.qml and populated it with things like: const int MAX_SCREEN_WIDTH = 480; because all the QML stuff looks quite a bit like C code. When I included that in another qml file with: include constants.qml I was not real surprised it did not work. From the QT documents web page searches for "constant" and for "keyword const" were not productive. What is the syntax to use for creating a QML file with a list of constants for all the other QML files to use? That way I can replace all the lines of: width: 480 with width: MAX_SCREEN_WIDTH - mrjj Qt Champions 2016 Hi as far as i know there is not const in QML Javascript has it so maybe you can use that. @BKBK you can make your properties readonly readonly property <propertyType> <propertyName> : <initialValue> Read-only properties must be assigned a value on initialization. After a read-only property is initialized, it no longer possible to give it a value, whether from imperative code or otherwise. on the other hand, I believe one is supposed to do this in a cpp class. Here an quick and dirty example: class GlobalConsts : public QObject{ public: Q_INVOKABLE inline const int &a(){return m_a;} Q_INVOKABLE inline const int &b(){return m_b;} private: const int m_a = 21; const int m_b = 42; } qmlRegisterType<GlobalConsts > ("MyConsts",1,0,"GlobalConsts"); //qml usage import MyConsts 1.0 MyConsts { id: constants } Rectangle{ x: constants.a() y: constants.b() }
https://forum.qt.io/topic/87322/constants-in-qml-files
CC-MAIN-2018-09
refinedweb
301
61.67
Introduction to PySpark to_Date PySpark To_Date is a function in PySpark that is used to convert the String into Date Format in PySpark data model. This to_Date function is used to format a string type column in PySpark into the Date Type column. This is an important and most commonly used method in PySpark as the conversion of date makes the data model easy for data analysis that is based on date format. This to_Date method takes up the column value as the input function and the pattern of the date is then decided as the second argument which converts the date to the first argument. The converted column is of the type pyspark.sql.types.DateType . In this article, we will try to analyze the various ways of using the PYSPARK To_Date operation PySpark. Syntax: The syntax for PySpark To_date function is: from pyspark.sql.functions import * df2 = df1.select(to_date(df1.timestamp).alias('to_Date')) df.show() The import function in PySpark is used to import the function needed for conversion. - Df1:- The data frame to be used for conversion - To_date:- The to date function taking the column value as the input parameter with alias value as the new column name. - Df2:- The new data frame selected after conversion. Screenshot: Working of To_Date in PySpark Let’s check the creation and working of PySpark To_Date with some coding examples. Examples() Output: df1.show() Screenshot: Now we will try to convert the timestamp column using the to_date function in the data frame. We will start by importing the required functions from it. from pyspark.sql.functions import * This will import the necessary function out of it that will be used for conversion. df1.select(to_date(df1.timestamp).alias('to_Date')) We will start by selecting the column value that needs to be converted into date column value. Here the df1.timestamp function will be used for conversion. This will return a new data frame with the alias value used. Screenshot: df1.select(to_date(df1.timestamp).alias('to_Date')).collect() We will try to collect the data frame and check the converted date column. [Row(to_Date=datetime.date(2021, 7, 24)), Row(to_Date=datetime.date(2019, 7, 22)), Row(to_Date=datetime.date(2021, 7, 25))] We will try to store the converted data frame into a new data frame and will analyze the result out of it. df2 = df1.select(to_date(df1.timestamp).alias('to_Date')) This will convert the column value to date function and the result is stored in the new data frame. which can be further used for data analysis. df2.show() Let us try to check this with one more example giving the format of the date before conversion. df = spark.createDataFrame([('2021-07-19 11:30:00',)], ['date']) This is used for creation of Date frame that has a column value as a date which we will use for conversion in which we can pass the format that can be used for conversion purposes. df.select(to_date(df.date, 'yyyy-MM-dd HH:mm:ss').alias('date')).collect() This converts the given format into To_Date and collected as result. Screenshot: This to date function can also be used with PySpark SQL function using the to_Date function in the PySpark. We just need to pass this function and the conversion is done. spark.sql("select to_date('03-02-2021','MM-dd-yyyy') converted_date").show() This is the converted date used that can be used and this gives up the idea of how this to_date function can be used using the Spark.sql function. Screenshot: spark.sql("select to_date('2021-04-03','yyyy-dd-MM') converted_date").show() The format can be given the way we want and we can use it for further conversion purposes. Screenshot: These are some of the Examples of PySpark to_Date in PySpark. Note: 1. It is used to convert the string function into Date. 2. It takes the format as an argument provided. 3. It accurately considers the date of data by which it changes up that is used precisely for data analysis. 4. It takes date frame column as a parameter for conversion. Conclusion From the above article, we saw the working of TO_DATE in PySpark. From various example and classification, we tried to understand how this TO_DATE FUNCTION ARE USED in PySpark and what are is used in the programming level. The various methods used showed how it eases the pattern for data analysis and a cost-efficient model for the same. We also saw the internal working and the advantages of TO_DATE in PySpark Date Frame and its usage for various programming purposes. And also, the syntax and examples helped us to understand much precisely the function. Recommended Articles This is a guide to PySpark to_Date. Here we discuss the Introduction, How PySpark To_Date works in PySpark? and examples respectively. You may also have a look at the following articles to learn more –
https://www.educba.com/pyspark-to_date/?source=leftnav
CC-MAIN-2021-43
refinedweb
820
56.55
I'm commenting a bit between the paragraphs to sharpen my mind :) On Wed, Nov 04, 2009 at 08:09:18PM +0100, Stefano Zacchiroli wrote: > What I was aiming to is a kind of document root which is under full > control of the package manager; hence where the sysadm cannot touch > anything by hand. That's actually the only way to have a meaningful > package-based namespace. I agree. The files installed by the package manager must be seperated from user/admin files. > The property I'd like is that if a package drops static files there > under a dir like package/, then those files automagically appear (in the > default vhost) as. That would mean dropping all files in whatever dir is configured (in all available web servers) as DocRoot. > Now, written this way, it looks harder to implement, because it is a > kind of overlay over a default docroot (unless we assume the default > docroot is read-only for the sysadm, which doesn't look reasonable). Right, either the admin can (and will) write to the DocRoot (which was meant to be reserved for the package manager), or we need two DocRoots configured which I don't think is possible with common web servers. > I see two solution to this: > > - either the final URL is something like > (replace "debian" with whatever > prefix you like) and have some other per-web-server mechanism take > care of adding an Alias/link/whatever from "debian" to that new static > doc root Like all packages drop their files in /var/lib/www/package and some default package (or the web server itself) drops a symlink /var/www/debian -> /var/lib/www ? This would again lead to at least one file name in the sysadmin's space that he/she can't use which is what we try to avoid in the first place. > - or we add some kind of postinst-time registration mechanism (with all > the usual drawbacks) that check that new static doc root and register > every (new) dir there as Alias for the installed web servers. That is basically what happens today in many cases, except that the files aren't dropped in one location but rather in /var/cache/$package or similar. The package's postinst registers the new files/dirs with the web servers (usually just apache2 and/or lighttpd). > Assuming that web servers can register themselves to the mechanism, > that would also solve the problem that webapp maintainers not > necessarily have the knowledge of the syntax of all available web > servers You mean like a trigger that is dealt with by any web server installed? > Any other idea? Actually, I don't see a way to implement that (but then I'm probably not the best code writer). It would be really nice if the web servers could somehow register themselves for this but I think in the end this is really what webapps-common was aimed at, isn't it? Except the. So, after all I think we need some manpower in webapps-common and we have a solution. Or not? > Many thanks for sharpening the analysis, Jan. You're welcome, although I prefer to be called Hauke. I'm a middle-name-user ;) > PS please keep the -webapps Cc:, I believe it is truly relevant to > this thread Ack, sorry for dropping it before. Hauke Attachment: signature.asc Description: Digital signature
https://lists.debian.org/debian-devel/2009/11/msg00221.html
CC-MAIN-2015-27
refinedweb
565
55.78
Grady Booch’s 1994 Book Object Oriented Analysis and Design, which I first read in the summer of 1995 defines an object’s state in the following way: The state of an object encompasses all of the (usually static) properties of the object plus the current (usually dynamic) values of each of these properties. He defines the difference between static state and dynamic state using a vending machine example. Static state is exhibited by the way that the machine is always ready to take your money, whilst dynamic state is how much of your money it’s got at any given instance. I suspect that at this point, you’ll quite rightly argue that explicit behavioural tests do test an object’s state by virtue of the fact that a given method call returned the correct result and that to get the correct result the object’s state had to also be correct… and I’ll agree. There are, however, those very few cases where classic behavioural testing isn’t applicable. This occurs when a public method call has no output and does nothing to an object except change its state. An example of this would be a method that returned void or a constructor. For example, given a method with the following signature: public void init(); …how do you ensure it’s done its job? It turns out that there are several methods you can use to achieve this… - Add lots of getter methods to your class. This is not a particularly good idea, as you’re simply loosening encapsulation by the back door. - Relax encapsulation: make private instance variables package private. A very debatable thing to do. You could pragmatically argue that having well tested, correct and reliable code may be better than having a high degree of encapsulation, but I’m not too sure here. This may be a short term fix, but could lead to all kinds of problems in the future and there should be a way of writing well tested, correct and reliable code that doesn’t include breaking an object’s encapsulation - Write some code that uses reflection to access an object’s internal state. This is the best idea to date. The down side is that it’s a fair amount of effort and requires a reasonable amount of programming competence. - Use PowerMock’s Whitebox testing class to do the hard work for you. The following fully contrived scenario demonstrates the use of PowerMock’s Whitebox class. It takes a very simple AnchorTag <a> class that will build an anchor tag after testing that an input URL string is valid. public class AnchorTag { private static final Logger logger = LoggerFactory.getLogger(AnchorTag.class); /** Use the regex to figure out if the argument is a URL */ private final Pattern pattern = Pattern.compile("^([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}$"); /** * A public method that uses the private method */ public String getTag(String url, String description) { validate(url, description); String anchor = createNewTag(url, description); logger.info("This is the new tag: " + anchor); return "The tag is okay"; } /** * A private method that's used internally, but is complex enough to require testing in its own right */ private void validate(String url, String description) { Matcher m = pattern.matcher(url); if (!m.matches()) { throw new IllegalArgumentException(); } } private String createNewTag(String url, String description) { return "<a href=\"" + url + "\">" + description + "</a>"; } } The URL validation test is done using a regular expression and a Java Pattern object. Using the Whitebox class will ensure that the pattern object is configured correctly and that our AnchorTag is in the correct state. This demonstrated by the JUnit test below: /** * Works for private instance vars. Does not work for static vars. */ @Test public void accessPrivateInstanceVarTest() throws Exception { Pattern result = Whitebox.<pattern> getInternalState(instance, "pattern"); logger.info("Broke encapsulation to get hold of state: " + result.pattern()); assertEquals("^([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}$", result.pattern()); } The crux of this test is the line: Pattern result = Whitebox.<pattern> getInternalState(instance, "pattern"); …which uses reflection to return the Pattern object private instance variable. Once we have access to this object, we simply ask it if it has been initialised correctly be calling: assertEquals("^([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}$", result.pattern()); In conclusion I would suggest that using PowerMock to explicitly test an object’s internal state should be used only when you can’t use straight forward classic JUnit test for behavioural testing. Having said that, it is another tool in your toolbox that’ll help you to write better code. Reference: Testing an Object’s Internal State with PowerMock from our JCG partner Roger at Captain Debug’s Blog.
http://www.javacodegeeks.com/2011/10/testing-objects-internal-state-with.html
CC-MAIN-2014-15
refinedweb
810
51.58
Just to clarify, the deepFace is not part of the library. I wonder if it can detect a face on it? Let’s try that (the below code is not part of the official tutorial). If you need help to install the deepFace library read this tutorial. from deepface import DeepFace result = DeepFace.analyze("deepFaceLogo.png", actions=['age', 'gender', 'race', 'emotion']) print(result) Where we have the deepFaceLogo.png to be the following image. ValueError: Face could not be detected. Please confirm that the picture is a face photo or consider to set enforce_detection param to False. Bummer. The deepFace library cannot detect a face in it’s logo. Well, back on track. Find a collection of movie stars and save them in a folder. A modern face recognition pipeline consists of 4 common stages: detect, align, represent and verify. DeepFacehandles all these common stages in the background. A normal process would first identify where in the picture a face is located (the detect stage). This is needed to remove all unnecessary background in the image and only focus on the face. Then it would proceed to align it, so the eyes in the head are in a horizontal line (the align stage). That is, the head is not tilting to one side. This makes the face recognition algorithm work better as all faces will have the same alignment. Further, we will change the representation of the image (the aligned face part) in the model. Finally, verify if the distance is close. That is, the smaller distance from the image, the more we are certain it is the right person. Let’s take a simple example. Let’s compare if I am Angelina Jolie. (If you need help to install the deepFace library read this tutorial). from deepface import DeepFace result = DeepFace.verify("rune.jpg", "pics-db/Angelina Jolie.jpg", model_name="VGG-Face") print(result) I have added the picture of me (rune.jpg) in the folder where I run my Python program and a pics-db with a picture of Angelina Jolie. And the result looks like this. { 'verified': False, 'distance': 0.7834609150886536, 'max_threshold_to_verify': 0.4, 'model': 'VGG-Face', 'similarity_metric': 'cosine' } The algorithm has determined that I am not Angelina Jolie (‘verified’: False). Now to the interesting part, it has a distance (‘distance’: 0.7834609150886536), which we will use to determine which movie star you look the most like. Here it is important to understand, that the lower the distance, the more you look-alike. Also, you see that the maximum threshold to verify is 0.4. That is the distance should be less than 0.4 to conclude that it is the same person in the picture. We have collected a library of images and located them in pics-db. Then I try with a picture of me (the same one I used in last step). (If you need help to install the deepFace library read this tutorial). from deepface import DeepFace import glob pic = "rune.jpeg" files = glob.glob("pics-db/*") model = "VGG-Face" results = [] for file in files: result = DeepFace.verify(pic, file, model_name=model) results.append((file, result['distance'])) results.sort(key=lambda x: x[1]) print("Model:", model) for file, distance in results: print(file, distance) Now I am a bit nervous, which one do I look the most like? Model: VGG-Face pics-db/Tom Cruise.jpg 0.4702601432800293 pics-db/The Rock.jpg 0.493824303150177 pics-db/Robert Downey Jr.jpg 0.4991753101348877 pics-db/Daniel Craig.jpg 0.5135003626346588 pics-db/Christian Bale.jpg 0.5176380276679993 pics-db/Brad Pitt.jpg 0.5225759446620941 pics-db/Will Smith.jpg 0.5245362818241119 pics-db/Michael Douglas.png 0.5407796204090118 pics-db/Keanu Reeves.jpg 0.5416552424430847 pics-db/Angelina Jolie.jpg 0.7834609150886536 Wow. I like this immediately. Tom Cruise, The Rock, Robert Downey Jr. Luckily, I look the least like Angelina Jolie, which is not that surprising (At least I would think so). Maybe, it depends. I guess you can make an App or Web-service with a movie star look-alike algorithm. You can also play around with different models. The deepFace library contains the following: “VGG-Face”, “Facenet”, “OpenFace”, “DeepFace”, “DeepID”, and “Dlib”. The results are not the same. Model: Facenet pics-db/Tom Cruise.jpg 0.7826492786407471 pics-db/Brad Pitt.jpg 0.870269775390625 pics-db/The Rock.jpg 0.8774074390530586 pics-db/Keanu Reeves.jpg 0.9102083444595337 pics-db/Daniel Craig.jpg 0.914682649075985 pics-db/Christian Bale.jpg 0.9467008262872696 pics-db/Robert Downey Jr.jpg 1.0119212558493018 pics-db/Angelina Jolie.jpg 1.0243268758058548 pics-db/Michael Douglas.png 1.067187249660492 pics-db/Will Smith.jpg 1.2313244044780731 The Facenet model says I look less like Will Smith and more like Angelina Jolie. Not sure I trust this one. If you enjoy this I recommend you read the following tutorial by the author of deepface Sefik Ilkin Serengil.
https://www.learnpythonwithrune.org/deepface-python-create-a-look-alike-algorithm/
CC-MAIN-2021-25
refinedweb
822
71
Although ADO.NET and ADO share some common concepts, they are different enough in many areas to give you fits when you first start working with the new .NET database access libraries. The first step in understanding how to use ADO.NET lies in understanding what you’ll find in each of its constituent namespaces: - System.Data.SqlClient contains the classes needed to connect to a SQL Server data source. - System.Data.OleDb is used for connecting to OLE-DB data sources. - System.Data.Common holds common classes that serve as bases for provider-specific classes. - System.Data contains a large set of provider-independent classes useful for high-level access to data. - System.Data.SqlTypes provides classes useful for converting .NET data types to and from SQL Server native data types. Which connection class should you use? As you just saw, there are two sets of connection classes in .NET, those found in the SqlClient and OleDb namespaces. What’s the difference? The SqlClient classes use the native SQL Server drivers to access a database, while the OleDb classes use the generic OLE-DB interface. When using SQL Server as a back end, the SqlClient classes will have a performance advantage over their more generalized OLE-DB cousins, so you should use the former for connecting to SQL Server. For simplicity’s sake, I’ll assume you will be using SQL Server for the remainder of this article. However, the classes I’ll be discussing will also apply for an OLE-DB back end, so you’re welcome to stick around if you have a different database back end. You’ll need to substitute equivalent OleDb classes for the SqlClient classes, and you’ll likely need to tinker with the connection string, but the sample code should work for you as well. Using connections in ADO.NET Like ADO before it, ADO.NET depends on connection objects to represent open data sources. However, connections in ADO.NET are different from those you’ll find in ADO. I’ve already touched on one significant difference: There are specialized connection classes for certain data sources, which allow vendors to create specialized connection classes that use their databases' native interfaces to provide extra functionality or a speed boost over the OleDb classes. I don’t have space here to cover all the differences, but check out the MSDN Web site for more information. The .NET Framework’s specialized SQL Server connection class uses System.Data.SqlClient.SqlConnection, so to connect to a SQL Server database, you’d create an instance of SqlConnection. When creating a connection object, you have the option of specifying the connection string when you call the constructor, or you can stick to the old methods of setting the connection string via the ConnectionString property. You cannot pass the string to the Open method, however, so don’t go trying that. Getting the connection string right Getting a connection string put together for your data provider can sometimes be the most challenging aspect of opening a connection. If you get into trouble, a good starting point is to use the Server Explorer in VS.NET to build the connection string, and then copy and paste it into your code. To connect to the NWIND database on a SQL Server named SomeServer, I’d use the following code: SqlConnection cn = new SqlConnection("Data Source=SomeServer; Initial Catalog=NWIND; Integrated Security=true;"); cn.Open(); Note that if your SQL Server does not use domain security, you’ll need to specify user ID and password elements, and remove the Integrated Security statement from the connection string. Working with commands After opening a connection, you can use one of the provider-specific command objects to execute commands on the connection. Commands are abstract representations of the SQL statements you use to work with data in a database. I don’t have space here for an introduction to SQL, but I will recommend the Builder.com SQL basics series if you’re new to SQL. SqlCommand is the SQL Server specific command object, and you can specify a T-SQL statement, or the name of a stored procedure, for the command to represent by either passing it as a constructor parameter or using the CommandText property. Extending my above example, if you wanted to retrieve the names of all the employees living in the US from the NWIND database’s Employees table, you’d use the following code to create your command: SqlCommand cmd = new SqlCommand("SELECT * FROM Employees WHERE Country = 'USA';", cn); cmd.CommandType = CommandType.Text; What kind of command is this? A good tip from ADO that still applies to ADO.NET is to always specify the type of the command, using the CommandType property, assuming that you know it. The System.Data.CommandType enumeration provides a list of all available commands. You can also execute action query statements using a command object. Simply specify the SQL statement in the constructor as you would a SELECT statement, and then invoke the ExecuteNonQuery method. For example, to remove the employee with an EmployeeID of 9, you’d use the following code: SqlCommand del = new SqlCommand(“DELETE * FROM Employees WHERE EmployeeID = 9”); del.ExecuteNonQuery(); To execute a scalar command—a command that returns a single value rather than a row of data—you’d use the ExecuteScalar method instead. If you wanted to know the number of records left in Employees after deleting the record in the last example, you could use the following code: SqlCommand count = new SqlCommand(“SELECT count(*) as EmpCount FROM Employees;”); int icount = (int) count.ExecuteScalar(); Retrieving data: Data readers You have connections and commands, but here’s where the similarities with ADO largely end. There is no RecordSet object in ADO.NET. Instead, you have several ways of obtaining data. The simplest is to use a data reader object. Data readers provide forward-only, stream-based access to the rows returned by a SQL statement or a stored procedure. Both SqlClient and OleDbClient have their own, private, implementations of data reader objects: SqlDataReader and OleDbDataReader, respectively. These two reader classes do not have a common class ancestor above System.Object, so they are not compatible with one another. Data readers are very fast, but they aren’t very structured. You retrieve data from them using the ordinal number of the column in the data returned by the command object. They aren’t type aware either, so you need to specify the type of data you are retrieving by calling a particular GetXXX method. For example, to retrieve the name (a string) and date of birth (DateTime) from all employees returned in the above example, you’d write the following: SqlDataReader rdr = cmd.ExecuteReader(); while(rdr.Read()) Console.WriteLine("Name: {0}, {1} DOB: {2}", rdr.GetString(1), rdr.GetString(2), rdr.GetDateTime(5)); Getting fancy: Retrieving XML data A rather neat feature of ADO.NET is the ability to work with data from a database as if it were an XML stream. The ExecuteXmlReader method returns a System.Xml.XmlReader object you can use to read the data returned from the command as if it were an XML document. I won’t go into the details of using XmlReader here, but I will suggest that you read “Learn to read and write XML with .NET’s XML classes” if you are unfamiliar with XmlReader. More to come… From my explanations, you should now have a working understanding of ADO.NET’s low-level data access classes and how to use them to manipulate data from a data source. In a future article, I’ll introduce the higher-level, provider-agnostic denizens of System.Data, and show you how to use them in a connected application.
http://www.techrepublic.com/article/adonet-database-access-made-easy/
CC-MAIN-2017-09
refinedweb
1,295
54.83
Thor is yet another Python 3 library for evented IO. There are many such libraries for Python already available. Thor focuses on making it easy to build high-performance HTTP intermediaries like proxies, load balancers, content transformation engines and service aggregators. Of course, you can use it just as a client or server too. It aims to be as fast as possible, to implement the protocols correctly, and to be simple. You can help meet these goals by contributing issues, patches and tests. Thor’s EventEmitter API is influenced by^H^H^H copied from NodeJS; if you’re familiar with Node, it shouldn’t be too hard to use Thor. However, Thor is nothing like Twisted; this is considered a feature. Currently, Thor has an event loop as well as TCP, UDP and HTTP APIs (client and server). New APIs (e.g., DNS) and capabilities should be arriving soon, along with a framework for intermediation. Thor just requires Python 3.5 or greater. Currently, it will run on most Posix platforms; specifically, those that offer one of poll, epoll or kqueue. If you have setuptools, you can install from the repository: easy_install thor or using pip: pip install thor On some operating systems, that might be pip3. Otherwise, download a tarball and install using: python setup.py install The documentation is a good starting point; see also the docstrings for the various modules, as well as the tests, to give an idea of how to use Thor. For example, a very simple HTTP server looks like this: import thor def test_handler(exch): def request_start(*args): exch.response_start(200, "OK", [('Content-Type', 'text/plain')]) exch.response_body('Hello, world!') exch.response_done([]) if __name__ == "__main__": demo_server = thor.HttpServer('127.0.0.1', 8000) demo_server.on('exchange', test_handler) thor.run() See Thor's GitHub to give feedback, view and report issues, and contribute code. All helpful input is welcome, particularly code contributions via a pull request (with test cases). Thor is not only “a hammer-wielding god associated with thunder, lightning, storms, oak trees, strength, destruction, fertility, healing, and the protection of mankind”, he’s also my Norwegian Forest Cat. Thor (the software program) grew out of nbhttp, which itself came from earlier work on evented Python in redbot. Thor (the cat) now rules our house with a firm but benevolent paw. He gets sick if we give him any milk, though.
https://openbase.com/python/thor
CC-MAIN-2021-43
refinedweb
399
66.54
Returning now to the subject we started discussing last time on FAIC: sometimes the compiler can know via static analysis[1. That is, analysis done knowing only the compile-time types of expressions, rather than knowing their possibly more specific run-time types] that an is operator expression is guaranteed to produce a particular result. But before we get into that, let’s briefly review the meaning of is in C#. The expression x is T for an expression x and a type T produces a bool. Generally speaking, if there is a reference, boxing or unboxing conversion from the runtime value of x to the type T then the result is true, otherwise the result is false. Note that in particular user-defined conversions are not considered. The intention of the operator is to determine if the runtime value of x is actually a useful value of the type T,[2. It is not to determine “is there any way to associate a value of type T with this value?” or “can the value x be legally assigned to a variable of type T?”] and therefore we add a few additional caveats: Tmay not be a pointer type xmay not be a lambda or anonymous method - if xis classified as a method group or is the null literal[3. There are some small spec holes here and around these holes are minor inconsistencies between the C# 5 compiler and Roslyn. The spec does not say what to do if the expression xis a namespace or a type; those are of course valid expressions. The compiler produces an error stating that an expression with a value is expected. Similarly for write-only properties and write-only indexers. The original-recipe C# 5 compiler produces an error if the expression is a void-returning call, which technically is a spec violation; Roslyn produces a warning, though frankly, I’d be more inclined to change the spec in this case. The specification does say that x is Tis an error if Tis a static type; the C# 5 compiler erroneously allows this and produces false whereas the Roslyn compiler produces an error.] then the result is false - if the runtime type of xis a reference type and its value is a null reference then the result is false - if the runtime type of xis a nullable value type and the HasValueproperty of its value is false then the result is false - if the runtime type of xis a nullable value type and the HasValueproperty of its value is true then the result is computed as though you typed x.Value is T So, knowing that, try to think of some situations in which you know for certain that x is T is going to always produce true, or always produce false. Here are a few that you and I know are always true: int i = 123; bool b1 = i is int; bool b2 = i is IComparable; bool b3 = i is object; bool b4 = "hello" is string; Here in every case we know first, that the operand is not null, and second, that the operand will always be of the given type, and therefore the operator will always produce “true”. Before we go on, I want to briefly review our criteria for when to make a warning:. There are a lot more situations where you know that the result will always be false. Can you think of some? Here are just a few off the top of my head: bool b5 = M is Func<object>; // M is a method group bool b6 = null is object; bool b7 = b5 is IEnumerable; bool b8 = E.Blah is uint; // E is an enum type bool b9 = i is double; The first two follow the rules of the spec. The latter three are cases where we can know via static analysis that the value cannot possibly be converted to the given type by a reference, boxing or unboxing conversion. The compiler produces a warning for all these trivially-analyzed cases. (Though of course again some of these examples — b6 in particular — are unlikely to show up in real code.) cannot possibly be true as a result. There are lots of cases where you and I know that a given expression will never be of a given type, but these cases can get quite complex. Let’s look at three complex ones: class C<T> {} ... static bool M10<X>(X x) where X : struct { return x is string; } static bool M11<X>(C<X> cx) where X : struct { return cx is C<string>; } static bool M12<X>(Dictionary<int, int> d) { return d is List<X>; } In case M10 we know that X will always be a value type and no value type is convertible to string via a reference, boxing or unboxing conversion. The type check must be false.. In case M12 we know that there is no way to make an object that inherits from both the dictionary and list base classes, no matter what X is. The type check must be false. In all these cases the compiler could produce a warning, but we are rapidly running up against the “possible to implement cheaply” criterion! The compiler team could spend a lot of expensive time coming up with heuristics which would not make a difference to real users writing real code. They have to draw the line somewhere. Where is that line? The heuristic the compiler team actually uses to determine whether or not to report a warning when the compiler detects that there is no compile-time conversion from x to T is as follows: - If neither the compile time type of xnor the type Tis an open type (that is, a type that involves generic type parameters) then we know that the result will always be false. There’s no conversion, and nothing to substitute at runtime to make there be a conversion. Give a warning. - One of the types is open. If the compile time type of xis a value type and Tis a class type then we know that the result will always be false.[4. This is a lie; there is one case where the compile time type of xis an open value type and Tis a class type, and there is no compile-time conversion from xto T, and x is Tcan be true, and therefore the warning must be suppressed. Can you write a program that demonstrates this scenario? I’ll put the answer in the comments.] (This is case M10above.) Give a warning. - Otherwise, abandon further analysis and do not produce a warning. This is far from perfect, but it is definitely in the “good enough” bucket. And “good enough” is, by definition, good enough. Of course, this heuristic is subject to change without notice, should the compiler team discover that some real user-impacting scenario motivates changing it. Next time on FAIC: How does the compiler ensure that the method type inference algorithm terminates? The answer to the puzzle in the footnote is: Wow that was unusual. I just wrote an extremely long comment but after I clicked submit my comment didn’t appear. Grrrr… well I’m not writing all that over again. Anyways, just wanted to say excellent blog! Nice weblog here! Also your web site rather a lot up very fast! What host are you the use of? Can I get your associate link on your host? I wish my site loaded up as fast as yours lol
https://ericlippert.com/2012/09/12/static-analysis-of-is/
CC-MAIN-2017-43
refinedweb
1,255
68.4
from mojo.drawingTools import * Using similar tools to draw in Cocoa object like DrawBot. (see TinyDrawBot extension) - save() save the current graphic state - restore() restore the current graphic state - rect(x, y, width, height) draws a rectangle - oval(x, y, width, height) draws an oval - newPath() creates a new path - moveTo((x, y)) move to point - lineTo((x, y)) line to point - curveTo((h1x, h1y), (h2x, h2y), (x, y)) curve to point with bcps - closePath() close the path - drawPath() draws the path - fill(r, g, b, a=1) Set the fill color as RGB value. - stroke(r, g, b, a=1) Set the stroke color as RGB value. - strokeWidth(value) Set the stroke width for a path. - miterLimit(value) Set the miter limit for a path. - lineJoin(join) Set the line join for a path, possible join arguments are: "bevel", "miter" or "round" - dashLine(dash) dash is a list of of values - translate(x, y) Translate the art board pane to "x", "y" - rotate(angle) Rotate the art board by an angle. - scale(x, y) Scale the art board by "x", "y", if "y" is not set the art board will be scaled proportionally. - skew(a, b) Skew the art board by "a", "b", if "b" is not set the art board will be skew with "a" = "b" - font(fontName, fontSize=None) Set the font by PostScript name. Optionally set the font size. - fontSize(fontSize) Set the font size. - text(textString, (x, y)) Draw a text on position "x", "y". - image(filePath, (x, y), alpha=1) Draw an image on position "x", "y". Optionally set an alpha value.
http://doc.robofont.com/api/mojo/mojo-drawingtools/
CC-MAIN-2017-13
refinedweb
268
69.31
I have started to code. It is one thing that I am wondering. Look at this simple code: public class Trabant_4 { public static void main(String[] args) { System.out.print("Enter amount of fuel:\n"); double tal1 = Keyboard.readDouble(); System.out.println("Enter amount of kilometers: "); double tal2 = Keyboard.readDouble(); System.out.println("Please, hold..."); double tal3 = (tal1/tal2)*10; System.out.println("Fuel consumtion is\n\n" + tal3 + "\n\nliter per kilometer"); } } Now, I have seen that sometimes it says ...(String[] args)...but also ...(String[] arguments).... My question is, make it any difference if I write 'args' or 'arguments'? Me personally prefer to write out everything, at least as I am beginning to learn to write code. Thank you for looking at my thread. WinkyCode
http://www.dreamincode.net/forums/topic/331790-args-or-arguments-is-it-any-difference/
CC-MAIN-2017-51
refinedweb
126
52.46
Home Information Classes Download Usage Mail List Requirements Links FAQ Tutorial STK "singing" looped soundfile class. More... #include <SingWave.h> STK "singing" looped soundfile class. This class loops a specified soundfile and modulates it both periodically and randomly to produce a pitched musical sound, like a simple voice or violin. In general, it is not be used alone because of "munchkinification" effects from pitch shifting. Within STK, it is used as an excitation source for other instruments. by Perry R. Cook and Gary P. Scavone, 1995–2017. Class constructor taking filename argument. An StkError will be thrown if the file is not found, its format is unknown, or a read error occurs. If the soundfile has no header, the second argument should be true and the file data will be assumed to consist of 16-bit signed integers in big-endian byte order at a sample rate of 22050 Hz..
https://ccrma.stanford.edu/software/stk/classstk_1_1SingWave.html
CC-MAIN-2018-05
refinedweb
150
65.12
$ cc -v FreeBSD clang version 7.0.0 (branches/release_70 338892) (based on LLVM 7.0.0svn) Target: x86_64-unknown-freebsd12.0 Thread model: posix $ make [...] In file included from Source/kwsys/SystemTools.cxx:23: In file included from Source/cmsys/FStream.hxx:10: In file included from /usr/include/c++/v1/fstream:184: In file included from /usr/include/c++/v1/ostream:138: In file included from /usr/include/c++/v1/ios:216: In file included from /usr/include/c++/v1/__locale:18: In file included from /usr/include/c++/v1/mutex:191: In file included from /usr/include/c++/v1/__mutex_base:15: In file included from /usr/include/c++/v1/chrono:795: /usr/include/c++/v1/ctime:77:9: error: no member named 'timespec_get' in the global namespace; did you mean 'timespec'? using ::timespec_get; ~~^ /usr/include/sys/_timespec.h:46:8: note: 'timespec' declared here struct timespec { ^ build log: <ctime> in -std=c++17 was broken by Created attachment 195942 [details] workaround Looks like C11 timespec_get() isn't implemented on FreeBSD unlike DragonFly or NetBSD. I'm committing a timespec_get() to -current shortly. What's the plan for /stable/11? MFC timespec_get(), land the workaround or freeze libc++ (breaking promise in bug 215193) ? (In reply to Jan Beich from comment #4) > What's the plan for /stable/11? MFC timespec_get(), land the workaround or > freeze libc++ (breaking promise in bug 215193) ? I think timespec_get() is probably fine to MFC, but I'll leave it up to Warner. :) A commit references this bug: Author: dim Date: Fri Aug 10 21:40:28 UTC 2018 New revision: 337593 URL: Log: Upstream libc++ added a using ::timespec_get line, when in C++17 or higher mode, in <>. Since we do not yet have this C11 function, comment out the line for now, as a workaround for a number of failing ports. Discussion with upstream is ongoing about an acceptable permanent fix. PR: 230400 Reported by: jbeich Changes: projects/clang700-import/contrib/libc++/include/ctime As of FreeBSD_version 1200077 we have this function, if that helps anybody... A commit references this bug: Author: dim Date: Sat Aug 11 20:08:26 UTC 2018 New revision: 337654 URL: Log: Undo r337593 (commenting out of timespec_get in libc++'s <ctime> header), now that r337576 added that function. PR: 230400 Changes: projects/clang700-import/contrib/libc++/include/ctime This should now be fixed, please retry those builds. Confirmed, builds fine now.
https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=230400
CC-MAIN-2019-47
refinedweb
405
56.96
Most of the components provided in this project need to know the namespace. For Kubernetes (1.3+) the namespace is made available to pod as part of the service account secret and automatically detected by the client. For earlier version it needs to be specified as an env var to the pod. A quick way to do this is: env: - name: "KUBERNETES_NAMESPACE" valueFrom: fieldRef: fieldPath: "metadata.namespace" For distros of Kubernetes that support more fine-grained role-based access within the cluster, you need to make sure a pod that runs with spring-cloud-kubernetes has access to the Kubernetes API. For any service accounts you assign to a deployment/pod, you need to make sure it has the correct roles. For example, you can add cluster-reader permissions to your default service account depending on the project you’re in:
https://cloud.spring.io/spring-cloud-static/Greenwich.RELEASE/multi/multi__security_configurations_inside_kubernetes.html
CC-MAIN-2019-18
refinedweb
141
63.19
test 1 study notes Flashcard maker : Lily Taylor 1. One drawback of socialism is that it may result in a reduction in the individual’s incentive to work hard. True 2. Global economics and politics have no significant influence on businesses in the United States. false 3. Sarah owns a bakery that specializes in cupcakes. Until recently, she charged a price of $5 for each treat. At this price Sarah’s customers bought an average of 384 cupcakes each week. For the last few weeks, she has reduced her price to $3.95 per cake, and her customers have purchased an average of 596 cupcakes each week. These results are consistent with the economic concept of demand. true 4. In recent years, U.S. manufacturing sector has experienced ___________ productivity. rising 5. In socialist economies, the government owns some, if not most, basic businesses such as telecommunications systems and utilities true A free market is one in which decisions about what to produce and in what quantities are made by: the market If a shortage exists for a good in a free-market economy, the: price of the good will rise Demand refers to the quantity of a good that consumers are willing and able to buy at different prices at a specific time. true Adam Smith believed the self-interest of business people would lead them to create needed goods, services, and jobs. true In a mixed economy, the government’s goal is to grow the economy and maintain some measure of social equality. true Fiscal policy involves increases or decreases in: government spending and taxes Inflation refers to the persistent rise in the purchasing power of money. false Monica notices that just a few big companies produce the vast majority of soft drinks. She would be correct in describing the soft drink industry as an oligopoly. true An economy is said to be in a recession if GDP declines for two or more consecutive quarters. true An oligopoly is a market that is characterized by: a few large sellers who dominate the market A command economic system is characterized by: reliance of the government to determine what is produced and who gets the output. At the equilibrium price, the quantity consumers desire to buy equals the quantity sellers desire to sell. true In a free-market economic system, the mechanism of __________ is the key determinant used to signal to producers what to produce and how much to produce. price Governments that were predominantly capitalist are moving toward socialism, while governments that were predominantly socialist are moving toward capitalism. true Keynesian economic theory suggests: short-term increases in government spending to stimulate the economy. A simple supply curve shows a relationship between the: price of a good and the quantity of that good sellers are willing to offer for sale at a specific point in time.. cpi Efforts by the Federal Reserve Bank (the Fed) to control the money supply and interest rates are known as: monetary policy One of the greatest concerns associated with capitalism is that: some business people may let greed guide their behavior Like most nations, the United States has a mixed economy. true Emerson, Inc., reported that it owns and operates 265 companies worldwide with 23% of its sales coming from Europe, 18% from Asia, 46% from the U.S., and 13% from other parts of the world. Clearly, Emerson exemplifies ______________. a multinational coroporation Denmark requires foreign companies that sell butter in Denmark to sell it in cubes, not tubs. This type of requirement is known as a: non tariff barrier Current trade data indicates that the nation of Bogusland exports more to other nations than it imports. Bogusland has: a trade surplus. Granting a foreign company the right to manufacture your product or to use your firm’s trademark in return for a fee is called: licensing In order to level the playing field in trade between the U.S. and China, U.S. policymakers have called upon China’s government to allow the yuan to float freely, as other world currencies. Through government regulation, China maintains an undervalued currency, which results in: maintaining robust Chinese exports and a favorable balance of trade for China. A sociological challenge that must be overcome in order to be successful in the global market is: a lack of cultural understanding. As the most powerful economy in the world, the United States does not need to concern itself with having an unfavorable balance of payments. False As a business strategy, the strategy behind “dumping” is to __________. gain a foothold in a new market A devaluation of the U.S. dollar would make American goods cheaper to foreign buyers. true A free-trade agreement is likely to result in: an increase in imported goods and services. In an effort to protect domestic jobs, some countries will place a limit on the number of certain types of products that can be imported. These limits are called: import quotas. An example of foreign direct investment would be Pepsi granting a Japanese firm the use of its formula and trademark, for a fee. false An example of a U.S. import would be the purchase of oil by U.S. companies from Saudi Arabia. true Free trade is the movement of goods and services between nations without political or economic barriers. true A form of foreign direct investment, where a domestic company purchases a company in a foreign country to produce a similar product or service, is a: foreign subsidiary. Export trading companies: connect sellers in the U.S. with buyers in other nations, and help with customs, documentation and payments. From a sociocultural perspective, U.S. business people are often accused of ethnocentricity. true Companies may have several reasons for creating joint ventures. Which of the following statements is one reason why firms may decide to form a joint venture? They will save time to market if they pool their technological know-how. A __________ is a partnership in which two or more companies (often from different countries) join together and share the risk and costs in order to undertake a major project. joint venture An influential foreign government official approaches your firm requesting a large sum of money. In return for this bribe, the official promises that your firm will receive preferential treatment in future government contracts. You refuse the request, explaining that the _________ Act of the United States prohibits you from making such payments. Foreign Corrupt Practices A major concern voiced by U.S. critics of the North American Free Trade Agreement (NAFTA) was that it would result in: loss of jobs in the U.S. economy. Comparative advantage theory states that a country should sell to other countries those products that it produces most efficiently and buy from other countries those products it cannot produce as efficiently. true As students think about a career in the business world today, which of the following is a good strategic suggestion? Study a foreign language. China has approximately 95% of the world’s Neodymium, a rare earth metal used in consumer and military electronics and contemporary technology. The fact that this is a necessary metal for the production of many products we use today—everything from smartphones to smart bombs—means China can almost name its price! Which of the following describes this situation? China has a near absolute advantage in Neodymium. Casey is typical of many U.S. businesspeople. Casey feels the U.S. culture defines the model for the rest of the world, and that the “American way” of doing things is the best. Casey is guilty of: ethnocentricity. Two recent studies found a strong correlation between academic dishonesty among undergraduates and dishonesty at work. true One good reason for managing a business ethically is to help reduce employee turnover. true Often it is the threat of negative publicity that pressures businesses to enforce their corporate code of ethics. true The majority of CEOs blame unethical employee conduct on: a failure of leadership to establish ethical standards. Purposefully understating your firm’s income to avoid paying higher taxes is an example of: illegal behavior. Legal behavior and ethical behavior are basically the same. false When WorldCom used intentional accounting irregularities to make the company look more profitable than it actually was, it: engaged in illegal behavior. The difference between an organization’s positive social contributions and its negative social impacts is called their: net social contribution. ________ refers to standards of moral behavior. Ethics Last week, the Local Citizens for a Greener America sent a formal document to Chipper’s Golf Resort asking the private club to measure its carbon footprint and publicly disclose the amount of fertilizer and other carbon-emitting substances that it uses on its two award-winning golf courses. LCGA is an example of _________. a watchdog group A firm’s carbon footprint is: the amount of carbon it releases in its effort to do business. Overly ambitious business goals and employee incentives can lead to unethical behavior. true Top leaders in government and business today are: held to higher ethical standards than in the past. Some investors believe it makes financial as well as moral sense to invest in companies whose practices promote sensitivity toward the environment. true Moral behavior refers to behavior that is accepted by society as right versus wrong. true U.S. businesses have little influence over the behavior of businesses from other countries. false Last year the Bank of Plenty, Inc., made an all-out effort to go paperless. The bank’s public relations arm promoted the strategy both internally and externally. Customers were strongly encouraged to utilize the bank’s online banking for all their banking needs. Customers could sign up for local workshops where employees were dedicated to showing them how to navigate the bank’s new website and find the information they required. The bank’s initiative demonstrates: an area where the firm can contribute to the green effort, as well as cut costs. Many businesses have developed internal procedures to enforce their ethical policies. Which of the following is an example of an outside group urging ethical behavior in businesses? union officials When Donut Plaza employs in-store recycling and composting, and uses nontoxic cleaners, Donut Plaza is participating in: corporate responsibility. Which of the following is an unresolved ethical issue that surrounds global trade? Labor standards Many Americans define ethical behavior according to the situation in which they find themselves. This suggests that there may be situations where ________ to cheat, steal, or lie. it might be okay While speaking with his sales force, the director of sales explains, “Anyone caught violating a sales law will be fired.” After studying business ethics, you recognize this remark as a reference to the firm’s __________ ethics. compliance-based While telling an abusive joke about an ethnic group may not be unlawful, it is unethical. true Sharon, a CPA for a large firm, noticed that the company’s accounting records drastically overstated the amount of inventory on hand, which led to overstating the assets of the firm. Initially, she brought it to the attention of her supervisor, but when nothing was done to correct the mistake in a timely manner, she decided the best course of action was to report it to the appropriate government official. Although her actions took her outside the company, she was counting on current law, under the __________, to protect her against company retaliation. Sarbanes-Oxley Act
https://studyhippo.com/test-1-study-notes/
CC-MAIN-2020-40
refinedweb
1,920
54.02
One of the applications of DFS is to find the number of connected components in a graph.In graph theory, a connected component of an undirected graph is a sub-graph in which any two vertices are connected to each other by paths, and which is connected to no additional vertices in the super-graph. Algorithm- A depth first search that begins at some particular vertex v will find the entire connected component containing v (and no more) before returning.To find all the connected components of a graph, loop through its vertices, starting a new depth first search whenever the loop reaches a vertex that has not already been included in a previously found connected component. Another application is to find if the given graph is a tree or not.A tree is an undirected graph which is connected and does not have cycles. Properties of a tree- 1.The tree should have only one connected component ie. it is not a disconnected graph. 2.If the graph has N vertices and N-1 edges,then it is a tree.This condition ensures that no cycles are formed. Algorithm- For a graph to be a tree,both the above conditions must be satisfied.Number of components is found using the above algorithm and it should be 1.Then,the second relation must be verified. Code- #include<stdio.h> #include<vector> using namespace std; vector<int>arr[10005]; int n,a,b,j=0,m; int color[100005]; //counter counts the number of components int counter; void dfs(int node) { color[node]=2;//marking the visited nodes for(int i=0;i<arr[node].size();++i) { if(color[arr[node][i]]==0) { dfs(arr[node][i]); } } } int main() { int t,p; int i; counter=0; p=1; j=0; // n is the number of vertices // m is the number of edges scanf("%d %d",&n,&m); //clearing the arrays and vectors for(i=0;i<n;i++) arr[i].clear(); for(i=0;i<n;++i){ color[i]=0; } while(j<m){ //a and b denote the starting and ending points of the edge scanf("%d %d",&a,&b); //maintaining the adjacency lists arr[a-1].push_back(b-1); arr[b-1].push_back(a-1); j++; } //looping through the vertices for(i=0;i<n;++i) { if(color[i]==0) { dfs(i); counter++; } } printf("Number of components is %d\n",counter); if((m==n-1)&&(counter==1))printf("IT IS A TREE\n"); else printf("NOT A TREE\n"); return 0; }
http://www.codemarvels.com/2013/08/applications-of-dfs/
CC-MAIN-2020-34
refinedweb
421
53.51
ListDiff ListDiff is a Swift port of IGListKit's IGListDiff. It is an implementation of an algorithm by Paul Heckel that calculates the diff between 2 arrays. Motivation The motivation for this project came from the following challenge which I learnt about it from Ryan Nystrom's talk at iOSConf.SG. Getting Started swift package generate-xcodeproj Installation CocoaPods pod 'ListDiff' Carthage github "lxcid/ListDiff" "master" Usage import ListDiff extension Int : Diffable { public var diffIdentifier: AnyHashable { return self } } let o = [0, 1, 2] let n = [2, 1, 3] let result = List.diffing(oldArray: o, newArray: n) // result.hasChanges == true // result.deletes == IndexSet(integer: 0) // result.inserts == IndexSet(integer: 2) // result.moves == [List.MoveIndex(from: 2, to: 0), List.MoveIndex(from: 1, to: 1)] // result.changeCount == 4 Rationale During the port, I made several decisions which I would like to rationalize here. - Using caseless enum as namespace. See Erica Sadun's post here. - No support for index paths. Decided that this is out of the scope. - Stack vs Heap. AFAIK, Swift does not advocates thinking about stack vs heap allocation model, leaving the optimization decisions to compiler instead. Nevertheless, some of the guideline do favour structmore, so only List.Entryis a (final) class as we need reference to its instances. Alternatives Github Help us keep the lights on Dependencies Used By Total:
http://swiftpack.co/package/lxcid/ListDiff
CC-MAIN-2019-18
refinedweb
221
52.76
Please confirm that you want to add Building Web Applications with Clojure to your Wishlist.. Configuring projects correctly for development is essential in every programming language. The use of Lein and Ring in web development under Clojure allows the developer to focus on the actual code. The Lein-ring plugin simplifies a lot of common web development tasks when programming in Clojure. In this video, we will see how to connect it to a project and configure its settings. Knowing about Ring handlers is very important when it comes to writing web applications in Clojure. If the programmer understands what it does and how it works, all other Ring concepts become clear and understandable. The Ring server (based on the Jetty adapter) allows the developer to quickly run the written Clojure web app. In addition, we will also see how the Ring server speeds up the development cycle with dynamic Clojure namespace reloading. Every web application needs to be distributed to a production/test/staging environment. This video presents the different options that are available when using the Lein-ring plugin. How the Ring handler works and how it is just like any other Clojure function. How to work with Ring handler request map. How to return appropriate Ring responses. How to dispatch Ring requests to different handler functions. Learn how route functions can be composed to streamline common tasks. An overview of the common mechanisms for Clojure web apps as reusable components. Rewrite a handler that provides a common mechanism to work as a middleware. Modify Ring request and response maps to provide additional features. Modify the handler configuration to use the Ring file that serves as middleware. Apply the correct middleware to access form data in Ring web applications. Build dynamic responses from Ring handlers. Use Ring middleware to send cookies to a browser and read received cookies. Use Ring middleware to manage sessions in Clojure web applications. Clojure/Ring can be used to provide RESTful APIs as well as standard web applications. Build an example RESTful API with Clojure and Ring. Handle errors in an API in a way that is understandable to other applications. How to access the PostgreSQL database from a Clojure/Ring web application. Connecting a Clojure web application to a MongoDB NoSQL database. Write dynamic applications in ClojureScript instead of JavaScript. Learn how to change page contents and access JavaScript objects from ClojureScript. Communicate with the backend from ClojureScript level. Use Compojure to organize your Ring handlers. Use Hiccup for dynamic HTML generation in Clojure. Use Enlive to separate HTML templates from Clojure code. Use Liberator to provide REST APIs with little effort..
https://www.udemy.com/building-web-applications-with-clojure/
CC-MAIN-2017-26
refinedweb
440
59.19
Sends data or expedited data over a connection. Transport Layer Interface Library (libtli.a) #include <tiuser.h> int t_snd(fd, buf, nbytes, flags) int fd; char *buf; unsigned nbytes; int flags; The t_snd subroutine is used to send either normal or expedited data. By default, the t_snd subroutine runs in asynchronous mode and stops immediately if there are flow-control restrictions. Even when there are no flow-control restrictions, the t_snd subroutine will wait if STREAMS internal resources are not available, regardless of the state of the O_NDELAY or O_NONBLOCK flag. On successful completion, the t_snd subroutine returns the number of bytes accepted by the transport provider. Normally this equals the number of bytes specified in the nbytes parameter. However, if the O_NDELAY or O_NONBLOCK flag is set, it is possible that only part of the data will be accepted by the transport provider. In this case, the t_snd subroutine sets the T_MORE flag for the data that was sent and returns a value less than the value of the nbytes parameter. If the value of the nbytes parameter is 0, no data is passed to the provider and the t_snd subroutine returns a value of 0. If the call to the t_snd subroutine is issued from the T_IDLE state, the provider may silently discard the data. If the call to the t_snd subroutine is issued from any state other than T_DATAXFER, T_INREL, or T_IDLE, the provider generates a TSYSERR error with system error EPROTO (which can be reported in the manner described above). On successful completion, the t_snd subroutine returns the number of bytes accepted by the transport provider. Otherwise, it returns a value of -1 and sets the t_errno variable to indicate the error. If unsuccessful, the t_errno variable is set to one of the following: This subroutine is part of Base Operating System (BOS) Runtime. The t_getinfo subroutine, t_getstate subroutine, t_open subroutine, t_rcv subroutine. List of Streams Programming References and STREAMS Overview in AIX Version 4.3 Communications Programming Concepts.
http://ps-2.kev009.com/tl/techlib/manuals/adoclib/libs/commtrf2/tsndtran.htm
CC-MAIN-2022-33
refinedweb
333
54.02
Consider the task of validating a phone number entered into a form on a Web page. The goal is to verify that the data entered has the proper format before permitting it to be submitted to the server for processing. If you’re only interested in validating North American phone numbers of the form NNN-NNN-NNNN where N’s are digits, you might write code like this: // Returns true if character is a digit function isDigit(character) { return (character >>= "0" && character <<= "9"); } // Returns true if phone is of the form NNN-NNN-NNNN function isPhoneNumber(phone) { if (phone.length != 12) return false; // For each character in the string... for (var i=0; i<<12; i++) { // If there should be a dash here... if (i == 3 || i == 7) { // Return false if there's not if (phone.charAt(i) != "-") return false; } // Else there should be a digit here... else { // Return false if there's not if (!isDigit(phone.charAt(i))) return false; } } return true; } This is a lot of code for such a seemingly simple task. The code is far from elegant, and just imagine how much more complicated it would have to be if you wanted to validate other formats—for example, phone numbers with extensions, international numbers, or numbers with the dashes or area code omitted. Regular expressions simplify tasks like this considerably by allowing programmers to specify a pattern against which a string is “matched.” This frees developers from having to write complicated and error-prone text matching code like we did in the preceding example. But regular expressions are not just limited to determining whether a string matches a particular pattern (like our NNN-NNN-NNNN in the preceeding listing); if the string does match, it is possible to locate, extract, or even replace the matching portions. This vastly simplifies the recognition and extraction of structured data like URLs, e-mail addresses, phone numbers, and cookies. Just about any type of string data with a predictable format can be operated upon with regular expressions.
http://www.yaldex.com/javascript_tutorial_2/LiB0053.html
crawl-003
refinedweb
337
58.72
Sometimes we need to get the file last modified date in Java, usually for listeners like JBoss config file changes hot deployment. java.io.File class lastModified() returns last modified date in long, we can construct date object in human readable format with this time. Java File last modified date A simple example showing how to get file last modified date in java. package com.journaldev.files; import java.io.File; import java.util.Date; public class FileDate { public static void main(String[] args) { File file = new File("employee.xml"); long timestamp = file.lastModified(); System.out.println("employee.xml last modified date = "+new Date(timestamp)); } } Output of the above program is: employee.xml last modified date = Fri Dec 07 14:19:10 PST 2012 If file doesn’t exists, lastModified() returns 0L, if I delete employee.xml then the output is: employee.xml last modified date = Wed Dec 31 16:00:00 PST 1969 Above time is the start of time in java. The 0L in java time. That’s all about finding the last modified time of a file in java.
https://www.journaldev.com/915/get-file-last-modified-date-time-java
CC-MAIN-2019-39
refinedweb
182
59.3
Guide of CPython’s Parser¶ - Author Pablo Galindo Salgado Abstract¶ The Parser in CPython is currently a PEG (Parser Expression Grammar) parser. The first version of the parser used to be an LL(1) based parser that was one of the oldest parts of CPython implemented before it was replaced by PEP 617. In particular, both the current parser and the old LL(1) parser are the output of a parser generator. This means that the way the parser is written is by feeding a description of the Grammar of the Python language to a special program (the parser generator) which outputs the parser. The way the Python language is changed is therefore by modifying the grammar file and developers rarely need to interact with the parser generator itself other than use it to generate the parser. How PEG Parsers Work¶ A PEG (Parsing Expression Grammar) grammar (like the current one) differs from a context-free grammar in that can arise with LL(1) parsers and with context-free grammars in general., nor do they necessarily mean that the parsing has failed. Since the choice operator is ordered, a failure very often merely indicates “try the following option”. A direct implementation of a PEG parser as a recursive descent parser will present exponential time performance in the worst case,. Key ideas¶ Important Don’t try to reason about a PEG grammar in the same way you would to with an EBNF or context free grammar. PEG is optimized to describe how input strings will be parsed, while context-free grammars are optimized to generate strings of the language they describe (in EBNF, to know if a given string is in the language, you need to do work to find out as it is not immediately obvious from the grammar). Alternatives are ordered ( A | Bis not the same as B | A). If a rule returns a failure, it doesn’t mean that the parsing has failed, it just means “try something else”. By default PEG parsers run in exponential time, which can be optimized to linear by using memoization. If parsing fails completely (no rule succeeds in parsing all the input text), the PEG parser doesn’t have a concept of “where the SyntaxErroris”. Consequences or the ordered choice operator¶ Although PEG may look like EBNF, its meaning is quite different. The fact that in PEG parsers alternatives are ordered (which is at the core of how PEG parsers work) has deep consequences, other than removing ambiguity. If a rule has two alternatives and the first of them succeeds, the second one is not attempted even if the caller rule fails to parse the rest of the input. Thus the parser is said to be “eager”. To illustrate this, consider the following two rules (in these examples, a token is an individual character): first_rule: ( 'a' | 'aa' ) 'a' second_rule: ('aa' | 'a' ) 'a' In a regular EBNF grammar, both rules specify the language {aa, aaa} but in PEG, one of these two rules accepts the string aaa but not the string aa. The other does the opposite – it accepts the string the string aa but not the string aaa. The rule ('a'|'aa')'a' does not accept aaa because 'a'|'aa' consumes the first a, letting the final a in the rule consume the second, and leaving out the third a. As the rule has succeeded, no attempt is ever made to go back and let 'a'|'aa' try the second alternative. The expression ('aa'|'a')'a' does not accept aa because 'aa'|'a' accepts all of aa, leaving nothing for the final a. Again, the second alternative of 'aa'|'a' is not tried. Caution The effects of ordered choice, such as the ones illustrated above, may be hidden by many levels of rules. For this reason, writing rules where an alternative is contained in the next one is in almost all cases a mistake, for example: my_rule: | 'if' expression 'then' block | 'if' expression 'then' block 'else' block In this example, the second alternative will never be tried because the first one will succeed first (even if the input string has an 'else' block that follows). To correctly write this rule you can simply alter the order: my_rule: | 'if' expression 'then' block 'else' block | 'if' expression 'then' block In this case, if the input string doesn’t have an 'else' block, the first alternative will fail and the second will be attempted without said part. Syntax¶¶ # comment¶ Python-style comments. e1 e2¶ Match e1, then match e2. rule_name: first_rule second_rule e1 | e2¶ Match e1 or e2. The first alternative can also appear on the line after the rule name for formatting purposes. In that case, a | must be used before the first alternative, like so: rule_name[return_type]: | first_alt | second_alt ( e )¶ Match e. rule_name: (e) A slightly more complex and useful example includes using the grouping operator together with the repeat operators: rule_name: (e1 e2)* [ e ] or e?¶ Optionally match e. rule_name: [e] A more useful example includes defining that a trailing comma is optional: rule_name: e (',' e)* [','] e*¶ Match zero or more occurrences of e. rule_name: (e1 e2)* e+¶ Match one or more occurrences of e. rule_name: (e1 e2)+ s.e+¶ Match one or more occurrences of e, separated by s. The generated parse tree does not include the separator. This is otherwise identical to (e (s e)*). rule_name: ','.e+ &e¶ Succeed if e can be parsed, without consuming any input. !e¶ Fail if e can be parsed, without consuming any input. An example taken from the Python grammar specifies that a primary consists of an atom, which is not followed by a . or a ( or a [: primary: atom !'.' !'(' !'[' ~¶ Commit to the current alternative, even if it fails to parse. rule_name: '(' ~ some_rule ')' | some_alt In this example, if a left parenthesis is parsed, then the other alternative won’t be considered, even if some_rule or ‘)’ fail to be parsed. Left recursion¶ PEG parsers normally do not support left recursion but CPython’s parser generator implements Variables in the Grammar¶ A sub-expression can be named by preceding it with an identifier and an = sign. The name can then be used in the action (see below), like this: rule_name[return_type]: '(' a=some_other_rule ')' { a } Grammar actions¶ To avoid the intermediate steps that obscure the relationship between the grammar and the AST generation the ommited, a default action is generated: If there’s a single name in the rule in the rule, it gets returned. If there is more than one name in the rule, a collection with all parsed expressions gets returned (the type of the collection will be different in C and Python). This default behaviour is primarily made for very simple situations and for debugging pourposes.* ENDMARKER { _PyAST_Module(a, NULL, p->arena) } expr_stmt[stmt_ty]: a=expr NEWLINE { _PyAST_Expr(a, EXTRA) } expr[expr_ty]: | l=expr '+' r=term { _PyAST_BinOp(l, Add, r, EXTRA) } | l=expr '-' r=term { _PyAST_BinOp(l, Sub, r, EXTRA) } | term term[expr_ty]: | l=term '*' r=factor { _PyAST_BinOp(l, Mult, r, EXTRA) } | l=term '/' r=factor { _PyAST_BinOp(l, Div, r, EXTRA) } | factor factor[expr_ty]: | '(' e=expr ')' { e } | atom atom[expr_ty]: | NAME | NUMBER[ast.Module]: a=expr_stmt* ENDMARKER { ast.Module(body=a or [] } expr_stmt: a=expr NEWLINE { ast.Expr(value=a, EXTRA) } expr: | l=expr '+' r=term { ast.BinOp(left=l, op=ast.Add(), right=r, EXTRA) } | l=expr '-' r=term { ast.BinOp(left=l, op=ast.Sub(), right=r, EXTRA) } | term term: | l=term '*' r=factor { ast.BinOp(left=l, op=ast.Mult(), right=r, EXTRA) } | l=term '/' r=factor { ast.BinOp(left=l, op=ast.Div(), right=r, EXTRA) } | factor factor: | '(' e=expr ')' { e } | atom atom: | NAME | NUMBER Pegen¶ Pegen is the parser generator used in CPython to produce the final PEG parser used by the interpreter. It is the program that can be used to read the python grammar located in Grammar/Python.gram and produce the final C parser. It contains the following pieces: A parser generator that can read a grammar file and produce a PEG parser written in Python or C that can parse said grammar. The generator is located at Tools/peg_generator/pegen. A PEG meta-grammar that automatically generates a Python parser that is used for the parser generator itself (this means that there are no manually-written parsers). The meta-grammar is located at Tools/peg_generator/pegen/metagrammar.gram. A generated parser (using the parser generator) that can directly produce C and Python AST objects. The source code for Pegen lives at Tools/peg_generator/pegen but normally all typical commands to interact with the parser generator are executed from the main makefile. How to regenerate the parser¶ Once you have made the changes to the grammar files, to regenerate the C parser (the one used by the interpreter) just execute: make regen-pegen using the Makefile in the main directory. If you are on Windows you can use the Visual Studio project files to regenerate the parser or to execute: ./PCbuild/build.bat --regen The generated parser file is located at Parser/parser.c. How to regenerate the meta-parser¶ The meta-grammar (the grammar that describes the grammar for the grammar files themselves) is located at Tools/peg_generator/pegen/metagrammar.gram. Although it is very unlikely that you will ever need to modify it, if you make any modifications to this file (in order to implement new Pegen features) you will need to regenerate the meta-parser (the parser that parses the grammar files). To do so just execute: make regen-pegen-metaparser If you are on Windows you can use the Visual Studio project files to regenerate the parser or to execute: ./PCbuild/build.bat --regen Grammatical elements and rules¶ Pegen has some special grammatical elements and rules: Strings with single quotes (’) (e.g. 'class') denote KEYWORDS. Strings with double quotes (”) (e.g. "match") denote SOFT KEYWORDS. Upper case names (e.g. NAME) denote tokens in the Grammar/Tokensfile. Rule names starting with invalid_ are used for specialized syntax errors. These rules are NOT used in the first pass of the parser. Only if the first pass fails to parse, a second pass including the invalid rules will be executed. If the parser fails in the second phase with a generic syntax error, the location of the generic failure of the first pass will be used (this avoids reporting incorrect locations due to the invalid rules). The order of the alternatives involving invalid rules matter (like any rule in PEG). Tokenization¶ It is common among PEG parser frameworks that the parser does both the parsing and the tokenization, but this does not happen in Pegen. The reason is that the Python language needs a custom tokenizer to handle things like indentation boundaries, some special keywords like ASYNC and AWAIT (for compatibility purposes), backtracking errors (such as unclosed parenthesis), dealing with encoding, interactive mode and much more. Some of these reasons are also there for historical purposes, and some others are useful even today. The list of tokens (all uppercase names in the grammar) that you can use can be found in the Grammar/Tokens file. If you change this file to add new tokens, make sure to regenerate the files by executing: make regen-token If you are on Windows you can use the Visual Studio project files to regenerate the tokens or to execute: ./PCbuild/build.bat --regen How tokens are generated and the rules governing this is completely up to the tokenizer ( Parser/tokenizer.c) and the parser just receives tokens from it. Memoization¶ As described previously, to avoid exponential time complexity in the parser, memoization is used. The C parser used by Python is highly optimized and memoization can be expensive both in memory and time. Although the memory cost is obvious (the parser needs memory for storing previous results in the cache) the execution time cost comes for continuously checking if the given rule has a cache hit or not. In many situations, just parsing it again can be faster. Pegen disables memoization by default except for rules with the special marker memo after the rule name (and type, if present): rule_name[typr] (memo): ... By selectively turning on memoization for a handful of rules, the parser becomes faster and uses less memory. Note Left-recursive rules always use memoization, since the implementation of left-recursion depends on it. To know if a new rule needs memoization or not, benchmarking is required (comparing execution times and memory usage of some considerably big files with and without memoization). There is a very simple instrumentation API available in the generated C parse code that allows to measure how much each rule uses memoization (check the Parser/pegen.c file for more information) but it needs to be manually activated. Automatic variables¶ To make writing actions easier, Pegen injects some automatic variables in the namespace available when writing actions. In the C parser, some of these automatic variable names are: p: The parser structure. EXTRA: This is a macro that expands to (_start_lineno, _start_col_offset, _end_lineno, _end_col_offset, p->arena), which is normally used to create AST nodes as almost all constructors need these attributes to be provided. All of the location variables are taken from the location information of the current token. Hard and Soft keywords¶ Note In the grammar files, keywords are defined using single quotes (e.g. ‘class’) while soft keywords are defined using double quotes (e.g. “match”). There are two kinds of keywords allowed in pegen grammars: hard and soft keywords. The difference between hard and soft keywords is that hard keywords are always reserved words, even in positions where they make no sense (e.g. x = class + 1), while soft keywords only get a special meaning in context. Trying to use a hard keyword as a variable will always fail: >>> class = 3 File "<stdin>", line 1 class = 3 ^ SyntaxError: invalid syntax >>> foo(class=3) File "<stdin>", line 1 foo(class=3) ^^^^^ SyntaxError: invalid syntax While soft keywords don’t have this limitation if used in a context other the one where they are defined as keywords: >>> match = 45 >>> foo(match="Yeah!") The match and case keywords are soft keywords, so that they are recognized as keywords at the beginning of a match statement or case block respectively, but are allowed to be used in other places as variable or argument names. You can get a list of all keywords defined in the grammar from Python: >>> import keyword >>> keyword.kwlist ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] as well as soft keywords: >>> import keyword >>> keyword.softkwlist ['_', 'case', 'match'] Caution Soft keywords can be a bit challenging to manage as they can be accepted in places you don’t intend to, given how the order alternatives behave in PEG parsers (see consequences of ordered choice section for some background on this). In general, try to define them in places where there is not a lot of alternatives. Error handling¶ When a pegen-generated parser detects that an exception is raised, it will automatically stop parsing, no matter what the current state of the parser is and it will unwind the stack and report the exception. This means that if a rule action raises an exception all parsing will stop at that exact point. This is done to allow to correctly propagate any exception set by calling Python C-API functions. This also includes SyntaxError exceptions and this is the main mechanism the parser uses to report custom syntax error messages. Note Tokenizer errors are normally reported by raising exceptions but some special tokenizer errors such as unclosed parenthesis will be reported only after the parser finishes without returning anything. How Syntax errors are reported¶ As described previously in the how PEG parsers work section, PEG parsers don’t have a defined concept of where errors happened in the grammar, because a rule failure doesn’t imply a parsing failure like in context free grammars. This means that some heuristic has to be used to report generic errors unless something is explicitly declared as an error in the grammar. To report generic syntax errors, pegen uses a common heuristic in PEG parsers: the location of generic syntax errors is reported in the furthest token that was attempted to be matched but failed. This is only done if parsing has failed (the parser returns NULL in C or None in Python) but no exception has been raised. Caution Positive and negative lookaheads will try to match a token so they will affect the location of generic syntax errors. Use them carefully at boundaries between rules. As the Python grammar was primordially written as an LL(1) grammar, this heuristic has an extremely high success rate, but some PEG features can have small effects, such as positive lookaheads and negative lookaheads. To generate more precise syntax errors, custom rules are used. This is a common practice also in context free grammars: the parser will try to accept some construct that is known to be incorrect just to report a specific syntax error for that construct. In pegen grammars, these rules start with the invalid_ prefix. This is because trying to match these rules normally has a performance impact on parsing (and can also affect the ‘correct’ grammar itself in some tricky cases, depending on the ordering of the rules) so the generated parser acts in two phases: The first phase will try to parse the input stream without taking into account rules that start with the invalid_prefix. If the parsing succeeds it will return the generated AST and the second phase will not be attempted. If the first phase failed, a second parsing attempt is done including the rules that start with an invalid_prefix. By design this attempt cannot succeed and is only executed to give to the invalid rules a chance to detect specific situations where custom, more precise, syntax errors can be raised. This also allows to trade a bit of performance for precision reporting errors: given that we know that the input text is invalid, there is no need to be fast because the interpreter is going to stop anyway. Important When defining invalid rules: Make sure all custom invalid rules raise SyntaxErrorexceptions (or a subclass of it). Make sure all invalid rules start with the invalid_prefix to not impact performance of parsing correct Python code. Make sure the parser doesn’t behave differently for regular rules when you introduce invalid rules (see the how PEG parsers work section for more information). You can find a collection of macros to raise specialized syntax errors in the Parser/pegen.h header file. These macros allow also to report ranges for the custom errors that will be highlighted in the tracebacks that will be displayed when the error is reported. Tip A good way to test if an invalid rule will be triggered when you expect is to test if introducing a syntax error after valid code triggers the rule or not. For example: <valid python code> $ 42 Should trigger the syntax error in the $ character. If your rule is not correctly defined this won’t happen. For example, if you try to define a rule to match Python 2 style invalid_print: "print" expression This will seem to work because the parser will correctly parse print(something) because it is valid code and the second phase will never execute but if you try to parse print(something) $ 3 the first pass of the parser will fail (because of the $) and in the second phase, the rule will match the print(something) as something between parentheses and the error will be reported there instead of the $ character. Generating AST objects¶ The output of the C parser used by CPython that is generated by the Grammar/Python.gram grammar file is a Python AST object (using C structures). This means that the actions in the grammar file generate AST objects when they succeed. Constructing these objects can be quite cumbersome (see the AST compiler section for more information on how these objects are constructed and how they are used by the compiler) so special helper functions are used. These functions are declared in the Parser/pegen.h header file and defined in the Parser/pegen.c file. These functions allow you to join AST sequences, get specific elements from them or to do extra processing on the generated tree. Caution Actions must never be used to accept or reject rules. It may be tempting in some situations to write a very generic rule and then check the generated AST to decide if is valid or not but this will render the official grammar partially incorrect (because actions are not included) and will make it more difficult for other Python implementations to adapt the grammar to their own needs. As a general rule, if an action spawns multiple lines or requires something more complicated than a single expression of C code, is normally better to create a custom helper in Parser/pegen.c and expose it in the Parser/pegen.h header file so it can be used from the grammar. If the parsing succeeds, the parser must return a valid AST object. Testing¶ There are three files that contain tests for the grammar and the parser: Lib/test/test_grammar.py. Lib/test/test_syntax.py. Lib/test/test_exceptions.py. Check the contents of these files to know which is the best place to place new tests depending on the nature of the new feature you are adding. Tests for the parser generator itself can be found in the Lib/test/test_peg_generator directory. Debugging generated parsers¶ Making experiments¶ As the generated C parser is the one used by Python, this means that if something goes wrong when adding some new rules to the grammar you cannot correctly compile and execute Python anymore. This makes it a bit challenging to debug when something goes wrong, especially when making experiments. For this reason it is a good idea to experiment first by generating a Python parser. To do this, you can go to the Tools/peg_generator/ directory on the CPython repository and manually call the parser generator by executing: $ python -m pegen python <PATH TO YOUR GRAMMAR FILE> This will generate a file called parse.py in the same directory that you can use to parse some input: $ python parse.py file_with_source_code_to_test.py As the generated parse.py file is just Python code, you can modify it and add breakpoints to debug or better understand some complex situations. Verbose mode¶ When Python is compiled in debug mode (by adding --with-pydebug when running the configure step in Linux or by adding -d when calling the PCbuild/python.bat script in Windows), is possible to activate a very verbose mode in the generated parser. This is very useful to debug the generated parser and to understand how it works, but it can be a bit hard to understand at first. Note When activating verbose mode in the Python parser, it is better to not use interactive mode as it can be much harder to understand, because interactive mode involves some special steps compared to regular parsing. To activate verbose mode you can add the -d flag when executing Python: $ python -d file_to_test.py This will print a lot of output to stderr so is probably better to dump it to a file for further analysis. The output consists of trace lines with the following structure: <indentation> (‘>’|’-‘|’+’|’!’) <rule_name>[<token_location>]: <alternative> … Every line is indented by a different amount ( <indentation>) depending on how deep the call stack is. The next character marks the type of the trace: >indicates that a rule is going to be attempted to be parsed. -indicates that a rule has failed to be parsed. +indicates that a rule has been parsed correctly. !indicates that an exception or an error has been detected and the parser is unwinding. The <token_location> part indicates the current index in the token array, the <rule_name> part indicates what rule is being parsed and the <alternative> part indicates what alternative within that rule is being attempted. References¶ - 1 Ford, Bryan - 2 Medeiros et al. - 3 Warth et al.
https://devguide.python.org/parser/
CC-MAIN-2021-39
refinedweb
4,052
58.62
The Real Work ( LocationsSupport) All of the real work is done by the workhorse class LocationsSupport, in Listing Four, and most of what it does is in its constructor. Before looking at the constructor, notice that this class is parametrized, which takes some explanation). The definition looks like this: public class LocationsSupport<T extends Enum<T> & Locations> { //... } and the declaration (from inside the Places enum) looks like this: enum Places implements Location { LocationsSupport<Places> support; //... support = new LocationsSupport<Places>( values() ); // Pass in an iterator across all enum elements //... } So, the class we're passing in (represented as T inside the LocationsSupport definition), is the Places enum. Places extends Enum<Places> implicitly (all enum classes extend Enum in this way), and Places also implements the Locations interface in Listing Three ( Places indeed implements Locations). For some reason, Java-generics represent this situation as <T extends Enum<T> & Locations>, but just read the & as "implements." The point of this exercise is that our support object will be communicating with a specific enum ( Places) whose name it doesn't know when it's compiled. The generics mechanism lets us avoid all the casts that would be required by this situation. Without generic types, every T would require Object, and that Object would have to be cast into something — but into what? Generics solve the problem. For purposes of the current example, every time you see T in LocationsSupport.java, mentally replace it with Places. The next item of interest is the dictionary, on line line 37. This is a hash map that will hold all the keys ( TMP, HOME, etc.) defined in the containing enum along with File objects representing the associated locations. These aren't the original strings, but are initialized using the original strings after things like tilde substitution occur. Most of the real work of loading and verifying the values is done in the constructor, which does all the validation I discussed earlier. The code is, I hope, self explanatory. The only notable thing is that each iteration of the main loop adds a line to a buffer that is logged at the bottom of the method (as opposed to logging in each iteration). All I'm doing is cleaning up the log file a little, but that's not a bad thing. Note that I'm logging the actual values used (extracted from the File object), not the input strings because the real values are what I'm actually interested in when I'm debugging my server. Listing Three: Locations.java, the Locations workhorse class. package com.holub.util; import java.io.File; /** * Support for enums that encapsulate locations (e.g. {@link Places}). * Note that the methods of this class let you ask the enum about * itself, but do not let you modify the Enum's value (ie. there * are no "setter" methods). That's quite deliberate. * * @author Allen Holub * * <div style='font-size:7pt; margin-top:.25in;'> * ©2012 <!--copyright 2012--> Allen I Holub. All rights reserved. * This code is licensed under a variant on the BSD license. View * the complete text at <a href=""> *</a>. * </div> */ public interface Locations { /** Return a File object representing the * directory specified in the current enum element's contents. */ File directory(); /** Return a File object representing the named file in the * directory represented by the current enum element's contents. * This method is effectively a convenience wrapper for: * <blockquote> * <code>new {@link File}({@link #directory()}, name );</code> * </blockquote> * Note that there's no requirement that the specified file * exists. Use methods of the {@link File} class to test for * existence, etc. */ File file( String name ); /** Return the default passed into this enum-element's constructor. Note that * any tilde (~) characters found in the returned string are NOT replaced * by the user.home system property string. That replacement is effectively * done by the {@link #directory()} method. */ String defaultValue(); /** Return true if the directory associated with the enum element should * be created if it doesn't already exist. */ boolean createIfNecessary(); } Listing 4: LocationsSupport.java, the LocationsSupport workhorse class. package com.holub.util; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.Map.Entry; import org.apache.log4j.Logger; import org.apache.log4j.helpers.NullEnumeration; //---------------------------------------------------------------------- public class LocationsSupport<T extends Enum<T> & Locations> { /** * Create the logger. * Note that the ExtendedLogger uses the LocationsSupport class (via the Places enum). * Consequently, we can't use it to access the log4j.properties file. I've solved the * problem by putting log4j.properties onto the classpath as well, but if you don't * do that, we'll just print log messages to stderr instead of using log4j. Also, * we'll use a standard log4j Logger instead of an ExtendedLogger: */ private static final Logger log = Logger.getLogger(Locations.class); /** We have two choices of where to store the File object associated * with a given key: we can push it into the enum element using some * sort of accessor method, or we can store it locally and the enum can * pull it out of the current object. The main problem with the push-it-into-the-enum * approach is that that would expose a "set" method in the enum element that anybody could * call at any point to change the File value, and I don't want that to * be possible. So, I'll put up with the minor inefficiency of looking up the * File value locally every time we need it. */ private Map<String,File> dictionary = new HashMap<String,File>(); /** For every enum element in the array, treat keys[i].name() as a key * and load the associated value from the following places (in order): * <ol> * <li>a -D command-line switch (in System properties). * <li>if no -D value found, an environment variable with the same name as the key. * <li>if no environment found, the default stored in the Enum element itself. * </ol> * That value must identify an existing directory in the file system, and a * File representing that location can be retrieved from {@link #directory(Enum)}. * * @throws IllegalStateException if a given key doesn't have value associated with it or if * that value doesn't identify an existing directory. * * @param keys The values() array associated with the enum that's using this helper class. * @throws IOException */ public LocationsSupport( T[] keys ) throws IllegalStateException { StringBuilder logMessage = new StringBuilder( "Loaded environment/-D properties:\n" ); try { for( T element : keys ) { String how = "????"; String key = element.name(); String value; if( (value = System.getProperty(key)) != null ) how = "from system property (-D)"; else if( (value = System.getenv(key)) != null ) how = "from environment"; else if( (value = element.defaultValue()) != null ) how = "from default. mapped from: " + value; if( value != null ) value = value.replaceAll("~", System.getProperty("user.home") ).trim(); if( value == null || value.length()==0 ) throw new IllegalStateException("Value for " + key + " cannot be null or empty." ); File location = new File( value ); try { if( element.createIfNecessary() ) if( !location.exists() ) { log.info("Creating directory: " + asString(location) ); if( !location.mkdirs() ) throw new IllegalStateException( "Couldn't create " + asString(location) ); } } catch(SecurityException e) // unexpected, but catch it on the off chance. { throw new IllegalStateException( "Not permitted to create " + asString(location) ); } if( !location.isDirectory() ) throw new IllegalStateException( "Location specified in " + key + " (" + asString(location) + ") does not exist or is not a directory" ); dictionary.put(key, location); logMessage.append("\t"); logMessage.append(key); logMessage.append("="); logMessage.append( asString(location) ); logMessage.append(" ("); logMessage.append(how); logMessage.append(" )\n"); } } finally { // If logging isn't active, yet, then print to stderr. if( log.getAllAppenders() instanceof NullEnumeration ) System.err.println(logMessage); else log.info(logMessage); } } /** Return the location associated with the indicated enum Element. * * @param key * @return */ public File directory( T element ) { return dictionary.get(element.name()); } /** Export all the cached properties to the indicated * properties object. Handy if you need to pass a * properties object to some subsystem for initialization. * The locations are represented in "canonical" form if possible; * otherwise, the "absolute" form is used. * * @param target Load this object with the properties. If null, * create a new properties object and load that. * @return the properties object into which the values were put. */ public Properties export( Properties target ) { if( target == null ) target = new Properties(); for( String key: dictionary.keySet() ) { File location = dictionary.get(key); String value = asString( location ); target.setProperty(key, value); } return target; } /** A convenience method that returns a string holding the * path to the desired location. Uses the File's "canonical" * form if possible, otherwise uses the "absolute" form. */ public static String asString( File location ) { try { return location.getCanonicalPath(); } catch (IOException e) { return location.getAbsolutePath(); } } /** Returns the current set as a newline-separated list * of key=value pairs, suitable for exporting as a * properties file. If you want a more compact format, use * <code>{@link #export(Properties)}.toString()</code>, which * invokes {@link Properties#toString()}. */ @Override public String toString() { StringBuilder b = new StringBuilder(); for( Entry<Object, Object> entry : export(null).entrySet() ) { b.append( (String)(entry.getKey()) ); b.append( "=" ); b.append( (String)(entry.getValue()) ); b.append( "\n" ); } return b.toString(); } } Conclusion So that's it. There is actually not all that much code here, and all the hard work is in the reusable LocationsSupport class, so it's easy to leverage this technique to create your own enums to track configurable locations. Location-based configuration is only the first part of the puzzle, though. In upcoming articles, I'll present a more complex enum that handles configuration files that hold key=value pairs where the values can be verified by type. That enum is based on the same principles as Places, but is a bit more complicated. (It requires the Java "reflection" APIs, for example.) I also plan to take an extensive look at the mock-based tests that I use for these classes so that you can get a handle on how to test this stuff. Allen Holub is a speaker, lecturer, and writer on software development. His recent books have discussed Java, multithreading, and the use of patterns. He is a frequent contributor to Dr. Dobb's. More Articles by Allen Holub Getting Started with The Cloud: The Ecosystem Getting Started with Google Apps and OAuth Secure Login in AJAX Applications
http://www.drdobbs.com/cpp/logging-in-c/cpp/solving-the-configuration-problem-for-ja/232601218?pgno=3
CC-MAIN-2015-27
refinedweb
1,687
50.33
25 June 2010 10:47 [Source: ICIS news] LONDON (ICIS news)--SolVin and Arkema will separate from their joint ventures in vinyl chloride monomer (VCM) and polyvinyl chloride (PVC) production in France and Spain, the companies said on Friday. Effective from 1 July 2010, both groups have decided to acquire their reciprocal minority interests within the industrial entities of VinylFos, Vinilis and VinylBerre. Following this deal, both partners would regain their respective independence on the production sites in which they hold a majority stake, the companies said. European PVC producer SolVin would become the sole shareholder of Vinilis, based in ?xml:namespace> "This operation will enable SolVin to simplify its industrial structure in this part of the European Union", said Enzo Morici, general manager of Solvay's vinyls business unit. "SolVin always reacts very fast to market changes and customer requests. It will be even more able to do so after this operation," added SolVin managing director, Pierre Tucoulat. “This streamlining of manufacturing structures will help us enhance our response and serve our customers in Both companies said the agreement would not impact their workforce or have consequences or on their results. SolVin is a joint venture of Solvay (75%) and BASF (25%). ($1 = €0.81) For more on Arkema, Solv
http://www.icis.com/Articles/2010/06/25/9371082/solvin-and-arkema-to-separate-from-vcm-and-pvc-joint.html
CC-MAIN-2013-48
refinedweb
211
59.03
Track¶ Log metrics to Neptune¶ How do I track multiple metrics (loss, scores) in the experiment? Solution¶ Step 1: Log In order to log metrics to Neptune, you simply need to: import neptune neptune.init('shared/onboarding') with neptune.create_experiment(): # 'log_loss' is User defined metric name neptune.send_metric('log_loss', 0.753) neptune.send_metric('AUC', 0.95) Another option is to log key: value pair like this: neptune.set_property('model_score', '0.871') Note You can create as many metrics as you wish. Step 2: Analyze Browse and analyse your metrics on the dashboard (example) or in the particular experiment (example experiment). Log images to Neptune¶ I generate model predictions after every epoch. How can I log them as images to Neptune? Solution¶ Log single image to Neptune Create PIL image that you want to log. For example: import imgaug as ia from PIL import Image img = ia.quokka() img_pil = Image.fromarray(img) Log it to Neptune: import neptune # This function assumes that NEPTUNE_API_TOKEN environment variable is defined. neptune.init(project_qualified_name='shared/onboarding') with neptune.create_experiment() as exp: exp.send_image('quokka', img_pil) As a result, quokka image is associated with the experiment Log multiple images to neptune You can log images in a loop. For example, you can augment your image and log it to Neptune: from imgaug import augmenters as iaa aug_seq = iaa.Affine(scale={"x": (0.8, 1.2), "y": (0.8, 1.2)}, translate_percent={"x": (-0.2, 0.2), "y": (-0.2, 0.2)}, rotate=(-25, 25), ) exp2 = neptune.create_experiment() for run in range(20): img_aug= aug_seq.augment_image(img) img_pil_aug = Image.fromarray(img_aug) exp2.send_image('quokka_version_{}'.format(run), img_pil_aug) exp2.close() Save experiment output¶ I can run my experiment but I am struggling to save the model weights and the csv file with the results when it completes. How can I do that in Neptune? Specify experiment parameters¶ I saw that Neptune logs experiment parameters. But I don’t know how to specify parameters for my experiments. Solution¶ You define your parameters at experiment creation, like this: import neptune # This function assumes that NEPTUNE_API_TOKEN environment variable is defined. neptune.init('username/my_project') # check params argument with neptune.create_experiment(name='first-pytorch-ever', params={'dropout': 0.3, 'lr': 0.01, 'nr_epochs': 10}): # your training script Where params is standard Python dict. Version datasets¶ When working on a project, it is not unusual that I change the datasets on which I train my models. How can I keep track of that in Neptune? Solution¶ Under many circumstances it is possible to calculate a hash of your dataset. Even if you are working with large image datasets, you have some sort of a smaller metadata file, that points to image paths. If this is the case you should: Step 1 Create hashing function. For example: import hashlib def md5(fname): hash_md5 = hashlib.md5() with open(fname, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest() Step 2 Calculate the hash of your training data and send it to Neptune as text: TRAIN_FILEPATH = 'PATH/TO/TRAIN/DATA' train_hash = md5(TRAIN_FILEPATH) neptune.send_text('train_data_version', train_hash) ... Step 3 Add data version column to your project dashboard: Note If your dataset is too large for fast hashing you could think about rearranging your data to have a light-weight metadata file. Keep my code private¶ My code is proprietary, so I do not want to send any sources to Neptune, while training locally. How can I do that? Solution¶ All you need to do it to pass empty list [] to the upload_source_files parameter, like this: import neptune # This function assumes that NEPTUNE_API_TOKEN environment variable is defined. neptune.init(project_qualified_name='shared/onboarding') with neptune.create_experiment(upload_source_files=[]) as exp: ... As a result you will not send sources to Neptune, so they will not be available in the Source Code tab in the Web app. Upload notebook checkpoint¶ I want to add a Notebook checkpoint to my project. How do I do that? Solution¶ Go to your Jupyter UI, where you will see several Neptune buttons: Neptune: For modifying configuration. Upload: For creating a new checkpoint in Neptune. Download: For downloading a specific checkpoint from Neptune. Activate: Associates experiments you will be running with this Notebook. Click Upload whenever you want to create new checkpoint in Neptune. As confirmation, Neptune displays a notification with a link. If the Activate button was clicked, checkpoints will be created automatically after every experiment creation.
https://docs.neptune.ai/python-api/how-to/track.html
CC-MAIN-2020-16
refinedweb
741
51.65
Investors in Carnival Corp (Symbol: CCL) saw new options become available today, for the November 1st expiration. At Stock Options Channel, our YieldBoost formula has looked up and down the CCL options chain for the new November 1st contracts and identified one put and one call contract of particular interest. The put contract at the $45.00 strike price has a current bid of 55 cents. If an investor was to sell-to-open that put contract, they are committing to purchase the stock at $45.00, but will also collect the premium, putting the cost basis of the shares at $44.45 (before broker commissions). To an investor already interested in purchasing shares of CCL, that could represent an attractive alternative to paying $49.58.22% return on the cash commitment, or 8.92% annualized — at Stock Options Channel we call this the YieldBoost. Below is a chart showing the trailing twelve month trading history for Carnival Corp, and highlighting in green where the $45.00 strike is located relative to that history: Turning to the calls side of the option chain, the call contract at the $50.00 strike price has a current bid of $1.50. If an investor was to purchase shares of CCL stock at the current price level of $49.58/share, and then sell-to-open that call contract as a "covered call," they are committing to sell the stock at $50.00. Considering the call seller will also collect the premium, that would drive a total return (excluding dividends, if any) of 3.87% if the stock gets called away at the November 1st expiration (before broker commissions). Of course, a lot of upside could potentially be left on the table if CCL shares really soar, which is why looking at the trailing twelve month trading history for Carnival Corp, as well as studying the business fundamentals becomes important. Below is a chart showing CCL's trailing twelve month trading history, with the $50.00 strike highlighted in red: Considering the fact that the $50.03% boost of extra return to the investor, or 22.09% annualized, which we refer to as the YieldBoost. The implied volatility in the put contract example is 36%, while the implied volatility in the call contract example is 30%. Meanwhile, we calculate the actual trailing twelve month volatility (considering the last 251 trading day closing values as well as today's price of $49.58) to be 30%..
https://www.nasdaq.com/articles/ccl-november-1st-options-begin-trading-2019-09-12
CC-MAIN-2021-25
refinedweb
412
64.1
Vote for next post or mention what do you want to see next here: Next post on? – Question Cafe Everything you need to know about Basic working of Deep Learning Neural Networks – Everything you need to know about? question.cafe HTTP is everywhere! Every website we visit is ran on HTTP server. You may think that then what about HTTPS servers. Technically, HTTPS is same as HTTP with more security. Many programmers at some point or the other may get curious about how HTTP servers work and how to build one from the scratch without any external libraries. And I?m one of that many programmers. Recently, I started using node.js for one of my projects. While using it, I got curious about ?How HTTP servers are build?? and ?How HTTP servers work?? And the next question I asked is: ?How can I build HTTP servers from scratch??. ?Is it even possible for beginners to build one??. The Answer is: The first question we ask is: Where do we start from? First, we need to learn about what is OSI. OSI: The Open Systems Interconnection model (OSI. To implement HTTP, we only care about 4th Layer: Transport Layer. Transport Layer:). In Transport Layer, we mainly use Transmission Control Protocol (TCP) to implement HTTP server. We can also use User Datagram Protocol (UDP) to implement HTTP server but many don?t use it. The reasons for it can deviate from our main topic of building HTTP server. In short, from RFC 2616:. So although it doesn?t explicitly say so, UDP is not used because it is not a ?reliable transport?. All the famous HTTP servers like Apache Tomcat, NginX etc are implemented on top of TCP. So, in this post we will just stick with HTTP server based on TCP. Now, you may think ?what the heck is RFC!? RFC: A. In short, it is a document where someone proposes changes, modifications for current methods or proposing a new methods. And also the specifications where the methods have been standardized. There are over 8200 RFCs as of August 2017. The official source for RFCs on the World Wide Web is the RFC Editor. Some of the standardized RFCs are: HTTP/1.1 ?Initially it is RFC 2616 but later replaced by RFC 7230, RFC 7231, RFC 7232, RFC 7233, RFC 7234, RFC 7235. So, we need to read from RFC 7230 to RFC 7235 to implement basic workings of HTTP. HTTP/2 ? RFC 7540 and RFC 7541 FTP ? RFC959 So, if we want to implement HTTP server, we have to read their particular RFC which is RFC 7230, RFC 7231, RFC 7232, RFC 7233, RFC 7234, RFC 7235. Just Relax for a moment before we dive into coding? Now implementing what we have learned: Implementing TCP: First we need to implement the Transport Layer of HTTP which is TCP. NOTE: C Language will be used for the coding part. The reason for using C language is because it can be used with any programming language like Python, Java, Swift etc. As this is ?From the Scratch?, we are building it from the C language which is considered a scratch language for many high-level modern languages. You can integrate your C code with any high-level language. The code we will be implementing is for UNIX-based systems like macOS and Linux. Only implementation code for TCP differs for Windows from UNIX. But implementation of HTTP server is same because we have to follow some specific guidelines from HTTP RFC which is language independent! To implement TCP, we have to learn TCP socket programming. What is socket?. Programming with TCP/IP sockets There are a few steps involved in using sockets: - Create the socket - Identify the socket - On the server, wait for an incoming connection - Send and receive messages - Close the socket Step 1. Create a socket A socket, server_fd, is created with the socket system call: int server_fd = socket(domain, type, protocol);: #include <sys/socket.h>……if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror(?cannot create socket?); return 0; }: int bind(int socket, const struct sockaddr *address, socklen_t address_len);: struct sockaddr_in { __uint8_t sin_len; sa_family_t sin_family; in_port_t sin_port; struct in_addr sin_addr; char sin_zero[8]; };: #include <sys/socket.h> ? struct sockaddr_in address;const int PORT = 8080; //Where the clients can reach at/* htonl converts a long integer (e.g. address) to a network representation */ /* htons converts a short integer (e.g. port) to a network representation */ memset((char *)&address, 0, sizeof(address)); address.sin_family = AF_INET; address.sin_addr.s_addr = htonl(INADDR_ANY); address.sin_port = htons(PORT); if (bind(server_fd,(struct sockaddr *)&address,sizeof(address)) < 0) { perror(?bind failed?); return 0; } Step 3. On the server, wait for an incoming connection Before a client can connect to a server, the server should have a socket that is prepared to accept the connections. The listen system call tells a socket that it should be capable of accepting incoming connections: #include <sys/socket.h> int listen(int socket, int backlog);: #include <sys/socket.h> int accept(int socket, struct sockaddr *restrict address, socklen_t *restrict address_len);. The code to listen and accept look like: if (listen(server_fd, 3) < 0) { perror(?In listen?); exit(EXIT_FAILURE); }if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0){ perror(“In accept”); exit(EXIT_FAILURE); } Step 4. Send and receive messages We finally have connected sockets between a client(when you visit IP address of your server from a web browser) and a server! Communication is the easy part. The same read and write system calls that work on files also work on sockets. char buffer[1024] = {0};int valread = read( new_socket , buffer, 1024); printf(?%sn?,buffer );if(valread < 0){ printf(“No bytes are there to read”);}char *hello = “Hello from the server”;//IMPORTANT! WE WILL GET TO ITwrite(new_socket , hello , strlen(hello)); NOTE: The real working of HTTP server happens based on the content present in char *hello variable. We will get back to it later. Step 5. Close the socket When we?re done communicating, the easiest thing to do is to close a socket with the close system call ? the same close that is used for files. close(new_socket); We have successfully created TCP socket on the server computer! TCP socket server-side code: To test out TCP server code, I have written a TCP client code:(Don?t worry about this code. This code is written to show the difference between simple TCP connection and HTTP connection. Do you remember what I have told about the variable char *hello in Step 4. Send and receive messages?) . TCP socket client-side code: Now, run the TCP socket server-side code in one Terminal and TCP socket client-side code in another Terminal. NOTE: The order is important here. First server-side code, then client-side code. In the server-side output: +++++++ Waiting for new connection ++++++++Hello from client——————Hello message sent——————-+++++++ Waiting for new connection ++++++++ In the client-side output: Hello message sentHello from server Yay! Our code is running and we are able to communicate between applications. That means our TCP implementation is working fine. We are mostly finished with the coding part. Now we will move on to the HTTP server implementation. HTTP First we will take a look at the interaction between Server and Web Browser. This is the basic outline of the interaction. If we zoom in more closely to the HTTP part: - Initially HTTP Client(i.e., web browser) sends a HTTP request to the HTTP Server. - Server processes the request received and sends HTTP response to the HTTP client. Now, lets take a look at client-server and what they send and what they receive. HTTP Client (Web Browser): Client needs to connect to the server every time. Server can?t connect to the client. So, it is the duty of the client to initiate the connection. When we want to connect to the server, what we will do usually? We type some URL/Address of the website in the browser To display the page, browser fetches the file index.html from a web server. Same as (Defaults: port 80, file index.html, http protocol). So, if you type in the web browser, the web browser re-constructs the URL/Address as: This is what our web-browsers send to the servers every time you navigate the internet pages. If the server is configured to certain default pages. Like, server has a default web page where it is displayed when we visit a folder on the server. That web page is decided by the name of the file. Some servers have public.html and some will have index.html. In this example, we consider index.html as default page. Can?t believe? We?ll do one thing. - Run the TCP server-side code (from above) in the Terminal. - Open your web-browser and enter localhost:8080/index.html in the address bar. - Now see what is the output in the Terminal. Output in Terminal: +++++++ Waiting for new connection ++++++++GET /index——————Hello message sent——————-+++++++ Waiting for new connection ++++++++ We get the similar output as shown in the picture. But, wait a second. Have you looked at the web-browser? This is what you see. What is the problem? Why can?t we see the data that we have sent from the server? Do you remember what I have told about the variable char *hello in Step 4. Send and receive messages? If you forgot about that. Go back and check what I have said there. We will get back to that variable char* hello in a minute. Don?t worry. HTTP Methods (Verbs): GET is the default method used by the HTTP. There are 9 HTTP methods. Some of them are: - GET ? Fetch a URL - HEAD ? Fetch information about a URL - PUT ? Store to an URL - POST ? Send form data to a URL and get a response back - DELETE ? Delete a URL GET and POST (forms) are commonly used REST APIs use GET, PUT, POST, and DELETE. HTTP Server: Now, its time to respond to the client and send them what they want! The client sent us some headers and expects same from us in-return. But instead of that, we are sending just a greeting message which is: char* hello = “Hello from server”; The browser is expecting same format response in which it sent us the request. HTTP is nothing but following some rules specified in the RFC documents. That is why I said HTTP implementation is language independent at the start of Implementing TCP. This is the HTTP response format the web-browser is expecting from us: If we want to send Hello from server, first we need to construct the Header. Then insert a blank line, then we can send our message/data. The headers shown above are just an example. In fact there are many Headers present in HTTP. You can take a look at the HTTP RFCs ? RFC 7230, RFC 7231, RFC 7232, RFC 7233, RFC 7234, RFC 7235. Now, we will construct a minimal HTTP Header to make our server work. char *hello = “HTTP/1.1 200 OKnContent-Type: text/plainnContent-Length: 12nnHello world!”; These 3 Headers are minimum required. - HTTP/1.1 200 OK ? This mentions what version of HTTP we are using, Status code and Status message. - Content-Type: text/plain ? This says that I?m (server) sending a plain text. There are many Content-Types. For example, for images we use this. - Content-Length: 12 ? It mentions how many bytes the server is sending to the client. The web-browser only reads how much we mention here. The next part is the Body part. Here, we send our data. First we need to calculate how many bytes we are sending in Body. Then we mention that in Content-Length. Also, we set the Content-Type appropriately according to the data we are sending. Status Code and Status Messages: Status codes are issued by a server in response to a client?s request made to the server. It includes codes from IETF Request for Comments (RFCs), other specifications, and some additional codes used in some common applications of the Hypertext Transfer Protocol (HTTP). The first digit of the status code specifies one of five standard classes of responses. The message phrases shown are typical, but any human-readable alternative may be provided. Unless otherwise stated, the status code is part of the HTTP/1.1 standard (RFC 7231). So, if you can?t find the file that client is asking, then you send appropriate status code. If the client has no permission to see the file, then you send appropriate status code. These are the list of status codes we can use. Now, run the below code in the Terminal and go to localhost:8080 in your browser. Now, you can see Hello world! in your browser. The only thing I have changed is char* hello variable. Finally, our HTTP server is working! How do we send a requested web page to the client? Till now, we learned how to send a string. Now, we will look at how we can send a file, image etc. Suppose, you have entered localhost:8080/info.html in the address bar. In the server Terminal we get the following Request Headers: GET /info For the sake of simplicity, we only consider the 1st line in the Request Headers. GET /info.html HTTP/1.1 So, we just have to search for the info.html file in current directory(as / specifies that it is looking in the root directory of the server. If it is like /messages/info.html then we have to look inside messages folder for info.html file). There are many cases here to consider: Some of them are: - The file(web page) is present - The file(web page) is absent - The client doesn?t have permissions to access the file (web page). And many more?.. First select appropriate status code from here. If the file is present and the client has permissions to access it, then select appropriate Content-Type from here. Then open the file, read the data into a variable. Count the number of bytes read from the file. When you read a simple text file, we can count while reading the file or from the return value of the read() function or strlen(variable). Set the Content-Length. Then construct the Response Header. Now add a newline at the end of Response Header and append the data to it which we have read from the file (If and only if the file is present and the client has permissions to access it). SEND THE RESPONSE HEADER TO THE CLIENT! Thats it! We have successfully created a HTTP Server From the Scratch! Got any doubts/questions/suggestions? Comment down below.
https://911weknow.com/http-server-everything-you-need-to-know-to-build-a-simple-http-server-from-scratch
CC-MAIN-2021-31
refinedweb
2,476
77.13
Here’s the reality, billions of credentials have been leaked or stolen and are now easily downloaded online by anyone. Many of these databases of identities include passwords in plain text, while others are one-way hashed. One-way hashing is better (we’ll get to why in a second), but it is only as secure as is mathematically feasible. Let’s take a look at one-way hashing algorithms and how computers handle them. Hashing A hash by definition is a function that can map data of an arbitrary size to data of a fixed size. SHA2 is a hashing algorithm that uses various bit-wise operations on any number of bytes to produce a fixed sized hash. For example, the SHA-256 algorithm produces a 256 bit result. The algorithm was designed specifically so that going from a hash back to the original bytes is infeasible. Developers use an SHA2 hash so that instead of storing a plain text password, they instead only store the hash. When a user is authenticated, the plain text password they type into the login form is hashed, and because the algorithm will always produce the same hash result given the same input, comparing this hash to the hash in the database tells us the password is correct. Cracking Passwords While one-way hashing means we aren’t storing plain text passwords, it is still possible to determine the original plain text password from a hash. Next, we’ll outline the two most common approaches of reversing a hash. Lookup Tables The first is called a lookup table, or sometimes referred to as a rainbow table. This method builds a massive lookup table that maps hashes to plain text passwords. The table is built by simply hashing every possible password combination and storing it in some type of database or data-structure that allows for quick lookups. Here’s an example of a lookup table for SHA2 hashed passwords: sha2_hash password ----------------------------------------------------------------------------------------- e150a1ec81e8e93e1eae2c3a77e66ec6dbd6a3b460f89c1d08aecf422ee401a0 123456 e5d316bfd85b606e728017e9b6532e400f5f03e49a61bc9ef59ec2233e41015a broncosfan123 561acac680e997e22634a224df2c0931cf80b9f7c60102a4e12e059f87558232 Letmein bdc511ea9b88c90b75c3ebeeb990e4e7c813ee0d5716ab0431aa94e9d2b018d6 newenglandclamchowder 9515e65f46cb737cd8c191db2fd80bbd05686e5992b241e8ad7727510b7142e6 opensesame 6b3a55e0261b0304143f805a24924d0c1c44524821305f31d9277843b8a10f4e password c194ead20ad91d30c927a34e8c800cb9a13a7e445a3ffc77fed14176edc3c08f xboxjunkie42 Using a lookup table, all the attacker needs to know is the SHA2 hash of the password and they can see if it exists in the table. For example, let’s assume for a moment that Netflix stores your password using an SHA2 hash. If Netflix is breached, their user database is likely now available to anyone with a good internet connection and a torrent client. Even a mediocre hacker now only needs to lookup the SHA2 hash associated with your Netflix account to see if it exists in their lookup table. This will reveal nearly instantly what your plain text password is for Netflix. Now, this hacker can log in to your Netflix account and binge watch all four seasons of Fuller House (“how rude!”). And he can also try this password on Hulu and HBO Go to see if you used the same email address and password for those accounts as well. The best way to protect against this type of attack is to use what is called a salt. A salt is simply a bunch of random characters that you prepend to the password before it is hashed. Each password should have a different salt, which means that a lookup table is unlikely to have an entry for the combination of the salt and the password. This makes salts an ideal defense against lookup tables. Here’s an example of a salt and the resulting combination of the password and the salt which is then hashed: // Bad, no salt. Very bland. sha2("password") // 6b3a55e0261b0304143f805a24924d0c1c44524821305f31d9277843b8a10f4e // Better, add a salt. salt = ";L'-2!;+=#/5B)40/o-okOw8//3a" toHash = ";L'-2!;+=#/5B)40/o-okOw8//3apassword" sha2(toHash) // f534e6bf84a638112e07e69861927ab624c0217c0655e4d3be07659bcf6c1c07 Now that we have added the salt, the “password” that we actually generated the hash from was the String ;L'-2!;+=#/5B)40/o-okOw8//3apassword. This String is long, complex and contains a lot of random characters. Therefore, it is nearly impossible that the hacker that created the lookup table would have generated the hash for the String ;L'-2!;+=#/5B)40/o-okOw8//3apassword. Brute Force The second method that attackers use to crack passwords is called brute force cracking. This means that the attacker writes a computer program that can generate all possible combinations of characters that can be used for a password and then computes the hash for each combination. This program can also take a salt if the password was hashed with a salt. The attacker then runs the program until it generates a hash that is the same as the hash from the database. Here’s a simple Java program for cracking passwords. We left out some detail to keep the code short (such as all the possible password characters), but you get the idea. import org.apache.commons.codec.digest.DigestUtils; public class PasswordCrack { public static final char[] PASSWORD_CHARACTERS = new char[] {'a', 'b', 'c', 'd'}; public static void main(String... args) { String salt = args[0]; String hashFromDatabase = args[1].toUpperCase(); for (int i = 6; i <= 8; i++) { char[] ca = new char[i]; fillArrayHashAndCheck(ca, 0, salt, hashFromDatabase); } } private static void fillArrayHashAndCheck(char[] ca, int index, String salt, String hashFromDatabase) { for (int i = 0; i < PASSWORD_CHARACTERS.length; i++) { ca[index] = PASSWORD_CHARACTERS[i]; if (index < ca.length - 1) { fillArrayHashAndCheck(ca, index + 1, salt, hashFromDatabase); } else { String password = salt + new String(ca); String sha2Hex = DigestUtils.sha2Hex(password).toUpperCase(); if (sha2Hex.equals(hashFromDatabase)) { System.out.println("plain text password is [" + password + "]"); System.exit(0); } } } } } This program will generate all the possible passwords with lengths between 6 and 8 characters and then hash each one until it finds a match. This type of brute-force hacking takes time because of the number of possible combinations. Password complexity vs. computational power Let’s bust out our TI-85 calculators and see if we can figure out how long this program will take to run. For this example we will assume the passwords can only contain ASCII characters (uppercase, lowercase, digits, punctuation). This set is roughly 100 characters (this is rounded up to make the math easier to read). If we know that there are at least 6 characters and at most 8 characters in a password, then all the possible combinations can be represented by this expression: possiblePasswords = 100^8 + 100^7 + 100^6 The result of this expression is equal to 10,101,000,000,000,000. This is quite a large number, North of 10 quadrillion to be a little more precise, but what does it actually mean when it comes to our cracking program? This depends on the speed of the computer the cracking program is running on and how long it takes the computer to execute the SHA2 algorithm. The algorithm is the key component here because the rest of the program is extremely fast at creating the passwords. Here’s where things get dicey. If you run a quick Google search for “fastest bitcoin rig” you’ll see that these machines are rated in terms of the number of hashes they can perform per second. The bigger ones can be rated as high as 44 TH/s. That means it can generate 44 tera-hashes per second or 44,000,000,000,000. Now, if we divide the total number of passwords by the number of hashes we can generate per second, we are left with the total time it takes a Bitcoin rig to generate the hashes for all possible passwords. In our example above, this equates to: bitcoinRig = 4.4e13 possiblePasswords = 100^8 + 100^7 + 100^6 = 1.0101e16 numberOfSeconds = possiblePasswords / bitcoinRig = ~230 numberOfMinutes = numberOfSeconds / 60 = ~4 This means that using this example Bitcoin rig, we could generate all the hashes for a password between 6 and 8 characters in length in roughly 4 minutes. Feeling nervous yet? Let’s add one additional character and see long it takes to hash all possible passwords between 6 and 9 characters. bitcoinRig = 4.4e13 possiblePasswords = 100^9 + 100^8 + 100^7 + 100^6 = 1.010101E18 numberOfSeconds = possiblePasswords / bitcoinRig = 22,956 numberOfMinutes = numberOfSeconds / 60 = ~383 numberOfHours = numberOfMinutes / 60 = ~6 By adding one additional character to the potential length of the password we increased the total compute time from 4 minutes to 6 hours. This is nearing a 100x increase in computational time to use the brute force strategy. You probably can see where this is going. To defeat the brute force strategy, you simply need to make it improbable to calculate all possible password combinations. Let’s get crazy and make a jump to 16 characters: bitcoinRig = 4.4e13 possiblePasswords = 100^16 + 100^15 ... 100^7 + 100^6 = 1e32 numberOfSeconds = possiblePasswords / bitcoinRig = 2.27e18 numberOfMinutes = numberOfSeconds / 60 = 3.78e16 numberOfHours = numberOfMinutes / 60 = 630,000,000,000,000 or 630 trillion numberOfDays = numberOfHours / 24 = 26,250,000,000,000 or 26.25 trillion days numberOfYears = numberOfDays / 365 = 71,917,808,219 or 71.9 billion years To boil down our results, if we take these expressions and simplify them, we can build an equation that solves for any length password. numberOfSeconds = 100^lengthOfPassword / computeSpeed This equation shows that as the password length increases, the number of seconds to brute-force attack the password also increases since the computer’s speed to execute the hashing algorithm is a fixed divisor. The increase in password complexity (length and possible characters) is called entropy. As the entropy increases, the time required to brute-force attack a password also increases. What does all this math mean? Great question. Here’s the answer: If you allow the use of short passwords, which makes them easy to remember, you need to decrease the value of computeSpeedin order to maintain a level of security. If you require longer randomized passwords, such as those created by a password generator, you don’t need to change anything because the value of computeSpeedbecomes much less relevant. Let’s assume we are going to allow users to select short passwords. This means that we need to decrease the computeSpeed value which means we need to slow down the computation of the hash. How do we accomplish that? The way that the security industry has been solving this problem is by continuing to increase the algorithmic complexity, which in turn causes the computer to spend more time generating one-way hashes. Examples of these algorithms include BCrypt, SCrypt, PBKDF2, and others. These algorithms are specifically designed to cause the CPU/GPU of the computer to take an excessive amount of time generating a single hash. If we can reduce the computeSpeed value from 4.4e13 to something much smaller such as 1,000, our compute time for passwords between 6 and 8 characters long become much better. In other words, if we can slow down the computer so it takes longer for each hash it has to generate, we can increase the length of time it will take to calculate all of the possible passwords. computeSpeed = 1e3 possiblePasswords = 100^8 + 100^7 + 100^6 = 1.0101e16 numberOfSeconds = possiblePasswords / computeSpeed = 10,101,000,000,000 or 10.1 trillion numberOfMinutes = numberOfSeconds / 60 = 168,350,000,000 or 168.35 billion numberOfHours = numberOfMinutes / 60 = 2,805,833,333 or 2.8 billion numberOfDays = numberOfHours / 24 = 116,909,722 or 116.9 million numberOfYears = numberOfDays / 365 = 320,300 Not bad. By slowing down the hash computation, we have increased the time from 4 minutes using our Bitcoin rig to 320,300 years. In this comparision you can see the practical difference between using SHA2 and BCrypt. BCrypt is purpose built to be extremely slow in comparison to SHA2 and other more traditional hashing algorithms. And here lies the debate that the security industry has been having for years: Do we allow users to use short passwords and put the burden on the computer to generate hashes as slowly as reasonably still secure? Or do we force users to use long passwords and just use a fast hashing algorithm like SHA2 or SHA512? Some in the industry have argued that enough is enough with consuming massive amounts of CPU and GPU cycles simply computing hashes for passwords. By forcing users to use long passwords, we get back a lot of computing power and can reduce costs by shutting off the 42 servers we have to run to keep up with login volumes. Others claim that this is a bad idea for a variety of reasons including: - Humans don’t like change - The risk of simple algorithms like SHA2 is still too high - Simple algorithms might be currently vulnerable to attacks or new attacks might be discovered in the future At the time of this writing, there are still numerous simple algorithms that have not been attacked, meaning that no one has figured out a way to reduce the need to compute every possible hash. Therefore, it is still a safe assertion that using a simple algorithm on a long password is secure. How FusionAuth does it FusionAuth defaults to PBKDF2 with 24,000 iterations as the default password hashing scheme. This algorithm is quite complex and with the high number of iterations, it is sufficiently slow such that long and short passwords are challenging to brute force attack. Fusionauth also allow you to change the default algorithm as well as upgrade the algorithm for a user when they log in. This allows you to upgrade your applications password security over time. FusionAuth has you covered If you are looking for a solution lets you manage and configure password hashing algorithms,.
https://fusionauth.io/learn/expert-advice/security/math-of-password-hashing-algorithms-entropy/
CC-MAIN-2022-05
refinedweb
2,260
60.85
.io;51 52 import java.io.IOException ;53 import java.io.OutputStream ;54 55 /**56 * Data written to this stream is forwarded to a stream that has been associated57 * with this thread.58 *59 * @author <a HREF="mailto:peter at apache.org">Peter Donald</a>60 * @version $Revision: 1.4 $ $Date: 2003/03/22 12:46:24 $61 */62 public final class DemuxOutputStream63 extends OutputStream 64 {65 private final InheritableThreadLocal m_streams = new InheritableThreadLocal ();66 67 /**68 * Bind the specified stream to the current thread.69 *70 * @param output the stream to bind71 */72 public OutputStream bindStream( final OutputStream output )73 {74 final OutputStream stream = getStream();75 m_streams.set( output );76 return stream;77 }78 79 /**80 * Closes stream associated with current thread.81 *82 * @throws IOException if an error occurs83 */84 public void close()85 throws IOException 86 {87 final OutputStream output = getStream();88 if( null != output )89 {90 output.close();91 }92 }93 94 /**95 * Flushes stream associated with current thread.96 *97 * @throws IOException if an error occurs98 */99 public void flush()100 throws IOException 101 {102 final OutputStream output = getStream();103 if( null != output )104 {105 output.flush();106 }107 }108 109 /**110 * Writes byte to stream associated with current thread.111 *112 * @param ch the byte to write to stream113 * @throws IOException if an error occurs114 */115 public void write( final int ch )116 throws IOException 117 {118 final OutputStream output = getStream();119 if( null != output )120 {121 output.write( ch );122 }123 }124 125 /**126 * Utility method to retrieve stream bound to current thread (if any).127 */128 private OutputStream getStream()129 {130 return (OutputStream )m_streams.get();131 }132 }133 Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ |
http://kickjava.com/src/org/apache/avalon/excalibur/io/DemuxOutputStream.java.htm
CC-MAIN-2016-44
refinedweb
290
58.69
package WebService::HackerNews; $WebService::HackerNews::VERSION = '0.05'; use 5.006; use Moo; use JSON qw(decode_json); use WebService::HackerNews::Item; use WebService::HackerNews::User; has ua => ( is => 'ro', default => sub { require HTTP::Tiny; require IO::Socket::SSL; HTTP::Tiny->new; }, ); has base_url => ( is => 'ro', default => sub { '' }, ); my $get = sub { my ($self, $relpath) = @_; my $url = $self->base_url.'/'.$relpath; my $response = $self->ua->get($url); # This is a hack. Can I use JSON->allow_nonref to handle # the fact that maxitem returns an int rather than [ int ]? return $response->{content} =~ m!^\s*[{[]! ? decode_json($response->{content}) : $response->{content} ; }; sub top_story_ids { my $self = shift; my $result = $self->$get('topstories.json'); return @$result; } sub item { my $self = shift; my $id = shift; my $result = $self->$get("item/$id.json"); return WebService::HackerNews::Item->new($result); } sub user { my $self = shift; my $id = shift; my $result = $self->$get("user/$id.json"); return WebService::HackerNews::User->new($result); } sub max_item_id { my $self = shift; my $result = $self->$get('maxitem.json'); return $result; } sub changed_items_and_users { my $self = shift; my $result = $self->$get('updates.json'); return ($result->{items} || [], $result->{profiles} || []); } 1; =head1 NAME WebService::HackerNews - interface to the official HackerNews API =head1 SYNOPSIS use WebService::HackerNews; my $hn = WebService::HackerNews->new; my @top100 = $hn->top_story_ids; my $item = $hn->item( $top100[0] ); my $user = $hn->user($item->by); printf qq{"%s" by %s (karma: %d)\n}, $item->title, $item->by, $user->karma; =head1 DESCRIPTION This module provides an interface to the official L<Hacker News API|>. This is very much a lash-up at the moment, and liable to change. Feel free to hack on it and send me pull requests. It provides a semi object-oriented interface to the API. You start off by creating an instance of C<WebService::HackerNews>: $hn = WebService::HackerNews->new; You can then call one of the methods to either get information about I<items> or I<users>. An item is either a story, a job, a comment, a poll, or a pollopt. All items live in a single space, and are identified by a unique integer identifier, or B<id>. Given an id, you can get all information for the associated item using the C<item()> method. A user is like an item, but represents a registered user of HackerNews. The id for a user isn't an integer, but is a username. Given a username, you can get all information for the associated user with the C<user()> method. Items and User are represented with classes, but where the attributes of items and users relate to further items and classes, they are represented as references to arrays of ids, rather than returning references to arrays of other objects. =head1 METHODS As of version 0.02, this implements all of the functions listed in the official documentation for the API. =head2 top_story_ids Returns a list of ids for the current top 100 stories. my @ids = $hn->top_story_ids; You can then call C<item()> to get the details for specific items. =head2 item($ID) Takes an item id and returns an instance of L<WebService::HackerNews::Item>, which has attributes named exactly the same as the properties listed in the official doc. $item = $hn->item($id); printf "item %d has type %s\n", $item->id, $item->type; =head2 user($ID) Takes a user id and returns an instance of L<WebService::HackerNews::User>, which has attributes named exactly the same as the L<user properties|> listed in the official doc. $user = $hn->user($username); printf "user %s has %d karma\n", $user->id, $user->karma; =head2 max_item_id Returns the max item id. =head2 changed_items_and_users Returns two array references, which contain IDs for changed items and usernames for changed users: use WebService::HackerNews 0.02; my $hn = WebService::HackerNews->new; my ($items, $users) = $hn->changed_items_and_users; process_changed_items(@$items); process_changed_users(@$users); This method returns "recently changed items and users", without defining 'changed since when?'. If you want to track changes, you'd just have to poll on a regular basis. This method is really aimed at people using Firebase streaming API. This method was added in version 0.02, so you should specify that as the minimum version of the module, as above. =head1 SEE ALSO L<Blog post about the API|>. L<API Documentation|>. =head1 REPOSITORY L<> =head1 AUTHOR Neil Bowers E<lt>neilb@cpan.orgE<gt> =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2014 by Neil Bowers <neilb@cpan.org>. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut
https://metacpan.org/release/WebService-HackerNews/source/lib/WebService/HackerNews.pm
CC-MAIN-2020-50
refinedweb
761
55.24
Python wrapper for NVidia Cg Toolkit What is python-cg? python-cg is a Python wrapper for NVidia Cg Toolkit runtime. I’ve started it because I like Python, I like NVidia CG and I want to to do some computer game/3d graphicsprototyping and research. Also I still find C++ counterproductive as far as my needs are concerned and I don’t want to waste my time doing boring stuff. Programming in Python is fun. I know about some projects that were meant to bring CG to Python but as far as I know they’re history now. Project is hostead at GitHub:. What’s the state? The project is in very early development stage. Overview of what’s supported right now: - Cg contexts - creating - destroying - CgFX effects - creating from file - creating directly from source code - accessing effects` techniques and their passes - accessing effect parameters with their names, semantics and parameter-specific metadata (rows, columns etc.) - setting sampler parameters and most of numerical parameters What doesn’t work at the moment and there’s no plan to implement it: - everything that’s left (well, until I decide I need some of it or someone else does that) Requirements This project requires: - NVidia Cg Toolkit ≥ 3.0 - Python interpreter (+ development files): - 2.x ≥ 2.6, or - 3.x ≥ 3.2 - C and C++ compiler Python packages required to build and install python-cg: - Cython ≥ 0.18 - numpy To build documentation/run tests you also need: - Mock ≥ 1.0 - Nose ≥ 1.2 - Sphinx ~ 1.2 (development version) Documentation Pregenerated documentation can be found at. You can also build documentation all by yourself by calling: sphinx-build -b html docs docs/build/html Generated HTML files are placed in docs/build/html/ directory. Building To build the project in place, run: python setup.py build_ext --inplace Important information - This project works with OpenGL and OpenGL only - It uses row-major matrices by default, just like numpy does Quickstart First you need to create an instance of CG class and use it to create new Context: from cg import CG cg = CG() context = cg.create_context() We want to use an effect to render some stuff so we’re gonna create Effect from file: effect = context.create_effect_from_file('effect.cgfx') Note This assumes that you have a file named effect.cgfx and that it contains a valid CG effect. We now have access to Effect’s techniques and parameters: for technique in effect.techniques: # ... for parameter in effect.parameters: # ... For the sake of simplicity let’s say we have a parameterless effect with only one Technique: technique = effect.techniques[0] Now we can access technique’s passes. Each Pass has methods begin() and end() and the actual drawing has to take place between a call to begin and end: gl.glClear(gl.GL_COLOR_BUFFER_BIT) for pass_ in technique.passes: pass_.begin() gl.glBegin(gl.GL_TRIANGLES) gl.glVertex3f(-0.5, -0.5, 0) gl.glVertex3f(0.5, -0.5, 0) gl.glVertex3f(0, 0.5, 0) gl.glEnd() pass_.end() # swap buffers You can find complete, runnable example application in example directory. Please note that it requires (in addition to python-cg requirements): Development version of SFML 2 Python packages listed in example/requirements.txt: pip install -r example/requirements.txt Then to run the example: python setup.py build_ext --inplace PYTHONPATH=. python example/main.py Testing To run tests, execute: python runtests.py 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/python-cg/
CC-MAIN-2017-34
refinedweb
588
58.79
(see Resources) with my colleague Roxane Ouellet, so you no longer have to slog through the dense specifications to get a handle on it. With no further ado, I present listing 1, the complete RDFS for the issue tracker. Listing 1. RDFS schema for the issue tracker You will note some changes, including changes to the namespaces used. These, unfortunately, are not as blithely accounted for as the fact that our earlier RDF examples did not use any defined classes. This schema represents what is currently being used for the issue tracker for RDFInference.org, including changes that have been made for various reasons. I'll present corresponding updates to the instance RDF below. I also adopt some lexical conventions: First of all, I define all the namespace URIs as entities in the DTD internal subset (a convention I learned from Ms. Ouellet), which reduces error and improves readability. Then, I only use rdf:about, never rdf:ID, a convention I recently adopted after hard experience with all the pitfalls associated with resolving IDs against the supposed URI of the containing document. Note that I use rdf:ID only when I can ensure that there is an explicit xml:base declaration, and that all RDF processors for which interoperability is needed support XML base. The Catalog class provides a way to aggregate all resources that have an issue, or for which users are allowed to create issues. This is mostly an application convenience. Imagine a Web-based form for the tracker. It would probably have a drop-down selection box for the resources of interest. One way to populate that list is to check for all the objects of dc:relation statements from a given catalog. The DAML+OIL schema I'm about to present illustrates another approach. There are a few other small changes, such as the renaming from "assigned-to" to "assignee" for more consistent use of parts of speech. Otherwise, there are no surprises in this schema, so let's move on to a look at the DAML+OIL version. DAML+OIL is a schema system that provides key improvements over RDFS, including a built-in data typing system, support for enumerations, specializations on properties, and classification and typing by inference. It also goes beyond mere schematics to allow us to define ontologies, which are meant to be approximations of how we hold concepts, but for now we shall be mostly using the basic schematic features. Listing 2 is a DAML+OIL schema for the issue tracker similar to Listing 1. Listing 2. DAML+OIL schema for the issue tracker Before any definitions comes the ontology header. This is a DAML convention that describes the document and specifies the schema (hence the empty rdf:about, which sets the document itself as the subject). It features a revision statement, which I define using a keyword to be expanded by the revision-control system. It also features an import, which is an explicit mechanism added by DAML+OIL for incorporating definitions from other files into the current one (before DAML, you either had to merge multiple sources into a model, or use a lower-level mechanism such as XInclude). As standard practice, I import the core DAML+OIL schema, adding definitions for DAML+OIL-specific resources. Next comes a special class, RelevantResource, whose instances are not stated explicitly, but which is defined by inference on the properties of instances. A closer look at the RelevantResource class should make this clear. It is defined as a subclass of an anonymous in-line resource, which in turn is of type daml:Restriction. This is a special DAML+OIL mechanism that allows you to define rules according to the properties instances have, and the values of those properties. In this case, the restriction selects all resources that have an issue property where the value of that property is of class Issue. By its subclassing from this restriction, the RelevantResource class is a sort of virtual class that includes a set of all resources that meet the restriction. If at any time a resource acquires the right property with a value of the right class, it automatically becomes a member of this virtual class, without needing to be explicitly stated as such. Please note that part of this restriction is strictly unnecessary. The range of the issue resource has already been constrained to class Issue by an rdfs:range statement. I left the toclass in the DAML restriction purely for illustration. This is a very important facility to have when you may not have control over all of the information space over which you are operating, and this is why DAML+OIL is put forth as a big step forward in the sort of technology that would be needed to underpin the Semantic Web. In our more modest case, this facility allows us to not have all resources explicitly registered for issue tracking, as we do in the RDFS form of the schema (using the Catalog class). I define all classes using daml:Class, which is a subclass of rdfs:Class That provides all the additional facilities introduced by DAML. Similarly, I use daml:ObjectProperty to define properties. The issue tracker schema does not use particular data types (string, integer, etc.) to define the value of any property, but as a note, such properties are defined in DAML+OIL as being subclasses of daml:DatatypeProperty. The DAML+OIL schema is actually what is being used in RDFInference.org applications, and is what we'll use as the basis of continuing work in this column. Because of the changes I've noted, I have revisited and updated the sample instances of issues that we've been looking at so far in this column -- see Listing 3. Listing 3. Updated instance data We define a resource against which the sample issues are raised. According to the DAML+OIL schema, is automatically a member of the RelevantResource class. The other significant change is that we refer to people through mailto URLs, which are then linked to their regular names using "friend of a friend" (FOAF), a well-known DAML+OIL schema for specifying information about individual contacts, suitable for describing who might be attached to an electronic mailbox. Note that there is another well-known choice for modeling contact information in RDF, based on the common vCard format for embedding contact information as e-mail attachments. The vCard RDF schema is more general in coverage than the FOAF schema, but we don't need its additional properties. And if we did, there is also a FOAF-based option: FOAFCorp, which adds elements related to corporate structure to the core personal profile information in FOAF. The changes to the XSLT that generate this form rather than the original are minor -- mostly the changing of literal result element names and namespace UR. - In addition to the introductory resources I listed in the last installment, there is now Introduction to DAML: Part I, by Roxane Ouellet and Uche Ogbuji. - Here's the "friend of a friend" (FOAF) schema for managing personal profile information. There is also FOAFCorp, which adds more detail for expressing the structure of corporate entities. - Representing vCard Objects in RDF/XML is a W3C note by Renato Iannella. > him at uche@ogbuji.net.
https://www.ibm.com/developerworks/xml/library/x-think9.html
CC-MAIN-2020-16
refinedweb
1,217
51.07
Important: Please read the Qt Code of Conduct - How To Call Qt/C++ OSX Dylib from Objective C From Objective C, how do I load a dynamic link library (OSX calls these dylib files) class method? Also, will it let me do something like show the Finder Choose File window under this unusual context from the Qt dylib? The reason I ask is that I like the ease of coding of Qt/C++ far more than Objective C. I built a minimalist Cocoa app in Objective C only so that I could utilize the native webkit of OSX, and then learned the technique to insert Javascript into it, and then have that call a class method in Objective C. The end goal would be that I click a button like "Choose File" in the webkit, it then calls the Javascript handler for that, which then calls my "cpp" object in Javascript, which calls the Objective C class method, which then calls the Qt/C++ class method, which then calls the API fo show the Finder's Choose File window, and then returns a result back. I've managed to get the Javascript working to call an Objective C class method just fine -- but then don't know the technique to call the Qt/C++ dylib's class method from there. Hi, You can use Objective-C++. Then you can go on and use the usual stuff in C++ and link the libraries to your application. @SGaist It didn't seem to work. Here's what I did: Created a shared dynamic link Dylib in Qt/C++ named libtestlib.1.0.0. The class name is Testlib. It had a test()class method inside that received string input and tacked on '-response', and returned that result back. I compiled it okay. Created an Objective C Cocoa-based application using the defaults. Added my testlib.hfile to my ObjC project. Added my binary dylib file to my ObjC project. In my main.mfile, did: #import "testlib.h"; - In my main.mfile's main()function, I tried to do: Testlib *o = new Testlib(); NSLog(@"Result=%@",o->test('request')); However, ObjC complains about the first line in step #6 and says: Use of undeclared identifier: o Unknown type name: Testlib Someone in a forum suggested I rename the .mto a .mmfile, but that didn't work. Someone else suggested renaming the .hto an .hppfile, but that didn't work either. Do you have that sample project available somewhere ? @SGaist Inside are 2 zips: Testlib - the Qt/C++ Dylib for OSX Sample - the Objective C app for OSX that tries to load Testlib The ObjC project won't compile. In main.m, you can see where I'm trying to load the testlib.h and then call TestLib's test class method. I'm quite surprised that no one has posted on the web how to make this bridge possible between ObjC to Qt/C++. @SGaist This seems pretty daunting -- trying to get much of the Qt framework to load for a dylib inside Objective C. Perhaps a better approach would be to just create a .mmfile in my project, create an ordinary C++ class there, and use these classes to make my life a bit easier: #include <string> #include <stdio.h> #include <sqlite3.h> #include <Foundation/Foundation.h> And then instead of using Qt, do it all using C++ with string, stdio (noting this), the sqlite3 library for C++ which comes with Macs when you install XCode, and the Apple Foundation classes. Also, so that one doesn't have to pass std::string and convert it, here's the funky way to pass NSString between Objective C++ (loaded in XCode) and Objective C in a .mmfile which lets you combine both C++ and Objective C: class Testlib { public: NS_RETURNS_RETAINED NSString *test(NSString *sIn) { // note the [[super funky Objective C syntax]] NSString *sOut = [[NSString alloc] init]; sOut = [NSString stringWithFormat:@"%@-response", sIn]; return sOut; } } Depending on what you would like that library to do, then indeed it might be overkill to pull Qt in. What should that library do (I take it the sample is not implementing the final stuff) ? @SGaist Some things I needed on this project: Didn't like the limitations of QML and Qt Widgets. QML was hard to use compared with just HTML and Javascript. I kept wondering why bother with QML when I could just use WebKit. Qt Widgets really required subclassing and paint intercepts to take it where I needed to take it. For instance -- imagine a table widget and you want a select all checkbox in column 1 -- not so easy. So, I used the embedded WebKit that comes with Qt 5.5. However, by doing so, I added 30MB more to the project. I got a powerful GUI just the way I wanted it, but at the expense of 30MB more in download size. Thus, I had to make a custom setup for it so that I could make a small installer download and say "Installing..." and other messages and progress bar updates while it downloaded the larger framework and installed it. But that was kind of a kludge when I could have used native webkit. Qt 5.5 has a tech preview of the native webkit. However, that is just that -- a tech preview. It had lots of problems, such as not able to show a SELECT popdown listbox that works, and many other issues. I prefer Qt's coding environment a whole lot more than Objective C. So, I thought I'd draw only the GUI in Objective C because then I could use a native webkit. I was going to make it simple -- just a window, menu, and the rest is all in the webkit widget. I found that there's a bridge in Objective C as well to make it such that Javascript can call an Objective C class method. However, trying to build most of the business logic of my application in Qt/C++ was going to be hard to include as a dylib inside Objective C because, well, it's super hard to set all the right settings in Objective C to make it load the right libraries and compiler tricks, as well as have the issue of string transfer from one framework to another. Plus, even if I managed to get it all working -- it would increase project size by around 10MB. It would be bundling two frameworks (Objective C and Qt) instead of one. These are the things my business logic needs to do: - connect over HTTP to a server with a REST-like request - parse strings - file I/O - SQLite database interaction - settings save/load - launch a particular browser (telling ObjC to do it) for in-app upgrade purchase - get the user's language (telling ObjC to do it) - get default paths and username for the given user (telling ObjcC to do it) So, I then realized that I can get all that with C++ inside Objective C and XCode as long as I include some extra libraries and rename my .mfile to .mmso that I can bridge ObjC to C++ and back. All this -- simply because Qt 5.5 doesn't have a fully working native webkit yet, and because 5.6 looks like they don't want to do that either -- they're talking about using Blink. The makers of Qt don't realize that they're increasing the application size dramatically on OSX with this strategy. What about QMacCocoaViewContainer ?
https://forum.qt.io/topic/61451/how-to-call-qt-c-osx-dylib-from-objective-c/10
CC-MAIN-2021-31
refinedweb
1,253
78.59
June 2, 2009 I got a photo radar ticket today for doing 36 in a 30. That's so not cool. "There is something fundamentally unfair about a government that takes away so much of people's money, power, and personal control while telling them that life will be better as a result." - Steve Forbes "Every generation needs a new revolution" - Thomas Jefferson "Big Brother is watching you" - George Orwell Posted by blogger at Tuesday, June 02, 2009 65 comments: Classic! that is 20% over the speed limit, speed racer. Hey Mario Andretti, what did it cost you? How do you like living in the testing grounds for the New World Order police state, Keith? Now I remember why I didn't want a car over here 6 that's a flipping rounding error I was too busy trying not to hit cars coming on my right on streets that don't fit two cars across to look at the speedometer I'm in favor of domestic terrorism against all speed cameras btw Got a photo radar ticket? You can fight it. Visit I'm in favor of domestic terrorism against all speed cameras btwDomestic terrorism is a crock of shit. Look at the details of every case - not just the media hype headlines - and it always turns out to be a bunch of incompetent borderline retarded street criminals who have been provocateured by an FBI informer. All the way back to the first bombing of the WTC it's the same story. Look at 7/7 too. Just like 9/11 there were drills running at the exact same time simulating the exact same scenario. Quite a coincidence. Domestic terrorism is a sham invented by the intelligence agencies to justify more control over society. Oh man Keith, statements like that will get you on the No Fly list for sure. Big Brother IS watching. Keefer, I've been saying here all along a very large part of our current situation is due to the 'Eurotard' infulence that has been creepiing in via the internet. Die Europe! Yeah, nice going Obama. That's some f*cking CHANGE!! Government Retroactively Changes the Law to Legalize it's Illegal Behavior in Torture Photos. So there you go. Another example of Obama covering Dubya's criminal ass. Just like FISA. "But it's for national security. For your own protection" F*cking criminals. -Gonzo "keith said... Now I remember why I didn't want a car over here 6 that's a flipping rounding error" Rounding Error? YOU should be working for Bernanke and Geithner doling out TARP funds. Rounding Error? I think NOT. Boo Ho Hoo. Keefer said: "I'm in favor of domestic terrorism against all speed cameras btw" I beleive we all are. Actually, speed cameras is the way things should be. It means cops can actually do something we citizens like to call...oh I don't know..."police work" and "criminal investigations". In state's like mine (California), where they're about the empty the prisons because state salaries and pensions have crushed the state's budget and ruined it's ability to govern, I actually wish they'd install MORE speed cameras, LESS speeders in SUV's trying to kill my family and yours, raise MORE state and municipal revenues. We need cops doing what they're supposed to be doing: fighting and investigating crime. We don't need Cops parked on the roadways, eating Krispy Kreme donuts, drinking coffee and listening to Rush Limbaugh waiting for a speed merchant like Keith to drive by. i bet the fine is some big money but be glad your not a taxpayer who bought the road and getting a fine given to the neo neo russian mafia.... er..... government..... Photo Radar popping up like mushrooms in Phoenix and the rest of Arizona as the state faces a total financial blow out Don't forget to check in at AZCENTRAL now and then. Your former hometown is getting into deeper doo doo by the day. On an article today someone posted this. I sounds like you. Arizona is as always whoring herself out to imvestors....hahahaha Home prices up ! (NOT) This poster must be an HP SA reader ! "Don't believe the hype. We have had about 90,000 foreclosures in the Phoenix area fro 2005 until now. There are another 50,000 foreclosures coming in the next 90 days. This will leave about 500,000 homeowners owing more on their homes than they are worth. There are huge pools of loans left to reset, including pay option arms and the HUGE pool that no one talks about - Fannie Mae 30 year fixed interest only. Because it's a fixed rate, it flies under the radar, but the reality is that after the 10 year interest only period, this loan recasts to a 20 year mortgage which will increase the payment 35%. It doesn't mean that now can't be a good time to buy, but just because it's cheaper than before doesn't mean it's a good deal. Proceed with caution." Last year I was disembarking a cruise ship after my vacation. The Customs officer kindly informed me that there was a warrant out for my arrest in New Mexico. I asked him what for - after being escorted to secondary they told me it was for not paying a speeding ticket from 16 YEARS AGO. Hitler's SA would be jealous to have such an efficient operation. I assume that KPH? In which case you were only doing 3.6 MPH over the limit. That's harsh. I don't object to speed cameras and red light cameras in general, though. And they ought to add tailgating cameras, if it can be worked out. Keith, That sucks! What is your call on the Cramer housing bottom call? Like I posted yesterday, I am confused which was housing will go since inventories seem to be dropping but delinquencies are still increasing. New article: Keith, thanks for finally addressing this issue. I am a member of the group Camerafraud in Phoenix. I also run their twitter page. Reflex Traffic Solutions just signed a contract with Phoenix that allows them to ticket people for "secondary violations" caught on film (that's right, those cameras are shooting video) like eating, using a cell phone or having a cracked windshield. Does anyone really think this is about safety. What part of "illegal" don't you understand? Don't pay it and see what happens. Let's test their computer system integration. Same thing happened to me - 36kph in a 30kph zone = 21.6mph in an 18mph zone. Actually, I agree with Markus - I think speed cameras are a great idea. But I think the tolerance (<4mph) is a little too tight. Speed cameras will be installed statewide in Maryland beginning in October of this year. Up until now, they were just in Montgomery County. Thanks, Maryland General Assembly! A referendum to take the issue out of the hands of the legislature failed by fewer than 2,000 signatures. Marylanders are about 80% against these cameras, but they lack the intitiative to inform themselves, to take action by signing a referendum petition, or to vote in representatives who are responsive to their wishes. Come October, everyone will be bellyaching about this. It will make everyone's lives miserable, and it will be richly deserved. But I guess it's all for the best. I mean, it's for the chlidren, right? Besides, why would you object to government cameras on every street corner unless you have something to hide? The government is protecting you, you should be very grateful. Here in Scottsdale, we have these red arrows that light up when the light turns green so that nobody can turn left until the red arrow becomes a green arrow. If you dare turn left against one of these red arrows - oh man, they will find you and make you pay. So I sit and sit and sit at my red arrows. Lots of times there is no oncoming car to be seen for miles and miles and I feel like a tool for sitting there like a buffoon not going. I know that the government loves me and is the angel on my shoulder protecting me and I feel much better and don't give my lost freedom a second thought. Keith, Your wealth must be extracted to keep you in servitude. With inflation and taxes it is impossible for the surf pawn to overcome... Property taxes sales taxes income taxes gas taxes fishing and hunting taxes hotel taxes tobacco and alcohol taxes road toll taxes dmv taxes pet licence taxes 911 taxes inheritance taxes import taxes building permit taxes business licence taxes fines and traffic tickets Welcome to servitude, a new brand of slavery that comes with the illusion of freedom. How will you pay the ticket sir? Will you be using the paper dollars we control you with? We prefer your credit card... and by the way, you are in the wrong line. Phoenix has photo radar vans all over the place. It's an awesome adrenaline rush when you are driving along and the guy in front of you slams on his brakes as though a helpless child just ran into the road trying to save his kitty cat all to find out that your life flashed in front of your eyes because the guy was doing 5MPH over the speed limit and freaked out when he saw the van appear from behind a tree. Traffic is way safer for sure now. More then 10% of Texans have outstanding arrest warrants. Mostly traffic fines, it is really a tax - Think of it as an involuntary lottery. About a year ago, I got a 29.00 parking ticket down at ASU on a Saturday because I stupidly thought that the parking meters were enforced only during the week when classes were going on. Nope! Apparantly the Nazis patrol Saturdays too (but not Sunday of course). The street that I parked on was completely empty, but those tax collectors working for the Tempe police found me quickly and snared me. And I paid too. Government knows how to get paid. Dont get mad Keith. That's common the US, that's ok. Wait until you get pulled over just cause your hispanic or black and hit with a few tickets that are completely made up (out of thin air). Now... that hurts my friend. Especially when the tickets add up to $500-600 bucks. It's all common practice. Notice that not many of us move either south or midwest US. We stay in the coast that way we can at least head to the Atlantic and go back home. Hehehehe. Dny Kieth you are f'ing schizo. You cannot, on the one hand, be a supporter of Obama and his asinine social policies, and then on the other hand, lambaste government control and call for its overthrow. Kieth, Welcome to the NWO. RayNLA OMG, enforcement of laws. How awful! Personally I say that most speed limits should be increased, but breaking them AT ALL should be a serious crime. Punishable to the point where one would choose to drive a solid 5 mph under to account for "rounding error". Speeders are a menace to law-abiding citizens and need to be removed from the road. There's women and children out there you know. Markus Arelius said... "Actually, speed cameras is the way things should be." Yeah, throw out any common sense or due process, makes things more efficient. "It means cops can actually do something we citizens like to call...oh I don't know..."police work" and "criminal investigations"" Actually a lot of crimes are found in the course of traffic work. You know, someone has a burned out tailight or not wearing a seatbelt, only to find out they have warrants on them. "LESS speeders in SUV's trying to kill my family and yours" Speed limits are set artificially low, particularly on highways so as to create revenue. Speed limits are set by stupid politicians, not traffic engineers. Traffic engineers recommend the speed limit to be at the 85 percentile speed, round up to the nearest 5mph interval. The autobahn has no speed limits in a lot of places and is the safest highway in the world. Most accidents occur in city driving because of failure to yield, running a red light, following to close, etc. Actually, speed cameras is the way things should. 6 mph is a rounding error? go argue that in court. turbotax timmy's tax error was just a rounding error too..... hey, that sounds like the title of a children's book: "turbotax timmy's tax error" Just wait till you're arrested and tased for having a Ron Paul bumper sticker on your car. Good to see the UK believes in the rule of law! Out here in California if you are a member of government you can get a license plate that comes back with no information. The police and companies running the cameras know not to issue tickets. Quite a racket, no? Great Idea Anon...Children's books for our time... Turbotax Timmy's Tax Error Forget Jesus, Obama Loves You! Enhanced 'In Bed on Time' Techniques Diaper Change You Can Believe In (No sh#t) Helicopters and Funny Money The BIG Book of Crooks (2009) I SPY Bubbles & Troubles Keith, the Speed Demon Dog (a pop up book) . Believe it or not I got a speeding ticket in Albuquerque, New Mexico 56 in a 55 !!!!!!!! NO SHIT . I got a ticket while parked at LAX for not having a front license plate. I've driving around for years without, cops looked right at my and kept going. I'm all for photo tickets and cameras at every intersection. Why? So that liability can be more easily assessed with regards to auto collisions. There are plenty of twisty rural roads where you can push the limit a bit and have a bit of fun. You want serious speed...pay for a day at the racetrack. It may be expensive but it's much cheaper than the fine AND the increased insurance premiums. Face it Keith. You got caught and now you're whining. If I can drive a Porsche 911 responsibly you should be able to drive your much slower vehicle in the same manner. Fuck. Now I'll probably get a ticket soon. Cops hate 911's But if you stole billions you would be heralded. That's also so Australian, Keith. Speed cameras and red light cameras are all over here. (After a few tickets, we found out which roads/intersections have those, and now we avoid them.) There are pigs with mobile vans with radar guns, especially in school zones in the morning. If you're a "hoon" (Aussie slang for wild hot-rodder) the police can confiscate your car and crush it at the scrap yard. Then there's the booze and drus buses. On weekend nights, and sometimes weekdays, the cops will block off main roads and pull over thousands of cars to breathalyse you for booze and rub a swab around your mouth to see if you've been smoking pot or meth. (Last result I saw in the paper from one near where we live -- 3,400 people tested; 19 nailed for booze, three for drugs. Massive, expensive effort, about a 2/3 of 1% bust rate. Waste of fucking money, IMHO, but it keeps the people terrorised and under control.) There's a section of the high-speed highway that runs north from our town to Sydney that has a set of speed cameras about 15 K outside city limits, and another set 30 K away. Not only does it write you a ticket if you're over the limit (110 kph) as you run through the cameras. It will also compare the time you passed through one set of cameras to when you passed through the second set, and if it calculates you were driving too fast EVEN WHEN YOU SLOWED DOWN AS YOU PASSED THROUGH THE CAMERAS! it will send you a ticket. Mrs. Bukko and I usually stop at a roadside park and smoke a bowl in between to get our timing right, then speed on. Fuck you pig bastards! In Tasmania, they're testing a technology that photographs the licence plate of every car that passes by. This will be instantly matched to a database to see if the person the car is registered to has not paid their insurance, or has parking fines or any other warrant outstanding. If it flags you, you'll be chased down by cop cars. As preston wrote, Mish had a good post on the Texas traffic fine situation. It's a worldwide phenomenon. The hand of the state is trying to squeeze everyone. It will wind up making most of the population into outlaws, people who are always subject to arrest if the authorities decide to reel them in. I don't like "Atlas Shrugged" but one valid point I remember is that an agent of the oppressive government said that they made all sorts of laws, not with the expectation that they would be obeyed, but so they could use those laws to arrest anyone they chose to. That's where the world is headed. While I like socialism, which involves an element of government control, I don't like authoritarianism. What America, and Australia, and England, is doing, is authoritarian. It's designed to extort money from anyone who drives. It's like what happens in the former Soviet bloc, where traffic cops routinely flag you down, make up some bullshit infraction and extract a bribe from you. (Beware of that if you drive in Eastern Europe this summer.) I'm on the Left, but I agree with many of your right-wing commenters on this: The government is the enemy of the people on this. ................................ EVERY speedometer has a 2 to 5% error in accuracy minimum you will have this progression from engineering to development , manufacture, assembly, installation, also wear and tear. Not to mention dramatic tire size changes, or axle ratio changes Keith, I have been telling you and the rest of the folks here that the UK has set up the most pervasive tracking and surveillance society the world has ever seen, and probably ever will see. They have become fascists. I can hear Orwell screaming at the top of his lungs an ocean away. They are exporting their tracking filth all over the world. Australia is doing the same with a company called Redflex, particularly in AZ. In fact, I read an article recently where some Arizonan got so pissed off he actually shot to death one of the Redflex employees in his speed trap van. The UK though, takes the cake. They will soon be setting up a variable speed camera system to catch people who slow down for one camera and then speed up until they come to the next one. Everything thing the Brits do will be tracked and stored. Total control by the fascists. That's what they are...fascists. They have become fascists under the Labor Party (a/k/a as Socialists). Jacqui Smith, who just resigned for various reasons, was one of the chief architects of the UK surveillance system. Perhaps now that she's gone things might change; but now that tracking has been set up there, you know have to fight an entrenched system...very hard to do. Get out of the UK while you can. This is what is in store for America with Obama. For the poster who said there should be gps and a chip to record everyone's speed, you are right on the money. Don't think the Socialists and Big Biz are not working towards that. They are. The plan is to first require gps and a chip to record the number of miles driven so that you will pay tax, by the mile, everytime you fill up. All gas pumps will be equipped with RFID readers that will do this. This has already been through a trial in Oregon and a couple of other states. Massachusetts and other Blue states are thinking of the same (it figures). Once they get that tech in our cars they will simply track us everywhere and monitor our speed, fining us on a continuously electronic basis. They will also keep a database of our whereabouts . Everyone has to take this seriously. This is the way things are going. Socialists/Fascists know no bounds for the thirst for control. If there's something out there that they can use to control people, systems, processes, institutions, business, govt. etc., they will embrace it and impose it. And once they can track our whereabouts 24/7 (they will soon put gps and rfid in our licenses too), they will effectively have controlled us for good. Everyone must see the warning signs of what the fascist UK is doing and what it means to the world; to free people everywhere. Tracking and surveillance is antithetical to Americanism. Don't Tread on." Good idea! They should also have a microphone and camera in each car. $10 for picking your nose, $20 for talking on the cell phone, etc. if you say anything bad about the government you get electricuted next time you try to gas up. Latvia crashing down in flames - 50% real-estate down in one year how is Europe , Keith ? :) Anyone silly enough to drive a car w/ a right side steering wheel deserves a big fat ticket. :) Anton Chiguhr Got a ticket for $120 that I fought and won. Administrative fee - $100. WTF??? To all that agree with speed camera taxation on the grounds of safety; look up the deaths per passenger/mile statistic for the Autobahn verses the US highway system. BTW, In the USA you do have the right to face your accuser, and I'm fairly certain heresay testimony originating from a machine is inadmissable...otherwise it's a seriously slippery slope from here. I liked it much better in the days of the feud and the vendetta. Those where the days! Now I get fined for returning a library book a week late, BAH! Obammy is going 174 mph , so you're not alone :) Obammy, 100 milions for us pls: The autobahn has no speed limits in a lot of places and is the safest highway in the world. ------------------------------- perhaps, but when there is a accident it is usually very spectacular and deadly. In other automotive news from the NY Times: Chinese Company Buying G.M.’s Hummer Brand “The Hummer brand is synonymous with adventure, freedom and exhilaration, and we plan to continue that heritage by investing in the business . . .” Yang Yi, the chief executive of Tengzhong, said in a statement released by G.M. !!! Want to know where it's all heading? Go to Then be afraid, be very afraid. Our rights are already gone. !!!. LOL exactly what I thought when I heard the news. Any time one of those Hummers goes by you know the driver is compensating for something! Tengzhong understands the market. They looked at the US car market and thought which car would best suit the average Chinese male with a 2-inch penis? Oh the Hummer the car that is most popular with the 2-inch penis demographic in the USA. Bwhahahaha! Bukko, In the US there are random drug testing laws - laws that I totally disagree with - but nevertheless I was subjected to these tests from time to time since I was the Director of Quality Assurance in a medical device manufacturer (ironically an Australian company HQ'd in the US). I'd imagine a nurse would be subjected to these laws. Do you have that in Australia or is it considered an invasion of privacy? -Mike Mike -- I've never been subjected to a drug test here, not even when I got hired, and especially not at random. That's one of the benefits of having a union. Unions make sure that bosses cannot subject you to harrassment like "Pee in this bottle NOW!" In the U.S., if I was to ge hurt on the job, I'd have to provide a urine spec so the company could try to deny any Workman's Comp on the grounds that I hurt myself because I was messed up. None of that here. Train drivers and people whose jobs might harm lots of people if they were high can be random tested, and if there's grounds to suspect that nurses were under the influence, they can be tested too. But overall, Aussies are judged on their performance and behaviour, the way it USED to be in the U.S. If you're a fuck-up at work, then sure, your arse should be sacked. But letting the boss man reach into your bladder, that's wrong. Too bad the police state that the U.S. has become doesn't recognise that any more. (FWIW, I make sure to NEVER do anything that might alter my consciousness before I come to work, because I take seriously the fact that I've got peoples' lives in my hands. Besides, who'd want to waste a good time at work?) Gee, sorry about the ticket, but if it gets you to post clips from Fight Club, it can't be all a bad thing. Recently, I was on the highway when a cop passed me at high speed. About 2 miles down the road, I see him off to the side with his radar gun out, he ended up getting a car just in front of me. So in other words, they guy drove like hell so that he could get to his hiding spot so that he could ticket people for speeding. Oh the hippocracy! boo hoo Smug Bastard you'll excuse my lack of compassion for your speeding ticket - some idiot not looking, making a roll/stop and in a hurry made a left turn against traffic directly in my path while on my motorcycle. The Smug Bastard went to the hospital and the Kingpin went into the shop - still waiting to see if it is a total loss or not. Genius doctor at the hospital clears me off the backboard after telling me what I already knew - (back and neck not broken). Sits me in a frickin' wheelchair for five hours in the waiting room with the uninsured scum of the earth - after five hours and still no one sees me and nurses tell me that several other people are to be seen before me, I go to the can, clean the blood off my face, do a self-examination and decide that nothing seems broken. Go to the nurse's station and ask if the will call me a cab so I can get the hell out of Dodge. Says it is against hospital policy? I guess sticking motorcycle/auto accident victims in the waiting room for hours on end is o.k. but calling them a cab is prohibited??? WTF - go figure??? Call the cab myself, go home and am now almost healed up. All this bullsh*t because some dumb ass who was probably yakking it up on their cell phone was in a frickin' hurry. As a p.s. - judging from what I saw straggling into the emergency room - this country is chock full of princess hypochondriacs. Smug Bastard From today! Speed Cameras Coming to US! wrong tiny url link in my last post. can't find the article now on AOL; they took it down.
http://sootandashes.blogspot.com/2009/06/i-got-photo-radar-ticket-today-for.html
CC-MAIN-2017-47
refinedweb
4,659
73.17
Debugging and Tracing in ASP.NET (4/4) Debugging and Tracing in ASP.NET Tracing The most important class for tracing is System.Diagostics.Trace. The Trace class has the same methods and properties as the Debug class except that its methods have the Conditional attribute of TRACE. In Visual Studio .NET TRACE is defined in both debug and release builds by default. So the methods of the Trace class are always executed by default. So this class should be used only when we always want the output. As with Debug, trace output goes to all listeners that are registered with the Trace class. The same listeners that are used for Debug can be used for Trace. The only other difference is that while Debug has a binary nature of either being on or off, Trace should be used in a multilevel hierarchy. To do this a switch called TraceSwitch is defined. This is similar to the BooleanSwitch class except that it has a level property that can have five values defined in the TraceLevel enumeration. Combined with the TraceSwitch class Trace can be used to provide flexible tracing of applications as shown below. // Create a TraceSwitch. static TraceSwitch traceSwitch = new TraceSwitch("trace", "Application"); static public void TraceOutput() { // Verbose Tracing. if(traceSwitch.TraceVerbose) { Trace.Write("Trace Output - Verbose"); } // Error Tracing if(traceSwitch.TraceError) { Trace.WriteLine("Trace Output - Error"); } } As always, though the switches, levels and listeners can be defined in code, they should be defined in the application's config file so that they can be changed whenever necessary without recompilation. Conclusion The System.Diagnostics namespace provides useful classes for debugging applications. These become important specifically while writing server side applications where IDE debuggers are difficult to use. These classes provide extensive debugging, tracing, event logging and performance monitoring features. About the Author Utpal Chakraborty is Manager, Software Engineering at Organic (). He has extensive experience in developing enterprise applications using Microsoft and non-Microsoft technologies. He can be reached at uchakraborty@organic.com. Created: December 4, 2002 Revised: December 4, 2002 URL:
http://www.webreference.com/programming/asp/debugging/4.html
CC-MAIN-2013-48
refinedweb
342
50.43
I'm constantly surprised by the number of developers who aren't aware of this handy piece of syntax. It's my favourite thing to come out of C# 2.0 and no developer should be without it. Like the conditional (?:) operator's big brother... introducing it for your coding pleasure... ?:. Let's jump straight to some examples: if ?? null //: null //: null ViewState // try to assign ViewState value as an int, else if null assign 123 int foo = (int?)ViewState["foo"] ?? 123; Response.Write("The value of foo is " + foo + "."); Input: ViewState["foo"]=1; Output: The value of foo is 1. Input: ViewState["foo"]=null; Output: The value of foo is 123. And my personal favorite, on demand field instantiation: private IList<string> foo; public IList<string> Foo { get { return foo ?? (foo = new List<string>()); } } Here's an interesting example derived from an idea in the discussions below. It shows how an operator override can be used within an object's definition to enable shorthand syntax for double-null checking. The scenario is checking an object property for null using a null-coalescing-operator, but also defaulting when null-object-reference occurs; which would normally cause a runtime exception. (Note that I don't recommend actually using this approach, I just thought it made an interesting example.) public class Address { private static Address Empty = new Address(); public string StreetName = null; public static Address operator +(Address address) { return address ?? Empty } } Console.WriteLine("The street name is "+ (+address).StreetName ?? "n/a" + "."); Input: address = new Address(); Output: The street name is n/a. Input: address = new Address(); address.StreetName = "Regent St"; Output: The street name is Regent St. Input: address = null; Output: The street name is n/a. To use the null-coalescing-operator, there are some compile-time ground rules. As you can see from the examples above, this little gem is very powerful and the possibilities are endless. Of course the benefits are purely syntactical, but it helps keep the code clean and easier to follow. I hope you enjoy it as much as I do. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) Matware wrote:...but is someone maintaining my code has to dive off to the language reference to fix a bug or add a feature I've failed as a developer Big Al 07 wrote:If I want terse, then I’ll go back to assembler. value ?? default value != null ? value : default; value object x = (Container.Matrix[i,j] != null) ? Container.Matrix[j,i] : Container.DefaultValue; mov eax, [value] or eax, eax jz L1 mov eax, [default] L1: xor ebx, ebx mov esi, [v+ecx*0x04+0x20] cmp esi, ebx jne L1 mov [result], esi jmp Exit L1: mov edi, [default] mov [result], edi Exit: foo ?? (foo = new List()); operator + logan1337 wrote:address.StreetName ?? "n/a" ...if address is null. public class Address { public string StreetName = null; public static bool operator +(Address address) { return address != null; } } string street = (+a)?a.StreetName:"n/a"; public class Address { private static Address Empty = new Address(); public string StreetName = null; public static Address operator +(Address address) { return address ?? Empty } } string street = (+a).StreetName ?? "n/a"; public class Street { public static readonly Street Empty = new Street("n/a"); private string value; public Street(string value) { this.value = value; } public override string ToString() { return value; } } public class Address { public static readonly Address Empty = new Address(Street.Empty); private Street street = Street.Empty; public Street Street { get { return street; } } public Address(Street street) { this.street = street; } } Address address = null; Console.WriteLine((address ?? Address.Empty).Street); Address address = Address.Empty; Console.WriteLine(address.Street); Address address = Address.NotSpecified General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/20666/The-Null-Coalescing-Operator?fid=466395&df=90&mpp=10&noise=1&prof=True&sort=Position&view=Quick&spc=Relaxed&select=2252856&fr=1
CC-MAIN-2015-18
refinedweb
642
58.58
hi simon! simon litwan wrote: > Jörn Nettingsmeier schrieb: >> hi everyone! >> >> >> i'm having weird library issues (or so i think) while running >> lenya-trunk in tomcat. xalan seems unable to map namespaces to prefixes, >> and this has been reported as a jar incompatibility issue before >> is anyone currently using this setup successfully? >> >> if so, would you mind sharing >> a) your tomcat and java version > jakarta-tomcat-5.0.28 > j2sdk1.4.2_10 > >> b) your architecture and os > x86, ubunut 6.06 >> c) a listing of your tomcat endorsed lib directory and the >> lenya/WEB-INF/lib directory > ls common/endorsed/ > jakarta-bcel-20040329.jar xalan-2.6.1-dev-20041008T0304.jar > xercesImpl-2.8.0.jar xml-apis.jar > jakarta-regexp-1.3.jar xalan-2.7.0.jar > xercesImpl-2.8.1.jar > jakarta-regexp-1.4.jar xercesImpl-2.6.2.jar > xml-apis-1.3.02.jar > old xercesImpl-2.7.1.jar > xml-apis-1.3.03.jar funny. after re-reading the tomcat/lenya install instructions, i'm sorry to say that your setup does not work :) that's a whole zoo of xerces versions you have in there... according to the docs, this should lead to problems. weird. did you do any cleanup after deploying? how exactly did you deploy to tomcat? with ./build.sh and the appropriate settings in local.build.properties, or via a war file? maybe i've cleaned up too much? --------------------------------------------------------------------- To unsubscribe, e-mail: user-unsubscribe@lenya.apache.org For additional commands, e-mail: user-help@lenya.apache.org
http://mail-archives.apache.org/mod_mbox/lenya-user/200610.mbox/%3C452C0B1D.6000806@apache.org%3E
CC-MAIN-2014-10
refinedweb
260
51.55
If you are working with Word documents in code in .NET Standard 2.0 targeted applications, there will be times when you do not want to store your data in a Word format. A PDF (Portable Document Format) is an ideal format for a variety of reasons. Why convert a Word document to PDF? - You do not have Microsoft Office installed on your system, but still want to print or distribute your Word documents. - that offers a complete solution to program and work with Word documents, with zero dependancies on Microsoft Office. With GcWord, developers can create powerful document conversions for archival and delivery systems in .NET Standard 2.0 targeted applications. You can convert Word documents to PDF on all three operating systems -- Windows, Mac, and Linux. GcWord's feature-rich object model is based on Microsoft Office API, Word Javascript API, and OpenXML SDK. The architecture is simple and handy to use. Developers can make use of its object model to create DOCX files through code, load DOCX file, and access the object model. You can add, remove, and modify objects (and their properties like formatting), save the file to a DOCX file or export it to PDF. You can do all this in any .NET Standard 2.0 targeted application. In this demo, we'll cover: - How to load the Word document (.docx) file in GcWord - Export the Word document to PDF Step 1: Exporting Word documents to PDF Learn how to install GcWord in a .NET Core console application and create a Word document in code, using GcWord. At the end of this blog, your Word document would look like this: Step 2: Add namespace In order to export a Word document to PDF, you need to download and install GrapeCity.Documents.Layout, and click Install. Accept the license agreement. Visual Studio for MAC - In the Package source on the top left, choose nuget.org. - Click Browse tab on the top right and search for "Grapecity.Documents." - On the left panel, choose GrapeCity.Documents.Layout among them. - Select it and then the build number. The package will be added to the application. Step 3: Load a Word document (.docx) file in GcWord Add following lines of code in main function of Program.cs. This code will create a GcWord document object. Then load the Word document into it. var doc = new GcWordDocument(); var path = Path.Combine(@"ImportanceOfWetlands.docx"); doc.Load(path); Step 4: Export the Word document to PDF Instead of saving to Word, you can directly save the Word document to PDF using following code: doc.SaveAsPdf("ImportanceOfWetlands.pdf"); Run the application. Your PDF would look like this: Watch the video tutorial It's that simple! We hope you like this feature. Do you have a question or comment? Please leave it in the thread below. View more demos and features of GcWord. Export your Word document to a PDf in .NET Apps Download GrapeCity Documents for Word Export your Word document to a PDf in .NET Apps Download GrapeCity Documents for WordDownload Now!
https://www.grapecity.com/blogs/convert-word-documents-to-pdf-in-dot-net-apps
CC-MAIN-2019-22
refinedweb
509
68.97
Portable RFM69 Signal Scanner Just wanted to share my tonight creation It shows Send and Receive RSSI and vcc (that btw is measured via voltage divider and is spot on with my multimeter) - NeverDie Hero Member last edited by Nice job! Looks very dapper. Alternatively, you may (?) be able to plug your screen directly into the I2C connector used for the TH sensor on: Depends on the pinout, of course. I thought about it but Vin and GND are swapped Hi great work. Could you give us more details please? Which version of mysensors do you use ? RF power report seems only availble in dev branch isn't it? Thanks Yes, I'm using latest version in dev branch. I also figured I can show both power level and power percentage ( I removed the "VCC" from lcd as it is not really necessary ) Here is the new code that uses the TX power readings. I think that RSSI values and tx power values could be useful to be reported by nodes every once and a while, at least to provide a feedback on how they are doing. #include <U8glib.h> #include <Wire.h> //#define MY_DEBUG // Enable debug prints U8GLIB_SSD1306_128X64 lcd(U8G_I2C_OPT_DEV_0 | U8G_I2C_OPT_NO_ACK | U8G_I2C_OPT_FAST); // Fast I2C / TWI #define MY_RADIO_RFM69 #define MY_RFM69_FREQUENCY RFM69_433MHZ #define MY_RFM69_NEW_DRIVER #define MY_TRANSPORT_WAIT_READY_MS 10000 //#define MY_NODE_ID 240 //#define VBAT_VCC #include <SPI.h> #include <MySensors.h> #define CHILD_ID_VBAT 201 // Battery voltage unsigned long SLEEP_TIME = 2000; // Sleep time between reads (in milliseconds) #define SKETCH_NAME "Signal Monitor" // Change to a fancy name you like #define SKETCH_VERSION "1.0" // Your version MyMessage msgVBat(CHILD_ID_VBAT, V_VOLTAGE); int Send_rssi, Rec_rssi; // RSSI RFM69 chip #define CHILD_ID_RSSI_HIGH 7 // RSSI received signal level #define CHILD_ID_RSSI_LOW 8 // RSSI background noise level MyMessage msgRSSI1(CHILD_ID_RSSI_HIGH, V_LEVEL); MyMessage msgRSSI2(CHILD_ID_RSSI_LOW, V_LEVEL); //========================= // 2.8 // Vmin (radio Min Volt)=1.9V (564v) #define VMAX 3.44 // Vmax = (2xAA bat)=3.0V (892v) int batteryPcnt = 0; // Calc value for battery % int batLoop = 0; // Loop to help calc average int batArray[3]; // Array to store value for average calc. float Vbat; #ifdef VBAT_VCC #include <Vcc.h> const float VccCorrection = 1.0 / 1.0; // Measured Vcc by multimeter divided by reported Vcc Vcc vcc(VccCorrection); #else int BATTERY_SENSE_PIN = A0; // select the input pin for the battery sense point #endif // VBAT_VCC void setup() { analogReference(INTERNAL); // For battery sensing lcd.setFont(u8g_font_unifont); } void presentation() { // Send the Sketch Version Information to the Gateway sendSketchInfo(SKETCH_NAME, SKETCH_VERSION); // Register all sensors to gw (they will be created as child devices) present(CHILD_ID_RSSI_HIGH, S_SOUND); present(CHILD_ID_RSSI_LOW, S_SOUND); present(CHILD_ID_VBAT, S_MULTIMETER); } void loop() { delay(500); // Allow time for radio if power used as reset Send_rssi = RFM69_getSendingRSSI(); // read RSSI in RFM69. Measure reception signal from gw send(msgRSSI1.set(Send_rssi)); // send RSSI level wait(500); // wait to get idle Rec_rssi = RFM69_getReceivingRSSI(); // read RSSI in RFM69. Wait and measure background noise send(msgRSSI2.set(Rec_rssi)); // send RSSI level wait(200); // wait for next send batM(); lcd.firstPage(); do { UpdateDisplay(); } while (lcd.nextPage()); sleep(SLEEP_TIME); //sleep a bit } void UpdateDisplay() { lcd.setPrintPos(0, 20); String row; row = (String)"S/R: " + Send_rssi + "/"+ Rec_rssi +"db"; lcd.print(row); lcd.setPrintPos(0, 42); row = (String)"Pwr%: " + RFM69_getTxPowerPercent() + "%"; lcd.print(row); lcd.setPrintPos(0, 64); row = (String)"PWR: " + RFM69_getTxPowerLevel() + "db"; lcd.print(row); } void batM() //The battery calculations { delay(500); int batteryPcnt; // Battery monitoring reading #ifdef VBAT_VCC Vbat = vcc.Read_Volts(); batteryPcnt = vcc.Read_Perc(VMIN, VMAX); #else int sensorValue = analogRead(BATTERY_SENSE_PIN); Vbat = sensorValue * VBAT_PER_BITS; // Calculate the battery in % batteryPcnt = static_cast<int>(((Vbat - VMIN) / (VMAX - VMIN))*100.); #endif delay(500); send(msgVBat.set(Vbat, 2));++; } } Nice clean signal scanner build! I must have one. Is that an open source proto board you used? I couldn't find it poking around a bit. Thanks for sharing it! @grubstake I think it is an earlier revision of @mfalkvidd Thanks, it looks like the Rev 9?, where the older pic you posted looks like a smaller version. I didn't realize the board was rearranged between Rev9 and recent R10. Yes, that was Rev 9, but the sketch would work with anything you have
https://forum.mysensors.org/topic/7822/portable-rfm69-signal-scanner
CC-MAIN-2022-21
refinedweb
670
58.28
In this chapter, we will cover the following recipes: Setting up a cross-platform development environment Creating a cross-platform project Understanding the project structure and application life cycle Updating and managing project dependencies Using source control on a Libgdx project with Git Importing and running the Libgdx official demos Before thinking about how to render an animated character onscreen, it is very important that you prepare all the required tools to create cross-platform applications with Libgdx and understand its basic principles. This is, precisely, the purpose of this initial chapter. First, we will cover how to install everything that is required for the three major operating systems, Windows, Mac, and GNU/Linux. Though we all know you want to go straight to the fun bit, a stable and productive working environment is vital in order to avoid future headaches. After we make sure that all is in order by testing a sample project, it will be time to take a closer look at how all Libgdx projects are structured. Often, a developer wants to use a newer version of Libgdx or some third-party library because it includes an incredible feature or solves a problem they were losing sleep over. For these reasons, it will prove very useful to know how to properly update a project so as to enjoy some fresh goodies. Finally, as you are probably very much aware, using source control for every single one of your endeavors is surely a life saver. Not only does it give us a backup system straightaway, but it also empowers us to share and keep track of the changes in the repository. This is extremely useful when you want to blame someone else for something that went wrong! In this chapter, we will show how to efficiently use source control with a Libgdx project using Git as an example. Once you go through this recipe, you will be able to enjoy Libgdx in all its glory and start developing games for all the supported platforms. Let's begin with a short disclaimer. For the most part, Libgdx relies on open source software that is widely available at no cost. This means that anyone can target desktops, Android, and browsers using a Windows, Mac, or GNU/Linux distribution. The only restriction applies to iOS, for which you will specifically need a Mac. Moreover, if you wish to test your work on a real device, an Apple developer account is essential and further costs apply. You need to be aware of the operating system version you will use to pick the right versions of the software packages we will install. The main explanation thread will focus on Windows 8 64-bit, but further comments will be provided whenever there are differences across systems. Here is our little software shopping list: Java Development Kit Eclipse IDE The Gradle plugin for Eclipse Android SDK, only for those who want to target Android devices The RoboVM plugin for Eclipse, only if you want to target iOS XCode, only for Mac users that want to target iOS Libgdx is based on Java, and therefore, Java Development Kit is a requirement. The installation step is as follows: Go to Oracle's download site,, and click on the latest release of Java SE Development Kit that corresponds to your operating system. Note that you need to differentiate between the x86 and x64 builds. Perform the following installation steps: Run the installer and follow the provided instructions. The process is quite straightforward, but when using Windows, you will have to remember the destination folder you picked; the default folder is C:\Program Files\Java\jdk_version. You need to tell the system where the JDK is located. If you are under Windows, right-click on My Computer, click on System Properties, access the Advanced section, and click on Environment Variables. Select New, and enter JAVA_HOMEas the name and your installation path as a value. In my case, the value is C:\Program Files\Java\jdk1.7.0_45. Mac users will have to edit their ~/.bash_profilefile and add the following: export JAVA_HOME=`/usr/libexec/java_home âv 1.7` Perform the following installation steps: Move the downloaded package to the desired installation folder and decompress it. You can do this from a desktop environment or the much more classic console. We will assume the file is jdk-7u45-linux-x64.gz; it's in the ~/Downloadsdirectory, and the installation folder is ~/dev/jdk1.7.0_45: mkdir âp ~/dev/jdk cd ~/Downloads tar âxzvf jdk-17u45-linux-x64.gz mv jdk1.7.0_45 ~/dev rm jdk-7u45-linux-x64.gz Tip Downloading the example code You can download the example code files for all Packt books you have purchased from your account at. If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you. This book is full of rich working examples you can experiment with. Access the following link to download the most up-to-date version:. In GNU/Linux, the system also needs to know where the JDK is. In order to do so, open the ~/.bashrcfile with your text editor of choice and add the following at the bottom: export JAVA_HOME=$HOME/dev/jdk1.7.0_45 export PATH=$PATH:$JAVA_HOME/bin Close the file, and run the following command to reload the user configuration: source ~/.bashrc Eclipse is the most popular IDE for Libgdx game development, and it is thus the one we will focus in this book. If it is not of your liking, you can use IntelliJ IDEA, Netbeans, or any editor along the command line. Perform the following installation steps: Go to the Eclipse downloads section at and select Eclipse Standard. The Eclipse 4 codename, Juno, is the minimum version needed to use the required plugins. Simply pick the right version for your operating system and wait for it to download; be wary that it is also 32/64-bit sensitive. Once this is complete, extract the compressed file where you want to use Eclipse from and you will be done. From a GNU/Linux system, you can do the following: cd ~/Downloads tar âxzvf eclipse-standard-kepler-SR1-linux-gtk-x86_64.tar.gz mv eclipse ~/dev rm eclipse-standard-kepler-SR1-linux-gtk-x86_64.tar.gz Follow these instructions to install Android Development Kit, which is essential to target Android devices: Access the download page at. Scroll down and unfold the View all downloads and sizes section and, again, choose your operating system from the SDK Tools Only section. Google has an easy-to-use installer for Windows users, so if you want to be spared part of the hassle, use the installer. The installer is really simple. Limit yourself to follow the instructions, and if JDK is properly added to the environment variables, everything should be completely smooth. The installation folder does not really matter. Unzip the package wherever you want, as long as you tell the system where it is. Again, this is done by editing the ~/.bash_profile file and adding something similar to this: export PATH=$PATH:/dev/android-sdk-mac_x86_64/tools export PATH=$PATH:/dev/android-sdk-mac_x86_64/platform-tools Perform the following installation steps: Unzip the package, move it to the desired installation folder, and add the export location to the PATHenvironment variable. The commands needed will be something similar to this: cd ~/Downloads tar âxzvf android-sdk.r22.2.1-linux.tgz mv android-sdk-linux ~/dev rm xzvf android-sdk.r22.2.1-linux.tgz Just like with JDK, edit the ~/.bashrcfile and add the following lines at the end: export PATH=$PATH:~/dev/android-sdk-linux/tools export PATH=$PATH:~/dev/android-sdk-linux/platform-tools Again, close the file and reload the ~/.bashrcfile: source ~/.bashrc After this, go to to the Android SDK folder and run SDK Manager, which will help us install specific packages. On GNU/Linux, you first need to give execution permissions to the user on the SDK folder: cd ~/dev/android-sdk-linux chmod âR 744 * Perform the following steps: Create an ANDROID_HOMEenvironment variable pointing to the root of Android SDK. This is done the same way as we did with the JAVA_HOMEvariable in the previous section. Run SDK Manager found in the toolsfolder. GNU/Linux users need to run an Android executable. Several Android SDK tools will appear selected by default; leave them selected. The Google USB driver is not compatible with GNU/Linux, but you should select it if you can. The SDK tool corresponding to the latest Android version available will be ticked as well. Feel free to choose whichever SDK you prefer, but keep in mind that Libgdx requires Android 2.2 or later. Regardless of the Android version you pick, it is always advisable to consider backwards compatibility so as to reach as wide an audience as possible. As a developer, you will want to be thorough when it comes to testing on multiple devices. Having said this, select Install packages and accept the licenses. Getting tired? Worry no more, we are getting close to the finish line! We are about to install several plugins that will allow us to manage our build process and target iOS devices: A course on how to use an IDE is out of the scope of this book. However, pertinent explanations will be provided when having to deal with Eclipse-specific issues. The installation steps are as follows: Run Eclipse and create a new workspace to import your recipe's code into. Just so we are all on the same page, let's name it libgdx-cookbook. Once you see the welcome panel, close it and select Help | Install New Software. The Android Developer Tools and the Google Web Toolkit plugins can be found at. Note Be aware that this will only work with Eclipse 4.3 Kepler. If you use a different Eclipse release, use the matching version number. Google has this URL available on its developers help guide for Eclipse at. Select Developer Tools, Google Plugin for Eclipse, and Google Web Toolkit SDK, and proceed with the installation. A modal dialog will warn you about installing unsigned content because there is always an inherent risk when installing plugins. Rest assured Google's tools are safe. Upon completion, Eclipse will need to restart, and you will be prompted to enter the Android SDK location. Now, follow the same process for the RoboVM plugin; you will find it at. There is only one option within the repository, so select it, carry on with the installation, and restart Eclipse once again. Gradle is an open source build automation system. It will gracefully handle all the dependencies of our projects, doing most of the cumbersome heavy lifting. Perform the following steps: Once again, go to the Install new software option in Eclipse and introduce the URL. Install the Gradle IDE entry and restart Eclipse for the last time. Great! One more task can be crossed out from our shopping list. XCode is the Apple IDE required to develop for their platforms. Mac users who want to target iOS can get hold of XCode free of charge from Apple Store. Eclipse has the impolite practice of not using UTF-8 encoding and Unix line endings if you are under a Microsoft operating system. While this will not affect you initially, it will prove to be a huge pain when it comes to using other peers' code as many conflicts will appear to ruin the party. Perform the following steps: Character encoding is applied on a per-workspace basis, and to fix it, you need to access the libgdx-cookbookworkspace you just created. Click on Window, select Preferences | General, then select Workspace, and make sure UTF-8 encoding and Unix line endings are your choices. The time of truth has come as we are about to import a Libgdx project to our workspace for the first time and see whether we have made any mistakes along the way. This is the most basic Libgdx project you can possibly make if you want to target all platforms. Use the source code provided with this book. Perform the following steps: Once you have Eclipse open in front of you, right-click on Package Explorer, select Import, and choose Gradle project inside the Gradle node. Select the [cookbook]/environmentfolder, and click on Build Model. Make sure you select all listed projects, and click on Finish to start importing the projects. Gradle will now download all the dependencies, which may take a while. As long as everything goes according to plan, the only error you might see on the Problems pane will be in the Android project. This is because it is set to use an Android SDK different from the one you installed. In such a case, right-click on environment-test-android, go to Properties, and tick your installed Android SDK under the Android tab. You can also install the missing SDK if you prefer to do so. All the assets are located inside the environment-test-androidproject and will be shared across all platforms. We now need to tell the desktop project where the assets are located. Right-click on the desktop project ( environment-test-desktop), select Properties | Run/Debug Settings, select DesktopLauncher, and click on Edit. Open the Arguments tab and select Other as the working directory. Now enter this in the input box: ${workspace_loc:environment-test-android/assets} As long as you followed this recipe correctly, there should be no errors hanging around; so, it is time to run the project on every platform as a final test. First, let's try the desktop project, which is the easiest of all. Right-click on it, select Run As followed by Java application, and then choose the entry point ( DesktopLauncher). You will see the following window: Android is next in the queue. Note I strongly advise you against testing a Libgdx game on the emulator because of its extremely poor performance. A device is so much better, and you will run your project through the desktop version most of the time anyway. This rapid iteration cycle is the main point in Libgdx's philosophy. To pair your Android device, be it a phone or tablet, you need to enable USB debugging on your Android device, which can be a little obscure in later versions. Perform the following steps: On the device, go to Settings, enter About Phone, and tap the Build Number block seven times to enable developer options. Yes, do not ask why. Once you get a message saying you just became a developer, you can go to Settings | Developer options and enable USB debugging. Now, you can run the environment test on your device by right-clicking on the Android project, entering the Run As menu, and selecting Android Application. Finally, choose your device from the list. Let's try the HTML project now. Perform the following steps: Right-click on the environment-test-gwtproject and select Run As Gradle buildâ¦. On the next window, type Ctrl + Space, and scroll down and double-click on the gwtSuperDev task. Click on Apply followed by Run. The first time you do this, it will take quite a while. Under the hood, the build process will launch a Jetty web server on your computer. After a while, you will be able to access it through the following URL: A background code server will accept build requests from the browser, so no manual full compilation is needed once you kick it off. You will notice a particular message in the compiler output: The code server is ready. Next, visit Access the URL and drag the Dev Mode On bookmarklet onto the browser's bar. You will never need to do this again. Back on your running environment test tab, click on the newly added bookmarklet, and select compile. Any change to the game code will be recompiled and reinjected in the web server. After a short time, the page will refresh and you can run the most recent version of your code. Additionally, Mac users can run the iOS project by right-clicking on environment-test-ios and going to the Run As menu. Inside, you will find three options of interest: iOS Device App: This requires you to have an actual connected device and an Apple developer subscription iOS Simulator App (iPad) iOS Simulator App (iPhone) Pretty much like the HTML5 project, the first build will take a long time; it should be fine after this. Congratulations! Now, you can run your Libgdx projects on all targetable platforms. The Libgdx development environment installation process is pretty much self-explanatory. However, it is worth mentioning a few details of how it is designed to facilitate cross-platform development and what technologies it relies on. You will at least know why you just installed so many things! Libgdx has a multiplatform API that allows users to write platform-agnostic Java code once and deploy it on all the supported platforms, while achieving the same behavior. Every platform has a backend that implements low-level subsystems: Application, Graphics, Audio, Input, Files, and Network. This way, we can happily request to draw a sprite onscreen, play some background music, or read a text file through the common graphics, audio, and file interfaces, respectively, and it will run everywhere. Magic! Deployment on platforms such as Android, iOS, or HTML5 might not be the fastest process ever, but this is usually mitigated by the ability of the desktop backend to serve as a debugging platform. Remember that this will become increasingly important as you and Libgdx become friends. The desktop backend mostly relies on LWJGL (Light Weight Java Game Library). At the same time, LWJGL is built on top of the magnanimous OpenGL (Open Graphics Library). A fun fact is that Minecraft was created using LWJGL. For Android development, Libgdx finds its resources on the official Android SDK as well as the embedded system-specific version of OpenGL, which is called OpenGL ES. This gets a lot trickier when it comes to HTML5 support because the technologies are quite different. HTML5 can display incredibly visually rich applications through WebGL and JavaScript, but unfortunately, this has little to do with the Libgdx toolchain. Compatibility with browsers is achieved through Google Web Toolkit (GWT), which compiles Java code into optimized JavaScript code, thanks to, what I like to call, black magic. Last but not least, we have iOS support that relies on RoboVM. This magnificent piece of open source software eats Java code for breakfast and spits out native ARM or x86 code. It also provides full access to Cocoa Touch API, allowing us to deploy on iOS devices, as long as we have a Mac. There are quite a few more technologies involved to make this happen, but this serves as a broad overview of what goes on under the hood. You can use Android SDK Manager to gain access to more Android APIs such as Google Play Game services, advertisement platforms, or Intel Hardware Accelerated Execution Manager (HAXM). HAXM is an alternative Android emulator, much faster than the default one. Feel free to explore! In the next recipe, you will learn how to create brand new Libgdx-based cross-platform projects. Let the fun begin! For instructions on how to deploy your Libgdx applications, go to the first four recipes in Chapter 13, Giving Back.; you only have to declare that you want to include them in your project. Luckily enough, you do not need to learn a lot about Gradle to start working on Libgdx projects because our framework bundles a tool that creates a skeleton application with all the basics for you to use. The gdx-setup tool offers a very straightforward user interface as well as a command-line option. Feel free to use whichever you are most comfortable with; we will explain both here. Perform the following steps: First, download the latest version of the tool from. Running the .jarfile with no additional arguments opens up the user interface straightaway. Filling the form in does not entail any mystery at all. Simply enter the project folder name, Java package name, name of the game logic entry point class, folder where the projects will be created, and location of your Android SDK. Once you are ready, click on the Generate button, as shown in the following screenshot: For those who fancy the command-line version of the tool, here is its usage: java --jar gdx-setup.jar --dir <dir-name> --name <app-name> --package <package_name> --mainClass <main_class> --sdkLocation <sdk_location> --dir: This is the destination folder of the projects --name: This is the name of the application, which will determine the project folders' names --package: This is the name of the Java package where the code will live --mainClass: This is the class name for the game code entry point --sdkLocation: This is the path to your Android SDK For example, to call the tool from the command line with the settings shown in the previous screenshot, you will have to enter: java âjar gdx-setup.jar âdir E:\projects\tools\test âname my-gdx-game âpackage com.mygdx.game âmainClass MyGdxGame âsdkLocation C:\android Done! Just like we did with environment-testin the previous recipe, now it is time to import the project in Eclipse. Right-click on Package Explorer, select Import, and choose the Gradle project inside the Gradle tab. Select your destination folder and click on Build Model. Right-click on the desktop project. Go to Properties | Run/Debug Settings, select DesktopLauncher, and click on Edit. Open the Arguments tab and select Other as the working directory. Now, enter this in the input box: ${workspace_loc:my-gdx-game-android/assets} You need to override the memory allowance for Gradle and specify the location of Android SDK so that Gradle can pick it up. Add the following lines to the gradle.propertiesfile located under the gradledirectory in your userfolder: org.gradle.jvmargs=-Xms128m -Xmx512msdk.dir=C:/android Your newly created Libgdx project should be fully functional. Gradle will take care of the dependencies, download the necessary libraries, and handle the compilation process. Like we mentioned before, the first build can take quite a while, but it should be significantly smoother from then on. Happy coding! At this point, you will notice how the Libgdx projects are structured. They are actually made of several projects, one per platform and another core project. The core project contains the actual logic of your game, while the platform-specific projects typically only have a launcher that calls the core entry point. The resulting directory tree inside the test folder will look as follows: |- settings.gradle - project submodules |- build.gradle - main Gradle build config file |- gradlew - Build script for GNU/Linux |- gradlew.bat - Build script for Windows |- local.properties - Intellij IDEA only file | |- gradle/ - local Gradle | |- core | |- build.gradle - Gradle build for core project, do not modify | |- src/ - Game code | |- desktop | |- build.gradle - Gradle build for desktop project | |- src/ - Desktop specific code | |- android | |- build.gradle - Gradle build for Android project | |- AndroidManifest.xml - Android config | |- src/ - Android specific code | |- res/ - Android icons and other resources | |- assets/ - Shared assets | |- gwt | |- build.gradle - Gradle build for GWT project | |- src/ - GWT specific code | |- webapp/ - War template | |- ios | |- build.gradle - Gradle build for iOS project | |- src/ - iOS specific code Gradle, our build system, is particularly good with multiproject solutions. It uses domain-specific language (DSL) rather than XML, like Ant and Maven do, to define targets as well as their dependencies. When we tell Gradle to build a project for us, it uses the build.gradle files to create a directed acyclic graph representing the dependencies. Then, it builds the dependencies in the right order. The dependency graph for the Libgdx project skeleton will look as follows: Gradle is extremely configurable so as to accommodate the needs of a diverse set of developers and their environments. This is done through several gradle.properties files located at various specific places: The project build directory where the main build.gradlefile is The user home, which will be C:\Users\User\.gradle\gradle.propertiesin Windows and ~/.gradle/gradle.propertiesin GNU/Linux The system properties These settings are applied in descending order, which means that the lower settings can overwrite the higher settings. Gradle downloads dependencies from repositories on demand. When your machine is behind a proxy, you need to specify this through one of the gradle.properties files by adding the following settings: systemProp.http.proxyHost= systemProp.http.proxyPort=8080 systemProp.http.proxyUser=userid systemProp.http.proxyPassword=password For secure addresses, you only need to replace http with https in the previous properties. As you surely understand, this is not a book on Gradle. If you wish to know more about it and how to tailor it for your needs, refer to the official user guide at. Throughout this recipe, we will examine the typical project architecture of Libgdx and how it makes cross-platform development a much less cumbersome quest. We will also learn how to configure platform-specific launchers in order to tweak parameters such as resolution, colors, the OpenGL version, and so on. More importantly, we will go through the Libgdx application life cycle. This is the heart of any game you will ever make using our beloved framework, and therefore, one can imagine it is something worth getting acquainted with. With the goal of illustrating the contents of this recipe, we will use the same environment test application we used in the Setting up a cross-platform development environment recipe to test that our Libgdx installation is working as expected. Fire up Eclipse and make sure you select your libgdx-cookbook workspace. Now, check you have the projects that compose the test application already available. If not, import the projects under [cookbook]/environment through Gradle, as shown in the previous recipe. As we already mentioned before, Libgdx applications are typically split in several projects: core, desktop, Android, iOS, and HTML. The platform-specific projects serve as the application's entry points on each platform; their duty basically boils down to invoking the core project's main class and passing in the basic configuration parameters for the game to run. Note Imagine you were to target Android exclusively, you could probably get away with one single project containing both the platform-agnostic and Android-specific code. However, this is a bad practice and should be avoided. What happens if you decide to port your game to a different platform later on? No one would like to refactor the project structure to accommodate it to the new circumstances. Regardless of the platform and devices you work with, it is always preferable to keep the two categories as isolated as possible. Every Libgdx application has a very well-defined lifecycle controlling the states it can be in at a given time. These states are: creation, pausing, resuming, rendering, and disposing. The lifecycle is modeled by the ApplicationListener interface, which we are required to implement as it will serve as the entrance to our game logic. In our recipe's example, the EnvironmentTest class in the core project carries out such roles. Meet the ApplicationListener interface: public interface ApplicationListener { public void create (); public void resize (int width, int height); public void render (); public void pause (); public void resume (); public void dispose (); } Your ApplicationListener interface implementation can handle each one of these events in the way it deems convenient. Here are the typical usages: create(): This is used to initialize subsystems and load resources. resize(): This is used to handle setting a new screen size, which can be used to reposition UI elements or reconfigure camera objects. render(): This is used to update and render the game elements. Note that there is no update()method as render()is supposed to carry out both tasks. pause(): This is the save game state when it loses focus, which does not involve the actual gameplay being paused unless the developer wants it to. resume(): This is used to handle the game coming back from being paused and restores the game state. dispose(): This is used to free resources and clean up. When do each of these methods get called? Well, that's a really good question! Before we start looking at cryptic diagrams, it is much better to investigate and find out for ourselves. Shall we? We will simply add some logging to know exactly how the flow works. Take a look at the EnvironmentTest.java file: public class EnvironmentTest implements ApplicationListener { private Logger logger; private boolean renderInterrupted = true; @Override public void create() { logger = new Logger("Application lifecycle", Logger.INFO); logger.info("create"); } @Override public void dispose() { logger.info("dispose"); } @Override public void render() { if (renderInterrupted) { logger.info("render"); renderInterrupted = false; } } @Override public void resize(int width, int height) { logger.info("resize"); renderInterrupted = true; } @Override public void pause() { logger.info("pause"); renderInterrupted = true; } @Override public void resume() { logger.info("resume"); renderInterrupted = true; } } The renderInterrupted member variable avoids printing render for every game loop iteration. Note Whenever Eclipse complains about missing imports, hit Ctrl + Shift + O to automatically add the necessary modules. The Logger class helps us show useful debug information and errors on the console. Not only does it work on desktops but also on external devices, as long as they are connected to Eclipse. Remember this little new friend as it will be truly useful for as long as you work with Libgdx. The constructor receives a string that will be useful to identify the messages in the log as well as on a logging level. In order of increasing severity, these are the available logging levels: Logger.INFO, Logger.DEBUG, Logger.ERROR, and Logger.NONE. Several methods can be used to log messages: info(String message) info(String message, Exception exception) debug(String message) debug(String message, Exception exception) error(String message) error(String message, Throwable exception) Logging levels can be retrieved and set with the getLevel() and setLevel() methods, respectively. Both the level and the method used to log a message will determine whether they will actually be printed on the console. For example, if the level is set to Logger.INFO, only messages sent through info() and error() will appear, and those sent through debug() will be ignored. Now, run the application on all the platforms and pay attention to the console. Depending on how you play with the focus, the output will vary, but it should be similar to this: Application lifecycle: create Application lifecycle: resize Application lifecycle: render Application lifecycle: pause Application lifecycle: render Application lifecycle: resume Application lifecycle: render Application lifecycle: dispose This should give you a pretty decent handle of how the application lifecycle works. Placing breakpoints on each ApplicationListener overridden method is also a good way of discovering what is going on. Instruction breakpoints allow you to debug an application and stop the execution flow that reaches the said instruction. At this point, you can run the code instruction by instruction and examine the current state of the active variables. To set a breakpoint, double-click next to the corresponding line; a blue dot will confirm that the breakpoint is set. Once you are done, you can debug the application by right-clicking on the desired project and selecting the Debug As menu. The Eclipse Debug view will then enter the stage with all its shiny panels. The Debug tab shows the current execution callstack, the Variables tab contains the current state of the variables within scope, and in the following screenshot, you can see the code with the current line highlighted. The arrow buttons in the upper toolbar can be used to step over the next instruction (F6) or move on to the next method (F5), where applicable, or out of the current method (F7), as shown in the following screenshot: Every platform project consists of a starter class (or entry point). This class is responsible for constructing the platform-specific application backend. Each backend implements the Application interface. The starter class also passes a new instance of our ApplicationListener implementation to the application backend. This implementation typically lives in the core project and serves as an entry point to our cross-platform game code. Finally, it also submits a configuration object, and by doing so, it provides a mechanism to customize general parameters, as we will see later. The entry point of the desktop project is the static main method of the DesktopLauncher starter class: public class DesktopLauncher { public static void main (String[] arg) { LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); new LwjglApplication(new EnvironmentTest(), config); } } As you can see, this creates LwjglApplicationConfiguration. Then, it instantiates a LwjglApplication object passing in a new EnvironmentTest instance along the recently created config object. Some of the most useful attributes of the configuration class are listed as follows: r, g, b, and a: This is the number of bits to be used per color channel, which are red, green, blue, and alpha, respectively. disableAudio: This is to set whether audio should be used. If it should, requesting the audio subsystem will return null. widthand height: This is the size of the application window in pixels. fullScreen: This is to set whether the application should start in the full screen or windowed mode. vSyncEnabled: This is to set whether vertical synchronization should be enabled. This ensures that the render operations are in sync with the monitor refresh rate, avoiding potential partial frames. title: This is the string with the desired title of the window. resizable: This is to set whether the user should be able to resize the application window. foregroundFPSand backgroundFPS: This is the number of desired frames per second when the application is active and inactive, respectively. The Android starter can be found in AndroidLauncher.java: public class AndroidLauncher extends AndroidApplication { @Override protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); initialize(new EnvironmentTest(), config); } Android starters use the Android SDK Activity framework, which those who have developed for this platform before will be familiar with. In this case, an AndroidApplicationConfiguration instance is used. Some of the most useful attributes are listed as follows: r, g, b, and a: Just as with the desktop project, these refer to the number of bits used per color channel. hideStatusBar: This is to set whether the application should hide the typical Android status bar that shows up right at the top of the screen. maxSimultaneousSounds: This is the number of maximum sound instances that can play at a given time. As you can see in Chapter 5, Audio and File I/O, dedicated to audio, they only refer to short sound effects as opposed to long streams of audio. useAccelerometer: This is to set whether the application should care about the accelerometer; it defaults to true. useCompass: This is to set whether the Android application should update the compass values; it also defaults to true. The HTML5 starter resides inside the GwtLauncher.java file and follows the pattern we already know: public class GwtLauncher extends GwtApplication { @Override public GwtApplicationConfiguration getConfig () { GwtApplicationConfiguration cfg = new GwtApplicationConfiguration(480, 320); return cfg; } @Override public ApplicationListener getApplicationListener () { return new EnvironmentTest(); } } A GwtApplicationConfiguration object is used to configure the HTML5 backend. Its most important parameters are as follows: antialiasing: This is to set whether to enable antialiasing, which is computationally expensive, but helps to avoid rough edges when rendering. canvasId: This is the identifier for the HTML element to embed the game canvas in. When not specified, the system will create a canvas element inside the <body>element. fps: This is the target frames per second at which we desire to run the game. widthand height: These are the dimensions of the drawing area in pixels. Finally, the iOS starter is hosted by the IOSLauncher.java file: public class IOSLauncher extends IOSApplication.Delegate { @Override protected IOSApplication createApplication() { IOSApplicationConfiguration config = new IOSApplicationConfiguration(); return new IOSApplication(new EnvironmentTest(), config); } public static void main(String[] argv) { NSAutoreleasePool pool = new NSAutoreleasePool(); UIApplication.main(argv, null, IOSLauncher.class); pool.drain(); } } The configuration object for this backend belongs to the IOSApplicationConfiguration class and here are its main parameters: accelerometerUpdate: This is the update interval to update the accelerometer values in seconds orientationLandscapeand orientationPortrait: This is to set whether the application supports the landscape or portrait orientation, respectively preferredFramesPerSecond: This is the number of frames per second we try to reach while running the application useAccelerometer: Just as on Android, this sets whether to update the accelerometer values useCompass: This is to set whether to update the compass sensor values So far, you autonomously experienced how a Libgdx application is organized and the mechanism it uses to run across platforms. Also, you tested how the application lifecycle works and which events are triggered as a consequence of an event. Now, it is time to get a higher-level overview of all these systems and see how they fit together. Here is an UML class diagram showing every piece of the puzzle that is involved in any way with game startups on specific platforms and in the application lifecycle. After a quick glance, we can observe how EnvironmentTest, our ApplicationListener implementation, is used by every launcher class along the various configuration classes: The next diagram depicts the mighty Libgdx application lifecycle. Every time the game starts, the create() method is called. Immediately after, there is a call to resize() so as to accommodate the current screen dimensions. Next, the application enters its main loop, where it calls render() continuously, while processing the input and other events, as required. When the application loses focus (for example, the user receives a call on Android), pause() is invoked. Once the focus is recovered, resume() is called, and we enter the main loop again. The resize() method is called every time the application surface dimensions change (for example, the user resizes the window). Finally, it's called when the player gets bored of our game. Sorry, this will never happen! When the player runs out of time to play our game and exits, pause() will be called, followed by dispose(). After looking at the basic concepts behind a simple Libgdx project, let's move on to a couple of tricks to improve your quality of life. As you already know, every Libgdx game needs to have an ApplicationListener interface implementation in its core project for the launchers to use. We also saw how the developer is forced to implement the create(), dispose(), render(), resize(), pause(), and resume() methods of such an interface. However, these overridden methods might end up completely empty. What a waste of digital ink, and more importantly, our precious time! Luckily enough, Libgdx provides a useful ApplicationAdapter class that already contains an empty implementation for each ApplicationListener interface method. This means that you can simply inherit from ApplicationAdapter and only override the methods you really need. This comes particularly in handy when writing small tests rather than big games. These small adapter classes are quite common within the API, and they are really comfortable to use as long as we do not need to inherit from anything else. Remember that Java does not support multiple inheritance. The following will be perfectly valid if we want a completely empty application: public class MyGame extends ApplicationAdapter {} Most games are made out of several screens the player can navigate through. The main menu, level selection settings, or levels are some of the most common examples. Though this completely depends on the nature of each project, most of them definitely share the structure. Libgdx comes with an utterly minimalistic screen system built-in, which might just be enough for your requirements, so why not use it? Reinventing the wheel is rarely a good idea. The two main components of this system are the Game abstract class and Screen interface. Game implements the well-known ApplicationListener interface, so you will only need your main class to inherit from Game. The Game class holds a reference to the current Screen and provides the getter and setter methods for it. Game requires you to implement the create() method, but already provides implementations for the rest of the application lifecycle methods. Be aware that if you override any of the other methods, you will need to call the parent version so as to maintain screen behavior correctness. The helpful bit comes with the render() method, which will automatically update and render the active Screen reference, as long as it is not null. What follows is an UML class diagram illustrating a sample game architecture based on the Game/ Screen model. The user implemented MyGame as a Game derived class, and the SettingsScreen, GameScreen, LevelSelectionScreen, and MainMenuScreen classes were derived from Screen: The Game public API looks like this. Note that method implementation has been omitted for space reasons: public abstract class Game implements ApplicationListener { public void dispose (); public void pause (); public void resume (); public void render (); public void resize (int width, int height); public void setScreen (Screen screen); public Screen getScreen (); } The Screen interface is quite similar to the ApplicationListener interface, but its equivalent methods will only be called when it is the active screen. It also adds the hide() and show() methods that will be called when changed to and from a screen, respectively. In the following code, you will find an overview of the interface: public interface Screen { public void render (float delta); public void resize (int width, int height); public void show (); public void hide (); public void pause (); public void resume (); public void dispose (); } This recipe will show you how to leverage Gradle in order to maintain your project and its dependencies. By the end of the recipe, you will be able to upgrade to a newer version of Libgdx and add third-party extensions and arbitrary Java libraries. Oftentimes, people tend to be reluctant to learn new technologies, especially build systems such as Gradle. However, they actually tremendously simplify the process, thus helping us make even more awesome games. Let's start with the environment-test project we created in the Setting up a cross-platform development environment recipe. At this point, you should have the project up and running within Eclipse or the IDE of your choice. Your application's dependencies are expressed in the build.gradle text file, which is pretty much the only file we will manipulate. Be advised against tinkering with the project-specific Gradle files as you stand a really good chance of making all hell break loose. Note This is not supposed to be a full Gradle manual; it's a mere introduction for you to get by and move on to making actual games. Throughout this primer, and for space reasons, we will only show small snippets from the build file. Go ahead and open the build.gradle file from Eclipse. The first thing you will come across is the buildscript element, which defines the list of repositories and basic dependencies. Repositories act as a library-serving system. We can reference libraries by name, and Gradle will ask the list of repositories for a library that matches the name: buildscript { repositories { maven { url '' } ... } dependencies { ... } } The allprojects element contains a string with the application version. Additionally, it defines appName as well as the Libgdx and roboVM versions it should build against. It also provides a list of repositories to fetch from: allprojects { apply plugin: "eclipse" apply plugin: "idea" version = "1.0" ext { appName = "environment-test" gdxVersion = "1.2.0" roboVMVersion = "0.0.13" } repositories { ... } } Every project has a project element indicating its name. A skeleton application's core project will only depend on the previously defined Libgdx version: project(":core") { apply plugin: "java" dependencies { compile "com.badlogicgames.gdx:gdx:$gdxVersion" } } Platform-specific projects, such as a desktop project, will depend on core as well as their corresponding backend and potentially native libraries: project(":desktop") { apply plugin: "java" dependencies { compile project(":core") compile "com.badlogicgames.gdx:gdx-backend-lwjgl:$gdxVersion" compile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop" } } Do not panic if you do not fully understand everything that goes on inside the build script. However, you should at least have a very basic grasp on how the general structure holds itself together. Now, let's get on to some useful business. Dependencies that are pulled from repositories take the following typical Maven format: compile '<groupId>:<artifactId>:<version>:<classifier>' Intuitively, whenever you desire to change a dependency version, you just need to go and modify the version component of its declaration. Now, imagine the Libgdx team has released a new version and we are all very excited with the new features; it is time to try them out. Conveniently enough, throughout the script, the Libgdx version points to the gdxVersion variable. We only need to find the allprojects element and change the following: gdxVersion = "1.1.0" To the following, you are free to choose whichever version you like: gdxVersion = "1.2.0" To make Gradle fetch the new dependencies, select all the projects, right-click on Gradle, and then click on Refresh All. Note Libgdx has stable and nightly builds. Stable builds are well tested, planned builds that can be identified by their version number, 1.2.0, for instance. Nightly builds, in turn, are generated overnight from whatever the Git repository contains. To use nightly builds in your project, you need to set 1.2-SNAPSHOT as the version identifier. Nightly builds are good to test and get the latest features as they are introduced; however, they are considerably riskier and prone to breaking. Use the stable builds if peace of mind is what you seek. Luckily enough, you can switch between them just by changing the gdxVersion variable. Libgdx comes with several additional libraries that provide a ton of extra features. The reason they are not part of the core is because either not everyone is likely to need them or because they might not work on all backends. These extensions have been mavenized and can be fetched from the repositories. Note Linking against libraries you do not need will unnecessarily increase the size of your distributable package. Desktop downloads are not too big of a problem as we have AAA game downloads going up to 50 GB nowadays. However, mobile games need to be careful about this since some 3G connections have bandwidth limits. Currently, the following are the Libgdx Gradle-ready extensions along with their required dependencies for each of the projects. The core dependency will add the interfaces for you to use within the game code, whilst the platform-specific dependencies will contain the implementation of such interfaces. You will need to add them inside the corresponding dependencies element. A bullet is a wrapper for the popular open source 3D physics library. Note that it is not compatible with the HTML5 backend as it needs to run native code. To use it with desktop, we use the following: compile "com.badlogicgames.gdx:gdx-bullet-platform:$gdxVersion:natives-desktop" Similarly, for Android, we use the following: compile "com.badlogicgames.gdx:gdx-bullet:$gdxVersion" natives "com.badlogicgames.gdx:gdx-bullet-platform:$gdxVersion:natives-armeabi" natives "com.badlogicgames.gdx:gdx-bullet-platform:$gdxVersion:natives-armeabi-v7a" The FreeTypeFont extension helps you generate bitmaps from TTF fonts on the fly. It is not compatible with the HTML5 backend. To use it with desktop, we use the following: compile "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-desktop" For Android, this is what we use:" The Controllers extension provides an API to get events from the game controllers. It is not compatible with the iOS backend; although the project still compiles and runs, it will just not detect any controller or event. For more information on controllers, see Chapter 4, Detecting User Input. To use it with desktop, we use the following: compile "com.badlogicgames.gdx:gdx-controllers-desktop:$gdxVersion" compile "com.badlogicgames.gdx:gdx-controllers-platform:$gdxVersion:natives-desktop" To use this extension with Android , we use the following: compile "com.badlogicgames.gdx:gdx-controllers-android:$gdxVersion" The Box2D extension will provide you with a full-blown rigid body physics engine compatible with all backends. Read more about it in Chapter 10, Rigid Body Physics with Box2D. We run the following code to use it with desktop: compile "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-desktop" For Android, we use the following code: compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion" natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi" natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi-v7a" natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-x86" Likewise, for iOS, we will use the following code: compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion" natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-ios" The Tools extension provides texture packing, font generation, and particle editor functionalities, only compatible with the desktop backend. Artificial Intelligence systems: steering behaviors, finite state machines, and behavior trees. Similarly, for android, we use the following: compile "com.badlogicgames.gdx:gdx-ai:$gdxVersion" It is possible to add extra repositories to Gradle to look for the files you need by adding them to the allprojects section. Gradle supports Maven- and Ivy-formatted repositories: allprojects { ... repositories { ivy { url "" } maven { url "" } } } The library you want to use so desperately might not be in any Maven or Ivy repository. Is everything lost? Of course not! You can make projects depend on local files such as arbitrary JAR packages. For instance, you can place the JAR files you need inside a lib folder in each project. Then, you will need to add the following entry to the dependencies section of the projects: dependencies { compile fileTree(dir: 'libs', include: '*.jar') } HTML5 projects will require extra attention when adding dependencies. The GWT compiler needs to know about the modules the application will use. This information needs to be specified in both the GdxDefinition.gwt.xml and GdxDefinitionSuperdev.gwt.xml files located in the class path. The following snippet shows a typical gwt.xml file highlighting the addition of the popular Universal Tween Engine dependency: <module rename- <inherits name='com.badlogic.gdx.backends.gdx_backends_gwt' /> <inherits name='com.cookbook.environment.EnvironmentTest' /> <inherits name='aurelienribon.tweenengine'/> <entry-point <set-configuration-property </module> The Box2D extension will require you to inherit from the following module: <inherits name='com.badlogic.gdx.physics.box2d.box2d-gwt' /> The Controllers extension will ask for the following module: <inherits name='com.badlogic.gdx.controllers.controllers-gwt' /> The AI extension will require the following: <inherits name='com.badlogic.gdx.ai' /> Managing GWT projects can be a bit fiddly, and we will cover this topic more thoroughly in the Making libraries compatible with GWT recipe of Chapter 11, Third-party Libraries and Extras. Every time you add or update a dependency, it is advisable to rebuild the Gradle model so that everything is up to date and you can carry on working normally. Select Gradle and Refresh All from the project by right-clicking on the contextual menu. Telling Gradle to refresh a project's dependencies will automatically make the system download those that have changed when the dependency is a snapshot. For example, this is what happens with the Libgdx nightly builds: gdxVersion = "1.2.0" However, you might want to force Gradle to redownload a specific dependency or even all of them. This can come in handy when a library changes, but the version number is still the same. Though rare, this can very well happen if someone makes a mistake. Gradle downloads and puts dependencies in a .gradle directory inside the user's home folder. It is possible to delete either the whole folder or specific libraries to make Gradle download them again the next time it tries to build the project. Digging a bit deeper, you can tell Gradle that a particular dependency is prone to change often. It will then check every 24 hours whether it has changed. If it has, it will redownload the dependency. This is achieved with the changing property: dependencies { compile group: "group", name: "project", version: "1.1-SNAPSHOT", changing: true } Once more, for further information on how to tune Gradle to your taste, refer to the official user guide. If you want to know more about libraries and tools that work well with Libgdx and can help you in your game development adventure, do not forget to read Chapter 11, Third-party Libraries and Extras. Writing software, in general, and making games, in particular, is a hard endeavor, which is why we should avoid unnecessary complications whenever we can using tools that will save us from despair. There are so many things that can go wrong during development; luckily for us, we can use source control as the first step to a better night's sleep. What if your hard drive breaks, bursts in flames, or gets stolen? Yes, the right answer is continuous backups, tons of them, and then some more! Surely, online cloud storage services such as Dropbox or Google Drive provide this for you out of the box. They even let you share folders with others, which might lure you into thinking that it is a good way of working as a team, but it just stops cutting it the second things go a bit beyond trivial. What if you come back home on a Saturday night after too many drinks and decide it is a great time to get some coding done? After all, you feel incredibly inspired! What follows is that you will wake up the next morning in sweat, tears and full of regret. Surely, Dropbox lets you revert changes on a per-file basis, but a lot of fiddling is required when the changes are spread across multiple systems, and you risk worsening things even more. Finally, what if two members in your team make changes to the same file? Conflict solving in Dropbox is flaky at best; you will most likely enter the realms of hell in these cases. Manually merge two files every time this happens, and believe me, it will happen constantly, but this is not something you will enjoy. Any good source control system gracefully solves each one of these little nightmares for you. A repository keeps track of every important file, and every time you make a set of changes, it is dead easy to create a new revision or snapshot of the whole project tree. These changes can be shared with your team members, and there is no problem in going back a few revisions whenever you realize a mistake has been made. Most source control systems also provide very intelligent mechanisms to merge files several people have modified. After this little rant, it is time to proceed with the recipe. We will use Git to put only the essential files of our Libgdx project under source control, and in this way sleep a lot better at night. Keep in mind that the intent is neither to provide a detailed guide on how revision control works nor how to fully understand Git, but just the bare minimum to get you started. Note Why Git? Well, according to Linus Torvalds, if you do not use Git, you are ugly. For those who don't know him, Linus Torvalds is the father of both the Linux kernel and Git revision control system. He does not have a huge appreciation towards alternatives such as CVS or SVN. Check Linus' talk, as it is very interesting, at. First, you need to install the Git client on your computer, which was originally conceived as a command-line tool by Linus Torvalds. However, nowadays we have visual clients at our disposal, which make life much easier. On both Windows and Mac, I will personally recommend SourceTree because it is quite intuitive and has everything you are likely to need at hand. However, there are alternatives such as Tortoise Git. Both are free, and the latter is also completely open source. SourceTree's installer can be found on its official site at. The package installation process varies across GNU/Linux distributions. In Debian-based distributions (most common ones), users can install the Git client using the command-line and apt-get: sudo apt-get install git This is a program capture; the cropped text is not relevant Every time you start a project, the first step should be to create a repository to keep track of everything that goes on with it. Services such as GitHub, Gitorious, and Google Code offer free repositories but require you to disclose the source. However, GitHub also allows you to create paid private repositories. Bitbucket is a competitive alternative if you seek a private repository at no cost. Last but not least, you can always host your own Git server at home, but then you will have to deal with problems such as backups, availability from the outside, and so on. Perform the following steps: Choose your poison, and create an account and a repository to start with, such as: GitHub, available at Gitorious, available at Google Code, available at Bitbucket, available at The next step will be to clone your newly created repository so as to have a local copy to work with. From SourceTree, click on Clone/New, select the Clone Repository tab, and enter the URL you received from the service of your choice. After entering the destination path, you can simply click on Clone, and the empty repository will be available on the leftmost panel, as shown in the following screenshot: GNU/Linux users can get away with the following command: git clone <REPO-URL> <DESTINATION-FOLDER> Have you already started working on your awesome game? Then, what you need to do is clone your brand new repository into an empty folder and pour all the project files there. Git requires an empty folder to either create or clone a repository. With your repository selected on SourceTree, click on Working Copy and take a close look at the Working Copy Changes panel; there will be tons of files that are not under source control asking you to include them, as shown in the following screenshot: The list of candidates for addition, deletion, and modified files can also be queried from the following command line: git status We do not need all this nonsense! If you already compiled something, there will be tons of clutter that will certainly become a huge waste of cloud storage. Though this comes cheap these days, it will be painful to upload and download changes further down the line. Ideally, we only want to keep track of whatever is absolutely necessary for someone to download a snapshot from the other end of the world and be able to continue working normally. Luckily enough, we can get rid of all the noise from git status and the Working Copy Changes panel by creating a .gitignore text file in the root folder of the repository with the following content: bin/ target/ obj/ .gwt/ gwt-unitCache/ war/ gen/ *.class It is time to add the .gitignore file to our repository. Perform the following steps: From the Working Copy Changes panel, right-click on the file and select Add to Index. Then, click on Commit, add a meaningful message such as Adds .gitignore file to make repository management easier, and finish by clicking on the Commit button on the modal window, as shown in the following screenshot: On the command line, it looks something like this: git add .gitignore git commit âm "Adds .gitignore file to make repository management easier" Now, you can safely proceed to add every remaining file and commit again. From GUI, follow the same process as with the .gitignorefile. However, if you are a command-line lover, you can stage and commit all the files at once like this: git add * git commit âm "Adds project basic files" Congratulations! Git is now keeping track of your project locally. Whenever you make changes, you simply need to add them again to the set of files about to be committed, and actually commit them. Obviously, you can achieve this with both the visual and command-line variants of the client. Note Writing meaningful commit messages might seem unimportant, but nothing is further away from the truth. Whenever you examine the history in search for the origin of a bug, you will want all the help you can get to understand what the person who made each commit was trying to do at that point in time. It is time to push all the commits you have made from your local repository to the remote repository hosted by the provider of your choice. This is the way your teammates, and potentially the whole world in case the repository is public, will be granted access to the changes. Perform the following steps: From SourceTree, click on Push and select the origin and destiny branches; typically, both will be named master. Once you are ready, click on OK and wait for the operation to finish, as shown in the following screenshot: Here is the command-line version of the same song: git push origin master Let's imagine that our game developer buddies have been sweating blood to add new shiny features. Naturally, you are eager to check what they have been up to and help them out. Assuming they pushed their changes to origin, you now need to pull every new commit and merge them with your working branch. Fortunately, Git will magically and gracefully take care of most conflicts. Perform the following steps: From SourceTree, you need to click on the Pull button and select the remote repository and branch you are pulling from. For a simplistic approach, these will be originand master. Once you are ready, click on the OK button, as shown in the following screenshot, and sit back and enjoy: A pull operation can also be triggered from the command line: git pull origin Git is a distributed revision control system. This means that, in principle, there is no central repository everyone commits to. Instead, developers have their own local repository containing the full history of the project. The way Git keeps track of your files is quite special. A complete snapshot of all the files within the repository is kept per version. Every time you commit a change, Git takes a brand new picture and stores it. Thankfully, Git is smart enough to not store a file twice, unless it changes from one version to another. Rather, it simply links the versions together. You can observe this process in the following diagram: As per the previous diagram, Version 1 has two files, A and B. Then, a commit is made updating A, so Git stores the new file and creates a link to B because it has not changed. The next commit modifies B, so Version 3 stores this file and a link to the unchanged revision of A. Finally, Version 4 contains modifications to A, a link to B (unchanged), and the first revision of the newly created file C. Most times you work with Git, you will operate locally because your repository contains everything that you need. It lets you check the full history, commit, and revert changes, among many others. This makes Git lightning fast and very versatile as it does not attach you to any Internet connection. The typical usage of Git is as follows: Clone a remote repository and make it locally available with git clone Modify, add, or remove files Add files to the staging area for them to be committed to your local repository with git add Commit the files and create a new version within your local repository using git commit Receive changes from a remote repository with git pull Send your local changes to a remote repository with git push Though we didn't use them, the way to experience Git's true glory is through branching and merging. You can think of the history of your repository as a series of directory-tree snapshots linked together. A commit is a small object that points to the corresponding snapshot and contains information about its ancestors. The first commit will not have a parentand subsequent commits will have a parent, but when a commit is the result of merging several changes together, it will have several parents. A branch is simply a movable pointer to one of these commits; you already know master, the default branch. The way we have been working, master will point to the last commit you made, as shown in the following diagram: Branching in Git has a minimal overhead as the only thing it does is create a new pointer to a certain commit. In the following diagram, we create a new branch called test: We can work on test for a while, go back to master, and then work on something different. Our repository will look something like this: Someone in the team decides it is time to bring the awesome changes made on test over to master; it is now merging time! A new commit object is created, with the last commits from master and test as parents. Finally, the master branch pointer moves forward so that it points to the new commit. Easy as pie! As we mentioned, this is not intended to be a comprehensive guide on Git but a mere introduction instead. If you are dying out of curiosity, I will wholeheartedly recommend Pro Git, which is freely available online under a Creative Commons license at. The .gitignore file we created earlier contains a list of rules that tell Git which files we are not interested in. Files under this branch of the directory tree that match the patterns and are not committed to the repository just yet, will not appear as candidates when running git status on the Source Tree Working Copy Changes panel. Typically, you will want to ignore specific files, that is, every file with a specific extension or anything that is under a certain folder. The syntax for these, in the same order, is quite simple: /game/doc/doc.pdf *.jar /game/game-core/bin SourceTree lets us add files and paths to .gitignore very easily. Select the file you want to add to the ignore list from the Working Copy Changes panel, and right-click and select Ignore. A new modal window will appear giving you the options to ignore just this file, all the files with this extension, or everything placed under a certain folder from the file's path. Once you select the option you want, click on OK, as shown in the following screenshot: This recipe was aimed at covering the very basics of the relationship between Libgdx and revision control systems. If you are interested in broadening your knowledge on the matter, read on. Regardless of what Linus Torvalds might tell you, Git is not the only revision control system out in the wild, and it might not be the best fit in your case. The following are other alternatives: Mercurial: This is cross-platform, open source, and completely distributed, just like Git. It is available at. Subversion: This is also cross-platform and open source, but it's a centralized system. It is usually perceived as easier to learn than Git and works for most projects. However, it is much less flexible. It is available at subversion.trigris.org. Perforce: This is a proprietary centralized system, but free for up to 20 users. It is widely used in the games industry for its binary file management. It is available at. Pro Git is a freely available book on how to master the version control system. It is available at. The Libgdx community is built around Git and hosted on GitHub. The following recipes are highly related to this revision control system: The Working from sources recipe in Chapter 13, Giving Back The Sending a pull request on GitHub recipe in Chapter 13, Giving Back Libgdx comes with a few full games to serve as example projects. Developers are encouraged to check them out, try them, and read the source code. It is a fantastic way to learn how things are done the Libgdx way. In this recipe, you will learn how to get and run the official demos. You only need to make sure your development environment works. The process to get up and running is explained in the Setting up a cross-platform development environment at the beginning of this chapter. There are eight official Libgdx demos. They are as follows: Pax Britannica: This is a one-button RTS available at Metagun: This is a 2D platformer available at Super Jumper: This is a Doodle Jump clone available at Invaders: This is a 2D Space Invaders clone available at Vector Pinball: This is a 2D pinball simulation using Box2D available at Cuboc: This is a 2D platformer available at The Plane That Couldn't Fly Good: This is a Flappy Bird clone available at Very Angry Robots: This is a 2D shooter platformer available at We will work with Super Jumper, but the process is identical for any other project; just follow these steps: Clone the repository using Git. The URL is available in the project page. Super Jumper's Git repository URL is [email protected]:libgdx/libgdx-demo-superjumper.git. If you do not know how to clone a Git repository, read the Using source control on a Libgdx project with Git recipe. Import the project from its folder into Eclipse following the instructions in the Setting up a cross-platform development environment recipe. Run each platform-specific project like any other Libgdx project. Now, you can run Super Jumper, as shown in the following screenshot: All the Libgdx official demos use Gradle as a build system, so the process of importing them into an IDE, getting them to compile, and running them is exactly the same as we saw in the past. As you progress through this book, it will be a great exercise to go back to the demos' source code and try to identify the concepts and techniques explained here. Luckily enough, the Libgdx community is big, active, and generous. This results in a great number of open source projects for people to study and learn from. Some of them can be found in the Libgdx gallery at.
https://www.packtpub.com/product/libgdx-cross-platform-game-development-cookbook/9781783287291
CC-MAIN-2020-50
refinedweb
11,733
53.31
Easy with defaultdict solution in Clear category for Call to Home by furtadobb """ to the day when they began. For example, if a call was started 2014-01-01 23:59:59, then it should be counted to 2014-01-01; """ import datetime import math from collections import defaultdict def cost(minutes): if minutes > 100: return (minutes - 100) * 2 + 100 return minutes def total_cost(calls) -> int: repo = defaultdict(int) total = 0 info = [(datetime.datetime.strptime(c[:19], '%Y-%m-%d %X'), c.split(' ')[-1]) for c in calls] for c in info: repo[c[0].date()] += math.ceil(int(c[1]) / 60) for c in repo.values(): total += cost(c) return total" Dec. 20, 2020 Forum Price For Teachers Global Activity ClassRoom Manager Leaderboard Jobs Coding games Python programming for beginners
https://py.checkio.org/mission/calls-home/publications/furtadobb/python-3/easy-with-defaultdict/share/2ed4120b36f137a576bd7798f1b4b1f2/
CC-MAIN-2022-21
refinedweb
131
56.15
Welcome to Cisco Support Community. We would love to have your feedback. For an introduction to the new site, click here. And see here for current known issues. Hello, I'm trying to develop a Webapp for showing content from Show and Share on my DMPs. I'm able to query SnS from PHP via XML Rest calls, but I'n not able to search for all featured videos. I'm searching for featured videos by this search param: <searchParam> <fieldName>com.cisco.vportal.1.featured</fieldName> <fieldValue>1</fieldValue> <paramClause>EQUAL</paramClause> <boost>0.9</boost> </searchParam> The featured Videos have this attributes: <contentattribute><key>featured</key><value>1</value><namespace>com.cisco.vportal.1</namespace></contentattribute><contentattribute><key>featured</key><value>2</value><namespace>com.cisco.vportal.1</namespace></contentattribute> So I need to search for a value greater than 0 or if this attribute exists.I've tried EXIST, GREATER aso. for paramClause, but nothing is working. I get this Java Exception: [detailed_response] => dms.general.error.no.invocation.error.key .... Caused by: com.cisco.vportal.exceptions.VPException: org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException: string value 'EXIST' is not a valid enumeration value for vpsearchparamclauseType in namespace What are the other enumeration values for vpsearchparamclauseType? Another question regarding the integration of SnS with DMP: The DMPs require MPEG-TS H.264 or MPEG-TS MPEG-2 videos and SnS require MP4 H.264. Is there a easy way to deploy videos to SnS, Digital Signage and Cast? I will answer the second part of your question. The is no easy part for playing VODs on all DMS components (SnS, DS, & CAST) at this time. You would need to transcode the SnS files to formats supported on the DMPs. In DMS 5.2 the 4400G (only) DMPs support playback of Windows Media files. The WIndows Media files can only be played back via DMP LOCAL Storage or via HTTP:// So if all of your content was Windows Media than the content would be compatible. The main problem that I forsee is if you have Apple Mac OSX users. Native OSX Browser support for WIndows Media is NOT supported at this time. The Mac users would need to use VMware with Windows to view the WMV content in SnS. I hope this helps! T.
https://supportforums.cisco.com/t5/digital-media-system/sns-api-and-integration-with-dmps/td-p/1456533
CC-MAIN-2017-43
refinedweb
384
60.01
Smart Dashboard << Simple Kenect Driver | FRC | Spike Coding >> - Make a new project - Select FRC-New CommandBasedRobot Template - call project name BroBot, other something you like--Package Name: org.usfirst.frc4101, Class name: Brobot - In the first package. Use the OI to bind the operator input, and RoboMap to make physical connections to logical names public class RobotMap{ public static final int leftMotor=1, rightMotor=2; } - The second package has the CommandBase and all the Commands you write. When you make a new command, be sure to add it to the CommandBase - The third package has our subsystems-- the hardware that is controlled by your Commands Adding a subsystem - rightclick on the third package which has our subsystems, and select New Subsystem (if that is not a choice, select Other, then find Subsystem - Name it and press next. here is example Claw subsystem. public class Claw extends Subsystem { // The claws motor Victor motor; // Initialize your subsystem here /** * Initialize the claw with the motor declared in {@link RobotMap} */ public Claw() { super("Claw"); motor = new Victor(RobotMap.clawMotor); } /** * Initialize the default command to be {@link ClawDoNothing}. */ public void initDefaultCommand() { setDefaultCommand(new ClawDoNothing()); } /** * Implements the claw's open capability. Simply tells the motor to move full * speed in one direction, it is the commands responsibility to tell it when * to stop opening. If the command doesn't, it will keep opening until the * command ends and the default command {@link ClawDoNothing} takes over. */ public void open() { motor.set(1); } /** * Implements the claw's close capability. Simply tells the motor to move * full speed in one direction, it is the commands responsibility to tell it * when to stop closing. If the command doesn't, it will keep opening until * the command ends and the default command {@link ClawDoNothing} takes over. */ public void close() { motor.set(-1); } /** * Implements the claw's do nothing capability. Simply tells the motor to * stop moving. After this is called the claw is neither opening or closing. */ public void doNothing() { motor.set(0); } } To Make a new Command - In CoomandBase add an import so it can find your new subsystem import edu.<your third package name>.brobot.subsystem.Claw public static Claw claw = new Claw(); - Go to the second package where the Commands are, right-clcik and select "New Command" like ClawDoNothing public class ClawDoNothing extends CommandBase { /** * Initialize the command so that it requires the claw. This means it will * be interrupted if another command requiring the claw is run. */ public ClawDoNothing() { requires(claw); } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run /** * Tells the claw to do nothing, stopping any previous movement. */ protected void execute() { claw.doNothing(); } // Make this return true when this Command no longer needs to run execute() /** * @return false, so that it executes forever or until another command * interrupts it. */ protected boolean isFinished() { return false; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } } To bind the Command to a button - Go to the first package and edit the OI class Here is and example from the Gears Robot public class OI { // Create the joystick and of the 8 buttons on it Joystick leftJoy = new Joystick(1); Button button1 = new JoystickButton(leftJoy, 1), button2 = new JoystickButton(leftJoy, 2), button3 = new JoystickButton(leftJoy, 3), button4 = new JoystickButton(leftJoy, 4), button5 = new JoystickButton(leftJoy, 5), button6 = new JoystickButton(leftJoy, 6), button7 = new JoystickButton(leftJoy, 7), button8 = new JoystickButton(leftJoy, 8); /** * Bind the press of each button to a specific command or command group. */ public OI() { button1.whenPressed(new PrepareToGrab()); button2.whenPressed(new Grab()); button7.whenPressed(new SodaDelivery()); } /** * @return The value of the left joystick. */ public double getLeftSpeed() { return leftJoy.getY(); } /** * @return The value of the right joystick. Note: this uses raw axis because * we have a logitech joystick that resembles a PS controller. */ public double getRightSpeed() { return leftJoy.getRawAxis(4); } }
https://mathorama.com/apcs/pmwiki.php?n=Main.SmartDashboard
CC-MAIN-2021-04
refinedweb
663
53.61
Frequently asked questions CSS Questions related to CSS Why doesn't my CSSPlugin work? Your chain is most likely not set up correctly. In case of the global config, make sure it looks like this: plugins : [ [ SassPlugin(), CSSPlugin() ] ] In case of a bundle specific config: fuse.bundle("app") .plugin(SassPlugin(),CSSPlugin() ) ) Warning Please double check the chain! It's very important!!! Note An array should be inside a plugin array! That's how the chaining in fusebox is achieved. Imports / Exports Questions related to imports/exports Default exports do not work Why my default exports doesn't work? It works with webpack?! import _ from "lodash" That's because typescript is not Babel. If you can configure it by adding a Babel Plugin. To solve this issue with typescript import your libraries as follows: import * as _ from "lodash" Bundling It says that "default" is undefined, why is that? When babel introduced ES2015 Modules => CommonJS, the spec wasn't completed. However, everyone was using it. The spec came along and stipulated that you cannot request a default import (ie. import Foo from 'x') from a module that doesn't have one. Instead, you must do import * as Foo from 'x' Why aren't my node modules transpiled? Because FuseBox does not transpile them. But you can easily do that by setting up the BabelPlugin like so: plugins : [ BabelPlugin({limit2project : false}) ] You can target the Babel Plugin to resolve a failing library like so: plugins : [ [ "node_modules/es6-lib/*", BabelPlugin({limit2project : false}) ] ] FuseBox deliberately limits Babel to increase the overal performance. That's why limit2project is required Why doesn't HMR work? HMR doesn't work with disabled cached. Enable it.
http://fuse-box.org/page/faq
CC-MAIN-2017-47
refinedweb
279
58.99
Agenda See also: IRC log previous minutes at approved Philippe: I moved status report item after xml protocol charter review, since Paul can only stay for 1/2 hour ACTION: plh to research IPR implications of a Core group (DONE) [recorded in] Philippe: we should put in the charter that the group is only allowed to do a Proposed rec without new features ... if we do a new feature, we'd need a new WG. Paulc. are you ok with that? Paul: Good enough, you did your AI. I'll check with laywers Philippe: Didn't ask Rigo about it, only talked to Ian Jacobs. We can come back to this question once we have a more concrete proposal on the table. Philippe: question is: what is the best NS you can get today? ... policy has decided to use new /ns convention without the year ... the drawback is: if there is a substantial change during CR, people will be unhappy if you change the semantics of the namespace <pauld> likes the year Paul: the NS for is a little bit easier to remember, but you might end up using "ns policy 2nd edition" NS Chris: so we have two choices: stick with /ns and might be forced to change it during CR ... (if we go to a new version: what do you do? only forward / backward compatible changes/?) ... I don't think there is a right answer Philippe: agreed there is no right answer ... the problem is the same as with the dated NS ... To my best knowledge, for V.Next, WGs are just adding new stuff to their namespace and try not to break it Paul: so policy could have choosen /2007/03 , or /ns form ... but in any case the best policy is not to change it during CR Philippe: unless you do substantial changes you don't change, right? Paul: want to distinguish between going back and forward ... so e.g. if you make a change to a feature and have to go back to WD, you can't use the namespace anymore Jacek: are you objecting against the /ns namespace policy? Paul: no, my point is: if you go backwards during CR you have "burned" the /ns namespace Jonathan: it occurs like wsdl would have a /ns/wsdl20 Philippe: it is up to the WG to decide what they want ... another way to avoid a different version of the /ns is to say: we would keep the same namespace in any case ... but some WG participants might disagree with such approach if they start implementing the specification Jonathan: for wsdl, you could do /ns/wsdl2 ... but I would challenge the idea that it is bad to change the NS between CR > PR ... it depends very much on the implementers community ... I thought about this recently, and maybe WSDL could make the change ... we did a lot of changes Philippe: the changes were marked at risk btw Jonathan: still there was a lot of changes Jacek: agree with most of what jonathan said ... I'm against /ns/wsdl2 ... difference between wsdl2.1 or wsdl2.2 is not good, I'd like to have /ns/wsdl ... remove of MEPs would not be a reason to do the change of the NS Jonathan: there was a lot of changes Jacek: do we need to go back to LC? Philippe: don't think so, there was a lot of clarifications ... but let's not discuss this now Jonathan: I'm in favor of using the /ns version for wsdl and want to bring that to the WG Paul: I concur with Philippe: It depends on the WG and what they want to achieve ... agree with jonathan to bring this to his WG ... jonathan is looking back from "after CR" so that's an easier position to be in. Jonathan: at entering CR I thought there might be changes which are close to significant ... maybe different to policy Paul: in xquery there was a change of data types without a new NS, and the WG agreed Philippe: In any case, it is important to describe what you want to do in the NS document when you move to CR. people are looking at that document for implementation expectation and might call you on it if you don't say anything. <cferris> +1 to plh that you document the namespace policy in the namespace document. ws-policy did this Jonathan: Jacek said it would be nice if namespaces would be "together" like various WSDL versions <cferris> Jonathan: we can decide independently but it would be good to know what WGs do <cferris>. Jacek: couldn't WGs say that they expect to change the /ns during CR? Philippe: needs to be discussed by each WG. W3C introduced /ns because of feedback of some WGs. ... the dated version is still available and W3C doesn't give any preference to one or the other. Jonathan: what will your WG do, Jacek? Jacek: prefer to do what WSDL does Philippe: did not talk to policy folks before sending message on interop event ... idea is to have an interop event where everybody can participate Paul: we are not in CR yet, will decide that tomorrow ... I want to get out of CR via the March / May f2f (without consulting Chris) ... we could use the second f2f for interop ... the May meeting is scheduled to be in Ottawa Philippe: in WSDL and Addressing, the interop events were before / after the actual f2f, not during the actual f2f. Paul: would other chairs find this useful? Bob: does May avoid XTech and WWW 2007 / AC meeting? Paul: we looked at WWW 2007 / AC, we did not look at XTech ... we planned for 23,24, 25 May ... to make clear: we ask "you come to the interop event and bring the implementation of your policy assertion"? Bob: I guess that is the expectation Chris: as XML Protocol chair we have a draft that is 4 days old ... I don't think we would be ready. The policy WG would need to develop tests for a May interop event Philippe: for the f2f in May, are you including the interop idea? Paul: we asked the hosts of both f2fs if there are rooms for interop tests ... beyond that there are no detailed plans ... the WG expects that there will be interop tests during the f2f Bob: I'll check what the developer overlap is between implementations WS-Policy and Addressing policy assertions Philippe: For Policy, you did not discuss in the WG how you want to do the testing, correct? Paul: true. However, IBM and MS submitted interop scenarios Philippe: might be difficult for people to integrate their own tests into that Paul: we don't need to provide that to leave CR, right? Philippe: correct. On the interop stuff: is it "just" test cases? Chris: yes Philippe: test cases is easy, the framework to check results is the hard part Chris: not sure if there will be a framework for testing Paul: last time we had an interop event without a framework, and it worked ... having a framework or not is quite subjective ACTION: bob to ask addressing for test development for policy assertions [recorded in] ACTION: cferris to ask xml protocol for test development for policy assertions [recorded in] ACTION: paulc and cferris to ask policy WG about CR exit criteria [recorded in] [Paul Cotton leaves the call] Chris: I asked everyone to look at Jonathan's note to have a discussion Philippe: does the WG just want to take the member submission and put it to REC, or do more functionality? Chris: we will take the submission as a starting point and will do issue resolution against it ... there are some things the WG may want to address, but I did not hear a desire to extend the functionality ... there is not much to extend Jonathan: the granularity could be extended ... Canon is interested in a high level of granularity Philippe: XML Protocol has to decide whether they want to extend the granularity ... the WG should discuss it and put it into the charter Jonathan: the charter is not clear if the document will be feature or schedule driven Chris: the WG does not want to make that their lifes project Jonathan: the WSDL WG had different answers to that question over time ... would have been better to have it explicit in the charter from the start ... would recommend to put a stake in the ground from the beginning Philippe: IMO, it is important for this WG to be schedule driven and the charter should emphasize this. We don't need an MTOM policy assertion in two years. [Paul Downey leaves the call] Philippe: Anything to report to the CG? Chris: we intend to have a poll tomorrow about transition to candidate rec Jacek: semantic annotation might be able to become a REC together with WSDL. What is the timeline for WSDL? Jonathan: we have about 10 issues open, interop testing is ongoing. So in best case, we could move in 2-3 weeks. Jacek: that is maybe outside our reach Jonathan: you never know, we could be stuck on an issue. Bob: addressing metadata is in LC, we are looking for feedback ... we hope to go to CR immediately Philippe: policy, description, ws-rx ought to give feedback on that document Chris: about XML Protocol: got FPWD of one-way MEP ... asked addressing and WSDL to look at that Jonathan: WSDL WG should provide comments by the end of the week Chris: after that we will target last call, around March Philippe: feb 20, any regrets? [none heard] Philippe: Paul Downey said this time is difficult. Would people be willing to change? no objection (in general) Philippe: I'll put it on the agenda for the Feb 20 call ... If at all possible, I'm guessing the only option is to move it to a different day at the same time Jacek: might be difficult for me. This call is easy since it's just after the SAWSDL one.
http://www.w3.org/2007/02/06-ws-cg-minutes.html
CC-MAIN-2016-22
refinedweb
1,681
77.47
Using jQuery's animate() Method To Power Easing-Based Iteration Last night, I was reading about jQuery animation when I had the thought that you could use the animate() method to power iteration in which the iteration-step was implemented with an easing function rather than with a liner incrementation. A while back, I demonstrated that the step callback of the animate() method could be used to create complex, custom animation; but, I think you could abstract that concept out even further to create animate-powered iteration. Now, why would you want to do this? I have no idea; but, it seemed like a fun thing to try. In the following code, I am adding the ease() function to the jQuery namespace: jQuery.ease( start, end, duration, easing, callback ) To relate this concept back to for-loop iteration, you can sort of think of the above as being equivalent to the following pseudo code: for (var i = start ; i <= end ; i = easing()){ callback( i ); } When the callback gets invoked for each step of the iteration, I am passing in the following parameters: - Index: The current value of the iteration index. - StepIndex: The current iteration (increments 1 for each callback invocation). - EstimatedSteps: The rough estimation of how many times the callback will be invoked. - Start: The original start value. - End: The original end value. To see this in action, take a look at the following code: <!DOCTYPE html> <html> <head> <title>Using jQuery's Animate / Easing For Iteration</title> <script type="text/javascript" src="./jquery-1.4.2.js"></script> <script type="text/javascript"> // I am the easing iteration funciton. This is built on top // of the core animate function so that it can leverage the // built-in timer optimization. jQuery.ease = function( start, end, duration, easing, callback ){ // Create a jQuery collection containing the one element // that we will be animating internally. var easer = $( "<div>" ); // Keep track of the iterations. var stepIndex = 0; // Get the estimated number of steps - this is based on // the fact that jQuery appears to use a 13ms timer step. // // NOTE: Since this is based on a timer, the number of // steps is estimated and will vary depending on the // processing power of the browser. var estimatedSteps = Math.ceil( duration / 13 ); // Set the start index of the easer. easer.css( "easingIndex", start ); // Animate the easing index to the final value. For each // step of the animation, we are going to pass the // current step value off to the callback. easer.animate( { easingIndex: end }, { easing: easing, duration: duration, step: function( index ){ // Invoke the callback for each step. callback( index, stepIndex++, estimatedSteps, start, end ); } } ); }; // -------------------------------------------------- // // -------------------------------------------------- // // Ease from star (1) to finish (100). $.ease( 1, 100, 1000, "swing", function(){ console.log( arguments ); } ); </script> </head> <body> <!-- Intentionally left blank. --> </body> </html> As you can see, I am defining an iteration from 1 to 100 over the course of 1000ms using the "swing" easing logic that comes with the jQuery core library. When I execute this iteration, the following arguments are logged to the console: [1.0002442725080185, 0, 77, 1, 100] [1.0021984381069835, 1, 77, 1, 100] [1.0549511893824843, 2, 77, 1, 100] [1.3162401292595844, 3, 77, 1, 100] [1.5386187677878915, 4, 77, 1, 100] [1.9360193865549626, 5, 77, 1, 100] [2.59404353372116, 6, 77, 1, 100] [3.188245767482659, 7, 77, 1, 100] [4.086498284786836, 8, 77, 1, 100] [5.3855378065454635, 9, 77, 1, 100] [6.047634999849525, 10, 77, 1, 100] [6.899998311311322, 11, 77, 1, 100] [7.735790848954654, 12, 77, 1, 100] [8.789299598058602, 13, 77, 1, 100] [9.823552772835283, 14, 77, 1, 100] [11.103130839289712, 15, 77, 1, 100] [12.359594482598432, 16, 77, 1, 100] [13.78378224943241, 17, 77, 1, 100] [15.169889687317145, 18, 77, 1, 100] [17.30106396143236, 19, 77, 1, 100] [19.067489633276345, 20, 77, 1, 100] [20.903703338652814, 21, 77, 1, 100] [22.805628223942726, 22, 77, 1, 100] [24.769041540274877, 23, 77, 1, 100] [26.789584019084327, 24, 77, 1, 100] [28.583467563574366, 25, 77, 1, 100] [30.556131432173697, 26, 77, 1, 100] [32.4225127863664, 27, 77, 1, 100] [34.17215696448678, 28, 77, 1, 100] [35.79644171193677, 29, 77, 1, 100] [37.43828402671404, 30, 77, 1, 100] [39.247104825491, 31, 77, 1, 100] [40.614355964536855, 32, 77, 1, 100] [42.29606192000807, 33, 77, 1, 100] [44.14175320508501, 34, 77, 1, 100] [46.30629455396736, 35, 77, 1, 100] [48.168230689872686, 36, 77, 1, 100] [50.34449141944896, 37, 77, 1, 100] [52.36566404216176, 38, 77, 1, 100] [54.84863422926178, 39, 77, 1, 100] [56.39530942469606, 40, 77, 1, 100] [58.397061818725085, 41, 77, 1, 100] [60.385644035463145, 42, 77, 1, 100] [62.50866192437266, 43, 77, 1, 100] [64.1606576911129, 44, 77, 1, 100] [66.23934837470433, 45, 77, 1, 100] [68.14238799630591, 46, 77, 1, 100] [70.01600485497607, 47, 77, 1, 100] [71.71667929686885, 48, 77, 1, 100] [73.66252580589837, 49, 77, 1, 100] [75.42934848097015, 50, 77, 1, 100] [77.15459570091967, 51, 77, 1, 100] [78.83539021693224, 52, 77, 1, 100] [80.46892891535957, 53, 77, 1, 100] [82.05248749256015, 54, 77, 1, 100] [83.58342499830574, 55, 77, 1, 100] [85.0591882401769, 56, 77, 1, 100] [86.58394705735986, 57, 77, 1, 100] [87.83544334643715, 58, 77, 1, 100] [89.2283451235411, 59, 77, 1, 100] [90.36274034270053, 60, 77, 1, 100] [91.61449701019272, 61, 77, 1, 100] [92.62422684883724, 62, 77, 1, 100] [93.57409585614153, 63, 77, 1, 100] [94.60482294732421, 64, 77, 1, 100] [95.485584276624, 65, 77, 1, 100] [96.23203685930869, 66, 77, 1, 100] [96.96732595386678, 67, 77, 1, 100] [97.67247740510233, 68, 77, 1, 100] [98.245592213661, 69, 77, 1, 100] [98.73908020293557, 70, 77, 1, 100] [99.15211836755276, 71, 77, 1, 100] [99.48401787083121, 72, 77, 1, 100] [99.7342251935759, 73, 77, 1, 100] [99.90232305719944, 74, 77, 1, 100] [99.98803111963072, 75, 77, 1, 100] [100, 76, 77, 1, 100] Internally, the ease() function creates a detached DOM node and then uses jQuery's animate() method to "animate" a fake CSS property that will act as our iteration index. Then, we simply hook into the step-callback in order to invoke the given iteration callback, passing in our current iteration value. It would have been simple enough to bypass the animate() method and set up my own timer using setInterval(). However, Javascript timers are expensive to use. jQuery handles this cost quite gracefully by creating a central timer from which all animate() methods are powered. As such, I figured it would make the most sense just to leverage the optimized infrastructure that jQuery already had in place. Again, I am not sure why anyone would want to use this; but, it popped into my head last night and I wanted to see if I could make it happen. Of course, this implementation presupposed that one would want to use a duration over which the iteration would take place. We could remove the duration aspect altogether, which gives me a new idea... but more on that later. Reader Comments As part of an exploration of function overloading, I have taken this concept and created two different forms of execution: with duration and without duration: Actually, this turned out to be useful for me. I'm not sure why jQuery doesn't expose support to something like this by default. Thanks! @Sathya, Oh cool - glad you found it useful. I think the hardest thing about this, as far as generic usefulness, is that it requires the concept of a "duration" in addition to a start/end. Although, I suppose you could just think of this as the "step" portion of a traditional for-loop. That said, I think it is cool and useful for specific things., first of all - THANK YOU :) I have a small problem though - the easing always starts from 0, no matter what number I set as the start parameter. I've set up a jsfiddle for testing, so maybe you can check it out and tell me what's wrong? Here's the link: @Witek, Aaaaand it's done. I changed the animated property from easingIndex to some existing css property - width. And it started working as expected. @Witek, Thanks! That was just what I needed. @Ben, I used this to animate a range input at page load. Thanks!
https://www.bennadel.com/blog/2007-using-jquerys-animate-method-to-power-easing-based-iteration.htm
CC-MAIN-2021-04
refinedweb
1,364
86.81
= Decoding this gives us the string SEQ = 4; DATA = 0x2c29150f1e311ef09bc9f06735acL; SIG = 0x1665fb2da761c4de89f27ac80cbL; So we have a sequence number, some data and a signature. Now let’s see if we can decrypt the data part. Apparently, crypto nerds Alice and Bob failed to choose a large enough n, allowing us to recover their private RSA keys. By converting the hexadecimal numbers to their full-fledged decimal values, and entering them somewhere like here (and here) we can find the prime factors of which the n consists: 0x53a121a11e36d7a84dde3f5d73cf = 38456719616722997 · 44106885765559411 0x99122e61dc7bede74711185598c7 = 49662237675630289 · 62515288803124247 With RSA, those primes factors (p and q) and the exponent (e = 0x10001 = 65537) are all you need to find the decryption key. To generate Bob’s private key, we can use a few simple python lines: from Crypto.PublicKey import RSA import gmpy n = long(3104649130901425335933838103517383) e = long(65537) p = 49662237675630289 q = 62515288803124247 d = long(gmpy.invert(e, (p-1)*(q-1))) rsa = RSA.construct( (n, e, d) ) Using this rsa key, we’re able to decrypt the data: decrypted = rsa.decrypt(long('0x2c29150f1e311ef09bc9f06735acL', 16)) print str(hex(decrypted)).strip('0x').rstrip('L').decode('hex') which results in the newline character ( 0x0a). Looking through the rest of the decoded packets, we notice every data contains one encrypted character. It would make sense to put the decrypted character at the position of the sequence number in an output string. All we have to fix now, is the problem of having multiple packets with the same sequence number. In order to seperate the bad from the good packets, we will need to check if the signature matches the packet using Alice’s private key. The following python script performs all of that for us. Only packets where the signature matches the data are considered as valid. Note that I first saved the pcapng as a pcap file in order to be able to use the python module pcapfile. from Crypto.PublicKey import RSA import gmpy # Alice's public encryption parameters n1 = long(1696206139052948924304948333474767) e = long(65537) # Bob's n2 = long(3104649130901425335933838103517383) # Yes! We can factorize the n p1 = 38456719616722997 q1 = 44106885765559411 p2 = 49662237675630289 q2 = 62515288803124247 # that means we can find the decryption exponent d phi1 = (p1-1)*(q1-1) phi2 = (p2-1)*(q2-1) d1 = long(gmpy.invert(e, phi1)) d2 = long(gmpy.invert(e, phi2)) # now construct the RSA with all the parameters rsa1 = RSA.construct( (n1, e, d1) ) rsa2 = RSA.construct( (n2, e, d2) ) # and decrypt the messages from a pcap file! from pcapfile import savefile cf = savefile.load_savefile(open("bob_alice_encrypted.pcap")) output = {} for p in cf.packets: pack = str(p.packet)[136:].decode('hex').decode('base64') if 'DATA' in pack: seq = int(pack.split(';')[0].split(' ')[2]) data = pack[16:].split(';')[0][:-1] sig = long(pack.split(';')[2].split(' = ')[1], 16) m = long(data, 16) decrypted = rsa2.decrypt(m) sigcheck = rsa1.sign(decrypted, '')[0] val = str(hex(decrypted)).strip('0x').rstrip('L').zfill(2).decode('hex') if sig == sigcheck: output[seq] = val print ''.join(output.values()) We are left with the flag: flag{n0th1ng_t0_533_h3r3_m0v3_0n}
https://www.honoki.net/2015/10/hack-lu-2015-creative-cheating/
CC-MAIN-2018-13
refinedweb
507
67.45
Use this stylesheet to extract only the text from any XML document. Sometimes you just want to leave the XML behind and keep only the text found in a document. The stylesheet text.xsl can do that for you. (There's an even easier way; see "Built-in Templates" following). It can be applied to any XML document, which includes XHTML. It is shown in Example 3-15. <xsl:stylesheet xmlns: <xsl:template <xsl:apply-templates </xsl:template> </xsl:stylesheet> This stylesheet finds the root node and then selects all element children (*) for processing. To test, apply this stylesheet to the XHTML document magnacarta.html, the pact between King John and the barony in England that was first signed at Runnymede on June 15, 1215 (see): xalan magnacarta.html text.xsl A small portion of the output is shown in Example 3-16. The result is shown in IE in Figure 3-18. Magna Carta: You can also extract text from a document just by relying on XSLT's built-in templates. A stylesheet as simple as this single line: <xsl:stylesheet will invoke the built-in templates because there is no explicit template for any nodes that might be found in the source document. The built-in templates process all the children of the root and all elements, and copies text through for attributes and text nodes (the built-in templates do nothing for comment, processing-instruction, or namespace nodes). The benefit of using text.xsl over built-in templates is that text.xsl gives you a framework to exercise some control over the output (e.g., through additions of templates). However, adding templates to text.xsl won't make any difference, unless those templates match the document element more precisely (and therefore have higher priority than the template matching *). An empty stylesheet is the simplest one to start from if you want to add more precise templates.
https://etutorials.org/XML/xml+hacks/Chapter+3.+Transforming+XML+Documents/Hack+39+Create+a+Text+File+from+an+XML+Document/
CC-MAIN-2021-31
refinedweb
319
75
Constant::Export::Lazy - Utility to write lazy exporters of constant subroutines This is an example of a My::Constants package that you can write using Constant::Export::Lazy that demonstrates most of its main features. This is from the file t/lib/My/Constants.pm in the source distro: package My::Constants; use strict; use warnings; use Exporter 'import'; use constant { X => -2, Y => -1, }; our @EXPORT_OK = qw(X Y); use Constant::Export::Lazy ( constants => { # This is the simplest way to go, just define plain constant # values. A => sub { 1 }, B => sub { 2 }, # You get a $ctx object that you can ->call() to retrieve the # values of other constants. This is how you can make some # constants depend on others without worrying about # ordering. Constants are still guaranteed to only be # fleshened once! SUM => sub { my ($ctx) = @_; $ctx->call('A') + $ctx->call('B'), }, # For convenience you can also access other constants, # e.g. those defined with constant.pm SUM_INTEROP => sub { my ($ctx) = @_; $ctx->call('X') + $ctx->call('Y'), }, # We won't call this and die unless someone requests it when # they import us. DIE => sub { die }, # These subroutines are always called in scalar context, and # thus We'll return [3..4] here. # # Unlike the constant.pm that ships with perl itself we don't # support returning lists. So if you want to return lists you # have to return a reference to one. LIST => sub { wantarray ? (1..2) : [3..4] }, # We can also supply a HashRef with "call" with the sub, and # "options" with options that clobber the global # options. Actually when you supply just a plain sub instead # of a HashRef we internally munge it to look like this more # verbose (and more flexible) structure. PI => { call => sub { 3.14 }, options => { override => sub { my ($ctx, $name) = @_; # You can simply "return;" here to say "I don't # want to override", and "return undef;" if you # want the constant to be undef. return $ENV{PI} ? "Pi is = $ENV{PI}" : $ctx->call($name); }, # This is an optional ref that'll be accessible via # $ctx->stash in any subs relevant to this constant # (call, override, after, ...) stash => { # This `typecheck_rx` is in no way supported by # Constant::Export::Lazy, it's just something # we're passing around to the 'after' sub below. typecheck_rx => qr/\d+\.\d+/s, # such an epicly buggy typecheck... }, }, }, }, options => { # We're still exporting some legacy constants via Exporter.pm wrap_existing_import => 1, # A general override so you can override other constants in # %ENV override => sub { my ($ctx, $name) = @_; return unless exists $ENV{$name}; return $ENV{$name}; }, after => sub { my ($ctx, $name, $value, $source) = @_; if (defined(my $stash = $ctx->stash)) { my $typecheck_rx = $stash->{typecheck_rx}; die "PANIC: The value <$value> for <$name> doesn't pass <$typecheck_rx>" unless $value =~ $typecheck_rx; } print STDERR "Defined the constant <$name> with value <$value> from <$source>\n" if $ENV{DEBUG}; return; }, }, ); 1; And this is an example of using it in some user code (from t/synopsis.t in the source distro): package My::User::Code; use strict; use warnings; use Test::More qw(no_plan); use lib 't/lib'; BEGIN { # Supply a more accurate PI $ENV{PI} = 3.14159; # Override B $ENV{B} = 3; } use My::Constants qw( X Y A B SUM SUM_INTEROP PI LIST ); is(X, -2); is(Y, -1); is(A, 1); is(B, 3); is(SUM, 4); is(SUM_INTEROP, -3); is(PI, "Pi is = 3.14159"); is(join(",", @{LIST()}), '3,4'); And running it gives: $ DEBUG=1 perl -Ilib t/synopsis.t Defined the constant <A> with value <1> from <callback> Defined the constant <B> with value <3> from <override> Defined the constant <SUM> with value <4> from <callback> Defined the constant <SUM_INTEROP> with value <-3> from <callback> Defined the constant <PI> with value <Pi is = 3.14159> from <override> Defined the constant <LIST> with value <ARRAY(0x16b8918)> from <callback> ok 1 ok 2 ok 3 ok 4 ok 5 ok 6 ok 7 ok 8 1..8 By default we only support importing constants explicitly by their own names and not something like Exporter's @EXPORT, @EXPORT_OK or %EXPORT_TAGS, but you can trivially add support for that (or any other custom import munging) using the "buildargs" callback. This example is from t/lib/My/Constants/Tags.pm in the source distro: package My::Constants::Tags; use v5.10; use strict; use warnings; use Constant::Export::Lazy ( constants => { KG_TO_MG => sub { 10**6 }, SQRT_2 => { call => sub { sqrt(2) }, options => { stash => { export_tags => [ qw/:math/ ], }, }, }, PI => { call => sub { atan2(1,1) * 4 }, options => { stash => { export_tags => [ qw/:math/ ], }, }, }, map( { my $t = $_; +( $_ => { call => sub { $t }, options => { stash => { export_tags => [ qw/:alphabet/ ], }, } } ) } "A".."Z" ), }, options => { buildargs => sub { my ($import_args, $constants) = @_; state $export_tags = do { my %export_tags; for my $constant (keys %$constants) { my @export_tags = @{$constants->{$constant}->{options}->{stash}->{export_tags} || []}; push @{$export_tags{$_}} => $constant for @export_tags; } \%export_tags; }; my @gimme = map { /^:/ ? @{$export_tags->{$_}} : $_ } @$import_args; return \@gimme; }, }, ); 1; And this is an example of using it in some user code (from t/synopsis_tags.t in the source distro): package My::More::User::Code; use strict; use warnings; use Test::More qw(no_plan); use lib 't/lib'; use My::Constants::Tags qw( KG_TO_MG :math :alphabet ); is(KG_TO_MG, 10**6); is(A, "A"); is(B, "B"); is(C, "C"); like(PI, qr/^3\.14/); And running it gives: $ perl -Ilib t/synopsis_tags.t ok 1 ok 2 ok 3 ok 4 ok 5 1..5 This is a library to write lazy exporters of constant subroutines. It's not meant to be a user-facing constant exporting API, it's something you use to write user-facing constant exporting APIs. There's dozens of modules on the CPAN that define constants in one way or another, why did I need to write this one? Our constants are fleshened via callbacks that are guaranteed to be called only once for the lifetime of the process (not once per importer or whatever), and we only call the callbacks lazily if someone actually requests that a constant of ours be defined. This makes it easy to have one constant exporting module that runs in different environments, and generates some subset of its constants depending on what the program that's using it actually needs. Some data that you may want to turn into constants may require modules that aren't available everywhere, queries to databases that aren't available everywhere, or make certain assumptions about the environment they're running under that may not be true across all your environments. By only defining those constants you actually need via callbacks managing all these special-cases becomes a lot easier. Maybe you have one constant indicating whether you're running in a dev environment, and a bunch of other constants that are defined differently if the dev environment constant is true. Now say you have several hundred constants like that, managing the inter-dependencies and ensuring that they're all defined in the right order with dependencies before dependents quickly gets messy. All this complexity becomes a non-issue when you use this module. When you define a constant you get a callback object that can give you the value of other constants. When you look up another constant we'll either generate it if it hasn't been materialized yet, or look up the materialized value in the symbol table if it has. Thus we end up with a Makefile-like system where you can freely use whatever other constants you like when defining your constants, and we'll lazily define the entire tree of constants on-demand. You only have to be careful not to introduce circular dependencies. Our API is exposed via a nested key-value pair list passed to use, see the "SYNOPSIS" for an example. Here's description of the data structure you can pass in: This is a key-value pair list of constant names to either a subroutine or a hash with "call" and optional options. Internally we just convert the former type of call into the latter, i.e. CONST => sub {...} becomes CONST => { call => sub { ... } }. The subroutine we'll call with a context object to fleshen the constant. It's guaranteed that this sub will only ever be called once for the lifetime of the process, except if you manually call it multiple times during an "override". Our options hash to override the global "options". The semantics are exactly the same as for the global hash. We support various options, most of these can be defined either globally if you want to use them for all the constants, or locally to one constant at a time with the more verbose hash invocation to "constants". The following options are supported: A callback that can only be supplied as a global option. If you provide this the callback we'll call it to munge any parameters to import we might get. This can be used (as shown in the synopsis) to strip or map parameters to e.g. implement support for %EXPORT_TAGS, or to do any other arbitrary mapping. This callback will be called with a reference to the parameters passed to import, and for convenience with the constants hash you provided (e.g. for introspecting the stashes of constants, see the synopsis example. This is expected to return an array with a list of constants to import, or the empty list if we should discard the return value of this callback and act is if it wasn't present at all. This plays nice with the "wrap_existing_import" parameter. When it's in force any constant names (or tag names, or whatever) you return that we don't know about ourselves we'll pass to the fallback import subroutine we're wrapping as we would if buildargs hadn't been defined. A boolean that can only be supplied as a global option. If you provide this the package you're importing us into has to already have a defined import subroutine. We'll clobber it with something that uses us to export all the constants we know about (i.e. the ones passed to "constants"), but anything we don't know about will be passed to the import subroutine we clobbered. This is handy for converting existing packages that use e.g. a combination of Exporter to export a bunch of constant constants without having to port them all over to Constant::Export::Lazy at the same time. This allows you to do so incrementally. For convenience we also support calling these foreign subroutines with $ctx->call($name). This is handy because when migrating an existing package you can already start calling existing constants with our interface, and then when you migrate those constants over you won't have to change any of the old code. We'll handle calling subroutines generated with perl's own constant.pm (including "list" constants), but we'll die in call if we call a foreign subroutine that returns more than one value, i.e. constants defined as use constant FOO = (1, 2, 3)> instead of use constant FOO = [1, 2, 3]>. If this isn't set and the class we're being imported into already has an import subroutine we'll die. There's a caveat with this related to how we check for an existing import subroutine. We don't use UNIVERSAL::can, instead we manually check the symbol table for the package we're being imported into. So this won't do the "right" thing if we're being imported into a package that doesn't have its own import subroutine, but gets it via a base class, we'll just silently shadow that import routine. The reason for this caveat is that if someone's ruined your day and imported the UNIVERSAL package UNIVERSAL::can("import") will return true for every single package, our check for an existing import will always return true, so those packages that are using us without setting wrap_existing_import will all fail. Maybe we could deal with this in some better way, e.g. do the "right" thing and e.g. not die if we detect an import routine and UNIVERSAL is loaded, but this edge case is really obscure, and I doubt anyone actually needs to use this package to export constants from a package that has a base class with an existing import routine. This callback can be defined either globally or locally and will be called instead of your call. In addition to the context object this will also get an argument to the $name of the constant that we're requesting an override for. This can be used for things like overriding default values based on entries in %ENV (see the "SYNOPSIS"), or anything else you can think of. In an override subroutine return $value will return a value to be used instead of the value we'd have retrieved from "call", doing a return; on the other hand means you don't want to use the subroutine to override this constant, and we'll stop trying to do so and just call "call" to fleshen it. You can also get the value of "call" by doing $ctx->call($name). We have some magic around override ensuring that we only get the value, we don't actually intern it in the symbol table. This means that calling $ctx->call($name) multiple times in the scope of an override subroutine is the only way to get Constant::Export::Lazy to call a "call" subroutine multiple times. We otherwise guarantee that these subs are only called once (as discussed in "It's lazy" and "call"). This callback will be called after we've just interned a new constant into the symbol table. In addition to the context object this will also get $name, $value and $source arguments. The $name argument is the name of the constant we just defined, $value is its value, and $source is either "override" or "callback" depending on how the constant was defined. I.e. via "override" or directly via "call". This was added to support replacing modules that in addition to just defining constants might also want to check them for well-formedness after they're defined, or push known constants to a hash somewhere so they can all be retrieved by some complimentary API that e.g. spews out "all known settings". You must return: from this subroutine, if anything's returned from it we'll die, this is to reserve any returning of values for future use. This is a reference that you can provide for your own use, we don't care what's in it. It'll be accessible via the context object's stash method (i.e. my $stash = $ctx->stash) for "call", "override" and "after" calls relevant to its scope, i.e. global if you define it globally, otherwise local if it's defined locally. This callback can be defined either globally or locally. When it's provided it'll be used to munge the internal name of the subroutine we define in the exporting package. This allows for preventing the anti-pattern of user code not importing constants before using them. To take the example in the synopsis it's for preventing My::Constants::PI and My::User::Code::PI interchangeably, using this facility we can change My::Constants::PI to e.g. My::Constants::SOME_OPAQUE_VALUE_PI. This is useful because users used to using other constant modules might be in the habit of using non-imported and imported names interchangeably. This is fine when the constant exporting module isn't lazy, however with Constant::Export::Lazy this relies on someone else having previously defined the constant at a distance, and if that someone goes away this'll silently turn into an error at a distance. By using the private_name_munger option you can avoid this happening in the first place by specifying a subroutine like: private_name_munger => sub { my ($gimme) = @_; # We guarantee that these constants are always defined by us, # and we don't want to munge them because legacy code calls # them directly for historical reasons. return if $gimme =~ /^ALWAYS_DEFINED_/; state $now = time(); return $gimme . '_TIME_' . $now; }, Anyone trying to call that directly from your exporting package as opposed to importing into their package will very quickly discover that it doesn't work. Because this is called really early on this routine doesn't get passed a $ctx object, just the name of the constant you might want to munge. To skip munging it return the empty list, otherwise return a munged name to be used in the private symbol table. We consider this a purely functional subroutine and you MUST return the same munged name for the same $gimme because we might resolve that $gimme multiple times. Failure to do so will result your callbacks being redundantly re-defined. As discussed above we pass around a context object to all callbacks that you can define. See $ctx in the "SYNOPSIS" for examples. This objects has only two methods: call This method will do all the work of fleshening constants via the sub provided in the "call" option, taking the "override" callback into account if provided, and if applicable calling the "after" callback after the constant is defined. If you call a subroutine you haven't defined yet (or isn't being imported directly) we'll fleshen it if needed, making sure to only export it to a user's namespace if explicitly requested. See "override" for caveats with calling this inside the scope of an override callback. stash An accessor for the "stash" reference, will return the empty list if there's no stash reference defined. Ævar Arnfjörð Bjarmason <avar@cpan.org> This software is copyright (c) 2013 by Ævar Arnfjörð Bjarmason <avar@cpan.org> This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
http://search.cpan.org/dist/Constant-Export-Lazy/lib/Constant/Export/Lazy.pm
CC-MAIN-2016-30
refinedweb
2,979
58.62
...making Linux just a little more fun! By Pramode C.E. The Python programming language's support for generators is described in PEP 255. This article demonstrates a few simple programs which make use of this feature to do some fun stuff like filtering out prime numbers, representing an `infinite' series expansion in a finite way, applying the Euler `accelerator' to make a series converge faster etc. Many of the programs which I describe here have been taken from `test_generators.py' which is available with the Python source distribution. A few ideas have been stolen from the Computer Science classic, Structure and Interpretation of Computer Programs. A generator is, simply put, a function which can stop whatever it is doing at an arbitrary point in its body, return a value back to the caller, and, later on, resume from the point it had `frozen' and merrily proceed as if nothing had happened. Here is a simple example: from __future__ import generators def foo(): print 'hello' yield 1 print 'world' yield 2 I am using Python 2.2 - in order to use the generator facility, a special `import' statement should be placed at the very beginning of the file. It may not be required in later versions. Note the `yield' keyword. A function which contains a yield statement anywhere in its body is considered to be special by the Python interpreter - it is treated differently from ordinary functions. Let's see how: >>> from gen1 import * >>> a = foo() >>> print a <generator object at 0x8158db8> We note that calling the function did not result in the function getting executed. Instead, the Python interpreter gave us a `generator object'. This is one of the implications of using the yield statement in the body of the function. Now, what do we do with this generator object? >>> a.next() hello 1 >>> a.next() world 2 >>> a.next() Traceback (most recent call last): File "<stdin>" line 1, in ? StopIteration Calling a.next() resulted in the function beginning its execution - it prints hello and comes to a dead stop at the `yield' statement, returning the value 1 to the caller. The function has gone back to its caller, but its `local state' has been fully preserved. Another invocation of a.next results in the function restarting from where it had stopped earlier - it prints `world' and stops after returning the value 2 to the caller. Yet another invocation of a.next results in the function `falling off' the end - because our function is a special `generator function', this will result in an exception, StopIteration, being raised. Let's now try running a for loop on our generator: >>> a = foo() >>> for i in a: ... print i ... hello 1 world 2 >>> The for loop works by invoking a.next() and assigning the value obtained to i, which then gets printed. The strings 'hello' and 'world' get printed as part of the execution of `foo'. It would also be interesting to try out invoking the `list' function on the generator object - we will get a list [1,2] as the result. In both cases (for loop as well as `list'), iteration stops when the StopIteration exception is raised. The body of a generator function should not contain a return statement of the form `return expr' - a simple `return' is allowed. The PEP discusses this and many more things. You should try running the following code: from __future__ import generators def foo(n): if (n < 3): yield 1 else: return yield 2 Try running a for loop over the generator objects returned by say, foo(10) and foo(1). Also, try calling next() on these objects. Generators present us with some fun ways to manipulate infinite sequences - though some people might question their practical utility! As far as we are concerned, being fun is reason enough! from __future__ import generators def foo(): i = 0 while 1: yield i i = i + 1 What we have above is the simplest possible `infinite' generator. Try calling next() on the generator object returned by calling `foo'. Give this object as an argument to a `for' loop - you will see that the loop keeps on printing numbers. If you wish Python to eat up memory, try running `list(foo())'. Try writing a more interesting function, say a Fibonacci series generator. Here is an infinite series of alternating positive and negative terms: 1 - 1/3 + 1/5 - 1/7 + ... This series converges to PI/4. We will write a Python generator for it. def pi_series(): sum = 0 i = 1.0; j = 1 while(1): sum = sum + j/i yield 4*sum i = i + 2; j = j * -1 Each `yield' statement keeps on returning a better approximation for PI. Test it out by calling `next' on the generator returned by invoking pi_series. We note that the series does not converge very fast. It would be convenient to have a function which would return the first N values yielded by a generator. def firstn(g, n): for i in range(n): yield g.next() Note that the first argument to this function is a generator object. Here is what I got when I tried out `list(firstn(pi_series(), 8))': [4.0, 2.666666666666667, 3.4666666666666668, 2.8952380952380956, 3.3396825396825403, 2.9760461760461765, 3.2837384837384844, 3.0170718170718178] We can apply a `sequence accelerator' to convert a series of terms to a new series which converges to the original value much faster. One such accelerator, invented by Leonhard Euler, is shown below: (Sn+1) stands for the (n+1)th term, (Sn-1) for the (n-1)th term. If Sn is the n'th term of the original sequence, then the accelerated sequence has terms as shown in the equation above. Let's try writing a generator function which accepts a generator object and returns an `accelerated' generator object. def euler_accelerator(g): s0 = g.next() # Sn-1 s1 = g.next() # Sn s2 = g.next() # Sn+1 while 1: yield s2 - (sqr(s2 - s1))/(s0 - 2*s1 + s2) s0, s1, s2 = s1, s2, g.next() Here is what I got when I tried printing the first few terms of this series: [3.166666666666667, 3.1333333333333337, 3.1452380952380956, 3.1396825396825401, 3.1427128427128435, 3.1408813408813416, 3.1420718170718178, 3.1412548236077655]Note that the series is converging much faster! You can get the program as a whole: A cute idea for `filtering out' prime numbers, invented by the Alexandrian mathematician Eratosthenes, works as follows. Suppose you want to find out all prime numbers below, say, 1000. You first cancel all multiples of 2 (except 2) from a list 1..1000. Now you will cancel all multiples of 3 (except 3). 4 has already been canceled, as it is a multiple of 2. Now you will take off all multiples of 5, except 5. And so on. Ultimately, what remains in the list would be prime numbers! Let's start with a generator which gives us all integers from `i' onwards: def intsfrom(i): while 1: yield i i = i + 1Now let's write a generator which will eliminate all multiples of a number `n' from a sequence: def exclude_multiples(n, ints): for i in ints: if (i % n): yield iAn invocation of the generator, say, list(firstn(exclude_multiples(2, intsfrom(1)), 5)), will give us the list [1,3,5,7,9]. Now, its time for us to build our `sieve'. def sieve(ints): while 1: prime = ints.next() yield prime ints = exclude_multiples(prime, ints)You can get the source file containing these function definitions from here: Generator functions can call themselves recursively. It takes some time getting used to it. Let's try analyzing the way the following functions work: from __future__ import generators def abc(): a = deff() for i in a: yield i yield 'abc' def deff(): a = ijk() for i in a: yield i yield 'deff' def ijk(): for i in (1,2,3): yield i yield 'ijk'An invocation of abc will yield a generator object. Calling `next' on it would result in `abc' starting execution. The very first line of `abc' invokes `deff' which returns a generator object. After that, a.next() is invoked as part of the very first iteration of the for loop. This results in `deff' starting execution the same way. The body of `deff' builds a generator object by calling `ijk' and calls its `next' method as part of the for loop. This results in `ijk' starting execution and yielding 1, `deff' also yields 1, and `abc' also yields 1. Calling the `next' method (of the generator object returned by invoking `abc') two more times will result in the values 2 and 3 getting propagated up. Yet another invocation will result in the string `ijk' propagating up the call stack because the for loop in the body of `ijk' has terminated. Calling `next' again will result in the body of `ijk' terminating, with the result that the `for' loop in `deff' gets a StopIteration exception, which results in that loop terminating and the function yielding the string `deff'. Subsequent invocation of `next' will result in `abc' being returned to the top level caller. The final invocation of next (again, note that we are invoking `next' on the object returned by calling `abc') will result in the caller getting a StopIteration exception because the body of `abc' has also been executed in full. Let's now look at Guido's binary tree example. The classical inorder traversal is coded as below: def inorder(t): if t: for x in inorder(t.left): yield x yield t.dat for x in inorder(t.right): yield xLet's think of invoking inorder on a tree with only one node (say containing data 50). Doing `for x in inorder(t.left)' is same as: a = inorder(t.left) for x in a: ....Because t.left is 0, calling a.next() (which the for loop does) results in a StopIteration exception - this terminates the loop immediately. The next statement in the body is `yield t.dat' - this returns 50. The next for loop also terminates immediately because of a StopIteration. It should be easy to visualize the way the code works for more complex tree structures. Here is the source for the program - [ Listing 7 ]. Let's define a `signal' as a stream of positive and negative integers. 1 2 -1 -4 3 2 -3 -4 2 3 4 -2 ... A zero-crossing detector outputs a signal which describes the zero crossings of the input signal - the resulting signal is +1 whenever the input signal changes from negative to positive, -1 whenever input signal changes from positive to negative and 0 otherwise. We shall assume that 0 is positive. Here is the zero-cross detector: def zerocross(g): a = g.next() b = g.next() while 1: yield cross_detect(a, b) a, b = b, g.next()If the signal is coming from a sensor, noise will lead to spurious zero crossings. So, we can think of `smoothing' the signal (using some form of `moving average' computation) and then detecting the zero crossings. Most of the code has been `lifted' from `test_generators.py', which comes with the Python source distribution. Thanks to the Python community for many hours of pleasurable code reading, and for creating the BEST programming language in the world! Thanks to the authors of SICP for making such a classic freely available on the web! I am an instructor working for IC Software in Kerala, India. I would have loved becoming an organic chemist, but I do the second best thing possible, which is play with Linux and teach programming!
http://www.tldp.org/LDP/LGNET/100/pramode.html
CC-MAIN-2013-48
refinedweb
1,928
64.71
MooX-Struct =========== Created: 2012-10-04 Home page: <> Bug tracker: <> Maintainer: Toby Inkster (TOBYINK) <tobyink@cpan.org> 0.013 2014-09-10 [ Packaging ] - Switch to Dist::Inkt. 0.012 2013-05-18 [ Bug Fixes ] - Stop relying on hash order to pass t/14trace.t. 0.011 2013-05-12 [ Documentation ] - Add CAVEATS section to documentation. Chris Prather++ <> 0.010 2012-12-21 100% Devel::Cover coverage! [ Bug Fixes ] - Passing objects overloading hash dereference to the constructor was supposed to be supported; now it actually works. - Processing flags in EXTEND method could cause infinite loop. - Usage with Data::Printer was causing an exception related to prototypes. [ Other ] - Added: Many new test cases. 0.009 2012-12-18 [ Bug Fixes ] - Fix an internal issue in MooX::Struct::Processor, whereby it would ignore attributes inherited from the default base class when building the FIELDS method. [ Packaging ] - Moar test cases. [ Other ] - Attributes inherited from roles are no longer included in FIELDS. - Moo-style constructor is no longer strict. (This may change back!) 0.008 2012-12-17 [ Documentation ] - Add pod to test suite. [ Other ] - Added: Provide '-class' feature (currently tested for but not documented). 0.007 2012-10-28 - Added: Allow namespace::clean behaviour to be avoided via a '-retain' flag. 0.006 2012-10-09 [ Bug Fixes ] - Fix minor pod syntax error. [ Other ] - Added: Allow structs to consume roles using '-with' option. - Added: Bundle MooX::Struct::Util. - Added: New experimental method 'EXTEND'. - Constructor is now strict; it will croak if passed hash keys it doesn't recognise. - Removed: Dropped 'object_id' alias for 'OBJECT_ID'. 0.005 2012-10-08 - Added: New method 'CLONE'. - Added: New method 'FIELDS'. - Added: New method 'TO_HASH'. - Added: New method 'TO_STRING'. - Added: New method 'TYPE'. - Added: Overload a lot of operations on structs. - Added: Provide Point[$x,$y] style constructor. - Added: Special Data::Printer support. - The 'object_id' method is now called 'OBJECT_ID'. 0.004 2012-10-07 [ Bug Fixes ] - Workaround strange closure bug in Perl < 5.14. Fixes RT#80043. <> 0.003 2012-10-05 [ Bug Fixes ] - Broken and undocumented sigils feature is now working, documented and tested. [ Other ] - Added: New bang postfix sigil, indicating a required attribute. - The '-isa' feature for setting superclasses is now called '-extends'. 0.002 2012-10-05 [ Packaging ] - List dependencies. 0.001 2012-10-04 Initial release
https://metacpan.org/changes/distribution/MooX-Struct
CC-MAIN-2016-40
refinedweb
383
63.05
Loads a Workload Manager (WLM) configuration into the kernel. Workload Manager Library (libwlm.a) #include <sys/wlm.h> int wlm_set ( flags) int *flags; The wlm_set subroutine is used to set, change, or query the mode of operations of WLM. The state of WLM can be: All combinations of the flags above are not legal: Upon successful completion, the wlm_set subroutine returns a value of 0, and the current state of WLM is returned in the integer pointed to by flags. The return value is WLM_OFF, WLM_ACTIVE, or WLM_PASSIVE. When WLM is on in either active or passive mode, the WLM_BIND_RSETS flag is added when WLM uses resource sets bindings. For a list of the possible error codes returned by the WLM API functions, see the description of the wlm.h header file. The wlmcntrl command. The wlm.h header file. The wlm_load (wlm_load Subroutine) subroutine.
http://ps-2.kev009.com/wisclibrary/aix51/usr/share/man/info/en_US/a_doc_lib/libs/basetrf2/wlm_set.htm
CC-MAIN-2022-33
refinedweb
145
68.06
Hi, I want to pass an object from a jsp to a servlet. I've tried to use request.setAttribute("Object", object) in the jsp page and call the object in my servlet using request.getAttribute("Object"). Unfortunately did work. Could anybody help me with this and give expample code? I'm new to JSP and please don't slaughter me when this is a pretty easy and stupid question ;-) Cheers Passing an object from jsp to servlet (4 messages) - Posted by: Silke Langenberg - Posted on: January 29 2005 12:13 EST Threaded Messages (4) - Passing an object from jsp to servlet by Matt Weaver on February 01 2005 10:25 EST - JSP TO SERVLET Passing Object by ss ssss on February 24 2005 06:25 EST - Passing an object from jsp to servlet by sachin desai on April 25 2005 05:28 EDT - To pass an object from jsp to servlet by dhaval chavda on March 17 2010 03:10 EDT Passing an object from jsp to servlet[ Go to top ] Inside the JSP you want to use response.setAttribute("obj", obj); The response is what will be sent to the Servlet. - Posted by: Matt Weaver - Posted on: February 01 2005 10:25 EST - in response to Silke Langenberg You could also stick it in the session (just be sure to clean up afterwards or you will get an "over-stuffed session"). Normally you get POST data from a form and create your objects in a Servlet (request.getParameter("")) instead of (request.getAttribute(""), assuming you set it). You should seek to minimize Java code in jsps (that's what tlds are for). This makes the front end easier for non-developers to create (what is all this junk in my HTML?). Otherwise, you are running into the danger of making big, complicated jsps that contain way too much java code. This is actually symptomatic of an anti-pattern (monolithic jsp). I have seen jsps that are several thousand lines of mostly java code. Don't let that happen to you! JSP TO SERVLET Passing Object[ Go to top ] hi, - Posted by: ss ssss - Posted on: February 24 2005 06:25 EST - in response to Silke Langenberg to pass a object from JSP Page to Servlet you use the method doPost(HttpServletRequest request, HttpServletResponse response) or doGet(HttpServletRequest request, HttpServletResponse response) eg. import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class greetServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { //Get Parameters from the request String name=request.getParameter("name"); String email=request.getParameter("email"); String message=null; } } Passing an object from jsp to servlet[ Go to top ] please fwd the same info to me. - Posted by: sachin desai - Posted on: April 25 2005 05:28 EDT - in response to Silke Langenberg thanking you. Sachin. To pass an object from jsp to servlet[ Go to top ] hey dear.if u not getting with setAttribute and getAttribute than make use of usebean.take usebean in between and in that set a value for ur object and get in servlet page.u will get it. - Posted by: dhaval chavda - Posted on: March 17 2010 03:10 EDT - in response to Silke Langenberg
http://www.theserverside.com/discussions/thread.tss?thread_id=31484
CC-MAIN-2017-17
refinedweb
540
69.72
When you have to store a set of strings, what data structure should you use? You could use hash tables, which sprinkle the strings throughout an array. Access is fast, but information about relative order is lost. Another option is the use of binary search trees, which store strings in order, and are fairly fast. Or you could use digital search tries, which are lightning fast, but use lots of space. In this article, we'll examine ternary search trees, which combine the time efficiency of digital tries with the space efficiency of binary search trees. The resulting structure is faster than hashing for many typical search problems, and supports a broader range of useful problems and operations. Ternary searches are faster than hashing and more powerful, too. We described the theory of ternary search trees at a symposium in 1997 (see "Fast Algorithms for Sorting and Searching Strings," by J.L. Bentley and R. Sedgewick, Proceedings of the 8th Annual ACM-SIAM Symposium on Discrete Algorithms, January 1997). In this article, we'll concentrate on what the data structure offers working programmers. Algorithms in C, Third Edition, by Robert Sedgewick (Addison-Wesley, 1998) provides yet another view of ternary search trees. For more information (including all the code in this article and the driver software), refer to or see "Resource Center," page 3. A Grove of Trees Figure 1 is a binary search tree that represents 12 common two-letter words. For every node, all nodes down the left child have smaller values, while all nodes down the right child have greater values. A search starts at the root. To find the word "on," for instance, we compare it to "in" and take the right branch. We take the right branch at "of" and the left branch at "or," and then arrive at "on." Every comparison could access each character of both words. Figure 1: A binary search tree for 12 words. Digital search tries store strings character by character. Figure 2 is a tree that represents the same set of 12 words; each input word is shown beneath the node that represents it. (Two-letter words lead to prettier pictures; all structures that we'll see can store variable-length words.) In a tree representing words of lowercase letters, each node has 26-way branching (though most branches are empty, and not shown in Figure 2). Searches are very fast: A search for "is" starts at the root, takes the "i" branch, then the "s" branch, and ends at the desired node. At every node, we access an array element (one of 26), test for null, and take a branch. Unfortunately, search tries have exorbitant space requirements: Nodes with 26-way branching typically occupy 104 bytes, and 256-way nodes consume a kilobyte. Eight nodes representing the 34,000-character Unicode Standard would together require more than a megabyte! Figure 2: A digital search trie for 12 words. Ternary search trees combine attributes of binary search trees and digital search tries. Like tries, they proceed character by character. Like binary search trees, they are space efficient, though each node has three children, rather than two. A search compares the current character in the search string with the character at the node. If the search character is less, the search goes to the left child; if the search character is greater, the search goes to the right child. When the search character is equal, though, the search goes to the middle child, and proceeds to the next character in the search string. Figure 3 is a balanced ternary search tree for the same set of 12 words. The low and high pointers are shown as solid lines, while equal pointers are shown as dashed lines. Each input word is shown beneath its terminal node. A search for the word "is" starts at the root, proceeds down the equal child to the node with value "s," and stops there after two comparisons. A search for "ax" makes three comparisons to the first letter ("a") and two comparisons to the second letter ("x") before reporting that the word is not in the tree. Figure 3: A ternary search tree for 12 words. The idea behind ternary search trees dates back at least as far as 1964. In "Randomized Binary Searching with Tree Structures" (Communications of the ACM, March 1964), H.A. Clampett sketched a primitive version of the structure. Computer scientists have proven many theorems about the trees; for instance, searching for a string of length k in a ternary search tree with n strings will require at most O( log n+ k) comparisons. The C Structure As far as we can tell, previous authors have viewed ternary search trees as a theoretical structure for proving theorems. We were delighted to find that the trees also lead to practical computer programs. Although we've chosen to illustrate the data structure in C, we could have just as easily chosen C++, Java, or other languages. Each node in a ternary search tree is represented by the following structure: typedef struct tnode *Tptr; typedef struct tnode { char splitchar; Tptr lokid, eqkid, hikid; } Tnode; The value stored at the node is splitchar, and the three pointers represent the three children. The root of the tree is declared to be Tptr root. We will represent every character in each string, including the null character that terminates it. Membership Searching We begin with a recursive version of the search function. It returns 1 if string s is in the subtree rooted at p, and 0 otherwise; it is originally called as rsearch(root, s): int rsearch(Tptr p, char *s) { if (!p) return 0; if (*s < p->splitchar) return rsearch(p->lokid, s); else if (*s > p->splitchar) return rsearch(p->hikid, s); else { if (*s == 0) return 1; return rsearch(p->eqkid, ++s); } } The first if returns 0 if the search has run off the end of the tree. The next two if statements take the low and high branches as appropriate. The final else branch returns 1 if the current character is the end-of-string character 0, and otherwise moves to the next input character and to the equal branch. Some programmers might feel more comfortable with the iterative version of the search function (which has only one argument): int search(char *s) { Tptr p; p = root; while (p) { if (*s < p->splitchar) p = p->lokid; else if (*s == p->splitchar) { if (*s++ == 0) return 1; p = p->eqkid; } else p = p->hikid; } return 0; } This is substantially faster on some compilers, and we'll use it in later experiments. On most optimizing compilers, though, the run time of the recursive version is within a few percent of the iterative version. Both versions of the search use a pattern that we will see repeatedly: If the search character is less, go to lokid; if it is greater, go to hikid; if it is equal, go to the next character and eqkid. The following code illustrates that shorter is not always cleaner, simpler, faster, or better: int rsearch2(Tptr p, char *s) { return (!p ? 0 : ( *s == p->splitchar ? (*s ? rsearch2(p->eqkid, ++s) : 1) : (rsearch2(*s < p->splitchar ? p->lokid : p->hikid, s)) )); }
http://www.drdobbs.com/database/ternary-search-trees/184410528?cid=SBX_ddj_related_mostpopular_default_combining_tbb_and_ipp_with_intel_paralle&itc=SBX_ddj_related_mostpopular_default_combining_tbb_and_ipp_with_intel_paralle
CC-MAIN-2015-14
refinedweb
1,209
69.92
Teuchos::FILEstream: Combined C FILE and C++ stream. More... #include <Teuchos_FILEstream.hpp> Teuchos::FILEstream: Combined C FILE and C++ stream. Teuchos::FILEstream is a class that defines an object that is simultaneously a C FILE object and a C++ stream object. The utility of this class is in connecting existing C++ code that uses streams and C code that uses FILEs. An important example of this situation is the python wrappers for Trilinos packages. Trilinos is of course written primarily in C++, but the python wrappers must interface to the python C API. Wrappers for Trilinos methods or operators that expect a stream can be given a Teuchos::FILEstream, which then behaves as a FILE within the python C API. This is a low-level object that should not be needed at the user level. Definition at line 67 of file Teuchos_FILEstream.hpp. Constructor. The only constructor for Teuchos:FILEstream, and it requires a pointer to a C FILE struct. Definition at line 76 of file Teuchos_FILEstream.hpp.
http://trilinos.sandia.gov/packages/docs/r10.8/packages/teuchos/doc/html/classTeuchos_1_1FILEstream.html
CC-MAIN-2014-10
refinedweb
168
65.22