Search Results

Search found 165 results on 7 pages for 'flatten'.

Page 4/7 | < Previous Page | 1 2 3 4 5 6 7  | Next Page >

  • Puppet yum repo - Pull down 2.7.x vs 3.0.x

    - by Mike Purcell
    So a few weeks ago I started on the path to using puppet to automate all the configs/services. At the time I was using the EPEL repo, which installed version 2.6.x. After some reading I was trying to gain access to the flatten method available via the puppet stdlib, and thought it was available by default in the newer 2.7.x version. So I added a puppet repo with the following settings: [puppetlabs] name=Puppet Labs Packages baseurl=http://yum.puppetlabs.com/el/$releasever/products/$basearch/ enabled=1 gpgcheck=1 gpgkey=http://yum.puppetlabs.com/RPM-GPG-KEY-puppetlabs The problem with this, is it installed v3.0.x instead of 2.7.x. And apparently 3.0.x is a major upgrade which was released only a few weeks ago. Obviously I would prefer to use the 2.7.x for the next few months while PuppetLabs fix any defects which will inevitably arise after a major version. So my question is, what setting can I add to the puppet repo config to pull down only the 2.7.x branch and not the 3.0.x branch?

    Read the article

  • Convert SWF/FLA back to PDF [closed]

    - by mitjak
    Possible Duplicate: How do I convert SWF into a PDF? I have a number of graphics and text only SWF and FLA files that I'd like to convert to PDF preserving the text and formatting. Printing to PDF from Flash Player seems to flatten everything into an image without preserving the text. I've got a large number of those files, so it would be quite nice to have a automatable/console utility to do the job. Appreciate any help or pointers. Thanks! EDIT: It seems like most SWF files were created with pdf2swf, so I'm hoping there is a similar tool for doing a reverse conversion.

    Read the article

  • Netflix, jQuery, JSONP, and OData

    - by Stephen Walther
    At the last MIX conference, Netflix announced that they are exposing their catalog of movie information using the OData protocol. This is great news! This means that you can take advantage of all of the advanced OData querying features against a live database of Netflix movies. In this blog entry, I’ll demonstrate how you can use Netflix, jQuery, JSONP, and OData to create a simple movie lookup form. The form enables you to enter a movie title, or part of a movie title, and display a list of matching movies. For example, Figure 1 illustrates the movies displayed when you enter the value robot into the lookup form.   Using the Netflix OData Catalog API You can learn about the Netflix OData Catalog API at the following website: http://developer.netflix.com/docs/oData_Catalog The nice thing about this website is that it provides plenty of samples. It also has a good general reference for OData. For example, the website includes a list of OData filter operators and functions. The Netflix Catalog API exposes 4 top-level resources: Titles – A database of Movie information including interesting movie properties such as synopsis, BoxArt, and Cast. People – A database of people information including interesting information such as Awards, TitlesDirected, and TitlesActedIn. Languages – Enables you to get title information in different languages. Genres – Enables you to get title information for specific movie genres. OData is REST based. This means that you can perform queries by putting together the right URL. For example, if you want to get a list of the movies that were released after 2010 and that had an average rating greater than 4 then you can enter the following URL in the address bar of your browser: http://odata.netflix.com/Catalog/Titles?$filter=ReleaseYear gt 2010&AverageRating gt 4 Entering this URL returns the movies in Figure 2. Creating the Movie Lookup Form The complete code for the Movie Lookup form is contained in Listing 1. Listing 1 – MovieLookup.htm <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Netflix with jQuery</title> <style type="text/css"> #movieTemplateContainer div { width:400px; padding: 10px; margin: 10px; border: black solid 1px; } </style> <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></script> <script src="App_Scripts/Microtemplates.js" type="text/javascript"></script> </head> <body> <label>Search Movies:</label> <input id="movieName" size="50" /> <button id="btnLookup">Lookup</button> <div id="movieTemplateContainer"></div> <script id="movieTemplate" type="text/html"> <div> <img src="<%=BoxArtSmallUrl %>" /> <strong><%=Name%></strong> <p> <%=Synopsis %> </p> </div> </script> <script type="text/javascript"> $("#btnLookup").click(function () { // Build OData query var movieName = $("#movieName").val(); var query = "http://odata.netflix.com/Catalog" // netflix base url + "/Titles" // top-level resource + "?$filter=substringof('" + escape(movieName) + "',Name)" // filter by movie name + "&$callback=callback" // jsonp request + "&$format=json"; // json request // Make JSONP call to Netflix $.ajax({ dataType: "jsonp", url: query, jsonpCallback: "callback", success: callback }); }); function callback(result) { // unwrap result var movies = result["d"]["results"]; // show movies in template var showMovie = tmpl("movieTemplate"); var html = ""; for (var i = 0; i < movies.length; i++) { // flatten movie movies[i].BoxArtSmallUrl = movies[i].BoxArt.SmallUrl; // render with template html += showMovie(movies[i]); } $("#movieTemplateContainer").html(html); } </script> </body> </html> The HTML page in Listing 1 includes two JavaScript libraries: <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></script> <script src="App_Scripts/Microtemplates.js" type="text/javascript"></script> The first script tag retrieves jQuery from the Microsoft Ajax CDN. You can learn more about the Microsoft Ajax CDN by visiting the following website: http://www.asp.net/ajaxLibrary/cdn.ashx The second script tag is used to reference Resig’s micro-templating library. Because I want to use a template to display each movie, I need this library: http://ejohn.org/blog/javascript-micro-templating/ When you enter a value into the Search Movies input field and click the button, the following JavaScript code is executed: // Build OData query var movieName = $("#movieName").val(); var query = "http://odata.netflix.com/Catalog" // netflix base url + "/Titles" // top-level resource + "?$filter=substringof('" + escape(movieName) + "',Name)" // filter by movie name + "&$callback=callback" // jsonp request + "&$format=json"; // json request // Make JSONP call to Netflix $.ajax({ dataType: "jsonp", url: query, jsonpCallback: "callback", success: callback }); This code Is used to build a query that will be executed against the Netflix Catalog API. For example, if you enter the search phrase King Kong then the following URL is created: http://odata.netflix.com/Catalog/Titles?$filter=substringof(‘King%20Kong’,Name)&$callback=callback&$format=json This query includes the following parameters: $filter – You assign a filter expression to this parameter to filter the movie results. $callback – You assign the name of a JavaScript callback method to this parameter. OData calls this method to return the movie results. $format – you assign either the value json or xml to this parameter to specify how the format of the movie results. Notice that all of the OData parameters -- $filter, $callback, $format -- start with a dollar sign $. The Movie Lookup form uses JSONP to retrieve data across the Internet. Because WCF Data Services supports JSONP, and Netflix uses WCF Data Services to expose movies using the OData protocol, you can use JSONP when interacting with the Netflix Catalog API. To learn more about using JSONP with OData, see Pablo Castro’s blog: http://blogs.msdn.com/pablo/archive/2009/02/25/adding-support-for-jsonp-and-url-controlled-format-to-ado-net-data-services.aspx The actual JSONP call is performed by calling the $.ajax() method. When this call successfully completes, the JavaScript callback() method is called. The callback() method looks like this: function callback(result) { // unwrap result var movies = result["d"]["results"]; // show movies in template var showMovie = tmpl("movieTemplate"); var html = ""; for (var i = 0; i < movies.length; i++) { // flatten movie movies[i].BoxArtSmallUrl = movies[i].BoxArt.SmallUrl; // render with template html += showMovie(movies[i]); } $("#movieTemplateContainer").html(html); } The movie results from Netflix are passed to the callback method. The callback method takes advantage of Resig’s micro-templating library to display each of the movie results. A template used to display each movie is passed to the tmpl() method. The movie template looks like this: <script id="movieTemplate" type="text/html"> <div> <img src="<%=BoxArtSmallUrl %>" /> <strong><%=Name%></strong> <p> <%=Synopsis %> </p> </div> </script>   This template looks like a server-side ASP.NET template. However, the template is rendered in the client (browser) instead of the server. Summary The goal of this blog entry was to demonstrate how well jQuery works with OData. We managed to use a number of interesting open-source libraries and open protocols while building the Movie Lookup form including jQuery, JSONP, JSON, and OData.

    Read the article

  • CodePlex Daily Summary for Monday, April 05, 2010

    CodePlex Daily Summary for Monday, April 05, 2010New Projects.Net Data Form Wizard: A Basic .Net application that will connect to a SQL Server, allow you to select a database, then select from the user created tables, read the tabl...Agilisa Data.Controls: Agilisa DataControls provides ready to use Databound controls, encapsulating the data connection logic, caching, for ASP.NET Controls. Just drop th...algoritmia: A Python 3.1+ library of Data Structures and Algorithms. This library is being used to teach a course on Algorithms in my university. It contains ...Bag of Tricks: The original WPF Bag of tricks, now maintained by your friends at Pixel Lab.DIMIS: It is a simple asp.net system, just for practice!DotNetNuke® Postgres Data Provider: DNN PG Provider is a DotNetNuke® 4.9.2 Data Provider for PostgreSQL, an enterprise class open source database system. With DNN PG DataProvider y...Home Finance: This project develop to manage your home finance.House Repair Management System: House Repair Management SystemLaunchpadNET: LaunchpadNET is a C# library for interfacing your .NET program with the Novation Launchpad controller.Mapsui - UI for maps: Mapsui is a UI library for mapping applications. It is based on BruTile and SharpMap. It is designed to be fast and responsive.micronovo: micronovomicronovomicronovomicronovoNPlurk: The project goal is to provide a .NET implemented Plurk API wrapper. PowerExt: PowerExt is a Windows Explorer add-in written in C++. Primarily targeted at programmers, it adds an additional .NET tab to the File Properties dial...Python Multiple Dispatch: Multiple dispatch (AKA multimethods) for Python 3 via a metaclass and type annotations.SpugDisposeCheck - Visual Studio Addin for validating Sharepoint dispose objects: AddIn that wraps the SPDisposeCheck Tool from Microsoft and fully integrate it with Visual Studio.System.Tuples: System.Tuples is a small tuple library. It uses T4 to generate tuples, and is made to be compatible with .net 2.0, .net 3.0 and .net 3.5.WebStatistics Server for Windows Server: WebStatistics Server for Windows Server is a tool to create visitor and traffic statistics of a Windows Server running IIS Webserver. It includes a...whileActivity Test: This is a temporary project to test the whileActivity and the updateResourceActivity (Forefront Identity Manager 2010 rtm)XBMC NFO Exporter: XBMC Nfo Exporter is a simple utility that allows you to create reports based on your media XMBC NFO files.XML Flattener: A simple tool to flatten "pretty"-printed XML files into a single line for use in web service test situations, etc. xvanneste: Sources et exemples utilisés sur le site http://www.xvanneste.com et http://media.xvanneste.comzhengym: 这是我个人的测试项目New Releases.Net Data Form Wizard: Alpha: I am only providing the logical code at this point. I will release a completed project once it has basic functionality, at the moment it only gener....Net Data Form Wizard: Alpha Code: This is only the basic VB code to create a form from the database information.Alter gear SQL index Management: Setup 1.1.1: Changes : Added ability to save / delete connection stringsExcelDna: ExcelDna Version 0.24: This versions adds packing support for .config files, and fixes a bug where temp files were not cleaned up.Hash Calculator: HashCalculator 1.1: Added drag-and-drop support Fixed some bugsHeadCounter: HeadCounter 1.2.4 'Vaelastrasz': Added a basic bbcode option for forum posting to sites that do not support full bbcode implementations (e.g. Guild Portal)Home Access Plus+: v3.2.5.0: v3.2.5.0 Release Change Log: Added the booking system File Changes: ~/app_data/* ~/bin/CHS.dll ~/bin/CHS.pdb ~/bin/CHS Extranet.dll ~/bin/...Home Access Plus+: v3.2.5.1: v3.2.5.1 Release Change Log: Fixed access to the booking system for non domain admin File Changes: ~/bin/CHS Extranet.dll ~/bin/CHS Extranet.pdb...Howard van Rooijen's Code Samples: Getting Started with MongoDB and NoRM: Code to accompany the blog post A .NET Developer Guide to: MongoDB and NoRM This download contains the a solution with the following structure: G...iExporter - iTunes playlist exporting: iExporter gui v2.5.1.0 - console v1.2.1.0: Paypal donate! Fixed small bug for iExporter Gui When pressing the Select button more then once, the Deselect button would not disable the Export...IST435: Lab 2 Demo Solution: Lab 2 Demo Solution - OverviewThis is a demo solution for Lab 2 which meets the basic requirements of the lab. Note that this solution has the foll...JSINQ - LINQ to Objects for JavaScript: JSINQ 1.0.0.1: Minor bugfixes with the Enumerable and Dictionary implementations.Mavention: Mavention Instant Page Create: Mavention Instant Page Create allows you to create new Publishing Pages with a single mouse click. Screenshots and more information available @ htt...Microsoft Dynamics CRM 4.0 Marketing List Member Importer: Nocelab ExcelAddin - Release 2.2: Version: 2.2 Release Note: - Added tab in the task panel - Added test button to check MSCRM connection How to install: - Uninstall previous ve...Multiplayer Quiz: Release 1_6_903_0b: Latest beta release - please leave any bugs etc in comments.MVVM Light Toolkit: MVVM Light Toolkit V3 SP1: This release can be installed on top of V3, and adds the following features: Project and Item templates for Visual Studio 10 Express (phone editio...NPlurk: First release: This is first release of NPlurk and it's almost completely workable. Enjoy!Performance Analysis of Logs (PAL) Tool: PAL v2.0 Alpha 5: Export to Perfmon Log Template or Data Collector Set Added: Added the feature to export perfmon log templates (*.htm) for WinXP/2003 computers or D...Python Multiple Dispatch: v0.1: Initial release. I believe it is working fine.ReRemind: V7: - Added new notification: "Unread MMS" <- Default is enabled, so be sure to go into Config if you don't want this. - Config now supports sound and ...SharePhone: SharePhone v.1.0.2: Added support for retrieving user profiles and saving back to SharePoint Use clientContext.GetUserProfile(..) or clientContext.UpdateUserProfile(..)Shinkansen: compress, crunch, combine, and cache JavaScript and CSS: Shinkansen 1.0.0.033010: Added support for ASP.NET MVC. Download contains binaries only.SpugDisposeCheck - Visual Studio Addin for validating Sharepoint dispose objects: SpugDisposeCheck Beta Release [Stable]: SpugDisposeCheck - Visual Studio Addin for validating Sharepoint dispose objects You can download the Microsoft SPDisposeCheck Tool from here:http...Starter Kit Mytrip.Mvc.Entity: Mytrip.Mvc.Entity 1.0 RC2: EF Membership XML Membership UserManager FileManager Localization Captcha ClientValidation Theme CrossBrowser VS 2010 RC MVC 2 R...System.Tuples: System.Tuples for .net 2.0: The System.Tuples release for .net 3.0System.Tuples: System.Tuples for .net 3.0: The System.Tuples release for .net 3.0 Extension methods have been removed to remain compatible with 3.0System.Tuples: System.Tuples for .net 3.5: The System.Tuples release for .net 3.5 Contains full functionality of the library.WatchersNET.TagCloud: WatchersNET.TagCloud 01.03.00: Whats New Html (non Flash) TagCloud can be skinned 11 Skins added for Html Cloud Skin Orange Skin Purple Import/Export of Custom Tags Sett...whileActivity Test: Activity1.zip: ActivityLibrary1.zip contains the source code to do a testWindows Phone 7 Panorama control: panorama control v0.5: Control source code for v0.5. This is the first drop. Doens't include sample project.Windows Phone 7 Panorama control: panorama control v0.5 + samples: Control source code and sample project. This drop includes 2 samples projects : - PhoneApp - Windows Phone sample - SilverlightApp - Silverlight...XML Flattener: XML Flattener: A simple WinForms app--paste in your XML, hit Flatten, and copy the result.xvanneste: RestFul SharePoint: ListItem.xslt ListItems.xslt Lists.xslt ListItemSPChat.xslt RestFull.htm SPChat.htmZinc Launcher: Zinc Launcher 1.0.1.0: Zinc Launcher requires that Zinc be properly installed. It should work under Vista Media Center and 7 Media Center, although Vista is untested. Zin...Most Popular ProjectsRawrWBFS ManagerMicrosoft SQL Server Product Samples: DatabaseASP.NET Ajax LibrarySilverlight ToolkitAJAX Control ToolkitWindows Presentation Foundation (WPF)ASP.NETMicrosoft SQL Server Community & SamplesDotNetNuke® Community EditionMost Active ProjectsGraffiti CMSnopCommerce. Open Source online shop e-commerce solution.RawrFacebook Developer ToolkitjQuery Library for SharePoint Web ServicesBlogEngine.NETFarseer Physics EngineNcqrs Framework - A CQRS framework for .NETpatterns & practices – Enterprise LibraryN2 CMS

    Read the article

  • How would you refactor nested IF Statements?

    - by saunderl
    I was cruising around the programming blogosphere when I happened upon this post about GOTO's: http://giuliozambon.blogspot.com/2010/12/programmers-tabu.html Here the writer talks about how "one must come to the conclusion that there are situations where GOTOs make for more readable and more maintainable code" and then goes on to show an example similar to this: if (Check#1) { CodeBlock#1 if (Check#2) { CodeBlock#2 if (Check#3) { CodeBlock#3 if (Check#4) { CodeBlock#4 if (Check#5) { CodeBlock#5 if (Check#6) { CodeBlock#6 if (Check#7) { CodeBlock#7 } else { rest - of - the - program } } } } } } } The writer then proposes that using GOTO's would make this code much easier to read and maintain. I personally can think of at least 3 different ways to flatten it out and make this code more readable without resorting to flow-breaking GOTO's. Here are my two favorites. 1 - Nested Small Functions. Take each if and its code block and turn it into a function. If the boolean check fails, just return. If it passes, then call the next function in the chain. (Boy, that sounds a lot like recursion, could you do it in a single loop with function pointers?) 2 - Sentinal Variable. To me this is the easyest. Just use a blnContinueProcessing variable and check to see if it is still true in your if check. Then if the check fails, set the variable to false. How many different ways can this type of coding problem be refactored to reduce nesting and increase maintainability?

    Read the article

  • Keeping Aspect Screen Ration While Stays in Center

    - by David Dimalanta
    I sqw and I tried this suggestion on PISTACHIO BRAINSTORMIN* on how to make a good and adaptive screen ration. For every different screen size, let's say I put the perfect circle as a Texture in LibGDX and played it on screen. Here's the blueberry image example and it's perfectly rounded: When I played it on the Google Nexus 7, the circle turn into a slightly oblonng shape, resembling as it was being flatten a bit. Please observe this snapshot below and you can see the blueberry is almost but slightly not perfectly rounded: Now, when I tried the suggested code for aspect ratio, the perfect circle retained but another problem is occured. The problem is that I expecting for a view on center but instead it's been moved to the right offset leaving with a half black screen. This would be look like this: Here is my code using the suggested screen aspect ratio code: Class' Field // Ingredients Needed for Screen Aspect Ratio private static final int VIRTUAL_WIDTH = 720; private static final int VIRTUAL_HEIGHT = 1280; private static final float ASPECT_RATIO = ((float) VIRTUAL_WIDTH)/((float) VIRTUAL_HEIGHT); private Camera Mother_Camera; private Rectangle Viewport; render() // Camera updating... Mother_Camera.update(); Mother_Camera.apply(Gdx.gl10); // Reseting viewport... Gdx.gl.glViewport((int) Viewport.x, (int) Viewport.y, (int) Viewport.width, (int) Viewport.height); // Clear previous frame. Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); show() Mother_Camera = new OrthographicCamera(VIRTUAL_WIDTH, VIRTUAL_HEIGHT); Was this code useful for screen aspect ratio-proportion fixing or it is statically dependent on actual device's width and height? *see http://blog.acamara.es/2012/02/05/keep-screen-aspect-ratio-with-different-resolutions-using-libgdx/#comment-317

    Read the article

  • Keeping Aspect Screen Ratio While Stays in Center

    - by David Dimalanta
    I sqw and I tried this suggestion on PISTACHIO BRAINSTORMIN* on how to make a good and adaptive screen ration. For every different screen size, let's say I put the perfect circle as a Texture in LibGDX and played it on screen. Here's the blueberry image example and it's perfectly rounded: When I played it on the Google Nexus 7, the circle turn into a slightly oblonng shape, resembling as it was being flatten a bit. Please observe this snapshot below and you can see the blueberry is almost but slightly not perfectly rounded: Now, when I tried the suggested code for aspect ratio, the perfect circle retained but another problem is occured. The problem is that I expecting for a view on center but instead it's been moved to the right offset leaving with a half black screen. This would be look like this: Here is my code using the suggested screen aspect ratio code: Class' Field // Ingredients Needed for Screen Aspect Ratio private static final int VIRTUAL_WIDTH = 720; private static final int VIRTUAL_HEIGHT = 1280; private static final float ASPECT_RATIO = ((float) VIRTUAL_WIDTH)/((float) VIRTUAL_HEIGHT); private Camera Mother_Camera; private Rectangle Viewport; render() // Camera updating... Mother_Camera.update(); Mother_Camera.apply(Gdx.gl10); // Reseting viewport... Gdx.gl.glViewport((int) Viewport.x, (int) Viewport.y, (int) Viewport.width, (int) Viewport.height); // Clear previous frame. Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); show() Mother_Camera = new OrthographicCamera(VIRTUAL_WIDTH, VIRTUAL_HEIGHT); Was this code useful for screen aspect ratio-proportion fixing or it is statically dependent on actual device's width and height? *see http://blog.acamara.es/2012/02/05/keep-screen-aspect-ratio-with-different-resolutions-using-libgdx/#comment-317

    Read the article

  • Flattening PDF transparency

    - by Jan
    I have a PDF, made with Inkscape, that uses transparent colors. This image shall be used in a LaTeX document. While preserving the transparency is nice for editing, it can be a problem for printing. Printing usually involves PDF to PS conversion. Since Postscript does not support transparency, this requires either flatting, i.e. creating a vector graphic that works without transparency or rastering, i.e. rendering a bitmap image. When a PDF document containing such a figure is printed (or converted to PS) using Evince (or Cairo or Ghostscript), the whole page gets rendered as a bitmap, rendering fonts ugly (different from other pages). (Adobe Acrobat handles such PDFs well.) Unfortunately, converting the PDF figures to EPS (before including them with LaTeX) doesn't help much, because both pdftops and pdf2ps (again, Cairo or Ghostscript) rasterize the image, i.e. render a bitmap (saved as EPS). (This is slightly better, because it doesn't affect the whole page, but I'd still prefer a vector graphics.) How can I flatten transparency with Inkscape or other software on Linux?

    Read the article

  • How to persuade C fanatics to work on my C++ open source project?

    - by paperjam
    I am launching an open-source project into a space where a lot of the development is still done Linux-kernel-style, i.e. C-language with a low-level mindset. There are multiple benefits to C++ in our space but I fear those used to working in C will be scared off. How can I make the case for the benefits of C++? Specifically, the following C++ attributes are very valuable: concept of objects and reference-counting pointers - really don't want to have to malloc(sizeof(X)) or memcpy() structs templates for specialising whole bodies of code with specific performance optimizations and for avoiding duplication of code. template metaprogramming related to the above syntactic sweetness available (e.g. operator overloading, to be used in very small doses) STL Boost libraries Many of the knee-jerk negative reactions to C++ are illfounded. Performance does not suffer: modern compilers can flatten dozens of call stack levels and avoid bloat through wide use of template specializations. Granted, when using metaprogramming and building multiple specializations of a large call tree, compile time is slower but there are ways to mitigate this. How can I sell C++?

    Read the article

  • Accessing a vector<vector<int>> as a flat array

    - by user1762276
    For this array: vector<vector<int> > v; v.push_back(vector<int>(0)); v.back().push_back(1); v.back().push_back(2); v.back().push_back(3); v.back().push_back(4); I can output {1, 2, 3, 4} easily enough: cout << v[0][0] << endl; cout << v[0][1] << endl; cout << v[0][2] << endl; cout << v[0][3] << endl; To access it as a flat array I can do this: int* z = (int*)&v[0].front(); cout << z[0] << endl; cout << z[1] << endl; cout << z[2] << endl; cout << z[3] << endl; Now, how do I access the multidimensional vector as a flat multidimensional array? I cannot use the same format as accessing a single-dimensional vector: // This does not work (outputs garbage) int** n = (int**)&v.front(); cout << n[0][0] << endl; cout << n[0][1] << endl; cout << n[0][2] << endl; cout << n[0][3] << endl; The workaround I've found is to do this: int** n = new int* [v.size()]; for (size_t i = 0; i < v.size(); i++) { n[i] = &v.at(i).front(); } cout << n[0][0] << endl; cout << n[0][1] << endl; cout << n[0][2] << endl; cout << n[0][3] << endl; Is there a way to access the entire multidimensional vector like a flat c-style array without having to dynamically allocate each dimension above the data before accessing it? Speed is not critical in the implementation and clarity for maintenance is paramount. A multidimensional vector is just fine for storing the data. However, I want to also expose the data as a flat c-style array in the SDK so that it can be easily accessible by other languages. This means that exposing the vectors as an STL object is a no go. The solution I came up with works fine for my needs as I only evaluate the array once at the very end of processing to "flatten" it. However, is there a better way to go about this? Or am I already doing it the best way I possibly can without re-implementing my own data structure (overkill since my flatten code is only a few lines). Thank you for your advice, friends!

    Read the article

  • Does throwing an exception in an EvalFunc pig UDF skip just that line, or stop completely?

    - by Daniel Huckstep
    I have a User Defined Function (UDF) written in Java to parse lines in a log file and return information back to pig, so it can do all the processing. It looks something like this: public abstract class Foo extends EvalFunc<Tuple> { public Foo() { super(); } public Tuple exec(Tuple input) throws IOException { try { // do stuff with input } catch (Exception e) { throw WrappedIOException.wrap("Error with line", e); } } } My question is: if it throws the IOException, will it stop completely, or will it return results for the rest of the lines that don't throw an exception? Example: I run this in pig REGISTER myjar.jar DEFINE Extractor com.namespace.Extractor(); logs = LOAD '$IN' USING TextLoader AS (line: chararray); events = FOREACH logs GENERATE FLATTEN(Extractor(line)); With this input: 1.5 7 "Valid Line" 1.3 gghyhtt Inv"alid line"" I throw an exceptioN!! 1.8 10 "Valid Line 2" Will it process the two lines and will 'logs' have 2 tuples, or will it just die in a fire?

    Read the article

  • SNMP: ASN.1 MIB Definitions. Referencing a table within a table

    - by Doug
    Its's been a while since I've written ASN.1 so.. Our data model is comprised of several table definitions within a table. This is not workable in SNMP, so we need to flatten the definitions. The easiest way to do this would be to have the embedded table indexed by the same OID as the parent table. Thus someTableEntry ::= SEQUENCE { someTableIndex Integer32, someTableDomain Integer32, someTableFooTable SEQUENCE OF SomeTableFooTable } becomes someTableEntry ::= SEQUENCE { someTableIndex Integer32, someTableDomain Integer32, } someTableFooTable ::= SEQUENCE { someTableIndex Integer32, .... } The good thing is that in our application there will NEVER be any kind of SET, GET or GET NEXT so no need for SNMP walk (there are some very good reasons for this that supersede the need for network management elegance. All attributes will be reported via traps only. I think this is a valid SNMP MIB definitions but wanted to get some feedback. Thanks in advance.

    Read the article

  • Threading extra state through a parser in Scala

    - by Travis Brown
    I'll give you the tl;dr up front I'm trying to use the state monad transformer in Scalaz 7 to thread extra state through a parser, and I'm having trouble doing anything useful without writing a lot of t m a -> t m b versions of m a -> m b methods. An example parsing problem Suppose I have a string containing nested parentheses with digits inside them: val input = "((617)((0)(32)))" I also have a stream of fresh variable names (characters, in this case): val names = Stream('a' to 'z': _*) I want to pull a name off the top of the stream and assign it to each parenthetical expression as I parse it, and then map that name to a string representing the contents of the parentheses, with the nested parenthetical expressions (if any) replaced by their names. To make this more concrete, here's what I'd want the output to look like for the example input above: val target = Map( 'a' -> "617", 'b' -> "0", 'c' -> "32", 'd' -> "bc", 'e' -> "ad" ) There may be either a string of digits or arbitrarily many sub-expressions at a given level, but these two kinds of content won't be mixed in a single parenthetical expression. To keep things simple, we'll assume that the stream of names will never contain either duplicates or digits, and that it will always contain enough names for our input. Using parser combinators with a bit of mutable state The example above is a slightly simplified version of the parsing problem in this Stack Overflow question. I answered that question with a solution that looked roughly like this: import scala.util.parsing.combinator._ class ParenParser(names: Iterator[Char]) extends RegexParsers { def paren: Parser[List[(Char, String)]] = "(" ~> contents <~ ")" ^^ { case (s, m) => (names.next -> s) :: m } def contents: Parser[(String, List[(Char, String)])] = "\\d+".r ^^ (_ -> Nil) | rep1(paren) ^^ ( ps => ps.map(_.head._1).mkString -> ps.flatten ) def parse(s: String) = parseAll(paren, s).map(_.toMap) } It's not too bad, but I'd prefer to avoid the mutable state. What I want Haskell's Parsec library makes adding user state to a parser trivially easy: import Control.Applicative ((*>), (<$>), (<*)) import Data.Map (fromList) import Text.Parsec paren = do (s, m) <- char '(' *> contents <* char ')' h : t <- getState putState t return $ (h, s) : m where contents = flip (,) [] <$> many1 digit <|> (\ps -> (map (fst . head) ps, concat ps)) <$> many1 paren main = print $ runParser (fromList <$> paren) ['a'..'z'] "example" "((617)((0)(32)))" This is a fairly straightforward translation of my Scala parser above, but without mutable state. What I've tried I'm trying to get as close to the Parsec solution as I can using Scalaz's state monad transformer, so instead of Parser[A] I'm working with StateT[Parser, Stream[Char], A]. I have a "solution" that allows me to write the following: import scala.util.parsing.combinator._ import scalaz._, Scalaz._ object ParenParser extends ExtraStateParsers[Stream[Char]] with RegexParsers { protected implicit def monadInstance = parserMonad(this) def paren: ESP[List[(Char, String)]] = (lift("(" ) ~> contents <~ lift(")")).flatMap { case (s, m) => get.flatMap( names => put(names.tail).map(_ => (names.head -> s) :: m) ) } def contents: ESP[(String, List[(Char, String)])] = lift("\\d+".r ^^ (_ -> Nil)) | rep1(paren).map( ps => ps.map(_.head._1).mkString -> ps.flatten ) def parse(s: String, names: Stream[Char]) = parseAll(paren.eval(names), s).map(_.toMap) } This works, and it's not that much less concise than either the mutable state version or the Parsec version. But my ExtraStateParsers is ugly as sin—I don't want to try your patience more than I already have, so I won't include it here (although here's a link, if you really want it). I've had to write new versions of every Parser and Parsers method I use above for my ExtraStateParsers and ESP types (rep1, ~>, <~, and |, in case you're counting). If I had needed to use other combinators, I'd have had to write new state transformer-level versions of them as well. Is there a cleaner way to do this? I'd love to see an example of a Scalaz 7's state monad transformer being used to thread state through a parser, but Scala 6 or Haskell examples would also be useful.

    Read the article

  • Passing a non-iterable to list.extend ()

    - by JS
    Hello, I am creating a public method to allow callers to write values to a device, call it write_vals() for example. Since these values will by typed live, I would like to simplify the user's life by allowing them type in either a list or a single value, depending on how many values they need to write. For example: write_to_device([1,2,3]) or write_to_device(1) My function would like to work with a flat list, so I tried to be clever and code something like this: input_list = [] input_list.extend( input_val ) This works swimmingly when the user inputs a list, but fails miserably when the user inputs a single integer: TypeError: 'int' object is not iterable Using list.append() would create a nested list when a list was passed in, which would be an additional hassle to flatten. Checking the type of the object passed in seems clumsy and non-pythonic and wishing that list.extend() would accept non-iterables has gotten me nowhere. So has trying a variety of other coding methods. Suggestions (coding-related only, please) would be greatly appreciated.

    Read the article

  • Optimizing for speed - 4 dimensional array lookup in C

    - by Tiago
    I have a fitness function that is scoring the values on an int array based on data that lies on a 4D array. The profiler says this function is using 80% of CPU time (it needs to be called several million times). I can't seem to optimize it further (if it's even possible). Here is the function: unsigned int lookup_array[26][26][26][26]; /* lookup_array is a global variable */ unsigned int get_i_score(unsigned int *input) { register unsigned int i, score = 0; for(i = len - 3; i--; ) score += lookup_array[input[i]][input[i + 1]][input[i + 2]][input[i + 3]]; return(score) } I've tried to flatten the array to a single dimension but there was no improvement in performance. This is running on an IA32 CPU. Any CPU specific optimizations are also helpful. Thanks

    Read the article

  • What does class_eval <<-"end_eval", __FILE__, __LINE__ mean in Ruby?

    - by viatropos
    I'm learning how to use class_eval in modules (I'm somewhat familiar with class_eval) and came across this helpful class in resource_controller. In there they have things like this: class_eval <<-"end_eval", __FILE__, __LINE__ def #{block_accessor}(*args, &block) unless args.empty? && block.nil? args.push block if block_given? @#{block_accessor} = [args].flatten end @#{block_accessor} end end_eval What does __FILE__ and __LINE__ do in that context? I know __FILE__ references the current file, but what does that whole thing do exactly? Don't really know how to search for that :).

    Read the article

  • GD! Converting a png image to jpeg and making the alpha by default white and not black.

    - by Shawn
    I tried something like this but it just makes the background of the image white, not necessarily the alpha of the image. I wanted to just upload everything as jpg's so if i could somehow "flatten" a png image with some transparently to default it to just be white so i can use it as a jpg instead. Appreciate any help. Thanks. $old = imagecreatefrompng($upload); $background = imagecolorallocate($old,255,255,255); imagefill($old, 0, 0, $background); imagealphablending($old, false); imagesavealpha($old, true);

    Read the article

  • Finding indexes of each element in a multidimensional array in ruby

    - by Shreyas Satish
    Eg :a=[["hello", "world"], ["good", "lord"], ["hello", "lord"]] I need to find and record the indexes of each word with respect to the super-array. i.e hello => 0,2 world => 0 lord => 1,2. here's my shot ,but its very amateurish and lengthy. all_tokens=tokens.flatten all_tokens.each do|keyword| tokens.each do|token_array| if token_array.include?keyword x << i end i=i+1 end y[k] = x.clone y=y.clear end

    Read the article

  • Sorting/Paginating/Filtering Complex Multi-AR Object Tables in Rails

    - by Matt Rogish
    I have a complex table pulled from a multi-ActiveRecord object array. This listing is a combined display of all of a particular user's "favorite" items (songs, messages, blog postings, whatever). Each of these items is a full-fledged AR object. My goal is to present the user with a simplified search, sort, and pagination interface. The user need not know that the Song has a singer, and that the Message has an author -- to the end user both entries in the table will be displayed as "User". Thus, the search box will simply be a dropdown list asking them which to search on (User name, created at, etc.). Internally, I would need to convert that to the appropriate object search, combine the results, and display. I can, separately, do pagination (mislav will_paginate), sorting, and filtering, but together I'm having some problems combining them. For example, if I paginate the combined list of items, the pagination plugin handles it just fine. It is not efficient since the pagination is happening in the app vs. the DB, but let's assume the intended use-case would indicate the vast majority of the users will have less than 30 favorited items and all other behavior, server capabilities, etc. indicates this will not be a bottleneck. However, if I wish to sort the list I cannot sort it via the pagination plugin because it relies on the assumption that the result set is derived from a single SQL query, and also that the field name is consistent throughout. Thus, I must sort the merged array via ruby, e.g. @items.sort_by{ |i| i.whatever } But, since the items do not share common names, I must first interrogate the object and then call the correct sort by. For example, if the user wishes to sort by user name, if the sorted object is a message, I sort by author but if the object is a song, I sort by singer. This is all very gross and feels quite un-ruby-like. This same problem comes into play with the filter. If the user filters on the "parent item" (the message's thread, the song's album), I must translate that to the appropriate collection object method. Also gross. This is not the exact set-up but is close enough. Note that this is a legacy app so changing it is quite difficult, although not impossible. Also, yes there is some DRY that can be done, but don't focus on the style or elegance of the following code. Style/elegance of the SOLUTION is important, however! :D models: class User < ActiveRecord::Base ... has_and_belongs_to_many :favorite_messages, :class_name => "Message" has_and_belongs_to_many :favorite_songs, :class_name => "Song" has_many :authored_messages, :class_name => "Message" has_many :sung_songs, :class_name => "Song" end class Message < ActiveRecord::Base has_and_belongs_to_many :favorite_messages belongs_to :author, :class_name => "User" belongs_to :thread end class Song < ActiveRecord::Base has_and_belongs_to_many :favorite_songs belongs_to :singer, :class_name => "User" belongs_to :album end controller: def show u = User.find 123 @items = Array.new @items << u.favorite_messages @items << u.favorite_songs # etc. etc. @items.flatten! @items = @items.sort_by{ |i| i.created_at } @items = @items.paginate :page => params[:page], :per_page => 20 end def search # Assume user is searching for username like 'Bob' u = User.find 123 @items = Array.new @items << u.favorite_messages.find( :all, :conditions => "LOWER( author ) LIKE LOWER('%bob%')" ) @items << u.favorite_songs.find( :all, :conditions => "LOWER( singer ) LIKE ... " ) # etc. etc. @items.flatten! @items = @items.sort_by{ |i| determine appropriate sorting based on user selection } @items = @items.paginate :page => params[:page], :per_page => 20 end view: #index.html.erb ... <table> <tr> <th>Title (sort ASC/DESC links)</th> <th>Created By (sort ASC/DESC links))</th> <th>Collection Title (sort ASC/DESC links)</th> <th>Created At (sort ASC/DESC links)</th> </tr> <% @items.each |item| do %> <%= render { :partial => "message", :locals => item } if item.is_a? Message %> <%= render { :partial => "song", :locals => item } if item.is_a? Song %> <%end%> ... </table> #message.html.erb # shorthand, not real ruby print out message title, author name, thread title, message created at #song.html.erb # shorthand print out song title, singer name, album title, song created at

    Read the article

  • Using PIG with Hadoop, how do I regex match parts of text with an unknown number of groups?

    - by lmonson
    I'm using Amazon's elastic map reduce. I have log files that look something like this random text foo="1" more random text foo="2" more text noise foo="1" blah blah blah foo="1" blah blah foo="3" blah blah foo="4" ... How can I write a pig expression to pick out all the numbers in the 'foo' expressions? I prefer tuples that look something like this: (1,2) (1) (1,3,4) I've tried the following: TUPLES = foreach LINES generate FLATTEN(EXTRACT(line,'foo="([0-9]+)"')); But this yields only the first match in each line: (1) (1) (1)

    Read the article

  • How to perform ant path mapping in war task?

    - by eljenso
    I have several JAR file pattern sets, like <patternset id="common.jars"> <include name="external/castor-1.1.jar" /> <include name="external/commons-logging-1.2.6.jar" /> <include name="external/itext-2.0.4.jar" /> ... </patternset> I also have a war task containing a lib element: ... Like this however, I end up with a WEB-INF/lib containing the subdirectories from my patterns: WEB-INF/lib/external/castor-1.1.jar WEB-INF/lib/external/... Is there any way to flatten this, so the JAR files appear top-level under WEB-INF/lib, regardless of the directories specified in the patterns? I looked at mapper but it seems you cannot use them inside lib.

    Read the article

  • PHP: Modifying array recursively?

    - by Industrial
    Hi everybody, I have tried to make a function that iterates through the following array to flatten it and add parent id to children, where applicable. I just can't make it work, so I hope that anyone here has an idea of what to do: Here's the starting point: Array ( [0] => Array ( [id] => 1 ) [1] => Array ( [id] => 2 [children] => Array ( [0] => Array ( [id] => 3 ) ) ) ) The expected result : Array ( [0] => array ( [id] => 1 ) [1] => array ( [id] => 2 ) [2] => array ( [id] => 3, [parent] => 2 ) ) Hope that anyone can point me in the right direction. Thanks a lot!

    Read the article

  • Convert a sequence of sequences to a dictionary and vice-versa

    - by louis
    One way to manually persist a dictionary to a database is to flatten it into a sequence of sequences and pass the sequence as an argument to cursor.executemany(). The opposite is also useful, i.e. reading rows from a database and turning them into dictionaries for later use. What's the best way to go from myseq to mydict and from mydict to myseq? >>> myseq = ((0,1,2,3), (4,5,6,7), (8,9,10,11)) >>> mydict = {0: (1, 2, 3), 8: (9, 10, 11), 4: (5, 6, 7)}

    Read the article

  • Ruby efficient way of building an array from an array of arrays

    - by randombits
    I have an array of ActiveRecord objects, each one which has its own respective errors array. I want to flatten it all out and get only the unique values into one array. So the top level array might look like: foo0 = Foo.new foo1 = Foo.new foo2 = Foo.new foo3 = Foo.new arr = [foo0, foo1, foo2, foo3] Each one of those objects could potentially have an array of errors, and I'd like to get just the unique message out of them and put them in another array, say called error_arr. How would you do it the "Ruby" way?

    Read the article

  • Google Street View API v3 : how can I avoid having "fish-eye" effect on Firefox?

    - by Benj
    I'm using google maps API V3 and I'm having trouble displaying correctly the street view within Firefox. I always get the "fish-eye" view (does not happen with Google chrome). So I assumed that the problem came from Firefox. I took a look to the street view options but found nothing. I would like to know if there is an option to have a flatten street view or if it is because Firefox does not support this kind of feature. If someone could explain it to me, I would be grateful. Below, what it looks in Firefox : And what it looks in Chrome :

    Read the article

< Previous Page | 1 2 3 4 5 6 7  | Next Page >