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
Been made to do this task where I need to make an animal guessing game using if-else. I cannot figure out how to make this code so it will add more than four animals. The game is basically Think of an animal. Is it a bird? yes Can it fly? no Is it an emu? no Oh. Well, thank you for playing. This is all the animals I need to include: TREE.JPG and this is the code I have to modify to include the new animals in: public class animalquiz { public static void main(String[] args) { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); boolean answerIsCorrect; System.out.println("Think of an animal.\n"); if(ask("Is it a bird? ", keyboard)) { if(ask("Can it fly? ", keyboard)) { answerIsCorrect = ask("Is it a kookaburra? ", keyboard); } else { answerIsCorrect = ask("Is it an emu? ", keyboard); } } else { if(ask("Does it lay eggs? ", keyboard)) { answerIsCorrect = ask("Is it a platypus? ", keyboard); } else { answerIsCorrect = ask("Is it a kangaroo? ", keyboard); } } if(answerIsCorrect) { System.out.println("Yes! I am invincible!"); } else { System.out.println("Oh. Well, thank you for playing."); } } /** * A utility method to ask a yes/no question * * @param question the question to ask * @param a scanner for user input * * @return whether the user answered "yes" (actually, whether the user answered anything starting with Y or y) */ private static boolean ask(String question, Scanner keyboard) { System.out.print(question); String answer = keyboard.nextLine().trim(); return answer.charAt(0) == 'Y' || answer.charAt(0) == 'y'; } } I hope someone can help and explain how I can do this
http://www.javaprogrammingforums.com/loops-control-statements/26134-guessing-game-help.html
CC-MAIN-2016-36
refinedweb
266
62.54
The Java Specialists' Newsletter Issue 0452002-04-11 Category: GUI Java version: GitHub Subscribe Free RSS Feed Welcome to the 45th edition of The Java(tm) Specialists' Newsletter, read in over 78 countries, with newest additions Thailand and Iceland. Both end with "land" but they couldn't be two more opposite countries. Why don't those drivers who insist on crawling along the German Autobahn at 140km/h stick to the slow lane? I drove almost 500km on Friday, and had the opportunity to meet Carl Smotricz (my archive keeper) and some other subscribers in Frankfurt. We had some very inspiring discussions regarding Java performance, enjoyed some laughs at Java's expense and listened to my tales of life in South Africa. Unsubscription Fees: Some of my readers wrote to tell me what a fantastic idea unsubscription fees were to make some money. Others wrote angry notes asking how I had obtained their credit card details. All of them were wrong! Note the date of our last newsletter - 1st April! Yes, it was all part of the April Fool's craze that hits the world once a year. Apologies to those of you who found that joke in poor taste (my wife said I shouldn't put it in, but I didn't listen to her). The rest of the newsletter was quite genuine. A friend, who was caught "hook, line & sinker", suggested that I should clear things up and tell you exactly what my purpose is in publishing "The Java(tm) Specialists' Newsletter": #1. Publishing this newsletter is my hobby: No idealism here at all. A friend encouraged me a few years ago to write down all the things I had been telling him about Java, so one day I simply started, and I have carried on doing it. It's a great way to relax, put the feet up and think a while. #2. There are no subscription / unsubscription fees: The day that I'm so broke that I need to charge you for reading the things I write, will be the day that I immediately start looking for work as a permanent employee again. There are neither subscription nor unsubscription fees, nor will there ever be. #3. How do I earn my living? Certainly not by writing newsletters! I spend about 75% of my time writing Java code on contract for customers situated in various parts of the world. 20% of my time is spent presenting Java and Design Patterns courses in interesting places such as Mauritius and South Africa and the last 5% is spent advising companies about Java technology. #4. Marketing for Maximum Solutions: Because people know my company and me through this newsletter, I have received many requests for courses, contract work and consulting, and this helps me to make a living. My hobby of writing the newsletter has turned out to have some nice side effects. And now, without wasting any more time, let's look at a real-life Java problem... Join us on Crete (or via webinar) for advanced Core Java Courses:Concurrency Specialists Course 1-4 April 2014 and Java Specialists Master Course 20-23 May 2014. The last slide of all my courses says that my students may send me questions any time they get stuck. A few weeks ago Robert Crida from Peralex in Bergvliet, South Africa, who came on my Java course last year, asked me how to display a JTextArea within a cell of a JTable. I sensed it would take more than 5 minutes to answer and being in a rush to finish some work inbetween Mauritius and Germany, I told him it would take me a few days to get back to him. When I got to Germany, I promptly forgot about his problem, until one of his colleagues reminded me last week. Robert was trying to embed a JTextArea object within a JTable. The behaviour that he was getting was that when he resized the width of the table, he could see that the text in the text area was being wrapped onto multiple lines but the cells did not become higher to show those lines. He wanted the table row height to be increased automatically to make the complete text area visible. He implemented a JTextArea cell renderer as below: import java.awt.Component; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.table.TableCellRenderer; public class TextAreaRenderer extends JTextArea implements TableCellRenderer { public TextAreaRenderer() { setLineWrap(true); setWrapStyleWord(true); } public Component getTableCellRendererComponent(JTable jTable, Object obj, boolean isSelected, boolean hasFocus, int row, int column) { setText((String)obj); return this; } } I wrote some test code to try this out. Before I continue, I need to point out that I use the SUN JDK 1.3.1 whereas Robert uses the SUN JDK 1.4.0. The classic "write once, debug everywhere" is a topic for another newsletter ... import javax.swing.*; import java.awt.BorderLayout; public class TextAreaRendererTest extends JFrame { // The table has 10 rows and 3 columns private final JTable table = new JTable(10, 3); public TextAreaRendererTest() { // We use our cell renderer for the third column table.getColumnModel().getColumn(2).setCellRenderer( new TextAreaRenderer()); // We hard-code the height of rows 0 and 5 to be 100 table.setRowHeight(0, 100); table.setRowHeight(5, 100); // We put the table into a scrollpane and into a frame getContentPane().add(new JScrollPane(table)); // We then set a few of the cells to our long example text String test = "The lazy dog jumped over the quick brown fox"; table.getModel().setValueAt(test, 0, 0); table.getModel().setValueAt(test, 0, 1); table.getModel().setValueAt(test, 0, 2); table.getModel().setValueAt(test, 4, 0); table.getModel().setValueAt(test, 4, 1); table.getModel().setValueAt(test, 4, 2); } public static void main(String[] args) { TextAreaRendererTest test = new TextAreaRendererTest(); test.setSize(600, 600); test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); test.show(); } } You'll notice when you run this, that when the row is high enough the text wraps very nicely inside the JTextArea, as in cell (0, 2). However, the JTable does not increase the row height in cell (4, 2) just because you decide to put a tall component into the cell. It requires a bit of prodding to do that. JTextArea My first approach was to override getPreferredSize() in the TextAreaRenderer class. However, that didn't work because JTable didn't take your preferred size into account in sizing the rows. I spent about an hour delving through the source code of JTable and JTextArea. After a lot of experimentation, I found out that JTextArea actually had the correct preferred size according to the width of the column in the JTable. I tried changing the getTableCellRendererComponent() method: getPreferredSize() JTable getTableCellRendererComponent() public Component getTableCellRendererComponent(JTable jTable, Object obj, boolean isSelected, boolean hasFocus, int row, int column) { setText((String)obj); table.setRowHeight(row, (int)getPreferredSize().getHeight()); return this; } On first glimpse, the program seemed to work correctly now, except that my poor CPU was running at 100%. The problem was that when you set the row height, the table was invalidated and that caused getTableCellRendererComponent() to be called in order to render all the cells again. This in turn then set the row height, which invalidated the table again. In order to put a stop to this cycle of invalidation, I needed to check whether the row is already the correct height before setting it: public Component getTableCellRendererComponent(JTable jTable, Object obj, boolean isSelected, boolean hasFocus, int row, int column) { setText((String)obj); int height_wanted = (int)getPreferredSize().getHeight(); if (height_wanted != table.getRowHeight(row)) table.setRowHeight(row, height_wanted); return this; } I tried it out (on SUN JDK 1.3.1) and it worked perfectly. There are some restrictions with my solution: Satisfied, I sent off the answer to Robert, with the words: "After spending an hour tearing out my hair, I found a solution for you, it's so simple you'll kick yourself, like I did myself ;-)" A few hours the answer came back: "Your solution does not solve my problem at all." "What?" I thought. Upon questioning his configuration, we realised that I was using JDK 1.3.1 and Robert was using JDK 1.4.0. I tried it on JDK 1.4.0 on my machine, and truly, it did not render properly! What had they changed so that it didn't work anymore? After battling for another hour trying to figure out what the difference was and why it didn't work out, I gave up and carried on with my other work of tuning someone's application server. If you know how to do it in JDK 1.4.0, please tell me! I have avoided JDK 1.4 for real-life projects, because I prefer others to find the bugs first. Most of my work is spent programming on real-life projects, so JDK 1.3.1 is the version I'm stuck with. My suspicion of new JDK versions goes back to when I started using JDK 1.0.x, JDK 1.1.x, JDK 1.2.x. I found that for every bug that was fixed in a new major version, 3 more appeared, and I grew tired of being a guinea pig. I must admit that I'm very happy with JDK 1.3.1, as I was with JDK 1.2.2 and JDK 1.1.8. I think that once JDK 1.4.1 is released I'll start using it and then you'll see more newsletters about that version of Java. In a future newsletter I will demonstrate how you can implement "friends" at runtime in the JDK 1.4. Heinz GUI Articles Related Java Course
http://www.javaspecialists.eu/archive/Issue045.html
CC-MAIN-2014-10
refinedweb
1,616
63.59
Measuring the coverage of unit tests is an important topic because we need to check the design of the tests and the scope in the code of them. Coverlet is an amazing tool to measure the coverage of unit tests in .NET projects. Coverlet is completely opensource and free. it supports .NET and .NET Core and you can add it as a NuGet Package. Coverlet Coverlet is a cross platform code coverage framework for .NET, with support for line, branch and method coverage. It works with .NET Framework on Windows and .NET Core on all supported platforms. Installation VSTest Integration: dotnet add package coverlet.collector N.B. You MUST add package only to test projects MSBuild Integration: dotnet add package coverlet.msbuild N.B. You MUST add package only to test projects Global Tool: dotnet tool install --global coverlet.console Quick Start VSTest Integration Coverlet is integrated into the Visual Studio Test Platform as a data collector. To get coverage simply run the following command: dotnet test --collect:"XPlat Code Coverage" After the above command is run, a coverage.cobertura.json file containing the results will be published to the TestResults directory as an attachment. A summary of the results will also be displayed in the terminal. See documentation for advanced usage. Requirements - You need… First, we have to add the NuGet within an existing unit test project (MSTest, xUnit, etc..). Coverlet has many ways to use it but I recommend to use MSBuild. dotnet add package coverlet.msbuild after that, we can use easily the integration between MSBuild and coverlet to run the test and measure the coverage with the following command: dotnet test /p:CollectCoverage=true you will get the following result: In the first column from left to right we can see the list of modules covered. In the column 'Line', we get the percentage of lines checked after running the tests and it's the same for 'Branch'(statements) and 'Method'(functions inside the classes). Coverlet generates a file coverage.json that contains the whole information displayed in the console. You can consume this file with your own application. Try it out! Mteheran / CoverletDemo Coverlet demo for unit test coverage CoverletDemo Coverlet demo for unit test coverage Posted on by: Miguel Teheran Developer by passion, C#, animals, nature and travel lover. Discussion Thanks for this article. Trying to connect coverlet test coverage to my CI pipeline now but didn't get how to collect total test coverage. I have 3 test projects, like Project1.Tests.csproj, Project2.Tests.csproj and Project3.Tests.csproj and coverlet shows tests coverage for each project separately. Wondering is there a possibility to collect total test coverage between all projects. Coverlet always shows the namespaces separated but you also will see a total table at the end. you have to put the test dlls (binaries) in the same folder and run "dotnet test /p:CollectCoverage=true" there. Thanks, it is what I need actually! Also, I have added a few more command line arguments. Here is the command that works for me perfectly (just in case if anyone needs it): Sweet! Thanks for sharing it
https://dev.to/mteheran/coverlet-unit-tests-coverage-for-net-4954
CC-MAIN-2020-40
refinedweb
524
58.48
As you know, there are many frameworks for mobile app development and a growing number of them are based on HTML5. These next-generation tools help developers create mobile apps for phones and tablets without the steep learning curve associated with native SDKs and other programming languages like Objective-C or Java. For countless developers throughout the world, HTML5 represents the future for cross-platform mobile app development. But the question is why? Why has HTML5 become so popular? The widespread adoption of HTML5 involves the emergence of the bring your own device (BYOD) movement. BYOD means that developers can no longer limit application usage to a single platform because consumers want their apps to run on the devices they use every day. HTML5 allows developers to target multiple devices with a single codebase and deliver experiences that closely emulate native solutions, without writing the same application multiple times, using multiple languages or SDKs. The evolution of modern web browsers means that HTML5 can deliver cross-platform, multi-device solutions that mirror behaviors and experiences of “native” apps to the point that it’s often difficult to distinguish between an app written using native development tools and those using HTML. Multiple platform support, time to market and lower maintenance costs are just a few of the advantages inherent in HTML/JavaScript. It’s advantages don’t stop there. HTML’s ability to mitigate long-term risks associated with emerging technologies such as WinRT, ChromeOS, FirefoxOS, and Tizen is unmatched. Simply said, the only code that will work on all these platforms is HTML/JavaScript. Is there a price? Yes, certainly native app consumes less memory and will have faster or more responsive user experience. But in all cases where a web app would work, you can make a step further and create a mobile web app or even packaged application for the store, for multiple platforms, from single codebase. PhoneJS lets you get started fast. PhoneJS is a cross-platform HTML5 mobile app development framework that was built to be versatile, flexible and efficient. PhoneJS is a single page application (SPA) framework, with view management and URL routing. Its layout engine allows you to abstract navigation away from views, so the same app can be rendered differently across different platforms or form factors. PhoneJS includes a rich collection of touch-optimized UI widgets with built-in styles for today’s most popular mobile platforms including iOS, Android, and Windows Phone 8. To better understand the principles of PhoneJS development and how you can create and publish applications in platform stores, let’s take a look at a simple demo app called TipCalculator. This application calculates tip amounts due based on a restaurant bill. The complete source code for this app is available here. The app can be found in the AppStore, Google Play, and Windows Store. TipCalculator is a Single-Page Application (SPA) built with HTML5. The start page is index.html, with standard meta tags and links to CSS and JavaScript resources. It includes a script reference to the JavaScript file index.js, where you’ll find the code that configures PhoneJS app framework logic: TipCalculator.app = new DevExpress.framework.html.HtmlApplication({ namespace: TipCalculator, defaultLayout: "empty" }); Within this section, we must specify the default layout for the app. In this example, we’ll use the simplest option, an empty layout. More advanced layouts are available with full support for interactive navigation styles described in the following images: empty PhoneJS uses well-established layout methodologies supported by many server-side frameworks, including Ruby on Rails and ASP.NET MVC. Detailed information about Views and Layouts can be found in our online documentation. To configure view routing in our SPA, we must add an additional line of code in index.js: TipCalculator.app.router.register(":view", { view: "home" }); This registers a simple route that retrieves the view name from the URL (from the hash segment of the URL). The home view is used by default. Each view is defined in its own HTML file and is linked into the main application page index.html like this: <link rel="dx-template" type="text/html" href="views/home.html" /> A viewmodel is a representation of data and operations used by the view. Each view has a function with the same base name as the view itself and returns the viewmodel for the view. For the home view, the views/home.js script defines the function home which creates the corresponding viewmodel. TipCalculator.home = function(params) { ... }; Three input parameters are used for the tip calculation algorithm: bill total, the number of people sharing the bill, and a tip percentage. These variables are defined as observables, which will be bound to corresponding UI widgets. Note: Observables functionality is supplied by Knockout.js, an important foundation for viewmodels used in PhoneJS. You can learn more about Knockout.js here. This is the code used in the home function to initialize the variables: var billTotal = ko.observable(), tipPercent = ko.observable(DEFAULT_TIP_PERCENT), splitNum = ko.observable(1); The result of the tip calculation is represented by four values: totalToPay, totalPerPerson, totalTip , tipPerPerson . Each value is a dependent observable (a computed value), which is automatically recalculated when any of the observables used in its definition change. Again, this is standard Knockout.js functionality. totalToPay totalPerPerson totalTip tipPerPerson var totalTip = ko.computed(...); var tipPerPerson = ko.computed(...); var totalPerPerson = ko.computed(...); var totalToPay = ko.computed(...); For an example of business logic implementation in a viewmodel, let’s take a closer look at the observable totalToPay. The total sum to pay is usually rounded. For this purpose, we have two functions roundUp and roundDown that change the value of roundMode (another observable). These changes cause recalculation of totalToPay, because roundMode is used in the code associated with the totalToPay observable. roundDown roundMode var totalToPay = ko.computed(function() { var value = totalTip() + billTotalAsNumber(); switch(roundMode()) { case ROUND_DOWN: if(Math.floor(value) >= billTotalAsNumber()) return Math.floor(value); return value; case ROUND_UP: return Math.ceil(value); default: return value; } }); When any input parameter in the view changes, rounding should be disabled to allow the user to view precise values. We subscribe to the changes of the UI-bound observables to achieve this: billTotal.subscribe(function() { roundMode(ROUND_NONE); }); tipPercent.subscribe(function() { roundMode(ROUND_NONE); }); splitNum.subscribe(function() { roundMode(ROUND_NONE); }); The complete viewmodel can be found in home.js. It represents a simple example of a typical viewmodel. Note: In a more complex app, it may be useful to implement a structure that modularizes your viewmodels separate from view implementation files. In other words, a file like home.js need not contain the code to implement the viewmodel and instead call a helper function elsewhere for this purpose. In this walkthrough we’re trying to keep things structurally simple. Let’s now turn to the markup of the view located in the view/home.html file. The root div element represents a view with the name ‘home’. Within it is a div containing markup for a placeholder called ‘content ’. content <div data- <div data- ... </div> </div> A toolbar is located at the top of the view: <div data-</div> dxToolbar is a PhoneJS UI widget. It’s defined in the markup using Knockout.js binding. dxToolbar A fieldset appears below the toolbar. To display a fieldset, we use two special CSS classes understood by PhoneJS: dx-fieldset and dx-field. The fieldset contains a text field for the bill total and two sliders for the tip percentage and the number of diners. dx-fieldset dx-field <div data- </div> <div data-</div> <div data-</div> Two buttons (dxButton) are displayed below the editors, allowing the user to round the total sum to pay. The remaining view displays fieldsets used for calculated results. dxButton <div class="round-buttons"> <div data-</div> <div data-</div> </div> <div id="results" class="dx-fieldset"> <div class="dx-field"> <span class="dx-field-label">Total to pay</span> <span class="dx-field-value" style="font-weight: bold" data-</span> </div> <div class="dx-field"> <span class="dx-field-label">Total per person</span> <span class="dx-field-value" data-</span> </div> <div class="dx-field"> <span class="dx-field-label">Total tip</span> <span class="dx-field-value" data-</span> </div> <div class="dx-field"> <span class="dx-field-label">Tip per person</span> <span class="dx-field-value" data-</span> </div> </div> This completes the description of the files required to create a simple app using PhoneJS. As you’ve seen, the process is simple, straightforward and intuitive. Starting and debugging a PhoneJS app is just like any other HTML5 based app. You must deploy the folder containing HTML and JavaScript sources, along with any other required file to your web server. Because there is no server-side component to the architectural model, it doesn’t matter which web server you use as long as it can provide file access through HTTP. Once deployed, you can open the app on a device, in an emulator or a desktop browser by simply navigating app’s start page URL. If you want to view the app as it will appear in a phone or tablet within a desktop browser, you will have to override the UserAgent in the browser. Fortunately, this is easy to do with the developer tools that ship as part of today’s modern browsers: If you prefer not to modify UserAgent settings, you can use the Ripple Emulator to emulate multiple device types. At this point you have a web application that will work in the browser on the mobile device and look like native app. Modern mobile browsers provide access to local storage, location api, camera, so good chances are that your app already has anything it needs. But what if you need access to device features that browser does not provide? What if you want an app in the app store, not just a webpage. Then you’ll have to create a hybrid application and de-facto standard for such an app is Apache Cordova aka PhoneGap. PhoneGap project for each platform is a native app project that contains WebView (browser control) and a “bridge” that lets your JavaScript code inside WebView access native functions provided by PhoneGap libraries and plugins. To use it, you need to have SDK for each platform you are targeting, but you don’t need to know details of native development, you just need to put your HTML, CSS, JS files into right places and specify your app’s properties like name, version, icons, splashcreens and so on. To be able to publish your app, you will need to register as developer in the respective development portal. This process is well documented for each store and beyond the scope of this article. After that you’ll be able to receive certificates to sign your app package. The need to have SDK for each platform installed sounds challenging - especially after “write one, run everywhere” promise of HTML5/JS approach. This is a small price to pay for building hybrid application and have everything under control. But still there are several services and products that solves this problem for you. One is Adobe’s online service - PhoneGap Build which allows you to build one app for free (to build more, you’ll need a paid account). If you have all the required platform certificate files, the service can build your app for all supported platforms with a few mouse clicks. You only need to prepare app descriptions, promotional and informational content and icons in order to submit your app to an individual store. For Visual Studio developers, DevExpress offers a product called DevExtreme (it includes PhoneJS), which can build applications for iOS, Android and Windows Phone 8 directly within the Microsoft Visual Studio IDE. To summarize, if you need a web application that looks and feels like native on a mobile device, you need PhoneJS - it contains everything required to build touch-enabled, native-looking web application. If you want to go further and access device features, like the contact list or camera, from JavaScript code, you will need Cordova aka PhoneGap. PhoneGap also lets you compile your web app into a native app package. If you don’t want to install an SDK for each platform you are targeting, you can use the PhoneGapBuild service to build your package. Finally, if you have DevExtreme, you can build packages right inside Visual Studio. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
http://www.codeproject.com/Articles/633706/PhoneJS-HTML5-JavaScript-Mobile-Development-Framew
CC-MAIN-2015-06
refinedweb
2,095
55.03
Install packages with Python tools on SQL Server Applies to: SQL Server 2017 (14.x) only This article describes how to use standard Python tools to install new Python packages on an instance of SQL Server Machine Learning Services. In general, the process for installing new packages is similar to that in a standard Python environment. However, some additional steps are required if the server does not have an Internet connection. For more information about package location and installation paths, see Get Python package information. Prerequisites - You must have SQL Server Machine Learning Services installed with the Python language option. Other considerations Packages must be Python 3.5-compliant and run on Windows. The Python package library is located in the Program Files folder of your SQL Server instance and, by default, installing in this folder requires administrator permissions. For more information, see Package library location. Package installation is per instance. If you have multiple instances of Machine Learning Services, you must add the package to each one. Database servers are frequently locked down. In many cases, Internet access is blocked entirely. For packages with a long list of dependencies, you will need to identify these dependencies in advance and be ready to install each one manually. Before adding a package, consider whether the package is a good fit for the SQL Server environment. We recommend that you use Python in-database for tasks that benefit from tight integration with the database engine, such as machine learning, rather than tasks that simply query the database. If you add packages that put too much computational pressure on the server, performance will suffer. On a hardened SQL Server environment, you might want to avoid the following: - Packages that require network access - Packages that require elevated file system access - Packages used for web development or other tasks that don't benefit by running inside SQL Server Add a Python package on SQL Server To install a new Python package that can be used in a script on SQL Server, you install the package in the instance of Machine Learning Services. If you have multiple instances of Machine Learning Services, you must add the package to each one. The package installed in the following examples is CNTK, a framework for deep learning from Microsoft that supports customization, training, and sharing of different types of neural networks. For offline install, download the Python package If you are installing Python packages on a server with no Internet access, you must download the WHL file from a computer with Internet access and then copy the file to the server. For example, on an Internet-connected computer you can download a .whl file for CNTK and then copy the file to a local folder on the SQL Server computer. See Install CNTK from Wheel Files for a list of available .whl files for CNTK. Important Make sure that you get the Windows version of the package. If the file ends in .gz, it's probably not the right version. For more information about downloads of the CNTK framework for multiple platforms and for multiple versions of Python, see Setup CNTK on your machine. Locate the Python library Locate the default Python library location used by SQL Server. If you have installed multiple instances, locate the PYTHON_SERVICES folder for the instance where you want to add the package. For example, if Machine Learning Services was installed using defaults, and machine learning was enabled on the default instance, the path is: cd "C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\PYTHON_SERVICES" Tip For future debugging and testing, you might want to set up a Python environment specific to the instance library. Install the package using pip Use the pip installer to install new packages. You can find pip.exe in the Scripts subfolder of the PYTHON_SERVICES folder. SQL Server Setup does not add the Scripts subfolder to the system path, so you must specify the full path, or you can add the Scripts folder to the PATH variable in Windows. Note If you're using Visual Studio 2017, or Visual Studio 2015 with the Python extensions, you can run pip install from the Python Environments window. Click Packages, and in the text box, provide the name or location of the package to install. You don't need to type pip install; it is filled in for you automatically. If the computer has Internet access, provide the name of the package: scripts\pip.exe install cntk You can also specify the URL of a specific package and version, for example: scripts\pip.exe install If the computer does not have Internet access, specify the WHL file you downloaded earlier. For example: scripts\pip.exe install C:\Downloads\cntk-2.1-cp35-cp35m-win_amd64.whl You might be prompted to elevate permissions to complete the install. As the installation progresses, you can see status messages in the command prompt window. Load the package or its functions as part of your script When installation is complete, you can immediately begin using the package in Python scripts in SQL Server. To use functions from the package in your script, insert the standard import <package_name> statement in the initial lines of the script: EXECUTE sp_execute_external_script @language = N'Python', @script = N' import cntk # Python statements ... '
https://docs.microsoft.com/en-us/sql/machine-learning/package-management/install-python-packages-standard-tools?view=sql-server-2017&viewFallbackFrom=azuresqldb-mi-current
CC-MAIN-2022-05
refinedweb
879
54.22
Windows Containers are an isolated, resource controlled, and portable operating environment. An application inside a container can run without affecting the rest of the system and vice versa. This isolation makes SQL Server in a Windows Container ideal for Rapid Test Deployment scenarios as well as Continuous Integration Processes. This blog provides a step by step guide of setting up SQL Server Express 2014 in a Windows Container by using this community-contributed Dockerfile. Prerequisites • System running Windows Server Technical Preview 4 or later. • 10GB available storage for container host image, OS Base Image and setup scripts. • Administrator permissions on the system. Setup a VM or a physical machine as a Windows Container Host Step 1: Start a PowerShell session as administrator. This can be done by running the following command from the command line. PS C:\> powershell.exe Step 2: Use the following command to download the setup script. Note: The script can also be manually downloaded from this location – Configuration Script. wget -uri -OutFile C:\Install-ContainerHost.ps1 Step 3: After the download completes, execute the script. PS C:\> powershell.exe -NoProfile C:\Install-ContainerHost.ps1 With these steps completed your system should be ready for Windows Containers. You can follow this link to read the full article that describes more on setting up a VM or a physical machine as a Windows Container Host. Installing SQL Server Express 2014 in a Windows Container Step 1: Copy all files from this community-contributed Dockerfile locally into your c:\sqlexpress folder. Note: All files were provided by brogersyh . The Dockerfile contains all the SQL Server configuration settings (ports, passwords etc.) that you can customize if needed. Step 2: Start a PowerShell session and run the following command: docker build -t sqlexpress . Starting SQL Server Step 1: Start a PowerShell session and run the following command: docker run -it -p 1433:1433 sqlexpress cmd Step 2: Enter PowerShell in the Container Window by typing: Powershell Step 3: Start SQL Server by running the following PS Script (downloaded from step2): ./start Step 4: Verify that SQL Server is running with the following command: get-service *sql* Next Steps We are currently working on testing and publishing SQL Server Container Images that could speed up the process of getting started with SQL Server in Windows Containers significantly. Stay tuned for an update! Further Reading Windows Containers Overview Windows-based containers: Modern app development with enterprise-grade control. Windows Containers: What, Why and How Join the conversationAdd Comment ist there a way to access the DB with the sql management studio? Absolutely! You can access the DB from sql management studio by using the container’s IP Address along with the sql authentication credentials stored in the Dockerfile (Installing SQL Server Express 2014 in a Windows Container: Step1 int he tutorial). Use the container’s internal IP Address if you are accessing the DB from SSMS installed on the Host and the external IP Address if you are accessing it from another machine. Note that a firewall rule might need to be created depending upon your setup. Please refer to this article for more information regarding Container Networking:. What is the advantage of a Docker container running SQL Server in isolation over a VM running SQL Server in isolation? With a VM, I only need one copy of the OS bits. With a Docker container, there appears to be multiple copies of the OS bits in C:\ProgramData\docker\windowsfilter. After following the instructions above I ended up with 21GB of bloat in those folders. What’s the point? Thanks a lot for the feedback Paul. You can think of containers as another resource sharing option and not necessarily as a VM replacement. Depending on the scenario one option might be more suitable than the other. With that said, choosing between a container and a VM can be tricky, but I believe that this blog post: provides a nice overview on Containers and explains their key differences compared to VMs (Eg. namespace isolation, governing resources etc.). Hope that helps. Hi, I was able to build the container image with you scripts: PS C:\sqlexpress> docker images REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE sqlexpress latest 707d46ea7004 16 minutes ago 3.239 GB But when I try to start the container, I get a huge error: PS C:\sqlexpress> docker run -it -p 1433:1433 sqlexpress cmd docker : panic: runtime error: invalid memory address or nil pointer dereference At line:1 char:1 + docker run -it -p 1433:1433 sqlexpress cmd + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (panic: runtime …ter dereference:String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError Any ideas? Hi Pedro – Could you please post this issue to the Windows container forum for further investigation? Thanks, Perry Hi Perry, Yes, I can. I’ve been digging a little bit more on the subject but I will post it to the forum. hello I have followed your steps and everything is working like a charm. Thanks you Great! Thanks for trying SQL in Windows Containers SoyUnEmilio! How can one attach already present mdf and log file? what exactly is happening in datatemp, start.ps1? Hi Sam – Please take a look at the following section that describes how you can attach existing .mdf and .ldf files. Can you be a bit more specific on your datatemp, start.ps1 question? Thanks, Perry Given that SQL Server uses non-preemptive scheduling and aside from two windows DLLs it is virtually bare metal when it comes to scheduling, how does resource management work with SQL Server and windows containers, in terms of constraining the CPU resource and instance uses. Hi Chris – Please take a look at this:–Part-4-Resource-Management video that walks through how to manage resources, such as CPU, disk, memory and network, for Windows Server Containers. Thanks, Perry Is there an option to run full SQL Server i.e. not express, in a container? Hi Andrew – Although, currently SQL Server Express is the only edition available as a Docker image, you could edit the existing Docker file: and create your own image. Thanks, Perry Hi I have one container with Web site up and running on the my development machine windows 2016(I did not commit yet), of course I need to port on to docker hub. Now I need to build another container to host db sql server express. 1. I have question how to do download it on to client(windows 10) as client, I am seeing the image ps images dockker images command. How do I add it to my client through vm hyper v app? or docker run command. Also just wondering how work on db stuff now, create another container sql server express and how does this web container will see db container. app web ui taking to db server on client machine. Hi Narayan – Please follow the tutorial below to get started with setting up a multi container application that includes SQL Server Express 2016. Let me know if you run into any issues, Thanks, Perry
https://blogs.msdn.microsoft.com/sqlserverstorageengine/2016/03/21/sql-server-in-windows-containers/
CC-MAIN-2018-47
refinedweb
1,171
54.83
arup rakshit Joined 80 Experience 0 Lessons Completed 0 Questions Solved Activity Thanks for your suggestions! Thanks again! How can I refactor the view code, and extract out as much as Ruby code from that ? What is your suggestion regarding the searching as you mentioned in your earlier comment? Thanks for your reply! No, I am just trying to display users names group by location/age/department etc. Currently nothing I think about for searching. How can I write the below operation, being handled by group_by Ruby method, in terms of DB specific query? def list_users @search_by_options = [:age, :location, :department, :designation] @users = User.all.group_by { |user| user.public_send(params[:search_by] || :location) } end Corresponding view code is as below :- <%= form_tag list_users_users_path, :method => 'get' do %> <p> <%= select_tag "search_by", options_for_select(@search_by_options) %> <%= submit_tag "Submit"%> </p> <% end %> <% @users.each do |grouping_key, users| %> <p> <%= grouping_key %> : <%= users.map(&:name).join("||")%></p> <% end %> <%= link_to "Back to Main page", root_path %>
https://gorails.com/users/1548
CC-MAIN-2020-50
refinedweb
151
51.34
"Shall I compare thee to a summer's day?" - William Shakespeare, 'Sonnets' Created: 24th October 1999 Last Modified: 27th November 1999 This page explains how to compare values and use conditional jumps. The CP instruction stands for compare. It takes the general form cp ValueToCompareWith and compares the value of the a register with ValueToCompareWith, which can be any 8 bit register, an 8 bit number or (hl). So: cp 7 cp b cp e cp (hl) cp %11010111 and so on. What the CP instruction actually does is substracts ValueToCompareWith from the value of the a register, but it doesn't store the result anywhere or affect the value of either the a register or ValueToCompareWith. What it does do is affect the flags. The f register is sometimes called the flag register. It can't be used in maths, logic or any other 'useful' instruction (it can be pushed and popped from the stack when paired with a to give the af register pair). However, many instructions affect the value of f. Most of the bits in f have a meaning, for example one of the bits is set if there has been a carry and reset if there hasn't. The f register lets us use 'if..else' statements in assembly. There is another form of the CALL, JR and JP instructions, which is call condition,address (or jp condition,address or jr condition,address). The address part remains the same, and condition is one of the following (there are other possibilities, but they don't all work for JR): Note that you can also do ret condition. So you can now finally write a useful program (or at least you can once I've told you what call _getkey does). The _getkey ROM routine pauses the calculator until a key is pressed, and then returns the value of that key in the a register. It also trashes a few other registers, so if you need them don't forget to push them onto the stack. The number returned in the a register isn't the same as the one used in the built in language, it's a bit more advanced. There are equates defined for the different keys, so rather than doing cp 7 you can do cp kExit (for some reason there's no underscore). If you need a list of the equates for the keys they're in a file called "asm86.h" which you'll find in whatever directory you installed Assembly Studio in in a subdirectory called "include". They all start with a small k - the ones with a capital k are something else. The program should clear the screen. It should then wait for a key to be pressed. If the key is [EXIT] then the program should quit. If the key is [ENTER] then the program should display a star (character 42) on the screen and go onto the next line. If it is any other key the program should do nothing. The program should then wait for another key and so on. Try and work out your own code before copying the one below. Remember, your code will probably be different from mine because I've used a few shortcuts, but as long as it works that's fine. Source: getkey1.asm Compiled: getkey1.86p #include "ti86asm.inc" .org _asm_exec_ram call _clrScrn ; Clears the screen (duuh!) call _homeup ; Cursor to top left LoopStart: call _getkey ; Wait for a key to be pressed cp kExit ; Compare it to kExit - [EXIT] key ret z ; If they're equal return to the OS cp kEnter ; Otherwise compare it to kEnter - [ENTER] key jr nz,LoopStart ; If it's not enter go and get another key ; If it is enter... ld a,42 ; a = 42 (ASCII character '*') call _putc ; Display charater in a call _newline ; Go onto a new line jr LoopStart ; Then go back to the start of the loop .end ; Tell the assembler to stop
http://www.asm86.cwc.net/tutorial/page3_7.html
crawl-001
refinedweb
665
70.84
The title is not a mistake. Does it mean RxJava 2.x is a step back? Quite the contrary! In 2.x an important distinction was made: 2.x makes an important distinction between streams that can support backpressure ("can slow down if needed" in simple words) and those that don't. From the type system perspective it becomes clear what kind of source are we dealing with and what are its guarantees. So how should we migrate our So, to wrap up, whenever you see an There is no simple rx.Observablefrom RxJava 1.x is a completely different beast than io.reactivex.Observablefrom 2.x. Blindly upgrading rxdependency and renaming all imports in your project will compile (with minor changes) but does not guarantee the same behavior. In the very early days of the project Observablein 1.x had no notion of backpressure but later on backpressure was included. What does it actually mean? Let's imagine we have a stream that produces one event every 1 millisecond but it takes 1 second to process one such item. You see it can't possibly work this way in the long run: import rx.Observable; //RxJava 1.x import rx.schedulers.Schedulers; Observable .interval(1, MILLISECONDS) .observeOn(Schedulers.computation()) .subscribe( x -> sleep(Duration.ofSeconds(1))); MissingBackpressureExceptioncreeps in within few hundred milliseconds. But what does this exception mean? Well, basically it's a safety net (or sanity check if you will) that prevents you from hurting your application. RxJava automatically discovers that producer is overflowing the consumer and proactively terminates the stream to avoid further damage. So what if we simply search and replace few imports here and there? import io.reactivex.Observable; //RxJava 2.x import io.reactivex.schedulers.Schedulers; Observable .interval(1, MILLISECONDS) .observeOn(Schedulers.computation()) .subscribe( x -> sleep(Duration.ofSeconds(1)));The exception is gone! So is our throughput... The application stalls after a while, staying in an endless GC loop. You see, Observablein RxJava 1.x has assertions (bounded queues, checks, etc.) all over the place, making sure you are not overflowing anywhere. For example observeOn()operator in 1.x has a queue limited to 128 elements by default. When backpressure is properly implemented across the whole stack, observeOn()operator asks upstream to deliver not more than 128 elements to fill in its internal buffer. Then separate threads (workers) from this scheduler are picking up events from this queue. When queue becomes almost empty, observeOn()operator asks ( request()method) for more. This mechanism breaks apart when producer does not respect backpressure requests and sends more data than it was allowed, effectively overflowing the consumer. The internal queue inside observeOn()operator is full, yet interval()operator keeps emitting new events - because that's what interval()is suppose to do. Observablein 1.x discovers such overflow and fails fast with MissingBackpressureException. It literally means: I tried so hard to keep the system in healthy state, but my upstream is not respecting backpressure - backpressure implementation is missing. However Observablein 2.x has no such safety mechanism. It's a vanilla stream that hopes you will be a good citizen and either have slow producers or fast consumers. When system is healthy, both Observables behave the same way. However under load 1.x fails fast, 2.x fails slowly and painfully. Does it mean RxJava 2.x is a step back? Quite the contrary! In 2.x an important distinction was made: Observabledoesn't care about backpressure, which greatly simplifies its design and implementation. It should be used to model streams that can't support backpressure by definition, e.g. user interface events Flowabledoes support backpressure and has all the safety measures in place. In other words all steps in computation pipeline make sure you are not overflowing the consumer. interval()example to RxJava 2.x? Easier than you think: Flowable .interval(1, MILLISECONDS) .observeOn(Schedulers.computation()) .subscribe( x -> sleep(Duration.ofSeconds(1)));That simple. You may ask yourself a question, how come Flowablecan have interval()operator that, by definition, can't support backpressure? After all interval()is suppose to deliver events at constant rate, it can't slow down! Well, if you look at the declaration of interval()you'll notice: @BackpressureSupport(BackpressureKind.ERROR)Simply put this tells us that whenever backpressure can no longer be guaranteed, RxJava will take care of it and throw MissingBackpressureException. That's precisely what happens when we run Flowable.interval()program - it fails fast, as opposed to destabilizing whole application. So, to wrap up, whenever you see an Observablefrom 1.x, what you probably want is Flowablefrom 2.x. At least unless your stream by definition does not support backpressure. Despite same name, Observables in these two major releases are quite different. But once you do a search and replace from Observableto Flowableyou'll notice that migration isn't that straightforward. It's not about API changes, the differences are more profound. There is no simple Flowable.create()directly equivalent to Observable.create()in 2.x. I made a mistake myself to overuse Observable.create()factory method in the past. create()allows you to emit events at an arbitrary rate, entirely ignoring backpressure. 2.x has some friendly facilities to deal with backpressure requests, but they require careful design of your streams. This will be covered in the next FAQ. FYI, there is the Flowables.intervalBackpressure operator in the extensions project that doesn't signal MissingBackpressureException and emits values based on time and demand: The thing to note is that the emission pattern may no longer be completely periodic and the signals may arrive in quick succession if there was a temporal lack of requests. I once asked you a related question on Twitter, but still unsure - does your RxJava book cover 2.x flavor? If not - do you consider it still relevant or you plan for 2.x edition? Dear Igor, our RxJava book unfortunately covers 1.x. I have no plans so far to publish a 2nd edition, but we'll see :-).
https://www.nurkiewicz.com/2017/08/1x-to-2x-migration-observable-vs.html
CC-MAIN-2018-34
refinedweb
1,001
52.05
Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video. Better Errors4:20 with Alena Holligan One of the most commonly overlooked parts of designing an API is proper error messaging. We all get excited to get our API out the door for its amazing functionality, and we forget to take care of informing callers of our API about errors that they might encounter. Because clients don’t have access to our error logs, we need to give them appropriate error messages. Exception Constants const COURSE_NOT_FOUND = 'Course Not Found'; const COURSE_INFO_REQUIRED = 'Required course data missing'; const COURSE_CREATION_FAILED = 'Unable to create course'; const COURSE_UPDATE_FAILED = 'Unable to update course'; const COURSE_DELETE_FAILED = 'Unable to delete course'; const REVIEW_NOT_FOUND = 'Review Not Found'; const REVIEW_INFO_REQUIRED = 'Required review data missing'; const REVIEW_CREATION_FAILED = 'Unable to create review'; const REVIEW_UPDATE_FAILED = 'Unable to update review'; const REVIEW_DELETE_FAILED = 'Unable to delete review'; Error Handler To change how the handler, we have to add it to our dependencies as the "errorHandler" $container['errorHandler'] = function ($c) { return function ($request, $response, $exception) use ($c) { $data = [ 'status' => 'error', 'code' => $exception->getCode(), 'message' => $exception->getMessage(), ]; return $response->withJson($data,$statusCode); }; }; - 0:00 One of the most commenly overlooked parts of designing an API - 0:05 is proper error messaging. - 0:07 We all get excited to get our API out the door for its amazing functionality. - 0:12 And we forget to take care of informing callers of our API - 0:16 about errors that they might encounter. - 0:18 Because clients don't have access to our error logs, - 0:22 we need to give them appropriate error messages. - 0:26 Let's see what we can do about better communicating when things don't go right. - 0:32 We're going to start by setting up a custom exception for our API. - 0:36 Add a new folder under source named Exception. - 0:44 Then create a new file named APIException.php. - 0:54 First, we need to add our namespace. - 0:59 This will be App\Exception. - 1:04 Then we can add our class. - 1:06 ApiException extends the default Exception. - 1:18 We're going to keep this class pretty close to the original, - 1:24 so we'll start with our constructor, public function __construct. - 1:31 Our message, Will have a default of an empty string. - 1:38 Our code will default to 400 and - 1:44 our Exception previous or null. - 1:51 Then we're gonna call the parent __construct. - 1:57 Pass the message, the code and previous. - 2:03 Besides that, we're going to add some constants for writing our messages. - 2:08 We'll be able to access these outside the class, just like we do for - 2:12 the PDO constants. - 2:14 This will help our verbage stay consistent. - 2:16 I don't wanna worry about typing all these out. - 2:18 So I've included them in the teacher's notes. - 2:21 You can copy and paste from there. - 2:24 This is just an extra exception, - 2:26 it's not gonna actually change how Slim handles the exceptions. - 2:30 So we wanna set up a custom handler as well, so - 2:33 we can return a JSON error response. - 2:37 So in our dependencies, We're going to add another container. - 2:46 Container, and this needs to be called errorHandler. - 2:59 And let's close our semi colon. - 3:02 Then we're going to return and set a new function. - 3:07 We'll need the request, the response, - 3:11 and the exception, and we'll want to use. - 3:19 We'll set data equal to an array. - 3:24 Let's close some semi colons. - 3:29 Our status is going to equal error. - 3:36 Our code is going to equal the exception getCode and - 3:42 the message, Is going to equal the exception, getMessage. - 3:53 Now, we can return a response withJson and - 3:58 say data and the exception, getCode. - 4:05 Let's check this out with Postman just to make sure that we didn't break anything. - 4:10 We're gonna look for all our courses. - 4:13 Great, it still works. - 4:15 Now, we're ready to look at our methods and throw some exceptions.
https://teamtreehouse.com/library/better-errors
CC-MAIN-2020-05
refinedweb
739
64.81
You can subscribe to this list here. Showing 2 results of 2 Hi, I am running into an issue trying to use enable_on_exec in per-thread mode with an event group. My understanding is that enable_on_exec allows activation of an event on first exec. This is useful for tools monitoring other tasks and which you invoke as: tool my_program. In other words, the tool forks+execs my_program. This option allows developers to setup the events after the fork (to get the pid) but before the exec(). Only execution after the exec is monitored. This alleviates the need to use the ptrace(PTRACE_TRACEME) call. My understanding is that an event group is scheduled only if all events in the group are active (disabled=0). Thus, one trick to activate a group with a single ioctl(PERF_IOC_ENABLE) is to enable all events in the group except the leader. This works well. But once you add enable_on_exec on on the events, things go wrong. The non-leader events start counting before the exec. If the non-leader events are created in disabled state, then they never activate on exec. The attached test program demonstrates the problem. simply invoke with a program that runs for a few seconds. #include <sys/types.h> #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <unistd.h> #include <string.h> #include <sys/wait.h> #include <syscall.h> #include <err.h> #include <perf_counter.h> int child(char **arg) { int i; /* burn cycles to detect if monitoring start before exec */ for(i=0; i < 5000000; i++) syscall(__NR_getpid); execvp(arg[0], arg); errx(1, "cannot exec: %s\n", arg[0]); /* not reached */ } int parent(char **arg) { struct perf_counter_attr hw[2]; char *name[2]; int fd[2]; int status, ret, i; uint64_t values[3]; pid_t pid; if ((pid=fork()) == -1) err(1, "Cannot fork process"); memset(hw, 0, sizeof(hw)); name[0] = "PERF_COUNT_HW_CPU_CYCLES"; hw[0].type = PERF_TYPE_HARDWARE; hw[0].config = PERF_COUNT_HW_CPU_CYCLES; hw[0].read_format = PERF_FORMAT_TOTAL_TIME_ENABLED|PERF_FORMAT_TOTAL_TIME_RUNNING; hw[0].disabled = 1; hw[0].enable_on_exec = 1; name[1] = "PERF_COUNT_HW_INSTRUCTIONS"; hw[1].type = PERF_TYPE_HARDWARE; hw[1].config = PERF_COUNT_HW_INSTRUCTIONS; hw[1].read_format = PERF_FORMAT_TOTAL_TIME_ENABLED|PERF_FORMAT_TOTAL_TIME_RUNNING; hw[1].disabled = 0; hw[1].enable_on_exec = 1; fd[0] = perf_counter_open(&hw[0], pid, -1, -1, 0); if (fd[0] == -1) err(1, "cannot open event0"); fd[1] = perf_counter_open(&hw[1], pid, -1, fd[0], 0); if (fd[1] == -1) err(1, "cannot open event1"); if (pid == 0) exit(child(arg)); waitpid(pid, &status, 0); for(i=0; i < 2; i++) { ret = read(fd[i], values, sizeof(values)); if (ret < sizeof(values)) err(1, "cannot read values event %s", name[i]); if (values[2]) values[0] = (uint64_t)((double)values[0] * values[1]/values[2]); printf("%20"PRIu64" %s %s\n", values[0], name[i], values[1] != values[2] ? "(scaled)" : ""); close(fd[i]); } return 0; } int main(int argc, char **argv) { if (!argv[1]) errx(1, "you must specify a command to execute\n"); return parent(argv+1); } Oleg, On Tue, Aug 18, 2009 at 1:45 PM, Oleg Nesterov<oleg@...> wrote: > On 08/18, stephane eranian wrote: >> > In any case. We should not look at SA_SIGINFO at all. If sys_sigaction() was >> > called without SA_SIGINFO, then it doesn'matter if we send SEND_SIG_PRIV or >> > siginfo_t with the correct si_fd/etc. >> > >> What's the official role of SA_SIGINFO? Pass a siginfo struct? >> >> Does POSIX describe the rules governing the content of si_fd? >> Or is si_fd a Linux-ony extension in which case it goes with F_SETSIG. > > Not sure I understand your concern... > > OK. You suggest to pass siginfo_t with .si_fd/etc when we detect SA_SIGINFO. > The reason I refer to SA_SIGINFO is simply because of the excerpt from the sigaction man page:. In other words, I use this to emphasize the fact that to get a siginfo struct, you need to pass SA_SIGINFO and use sa_sigaction instead of sa_handler. That's all I am saying. > But, in that case we can _always_ pass siginfo_t, regardless of SA_SIGINFO. > If the task has a signal handler and sigaction() was called without > SA_SIGINFO, then the handler must not look into *info (the second arg of > sigaction->sa_sigaction). And in fact, __setup_rt_frame() doesn't even > copy the info to the user-space: > > if (ka->sa.sa_flags & SA_SIGINFO) { > if (copy_siginfo_to_user(&frame->info, info)) > return -EFAULT; > } > > OK? Or I missed something? > No, I think we are in agreement. To get meaningful siginfo use SA_SIGINFO. > Or. Suppose that some app does: > > void io_handler(int sig, siginfo_t *info, void *u) > { > if ((info->si_code & __SI_MASK) != SI_POLL) { > // RT signal failed! sig MUST be == SIGIO > recover(); > } else { > do_something(info->si_fd); > } > } > > int main(void) > { > sigaction(SIGRTMIN, { SA_SIGINFO, io_handler }); > sigaction(SIGIO, { SA_SIGINFO, io_handler }); > ... > } > I don't think you can check si_code without first checking which signal it is in si_signo. The values for si_code overlap between the different struct in siginfo->_sifields. >> It would seem natural that in the siginfo passed to the handler of SIGIO, the >> file descriptor be passed by default. That is all I am trying to say here. > > Completely agreed! I was always puzzled by send_sigio_to_task(). I was never > able to understand why it looks so strange. > > So, I think it should be > > static void send_sigio_to_task(struct task_struct *p, > struct fown_struct *fown, > int fd, > int reason) > { > siginfo_t si; > /* > * F_SETSIG can change ->signum lockless in parallel, make > * sure we read it once and use the same value throughout. > */ > int signum = ACCESS_ONCE(fown->signum) ?: SIGIO; > > if (!sigio_perm(p, fown, signum)) > return; > > si.si_signo = signum; > si.si_errno = 0; > si.si_code = reason; > si.si_fd = fd; > /* Make sure we are called with one of the POLL_* > reasons, otherwise we could leak kernel stack into > userspace. */ > BUG_ON((reason & __SI_MASK) != __SI_POLL); > if (reason - POLL_IN >= NSIGPOLL) > si.si_band = ~0L; > else > si.si_band = band_table[reason - POLL_IN]; > > /* Failure to queue an rt signal must be reported as SIGIO */ > if (!group_send_sig_info(signum, &si, p)) > group_send_sig_info(SIGIO, SEND_SIG_PRIV, p); > } > > (except it should be on top of fcntl-add-f_etown_ex.patch). > This way, at least we don't break the "detect RT signal failed" above. > > What do you think? > > But let me repeat: I just can't convince myself we have a good reason > to change the strange, but carefully documented behaviour. > I agree with you. Given the existing documentation in the man page of fcntl() and the various code examples. I think it is possible for developers to figure out how to get the si_fd in the handler. This problem is not specific to perf_counters nor perfmon. Any SIGIO-based program may be interested in getting si_fd, therefore I am assuming the solution is well understood at this point.
http://sourceforge.net/p/perfmon2/mailman/perfmon2-devel/?viewmonth=200908&viewday=20
CC-MAIN-2015-06
refinedweb
1,089
60.51
Automatic, accurate crop type maps can provide unprecedented information for understanding food systems, especially in developing countries where ground surveys are infrequent. However, little work has applied existing methods to these data scarce environments, which also have unique challenges of irregularly shaped fields, frequent cloud coverage, small plots, and a severe lack of training data. To address this gap in the literature, we provide the first crop type semantic segmentation dataset of small holder farms, specifically in Ghana and South Sudan. We are also the first to utilize high resolution, high frequency satellite data in segmenting small holder farms. The dataset includes time series of satellite imagery from Sentinel-1, Sentinel-2, and PlanetScope satellites throughout 2016 and 2017. For each tile/chip in the dataset, there are time series of imagery from each of the satellites, as well as a corresponding label that defines the crop type at each pixel. The label has only one value at each pixel location, and assumes that the crop type remains the same across the full time span of the satellite image time series. In many cases where ground truth was not available, pixels have no label and are set to a value of 0. Crop type mapping of small holder farms in Ghana and South Sudan Semantic Segmentation of Crop Type in Africa: A Novel Dataset and Analysis of Deep Learning Methods, Rose Rustowicz Rustowicz R., Cheong R., Wang L., Ermon S., Burke M., Lobell D. (2020) "Semantic Segmentation of Crop Type in South Sudan Dataset", Version 1.0, Radiant MLHub. [Date Accessed] from radiant_mlhub import Dataset ds = Dataset.fetch('su_african_crops_south_sudan') for c in ds.collections: print(c.id) Python Client quick-start guide
https://mlhub.earth/data/su_african_crops_south_sudan
CC-MAIN-2022-27
refinedweb
282
51.78
ye gods, I’m trying to learn my 1st OO lang and chose ruby. I’ve already got a couple of simple batch processing programs written and functioning but CommandLine is kicking my butt. As I read the docs ‘program -a -b’ can be called with ‘program -ab’, setting flags a & b in either case. I get an Unknown option error. I cut this example directly from: /usr/lib/ruby/gems/1.8/gems/commandline-0.7.10/docs/posted-docs.index.html #!/usr/bin/env ruby require ‘rubygems’ require ‘commandline’ class App < CommandLine::Application def initialize options :help, :debug end def main puts “call your library here” end end#class App Then added :verbose to options (options :help, :debug, :version). My results: % ruby example.rb -d -v call your library here % ruby example.rb -dv Unknown option ‘-dv’. Usage: example.rb % _ I’ve read everything I can find and tried a dozen different permutations on the theme, including :posix instead of :flag. I’m sure I’m overlooking something basic due to newbie-myopia. Any advice? pb
https://www.ruby-forum.com/t/commandline-help-for-frustrated-newb/58616
CC-MAIN-2018-47
refinedweb
179
57.57
Java Reference In-Depth Information Thread 1_Prepare to increase book stock Thread 1 _ Book stock increased by 5 Thread 1 _ Sleeping Thread 2 _ Prepare to check book stock Thread 1 _ Wake up Thread 1 _ Book stock rolled back Thread 2 _ Book stock is 10 Thread 2 _ Sleeping Thread 2_Wake up In order that the underlying database can support the READ_COMMITTED isolation level, it may acquire an update lock on a row that was updated but not yet committed. Then other transactions must wait to read that row until the update lock is released, which happens when the locking transaction commits or rolls back. The REPEATABLE_READ Isolation Level Now let's restructure the threads to demonstrate another concurrency problem. Swap the tasks of the two threads so that thread 1 checks the book stock before thread 2 increases the book stock. package com.apress.springenterpriserecipes.bookshop.spring; ... public class Main { public static void main(String[] args) { ... final BookShop bookShop = (BookShop) context.getBean( " bookShop " ); Thread thread1 = new Thread(new Runnable() { public void run() { bookShop.checkStock( " 0001 " ); } }, " Thread 1 " ); Thread thread2 = new Thread(new Runnable() { public void run() { try { bookShop.increaseStock( " 0001 " , 5); } catch (RuntimeException e) {} } }, " Thread 2 " ); Search WWH :: Custom Search
http://what-when-how.com/Tutorial/topic-105fbg1u/Spring-Enterprise-Recipes-A-Problem-Solution-Approach-208.html
CC-MAIN-2018-30
refinedweb
206
58.01
Arduino, The Documentary Today's Mobile Monday post is one that I thought could dispatch a number of birds with a single post... What do you think of when you hear the word “Champ”? Someone who is the best? A sports champion? How about someone who fights for a cause? Here at Microsoft we have employees called “Developer Evangelists”. Part of their job is to help get the word out about Microsoft products and technologies. The other part of their job is to champion our developers. Here in Windows Phone we call our evangelists “Phone Champs”. Champs ensure our developers get exactly the help & support they need and are the voice of the developer community. They are all experts on our platform and serve as local resources to answer questions from current or prospective developers. Champs can help you troubleshoot a problem in your app and can help you get your hands on a phone for testing. Oh, and some of our Champs are really funny and can tell you a good joke or two. So how do you find one of our great Phone Champs? Today I’m happy to announce a new application to help you find them. We originally wanted to call the app “Champ Acquisition and Discovery 1.0 for Workgroups Windows Phone Edition.” Luckily cooler heads prevailed and we’re calling it “Find My Champ”. ... Get the App Go download the app’s source code. Compile the code in our dev tools and side-load Find My Champ onto your developer device or into the emulator. The app will also be in the Marketplace soon for you to download. Find your local Phone Champ and get in touch with them. Ask them for help with your app or to let you know about events or hackathons in your area. We’d love to get your feedback on the Find My Champ application. Tell us what we can do to make it more useful. You can also come help us improve the app on Codeplex. Additionally, I suspect that many of you will have creative ideas for how to use the Champs OData feed in other applications, mashups, etc. Please let me know what you create! The first thing that I thought was cool was that this is backed on an OData feed. This means that if we, the development community want to present our own view of the data, in our own apps, we can very easily. Using the OData feed is very easy. Here's a snap from the must have LINQPad utility querying the feed. LINQPad makes it almost too easy to play with this feed. Say I want all the Champs with a Last Name starting with E, order by LastName? Or who have a MSDN blog and also have a Twitter account? Okay, OData via Linq is cool, but what if you want the actual OData URL for this query? Again, LINQPad makes that click easy. Just click on the "SQL" right above the results; Then to maybe finally blow your mind, did you know Notepad can open URL's? So we're got the data, lets check out the app source. First, when you download the source, you'll need to add one reference, easily done via NuGet. When you first open the Solution you'll see this (if you expand the given items). Note the warning/missing icons; Fire up NuGet and search for "SilverlightToolkitWP" Click install. That's it. You should now be good to go and able to run the app in the Emulator. When first running the app in the Emulator, the Local list will be this default list. If you want to see the local people for a given location, set the location and then re-run the app (refresh doesn't yet seem to take a change in location into account). So here I set the location; Then exit and re-run the app in the Emulator. Set to another location, exit and rerun the app. You don't need to kill the emulator or debugging session, just re-run it in the emulator (if that makes sense?) The source is pretty easily readable and spelunkable; Data binding is used as you would expect. One of the things I thought key was how "local" was determined. How was your location and the Champ's Lat/Long's used to determine "local?" public static double GetDistance(double fromLatitude, double fromLongitude, double toLatitude, double toLongitude) { int earthRadius = 6371; // earth's radius (mean) in km double chgLat = DegreeToRadians(toLatitude - fromLatitude); double chgLong = DegreeToRadians(toLongitude - fromLongitude); double a = Math.Sin(chgLat / 2) * Math.Sin(chgLat / 2) + Math.Cos(DegreeToRadians(fromLatitude)) * Math.Cos(DegreeToRadians(toLatitude)) * Math.Sin(chgLong / 2) * Math.Sin(chgLong / 2); double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a)); double d = earthRadius * c; return d; } private static double DegreeToRadians(double value) { return Math.PI * value / 180.0; } private void UpdateDistance() { if (GeoData.Status != GeoPositionStatus.Ready) return; // when position is updated, update distance var _FromLat = GeoData.Location.Latitude; var _FromLong = GeoData.Location.Longitude; var _ToLat = (double)Latitude; var _ToLong = (double)Longitude; this.DistanceAway = FMCLocation.GetDistance(_FromLat, _FromLong, _ToLat, _ToLong); } // this is the same as PropertyChanged("Distance"), just easier to use public event EventHandler DistanceChanged; private double m_DistanceAway; public double DistanceAway { get { return m_DistanceAway; } set { m_DistanceAway = value; OnPropertyChanged("DistanceAway"); OnPropertyChanged("IsLocal"); if (DistanceChanged != null) DistanceChanged(this, EventArgs.Empty); } } public bool IsLocal { get { return (DistanceAway > 0 && DistanceAway < 250); } } If you're looking for help in building your Windows Phone 7 applications and are looking for help, think about contacting your local Champ. That's part of their job and desire, to be there to help you. Finding them, is now super easy, via this app (which you have to agree is kind of meta-cool... Very cool Great post. I love seeing the LINQPad stuff and I had no idea that Notepad could do that! I will also share that we got our first remix on the Find My Champ app. See the video here: Excellent !!! Thank you for this.
https://channel9.msdn.com/coding4fun/blog/Need-to-find-your-local-Windows-Phone-Champion-Heres-an-OData-service-Phone-app-and-source-that-will
CC-MAIN-2017-51
refinedweb
1,014
66.64
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. Tutorial that explains interaction with the OpenERP ORM? I am in process of writing OpenERP modules and want to learn how: (1) To be able to create model objects (2) Store data or records in them via an API. (3) Query them to retrieve data. (Just like we do in Django Models using the Queryset API) Where can I get a good tutorial that explains the above 3 cases with all the available methods? Also, I want to interact with the ORM with the help of easy to use Python API's without using XML-RPC's as much as possible. Regarding (1): when you do a search for 'openerp create module', there are various sites (including youtube) which show and help you to create a new module. Although many of them say it is for V6 or V6.1, it also works for V7. Regarding (2): What do you mean by this question? Regarding (3): within the module, you can use API-like things like model_id = model.search([('fieldname', '=', some_value')]) if there is no result, model_id will be [], otherwise [<id>] It is not clear to me what you mean by the last sentence, but I think you want to use the openERP ORM, from script(s), without logging in into openERP. In that case, I use openerplib, a module you can install 'openerplib'. This allows you to hide the XML-RPC like code, to get some nicer looking code. Next week I can post how to install this library and an example, how to make a script using this library. #openerplib I use Ubuntu, so if you are using Windows, change the commands to Windows commands. To install openerplib, you need to download and install setup_tools: wget sudo ./setuptools-0.6c11-py2.7.egg now you can openerplib: sudo easy_install openerp-client-lib usage of openerplib in a script import openerplib h = 'localhost' db = 'myDB' u = 'admin' pw = 'verySecurePassword!' connection = openerplib.get_connection( hostname=h, database=db, login=u, password=p) #now you have a connection to the DB and can you do some things #first get an object of your model user_obj = connection.get_model('res.model') # use this object to execute some action, in this case, search for user(s) # with John in the name, but also Johnny.... user_id = user_obj.search([('name', 'in', 'John')]) if user_id == []: print 'No user found who has John in his name' else: #now read all the users whose IDs are in user_id users = user_bj.read(user_id) print 'There are %s user(s) with John in the name' %(len(user_id) for u in users: print 'User %s has userID %s' %(u['name'], u['id']) #close the connection nicely connection.close() (2) I want to load a model (table) with data retrieved dynamically from an external application API. The idea is to be able to interact with the external API from within OpenERP, synchronize OpenERP model data with the API data, (when a new record is created via Openerp action, a resource is added for the same via a PUT or POST request to the external API too, and vice versa) Perhaps (2) needs to be framed into a new question. The openerplib thing sounds exiting. Can you give me a link to it; get lots of stuff when I search? Hi, you can start with Developer Memento OpenERP for Open Source RAD with OpenERP 7.0 and good start with ORM. Yes, got it a day back. I got a link on one of your other answers on a question asking about Module development. This doc is perhaps the best I have see so far. Thanks, (On a sidenote, I still think there needs to be more documentation to explain module development in detail and with different!
https://www.odoo.com/forum/help-1/question/tutorial-that-explains-interaction-with-the-openerp-orm-18168
CC-MAIN-2016-50
refinedweb
654
69.41
JSP - Expression Language (EL) JSP Expression Language (EL) makes it possible to easily access application data stored in JavaBeans components. JSP EL allows you to create expressions both (a) arithmetic and (b) logical. Within a JSP EL expression, you can use integers, floating point numbers, strings, the built-in constants true and false for boolean values, and null. Simple Syntax: Typically, when you specify an attribute value in a JSP tag, you simply use a string. For example: <jsp:setProperty JSP EL allows you to specify an expression for any of these attribute values. A simple syntax for JSP EL is as follows: ${expr} Here expr specifies the expression itself. The most common operators in JSP EL are . and []. These two operators allow you to access various attributes of Java Beans and built-in JSP objects. For example above syntax <jsp:setProperty> tag can be written with an expression like: <jsp:setProperty When the JSP compiler sees the ${} form in an attribute, it generates code to evaluate the expression and substitues the value of expresson. You can also use JSP EL expressions within template text for a tag. For example, the <jsp:text> tag simply inserts its content within the body of a JSP. The following <jsp:text> declaration inserts <h1>Hello JSP!</h1> into the JSP output: <jsp:text> <h1>Hello JSP!</h1> </jsp:text> You can include a JSP EL expression in the body of a <jsp:text> tag (or any other tag) with the same ${} syntax you use for attributes. For example: <jsp:text> Box Perimeter is: ${2*box.width + 2*box.height} </jsp:text> EL expressions can use parentheses to group subexpressions. For example, ${(1 + 2) * 3} equals 9, but ${1 + (2 * 3)} equals 7. To deactivate the evaluation of EL expressions, we specify the isELIgnored attribute of the page directive as below: <%@ page isELIgnored ="true|false" %> The valid values of this attribute are true and false. If it is true, EL expressions are ignored when they appear in static text or tag attributes. If it is false, EL expressions are evaluated by the container. Basic Operators in EL: JSP Expression Language (EL) supports most of the arithmetic and logical operators supported by Java. Below is the list of most frequently used operators: Functions in JSP EL : JSP EL allows you to use functions in expressions as well. These functions must be defined in custom tag libraries. A function usage has the following syntax: ${ns:func(param1, param2, ...)} Where ns is the namespace of the function, func is the name of the function and param1 is the first parameter value. For example, the function fn:length, which is part of the JSTL library can be used as follows to get the the length of a string. ${fn:length("Get my length")} To use a function from any tag library (standard or custom), you must install that library on your server and must include the library in your JSP using <taglib> directive as explained in JSTL chapter. JSP EL Implicit Objects: The JSP expression language supports the following implicit objects: You can use these objects in an expression as if they were variables. Here are few examples which would clear the concept: The pageContext Object: The pageContext object gives you access to the pageContext JSP object. Through the pageContext object, you can access the request object. For example, to access the incoming query string for a request, you can use the expression: ${pageContext.request.queryString} The Scope Objects: The pageScope, requestScope, sessionScope, and applicationScope variables provide access to variables stored at each scope level. For example, If you need to explicitly access the box variable in the application scope, you can access it through the applicationScope variable as applicationScope.box. The param and paramValues Objects: The param and paramValues objects give you access to the parameter values normally available through the request.getParameter and request.getParameterValues methods. For example, to access a parameter named order, use the expression ${param.order} or ${param["order"]}. Following is the example to access a request parameter named username: <%@ page <p>${param["username"]}</p> </div> </body> </html> The param object returns single string values, whereas the paramValues object returns string arrays. header and headerValues Objects: The header and headerValues objects give you access to the header values normally available through the request.getHeader and request.getHeaders methods. For example, to access a header named user-agent, use the expression ${header.user-agent} or ${header["user-agent"]}. Following is the example to access a header parameter named user-agent: <%@ page <p>${header["user-agent"]}</p> </div> </body> </html> This would display something as follows: The header object returns single string values, whereas the headerValues object returns string arrays.
http://www.tutorialspoint.com/cgi-bin/printversion.cgi?tutorial=jsp&file=jsp_expression_language.htm
CC-MAIN-2014-52
refinedweb
785
54.12
UFDC Home | Digital Military Collection myUFDC Home | Florida weekly ( 08-25-2011 ) Item menu Print Send Add Description Standard View MARC View Metadata Usage Statistics All Volumes PDF Downloads Citation Permanent Link: Material Information Title: Florida weekly Place of Publication: Palm Beach Gardens, Florida Publisher: Florida Media Group, LLC Publication Date: 08-25: 08-25-2011.pdf Full Text PAGE 1 A look at the 2011/2012 Kravis season. A31 >>inside: Itzhak Perlman, Larry the Cable Guy among spectacular varietyLAUNCHESKRAVIS20THSEASON ROGER WILLIAMS A2 PUZZLES A32PETS A8BUSINESS A16 LINDA LIPSHUTZ A12REAL ESTATE A21ARTS A23EVENTS A26-27 ANTIQUES A22HEALTHY LIVING A12FILM A28SOCIETY A33 PRSRT STD U.S. POSTAGE PAID FORT MYERS, FL PERMIT NO. 715 An array a day She made daily art from her collections. A23 X INSIDE SocietySee whoÂ’s out and about in Palm Beach County. A33 X Download our FREE App todayAvailable on the iTunes App Store. X WEEK OF AUGUST 25-31, 2011 Vol. I, No. 46  FREE Born to sellChappy Adams is 3rd generation in real estate. A16 XA secret grindChuck Burger Joint offers flavorful burgers, dogs. A35 XTo professionals and skilled workers who have lost their jobs, counselors in the Professional Placement offices of Work-force Alliance in West Palm Beach deliver a tough message: Get over it (the lost job). Get on with it (finding the next one). HOW to get on with it is the trick. In group workshops, in one-on-one and group training and consultation, counselors at Workforce Alliance and career coaches such as Pamela Toussaint echo approaches long promoted by self-helpers. These are homilies and also action steps. ÂTheyÂre time-tested,ÂŽ Ms. Toussaint says. ÂAnd they work.ÂŽ F LAUGHTER IS THE BEST MEDICINE, then the Kravis Center for the Performing Arts may be the place to go for a cure. Comedy is coming up front and center for the arts cen-terÂs 20th season. ÂWe got a lot of feedback from the community that they wanted to see more comedy,ÂŽ said Kravis Center CEO Judy Mitchell. And to that end, count on some of the standards: Jackie Mason will return (Jan. 31, and Dennis Miller will perform With help, jobless can find workSEE JOBLESS, A10 X SEE 20TH, A30 X BY TIM NORRIStnorris@” oridaweekly.com TOUSSAINT BY SCOTT SIMMONSssimmons@” oridaweekly.com << Wanda Sykes, left, and Straight No Chaser, below, come to Kravis this season. COURTESY IMAGES I PAGE 2. FLORIDA WEEKLYA2 NEWS WEEK OF AUGUST 25-31, 2011 ÂWASHINGTON „ The Obama Administration announced Thursday that it would suspend deportation hearings against many illegal immigrants who pose no threat to public safety.ÂŽ For GodÂs sake, what a pack of pusillanimous pansies. The story that led off with this sorry announcement appeared a few days ago in The New York Times, a bastion of the far left, like all media outlets. Left, by the way, derives from the AngloSaxon word Âlyft,ÂŽ meaning weak, and the Latin word sinistra, originally meaning left, but later connoting something sinister and evil, such as a media outlet. So they want to suspend deportation of us? What a regiment of boneheads. They think we shouldnÂt be blamed for the sins of our fathers. Wow, maybe theyÂre Christians. Or maybe they suffer from some similar viral or genetic malady. The sinister pinko who sponsored this legislation, Democratic Sen. Richard Durbin of Illinois, claims that Âthese young people should not be punished for their parents mistakes.ÂŽCan you believe that he and these other lefties actually say stuff like that? ÂShould not be punished for their parents mistakes.ÂŽWhy not? ThatÂs as good a reason to punish them as any, and one of the most common still in use across the planet. Pun-ishing children for what their parents do is the grease that keeps the old wheel turning, isnÂt it? And check this out: ÂThe new policy is expected to help thousands of illegal immi-grants who came to the United States as young children, graduated from high school, and want to go on to college or serve in the armed forces.ÂŽinÂs comment and the rest of the story in the Great Gray Lady (thatÂm not kidding about this, although they do it regularly with no seeming reason). Maybe theyÂd targeted some of those illegal immi-grants. Each other, in other words.The funniest thing about all this is status, ours in particular. Undeniably, weÂre the kings of illegal when it comes to immigration. Me. My neighbors. You. Not those little brown peo-ple from south of the border who do most of the field farming in the region and the state. We (my forbears and yours) didnÂt just sneak in here all meek and mild like they did hoping to find work that no truck-driving, gun-toting, rear-bumper-beef-for-supper advocate of deportation for brown people would be caught dead doing. We weren-conscious determination, along with God, whom we invoked regularly. And we ran right over the top of them. Except for the Seminoles, of course, who fought us to a standstill, and except for that small diversion from 1846 to 1848. ThatÂt kidding around, as time would tell. High casualty counts in the name of illegal immi-grants?Ât respect (except in a fight) any more than we did „ Colo-rado „ the old Mexican border „Ât have a chance against us. Meanwhile back at the Obama ranch, Republican Rep. Lamar Smith, of Formerly Mexico (Texas is what they call it now), denounced the new policy. He calls it Âbackdoor amnesty to illegal immigrants.ÂŽ We just kicked in the front door, after all.And a guy named Roy Beck, described in the Great Lyft Lady as president of Numbers USA, claims itÂs Âa jobs issue.ÂŽ According to him, ÂThe president is taking sides, putting illegal aliens ahead of unemployed Americans.ÂŽ Sure, Roy. ThatÂs why IÂve never driven by a crowded bus lot in Florida counties where farm labor contractors pick up workers and seen a single beefy unemployed Anglo male standing there waiting for a job with the other, albeit newer, illegal immigrants. It couldnÂt be that the older illegals are lazier and whinier than the newer illegals, could it? Q COMMENTARY Our forebears didnÂ’t need backdoor amnesty — just good ammo roger WILLIAMS O rwilliams@floridaweekly umache r SCHUMACHER Dress Di ne & Drive Ev ent Infiniti, SakÂs Fifth Avenue & The Capital Grille partnerTo Give Away a 2-year paid lease on a Infiniti G Series Model. Program r uns from June 20thSept. 8th. See dealer for contest rules and details. 8/31... Â10 Infiniti QX56Low, low milesmust see #Z2360 $43,988Â08 Infiniti EX35Loaded, low milessilver, nice.#Z2287 $25,988 Â08 Infiniti M35Loaded, low milesmust see#Z2321 $28,988Â08 Infiniti G35 Loaded, lowlow miles#Z2365 $25,988 PAGE 4 FLORIDA WEEKLYA4 NEWS WEEK OF AUGUST 25-31, 2011 561.626.9801 € 3370 Burns Road, Suite 206 Palm Beach Gardens Free Varicose Vein Screening Saturday, September 24 9:00 AM TO 12:00 NOONAppointments RequiredCall 626.9801 *THE PATIENT AND ANY OTHER PERSON RESPONSIBLE FOR PAYMENT HAS A RIGHT TO REFUSE TO PAY, CANCEL PAYME NT, OR BE REIMB URSED FOR PAYMENT FOR ANY OTHER SERVICE, EXAMINATION, OR TREATMENT THAT IS PERFORMED AS A RESULT OF AND WITHIN 72 HOURS OF RESPONDING TO THE ADVERTISEMENT FOR THE FREE, DISCOUNTED FEE, OR REDUCED FEE SERVICE, EXAMINATION OR TREATMENT. Dr. Richard S. Faro and Dr. JosephMotta, the Palm Beaches leaders invein and vascular care, will screenfor the presence of varicose veinsand venous disease. Don't miss thisexceptional opportunity to haveboard certified surgeons evaluatethe health of your legs! Board Certified in Vascular Surgery, Thoracic Surgery, Cardiac Surgery & Phlebology PublisherMichelle Nogamnoga@floridaweekly.comEditor & Circulation DirectorBet Maria Marino Linda Lipshutz.com Barry OÂ’Brien bobrien (ÂmudboggingÂŽ). When the gatorÂs owner tracked down the three nearby, they denied the theft and insisted that theirs is an altogeth-er-different 14-foot-long stuffed alli-gator. (WardÂs blood-alcohol reading was 0.40.) When deputies in Monroe County, Tenn., arrested a woman for theft in August, they learned that one of the items stolen was a 150-year-old Vati-can-certified holy relic based on the Veil of Veronica (supposedly used to wipe Jesus face before the crucifixion). The painting had been stolen from the closet of a trailer home on a back road in the Tennessee mountains, where a local named ÂFrosty,ÂŽ age 73, had kept it for 20 years with no idea of its sig-nificance. Q NEWS OF THE WEIRD BY CHUCK SHEPHERDDISTRIBUTED BY UNIVERSAL PRESS SYNDICATEGovernmentin action Of the 1,500 judges who referee disputes as to whether someone qualifies for Social Security disability benefits, David Daugherty of West Virginia is the current soft-touch champion, finding for the claimant about 99 percent of the time (compared to judges overall rate of 60 percent). As The Wall Street Jour-nal reported in May, Judge Daugherty decided many of the cases without hear-ings or with the briefest of questioning, including batches of cases brought by the same lawyer. He criticized his less lenient colleagues, who Âact like itÂs their own damn money weÂre giving away.ÂŽ (A week after the Journal report, Judge Daugherty was placed on leave, pending an investigation.) The Omaha (Neb.) Public School system spent $130,000 of its stimulus grant recently just to buy 8,000 copies of the book ÂThe Cultural Proficiency Journey: Moving Beyond Ethical Barriers Toward Profound School ChangeÂŽ „ that is, one copy for every single employee, from principals to building custodians. Alarmingly, wrote an Omaha World-Her-ald columnist, the book is Âriddled with gobbledygook,ÂŽ Âendless graphs,ÂŽ and such tedium as the Âcultural proficiency continuumÂŽ and discussion of the Âdis-equilibriumÂŽ arising Âdue to the struggle to disengage with past actions associated with unhealthy perspectives.ÂŽ Once hired, almost no federal employee ever leaves. Turnover is so slight that, among the typical causes for workers leaving, Âdeath by natural causesÂŽ is more likely the reason than Âfired for poor job performance.ÂŽ According to a July USA Today report, the federal rate of termination for poor performance is less than one-fifth the private sectorÂs, and the annual retention rate for all fed-eral employees was 99.4 percent (and for white collar and upper-income workers, more than 99.8 percent). Government defenders said the numbers reflect excel-lence in initial recruitment. In January, Alison Murray purchased her first-ever home, in Aberdeen, Scot-land, but was informed in August that she has to relocate, temporarily, because the house has become infested with bats, which cannot be disturbed, under Scot-tish and European law, once they settle in. Conservation officials advised her that she could probably move back in Novem-ber, when the bats leave to hibernate. Q Reverse affirmative action In McGehee, a town of 4,200 in southeastern Arkansas, a black girl (Kym Wimbe rly) who had f inished first in her senior class was named only Âco-ÂŽvaledictorian after officials at McGehee High changed the rules to avoid what one called a potential Âbig mess.ÂŽ As a result, in an ironic twist on Âaffirmative action,ÂŽ the highest-scor-ing white student was elevated to share top honors. Said KymÂs mother, ÂWe (all) know if the tables were turned, there wouldnÂt be a co-valedictorian.ÂŽ In July, the girl filed a lawsuit against the school and the protocol-changing principal. Q (Not so) great artÂs leaf in the other. At a May show at Bogota. Q HitlerÂ’s dollsNews of the Weird has reported on life-sized, anatomically correct dolls manufactured in fine detail with human features (e.g., the ÂReal Doll,ÂŽ as one brand is called), which are as different from the plastic inflatable dolls sold in adult stores as fine whiskey is to $2-a-bottle rotgut. An early progeni-tor of the exquisite dolls, according to new research by Briton Graeme Donald, was Adolf Hitler, who was worried that he was losing more soldiers to vene-real disease than to battlefield injuries, and ordered his police chief, Heinrich Himmler, to oversee development of a meticulously made doll with blonde hair and blue eyes. (However, according to Mr. Donald, the project was stopped in 1942 and all the research lost in the Allies bombing of Dresden, Germany.) Among those who had heard of HitlerÂs earlier interest, according to Mr. Donald, were the creators of what later became the Barbie doll. Q PAGE BECAUSE A HEALTHY SMILE LASTS A LIFETIME!Dr. Christopher Ramsey Dr. Robert Ritter Dr. Isabelle Ritter COMPREHENSIVE DENTAL CARE, INCLUDING GENERAL, RESTORATIVE, AND COSMETIC DENTAL PROCEDURES PAGE 6 $9(18(%_5,9,(5$%($&+)/ 3+ '&/26(#5<%29,&+&20 :::5<%29,&+&20 )XOO6HUYLFH ÂÂiˆ“ˆ>ivii`L>VŽœ“œi annoying whistlingU7œ`>iVÂi>i>`i>ˆiœ understandU>>}iœˆiœ…i>ˆ}ˆ>Vœ`ˆ more natural and not distortedU`>œVÂ…>}ˆ}iˆœ“i\> sounds change, S-Series iQ changesU“œiiiV…ˆiˆ}ˆLˆÂˆˆœˆi S-Series iQ instantly reacts and iœ`>'œ“>ˆV>œ“>'> adjustments needed 12 Months, 0% Financing* Guaranted Best Price! ÂIÂve worn behind-the-ear “t instruments and have never been able to use completelyin-the-canal instruments until now. Starkey S-Series iQ completely-in-the-canal open “t instruments allow me to experience clearer, more natural sounds.ÂŽ Â… Mel Grant, Au.D. $1,000 off ANYPAIROF3r3ERIESI1(EARING)NSTRUMENTS /FFEREXPIRES Made in the USA exclusively from Take Stock in Children, a statewide non-profit organization with a 16-year history of breaking the cycle of poverty by providing scholar-ships, mentors and hope, will present its inaugural ÂStrides For EducationÂŽ 5K Walk/Run around the state to help raise awareness and funds for FloridaÂs low-income and at-risk youth who wish to pursue a college educa-tion. The events will be held on Saturday, Nov. 19.Many of Take Stock in ChildrenÂs ÂStrides For EducationÂŽ 5K Walk/Runs will take place across Florida to benefit local programs in Brevard, Bro-ward, Collier, Escambia, Franklin, Hendry, Immokalee, Lake, Lee, Miami-Dade, Nassau, Palm Beach, Pinel-las, Sarasota and Sumter counties. Take Stock in Children aims to have a few thousand participants statewide as a part of this first-ever fundraising effort, which will raise funds to provide college scholarships for low-income students. With the cost of tuition rising and sig-nificant increases of other college-related expenses, children throughout Florida are struggling more than ever to achieve their dreams of a college education. ÂStrides For Education is more than just a walk, itÂs an opportunity to get the community involved in supporting these students along the path to success,ÂŽ says Richard Berkowitz, State Board Chair of Take Stock in Children. ÂWe are dedicated to preparing our scholars to become the next generation of leaders, and to helping create a better tomorrow for the communities in which we live.ÂŽ Take Stock in ChildrenÂs ÂStrides For Edu-cationÂŽ 5K Walk/Runs are open to all individu-als, families, companies and local organizations, and will feature family friendly activities, give-aways, and much more. Registration is $35 per person, with all proceeds to benefit Take Stock in Children, which current-ly promo-tional materials, as well as displayed in key locations throughout Florida. Sponsors to date include the Helios Education Foundation, Comcast, Berkowitz, Dick, Pollack & Brant and Pollo Tropical.To participate, volunteer or sponsor Take Stock in ChildrenÂs ÂStrides For EducationÂŽ 5K Walk/Run, call (888) 322-4673 or see give.takestockinchildren.org. Q Statewide 5K walk/run to raise college funds PAGE 7 c erti cate will also co ver a prev en tion evalua tion for Medicar e recipients T he patient and an y other person r esponsible for pa yment has the righ t t o r efuse t o pay cancel payment or be reimbursed for any other servic e, e xamination or tr ea tmen t tha t is per formed as a r esult of and within 72 hours of responding to the adver tisement for the free discoun ted fee or r educed fee servic e, examina tion or tr ea tmen t. Expir es 9-24-2011. $150VA L UE $150VA L UE DR. MICHAEL PAPA Chiropractor/Clinic Director BACK TO SCHOOL & SPORTS PHYSICALS JUST $20 FLORIDA WEEKLY WEEK OF AUGUST 25-31, 2011 A7 Working closely with a team of researchers from Duke University, scientists from the Florida campus of The Scripps Research Institute have helped identify a molecular pathway that plays a key role in stress-related damage to the genome, the entirety of an organismÂs hereditary information. The new findings, published in the journal Nature on August 21, could not only explain the development of certain human disorders, they could also offer a potential model for prevention and therapy. While the human mind and body are built to respond to stress „ the well-known Âfight or flightÂŽ response, which lasts only a few minutes and raises heart rate and blood glucose levels „ the response itself can cause significant damage if maintained over long periods of time. When stress becomes chronic, this natural response can lead to a number of disease-related symptoms including peptic ulcers and cardiovascular disorders. To make matters worse, evidence indicates that chronic stress eventually leads to DNA damage, which in turn can result in various neuropsychiatric conditions, miscarriages, cancer, and even aging itself. Until the new study, however, exactly how chronic stress wreaks havoc on DNA was basically unknown. ÂPrecisely how chronic stress leads to DNA damage is not fully understood,ÂŽ said Derek Duckett, associate scientific direc-tor of the Translational Research Institute at Scripps Florida. ÂOur research now outlines a novel mechanism highlighting b-arrestin-1 as an important player.ÂŽ The long-term effects of these stress hormones on DNA damage identified in the study represent a conceptual as well as a tangible advance, according to Robert J. Lefkowitz, a Duke University professor of medicine who led the study. Since stress is not time limited and can be sustained over months or even years, it is well appreciated that persistent stress may have adverse effects. The newly uncovered mechanism involves -arrestin-1 proteins, 2-adrenore-ceptors (2ARs), and the catecholamines, the classic fight-or-flight hormones released during times of stress„adrena-line, noradrenaline, and dopamine. Arres-tin proteins are involved in modifying the cellÂs response to neurotransmitters, hor-mones, and sensory signals; adrenoceptors respond to the Catecholamine noradrena-line and adrenaline. Under stress, the hormone adrenaline stimulates 2ARs expressed throughout the body, including sex cells and embryos. Through a series of complex chemical reactions, the activated receptors recruit -arrestin-1, creating a signaling pathway that leads to catecholamine-induced deg-radation of the tumor suppressor protein p53, sometimes described as Âthe guardian of the genome.ÂŽ The findings also suggest that this degradation of p53 leads to chromosome rear-rangement and a build-up of DNA damage both in normal and sex cells. These types of abnormalities are the primary cause of miscarriages, congenital defects, and men-tal retardation, the study noted. Q Scripps scientists pinpoint cause of stress-related DNA damageDUCKETT PAGE 8 FLORIDA WEEKLYA8 NEWS WEEK OF AUGUST 25-31, 2011 lem. This is especially true if the behavior change is sudden. If you start trying to retrain a pet whoÂs sick, not only will you get nowhere, but youÂll also delay the resolution of the condi-tion that may be causing your pet discom-fort or pain.ItÂs important to know whatÂs normal for your pet and to look for small changes in appearance or behavior that could be the early signs of illness, even before they prompt annoying behavior problems. ItÂs important to always keep an eye on your petÂs overall condition, for example, being careful to note a loss in weight, a newfound dullness to his coat or a change in energy levels. Changes in eating and elimination habits are also worthy of investigation, as are subtle shifts in temperament „ such as a pet who seems a little more aloof or more clingy.Double your vigilance when your pet crosses into the senior years. Many of the problems pet lovers assume are just part of the aging process „ stiff joints or absentmindedness „ can be treated, with both traditional and alternative methods available. Such treatments can vastly improve your aging petÂs quality of life, and yours as well, since you wonÂt be dealing with the accompanying behavior problems. If youÂre already dealing with unwanted behavior, call your veterinarian first, because pun-ishing a sick pet isnÂt fair, and it wonÂt fix a thing. Q When a good pet goes bad, illness may be the problembehavior changes in a cat whose body is suddenly supercharged. That snapping dog? A painful ear infection may be the culprit, or perhaps joint pain. The fact that sheÂs snapping when petted, not biting, speaks volumes about her good temperament, despite her extreme pain. And what about the cat whose perfect potty habits are suddenly gone? His case could have any number of medical causes behind it, from an infection or kidney dis-ease to diabetes. With good medical care, all three of these pets will likely be made healthy and should be able to be well-mannered pets again. Cases such as these make clear why the first rule of solving any behavior problem is to make sure that itÂs not a medical probSome of the saddest emails I get are from people who are punishing or even contemplating ending the lives of formerly well-mannered pets with new behavior problems. So many of these pet lovers chalk up the changes to ÂspiteÂŽ or some other off-beat reason while missing the most obvious reason of all: Their pet is sick. Some everyday examples: „ An 8-year-old cat who has always been pretty relaxed suddenly starts zoom-ing around, knocking things off tables and using claws in play.„ A 9-year-old collie mix who has always been trustworthy and happy suddenly starts snapping when being petted. „ A 6-year-old cat suddenly starts missing the litter box, even though there has been no change in the location, filler or cleanliness. People often look for one simple training tip that will bring back the problem-free relationship they had with their animal companions. But sometimes, what pet lov-ers assume is a behavioral problem, really isnÂt „ itÂs a medical problem; one that will be resolved only with proper diagnosis and treatment. That zooming cat? ThereÂs a pretty good chance she has a condition called hyper-thyroidism, in which the thyroid gland overproduces, and in so doing prompts PET TALES Too sick to be good When an older dog starts reacting poorly to being awakened, there could be several medical issues in play.BY GINA SPADAFORI _______________________________Special to Florida Weekly O Pets of the WeekTo adopt a pet„ The Peggy Adams Animal Rescue League Humane Society of the Palm Beaches, was founded in 1925 and is a limited ad-mission non-pro t humane society providing services to more than 10,000 animals each year. It is located at 3100/3200 Military Trail in West Palm Beach. Adoptable pets and other information can be seen at hspb.org. For adop-tion information call 686-6656.>> Marcie is an 8-year-old spayed female Red Harrier mix. She has had a tough life, but is easy going and enjoys being petted. She doesn't like people around when she's eating. She weighs 62 pounds and is eligible for the Senior to Senior adoption program; anyone 55 or older does not pay an adoption fee. >> Hey is a 9-month-old spayed tuxedo female shorthair. She is playful, active and loving. The Friends of Mounts Botanical Garden will soon be hosting one of its most popular annual events „ ÂEverything Orchids; A Shady Affair Plant Sale.ÂŽ ItÂs Sept. 10 and 11 from 10 a.m. to 4 p.m. And on Sept. 10 there will be a ribbon-cutting dedication of the remod-eled bridge and overlook to the Zim-merman Shade and Color Garden on the Island of the Mounts. Members get in free and cost for non-members is $5 for the weekend event that showcases a select number of top orchid and shade plant growers, artists, and craftspeople that will share their knowledge and passion for orchids and plants. The event features informative lectures and a silent auction of horticultural tabletop arrangements. The dedication and ribbon cutting is Saturday from 3 p.m. to 5 p.m. Art-ist Mark Fuller will be on hand, and hors dÂoeuvres, beverages and cake will be served in honor of the 60th birthday of Michael Zimmerman, the longtime president of Friends of Mounts Botanical Garden. RSVPs are requested at 233-1757.Orchid event, plant sale weekend set at Mounts Botanical GardenCOURTESY PHOTO A ribbon-cutting for a remodeled bridge at Mounts Botanical Gardens is set for Sept. 10.SPECIAL TO FLORIDA WEEKLYMounts Botanical Garden is Palm Beach CountyÂs oldest and largest public garden. Mounts displays tropi-cal and subtropical plants from around the world, including plants native to Florida, exotic trees, tropical fruit, herbs, citrus, palms and more. As a component of the Palm Beach County Cooperative Extension Service, and through its affiliation with the Uni-versity of Florida IFAS, Mounts is the place to connect with Extension Horticulturists, Master Gardeners, the Florida Yards and Neighborhoods Pro-gram, and professional horticultural advisors. Mounts also offers a variety of horticultural classes, and garden-related events and workshops. Located at 531 North Military Trail in West Palm Beach, Mounts is open Monday-Saturday from 8:30 a.m. to 4 p.m. and Sunday from noon to 4 p.m. The suggested donation for entry to the Garden is $5 per person. For more information, call 233-1757 or visit. Q PAGE 9 FLORIDA WEEKLY WEEK OF AUGUST 25-31, 2011 A9 A partnership between Jupiter Medical Center and NuVista Living is expected to create 150 new jobs, the companies said. The joint venture will make the hospital a partner in NuVistaÂs Institute for Healthy Living, Life Science and Research, a con-tinuing care senior center being built in Abacoa. The institute, a $70 million project expected to open in the spring of 2013, will have a positive economic impact for northern Palm Beach County, both during construction and long-term, according to NuVista CEO Paul Walczak. Plans call for 150 net new permanent jobs out of a total work force of 200 posi-tions. At completion, the institute is pro-jected to generate a net annually recurring economic impact of $20 million rippling throughout the community. According to a news release, the new community will focus will focus on enhancing patients quality of life while improving care outc omes. By expanding Jupiter Medical CenterÂs and NuVista LivingÂs existing relation-ships with Scripps Florida and Florida Atlantic University, the institute will fos-ter collaboration in care, education and research. In addition to 129 nursing home beds, new institute will include a dedicated 70-bed assisted living center and a 30-bed unit for residents with AlzheimerÂs and other memory disorders. The hospital, which provides long-term nursing care and rehabilitation at its 120-bed Pavilion facility, does not currently offer care to patients with AlzheimerÂs and other memory disorders. As part of the joint venture, Jupiter Medical Center will transfer the Certifi-cate of Need for 60 long-term nursing care beds at The Pavilion to the Institute for Healthy Living, Life Science and Research for the new Abacoa facility and the insti-tuteÂs future use, Jupit er Medical Center CEO John Couris said. Meeting long-term care needs through the institute will enable the hospital to transition the Pavilion to provide only rehabilitation services that are tied to spe-cific clinical service lines. Jupiter Medical Center will continue to own and operate the Pavilion as a rehabilitation center, with 60 private rooms. The 35-year-old facility will undergo a renovation. In other news, Jupiter Medical Center also has broken ground on the Raso Edu-cation Center. The two-story building will offer educational space for the hospitalÂs 1,500 staff members and 540 physicians, and will host the community for health-care lectures and events. Q Jupiter Medical Center, NuVista Living announce $70 million project COURTESY PHOTOJohn Couris, CEO of Jupiter Medical Center, left, and Paul Walczak, CEO of NuVista Living, an-nounce a joint venture between the providers. PAGE 10 FLORIDA WEEKLYA10 NEWS WEEK OF AUGUST 25-31, 2011 If they worked like a charm for everyone, of course, weÂd all be working. Any-one wedded to statistics might wonder why more and more Americans are out of work longer and longer. Advising someone else about landing a job, counselors acknowledge, or about any aspect of living, is easier than step-ping into his or her shoes and going through it. In ÂBait and Switch,ÂŽ an account of her experiences looking for professional work, Barbara Ehrenreich tells of pay-ing for coaches, traveling to Ânetwork-ing occasions and executive job-search training sessions,ÂŽ undergoing a physi-cal make-over and efforts to reshape her personality to fit the preferences of employers. She offers these words of caution about what she calls Âthe transi-tion industryÂŽ aimed at the white-collar, middle-class and professional jobless: ÂWhen the unemployed...reach out for human help and solidarity, the hands that reach back to them all-too-often clutch and grab.ÂŽ Much of the advice, in fact, seems to belittle and reduce, based on the idea that we are products and need to pitch ourselves as such. Packaging becomes appearance and tone. Fifteen-second commercials become Âillustrative storiesÂŽ about what we can do. We are reduced to what we have to offer to the people in charge. Judy Dunn and Mike McLaren and their co-workers at Workforce Alliance say they understand the skepticism. We live, though, they say, in a first-take, quick-serve, bottom-line world, where quick action and a positive approach get results. Take a glance at other books, ÂThe Seven Habits of Highly Successful People,ÂŽ or updated versions of ÂWhat Color is Your Parachute?ÂŽ Try these things, they say, and look at the differ-ence they make. Everyone interviewed for this series, to a person, applauds Workforce Alliance and praises various counselors there. ÂI think they do a really nice job,ÂŽ Chet Zawadzki says. ÂIÂve been working with them since March or so. I wish I had found them earlier.ÂŽ Debbie Wemyss adds, ÂEvery once in awhile I hit my threshold, and thatÂs when I pick up the phone and I call Judy, say ÂI need five minutes of your time. I need to vent, please.ÂŽ A few hours later sheÂll call back and say, ÂOK, IÂm ready, I have my soda. Let me have it. SheÂs great about it, and I respect her time so I keep it short. SheÂs very skilled. I canÂt speak highly enough about her and Martha Sanchez and the other people at Workforce Alliance.ÂŽ Some of the jobless, looking elsewhere, also have stories of shysters, charging money just to register or taking a slice of income afterward. The solution, they dis-cover, starts and ends with themselves. HereÂs a sampling of Workforce AllianceÂs and Ms. ToussaintÂs time-tested counsel: Q Work through anger and loss and move on. Communing with family and friends, going for counseling, sharing stories with other job-hunters, finding a positive, forward-looking focus, good diet and even regular exercise can help. Keep to a daily routine, as you did when working. ÂIf youÂre in shorts and a T-shirt, youÂre not in job mode,ÂŽ Judy Dunn says. ÂYou have to put on the shirt and the pants or the dress, how you go to work, and it changes your mind-set.ÂŽ Q Do not watch the news. ÂCatch up, if you must,ÂŽ Ms. Dunn says, Âbut donÂt watch in the morning and then at noon and then at 5 and then at 11. Do not do that. You will sink.ÂŽ Q Take a self-inventory. ÂWhat really makes you happy?ÂŽ Ms. Dunn says. ÂMake a list, very elementary, likes and dislikes. Is it a sport? Is it sitting outside reading books? What do you dislike? Some folks canÂt sit in a cubicle all day. Some canÂt be out on the road; they donÂt want to travel. When youÂre looking at the oppor-tunities, based on education and skill set, where is most of your day going to spent? So this could be a great job and itÂs my top five likes, but itÂs also my first and second dislike. ItÂs not a good job for you.ÂŽ Q Collect a job-hunting network of acquaintances, friends and former co-workers. ÂItÂs all about relationships,ÂŽ Pamela Toussaint says. ÂRelationships are going to make or break your job search. YouÂve got to be a people-person.ÂŽ Q Attend public job and career fairs and workshops. ÂYou go early,ÂŽ Ms. Tous-saint says. You have your freshly printed business cards, walk around and meet people, exchange cards, go on LinkedIn, invite them to join the network.ÂŽ Q Volunteer. ÂEverybody has a skill, has a gift,ÂŽ Ms Toussaint says. ÂThere are JOBLESSFrom page 1 EVEN A CASUAL LISTENER CAN HEAR THE tug-of-war in Elena OliveriÂs voice. One minute, she says, ÂBeing out of work, my life has changed dramatically. Things break down in the house, and you think to yourself, how am I going to replace that? Things you didnÂt think twice about five years ago. Like the coffee maker goes, or my watch broke. Now I have to think twice about discre-tionary spending.ÂŽ Then her tone changes, her face brightens. ÂI know IÂm good, that I have to keep getting out there,ÂŽ she says. ÂYou canÂt live in the past. What IÂm excellent at is producing marketing pro-grams. I need to find a place for that, in something I can believe in.ÂŽ For nearly all who are out of work, the immediate and long-term outlook can teeter between hopeful and despairing. As rejections mount, they become dis-couraged. The trick, as they try to push uphill while fighting the slide backward, is how to find their footing. Nobody likes doubt in an interview. Living for the moment in West Palm Beach, Ms. Oliveri faces the added chal-lenge of being relatively new in town. Her networks, she says, are in New York City, where she worked in advertising for McCann Erickson, a major glob-al advertising firm, and in San Diego, where she worked in non-profit mar-keting for the San Diego Center for Children and Scripps Health Founda-tion and directed self-empowerment seminars for Landmark Education. ÂNew York work was at the beginning of my career,ÂŽ she says. ÂAdvertis-ing is for the young people.ÂŽ But sell-ing something she believes in, she says, taps her youthful energy. After she moved to Florida two years ago, she worked as a contractor in marketing at Florida Power & Light, until her contract ended in January. ÂAs much as they loved me, they canÂt add to staff right now,ÂŽ she says. Her search, as for so many looking for new work, is not only for a regular pay-check and decent healthcare but also for who she is, for what she does best and cares about most, and for a job that fits. For meaningful work. In a down economy, in any economy, some see that idea as self-indulgence. Take the best work you can get, they say, and grind it out while youÂre looking. Employers and their HR staffs, though, can usually read a short-term outlook. Ms. Oliveri has the wisdom of more than 20 years in the professional world, and she says that those who take jobs that donÂt fit just for a paycheck are actually costing their employers and co-workers money and energy. Another issue is faking „ or, at least, shortening „ rsums. Profes-sional workers, seeking paychecks in retail or clerical work, learn that they need to hide their credentials, stow any reference to their hard-fought college degrees, their executive or managerial experience, their higher salaries. With the full rsum, nothing. Going short, they get play. Ms. Oliveri just wants back in, back into good work for decent money and something with a future. Even without healthcare, she says, contract work is OK, as long as you know how long the contract will last. Maybe, she acknowledges, most Florida employers are up-against-it, too Just now, sheÂs reshuffling herself. She grew up in New Jersey, the New York suburbs, and marketing took her to California. Her voice strengthens as she talks about volunteer work she did in San Diego, training children to believe in themselves. She strives, she says, for that same opportunity to contribute in her next job. She admits that, at moments, she wonders what would happen if there isnÂt a next job. ÂI do fine by myself,ÂŽ she says. ÂI keep busy. But, although IÂm older, IÂm still mentally young at heart. IÂm not ready for a sedentary lifestyle.ÂŽ Her latest business card, under her name in a box against a line of stripes, starts with ÂMarketing € Administration € Non-Profit.ÂŽ Phone, e-mail, and online LinkedIn address follow. Below, she adds ÂExceeding Expectations at Every Opportunity.ÂŽ Employers may not ask about age, on penalty of discrimination charges, but in many places age is the invisible and unspoken elephant in the room. Some dodge it with physical requirements, though many in the fitness-conscious Â60s-Â70s generation can still meet them. Many use skill with computer software applications as a stumbling block. Most say nothing. Elena Oliveri would love to work in fund-raising and marketing and she has tested the waters in education and the arts. More than anything, she wants to contribute, and to be paid a fair wage for doing it. As for networking, she says, thatÂs also a challenge these days. ÂPeople donÂt want to take a chance,ÂŽ she says. ÂColleagues donÂt want to risk their reputations promoting you. The most they will do is say, ÂWell, IÂll give your rsum to someone, a friend. You donÂt even get the name of the friend, so you can follow up. ItÂs very difficult. They tell us at Workforce (Alliance) to get the name and the number of people, then call them directly. You call and say, ÂIÂll buy you coffee. Well, they donÂt have time. You just wonder, ÂWasnÂt there somebody who helped YOU out? ÂSo IÂm looking at volunteering in the arts.ÂŽ She knows itÂs a long-shot, she says, and adds, ÂYou still have to go with the game you know.ÂŽ Even, she acknowledges, when youÂre standing on the sidelines, on your toes, waiting for the call. Q ÂWasnÂt there somebody who helped you?ÂELENA OLIVERIÂ’S STORY BY TIM NORRIStnorris@” oridaweekly.com OLIVERI “They tell us at Workforce (Alliance) to get the name and the number of people, then call them directly. You call and say, ‘IÂ’ll buy you coffee.Â’ Well, they donÂ’t have time. You just wonder, ‘WasnÂ’t there somebody who helped YOU out?’” PAGE 11 FLORIDA WEEKLY WEEK OF AUGUST 25-31, 2011 NEWS A11 THE SURPRISE WITH CHET ZAWADZKI OF Abacoa, Town of Jupiter, isnÂt how he lost his job. Familiar story: smaller, family-owned company taken over by a bigger one, then the parent corporation expands. The com-pany culture changes, costs and jobs are cut, the old guard is out the door. The surprise is WHO he was and what he was doing when he lost it. Mr. Zawadzki is an IT guy, a computer expert who started programming with stacks of punch cards and steeped himself in every electronic advance, a seasoned expert in Internet tech-nology. HeÂs been respected by co-workers, cordial, cooperative, a go-to utility man, a director, a manager, a team player. He signed on in 1991 as IT manager with a Laramie Tire Distributors, in Norristown, Pa. Five years later, Laramie and several similar companies were bought by Tread-ways Corp., the U.S. tire distribution arm of Sumitomo Corp. of Japan, and they brought Mr. Zawadzki along as director of informa-tion technology. ÂIt was actually one of the best companies IÂve worked for in my life,ÂŽ he says. ÂThe company itself was run by a core group of smart, savvy people, and our Japanese parent brought in a lot of excellent business practices and metrics. It was fun to work there.ÂŽ Then, in 2008, Sumatoma tucked that subsidiary into newly acquired TBC Corp., based in Palm Beach Gardens. When the larger company moved him from Pennsyl-vania to Florida, Mr. Zawadzki saw it as a step up. His wife, Diane, gave up a well-paying human services job to join him. ÂThe expectation was that we would come down here and, after a couple of years, Diane would retire,ÂŽ he says. ÂIÂd work as long as I wanted.ÂŽ Midway through 2010, out of the blue, he was told they were eliminating his job. ÂItÂs traumatic,ÂŽ he says. ÂI grew up in Bridesburg in northeast Philadelphia, a blue-collar neighborhood, factories, and in my family you worked. I donÂt think I knew of anyone who didnÂt. My father was a chemical worker at Roman-Haas, and he worked there from when he came back from the Second World War until he retired in 1978. If you were out of work, that was a source of shame.ÂŽ After the ax fell, Mr. Zawadzki stayed with TBC another 30 days to ease the transition. ÂLook, I understand that things change,ÂŽ he says. ÂTreadways treated its people very, very well. When we came down here, I understood that TBC was going through a lot of turmoil. I think that if Sumitomo hadnÂt taken over, they might have gone bankrupt. Their technology was old. Their existing processes were inad-equate to handle the growth that they were taking on. I was excited to come down and help in their effort to upgrade and prepare them to move forward.ÂŽ Internet and telecommunications, the digital realm, might seem humming with prospects. Mr. ZawadzkiÂs friends thought heÂd land a new job in a few weeks, a couple of months at most. The cutting edge, he discovered, can cut both ways. ÂIT has changed so dramatically,ÂŽ he says. ÂThese days IT is all about certifications on the technical level, and, for my money, the technology changes too fast for you to keep up with the certifications. There are too many certification groups, certifying the same skill sets. You see peo-ple paying thousands of dollars for certifi-cations that will need to be upgraded (for more money) in two years or be rendered obsolete. Also, if your company doesnÂt stay current with new technology, youÂre at a disadvantage because your skills will atrophy. Many companies donÂt, or wonÂt, train anymore; they just replace workers with new employees who have taken certi-fication courses.ÂŽ Mr. Zawadzki lost his job a year ago. At age 62 heÂs still out of work. That brings training into play to keep up-to-date, and with it come institutions, public and private, offering courses for profit. Chet Zawadzki knows plenty about that, too. In Penn-sylv ania, he once worked as director of a proprietary school in information technol-ogy called Computer Learning Center. ÂWe were accredited by the Penn sylv ania State Board of Private Licensed Schools and audited on a consistent basis, but a lot of the ads and schools I see down here seem so incredibly shaky,ÂŽ he says. ÂMany of the ads I see seem to prey on the poor, the unedu-cated, and on older workers. I donÂt recall seeing as much of this up North. Down here it seems like a cottage industry.ÂŽ He has seen a sea-change, too, in finding and applying for job openings. ÂIf youÂve gone out to many company and career web sites,ÂŽ he says, Âeverything is driven by HR recruitment software. Now, donÂt misunderstand me. I like information technology. IÂm an advocate of it. IÂm com-fortable with it. But the tools that are out there...itÂs almost maddening. I feel sorry for anyone using these tools, because on each of the different sites you have to create your resume. Sometimes you can upload, but not often, and they all want you to do their own individual process. You spend more time working with the software, and itÂs all slightly different; some of its quirky, some of itÂs not implemented correctly; you fill something out and it doesnÂt do any-thing, it doesnÂt come back with an error message, youÂre often not quite sure if it made it to its destination. ÂHow often do I hear back? Almost never.ÂŽ He is ready, he says, to move into supply chain management, where he can use his long experience in distribution. In the job hunt, resources and attitude become crucial. Mr. Zawadzki affirms that he is luckier than many. Diane, working for the Veterans Administration, he says, mostly enjoys her job. ÂWeÂve been together for 23 years, and we understand the circumstances, traumat-ic as they may be, and donÂt take it out on each other,ÂŽ he says. ÂWeÂve been fortunate because weÂve saved a lot, so thereÂs less pressure on the financial front. But, still, weÂve lost a significant income over the last year. And we may have to relocate again.ÂŽ Their support system includes Dakota, nickname Buddy, an 11-year-old yellow Lab-rador retriever he and his wife adopted a year and a half ago from Safe Harbor. ÂWe picked a senior dog because, the poor guy, it was like nobody wanted him,ÂŽ Mr. Zawadzki says. ÂHeÂd been there awhile, and he was really kind of shell-shocked by the experience. HeÂs the sweetest dog. He loves me being out of work. More walks! ÂMe? I need to work. IÂm getting sick of my own cooking.ÂŽ Q ÂHow often do I hear back? Almost neverÂCHET ZAWADZKIÂ’S STORYpeople out there who need help and canÂt pay for it. YouÂre gonna meet somebody else out there whoÂs of like mind. They may work for a company that youÂre try-ing to get into, so think of volunteering as another way to expand your network.ÂŽ Q Create a rsum that shows what you can do, with pointed examples. Q Target and research potential employers. ÂItÂs not about throwing 50 rsums out there,ÂŽ Judy Dunn says. ÂItÂs about targeting the right company. What do I want to be when I grow up? WhatÂs the next venture in my life?ÂŽ Q Tailor your rsum to each potential employer. Read the job description in detail, match the fit against key words and, if itÂs right, use those words in your rsum and cover letter. ÂGenerally, what an employer puts in the first few sentences of a job description is whatÂs most important to them,ÂŽ Ms. Dunn says. ÂIf you havenÂt addressed that, up front, youÂre gonna miss out. In this market today, if your key words are not in the top two-thirds of the page, the (Human Resources) computer will actually elimi-nate you.ÂŽ Q Build and sustain your brand. Spurred by online multi-media, self-image and packaging have become part of personal presentation. Be true to yourself, but also consider putting your best self forward. Q Online isnÂt the answer. Get off your duff. ÂThe reality is, itÂs still only 5 per-cent are finding their jobs on the Internet, OK?ÂŽ Judy Dunn says. ÂEighty percent are getting out there. Networking is still the number one way, period.ÂŽ Q Hand out a business card. Include your basic contact information and a title that expresses your strengths. ÂBusiness cards are free,ÂŽ Ms. Toussaint says. ÂYou can make your own on Word, print it off at the library. Or go on Vistaprint.com, $9.99 for 200.ÂŽ Q In the interview, listen carefully, be positive and honest but not self-indul-gent or confessional, show your inter-est. ÂEmployers are going to hire people they like, period,ÂŽ Ms. Dunn says. ÂHave a smile on your face, shoulders back, head up. ItÂs not the person with the most talent or the best education. ItÂs the person who fits in their culture. You still have to be the one they like.ÂŽ You also, she adds, need to decide whether you like THEM. Q Develop a number of short, crisp stories to illustrate your work experience. ÂIt is so much more powerful when you can give examples from your past,ÂŽ Pamela Toussaint says, Âbecause what are the hiring managers trying to decipher? How youÂre going to help them solve their problems, right?ÂŽ Q Ask questions. Show youÂve done your homework by asking specific things about the company and its culture. ÂAnd, afterward,ÂŽ Ms. Dunn says, Âyou need to ask, ÂHow do you like to communicate? May I have one of your business cards, and I see you have a phone and an e-mail, which way do you prefer to communi-cate? Why not ask? ÂIÂd like to follow up with you, is it OK if I call in a week? In a day? If I donÂt know when theyÂre mak-ing that decision, how do I know when to follow up?ÂŽ Q DonÂt underestimate the receptionist. ÂSome companies are watching you from the moment you arrive in the park-ing lot,ÂŽ Ms. Toussaint says. ÂWhen youÂre sitting in the foyer or the open area, theyÂre watching you. If youÂre sitting here texting your friends or talking on the phone, or disengaged with whatÂs going on around you, thatÂs a huge red flag to companies. TheyÂre going to come out and ask that receptionist, how was this person acting? What were they doing? What do you think? Remember, whoÂs the most powerful person in a company? The receptionist.ÂŽ Q Send a thank-you note ÂYou have an interview at 4 this afternoon?ÂŽ Ms. Toussaint says. ÂBy the open of business tomorrow you should have a thank-you note out to them. ItÂs nice to have a hand-written note in the mail to them, but you should also have a quick e-mail.ÂŽ Q When turned down, donÂt take it personally. Refer to step one. Q Keep moving ahead. ÂTrouble letting go of the old dreams.... I see that every day,ÂŽ Judy Dunn says. ÂIt takes some folks a couple of months; some folks are three years in and theyÂre still waiting for some-thing to come back. WeÂre going forward, as a society. Even if every computer on the planet crashed and burned, someone would figure out a way to get them back up. WeÂre not going back. Be realistic and move forward.ÂŽ Amid the job-killing ravages of the current economy, counselors acknowledge, no one is immune. Judy DunnÂs husband, she says, has been looking for work for more than a year. Her sympathy and partnership might help, but even her wise counsel canÂt overhaul the economy or its politics. He has, she knows, nearly 10 million men and women sharing the hard-ribbed boat. Q BY TIM NORRIStnorris@” oridaweekly.com ZAWADZKI PAGE 12 FLORIDA WEEKLYA12 NEWS WEEK OF AUGUST 25-31, 2011 Todd knew he was in for it when he saw his motherÂs car in the driveway. It was wishful thinking to believe he would come home to some peace and quiet. Predictably, Rachel was at the front door in tears. ÂYour mother is driving me up the wall. Today, she had the nerve to instruct me on the best way to burp Jonah. Does she think IÂm a total idiot? Is she the only woman who ever had a baby? Will she ever take a hint and figure out when itÂs time to go home?ÂŽ When Jonah was first born, Todd had found it reassuring to know that both sets of parents were nearby should they need some help. Rachel had taken an indefinite leave from work and had been looking forward to settling in with the baby. Dur-ing their engagement, Rachel and his mom had gone through some rough spots. His mother could be a know-it-all and a bit pushy, but heÂd been impressed by RachelÂs warmth and diplomacy in planning the wedding. She seemed to know just how to handle his mother. He had hoped a new baby would draw everyone closer. What he didnÂt anticipate was how frequently his mother would Âdrop byÂŽ and how long she would stay. DidnÂt she have a life? But, worse than that was his motherÂs bossiness and the way she tried to take over. Rachel was becoming increasingly resentful, and would pick a fight with Todd as if it were his fault that his mother had over-stepped her bounds. Todd had asked his father to intervene but that turned out to be a disaster. His mother was incensed Todd had gone behind her back and blamed Rachel for instigating trouble. She left the house in a huff, saying she had never felt so unwelcome and unappreciated in her life. The tension was unbearable. As much as the birth of a child may bring closeness and joy to the extended family, the relationships may become overbur-dened by the simultaneous challenge of making the necessary accommodations. Hormonal explosions and sleep depriva-tion compromise the young mother as she taxes herself to demonstrate she can master the awesome new responsibilities. With expectations of herself that are often unrealistic, she may feel demoralized when things donÂt go as she envisioned. If she had been working, she may now be adjust-ing to a stay-at-home routine, without the camaraderie of co-workers and a regular work structure. Time spent with family members, previously limited by demand-ing schedules, may now be open-ended. Throughout their courtship and engagement, young couples often learn a lot about each otherÂs upbringing and begin a give and take process of spelling out the place their extended families will have in their everyday lives. All the parties, by now, have sized up each otherÂs positive attributes or personality quirks and have established relationships with each other, for better or worse. Young couples have faced the chal-lenge of determining how much they will be influenced by their families values and belief systems. Unresolved hostilities and differences that may have emerged during the courtship and wedding planning will likely be heightened after the baby arrives, as the families juggle to balance the right mix of involvement. The birth of a child ups the ante as the young couple faces the arduous task of asserting separateness and independence from their parents. As they shift their attention to the needs of the child, they may neglect to give their own relationship special care. ItÂs not uncommon for a hus-band or wife to believe that their needs are no longer being considered and that their spouse is being neglectful or unsupportive. When this happens, it wonÂt take much for little things to deteriorate to arguments. It will be helpful to have heart-to-heart discussions, not only about the amount of time they would like to spend with their families, but also about how much of their personal business they are comfortable sharing. For example, Todd might prefer to spend Sundays alone as a private family day. Rachel may argue that her family has traditionally shared Sunday dinners and she does not want to give this up. Rachel may have the additional task of determining how much family visiting time during the day will be the right fit. Although Todd may be at work, (so it is ÂtechnicallyÂŽ not his issue,) he can offer tremendous support to Rachel if he offers to broach important topics to his family with her. Rachel may be feeling defensive, believing Todd is disappointed in how she has been relating to his family. It may help if he reminds her that he was so proud of how she handled conflicts during the engagement and that he will support her now when family issues come up. The way the couple speaks to each other and their parents may impact the com-fort of these relationships going forward. Clearly and firmly stating (if possible, with love and consideration) the kind of give and take they would like to have in the relationships will be helpful. Sometimes, the parties are so worried about offending each other that they couch their words and misrepresent what they truly mean. Be prepared to have misunderstandings if you say: ÂFeel free to visit any time.ÂŽ Much better to say: ÂIÂd love it if you could drop over on Monday or Tuesday for a couple of hours in the afternoon. Does that work?ÂŽ This enables Rachel to have better control over the rest of her life, so she can feel free to take care of business or plan visits with friends, or to rest when the baby naps. When their parents are loving and seemingly well intended, the couple may feel ungrateful if they try to set boundaries. What they really want to say is: ÂWe love you, we want you in our lives, but we need our own space and we want the freedom to parent our child our way.ÂŽ It will be important for the older folks to remind themselves that the young parents are test-driving stressful new responsi-bilities and may not always show tact and diplomacy. It would help for them to pay attention to the impact of their visits and advice, regularly checking to make sure they have not over-stepped their bounds. Each set of grandparents may feel further slighted or insecure if it appears that the young couple is favoring the involve-ment of the ÂotherÂŽ family. All the parties may worry that their efforts may be misunderstood and blown out of proportion. Just as concerning, sen-sitivities may deteriorate to arguments about petty non-issues. Will this couple be able to push through the discomfort of stating a message that may not be well received, and can the extended family rela-tionships thrive when there is straightfor-ward clarification? If the young husband and wife bond together with a clear mes-sage to the others it should head off a lot of confusion and conflict, because there will be a unified feeling of support. If both generations could only remember that everyone has each otherÂs best interests at heart, but that they are not going to get it right without a lot of con-sideration and clarity, they will be taking important steps to support all the parties in enjoying what can be a very special time in their lives. Q HEALTHY LIVING u linda LIPSHUTZ O llipshutz@floridaweekly.comGrandparents: DonÂ’t overstep when that new baby arrivesOver the past few weeks, there has been little good news to take to bed with sweet dreams in mind. Being an eternal opti-mist, pessimism does not come naturally. Having spent 10 years in Mississippi, you learn that dwelling on an endless supply of deficits does not create a climate of hope. The burdens borne in that state by history and inheritance are deep still, no matter that it is the 21st century and civilized society is supposed to have fully arrived. Regrettably, there and elsewhere, civility has not risen to the plane of us living and getting along together just fine. Having yet again thought and voiced this gloom only illustrates that desultory thinking is a cul-de-sac from which escape is dif-ficult „ which got me to thinking about our need for good news. Recently, I watched on YouTube a short video clip of the release of ÂAndre,ÂŽ a sea turtle that underwent a long rehabilitation at the Juno-based Loggerhead Marine Life Center. Our staff met there in July to do some future year planning. The place was abuzz with kids and filled with the energy of doing something worthy and measure-able, one turtle at a time. What stirs the heart about this place is the sum of all the center represents to our region, oceans and marine life. Having had the opportunity to encoun-ter this deep sea creature on the eve of its release, I found myself, tears welling up, watching the video of AndreÂs trundle off into the ocean. I felt the same ripple of joy of those on the beach who cheered and applauded. After-wards, I thought sheepishly to myself that things must really be bad when all it takes is a turtleÂs release to provoke weep-ing. Something stirred that hadnÂt been touched in too long a time „ a moment made poignant by the recognition that something is inherently right and wonder-ful in the world when the survival of even a lowly sea turtle matters. Calling forth and savoring those things all about you that offer strength and sol-ace is an important exercise in a troubled world. Si Kahn, a colleague and songwrit-er, describes this as being able, in the face of great challenges, to Âkeep on keepin on.ÂŽ We live in an era of forbidding and recalcitrant gloom, driven there by winds of uncertainty that are changing the world we thought we knew. To retreat from that ledge, we need the reassurance that, even in the midst of a stampede toward the unknown, beauty can be found in how we choose to see the world. Seeing beauty is redemption from pessimism. Release from pessimism is how we build with hope, brick by brick, a better future. Here are two more things I would nominate as ÂRight in the WorldÂŽ that measure on the scale of awesome that is proportionate to saving Andre, the sea turtle: the qual-ity and commitment of our communities non-profit leadership and the tremen-dous asset these individuals represent toward achieving, in our time, a more just, humane and caring world. Call me preju-diced but anyone who is engaged in the non-profit sector these days has to have nerves of steel and the courage of a lion. Our region profits enormously from an abundance of seasoned non-profit profes-sionals who are accomplishing important milestones toward improved quality of life in our local communities. They make this commitment of vocation by choice and with a fierce loyalty to serving those who often need societies help the most. They donÂt just make lemonade out of lemons; they transform lemons into stars on a dark night. Advocates working to protect and sustain now and for future generations, conservation of FloridaÂs unique envi-ronmental resources: in Florida, growth to prosperity is as ketchup is to fries. How many times is it necessary to stand in front of a metaphorical bulldozer, to challenge and question, the wholesale destruction forever of what cannot be put back or replaced? ÂEconomic ProgressÂŽ and its evil twin, ÂProgress-at-Any-Cost,ÂŽ are how we continue to frame unaccept-able choices with no terms of escape and a tiger behind every door. With all the hindsight of which Florida ought to have plenty, we deserve a more intelligent dis-course on issues of sustainability. The Flo-ridians who raise their voices and bring vision, passion, and their reasoned intel-ligence to protection and conservation of the environment are todayÂs wilderness warriors. We can be thankful that caring did not stop with Teddy Roosevelt, as itÂs very likely thereÂd be no Andres left. “Saving Andre” shines a light on the hopeful work of non-profit professionals leslie LILLY President and CEO of the Community Foundation for Palm Beach and Martin Counties O PAGE 13 Action Sports 1002 Jupiter Park Lane Unit 1 Jupiter, Fl 33458 1-866-944-9554 Introducing the MBT Jambo The NEW MBT Jambo is a casual canvas sneaker with a streamlined prole that hides the fact you are wearing a secret workout weapon. Keep your workout going after your workout is over with the MBT Jambo. Great Selection of New and Closeout Styles Showroom Hours Mon. Sat. 10 am 6 pm FLORIDA WEEKLY WEEK OF AUGUST 25-31, 2011 A13 gone from a size 14 to a size 4 ÂIn four months of training and eating for my health, IÂve lost 26 pounds and am in the best shape I can ever remember!ÂŽ Â… Mary Murphy-Parkola Age 51 Special Educator and mother of two Heart disease. It affects our grandfathers and grandmothers, mothers and fathers, sisters and brothers, neighbors and friends all too often as the number one cause of death in the United States. To put this into perspective, in 2006 heart disease was responsible for one out of every four deaths in this country. The good news? At Palm Beach Gardens Medical Center, our skilled interventional cardiologists are utilizing advancements in the diagnosis and treatment of the earlier stages of heart disease to help patients beat the statistics and keep heart disease at bay.One of the procedures frequently performed to diagnose heart disease is performed through cardiac catheterization, which helps determine the extent of coronary artery diseasea major contributor to the develop-ment of heart disease. With coronary artery disease, accumulations of fat and calcium, or plaque, cause heart vessels to narrow. This subsequently reduces the amount of blood flow to the heart causing chest pain or even a heart attack if the plaque blocks arteries completely. At Palm Beach Gardens Medical Center, we have taken cardiac catheteriza-tion to the next level, performing techniques such as the transradial approach. With this approach, interventional cardiologists com-plete catheterization procedures through the radial artery in the wrist instead of the femo-ral artery in the groin.During a traditional cardiac catheterization, cardiac interventionalists thread a long, thin tube (catheter) into the femoral Healing hearts — itÂ’s all in the wristartery in the groin to access the blockage in the heart. With the transradial approach, interventional cardiologists perform the procedure through the radial artery in the wrist. Since arteries are much smaller in the wrist than in the leg and groin, the procedure requires specialized catheters and sheaths, which have been successfully developed with advancements in research and technology. Miniaturization of devices, improvements in devices and techniques, and specialized training programs for physi-cians have all contributed to an increased growth in the practice and efficacy of transradial interventional procedures. The technique can bring significant benefits to the patient, including decreased complica-tions at the puncture site, increased patient comfort, earlier discharge, and shorter hos-pital stays. In fact, many patients can sit up almost immediately following surgery and, in some cases, can be discharged home the same day. In addition, this approach may be suitable for patients of all ages, even those with chronic medical conditions and complex blockages. It is also an option for obese patients, where access through the groin can be difficult. As a hospital with a longstanding dedication to cardiac care, Palm Beach Gar-dens Medical Center takes great pride in protecting the hearts of its community. Providing some of the latest techniques in cardiac catheterization like the transradial interventional procedure is just one way the hospital is making strides to keep our communityÂs grandfathers and grandmoth-ers, mothers and fathers, sisters and broth-ers, neighbors and friends out of the heart disease statistics. For upcoming heart health screenings, call 561-625-5070. Q a i i p t i p j.michael COWLING CEO, Palm Beach Gardens Medical Center O PAGE 14 A14 WEEK OF AUGUST 25-31, 2011 For noticeably healthy skin, schedule today.* Session consists of a massage or facial and time for consultation and dressing. Prices subject to change. Rates and services vary by location. Additional local taxes and fees may apply. 2011 Massage Envy Franchising, LLC. Open 7 days: M-F 8AM-10PM, SAT 8AM-8PM, SUN 10AM-6PMJ UPITER -S PA3755 Military TrailCorner of Military Trail & Frederick Small Rd, next to Winn-Dixie(561) 743-8878MM #20509P ALM B EACH G ARDENS -S PA3938 Northlake BoulevardNorthlake & I-95, in the Home Depot Plaza (561) 627-3689MM #19906$Introductory 1-hourHealthy Skin facial session*49$Introductory 1-hourmassage session*39 now offering Murad facials! Massage Envy Spa As part of a joint research effort with the University of Michigan, scientists from the Florida campus of The Scripps Research Institute have for the first time defined the structure of one of the cellÂs most basic engines, which is required for cell growth, as it assembles from its components. The study reveals a series of redundant mechanisms that assure production of these critical structures while avoiding any missteps that could lead to their destruc-tion or to the production of incorrect cel-lular building blocks. These findings throw new light on a process that is integrally involved in a number of disease states, including cancer and AlzheimerÂs disease. The study, published on August 11 in the advance online edition of the journal Science, reveals the structure of an assembly inter-mediate „ which involves almost 200 essential proteins known as Âassembly fac-torsÂŽ in addition to the four RNA mol-ecules and 78 ribosomal proteins that are part of the mature ribosome „ is a poten-tially Â…150 C) to image the 40S ribosome structure. ÂThis is the best-defined ribosomal assembly intermediate we have ever had with true structural information on the location of each assembly factor,ÂŽ said Katrin Karbstein, an associate professor at Scripps Florida and one of the senior authors of the study. ÂIt will be helpful in determining whatÂs going on in what is still a relatively unknown process.ÂŽ While most ribosome assembly takes place in the nucleolus, a protein-nucleic acid structure inside the nucleus, the final maturation process occurs in the cyto-plasm, the ÂgeneralÂŽ cellular compartment where protein translation occurs. In the cytoplasm, these pre-mature ribosomal subunits encounter large pools of mature subunits, messenger RNA, and vari-ous translation factors. This cellular stew presents a unique challenge, especially keeping the transla-tion process from acting on the subunits prematurely, which would result in their rapid degradation or in the production of incorrectly assembled proteins, both pro-cesses with potentially lethal o utcomes for the cell. The new study shows that that the bound assembly factors cooperate with one another in a highly redundant and multi-pronged approach to prevent such occurrences, chaperoning the pre-40S sub-units to keep them from falling victim to the translational apparatus. ItÂs important to note that this is a single snapshot of the late-stage assembly pro-cess, Ms. Karbstein added. ÂWe know bet-ter how the process works but this is by no means a final statement.ÂŽ Q Scripps scientists define structure of cell engineKARBSTEIN PAGE 15 FLORIDA WEEKLY WEEK OF AUGUST 25-31, 2011 A15Ss/RGANICTEXTILESFORUPHOLSTERYANDDRAPERY ALL ART & MIRRORs30% OFFnot including Florida HighwaymenA company that promises Âone-stop shoppingÂŽ con-trol their energy usage. Super Green Solutions sought certification from Certified Green Partners, and says it is the first U.S. Flagship Energy Efficient Products store to be Green Certified. The company also says it has a Âgreening everything that we do program,ÂŽ in which it uses a chain-of-custody com-mercial printer, FSC, recycled paper and recycles everything that it can „ from ink cartridges, to paper, packaging, cans, plastic and glass. The store has large recycling bins and encourages cli-ents to bring in ink cartridges, batter-ies, fluorescent and compact fluorescent lights for proper recycling. The company also has switched to using only green cleaning products and has voluntarily banned the use of plastic water bottles „ employees use stainless steel reus-able water bottles that they refill from an in-house atmo-spheric water filter and water generator. ÂWe hope and trust that the building industry, businesses and homeown-ers alike will see value in our holistic approach to sustainability and favor the promotion and use of energy efficient products,ÂŽ Sean Cochrane, CEO of Super Green Solutions, said in a statement. Super Green Solutions is at 3583 Northlake Blvd., North Palm Beach. Phone: 767-8224. Q Super Green Solutions opens certified green storeCOURTESY PHOTO Super Green Solutions has opened on Northlake Boulevard in North Palm Beach. WHY DOOR TO BALLOON TIME MATTERS DURING A HEART ATTACK. 561.625.5070THE HEART ATTACK RISK ASSESSMENT ITÂS FREE.ITÂS PRICELESS.pbgmc.com/heartscreenings AUGUST 25-31, 2011 A16 F.F. ÂCHAPPYÂŽ ADAMS IS OPTIMISTIC. After several years of seeing property values decline, the president of Illustrated Properties is seeing sales rise. ÂWeÂre up about 28 percent in the number of sales, which is a pretty remarkable number when you consider that last year we had that first-time homebuyer tax credit,ÂŽ he said. ÂWeÂre ahead this year and thatÂs with no stimulus.ÂŽ Prices also have begun to impr ove, he s aid.Chappy AdamsFLORIDA WEEKLYÂ’S EXECUTIVE PROFILEBY SCOTT SIMMONSssimmons@” oridaweekly.com ÂPrices below $200,000 have begun to stabilize,ÂŽ he said, acknowledging that with prices of Â$500,000 or ab ove, there may be depreciation. By this time next year everything will be trending upward.ÂŽ Mr. Adams grew up in Northern Palm Beach County „ in fact, he is a member of the third generation of Adamses to sell real estate in the area. His grandfather, F.F. ÂBudÂŽ Adams Sr. sold property on Jupiter Island during the 1930s. Chappy Adams dad, Bud Jr., founded Illustrated Properties in 1975, Chappy joined the company in the 1980s, and they have built the company to be one of the largest independent real estate enterprises in Palm Beach, Martin and Collier counties. Northern Palm Beach County is a vastly different place from what it was even in the 1990s. ÂItÂs funny. ThereÂs been a lot of change,ÂŽ Mr. Adams said. ÂI just came back from a trip to Sweden, where my mother is from. Her town in Sweden looks the same as it did in 1980.ÂŽ Mr. Adams, who has traveled to 70 countries, says he is amazed. ÂThe changes here are astounding,ÂŽ he said. ÂWe live in such a unique area that has experienced such growth over the past 30 to 40 years.ÂŽ He is looking ahead to further change, further growth. He predicts continued growth of the biotech hub that began with Scripps Research and Max Planck. ÂOver the next 10 years, it will grow as La Jolla has,ÂŽ he said. And he looks ahead to the Digit al Domain instit uteÂs opening in downtown West Palm Beach. The real estate firmÂs Wellington office remains busy, with large numbers of celebrities shopping for homes. ÂYou donÂt even know that world exists unless you go out there,ÂŽ he said. ÂWeÂre working with the daughter of one of the richest men in the world. TheyÂre looking to invest a staggering amount in Wellington.ÂŽ He said his agents in Wellington also worked with New York Mayor Michael Bloomberg, and that his office had han-dled the sale of a $12.2 million house at Seminole Landing in North Palm Beach to Tiger Woods ex-wife, Elin Norde-gren. That house, which Ms. Nordegren planned to tear down, had special ties to Mr. Adams. ÂIt was my fatherÂs old house 20 years ago,ÂŽ he said. Mr. Adams lives at Harbour Point, south of PGA Boulevard. ÂIÂm a boater and I can zip out to the Intracoastal,ÂŽ he said. All the better to gain perspective.ÂReal estate is as much who you know as what you know,ÂŽ Mr. Adams said. ÂI look at our agents who do really well, and theyÂre very social. If you get people that know, like and trust you, you will do well in real estate.ÂŽQFirst job: Pressure-cleaning roofsQWhat IÂm reading: ÂGame PlanÂŽ by Steve MurrayQMy personal philosophy: Work hard and play hard sometimes, and to use the rocking chair test as often as possible, that is when I am in my Â80s will I be happy with the choices I make today!QAbout Illustrated Properties: Illustrated Properties was started by my father, who has been an incredible mentor, I am so fortunate that we work so well together. I am actually a third-generation Realtor, my grandfather sold properties on Jupiter Island starting as far back as the Â30s. Today we have the No. 1 market share from Delray to Stuart. We have 550 Realtors working from 18 offices and are the Christies exclusive affiliate for most of the areas we serve.QWhat do you love about Florida? IÂm a boater and being on the water is very relaxing for me, so I love that we have boating weather almost year round.QBest thing about my work: The fact that there are no limits, that I work with such great staff and agents and that we continually look for ways to improve the company.QMy personal mission for the company: To continue to be the No. 1 company in the markets we serve, and to provide a relaxed, family-like atmo-sphere for all that work here.QWhatÂs on the horizon: I believe that we are basically at the bottom of the market and that things will begin to improve in 2012 in all price levels. We will look back on 2011 as the Âtime to buy.ÂŽQMy top tech tool: Trendgraphix, a tool that analyzes the real estate market trends.QI love: Skiing, my boat and traveling when I can.QI hate: Hypocritical peopleQFinally: I just feel truly blessed to work in a field I l ove, wor king with my father. And to top it all off we get to do this in Palm Beach County. Life is good! Q >> Name: Chappy Adams>> Age: 46>> Family: One 5-year-old daughter>> Hometown: Palm Beach Gardens>> Education: Graduated Benjamin School locally and graduated from Boston College in 1987 O in the know PAGE 17 FLORIDA WEEKLY WEEK OF AUGUST 25-31, 2011 BUSINESS A17 Visit us online at You should know ...FLORIDA WEEKLYÂS SPOTLIGHT ON LOCAL REAL ESTATE BUSINESS PROFESSIONALS NAME: Natalya Daley CURRENTLY: Realtor with K2 Realty SPECIALTY: Residential real estate working with both buyers & sellers in Palm Beach Gardens & Jupiter. HOMETOWN: Iowa City, Iowa RESIDENCY NOW: Palm Beach Gardens, Florida Â… The Community of Evergrene.BACKGROUND: A graduate of Northwestern University in Evanston Illinois, I moved to Palm Beach Gardens in 2003 from Chicago and have been an associate with K2 Realty for the past five years. FAMILY: My husband Jess (a former PGA Tour Golfer), two boys and several animals from the Peggy Adams Shelter.ACTIVITIES: When IÂm not with clients, I enjoy spending time with family and friends. I am also a passionate soccer player & have coached for the Palm Beach Gardens Youth Soccer League for the last three years. BEST THING ABOUT THE REAL ESTATE INDUSTRY: Meeting new people and successfully helping them purchase a new home. For my listing clients who are selling Â… produce the most lucrative sale possible. Much of real estate (especially in this market) is about problem solving and negotiating the best result. TOUGHEST PART OF THE JOB: Difficult lending situations. ADVICE FOR A NEW AGENT: No matter what the circumstance, honesty & integrity is the best solution. OUR JOBS WOULD BE EASIER IF: We could always buy low & sell high!!! A QUOTE YOU WOULD LIKE TO SHARE WITH OUR READERS: Limitations live only in our minds. If we use our imagination, our possibilities become limitlessƒ Natalya Daley.NETWORKING Boys and Girls Clubs of Broward County Hosts Construction Career Day1. Kersie Louima and Jim Robertson2. Shannon Brewster and Earl Baptiste3. Tyler Wharton 4. Quashonta Wright, Vanessa Baptiste, Christine Richardson, and Carol ClarkBoys & Girls Clubs of Broward County joined forces with more than a dozen leading construction companies to help about 300 high school students explore potential careers in construction at the 2011 Generals Construction Career Day in Pompano Beach. Career Day activities included hands-on ses-sions conducted by representatives from leading construction firms. 1 3 2 4 COURTESY PHOTOS PAGE 18 FLORIDA WEEKLYA18 BUSINESS W EEK OF A UGUST 25-31, 2011 Cabo Flats Kids eat FREE. Kids 12 and under. Restrictions apply. Go van Gogh Toddler craft sessions 10-11am $12.50TUESDAYS MONDAYS At Downtown, Family Fun isnÂ’t only for the weekends. During the week we have plenty of fun for the whole family, with many events absolutely FREE! Complimentary Valet and Garage Parking DowntownAtTheGardens.comus TODAY for Specials! Bring this ad f a FREE ride o our CarouseFW00825 '7*)DPLO\)UHH(YHQWVYLQGG $0 We take more society and networking photos at area events than we can t in the newspaper. So, if you think we missed you or one of your friends, go to and view the photo albums from the manNETWORKING Sip, Shop & Socialize at STORE Self Storage, Palm Beach Gardens 1. Bonnie Peters, Joan Quittner, Brooke Pastor and Toni Worley 2. Tony Olivia with Beth Garcia, Terri Adonno and Christine Hoppe3. Dawn Addonizio, Carolyn Marshall and Kim Bickford 4. Darleys Franco and Lenes Perez 5. The Laser Skin Solutions crew 6. Marina Popovetsky, Enid Atwater and Miriam Jessell 7. Branden Gould, Daron Walker and Nancy Spoto 8. Beth Garcia and Beth Thomas 6 5 4 3 2 1 7 COURTESY PHOTOS PAGE 19 FLORIDA WEEKLY W EEK OF A UGUST 25-31, 2011 BUSINESS A19 Mommy and MeMeet at Carousel Courtyard Wednesday August 31st for family friendly activities. Our participating retailers include: A Latte Fun, Candles by MimiÂ’s Daughter, Go van Gogh, Keola Health & Wellness, Cartoon Cuts and more!Wednesday August 31, 11am-1pmCarousel Courtyard Mommy & Me July 27th, 11am-1pm Carousel Courtyard Centre Court FREE Live music for the whole familyWEDNESDAYS FRIDAY & SATURDAYS d for e on sel! Winners posted at ITÂ’S EASY: Join Our eClub Mailing List INSTANTLY! ENTER TO WIN A$1000 SHOPPING SPREE! ENTER TO WIN A$1000 SHOPPING SPREE! '7*)DPLO\)UHH(YHQWVYLQGG $0 o albums from the many events we cover. You can purchase any of the photos too. Send us your society and networking photos. Include the names of everyone in the picture. E-mail them to society@oridaweekly.com.NETWORKING Record turnout at Artists Association of Jupiter show About 170 attend opening of exhibition at A Unique Art Gallery 8 1. Barry Seidman andCraig Houdeshell 2. Doreen Kenney, Candice and Kenzie Johnson and Susan Lorenti3. Suzanne Schwartzmann (second place), show judge Barry Seidman, Craig Houdeshell (first place) and Jerry Hilderbrand (third place)4. Durga Garcia 1 3 4 2 COURTESY PHOTOS PAGE 20 FLORIDA WEEKLYA20 WEEK OF AUGUST 25-31, 2011 After my dentist of 20 years quoted me a price on an implant, I looked for a second opinion. I had seen ads for Appearance Implants and sought out Dr. Harrouff. When I walked into the lobby of the of ce, the rst thing I saw was a photo of the late Republican strategist Lee Atwater, who I later learned was a childhood friend of Dr. Harrouff. As a South Carolina democrat, I didnÂ’t have a lot of love for Lee; he had gotten the best of me in my rst campaign. I sure as hell wasnÂ’t too keen on letting any buddy of Lee work on me. After that rst encounter, I felt very comfortable with Dr. Harrouff. The entire experience was purely rst rate. From the people who greeted me in the lobby to the dental staff, the Appearance Implants & Laser Dentistry team makes you feel right at home. When Dr. Harrouff got down to performing the procedure, it was fast, relatively painless, and the result was just perfect. The nished implant works better than IÂ’d expected. He provided me with the most affordable treatment, and I have been more than impressed and satis ed by the results. I have recommended Dr. Harrouff and his profes-sional and friendly staff to many of my friends and colleagues.Congressman (D-SC) John W. Jenrette, Jr.; E. Spector, DDS Quality Dentistry at Affordable Prices. LIMITED TIME ONLY! 6390 W. Indiantown Road, Chasewood Plaza, Jupiter /PENEVENINGSs%MERGENCIESWELCOME (561) 741-7142 s 1-888-FL-IMPLANTSALL PHASES OF DENTISTRY Implants, Full Mouth Reconstructions, Veneers/Lumineers, Dentures, Porcelain Crowns and Bridges, Root Canal Therapy and Sedation Dentistry.. Harrouff is a diplomate member of the American Dental Implant Association, and recently completed an ITI training course at the Harvard School of Dental Medicine. Dr. Fein is a board-certi“ ed Periodontist and earned his doctorate from Columbia University and specialty certi“ cate from Nova Southeastern University. He has trained in all aspects of implant and periodontal therapy, and has published articles in the Journal of Periodontology and lectured on dental implants. Our dentists include graduates from Columbia, Louisville, Temple, University of Tennessee, Buffalo and University of Pittsburgh. NEW DENTURESfrom $359 each (D5110, D5120) Expires 9/7/2011SIMPLE EXTRACTIONS from $25 each (D7140) With standard denture purchase. New patients only. Expires 9/7/2011 DENTAL IMPLANTSfrom $499 each(D6010) New patients only. Expires 9/7/2011 ROOT CANAL THERAPYfrom $299 each (D3310) Expires 9/7/2011 FREEDIGITAL X-RAY & CONSULTATION(D2750) Expires 9/7/2011 MONEY & INVESTINGInvestors and traders can learn from each otherMany people think that investing and trading have little in common. Actually they have a lot in common. They might be traveling down different roads but traders and inves-tors want to get to basically the same place. They both have making money as their primary purpose. There are several ways to differentiate trading from investing: length of time an investment is held, the basis for making/exiting the investment decision (either technical or funda-mental or a combination), and the means of execution (self-executed, professionally managed, or algorith-mic/computer executed), among a host of other factors. Each of these various characteristics has a continuum of possibilities. For instance, with regard to the time an investment is held, high frequen-cy traders are often arbitraging-away price differentials between markets and they might hold something for a nanosecond. The other extreme is the genre of investor akin to War-ren Buffett who might hold an asset forever, or at least longer than most marriages last. But, in very broad and general terms, investing is associated with: longer-term time horizons, funda-mental analysis, which is most often the process behind asset selection, and human decision-making and exe-cution, albeit with some computer-ized assistance. By the very nature of any human process, a range of emotions (fear and greed, complacency, panic, euphoria, etc.) will influence (or even drive) the decision-making process. A longer-term horizon is often synonymous with Âa buy and holdÂŽ approach without any triggers to exit a position on prices drops. Rarely are there Âprice rules,ÂŽ i.e. no hard and fast rules for stopping losses. The underlying concept in this case is that the fundamentals of impend-ing growth, management changes, dividend hikes, etc. will be made manifest or work themselves out. Yes, there can be forms of portfolio diversification (ranging from nomi-nal to true asset diversification) but rules for money management are infrequent. Now contrast that to trading which is, in broad and generalized terms, shorter-term in time horizon (rang-ing from a nanosecond to dayto medium-term trading spanning sev-eral months). Also, trading is often Âtechnical onlyÂŽ and has a large set of rules for entries, exits and money management of the portfolio. The larger the set of these aforementioned technical rules, the shorter the time horizon, the greater the exposure to markets trading nonstop, the more diverse the investment positions in a portfolio, then the more probable it is that the trader relies on algorith-mic computerized trading. Unlike human decision-making, this trading has no emotion; it is void of fear, greed, panic or other emotions that influence human decision-making or execution. The objective is a con-sistent application of the rules and tools in the most efficient and objec-tive ways. A lot of computerized programs were birthed by hands-on, very experienced traders who then transformed their trading methods into algorithms. Now, do technicians disregard fundamental information as irrelevant? No, not at all; they know that behind price movements are the realities of the fundamentals of the market (ƒ. and buyer/seller emotions). But, for many traders, price reflects that which can often only be fundamen-tally explained and articulated after the fact. I interface with both the trading and the investing worlds. My observation is that while many investors have not allocated a portion of their portfolio to trading strategies or systems, they are leaning and learning that way as they want to get into faster-moving or more leveraged markets needing round-the-clock disciplines. A sec-ond observation is that the trading community often embraces funda-mental investing with a long-term horizon for portions of its portfolio, though traders are more inclined to bring disciplines of money manage-ment, true diversification and stop losses into their investment portfo-liosƒ as they are less relative and more absolute performance oriented. So, one mindset clearly accepts ele-ments of long-term investing; the other mindset is somewhat reticent to accept trading. I wonderƒ is there a bias, or a fear, or a misunderstand-ing, etc. of trading? Maybe the prob-lem is that the investment advice being rendered is more narrow in perspective and embraces only those products or services offered by the adviserÂs firm. The world is changing, the economies are changing, the weather is changing, wars happen, new Presi-dents get elected, analysts and money managers and investment commit-tees come and go. Yet, the rules of the algorithmic black box are not always changing and consistently applied. The mindset of the trader is most often: ÂCut losses and let profits run.ÂŽ There might be some real value to add this type of approach to invest-ing to your portfolio. You might con-sider the merits of trading systems (directly leased to you by brokers or offered as a money management product by portfolio managers or advisers). Consider that if the hedge fund managers have embraced Âblack boxesÂŽ for a portion of their port-folios, it might be that you would do so too. Talk to your adviser as to suitability, seek diversity of opin-ions from multiple advisers and seek counsel from investment experts as pertains to specific asset classes. Q „ There is a substantial risk of loss in trading commodity futures, options and off-exchange foreign currency products. Past performance is not indicative of future results. PAGE 21 REAL ESTATE A GUIDE TO THE REAL ESTATE INDUSTRYWEEK OF AUGUST 25-31, 2011Elegance for EquestriansTHIS HOME AT 13418 SAND RIDGE ROAD in the Palm Beach Gardens equestrian community of Caloosa is on five acres of high, dry land, with water on two sides. The neighborhood features all paved roads, 5-plus acre lots, riding trails and an equestrian center. It has four bed-rooms plus an octagon sitting room and office, 3 baths and a three-car garage. The Brentwood model, built by Vista Builders, features more than 3,800 square feet of air conditioned space and 5,275 total square feet. It features a long brick-paver driveway, impact windows, a stacked-stone double-sided fireplace, wood beam ceilings, hand scraped wood floors through-out the living area and a summer kitchen. French doors lead to covered patios in the front and in the back of the house. The security system includes cameras with cell phone capa-bility for remote monitoring. The gour-met island kitchen features Jenn-Air stainless steel appliances, brick facade, custom two-tone cabinets and a walk-in pantry with wood shelves. The large master bath includes his-and-her vani-ties, a whirlpool tub and open shower with dual shower heads. The generous landscaping package compliments the exterior and includes an irrigation sys-tem. Vista Builders has other homes under construction in Palm Beach Coun-try Estates and Square Lake that are also available for sale. This home is listed at $797,500. Contact the Smith Team, Scott D. Smith, 719-5133, and Nancy C. Smith, 719-5123, Keller Williams Realty. Q SPECIAL TO FLORIDA WEEKLY A21 New home in Caloosa offers riding trails, equestrian center COURTESY PHOTOThe home is on five acres of high, dry land with water on two sides. It features more than 3,800 square feet of air-conditioned space and 5,275 total square feet. Above: The gourmet kitchen boasts Jenn-Air stainless steel appli-ances, a walk-in pantry, and custom, two-tone cabinets.At left: A stacked-stone, double-sided fireplace is featured in this home built by Vista Builders. PAGE 22 FLORIDA WEEKLYA22 REAL ESTATE WEEK OF AUGUST 25-31, 2011 COURTESY PHOTO Beer served in this Gerz stein must taste good. The man with the big grin was called “Smiling Face” by the Stein Auction Co., the auction house that sold it for $529. Beer steins have long been popular. Today-tery. One famous German company that used the mark ÂGerzÂŽ opened in 1857 and remained in business until the 1990s (a new company with the same name was recently established in Ger-many and is using the old Gerz triangle mark). Gerz made steins using glass or pottery. Its regimental and figural 3-D character steins that look like animal or human heads, usually comic, are especially popular. An amusing Smil-ing Face pottery stein marked ÂGerzÂŽ sold for $529 at the Stein Auction Co.Âs June auction in Schaumburg, Ill. Q: I have a Hoosier-style Sellers one-piece cabinet that my mother pur-chased secondhand in the 1950s. IÂve been unable to figure out how old the cabinet is. There seems to be a lot of information out there about two-piece cabinets, but not about this one-piece unit. The cabinet was a mint-green color originally, and still has the origi-nal flour sifter. Can you help? A: Hoosier cabinets were first made by Hoosier Manufacturing Co. of New Castle, Ind., about 1900. The freestand-ing kitchen cabinets had a work sur-face and shelves and drawers fitted with a flour sifter, coffee and tea can-isters, cracker jars and other kitchen items. Soon all similar cabinets by other makers were called ÂHoosiers.ÂŽ ÂColonial Homestead by Royal.ÂŽ Different scenes are pictured on different pieces. The scene on the plates includes a table, chairs, grandfather clock, large fire-place with hanging cookpots and an old-fashioned gun over the fireplace. We find these interesting because we recently built a log cabin. This set was left to me by my great-uncle. It includes service for six people and includes plates, small bowls, cups and Stylish steins designed to prevent diseaseKOVELS: ANTIQUES & COLLECTING terry KOVEL news@floridaweekly.com O saucers, a platter and a vegetable bowl. IÂd like to know how old these are and what they might be worth. A: The Royal China Co. was in business in Sebring, Ohio, from 1934 to 1986. The company made dinnerware, cookware and advertising pre-miums. The Colo-nial Homestead pattern, which includes scenes from a colo-nial home, was designed by Gor-don Parker. It was introduced about 1951 and was sold by Sears, Roebuck & Co. through the 1960s. The dishes sell for very low prices today. Q: I have an old ticket that was my great-grandfatherÂs. ItÂs for a ÂMexican Bull FightÂŽ Âfirst bull fight held in the United States.ÂŽ Two professional bullfighters from Mexico were hired, but the bulls, whether imported or homegrown, were unen-thusiastic participants. So, according to most accounts, the event was a fiasco, a planned third day was can-celed, area humane societies protest-ed and those who attended wanted their money back. The Denver Public Library has a ticket like yours in its collection, and other historical soci-eties around Cripple Creek (south of Denver) probably would be interested in owning one. So you might consider donating yours. If you decide to sell, contact an ÂOld WestÂŽ auction. ThatÂs where youÂd probably get the most money and itÂs impossible to predict how much. Gillett, by the way, was a Gold-Rush town thatÂs now a ghost town. Bullfighting was banned in the United States in 1957 although so-called bloodless bullfights are held in some U.S. communities. Q: We found a Civil War discharge paper for Jasper Noon in my mother-in-lawÂs estate and are wondering if it has any value. There is a faded paymasterÂs stamp, an eagle, flags and stars at the top under the words ÂTo all whom it may concern.ÂŽ The soldier joined Company C, 50th Regiment of Indiana Infantry, on Nov. 1, 1861, and was dis-charged on Jan. 5, 1865. A: A collector of Civil War items might be interested in the discharge papers. Interest in Civil War items is expected to increase this year, since itÂs the 150th anniversary of the start of the Civil War. Jasper NoonÂs regiment was organized in September 1861 and mustered out in Septem-ber dis-charge papers sell for $60-$80. Tip: To remove verdegris (the green mold that forms on metal) from cos-tume jewelry, mix equal amounts of mayonnaise and ketchup. Rub it on and quickly remove it. Wash. Try again and leave it on longer if the first treatment doesnÂt work. DonÂt use on pieces with pearls.. THINKING of BUYING or SELLING in BALLENISL ES... Palm Beach Gardens ? Call Marsha Grass, Resident Realtor561.512.7709marshag@leibowitzrealty.com ÂI know the community. I live the lifestyle.ÂŽ Â… Marsha Grass rrrsrsGARDENS LANGREALTYCOM 0'!"OULEVARD3UITEs0ALM"EACH'ARDENS %NJOYTHELAKEVIEWFROMTHEDECKOF YOURPOOLINTHISBEDROOMBATHVILLA 4HISEXTENDED#APRIMODELOFFERSSPECIAL TOUCHESSUCHASGRANITEANDDESIGNER PAINTlNISHES ANN MELENDEZ 561-252-6343 "EAUTIFULLYREMODELEDUNITWITHBEDROOMS BATHSANDLARGEKITCHENWITHBREAKFAST COUNTER%XCEPTIONALINTRACOASTALANDOCEAN VIEWSFROMTHrmOORWRAPrAROUNDBALCONY 'ATEDCOMMUNITYWITHGREATAMENITIES SUSAN WINCH 561-516-1293 #ONTEMPORARYSINGLEFAMILYPOOLHOME WITHCLEANLINESANDLAKEANDGOLFCOURSE VIEWS$OUBLEDOORENTRYBEDROOM BATHHOMEONOVERANACREISCLOSETO GUARDrGATEDCOMMUNITYENTRANCE SUSAN EDDY 561-512-7128 !BSOLUTELYFABULOUSMODELHOMEREADY TOMOVEINTO4HREEBEDROOMSAND BATHS&ULLGOLFEQUITYAVAILABLE%VERY ROOMlLLEDWITHUPGRADESANDDESIGNER APPOINTMENTS4HISISAMUSTSEE CAROL FALCIANO 561-758-5869 PALM BEACH GARDENS-GARDEN OAKS RIVIERA BEACH-LAKE HARBOR COVE BAYHILL ESTATES MIRASOL Â… OLIVERA NEW ) 34) NEW ) 34) NEW ) 34) NEW ) 34) PAGE 23 ItÂs one of the largest art festivals in the country. And ArtiGras is seeking a few talented artists to set up shop at the three-day fes-tival, held Feb. 18-20 at Abacoa in Jupiter. Artists applications are being accepted for jury selection in 12 fine art categories including ceramics, digital art, drawing and printmaking, fiber (wearable and non-wearable), glass, jewelry, metal, mixed media, painting, pho-tography, sculp-ture and wood. Entries will be reviewed by an expert panel of five jurors for 270 fine art spaces. The ArtiGras Fine Arts Festival, which attracts upward of 125,000 visitors, also offers a ÂHomegrown ArtistÂŽ category for emerging artists. Under this program, selected devel-oping artists will receive mentoring services, professional booth photos, complimentary tent rental and a profile in the ArtiGras program. Qualifications include artists who have never exhibited in a show and artists who reside in the Palm Beach County area. Emerging Artist applicants should proceed in the same manner as professional artists and sub-mit their artwork online through Zap-plication.org. Deadline for artists to apply online for inclusion in ArtiGras is Sept. 2. Artists can email info@npbchamber.com, call 748-3946 or visit for more information. Q ArtiGras makes call for artistsSPECIAL TO FLORIDA WEEKLY FLORIDA WEEKLY ARTS & ENTERTAINMENTA GUIDE TO THE PALM BEACH COUNTY ARTS & ENTERTAINMENT SCENE A23 WEEK OF AUGUST 25-31, 2011 HANDS UP FOR LISA CONGDONÂS COLLECTION OF COLLECTIONS THE DISEMBODIED HANDS RANGE IN COLOR from albino white to pink and beige to a warm mocha brown. Some grasp baby bottles, while others are curled into defiant fists. Some hands lie open, expectantly, palms up, while others seem to be flashing gang signs. TheyÂre Lisa CongdonÂs collection of baby doll hands, just one of the hundreds of collections sheÂs amassed. A couple of years ago, the San Francisco-based artist and illustrator was searching for something to revi-talize herself artistically. It was BY NANCY STETSONnstetson@” oridaweekly.com COURTESY PHOTOAbove: Day 260 consists of a collection of doll hands. Artist Lisa Congdon challenged herself to photo-graph one of her collections every day for one year. Left: Ms. Cong-don shops at an antiques mall. SEE COLLECTION, A25 X PAGE 24 FLORIDA WEEKLYA24 ARTS & ENTERTAINMENT WEEK OF AUGUST 25-31, 2011 ÂAnyone headed back to the inn?ÂŽ I say.The men look to their half-full cups and eye each other as if evaluating the competition.ÂIÂm headed out now,ÂŽ one says. He drinks the last of his beer in one long draw.ÂMe, too,ÂŽ the man next to him says.Suddenly we are a crowd, assembled en mass, with me at the head. We walk back to the lodge, sweeping through the field I crossed earlier, and the men string out across the path. They fol-low my trail, step up beside me and fall back. They jostle each other as if compet-ing for an endangered species. Q Nothing draws a crowd like manatees mating. On a r ec ent. ÂWhatÂs going on?ÂŽ I asked a man by my side. He kept his camera trained on the watery tumult a few feet in front of us. ÂTheyÂre mating,ÂŽ he said.ÂAll of them?ÂŽÂOne in frontÂs a female.ÂŽAnd the rest? All those heavy male bodies piled on, trying to stake a claim during the femaleÂs brief stretch of fer-tility. They pursued her like a rare gem, a coveted item, the last woman in the world „ which, technically speaking, she almost is. Manatees are after all an endangered species. I slowed to let the crowd pass by me Men, like manatees, follow the scent of the female SANDY DAYS, SALTY NIGHTS artis HENDERSON sandydays@floridaweekly.com O as the throng of randy sea cows moved parallel to the beach. A woman spoke as she hurried down the shore. ÂArenÂt you glad weÂre not manatees?ÂŽ she said. IÂm at a retreat this week where available women are scarce. There are plenty of men „ married men, divorced men, still-single-and-seeking men. But the women who are free to chat, to flirt, to make poor decisions „ these women are remarkably limited. They have become suddenly more appealing, their value ris-ing with their scarcity, and in the eve-ning cocktail sessions the men rush to pile on. In sort of a throw back to summer camp, thereÂs a bonfire one night. I ask the people seated with me at dinner if theyÂre going. ÂItÂs going to be all dudes,ÂŽ the man to my right says. ÂA total sausage fest.ÂŽ I make my way there anyway, tromping across a field lit by the half moon over-head. In the distance, the fire glows orange against the black pitch of night. I arrive and make a quick tour, saying hello to friends IÂve made. They stand in tight groups holding plastic cups of beer. It is, in fact, a sau-sage fest. As the night draws down, I make a move to leave. through the field I crossed earlier, and the m en string out across the path. They fol l ow m y trai l step up b esi d e me a nd f all b a c k. They jostle e ac h ot h er a s i f com p et i ng f or an e ndangered species. Q chat, to flirt, to t hese women are e y have become g, t h eir va l ue ris a n d in t h e eveh e men rush to a ck to summer o ne ni g ht. I a sk m e at dinner i f d udes,ÂŽ the ÂA tot al an yi eld e rh e s t I k o y f h t a “They follow my trail, step up beside me and fall back...” PAGE 25 FLORIDA WEEKLY WEEK OF AUGUST 25-31, 2011 ARTS & ENTERTAINMENT A25 toward the end of 2009, and ÂI felt like I needed to be recharged creatively,ÂŽ she recalls. ÂI wanted to start a project that would challenge me creatively in a different way than what I do every day, which is draw and paint.ÂŽ She also planned to document it on the Internet, so sheÂd be held account-able. She entertained a few ideas, but the one that appealed the most was taking a photograph every day of one of her col-lections and posting it online. On occa-sion, sheÂd draw or paint an imaginary collection. So Ms. Congdon began Collectionaday. com, posting a different photograph or drawing daily, throughout 2010. She went from Day 1 (20 vintage erasers) to Day 365 (seven New YearÂs party favors.) In between, 362 other odd assortments include the plastic baby arms and vintage pool cue chalks, golf tees, bread bag ties, shoelaces, bob-bins, napkin rings, wooden and plastic clothespins, sales receipts, bingo cards, thread, twigs, feathers, river stones, old signage, sepia photographs, cookie cut-ters, paint brushes, matchboxes, hat pins and mid-century kitchenware. The website drew thousands and, a few months into the project, garnered national press. Ms. Congdon was on an NPR photo blog, quoted in a New York Times article about the lure of objects and featured in the February 2011 issue of Martha Stewart Living magazine, which flew her and her Scandinavian kitchenware to New York City to be pho-tographed. (Martha Stewart collects old brass plates or platters, Ms. Congdon says. Other collectors featured in the article amassed vintage metal dollhouses, sew-ing patterns and travel books.) Midway through the year, she signed a book deal, though that hadnÂt been her goal in starting the blog. ÂA Collection a DayÂŽ was released by the Canadian publisher Uppercase ear-lier this year. In 400-plus pages, the book contains all 365 collections, as well as some introductory essays. It comes in its own collectible tin. ÂItÂs the size of a brick,ÂŽ Ms. Congdon says. ÂSmall and thick.ÂŽ Signed copies can be purchased for $35 at collectionaday.bigcartel.com.Evoking nostalgiaThe images are visually intriguing, the subject matter unexpected. Ms. CongdonÂs work reminds you of what it was like to be a kid, when the world was new and everything was infinitely fascinating. She plays with color and pattern, group-ing her collections in various ways: by color, by shape, by size, by purpose. ÂFor the most part, I was grouping by the thing it was,ÂŽ she says. Many of the objects are vintage.ÂI think old things are appealing because they evoke some kind of nostal-gia, or they remind people of things that we donÂt do anymore, like letter writing by hand,ÂŽ she says. ÂOr maybe people are just attracted to things that people used to use a lot: school supplies or sewing suppliesƒ. I think everyoneÂs come into contact with them, at some point.ÂŽ Younger generations, people in their 20s or early 30s, probably donÂt have a relationship to a lot of things in the book, she says. ÂBut if youÂre over 30 or 35, either you used something I pho-tographed, or you knew someone who did: ÂOh, I remember my grandmother used to have those needle packs in her sewing basket. Or, ÂI remember I used those crayons in school.ÂÂŽGrouping is keyThe other reason people are drawn to these collections is because of how theyÂre arranged, she theorizes. Â(Some are) ordinary things that by themselves wouldnÂt be that interesting, but put them together in a group and arrange them in an interesting way, and all of a sudden youÂve got a work of art,ÂŽ she says. A collection of plastic leaves recalls Matisse cutouts. Twine wrapped around cardboard look like a fiber art piece. Two rows of pink and red vin-tage golf tees look like an exhibit of alien teeth from some futuristic nature museum. And four plastic wishbones in a row could pass for a minimalist sculpture. Other common items among Ms. CongdonÂs collections: twigs, river stones, rolls of colored tape, paintbrushes. She has a keen eye for composition and color; the way she groups her items makes viewers pay new attention to old objects. As a child, she had a couple of collections. Her first was Madame Alexander dolls, gifts from her mother and then her grandmother. ÂI never had more than six or seven of them,ÂŽ she says. She also collected plastic horses. ÂI was really into collecting and arranging things in my room. My mother always used to nag me to clean my room, and by that, she meant: Take things off the floor, make my bed, vacuum. ÂBut my favorite part was to take everything off the shelf, dust them, and put them back. That was the only part I enjoyed. I think that stuck with me through-out my life.ÂŽ Of all her collections, Ms. CongdonÂs mid-century Scandinavian kitchenware is her favorite.A guiding principleFor her blog, she had a rule: All the photographed collections had to be hers. She wouldnÂt borrow a collection from anyone. ÂMy friends would say, ÂI have a collection of such-and-such. Why donÂt you borrow it and photograph it? and I would say, ÂNot unless you want to give it to me. I have to own everything.ÂÂŽ A few people did give her collections, including an array of light bulbs. Ms. Congdon photographed them and also drew a picture of them for her book. ÂI loved how they came out in the pho-tograph,ÂŽ she says, adding sheÂd collect more light bulbs if she had a place to display them. ÂTheyÂre hard to find,ÂŽ she says. ÂItÂs sculptureƒ theyÂre really beautiful: very thin glass, and they have beautiful wire inside.ÂŽCollecting and creatingAs an artist and illustrator, Ms. Congdon, is in good company; many artists collect images and objects, keeping them in their studios. ÂI think thereÂs a connection, whether itÂs physical, or photographing them, or visually memorizing them, between collecting and the creative process,ÂŽ she says. ÂItÂs where we get our inspira-tion „ from looking at things. ItÂs what evokes memories or emotions for us. Music and smell do that, too.ÂŽ She counts among her clients Poketo for Target, Urban Outfitters, American Greetings, Harper Collins, Random House, Chronicle Books and Trader JoeÂs. She did 150 illustrations for ÂThe Dictionary of Extraordinary Ordinary Animals,ÂŽ scheduled for release Sept. 27 by Running Press. But doing the blog and the ÂCollection a DayÂŽ book was Âa really interest-ing ride,ÂŽ she says. SheÂs thinking about doing another Âyear-ofÂŽ project in 2012 and posting it on the Web, but it wonÂt be related to collections. ÂI feel that this particular project is done,ÂŽ she explains. ÂI did enjoy what I set out to do. I didnÂt set out to publish a book or make a blog people would enjoy visiting. For me, it was a personal creative challenge. Even though all these other things happened, I still feel like in the end, the personal creative challenge was valuable, and one of the best things to come out of it.ÂŽ Q COLLECTIONFrom page 23 COURTESY PHOTOAbove: Artist Lisa CongdonÂ’s homeLeft: Day 187Below: Ms. CongdonÂ’s website led to a book deal. PAGE 26 FLORIDA WEEKLYA26 ARTS & ENTERTAINMENT WEEK OF AUGUST 25-31, 2011 WHAT TO DO, WHERE TO GO Thursday, Aug. 25 Q Story time session at the Loxahatchee River Center – 9:30 a.m. Thursdays, Burt Reynolds Park, 805 N. U.S. 1, Jupiter. Call 743-7123 or visit. Q Pre-School Storytime – Featuring a story and an activity, 10 a.m. Aug. 25 at the Lake Park Public Library, 529 Park Ave., Lake Park. Free; 881-3330. Q Bonerama – Founded by Mark Mullins and Craig Klein, former mem-bers of Harry Connick Jr.Âs Big Band, Bonerama claims to carry the brass band concept to places unknown. The band plays at 8:30 p.m. Aug. 25 at the Bamboo Room, 25 S. J St., Lake Worth. Tickets: $22; 585-BLUE or brassfunkrock.event-brite.com. Q MosÂ’Art Theatre – Screenings of ÂRejoice & Shout,ÂŽ at 3:30 p.m., and ÂTabloid,ÂŽ at 6 p.m. Aug. 25. Tickets: $8. 700 Park Ave., Lake Park; 337-6763. Q Sailfish Marina Sunset Celebration – Shop for arts and crafts made by artists from around the coun-try, 6 p.m. Aug. 25, Sailfish Marina, east of the Intracoastal, just south of Blue Heron Boulevard, Palm Beach Shores; 842-8449. Q Lionfish Lecture – Learn how you can safely filet a lionfish for con-sumption. Randy Jordan, inventor of the ÂLion Tamer,ÂŽ will speak about the invasion of these nonnative fish on local reefs. Presenter Zack Jud will share research emphasizing the impact of lion-fish on the Loxahatchee River. Guests can enter drawings for prizes and snack on tasty fare. ItÂs 6-8:30 p.m. Aug. 25, Loggerhead Marinelife Center, 14200 U.S. 1, Juno Beach. RSVP to Rebecca Scarbrough, 627-8280, Ext. 107, or rscar-brough@marinelife.org. Q Christian Finnegan – The comic performs at various times Aug. 25-28 at the Palm Beach Improv, City-Place, West Palm Beach. Tickets: $15; 833-1812 or. Friday, Aug. 26 Q MosÂ’Art Theatre – Screenings of ÂInterruptersÂŽ and ÂNames of L ove,ÂŽ various times Aug. 26-Sept. 1. Family film: ÂSita Sings the Blues,ÂŽ 1 p.m. Aug. 31. inter-active fountain show. Member admission: adults, $6.95; children 12 and under, free. Non-member admission: adults, $11.95; children 3-12, $6.95; children 2 and under, free; 547-9453. Q Sunset Celebration – There will be arts and crafts exhibitors, music, food and cash bar from 6-8 p.m. Aug. 26 (the last Friday of the month) at Lake Park Marina, 105 Lake Shore Drive, Lake Park; 881-3353. Q DowntownÂ’s Weekend Kickoff – Singers perform 6-10 p.m. Fridays. Aug. 25: Pee Wee Lewis & The Hues. Downtown at the Gardens Centre Court, 11701 Lake Victoria Gardens Drive, Palm Beach Gardens; 340-1600. Q Ariana Savalas – The daughter sci-ence classification rehabilitation. Then, the group tags their turtles with a unique number and mimics a successful sea turtle release into the ocean. To be held at 3:30 p.m. Wednes-days and Fridays, and at 11 a.m. 1 p.m. and 2 p.m. Saturdays. Admission is free; 14200 U.S. 1, Juno Beach; 627-8280. Q GardensArt – ÂCreative Focus,ÂŽ photography and digital art by Melinda Moore, through Aug. 25, Palm Beach Gar-dens City Hall Lobby, 10500 N. Military Trail. Free; 630-1100.-stall its galleries of European and Ameri-can art. Museum is at 1451 S. Olive Ave., West Palm Beach. Art After Dark, with music, art demonstrations, is 5-9 p.m. Thursdays. Admission: $12 adults, $5 visi-tors 13-21; free for members and children under 13. Hours: 10 a.m.-5 p.m. Tuesday-Saturday; 1-5 p.m. Sunday; 10 a.m.-9 p.m. second Thursday of the month. Closed Mondays and major holidays;. Q Society of the Four Arts – Museum, library and gardens are at 2 Four Arts Plaza, Palm Beach. Admission: Free to members and children 14 and under, $5 general public; 655-7226. Q Exhibition of Paintings and Drawings by Pamela Larkin Caruso – Features botanicals and hearts, through Aug. 31. Eissey Campus of actor Telly Savalas performs Aug. 26-27 and Sept. 2-3 at The ColonyÂs Royal Room, 155 Hammon Ave., Palm Beach. Doors open at 6:30 p.m. and show starts around 8 p.m. Cost: $110 for dinner and show; $70 for show only. 659-8100. Q Tinsley Ellis – The hard-rocking blues guitarist plays a show at 9 p.m. Sept. 26 at the Bamboo Room, 25 S. J St., Lake Worth. Tickets: $18 and $23; 585-BLUE or eventbrite.com. Saturday, Aug. 27 Q Summer Green Market – 8 a.m.-1 p.m. Saturdays through August at STORE Self Storage, 11010 N. Military Trail, Palm Beach Gardens; 627-8444. Q Kids Story Time – 11:30 a.m. Saturdays, Loggerhead Marinelife Center, 14200 U.S. 1, Juno Beach. Free; marinelife.org. Q Celebrate Saturdays at Downtown – Singers perform 6-10 p.m. Saturdays. Aug. 27: Strangers Play-ground. Downtown at the Gardens Cen-tre Court, 11701 Lake Victoria Gardens Drive, Palm Beach Gardens; 340-1600. Q “Forever Plaid” – The revue focuses on four young singers killed in a 1950s car crash while on the way to their first big concert. ItÂs 2 and 7 p.m. Aug. 27, 2 p.m. Aug. 28, 7 p.m. Sept. 2, 2 and 7 p.m. Sept. 3 and 2 p.m. Sept. 4 at the MosÂArt Theatre, 700 Park Ave., Lake Park. Tick-ets: $20; 337-6763. Q The Jove Comedy Experience – The Jove Comedy Experience will perform ÂThe Welcome Back Show,ÂŽ a look at the return of school, hurricanes and snowbirds. ItÂs at 8 p.m. Aug. 27, The Atlantic Theater, 6743 W. Indiantown Road, Jupiter. Tickets: $15 advanced and $17 at the door. Call 575-4942 or visit. Q Daryl Hance – Most recently known as the guitarist for J.J. Grey and Mofro, Daryl Hance and special guests the Matt Farr Band play a show at 9 p.m. Aug. 27 at the Bamboo Room, 25 S. J St., Lake Worth. Tickets: $12; 585-BLUE or eventbrite.com. Tuesday, Aug. 30 Q Raising Confident, Competent Children Workshop – Sponsored by Bridges at Lake Park at 5:30 p.m. Aug. 30, Lake Park Public Library, 529 Park Ave., Lake Park. Refreshments and raffle included. Free; 881-3330. Q Matt Nathanson – With Train and Maroon 5, 7 p.m. Aug. 30, Cru-zan Amphitheatre, South Florida Fair-grounds, suburban West Palm Beach. Tickets: $13-$79.50; 795-8883 or ticket-master.com. Wednesday, Aug. 31 provides free Christian counseling, classes and support groups; 624-4358. Q Hatchling Tales – 10:30-11:30 a.m. Wednesdays, Loggerhead Marinelife Center, 14200 U.S. 1, Juno Beach. Free; marinelife.org. Q Basic Computer Class – Noon-1:30 p.m. Aug. 31 at the Lake Park Public Library 529 Park Ave., Lake Park. Free; 881-3330.e – k t g 9 k d d d o s : s d 8 a a f ( c a Q Q – i e E i s t m c L i a w e c t t COURTESY PHOTO Frank Licari (left) and Jesse Furman perform as The Jove Comedy Experience on Saturday at The Atlantic Theater in Jupiter. PAGE 27 Theatre lobby gallery, Palm Beach State College, Palm Beach Gardens. Gallery is open 11 a.m.-4 p.m. Monday-Friday and at all performances; 207-5905. Q The Art Gallery at Eissey Campus – ÂCollective Synergy,ÂŽ juried exhibition by members of the Palm Beach County Art Teachers Association, through Sept. 2, Palm Beach State Col-lege, Palm Beach Gardens. Free; 207-5015. September events Q The Legendary JCÂ’s – The Southern soul revue plays a show at 8:30 p.m. Sept. 1 at the Bamboo Room, 25 S. J St., Lake Worth. Tickets: $10; 585-BLUE or eventbrite.com. available at. Free for 16 and under. Early admission at 9 a.m. Sept. 3 is $10, good both days; (941) 697-7475. Q Learn to Kayak! – Representatives from Adventure Times Kayaks will teach a land-based course that gives beginners the skills necessary for kaya-king. Go Blue Awards Luncheon Kick-off – The Blue Friends Society of Loggerhead Marinelife Center will host a kick-off for the 3rd Annual Go Blue Awards Luncheon from 5:30-7:30 p.m. Sept. 8, at PGA National Resort & SpaÂs I-Bar. In addition to revealing the 2011 Go Blue Award Finalists, the event will feature hors dÂoeuvres and cocktails. The Go Blue Awards recognize leaders in ocean conservation. Proceeds will benefit Loggerhead Marinelife Center. Free for Blue Friends members, $25 for guests; 627-8280. Q Reading with a Ranger – Join park staff and listen to the reading of an environmental childrenÂs story. Partici-pate in activities and meet all the animals in our nature center. Reservations recom-mended. ItÂs at 10:30 a.m. Sept. 8 at John D. MacArthur Beach State Park, State Road A1A, on Singer Island, North Palm Beach. Free with park admission; 624-6952. Q Fashion Night Out – Enjoy a night of shopping, complimentary cock-tails, light bites, live music and give-aways. More than 45 high-end retailers will participate in this global salute to the fashion industry. 6-9 p.m. Sept. 8 at The Gardens Mall, Palm Beach Gardens. Free; 775-7750 or visit thegardensmall.com. Q Butterfly Walk – Join a park ranger on a walking tour through one of South FloridaÂs last remaining hard-wood hammocks. There will be sev-eral species of butter flies to identify and observe. Also, learn which plants attract these winged wonders to your backyard, 11 a.m. Sept. 10 at John D. MacArthur Beach State Park, State Road A1A, on Singer Island, North Palm Beach. Free with park admission; 624-6952. Q Everything Orchids; A Shady Affair Plant Sale – This weekend event showcases a select number of top orchid and shade plant growers, artists, and craftspeople that will share their knowledge and passion for orchids and plants. There will be lectures and a silent auction, 10 a.m.-4 p.m. Sept. 10-11, Mounts Botanical Gardens, 531 N. Military Trail, West Palm Beach. Free for members, $5 for nonmembers; 233-1757 or. Q Bluegrass Music with the Conch Stomp Band – Listen to the Conch Stomp Band play a variety of bluegrass songs. Fun for all ages. ItÂs 2-4 p.m. Sept. 11 at John D. MacArthur Beach State Park, State Road A1A, on Singer Island, North Palm Beach. Free with park admission; 624-6952. Q River Totters Arts nÂ’ Crafts –9 a.m. second Wednesday of each month (next session is Sept. Sept. 14) at the Jupiter Community Center, 200 Military Trail, Jupiter. Call 746-7363. Q Pre Gala Event – For Cancer Alliance of Help & Hope, 6-8 p.m. Sept. 15 at The Gardens Mall, Nordstrom Court, Palm Beach Gardens. Tickets: $25 each; free for kids under 12. To pre-purchase tickets to be entered into a drawing for a BRIO dinner for 10, e-mail katie@a1moving.com. Sponsored by Brio Tuscan grille and The Gardens Mall. All proceeds will benefit the CAHH. Q Monthly Blue Friends Beach Cleanup – 8 a.m. Sept. 17, Loggerhead Marinelife Center. Join the Blue Friends Society for the monthly beach cleanup and enjoy breakfast by Whole Foods. ItÂs at Loggerhead Park, 14200 U.S. 1, Juno Beach. E-mail bluefriends@marinelife.org to RSVP for your family, friends or group. Q Farm-Your-Backyard / Vegetable Garden – Horticulturist Mike Page and Arthur Kirstein, coordi-nator of Agricultural Economic Devel-opment, will teach this hands-on work-shop on how to successfully grow your own vegetables. This programÂs focus is on establishing and managing small veg-etable projects. Tips on site preparation, seedling establishment, planting, main-tenance and harvesting will be covered. 9 a.m.-2 p.m. Sept. 17, Mounts Botanical Garden, Exhibit Hall A, 531 N. Military Trail, West Palm Beach. $30 for mem-bers, $40 for nonmembers; 233-1757 or. Q “The Good Times are Killing Me” – High school students produce Lynda BarryÂs play about 1960s racial tensions at 7:30 p.m. Sept. 17 at the Maltz Jupiter Theatre, 1001 E. Indi-antown Road, Jupiter. Tickets: $15 for students and $20 for adults; 575-2223 or. Q Middle School Lock-In – The second annual event for Jewish sixththrough eighth-grade students will be at 8 p.m. Sept. 17 at the Doubletree Hotel, 4431 PGA Blvd. in Palm Beach Gardens. The sleepover event is sponsored by the Jewish Federation of Palm Beach CountyÂs Jewish Teen Initiative. There will be snacks, games, transportation to and from the event, and a light breakfast on Sept. 18 will be included. Cost of the event is $25 if registered and paid for by Sept.12. The cost increases to $35 after Sept. 12. Registration and transportation schedule is available at. Call 242-6630 or e-mail Adri-enne.Winton@JewishPalmBeach.org. Q The Country Comedy Tour –Mg Gaskin and Matt Mitchell, aka ÂCasio Kid,ÂŽ bring their own brand of south-ern flavor to their insights on everyday life. The show is suitable for all ages. 8 p.m. Sept. 17, Atlantic Theater, 6743 W. Indiantown Road, Jupiter. Tickets: $20 in advance or $25 at the door; family pack of tickets also is available. Bring your entire family (up to five people) for $60; 575-4942 or.„ Please send listings for the calendar to pbnews@floridaweekly.com and ssimmons@floridaweekly.comWHAT TO DO, WHERE TO GO e s d y m e 0 J E e A Q C M a a B t Q e M n o o o e t 9 T COURTESY PHOTO Matt Nathanson — 7 p.m. Aug. 30, Cruzan Amphitheatre, South Florida Fairgrounds, suburban West Palm Beach. Tickets: $13-$79.50; 795-8883 or ticketmaster.com.FLORIDA WEEKLY WEEK OF AUGUST 25-31, 2011 ARTS & ENTERTAINMENT A27 PAGE 28 FLORIDA WEEKLYA28 ARTS & ENTERTAINMENT WEEK OF AUGUST 25-31, 2011 Contrary to what ÂTwilightÂŽ fans believe, vampires are not constipat-ed teenagers who yearn for whiney women with the personality of a damp mop. Rather, vampires in their pur-est, most villainous cinematic form are hunters who prey on innocent human blood. Thanks to Colin FarrellÂs chilling performance, ÂFright NightÂŽ has a bad boy vamp thatÂs so different from ÂTwi-lightÂŽ heÂll have you believing vampires are cool again. On the outskirts of Las Vegas, Charley (Anton Yelchin) lives with his mom (Toni Colle tte) in a quiet suburban neighborhood. Their new neighbor, Jerry (Mr. Farrell), seems nice enough, though CharleyÂs friend Ed (Christo-pher Mintz-Plasse) thinks Jerry is a vampire because his windows are shut-tered and he only comes out at night. But this is Vegas, and Jerry works nights on the strip and sleeps during the day, we learn. IÂll bet he does. Once Charley discovers Jerry is a vampire, an interesting game of cat-and-mice ensues, as CharleyÂs girlfriend Amy (Imogen Poots) also gets danger-ously involved. Thankfully, a scene in which Charley sneaks around JerryÂs house plays with tension rather than predictability, even though someone with JerryÂs heightened sense of smell and hearing should obviously know heÂs there. For help, Charley consults with vampire expert Peter Vincent, whoÂs played by David Tennant as a cross between LA TEST FILMS ‘Fright NightÂ’ +++ Is it worth $14? NoIs it worth $10? Yes b e w m e h dan HUDAK O Russell Brand, Jack Sparrow and Criss Angel. ItÂs an odd combination, I grant you, but it provides a certain kookiness that offsets the dangerous fight for survival. The film is being released in 3D, and to see it in that format is a mistake. HereÂs a rule for any filmmaker or studio wanting to release a movie in 3D: If most of the story takes place at night, donÂt use 3D. Far too many the-aters still project 3D without enough light, meaning the image is darker than it should be. As a result, the visuals in ÂFright NightÂŽ donÂt resonate with the depth thatÂs intended, and the appeal of the format is lost. This is especially a shame because director Craig Gillespie clearly has fun with the 3D by spraying blood and having numerous objects hurl toward the screen. If only we could see them better. Seeing the film in regular 2D will also allow you to appreciate Mr. GillespieÂs craftsmanship. Note the little touches: The way he uses eerie music every time Jerry speaks, the quick flashes of visual effects before a vampire takes a bite „ flourishes like this make the film more dynamic and engaging and, therefore, more enjoyable.WhatÂs more, the best scene comes as Charley, his mother and Amy are escaping Jerry, and an unbroken shot holds much longer than we expect as it moves the camera around the car with ease.Whether you like the film or not, itÂs hard to dispute that itÂs very well made.Because ÂTwilightÂŽ has literally sucked the fun out of vampire movies, itÂs refreshing to see some fang-toothed predators on the prowl as we do in ÂFright Night.ÂŽ This is nicely crafted, escapist nonsense fun. Q „ Dan Hudak is the chairman of the Florida Film Critics Circle and a nationally syndicated film critic. You can e-mail him at dan@hudakonhollywood.com and read more of his work at. FLORIDA WEEKLY WEEK OF AUGUST 25-31, 2011 A29 1/2 PRICE SALE BUY 3 & GET A 4TH FREE PLUS Luxury Comfort Footwear FAMILY OWNED and OPERATEDMilitary Trail and PGA Boulevard, Palm Beach Gardens x£‡xࣣU…œi>'>Vœ“ OPEN 10-6 MONDAY THRU SATURDAY PUZZLE ANSWERS ÂThe Good Times are Killing Me,ÂŽ a coming-of-age story about interracial conflict and the friendship between two girls. The show will pre-miere at 7:30 p.m. on Sept. 17. A poignant drama, Lynda BarryÂs first play is about Edna, a pre-adolescent girl of the mid-1960s who believes in racial har-mony and develops an interracial friend-ship with Bonna, the girl next door. Life changes as the accelerating civil rights movement converges on the streets of her neighborhood, as soul music provides a soundtrack for the storyÂs laughter, bitter-ness and heartbreak. The student team auditioned more than 50 young aspiring performers and cast 22 local actors ages 8-18. Part of the TheatreÂs Emerging Artist Series, the show is sponsored in part by Betty and Rodger Hess, Tamar and Mil-ton Maltz, Bonnie and John Osher, The Roy A. Hunt Foundation and Muriel and Ralph Saltzman. Tickets are $15 for students and $20 for adults. Call 575-2223 or see jupitertheatre.org. The production includes strong lan-guage and adult subject matter. Q Student production Sept. 17 At Maltz Jupiter Theatre 1132 W. Indiantown Road, Jupiter 561.575.4700 • Monday–Saturday 8am–7pm • Sunday 9am–5pm FREE 8-OZ. CUP OF FRESHL Y BREWED COFFEE WITH ANY PURCHASE!“A Taste of Home in Every Bite!” PAGE 30 FLORIDA WEEKLYA30 ARTS & ENTERTAINMENT WEEK OF AUGUST 25-31, 2011 (Jan. 5). But look for Wanda Sykes and Larry the Cable Guy (Dec. 11 and Nov. 19, respectively). ÂWeÂre going from Larry the Cable Guy to Wanda Sykes,ÂŽ said Lee Bell, senior director of program-ming. ÂThatÂs pretty extreme.ÂŽ Look for a lot of new acts this season. ÂWe have 18 new shows that have never been here before in Dreyfoos Hall,ÂŽ Mr. Bell said. ÂIÂm very happy with the diversity of the overall season.ÂŽ That season also includes Hasidic reggae singer Matisyahu (Dec. 29) and the Lennon Sisters (Jan. 25). It comes down to research, he said.ÂWe did a marketing survey and Broadway and comedy seemed to be at the top of the list,ÂŽ Mr. Bell said. ÂWe have pulled together a season with that in mind, since weÂve done that market-ing survey.ÂŽ And since the Kravis took over the booking of its Broadway series, it has managed to score some first-run shows. ÂÂThe Addams Family is a first-run show, as is ÂCome Fly Away,ÂÂŽ he said. ÂLa Cage aux FollesÂŽ will star local favorite George Hamilton as Georges, and Chris-topher Siber recently signed on as Albin. ÂCome Fly Away,ÂŽ based on the music of Frank Sinatra, should hold appeal to a couple of generations of theatergoers. ÂThe music is live, performed to FrankÂs voice. ItÂs just astounding,ÂŽ Mr. Bell said. ÂYou kind of feel like youÂre there. ItÂs like the Elvis show they did years ago, with Elvis voice and the original band members playing in sync to the screen.ÂŽ Only there is no screen, and dancers step to the choreography of Twyla Tharp. ÂAnd Twyla Tharp continues to do great work,ÂŽ he said.Regional Arts changesVeterans of the Kravis CenterÂs Regional Arts clas-sical music season may have noticed the absence of solo vocalists on the program. ÂWith Regional Arts, that audience wants orchestras,ÂŽ Ms. Mitchell said. Well, that and it seems opera sing-ers are no more immune to colds and sore throats than their audi-ences during the winter season. Soprano Deborah Voigt had to cancel a few years ago, as did tenor Salvatore Licitra, who provided a memorable make-up concert „ and even then he sang over a cold. Look for some choral works this time around. ÂThereÂs a lot going on,ÂŽ Mr. Bell said. ÂRegional Arts „ theyÂre doing the Mozart Requiem with the Munich Symphony. ItÂs a very strong Regional Arts series, with the Cleveland Orches-tra and Joshua Bell.ÂŽ And it doesnÂt hurt that the past two seasons, Regional Arts has had a strong presence with music journalist Sharon McDaniel, who helps coordinate the series, writes the program notes and gives pre-performance lectures. ÂSharon is doing a fabulous job,ÂŽ Mr. Bell said. ÂWith her pre-concert dis-cussions and the program notes that she composes, it all adds to the appeal of Regional Arts.ÂŽKravis season evolvesWhen the Kravis Center opened in 1992, it had a strong mix of pop and classical elements. Its opening night included performances by Ella Fitzger-ald, Isaac Stern and Leontyne Price. ÂOur goal is always something for everybody,ÂŽ Ms. Mitchell said. ÂWeÂre not really known as a dance house or an opera house.ÂŽ Mr. Bell agrees.ÂYou have to be careful not to push too far out at a performing arts center like the Kravis,ÂŽ he said, adding, ÂItÂs been a challenge, especially over the past two, three years with the econo-my. We have done very well over the past few years.ÂŽ And that is despite a growing national trend of declining subscriptions, though Mr. Bell says theyÂre beginning to increase again. ÂThat trend is across the board, I believe,ÂŽ Mr. Bell said. ÂPeople just donÂt want to plan that far in advance. They donÂt want to etch in their calen-dars six months, eight months down the road.ÂŽ If there is one thing Mr. Bell knows, it is his audience. How long has he been there now?ÂItÂll be 15 years in March. My hair is white now,ÂŽ he said with a laugh. ÂI know which shows will be our chal-lenges, and which will require an extra push to get seats sold. After being here for so long you kind of know what the community standard is.ÂŽ Ms. Mitchell jokes that she has been at the Kravis since she was 12. ÂThis season is our 20th season and yeah, itÂs hard to imagine. Time flies when youÂre having fun,ÂŽ she said. ÂIÂm starting to feel really dated. That means IÂve been here 22 years now.ÂŽ But after 22 years, there still is a certain frisson to her job. ÂI look forward to it all the time,ÂŽ she said. ÂThere is lots to do, trying to stay up with what the community expects.ÂŽ And that is a reflection of the times.ÂObviously in this economy, itÂs a challenge,ÂŽ she said. ÂNobody is on autopilot here. Everybody is working pretty hard.ÂŽ Q 20THFrom page 1 The CEOÂ’s picks >> Here are ve shows Kravis Center CEO Judy Mitchell says you shouldn't miss:1. Straight No Chaser2. Pink Martini — "It's one that everyone may not necessarily know but shouldn't be missed."3. k.d. lang. — "Her voice is incredible."4. Diana Krall — "Another one that is just over the top. A terri c, wonderful evening."5. Benise — "A sleeper." Ms. Mitchell also says she is especially looking forward to "Peppino D'Agostino, a guitarist that is wonderful. And Chris Botti, our gala performer. Last year, he just did a fabulous, fabulous performance."MITCHELL BELL The Addams Family plays Nov. 8-13 Pink Martini plays April 7 Diana Krall plays Feb. 11 k.d. lang opens the season Oct. 6 PAGE 31 FLORIDA WEEKLY WEEK OF AUGUST 25-31, 2011 ARTS & ENTERTAINMENT A31 Q Broadway Series „ The season kicks off with ÂThe Addams Family,ÂŽ from Nov. 8-13. The Public TheaterÂs new Tony-winning production of ÂHairÂŽ follows from Jan. 10-15. After that, from Feb. 14-19, is the Tony-win-ning revival of ÂLa Cage aux Folles,ÂŽ starring Palm BeachÂs own George Hamilton. ÂCome Fly Away,ÂŽ the musi-cal with choreography by Twyla Tharp and music made famous by Frank Sina-tra, is set for March 13-18. The Kravis Center wraps up its season with the 25th anniversary production of ÂLes Misrables,ÂŽ from May 16-26. Q Dreyfoos Hall „ The Kravis CenterÂs 20th anniversary season begins Oct. 6 with k.d. lang and the Siss Boom Bang. Other acts this sea-son include Huey Lewis & The News (Nov. 3), Benise, The Spanish Guitar (Nov. 6), Matisyahu (Dec. 29), Michael Feinstein (Feb. 3), Patti LaBelle (Feb. 4) Bernadette Peters (Feb. 10), Diana Krall (Feb. 11), Patti LuPone (April 4), Pink Martini (April 7) and ManalapanÂs own Yanni (April 17-18). Trumpeter Chris Botti plays the gala (March 3). The season is especially comedy-heavy this year, with such comedians as Larry the Cable Guy (Nov. 19), Wanda Sykes (Dec. 11), Dennis Miller (Jan. 5), Jackie Mason (Jan. 31) and Martin Short (March 28). Q Regional Arts „ The classical music series opens with performances by the Munich Symphony Orchestra with Philippe Entremont (Nov. 15-16). Also on the bill are the Royal Philhar-monic Orchestra with Pinchas Zuker-man (Jan. 4-5), the Cleveland Orchestra with Franz Welser-Mst (Jan. 25), vio-linists Joshua Bell (Jan. 31) and Itzhak Perlman (March 6). Q Helen K. Persson Hall „ The intimate space is set up with cabaret seating. The season begins with Con-nie James singing works from the Great American Songbook (Nov. 25-26). Highlights include performances by The Nylons (Jan. 6-7), guitarist Pep-pino DÂAgostino (March 1-2) and caba-ret veterans Steve Ross, Anna Berg-man, Billy Stritch and Klea Blackhurst in ÂHe Loves ƒ and She LovesÂŽ (Feb. 24-25). Q The Rinker Playhouse „ Lee Bell, the Kravis CenterÂs senior direc-tor of programming, still is booking acts to fill time slots in the black-box theater in the aftermath of Florida StageÂs closing. Highlights so far include Capitol Steps (Feb. 28-March 11), ÂImagined: Celebrating the Songs of John Lennon,ÂŽ performed by The Nu-Utopians (Feb. 25) and SethÂs Big Fat Â70s Show (March 30-31). Q Family Fare „ The kid-friendly series opens with ÂKnuffle Bunny: A Cautionary MusicalÂŽ (Oct. 8), and also includes Sesame Street Live in ÂElmoÂs Super HeroesÂŽ (Oct. 15-16) and Clifford the Big Red Dog Live! (May 5). Q Adults at Leisure Series „ The matinee series of shows offers a touch of nostalgia. The Jimmy Dorsey Orchestra and The Pied Pipers open the series on Dec. 6. The series also includes The Lennon Sisters (Jan. 25), Marilyn McCoo & Billy Davis Jr. (Feb. 5) and the New Shanghai Circus (March 6). Q Young Artist Series „ This series brings to the fore developing classical musicians. Among them: Croatian guitarist Robert Belini (Nov. 21), violinist Hye-Jin Kim (Jan. 9), Van Cliburn Piano Competition winner Haochen Zhang (Feb. 23) and the trio Phoebus Three (March 12). Q Kravis CenterÂ’s 2011/2012 season offers a mix: HereÂ’s a look >> The Kravis Center for the Performing Arts is at 701 Okeechobee Blvd., West Palm Beach. Individual tickets to Kravis Center 2011/2012 season shows go on sale at 9 a.m. Sept. 24. For information, call 832-7469 or go online to. O in the know COURTESY PHOTOThe Kravis Center opened in 1992 in West Palm Beach. It presents classical and popular music, dance, theater and other performa nces. COURTESY PHOTOBenise, The Spanish Guitar brings an evening of so-called “nouveau flamenco” music to the Kravis Center on Nov. 6. He starred in a PBS special titled “Nights of Fire!” PAGE 32 FLORIDA WEEKLYA32 ARTS & ENTERTAINMENT WEEK OF AUGUST 25-31, 2011 20% OFFPROGRAM FEENew clients onlySuccessful Weight Loss Center 0'!"OULEVARDs3UITE 0ALM"EACH'ARDENSsrWith this coupon. Not valid with other offers or prior purchases. Offer expires 9-1-11. 690.05(3/*.+0,;653@>,,2/*.^PSS• Reshape your body• Get rid of abnormal fat• Increase your metabolism• Eliminate food cravings Successful Weight Loss Center 0'!"LVD3TE Palm Beach Gardens249-3770 Over 15 years of experience in family law• Custody • Visitation • Division of property • Relocation • Alimony and child support • Modi cations of prior Final Judgments • Mediator • Guardian Ad Litem 11380 Prosperity Farms RoadSuite 118, Palm Beach Gardens (561) 624-4900apastor@andrewpastorlaw.comFL Bar No. 95140 Andrew E. Pastor, P.A. • Divorce Attorney W SEE ANSWERS, A29W SEE ANSWERS, A292011 King Features Synd., Inc. World rights reserved. 2011 King Features Synd., Inc. World rights reserved.FLORIDA WEEKLY PUZZLES HOROSCOPES THEIR SONGS By Linda Thistle Q VIRGO (August 23 to September 22) Ease up and stop driving yourself to finish that project on a deadline that is no longer realis-tic. Your superiors will be open to requests for an extension. Ask for it. Q LIBRA (September 23 to October 2 2) You should soon be hearing some positive feedback on that recent business move. An old family problem recurs, but this time youÂll know how to handle it better. Q SCORPIO (October 23 to N o vember 2) Some surprising statements shed light on the problem that caused that once-warm relationship to cool off. Use this newly won knowl-edge to help turn things around. Q SAGITTARIUS (November 22 to December 21) Your spiritual side is especially strong at this time. Let it guide you into deeper contemplation of aspects about yourself that youÂd like to understand better. Q CAPRICORN (December 22 to January 19) Your merrier aspect continues to dominate and to attract folks who rarely see this side of you. Some serious new romancing could develop out of all this cheeriness. Q AQUARIUS (January 20 to F e bruary 18) YouÂre always concerned about the well-being of oth-ers. ItÂs time you put some of that concern into your own health situ-ation, especially where it involves nutrition. Q PISCES (February 19 to March 20) J ust w hen you thought your life had finally stabilized, along comes another change that needs to be addressed. Someone you trust can help you deal with it successfully. Q ARIES (March 21 to April 19 ) As t ensions ease on the home front, you can once more focus on changes in the workplace. Early diffi-culties are soon worked out. Stability returns as adjustments are made. Q TAURUS (April 30 to May 20) A new romance tests the unattached BovineÂs patience to the limit. But Venus still rules the Taurean heart, so expect to find yourself trying hard to make this relationship work. Q GEMINI (May 21 to June 20) ItÂs a good time to consider homerelated purchases. But shop around carefully for the best price -wheth-er itÂs a new house for the family or a new hose for the garden. Q CANCER (June 21 to July 22) A c ontentious family member seems intent on creating problems. Best advice: Avoid stepping in until you know more about the origins of this domestic disagreement. Q LEO (July 23 to August 22) A r ecent job-related move proves far more successful than you could have imagined. Look for continued ben-eficial fallout. Even your critics have something nice to say. Q BORN THIS WEEK: You have a sixth sense when it comes to find-ing people who need help long before they think of asking for it. And youÂre right there to provide it. ++ Place a number in the empty boxes in such a way that each row across, each column down and each small 9-box square contains all of the numbers from one to nine. + Moderate ++ Challenging +++ ExpertPuzzle Difficulty this week: PAGE 33 Start the New Year on a High Note!,œ…>Â…>>ˆ-ii“Li"nqU9œ“ˆ'ˆ"VœLiqnExperience the High Holidays on a whole new level this year with radio show host Rabbi Dovid Vigler and services infused with joy, laughter and inspiration. Services held at the Palm Beach Gardens Marriott at 4000 RCA Blvd.U'ˆ`*œ}>“Ur}ˆ…rÂ>>œ-iˆViUiˆiœÂˆ`>-i>`U œi“Li…ˆ ii`i`Enjoy the warm and welcoming atmosphere ofChabad in Palm Beach Gardens.Visit JewishGardens.com or call 561-6CHABAD (624-2223) for more information or to reserve your seat. AUGUST 25-31, 2011 ARTS & ENTERTAINMENT A33… Peace, Love & Fashion – Back to School Fashion ShowCOURTESY PHOTOS FLORIDA WEEKLY SOCIETY Fashion campers took over the Grand Court of The Gardens Mall for the annual Back to School Fash-ion Show. During the course of two shows, the campers strutt ed their stuff in outfits from H&M, Aeropostale, Lilly Pulitzer and Gap, among others. Tracy St. George from WRMF intro-duced the models in the show. h ion Show COURTESY PHOTOS e r t h e s Mall Fa s h of two i r stuff ostale, o t h ers. intro Tracy St. George from WRMF PAGE 34 Contemporary !SIANr&USION#UISINE Distinctive Sushi Small Plates Signature Cocktails &ULL7INE3AKE,IST Robata Grill "{£*œ'Âi>`ݣU*>“i>VÂ…>`i x£{"™'“ˆwÂ…L>Vœ“ SUMMER SPECIAL ‡Vœ'i`ˆivœf"x HAPPINESS xœvv>ÂÂ`ˆŽ{‡“ >`£“‡Vœi`>ˆ PAGE 35 FLORIDA WEEKLY OF AUGUST 25-31, 2011 ARTS & ENTERTAINMENT A35 School: (561) 748-8737 395 Seabrook Road, Tequesta, FL 33469 Museum: ( 561) 746-3101 373 Tequesta Drive, Tequesta, FL 33469 Art Classes PAINTING Oil, Acrylic, Watercolor, Encaustic CERAMICS Wheel Throwing, Ha ndbuilding, Pottery, Soda Kiln, Tile Making, Murals, Sculpture Imagine.Create. Celebrate!For Adults, Teens, Children and Special Needs, from Beginner to Professional, Daytime, Nights, Weekends. Presenting Six New Renowned Instructors. See Catalog and Register: LighthouseArts.org DRAWING Beginners to Advanced,Cartooning,Figure, BurlesketchIllustration PHOTOGRAPHY Digital,Photo s hop, How to Photograph Your Artwork MIXED MEDIAJEWEL RY OP EN STUDIOS TEENS & CHILDREN CeramicsPo r tfolio Family Time LighthouseArts.org scott SIMMONS ssimmons@floridaweekly.com DINING NOTES The grind is a secret blend.And Chuck Burger Joint hopes it has the makings of the perfect patty. The restaurant, which has opened at Midtown, will offer Creekstone RanchÂs natural burger meat, ground to a special blend by Bush Bros. purveyors in West Palm Beach. The restaurant is the brainchild of Michael Curcio, owner of JupiterÂs Pyro-Grill, a local fast-casual Mexican eatery that may remind you of an upscale Chipo-tle Grill. It is Mr. CurcioÂs first burger joint, and if his name sounds familiar, itÂs because his dad, Chuck, was the owner of Tire Kingdom. But there are no tires for sale here „ just burgers and hot dogs. A single Chuck Burger, served with lettuce, tomato, American cheese and ChuckÂs special spread „ a mayonnaise-based con-coction „ is $4.75. The roll was nicely toasted during a recent visit. For those who donÂt eat beef, there is the Greenburg(er), made of avocado ($5), and a turkey dog ($4.65), made of turkey sausage. And donÂt forget the BELT ($4.50) „ thatÂs bacon, lettuce, tomato, fried egg, cheese and ChuckÂs spread on a bun. The restaurant also has craft beer and wine lists. The crinkle-cut fries, made from Yukon Gold potatoes, are crisp and light, and Chuck Burger claims they contain up to 25 percent less fat than average fries. Frozen custards and milk shakes are on the menu, as are Sprecher root beer and Mexican Coca-Cola, popular because it is made with cane sugar, not corn syrup like American-produced Coke. Inside, the place offers counter service „ place your order, take a beeper and pick up your food when the beeper goes off. The windowed space is warm, with lots of wood on the walls and a polished concrete floor that may remind visitors of Chuck BurgerÂs neighbor to the east, Chipotle Grill. Set-ups are decidedly no-nonsense „ sandwiches are served in wax-paper wrappers, the trays are jellyroll pans, perfect for toting all that high-calorie goodness. The place was quiet during a visit on a recent Monday afternoon, but there was a steady stream of customers of all ages. Chuck Burger has no website, but it does have a Facebook page on which it will list specials. Chuck Burger Joint is at Midtown, 4665 PGA Blvd., Palm Beach Gardens. Phone: 629-5191.„ Flavor Palm Beach: The monthlong discount dining promotion kicks off with an al fresco tasting party on the downtown West Palm Beach Waterfront that benefits the Greater Palm Beach Chapter of the American Red Cross. The kick-off event will feature signature menu items and cocktails from many local restaurants, including Pistache French Bis-tro, The Wine Dive, Longboards, RoxyÂs Pub, DuffyÂs Sports Grill, Don RamonÂs, Off the Hookah, MortonÂs The Steakhouse, RuthÂs Chris Steakhouse, City Cellar Wine Bar & Grill and Cabana Nuevo Latino. There will be music by The String Theory Band, live ice sculpture carving, dance performances by Palm Beach Atlantic Uni-versity and a light show. This year, patrons also can vote on which restaurant will be named ÂBest BiteÂŽ of Flavor Palm Beach. Attendance for the kick-off party is free to the public from 6 p.m. to 9 p.m., with dining tickets at $35 in advance or $40 at At Chuck Burger Joint, the secret is in the grindthe door. For the month of September, more than 30 Palm Beach County eateries will offer special three-course, prix fixe menus priced at $20 for lunch and $30 for dinner to offer residents and visitors a taste of area restaurants at a discount. For more information on Flavor Palm Beach, a complete list of participating res-taurants, or to make reservations, visit FlavorPalmBeach.com. „ MortonÂs chain receives kudos: MortonÂs The Steakhouse has received Wine Spectator MagazineÂs ÂAward of ExcellenceÂŽ at all 77 locations, including West Palm Beach and Boca Raton. It is the fourth consecutive year the restaurant has been recognized with this accolade in the magazineÂs Restaurant Awards issue. The designation of an ÂAward of ExcellenceÂŽ is achieved by restaurants whose wine lists offer a carefully chosen selection of the finest quality wines that is a thematic match to the menu in both price and style, MortonÂs said in a news release. Addition-ally, the menu of restaurants that receive an ÂAward of ExcellenceÂŽ must offer at least 100 different wine selections.„ Culture & Cocktails: The Palm Beach County Cultural CouncilÂs popular series of five one-on-one conversations with cul-tural leaders continues this season at Caf Boulud in The Brazilian Court hotel in Palm Beach. HereÂs the lineup:Nov. 7: Shannon Donnelly, society editor of The Palm Beach Daily News. Interviewer is Pat Crowley, illustrator and cartoonist. Dec. 5: Edward Villella, founding artistic director of Miami City Ballet and a former dancer. Interviewer is Philip Neal, former principal dancer with New York City Bal-let and Miami City BalletÂs Palm Beach liaison. Jan. 9: Alex Dreyfoos, entrepreneur and cultural philanthropist who helped found the cultural council and the Kravis Center, among other institutions. Interviewer is Judy Mitchell, chief executive officer of the Kravis Center. Feb. 6: Yuki, fashion designer, in a conversation about couture in London from 1976-1986. Interviewer is Fred Sharf, a col-lector, scholar and author. March 5: Les Standiford, author of ÂBringing Adam Home,ÂŽ ÂLast Train to Paradise,ÂŽ ÂMeet You in HellÂŽ and numer-ous novels. Interviewer is John Blades, executive director of the Flagler Museum. All Culture & Cocktails events are free to members of the Cultural Council ($175 level and above). The price for everyone else is $35 per person, with proceeds going to the Cultural Council. Events are 5 p.m. to 7 p.m., with registration and cocktails from 5 p.m. to 5:45 p.m., and the ÂConversationÂŽ from 5:45 p.m. to 7 p.m., including audience Q&A. Caf Boulud will serve complimentary beverages and specially prepared hors dÂoeuvres. A cash bar and free valet park-ing are also available. Attendees at all five Culture & Cocktails events in Palm Beach will be given a 20 percent discount for dinner at Caf Bou-lud immediately following the conversation. This discount is for food only, and does not include drinks, tax or gratuity. Attendance is limited to the first 70 RSVPs. Call 472-3330.„ Coming: Construction workers have begun gutting the space that once was Ocean Grill & Sushi Bar, at 2460 PGA Blvd., in Prosperity Center, at the southeast cor-ner of PGA and Prosperity Farms Road. A sign in the window says Hiroki Japanese Restaurant is coming to the space. Q t t SCOTT SIMMONS / FLORIDA WEEKLY The crinkle-cut fries at Chuck Burger Joint are made from Yukon Gold potatoes. The beef in the Chuck Burger is ground by Bush Bros. in a special blend of Creekstone Ranch meat. PAGE 36 Oasis 11B 3BR/3.5BA + den and 4,000 + square feet with panoramic views of the ocean and intracoastal. Stunning residence with an oriental ” air.Offered at $1,650,000 jeannie@jwalkergroup.com561-889-6734 Jim Walker III Broker-Associate Jeannie Walker Luxury Homes Specialist One of only three condos on the island with a private restaurant! Call us today for a personal tour of these luxury residences! A pioneer in Luxury Condo living, Martinique has corner units with wrap-around balc onies, oor-to-ceiling windows in living areas, and his/her master baths. From $389 Martinique WT 201 2BR/3.5BA. Unique, completely renovated residence with spacious private balcony for outdoor living. Over 2,000 SF of living space. Crown molding, hardwood ” oors and neutral paint. Truly stunning. A must see!Asking $549,000Martinique WT 804 2BR/3.5BA. Renovated residence with tropical dcor. Magni“ cent breakfast bar area with rich wood-tone cabinetry, iron accents, granite counters and stone backsplash. Premier ocean to intracoastal views. Priced to sell! Asking $549,000Martinique PH 2601 2BR/3.5BA Penthouse with magni“ cent ocean and intracoastal views, and two parking spaces. Open and spacious, each room ” ows seamlessly into the next. Just steps from the ocean and white sandy beaches of South Florida. Asking $625,000Martinique ET 1103 2BR/3.5BA. One of-a-kind 11th-” oor oceanfront condo designed for those who appreciate luxury living with beautiful ocean and intracoastal views. Custom built-in furnishings made from burl wood imported from Spain.Asking $725,000Martinique ET 2201 2BR/3.5BA. Direct Ocean, from sunrise to sunset, boundless ocean to intracoastal views. This high northeast corner residence is in the coveted East Tower. Bright and fresh with views from every room. Asking $750,000Martinique WT 1404 2BR/3.5BA. Experience incredible southern views from this 14th-” oor residence boasting gorgeous sunrises over the ocean and sunsets over the intracoastal waterway. Master suite is spacious with his/her bathrooms. Asking $529,000 REDUCED REDUCED NEW! SOLD REDUCED MARTINIQUE ~ SINGER ISLAND SEASONAL & ANNUAL LUXURY RENTALS AVAILABLE. CALL US TODAY!
http://ufdc.ufl.edu/AA00062973/00046
CC-MAIN-2018-30
refinedweb
26,273
64.41
> I have a world cube (as opposed to a sphere), and on each of the six sides i have rigidbodies that need to fall towards it's relative side/ground. ConstantForce's Force parameter won't work because the world cube will need to rotate, and when that rotates, all the rigidbodies global rotation axis also changes. The Relative Force parameter won't work either because the rigidbodies themselves can also rotate independently, so their local rotation axis can change. So i figure some type of script that runs AddForce and adjusts the vector based on position and rotation of the rigidbody in relation to it's side would be the solution. I've posted in the forums about it (forum post) but haven't received any replies. My current solution works but i feel there must be a better way. You can find my current unity project at my Github with the scene set up with the cubes, but i'll also post the script here. The rigidbody must be child to the collider surface/ground/side it should fall down towards. rigidbody using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Rigidbody))] public class gravityBody : MonoBehaviour { public float gravity = -10f; Rigidbody rb; void Start () { rb = GetComponent<Rigidbody> (); rb.useGravity = false; } void FixedUpdate () { rb.AddForce(rb.transform.parent.up * gravity); //rb.AddRelativeTorque(new Vector3(0f,-0.25f,0f)); } } thank you. To clarify, you want them to fall down on the faces? For example even if the object was close to the corner, it wouldn't slide/fall toward the center of the face? Correct, it should fall straight down. So my current solution, since the object can potentially rotate and change it's local y axis, is it uses its parent's (the ground beneath it) local y axis. The ground beneath it never independently rotates, so the Y axis well stay the same (going straight through the "world cube" origin). So what does your script do Set Individual Rigidbody Gravity [Solved] 0 Answers How can I match Unity's gravity implementation per object? 1 Answer Physics in 2D mode not working? 0 Answers Correcting Directional velocity for a plane 0 Answers Gravity on a rotating platform 1 Answer
https://answers.unity.com/questions/1435333/how-to-make-rigidbodies-on-each-side-of-a-cube-fal.html
CC-MAIN-2019-26
refinedweb
372
55.84
Definitions for using the keyboard device. More... #include <sys/cdefs.h> #include <arch/types.h> #include <dc/maple.h> Go to the source code of this file. Definitions for using the keyboard device. This file contains the definitions needed to access the Maple keyboard device. Obviously, this corresponds to the MAPLE_FUNC_KEYBOARD function code. Size of a keyboard queue. Each keyboard queue will hold this many elements. Once the queue fills, no new elements will be placed on the queue. As long as you check the queue relatively frequently, the default of 16 should be plenty. Keyboard keymap. This structure represents a mapping from raw key values to ASCII values, if appropriate. This handles base values as well as shifted values. Keyboard status structure. This structure holds information about the current status of the keyboard device. This is what maple_dev_status() will return. Pop a key off the global keyboard queue. This function pops the front off of the keyboard queue, and returns the value to the caller. The value returned will be the ASCII value of the key pressed (accounting for the shift keys being pressed). If a key does not have an ASCII value associated with it, the raw key code will be returned, shifted up by 8 bits. Pop a key off a specific keyboard's queue. This function pops the front element off of the specified keyboard queue, and returns the value of that key to the caller. If the xlat parameter is non-zero and the key represents an ISO-8859-1 character, that is the value that will be returned from this function. Otherwise if xlat is non-zero, it will be the raw key code, shifted up by 8 bits. If the xlat parameter is zero, the lower 8 bits of the returned value will be the raw key code. The next 8 bits will be the modifier keys that were down when the key was pressed (a bitfield of KBD_MOD_* values). The next 3 bits will be the lock key status (a bitfield of KBD_LED_* values). Activate or deactivate global key queueing. This function will turn the internal keyboard queueing on or off. Note that there is only one queue for the whole system, no matter how many keyboards are attached, and the queue is of fairly limited length. Turning queueing off is useful (for instance) in a game where individual keypresses don't mean as much as having the keys up or down does. You can clear the queue (without popping all the keys off) by setting the active value to a different value than it was. The queue is by default on, unless you turn it off.
http://cadcdev.sourceforge.net/docs/kos-2.0.0/keyboard_8h.html
CC-MAIN-2018-05
refinedweb
445
75.1
How to divide an array into k number of parts in C++ A C++ array can be divided into k number of parts using the C++ code. So today we are going to perform this task. Let’s continue reading this article to see how we can do it with the code example. The Array is used to store multiple values in one variable. In an array, we have to first declare the array size and then we can use its maximum size. The size of an array cannot be increased after the declaration of an array. We have to first decide the maximum length for an array and declare it. We always take more space than required so that no error comes for data loss. The program is going to work – - It is going to check how many part array is going to divide. - Then it is going to divide the array accordingly into parts. See the code below: s=n/k; j=0; for(i=0;i<n;i++) { if(s==j) { cout<<endl; j=0; } cout<<arr[i]<<" "; j++; } Also, read: C++ program to create array of strings C++ code to divide an array into k number of parts Below is our C++ code that shows how we able to divide our array into k number of parts. We are given an array and dividing it into the desired fragments. First, we are going to divide an array into a fragment and get the position from where we can divide it. Then we are going to divide an array according to our input fragment we want to divide. #include <iostream> using namespace std; void divide(int arr[],float n, float k) { int s,i,j,h; s=n/k; j=0; for(i=0;i<n;i++) { if(s==j) { cout<<endl; j=0;} cout<<arr[i]<<" "; j++; } } int main() { int a[]={1,2,3,4,5,6}; float k; cout<<"Enter the value in which you want to divide:"; cin>>k; divide(a, 6, k); return 0; } Output: Enter the value in which you want to divide:3 1 2 3 4 5 6 Enter the value in which you want to divide:2 1 2 3 4 5 6 The array can be divided into the required desired length as shown in the output.
https://www.codespeedy.com/divide-an-array-into-k-number-of-parts-in-cpp/
CC-MAIN-2020-45
refinedweb
389
65.15
Wireless Headphones, Fitness bands, Bluetooth Speakers, In-Ear headphones, Mobile phones, Laptops... there are so many Bluetooth devices around us and most of these devices are battery operated. Have you ever wondered that, when you connect a Bluetooth device to your mobile phone how it automatically understands that the connected device is a computer or audio device or a mobile phone? For some devices our phone might even automatically shows the battery percentage of the connected device on the notification bar. How does all this happen on their own? There should be some common protocol shared between the phone and the Bluetooth device right! Stay curious, you will get answers for these questions as we try to understand Bluetooth Low Energy (BLE for short), with the popular ESP32 module. Unlike Classic Bluetooth in ESP32 the BLE operates only when a communication is activated and stays in sleep mode otherwise, this makes it the right choice for battery powered applications. BLE can also form mesh networks and act as Beacons. Normally a BLE modules works either as a server or as a client, here we will use ESP32 BLE as server. Here we have divided the complete ESP32 Bluetooth into three segments for ease of understanding. 1. Serial Bluetooth on ESP32 toggling LED from Mobile Phone 2. BLE server to send Battery level data to Mobile Phone using GATT Service 3. BLE client to scan for BLE devices and act as beacon. We have already covered the first article; in this article we will learn how to make the ESP32 BLE to work as a server and use the GATT Service to send battery level information. For testing purpose we will send hardcoded values from ESP32 as battery percentage to our mobile phone through BLE GATT service, this way our Mobile will assume that ESP32 is a battery operated Bluetooth device which is trying to send to its battery percentage. Before going into detail we will understad few terminologies related with Bluetooth Low Energy. Terminologies related to BLE (Bluetooth Low Energy) BLE Server: As told earlier the BLE can be programmed to work either as a Server or as a client. When working as a server the BLE can only provide data it cannot initiate a connection. Example would be a fitness band. A Server could send information only if the client requests for it. Most commonly the ESP32’s BLE is used a Server. Each Server will have one or more Service within it and similarly each service will have one or more characteristics associated with it. A Characteristic may have zero, one or more than one Descriptor inside it. Every Service, characteristic or Descriptor will have its own pre-defined unique ID called UUID. BLE Client: The client can scan connect and listen to other Bluetooth devices. An example would be your mobile phone. Note that most BLE hardware devices can work as server and as client, it the software that decides the role of the device. Peripheral Device / Central Device: In an BLE network there could be only one Central Device, but can have as many Peripheral devices as required. The Central Device can connect to all peripheral devices at the same time, but the peripheral device can connect only to the Central Device, this way no two peripheral device can share data among each other. A best example for Central device will be our smart Phones and for Peripheral device will be our Bluetooth earphone or fitness bands. BLE Advertising: A BLE Advertising is the geeky term to instruct the Bluetooth device to be visible to all so that it can pair and establish a connection .It can be considered as a one way communication. Here the server keeps on advertising data expecting a server to receive it. BLE Beacon is a type of BLE Advertisement. UUID (Universal Unique Identifier): Every BLE Bluetooth device is given a Universal Unique Identifier Number when programmed by the programmer. You can think of this identifier as a sequence of numbers which represents the functionality/role of the BLE device. Again there are two types of UUID. One is the Service UUID and the other is Characteristic UUID. GATT Service: GATT stands for Generic Attribute Profile; this defines some standard ways using which two BLE devices should always communicate. This Attribute (ATT) Protocol is pre-defined and is common for all BLE devices so this way any two BLE devices can identify each other. So GATT was the answer to our previous question. The technique using which two BLE device should send data to and forth is defined by the concept called services and characteristics. BLE Service / BLE characteristic: The Service UUID tells us what type of service the BLE device is going to perform and the Characteristic UUID tells what are the parameters or functions that will be performed by that service. So every Service will have one or more characteristics under them. Okay! Where does the programmer get this UUID from? Every UUID is already defined by the GATT (Generic Attribute Profile) you can visit their website and select the UUID as required for the project. I know it has bounced a bit over our head; let’s try understanding it with an example. Let’s assume the BLE device of an audio player. Initially when you pair it with your phone, your phone identifies it as an audio device and also displays the battery level on the status bar. So, for this to happen the audio player has to somehow tell your phone that it is willing to share the battery level and the percentage of charge it has in it battery. This is done by using the UUID, there is a specific UUID which tells that the BLE dice is going to provide details about battery level this UUID which tells the type of service is called Service UUID, again there could be so many parameters that has to be exchanged for completing a service like the value of battery is on such parameter, each parameter will have its own UUID and these are called the Characteristic UUID. The common function performed by a characteristic is Read, Write, Notify and Indicate. BLE Descriptor: The Descriptor is an optional attribute that is present inside the Characteristic. A Descriptor normally specifies how to access a Characteristic. BLE Beacon: A Bluetooth Beacon is more like a proximity switch which performs some pre-defined action when the user gets into a range (close proximity). It advertises its identity all the time and hence is ready to pair always. BLE2902: I am still sceptical about this thing, but you can think of it as a piece of software on the client side that informs the server to turn notification On or Off this will help us in saving power Hope you got a rough idea, the good is that we need not know much since all the handwork is already done for us though the libraries. Preparing the hardware The project requires no hardware set-up but make sure you have added ESP32 board details on your Arduino IDE and have tried minimum sample blink program to check if everything is working as expected. You sceptical on how to do it you can follow the Getting started with ESP32 with Arduino tutorial to do the same. Also to test the BLE services we will be using the nRF android application on our mobile which can be directly downloaded from the PlayStore. It is also available in Itunes Store for Iphone users. If you are planning to work with BLE for a long time, this application will really come in handy for debugging purposes. Programming ESP32 for Battery Level Indication using GATT service By this time I assume that you have a fair idea on what GATT service and how it is implemented using Service and characteristic models. Now, let us dive into the program to learn how it is implemented in ESP32 using the Arduino IDE. Before we continue I would like to use this space to thank Andreas Spiess for his video BLE which made things a lot clear on my side. We begin the program by importing the required libraries into our sketch. There are a lot of things to configure in order to use the ESP32’s BLE functionality hopefully though thanks to Neil Kolban who has already done the hard work for us and has provided the libraries. If you want to understand the functionality of the libraries you can refer to his documentation on github page. #include <BLEDevice.h> #include <BLEUtils.h> #include <BLEServer.h> //Library to use BLE as server #include <BLE2902.h> Next we have to define the Server Call-back function for our Bluetooth device. Before that lets understand that what is callback function in BLE. What is callback function in BLE? When BLE is operating as Server it is important to define a Server callback function. There are many types of callbacks associated with BLE but to put it simple you consider these as an acknowledgement being performed to make sure that action has been completed. A server callback is used to ensure that the connection between client and server is established successfully. We use the following lines of code to perform a server callback. bool _BLEClientConnected = false; class MyServerCallbacks : public BLEServerCallbacks { void onConnect(BLEServer* pServer) { _BLEClientConnected = true; }; void onDisconnect(BLEServer* pServer) { _BLEClientConnected = false; } }; Inside the void setup function, we initiate Serial communication at 115200 for debugging and then initialize the Bluetooth Device through InitBLE function. void setup() { Serial.begin(115200); Serial.println("Battery Level Indicator - BLE"); InitBLE(); } The initBLE is the place where all the magic happens. We have to create a Bluetooth server and use the Battery Level service in here. But before that we have to define the UUID for Service, Characteristic and Descriptor for reading the battery Level. All the UUID can be obtained from the Bluetooth GATT service website. For our case we are trying to use the Battery service and UUID for it is defined as 0X180F as shown below. Next, we need to know the Characteristic associated with this service. To know that simply click on Battery Service and you will be taken to Service Characteristics page, where it is mentioned that battery Level is the name of the characteristics and it takes in the value from 0 to 100. Also note that we can perform only two actions with this characteristic, one is to Read which is mandatory to do and the other is Notify which is Optional. So we have to send the battery value to client (Phone) which is mandatory and if needed we can notify the phone about which is optional. But wait we still did not find the UUID value for the Characteristic Battery Level. To do that get into the Battery Characteristic page and search for the Battery Level name you will find its UUID as 0X2A19, the snapshot of same is shown below. Now that we have all the values, let us put it the program as shown below. The name BatterySerivce, BatteryLevelCharacteristic and BatteryLevelDescriptor are user defined variables to refer to the Service, Characteristic and Descriptor that we are using in the program. The Value for Descriptor 0X2901 is used when the size of the value is 8-bit, more information can be found Descriptor Description page. )); Getting back to the initBLE function. We first have to start the BLE server and make it advertise with a name. The following lines are used to start the BLE as server. The name that I have given to my BLe server is “BLE Battery”, but you can choose your own. BLEDevice::init("BLE Battery"); // Create the BLE Server BLEServer *pServer = BLEDevice::createServer(); pServer->setCallbacks(new MyServerCallbacks()); Next we have to start the GATT service since we have already defined the UUID we can simply start the service using the line below. // Create the BLE Service BLEService *pBattery = pServer->createService(BatteryService); Once the service is started we can link the descriptor with characteristics, and set the values. The BLE2902 service is also added here as shown below.()); Finally everything is set, now all that is left is to ask the ESP32 to advertise so that other devices like our phone can discover it and connect to it , and when connected to a client it should initiate the Battery service which can be done though the following lines. pServer->getAdvertising()->addServiceUUID(BatteryService); pBattery->start(); // Start advertising pServer->getAdvertising()->start(); That is it so far so good, the last step is to tell the descriptor what is the value of the battery in percentage that should be sent to the client (Phone). This value can be from 0 -100 as we read earlier, to keep things simple, I have simple hard coded the value of battery to be 57 and then increment it every 5 seconds and start from 0 once it reaches 100. The code to do that is shown below. Note that the value that is being sent is in format unit8_t. uint8_t level = 57; void loop() { BatteryLevelCharacteristic.setValue(&level, 1); BatteryLevelCharacteristic.notify(); delay(5000); level++; Serial.println(int(level)); if (int(level)==100) level=0; } Testing your GATT service on ESP32 BLE The complete code explained above is given at the end of page. Upload the code to your ESP32 board. Once uploaded your phone should discover a Bluetooth device called “BLE Battery” Pair with it. Then install the nRF android application and open it and connect to the BLE Battery BLE device. Expand the Battery Service section and you should find the following screen. As you can see the Application has automatically identified that the BLE provides Battery Service and has the characteristics of Battery Level because of the UUID that we used in the program. You can also see that current battery value that is 67% wait for 5 seconds and you can also notice it getting incremented. The cool thing about using BLE is that now any application that works with BLE will think that your ESP32 is BLE device which notifies battery level. To try it out I used an application called BatON and the application identified the ESP32 as battery powered Bluetooth device and gave the percentage notification on my phone like this Cool!! Right? I have also shown the complete working in the video below. Now, that you have learnt how to use BLE Battery services with ESP32, you can try other GATT services as well which are very interesting like Pulse rate, HID, Heart Rate etc.. Have fun.... /*Program to use GATT service on ESP32 to send Battery Level * ESP32 works as server - Mobile as client * Program by: B.Aswinth Raj * Dated on: 13-10-2018 * Website: */ #include <BLEDevice.h> #include <BLEUtils.h> #include <BLEServer.h> //Library to use BLE as server #include <BLE2902.h> bool _BLEClientConnected = false; )); class MyServerCallbacks : public BLEServerCallbacks { void onConnect(BLEServer* pServer) { _BLEClientConnected = true; }; void onDisconnect(BLEServer* pServer) { _BLEClientConnected = false; } }; void InitBLE() { BLEDevice::init("BLE Battery"); // Create the BLE Server BLEServer *pServer = BLEDevice::createServer(); pServer->setCallbacks(new MyServerCallbacks()); // Create the BLE Service BLEService *pBattery = pServer->createService(BatteryService);()); pServer->getAdvertising()->addServiceUUID(BatteryService); pBattery->start(); // Start advertising pServer->getAdvertising()->start(); } void setup() { Serial.begin(115200); Serial.println("Battery Level Indicator - BLE"); InitBLE(); } uint8_t level = 57; void loop() { BatteryLevelCharacteristic.setValue(&level, 1); BatteryLevelCharacteristic.notify(); delay(5000); level++; Serial.println(int(level)); if (int(level)==100) level=0; }
https://circuitdigest.com/microcontroller-projects/esp32-ble-server-how-to-use-gatt-services-for-battery-level-indication
CC-MAIN-2019-47
refinedweb
2,575
52.19
Yes, I'll admit, I am a newbie in Java. However, now my brains got fried on this thing - picking random objects from wherever (example of an Array). Before detailing, my main question is: how do you use Random generator on objects (arrays, arraylists etc.)? (Not Int, Not String) I.e. how do you converts objects so that the Random generator can pick them? Assume following: Class Bankaccount Objects Bankaccounts (with attributes like balance, id etc.) - these are stored in an array. How can I pick, say 3 random objects (bankaccounts) from an array of say 10 bankaccounts? Code example: import java.util.*; import java.util.Random; class Bankaccount{ private int balance; public void setBalance(int a){ balance = a; } public int getBalance(){ return balance; } } //Alright, I am thinking of creating a new class which has a method that calls on the array of type Bankaccount and stores it //in whatever area, for example another array or arraylist. class pickRand{ public static Bankaccount [] get(Bankaccount[]array){ Random rand = new Random(); int rnd = rand.nextInt(array.length); //Objects to int - how to? Any hints? //Can a solution be to attack the balance variable of objects? //The other part of adding those objects is ok, and also how many to pick. } } public class Account{ public static void main(String []args){ Bankaccount b1 = new Bankaccount(); Bankaccount b2 = new Bankaccount(); Bankaccount b3 = new Bankaccount(); Bankaccount b4 = new Bankaccount(); Bankaccount b5 = new Bankaccount(); Bankaccount b6 = new Bankaccount(); Bankaccount b7 = new Bankaccount(); Bankaccount b8 = new Bankaccount(); Bankaccount b9 = new Bankaccount(); Bankaccount b10 = new Bankaccount(); b1.setBalance(10000); b2.setBalance(30000); b3.setBalance(13000); b4.setBalance(36000); b5.setBalance(19000); b6.setBalance(28000); b7.setBalance(30000); b8.setBalance(30000); b9.setBalance(15000); b10.setBalance(30000); //Yes, very thorough, but look up! :)/> Bankaccount [] bac = new Bankaccount [10]; bac[0] = b1; bac[1] = b2; bac[2] = b3; bac[3] = b4; bac[4] = b5; bac[5] = b6; bac[6] = b7; bac[7] = b8; bac[8] = b9; bac[9] = b10; //The final output looks something like this... Bankaccount[]bac2 = pickRand.get(bac); System.out.println(bac2);//and so on. } } Any hints will be greatly appreciated! However, please keep me in the Random generator area!
http://www.dreamincode.net/forums/topic/196388-random-objects-from-arrays-newbie-help/
CC-MAIN-2016-07
refinedweb
362
55.54
Revision history¶ This chapter describes improvements compared to earlier versions of cutplace. Version 0.8.8, 2015-11-13¶ - Changed development status to “Production/Stable” as cutplace has been processing millions of data rows on a daily base for a couple of months now. - Improved validation of Excel dates and times. Fields of type DateTime now check the format specified by the rule and in case it only contains date or time components only extracts those. (API note: internally, Excel dates and times returned by the low level function cutplace.rowio.excel_rows()still use the full YYYY-MM-DD hh:mm:ss format. This change mostly concerns cutplace.validio.Readerand cutplace.fields.DateTimeFieldFormat.validated_value().) - Cleaned up CID and data files for documentation, examples and tests ( issue #107 <>). There are fewer files now and they have multiple uses. Furthermore examples in the documentation now match the CID’s in the examplesfolder. Partially this can be attributed to parts of the documentation now including RST files that are updated during the build process. - Added Python 3.5 as a supported version. Version 0.8.7, 2015-07-18¶ - Fixed that errors detected by field formats during declaration got suppressed and typically resulted in more confusing errors later. - Fixed NameErroron platforms without tkinter. - Improved documentation: - Fixed missing example for own field and check in Using your own checks and field formats (issue #33). - Improved API: - Fixed that cutplace.rows()also yielded header rows instead of only data rows. - Cleaned up API documentation (typos, links). Version 0.8.6, 2015-07-14¶ - Fixed installation from source distribution by upgrading to Pyscaffold 2.2.1. Earlier versions used versioneer for version numbering and forgot to include versionneer.pyin the distribution archive. The current version uses setuptools_scm which only needs a clean dependency instead of additional source code (issue #108). - Added command line option --guito open a graphical user interface for validation (issue #77). - Improved error message for broken field declarations in CIDs detected by the field format constructor, which now include the name of the field and the location in the CID. - Improved error message when attempting to use a 0 byte as item delimiter in CID’s for delimited data. (Python’s csvmodule fails with a TypeErrorbecause the low level implementation is based on C). - Improved API: Cleaned up cutplace.Cid: - Changed cutplace.Cid.add_check()to require an cutplace.fields.AbstractCheckas parameter and added cutplace.Cid.add_check_row()to accept a row. - Changed cutplace.Cid.add_field_format()to require an cutplace.fields.AbstractFieldFormatas parameter and added cutplace.Cid.add_field_format_row()to accept a row. Version 0.8.5, 2015-03-09¶ Version 0.8.4, 2015-03-01¶ - Fixed validated writing of header rows by disabling validation of the header. - Fixed reading of non ASCII values from ODS under Python 2. - Fixed default decimal separator, which now is dot ( .) instead of comma ( ,). Interestingly enough in practice this never really mattered as long as there was no thousands separator (the default), in which case a decimal value using a dot as actual decimal separator simply preserved it and got accepted anyway. - Added rule to Decimal fields which allows to specify a range and precision (issue #10, contributed by Patrick Heuberger). - Improved documentation: cleaned up section on Using the graphical user interface. - Improved API documentation: added a section on Writing data. - Improved API: changed validation of length for fixed field values: cutplace.Writerrejects too long values with a FieldValueErrorand automatically pads too short values with trailing blanks while the low level cutplace.rowio.FixedRowWriterrejects both cases with an AssertionError. Furthermore the length of fixed values is now checked before validating it against the field format rule. Version 0.8.3, 2015-01-31¶ - Added option --untilto increase performance by skipping validation of field format and checks after a specified number of rows (issue #86). - Fixed reading of Excel error cells. - Improved API: - Removed shortcuts for exceptions from cutplace. Use the originals in cutplace.errorsinstead. - Added convenience function cutplace.validate()and cutplace.rows()to validate and read data with a single line of source code. - Added cutplace.Writerfor validated writing of delimited and fixed data (issue #84). - Improved API documentation. Version 0.8.2, 2015-01-19¶ - Changed syntax for ranges to prefer ellipsis ( ...) over colon ( :) because it expresses the intended meaning more clearly. The colon is still supported so existing CIDs keep working, but the documentation and examples use the new syntax. - Improved error reporting when parsing CIDs. In particular all errors related to the data format include a specific location, and some errors provide more information about the context they occurred in. - Cleaned up - Removed description of obsolete option --cid-encoding. - Cleaned up option groups with only one option. - Cleaned up sequence of options which is now sorted alphabetically. - Cleaned up notes on Development to reflect changes of 0.8.0. Version 0.8.1, 2015-01-11¶ - Fixed ranges for Integer fields with a length of one digit, which caused a ValueError. - Added Python 2 support to universal wheel for distribution. Version 0.8.0, 2015-01-11¶ This version is a major rework of the whole code base in order to to fix some long standing bug and migrate it to Python 3.2+ while retaining support for Python 2.6+. A big thank you goes to Patrick Heuberger, Jakob Neuberger and Patrick Prohaska for doing this as a school project for HTL Wiener Neustadt. In summary, the changes are: - A few long standing bugs have finally been fixed, in particular: - The documentation is now available at. - Cutplace interface definitions are now abbreviated as CID, replacing the acronym ICD (interface control document). Nevertheless the file format remains the same so existing data descriptions can be used as is. - The distribution now uses the wheel format instead of egg. A source distribution is still available as ZIP. Rarely used functionality that seemed a good idea to have at some time has been removed. If you deem of these features critical, feel free to submit a pull request or to open an issue and request a reimplementation: The cutplace command line options --acceptand --rejectare gone and all output options related to it. If you still need a filter to build a file that preserves all valid rows and removes rejected ones, a few line of Python code can do the trick: from cutplace import Cid, Reader cid = Cid('.../some_cid.ods') reader = Reader(cid, '.../some_data.csv') for row in reader.rows(on_error='continue'): # Do something with ``row``. pass The command line option --listencodingsis gone. Instead refer to the standard encodings listed in the Python documentation. The command line option --cid-encodingis gone. If you need non ASCII characters, use ODS format or CSV with UTF-8. The command line option --web(and all related options) to launch a small web server with a validation form is gone. Eventually there is going to be a GUI client, refer to issue #77. The tool cutsniff to build a draft CID is gone as it only takes a few minutes to build a draft anyway. Furthermore, the plain CSV results always needed quite some work to get a more presentable format concerning layout and colors. The API (see Module Index) has been reworked too and is cleaner and more pythonic now. The project structure applies most of the Simple Rules For Building Great Python Packages. The basic project structure and build process are provided by Pyscaffold. - All essential functions can be accessed after a simple import cutplace. The various sub modules are needed only for special requirements. - All errors raised by cutplaceare collected in cutplace.errors. Version 0.7.1, 2012-05-20¶ - Changed error location of failed row checks to use the first column instead of a number one past the actual number of columns (issue #42). - Changed Patternfield format to allow shell patterns instead of only simple DOS patterns (issue #37). - Improved cutsniff: - Added sniffing of numeric fields (#48). - Added first none empty field value as example. - Moved project and repository to <> (issue #47). - Improved API: - Added validating writer, see interface.Writerfor more information (issue #45). - Added property examplefor *FieldFormat(issue #41). - Cleaned up build and the section on “Jenkins” so that everything works as described even if Jenkins runs as deamon with MacPorts. Version 0.7.0, 2012-01-09¶ - Added command line option --pluginsto specify a folder where cutplace looks for plugins declaring additional field formats and checks. For details, see Using your own checks and field formats. - Changed interface.validatedRows(..., errors="yield")to yield tools.ErrorInfoin case of error instead of Exception. - Reduced memory foot print of CSV reading (Ticket #32). As a side effect, all formats now read and validate in separate threads, which should result in a slight performance improvement on systems with multiple CPU cores. - Cleaned up developer reports (Ticket #40). Most of the reports are now built using Jenkins as described in “Jenkins”, the only exception being the profiler report to monitor performance. Also changed build instructions to favor antover setup.py. - Cleaned up API: - cutplace and cutsniff have a similar main()that returns an integer exit code without actually calling sys.exit(). - Cleaned up formatting to conform to PEP8 style. Version 0.6.8, 2011-07-26¶ - Fixed “see also” location in error messages caused by IsUniqueCheckwhich used the current location as original location. - Fixed AttributeErrorwhen using the API method AbstractFieldFormat.getFieldValueFor(). - Fixed ImportErrorduring installation on systems lacking the Python profiler. Version 0.6.7, 2011-05-24¶ - Added option --namesto cutsniff to specify field names as comma separated list of names. Without this option, the names found in the last row specified by --headare used. Without this option, fields names will have generated values the user manually will have to change in order to get meaningful names. Version 0.6.5, 2011-05-17¶ - Added command line option --headerto cutsniff to exclude header rows from analysis. - Fixed build error in case module coverage was not installed by making coverage a required module again. Version 0.6.4, 2011-03-19¶ - Added cutsniff, a tool to create an ICD by analyzing an existing data file. - #21: Fixed automatic detection of Excel format when reading ICDs using the web interface. (Tickte #21). - Fixed AttributeErrorwhen data format was set to “delimited”. Version 0.6.3, 2010-10-25¶ - Fixed InterfaceControlDocument.checkNameswhich actually contained the field names. Additionally, checkNames now contains the names in the order they were declared in the ICD. Consequently the checks are performed in this order during validation unlike until now, where the internal hashcode decided the order of checks. (Ticket #35) - Improved documentation, in particular: - Added more information on writing field format and checks of your own. It still lacks details on how to actually use these in an ICD though. (Ticket #33) - Cleaned up introductions of most chapters with the intention to make them easier to comprehend. - Changed public instance variables to properties. This allows to mark many of them as read only, and also makes them show up in the API reference. (Ticket #34). Version 0.6.2, 2010-09-29¶ - Added input location for error messages caused by failed checks. (Ticket #26, #27 and #28) - Added error message if a field name is a Python keyword such as classor if. This avoids strange error messages if later an IsUniquecheck refers to such a field. (Ticket #20) - Changed style for error messages referring to locations in CSV, ODS and Excel data to R1C1. For example, “R17C23” points to row 15, column 23. - Changed internal modules to use “_” as prefix in name. This removes them from the API documentation. Furthermore, module toolshas been split into public toolsand internal _tools. - Changed interface for listeners of validation events: - Renamed ValidationListener to BaseValidationListener. - Added parameter location to acceptedRow() which is of type tools.InputLocation. - Cleaned up API documentation, using reStructured Text as output format and adding a tutorial in chapter Application programmer interface. - Cleaned up logging to slightly improve performance. Version 0.6.1, 2010-04-25¶ Added data format properties “decimal delimiter” (default: ”.”) and “thousands delimiter” (default: none). Fields of type Decimal take them into account. See also: Ticket #24. Added detailed error locations to some errors detected when reading the ICD. Changed choice fields to be case sensitive. Changed choice fields to support values in quotes. That way it is also possible to use escape sequences within values. Values with non ASCII characters (such as umlauts) have to be quotes now. See also: Ticket #25. Renamed module cutplace.range to cutplace.ranges to avoid name clash with the built in Python function range(). In case you have an older version of cutplace installed and plan to import the cutplace Python module using: from cutplace import * # ugly, avoid anyway you will have to manually remove the files cutplace/range.pyand cutplace/range.pyc(in case it exists). Added API documentation available from <>. Version 0.6.0, 2010-03-29¶ - Changed license from GPL to LGPL so closed source application can import the cutplace Python module. - Fixed validation of empty dates with DateTime fields. - Added support for letters, hex numbers and symbolic names in ranges. - Added support for letters, escaped characters, hex numbers and symbolic names in item delimiters for data formats. - Added auto detection of item delimiters tab (“\t”, ASCII 9) and vertical bar (|). [Josef Wolte] - Cleaned up code for field validation. Version 0.5.8, 2009-10-12¶ - Changed Unicode encoding errors to result in the row to be rejected similar to a row with an invalid field instead of a simple message in the console. - Changed command line exit code to 1 instead of 0 in case validation errors were found in any data file specified. - Changed command line exit code to 4 instead of 0 for errors that could not be handled or reported otherwise (usually hinting at a bug in the code). This case also results in a stack trace to be printed. Version 0.5.7, 2009-09-07¶ - Fixed validation of empty Choice fields that according to the ICD were allowed to be empty but nevertheless were rejected. - Fixed a strange error when run using Jython 2.5.0 on certain platforms. The exact message was: TypeError: 'type' object is not iterable. Version 0.5.6, 2009-08-19¶ - Added a short summary at the end of validation. Depending on the result, this can be either for instance eggs.csv: accepted 123 rowsor eggs.csv: rejected 7 of 123 rows. 2 final checks failed.. - Changed default for --logfrom``info`` to warning. - Improved confusing error message when a field value is rejected because of improper length. - Fixed ImportErrorwhen run using Jython 2.5, which does not support the Python standard module webbrowser. Attempting to use --browserwill result in an error message nevertheless. Version 0.5.5, 2009-07-26¶ - Added summary to validation results shown by web interface. - Fixed validation of Excel data using the web interface. - Cleaned up reporting of errors not related to validation via web interface. The resulting web page now is less cluttered and the HTTP result is a consistent 40x error. Version 0.5.4, 2009-07-21¶ - Fixed --splitwhich did not actually write any files. (Ticket #19) - Fixed encoding error when reading data from Excel files that used cell formats of type data, error or time. - Fixed validation of Decimal fields, which resulted in a NotImplementedError. - Fixed internal handling of ranges with a default, which resulted in a NameError. Version 0.5.3, 2009-07-18¶ - Added command line option --splitto store accepted and rejected data in two separated files. See also: ticket #17. - Fixed handling of non ASCII data, which did not work properly with all formats. Now cutplace consistently uses Unicode strings to internally represent data items. See also: ticket #18. - Improved error messages and removed stack trace in cases where it does not add anything of value such as for I/O errors. - Changed development status from alpha to beta. Version 0.5.1, 2009-06-11¶ - Added support for ICDs in Excel and ODS format for built in web server. - Changed representation of integer number read from Excel data: instead of for example “123.0” this now renders as “123”. - Improved memory usage for data and ICDs in ODS format. - Fixed reading of ICDs in Excel and ODS format. - Fixed TypeError when the CSV delimiters specified in the ICD were encoded in Unicode. Version 0.5.0, 2009-06-02¶ - Fixed handling of Excel numbers, dates and times. Refer to the section on Excel data format for details. - Changed order for field format (again): It now is name/example/empty/length/type/rule instead of name/example/empty/type/length/rule. - Changed optional items for field format: now the field name is the only thing required. If no type is specified, “Text” is used. - Added a proper tutorial that starts with a very simple ICD and improves it step by step. The old tutorial presented one huge ICD and attempted to explain everything in it, which could easily overwhelm the reader. - Migrated documentation from DocBook to RestructuredText. - Improved build and installation process ( setup.py). Version 0.4.4, 2009-05-23¶ - Fixed checks when validating more than one data file from the command line. Until now the checks did preserve internal state information needed to perform the check. For instance, IsUnique check remembered the keys of all rows read so far. So when a data file contained a row with a key that already showed up in an earlier data file, the check failed. To prevent this from happening, validate()now resets all checks. See also: Ticket #9. - Fixed detection of characters outside of the “Allowed characters” range. Apparently this never worked until now. - Fixed handling of empty choices consisting only of white space. - Fixed detection of fixed fields without length. - Fixed handling of white space in field items of fixed length data. - Added plenty of test cases and consequently performed a couple of minor fixes, improvements and clean ups. Version 0.4.3, 2009-05-18¶ - Fixed auto detection of delimiters in a CSV file, which got broken when switching to Python’s built in CSV reader with version 0.3.1. See also: Ticket #8. Version 0.4.2, 2009-05-17¶ - Added validation for data format property “Allowed characters”, which can be used with all data formats. - Added data format property “Header” to specify the number of header rows that should be skipped without validation. This property can be used with all data formats. - Added data format property “Sheet” to specify the number of the sheet to validate in spreadsheet data formats (Excel and ODS). - Added complex ranges that consist of several sub ranges separated by a comma (,). For example: “10:20, 30:40” means that a value must be between 10 and 20 or 30 and 40. - Moved forums to. - Moved project site and issue tracker to. - Fixed handling of data rows with too few or too many items. - Cleaned up error handling and error messages. Version 0.4.0, 2009-05-06¶ - Added support for ICDs stored in Excel format. In order for this to work, the xlrd Python package needs to be installed. It is available from. - Changed ICD format: Inserted a new column after the field name and before the field type that can contain an optional example value. This enables readers to quickly grasp the meaning of a field by taking a glimpse at the first few columns instead of having to “decipher” the field type and rule. Version 0.3.1, 2009-05-03¶ Added proper error messages for several possible error the user might make when writing an ICD. So far these errors resulted into confusing messages about failed assertions, attempted NoneTypeaccesses and the like. Added requirement that field names in the ICD only use ASCII letters, digits and underscore (_). This is necessary to prevent Python errors in checks that refer to field values using Python variables, such as DistinctCount and IsUnique. Changed CSV parser to use Python’s built in one. This works around the following issues: - Improved performance when working with CSV data (about 4 times faster). - Error when reading valid CSV data that contained nothing but a single item separator. However, it also introduces new issues: - Increased memory usage when working with CSV data because csv.readerdoes not fit well with the AbstractParserclass. Currently the whole file is read into memory. - Lack of any error detection in the CSV structure. For example, unclosed quotes at the end or inconsistent line feeds do not raise any errors. On the long run, cutplace will need its own CSV parser. If only this would not be so boring to code... Improved error messages for broken field names and types in the ICD. Version 0.3.0, 2009-04-28¶ Fixed error messages in case field name or type was missing in ICD. Fixed handling of percent sign (%) in DateTimefield format. Changed syntax to specify ranges like field lengths or rules for Integerfields formats. Use ”:” instead of ”...”. There are basically two reasons for this change: Firstly, this looks more Python-like and thus more consistent with other parts of the ICD like the “Checks” section which also uses Python syntax in various places. Secondly, this avoids issues with Excel which under certain circumstances changes the 3 characters in ”...” to a single character ellipsis. Using ”:” still is not without issues though: if you use a spreadsheet application to author ICDs, most of them think of a value like “1:60” (which could for example specify a field length between 1 and 60 characters) to refer to a time of 1 hour and 60 minutes. To avoid any confusion, disable the cell format auto detection of the spreadsheet application by changing all cells to contain “Text”. Version 0.2.2, 2009-04-07¶ - Added support to use data encodings other than ASCII by specifying them in the data format section of the ICD using the encoding property. - Added support for fixed data format. - Added command line option --browseto be used together with --webin order to open the validation page in the web browser. - Added command line option --icd-encodingto specify the character encoding to be used with ICDs in CSV format. Version 0.2.1, 2009-03-29¶ - Added support for ICDs in ODS format for command line client. - Added cutplace.exefor Windows, which will be generated during installation. - Added automatic installation of setuptools when you try to build cutplace using the Subversion repository. This feature is provided by ez_setup.py, which is available from the setuptools site. - Fixed cutplace script, which did exit with an ExitQuietlyOptionErrorfor options that just showed some information and exited (such as Version 0.2.0, 2009-03-27¶ - Added option --weband --portto launch web server providing a simple graphical user interface for validation. - Changed --listencodingsto --list-encodings. Version 0.1.2, 2009-03-22¶ - Added DistinctCountcheck. - Added IsUniquecheck. - Added command line option --trace. - Added support to validate an ICD when no data are specified in the command line. - Cleaned up error messages.
http://cutplace.readthedocs.io/en/latest/changes.html
CC-MAIN-2018-26
refinedweb
3,841
58.79
This question follows on from the following: Communicating between NodeJS and C using node-ipc and unix sockets In regards to the accepted solution (), I was wondering if someone might be able to clarify exactly how to send data from C to Node.js. The solution demonstrates sending data from Node.js to C, but not in reverse. I have an application that requires two-way communications, so the missing component is critical for me. My understanding of unix sockets that one of either write, send or sendmsg should be able to do the job, however, I am not having any luck. If this understanding is incorrect, please advise. In order to get a trivial example running, lets say when a message is read in the C code, lets send back a message and try to trigger the ipc.of[socketId].on('message',...) event on the node server. Which means I am trying to turn this: while ( (rc=read(cl,buf,sizeof(buf))) > 0) { printf("read %u bytes: %.*s\n", rc, rc, buf); } Into this:); } } This would mean that the complete server.c code now becomes: #include <stdio.h> #include <unistd.h> #include <sys/socket.h> #include <sys/un.h> #include <stdlib.h> #include <string.h> //Missing from original server.c char *socket_path = "/tmp/icp-test"; int main(int argc, char *argv[]) { struct sockaddr_un addr; char buf[100]; int fd,cl,rc; if (argc > 1) socket_path=argv[1]; if ( (fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { perror("socket error"); exit(-1); } memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; if (*socket_path == '\0') { *addr.sun_path = '\0'; strncpy(addr.sun_path+1, socket_path+1, sizeof(addr.sun_path)-2); } else { strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path)-1); unlink(socket_path); } if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) { perror("bind error"); exit(-1); } if (listen(fd, 5) == -1) { perror("listen error"); exit(-1); } while (1) { if ( (cl = accept(fd, NULL, NULL)) == -1) { perror("accept error"); continue; }); } } if (rc == -1) { perror("read"); exit(-1); } else if (rc == 0) { printf("EOF\n"); close(cl); } } return 0; } Now unfortunately, the write message for me returns code -1, and is not received by the node.js server. The client.js code remains unchanged, and is as provided in the original question. Can someone please clarify what I am doing learning js, I've search this question, but i can't find any solution for decode eval('eval(function...
https://cmsdk.com/node-js/communicating-between-c-and-nodejs-using-nodeipc-and-unix-sockets.html
CC-MAIN-2019-09
refinedweb
400
50.33
Subject: Re: [boost] [system] Header-only Boost.System by default ? From: Marc Glisse (marc.glisse_at_[hidden]) Date: 2017-10-15 21:48:26 On Sun, 15 Oct 2017, Niall Douglas via Boost wrote: >> So personally I stay inclined that defining >> BOOST_ERROR_CODE_HEADER_ONLY+BOOST_SYSTEM_NO_DEPRECATED would be a >> better default in the future. :D > > Requiring use from a DLL wholly prevents misoperation on Windows and > Mac, unless you mix Boost versions. That's why those macros are off by > default and should stay that way. It would be great to avoid talking about the 2 macros at the same time, since they do not do the same thing. BOOST_SYSTEM_NO_DEPRECATED mostly removes some old synonyms, which otherwise cause #include <boost/system/error_code.hpp> int main(){} to require linking with boost_system. This happens to a lot of users, where the file is included indirectly through other boost packages. If it really has the same dangers as BOOST_ERROR_CODE_HEADER_ONLY (are you sure about that? Is it about boost::throws?), then it should be split into 2 macros, where one only removes the old synonyms and can be enabled by default. -- Marc Glisse Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2017/10/239288.php
CC-MAIN-2019-39
refinedweb
207
68.77
request processing in servlets request processing in servlets how request processing is done in servlets and jsp Please visit the following links: JSP Tutorials Servlet Tutorials Here, you will find several examples of processing request servlets servlets why we require wrappers in servlets? what are its uses? Please explain These wrappers classes help you to modify request...:// servlets javax.servlet.GenericServlet and serves as the base class for HTTP servlets. HttpServlet-Request... package supports the development of servlets that use the HTTP protocol. The classes... specific features, including request and response headers, different request servlets servlets Hi what is pre initialized servlets, how can we achives? When servlet container is loaded, all the servlets defined... the request it loads the servlet. But in some cases if you want your servlet... the cookie information using the HTTP request headers. When cookie based session... sends a new request. By this cookie, the server is able to identify the user if it can remember difference between one client request and the other. HTTP is a stateless protocol because each request is executed independently without any servlets startup or when the first request is made. 2)Initialization: After creating... initialization parameters to the init() method. 3)Servicing the Request: After... for service. Servlet creates seperate threads for each request. The sevlet SERVLETS SERVLETS I have two Servlet Containers, I want to send a request from one Servlet from one container to one Servlet in the other container, How can I do servlets what servlets on the client from some server as a request to it. The doGet cannot be used to send too Servlets Servlets when i deployed the following servlet program in tomcat i get the following errors description The server encountered an internal error () that prevented it from fulfilling this request. exception Sessions in servlets Sessions in servlets What is the use of sessions in servlets?  .... This is often the case, but the HTTP protocol is basically a request-response mechanism with no necessary connection between one request and the next Servlets Programming Servlets Programming Hi this is tanu, This is a code for knowing...; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ public void doGet(HttpServletRequest request, HttpServletResponse Java Servlets . It postprocess a request ,i.e, gather data from a submitted HTML form and doing some jsp and servlets the request submitted from browser and process the data and redirect it to JSP Servlets - JDBC { public void doGet(HttpServletRequest request, HttpServletResponse response) throws request header and response - JSP-Servlet request header and response hi sir, i have facing some problem in this qustion:- Create a servlet that accept a name and a phone number... the following link: Thanks deploying - Java Beginners servlets deploying how to deploy the servlets using tomcat?can you... doGet( HttpServletRequest request, HttpServletResponse response ) throws...(""); out.println("HTTP Request Header"); out.println(""); out.println servlets servlets what is the duties of response object in servlets servlets servlets why we are using servlets servlets - JSP-Servlet first onwards i.e., i don't know about reports only i know upto servlets... { protected void processRequest(HttpServletRequest request...(HttpServletRequest request, HttpServletResponse response) throws servlets what are advantages of servlets what are advantages of servlets Please visit the following link: Advantages Of Servlets servlets - JSP-Servlet servlets. Hi friend, employee form in servlets...;This is servlets code. package javacode; import java.io.*; import java.sql.... InsertDataAction extends HttpServlet{ public void doGet(HttpServletRequest request servlets - Servlet Interview Questions which handles the requests. public void doPost(HttpServletRequest request...(HttpServletRequest request, HttpServletResponse response) throws... = response.getWriter(); String title = "Reading All Request Parameters servlets and jsp - JSP-Servlet servlets and jsp HELLO GOOD MORNING, PROCEDURE:HOW TO RUN... FOR ME,IN ADVANCE THANK U VERY MUCH. TO Run Servlets in Compand... to browzer and request(give url) i never used NETBEANS instead i used Eclipse jsp,servlets - JSP-Servlet that arrays in servlets and i am getting values from textbox in jsp... void doPost(HttpServletRequest request, HttpServletResponse response)throws InsertDataAction extends HttpServlet{ public void doGet(HttpServletRequest request... - Servlet Interview Questions with request parameter or context parameter; Test.java ------------- public class Test extends HttpServlet { public void doPost(HttpServletRequest request...(request, response); } } Test2.java ----------- public class Test2 - Java Beginners (); /** * Processes requests for both HTTP GET and POST methods. * @param request servlet request * @param response servlet response */ protected void processRequest(HttpServletRequest request, HttpServletResponse response Servlets - Java Interview Questions doGet(HttpServletRequest request, HttpServletResponse response Servlets - JSP-Servlet extends HttpServlet{ public void doPost(HttpServletRequest request...().getRequestDispatcher("/src/saving.jsp").forward(request,response.../login.jsp").forward(request,response); System.out.println("not sucessfullet Interview Questions extends HttpServlet { public void doGet(HttpServletRequest request servlets - Servlet Interview Questions request, HttpServletResponse response)throws IOException, ServletException servlets servlets what are different authentication options available in servlets There are four ways of authentication:- HTTP basic authentication HTTP digest authentication HTTPS client authentication Form-based The Advantages of Servlets Advantages of Java Servlets  ... that the servlets are written in java and follow well known standardized APIs so.... So servlets are write once, run anywhere (WORA) program. Powerful We can do servlets the servlets Servlets SERVLETS Servlets,Jsp,Javascript - JSP-Servlet Servlets,Jsp,Javascript Hi in my application i am creating a file from servlet whenever user clickes the button create file , but as the contents...(HttpServletRequest request, HttpServletResponse response)throws Creating methods in servlets - JSP-Servlet ); /** /** * Processes requests for both HTTP GET and POST methods. * @param request servlet request * @param response servlet response */ private String name...; protected void processRequest(HttpServletRequest request Send Cookies in Servlets Send Cookies in Servlets  ... in servlets. Cookies are small bits of information that a Web server sends... the cookies on request. When you run the program you will get the following output read text file in Servlets How to read text file in Servlets  ... file in servlets. In this example we will use the input stream to read the text... in servlets program. You can use this code in your application to read some request to help request to help how to write the program for the following details in java Employee Information System An organization maintains the following data about each employee. Employee Class Fields: int Employee ID String Name Advertisements If you enjoyed this post then why not add us on Google+? Add us to your Circles
http://roseindia.net/tutorialhelp/comment/84888
CC-MAIN-2016-18
refinedweb
1,045
56.05
I have 2 segmented images. One is otsu binary, and the other is outer boundary obtains from otsu's. Otsu binary: Object boundary: And code to find centroids like this:))] The mistake is quite simple. Your algorithm processes only black pixels, due to this condition: if (img[x,y] == 0):. Your image of the boundary contains a large proportion of black pixels. It is safe to assume that the centroid of all the black pixels in such image would be very close to the center of the image. The image in question is 402 pixels wide, and 302 pixels high. Your algorithm gives us (x=201, y=151) as the centroid -- this matches the expectation. To correctly process the object boundary, we need to make the boundary black, and everything else white. This is simple, just invert the image (e.g. 255 - img). Then your algorithm returns (x=165, y=123), which makes a lot more sense. import cv2 import numpy as np))] a = cv2.imread('cnt.png', 0) c1 = getCentroid(a) # Original c2 = getCentroid(255 - a) # Inverse b = cv2.cvtColor(a, cv2.COLOR_GRAY2BGR) cv2.circle(b, (c1[1], c1[0]), 3, (0,0,255)) cv2.circle(b, (c2[1], c2[0]), 3, (0,255,0)) cv2.imwrite('cnt_out.png', b) Note: Red is the centroid from original image, Green from the inverted image.
https://codedump.io/share/1PrxxoC1HFfh/1/how-to-get-object-centroid-just-from-object-boundary
CC-MAIN-2017-09
refinedweb
224
67.65
Tool that I made to help my personal workflow for creating rigging controls. I'm releasing it in hopes that others find it as helpful as I do. This product comes as is and is free to use however you see fit. Features include: + 35 different shapes to create + Creates controls as a parent/child of selected objects, in world space at selected objects, or at the origin. + Name created controls or just use a suffix. + Change control colors at shape level so children don't inherit drawing overrides. + Replace multiple control shapes with either one or an equal amount of replacement shapes. + Mirror control shapes from either side of a rig. + Included instructions in "bs_controls.py" for how to add more controls Installation: # Copy "bs_controls.py" and "bs_controlsUI.py" into your Maya scripts directory. # Add a shelf button with the following python code: import bs_controlsUI reload(bs_controlsUI) bsCon = bs_controlsUI.BSControlsUI() bsCon.bsControlsUI() Please use the Feature Requests to give me ideas. Please use the Support Forum if you have any questions or problems. Please rate and review in the Review section.
https://jobs.highend3d.com/maya/script/free-control-curves-ui-for-maya
CC-MAIN-2021-39
refinedweb
182
60.51
> For processes disappearing (if that can at all happen), we could solve > that by storing the jobs a process has accepted (started working on), > so if a worker process is lost, we can mark them as failed too. Sure, this would be reasonable behavior. I had considered it but decided it as a larger change than I wanted to make without consulting the devs. > I was already working on this issue last week actually, and I managed > to do that in a way that works well enough (at least for me): If I'm reading this right, you catch the exception upon pickling the result (at which point you have the job/i information already; totally reasonable). I'm worried about the case of unpickling the task failing. (Namely, the "task = get()" line of the "worker" method.) Try running the following: """ #!/usr/bin/env python import multiprocessing p = multiprocessing.Pool(1) def foo(x): pass p.apply(foo, [1]) """ And if "task = get()" fails, then the worker doesn't know what the relevant job/i values are. Anyway, so I guess the question that is forming in my mind is, what sorts of errors do we want to handle, and how do we want to handle them? My answer is I'd like to handle all possible errors with some behavior that is not "hang forever". This includes handling children processes dying by signals or os._exit, raising unpickling errors, etc. I believe my patch provides this functionality. By adding the extra mechanism that you've written/proposed, we can improve the error handling in specific recoverable cases (which probably constitute the vast majority of real-world cases).
https://bugs.python.org/msg110152
CC-MAIN-2019-18
refinedweb
278
63.39
- 11 Dec 2007 04:48:27 UTC - Distribution: Class-Handle - Module version: 1.07 - Source (raw) - Browse (raw) - Changes - How to Contribute - Issues (1) - Testers (1988 / 4 / 1) - KwaliteeBus factor: 1 - 69.28% Coverage - License: perl_5 - Perl: v5.5.0 - Activity24 month - Tools - Download (26.03KB) - MetaCPAN Explorer - Permissions - Permalinks - This version - Latest version - Dependencies - Class::ISA - Class::Inspector - and possibly others - Reverse dependencies - CPAN Testers List - Dependency graph - NAME - SYNOPSIS - DESCRIPTION - UNIVERSAL API - METHODS - BUGS - SUPPORT - AUTHOR - SEE ALSO NAME Class::Handle - Create objects that are handles to Classes SYNOPSIS #(); DESCRIPTIONand Class::Inspectorfor obtaining information about a Class, and some additional task methods, such as loadto common tasks relating to classes. UNIVERSAL API To ensure we maintain compliance with other classes that rely on methods provided by UNIVERSAL, Class::Handle acts in the normal way when something like <Class::Handle-VERSION>> is called. That is, it returns the version of Class::Handle itself. When UNIVERSALmethodsand canmethods. METHODS new $class The newconstructor name The c<name> method returns the name of the class as original specified in the constructor. VERSION Find the version for the class. Does not check that the class is loaded ( at this time ). Returns the version on success, undefif the class does not defined a $VERSION CODEref to the function is the method is available, or false if the class does not have that method available. installed. loaded Checks to see if a class is loaded. In this case, "class" does NOT mean "module". The loadedmethod will return true for classes that do not have their own file. For example, if a module Foocontains the classes Foo, Foo::Barand Foo::Buffy, the loadedmethod will return true for all of the classes. Returns true if the class is loaded, or false otherwise. filename Returns the base filename for a class. For example, for the class Foo::Bar, loadedwould return "Foo/Bar.pm". The filenamemethod is platform neutral, it should always return the filename in the correct format for your platform. resolved_filename @extra_paths The resolved_filenamew. function_refs Returns a list of references to all the functions in the classes immediate namespace. Returns a reference to an array of CODE refs of the functions on success, or undefon error or if the class is not loaded. function_exists $function Checks to see if the function exists in the class. Note that this is as a function, not as a method. To see if a method exists for a class, use the canmethod in UNIVERSAL, and hence to every other class. Returns true if the function exists, false if the function does not exist, or undefon error, or if the class is not loaded. methods @options. subclasses The subclassesmethod will search then entire namespace (and thus all currently loaded classes) to find all of the subclasses of the class handle. The actual test will be done by calling isaon the class as a static method. (i.e. <My::Class-isa($class)>>. Returns a reference to a list of the names of the loaded classes that match the class provided, or false is none match, or undefif the class name provided is invalid. super_path The super_pathmethod is a straight pass through to the Class::ISA::super_pathfunction.method. Module Install Instructions To install Class::Handle, copy and paste the appropriate command in to your terminal. cpanm Class::Handle perl -MCPAN -e shell install Class::Handle For more information on module installation, please visit the detailed CPAN module installation guide.
https://web-stage.metacpan.org/pod/Class::Handle
CC-MAIN-2022-33
refinedweb
575
54.73
Import the necessary Python libraries first. For details, see Part I. The Data: “diabetes” Dataset from Scikit Learn Scikit learn comes with some standard datasets, one of which is the ‘diabetes’ dataset. In this dataset, ten baseline variables(features), age, sex, body mass index, average blood pressure, and six blood serum measurements(s1, s2, s3, s4, s5 and s6) were obtained for each of 442 diabetes patients, along with response of interest, a quantitative measure of disease progression (y) one year after baseline. This dataset represents a classic regression problem, where the challenge is to model response y based on the ten features. This model can then be used for two purposes: - one, to identify the important features (out of the ten mentioned above) that contribute to disease progression - and two, to predict the response for future patients based on the features Each of these ten feature variables has been mean-centred and scaled by the standard deviation times n_samples (i.e. the sum of squares of each column totals 1) Let us get the diabetes dataset from the “datasets” submodule of scikit learn library and save it in an object called “diabetes” using the following commands: In [34]: from sklearn import datasets diabetes = datasets.load_diabetes() We now have loaded the data in the “diabetes” object. But in order to train models on it, we first need to get it in a format that is conducive and convenient for this process. In the next step, we do just that. Data Preprocessing The “diabetes” object belongs to the class Bunch, i.e. it is a collection of various objects bunched together in a dictionary-like format. These objects include the feature matrix “data” and the target vector “target”. We will now create a pandas dataframe containing all the ten features and the response variable (diab_measure) using the following commands: In [35]: df=pd.DataFrame(diabetes.data) df.columns= diabetes.feature_names # Creating a new column containing response variable ‘y’ (a quantitative measure of disease progressionone year after baseline) df[‘diabetes_measure’]=diabetes.target df.head() All the features and the response variable are now in a single dataframe object. In the next step, we will create the feature matrix(X) and the response variable(y) using the dataframe we just created: In [36]: # Creating the feature matrix X X=df.iloc[:,:-1] # Creating the response vector y y=df.iloc[:,-1] Now that we have our feature matrix and the response vector, we can move on to build and compare different regression models. But in order to do that, we first need to choose a suitable methodology to evaluate and compare these models. In the next section, we do just that. In the next installment, the author will go over a Model Evaluation Metric. Visit QuantInsti Blog to download the ready-to-use.
https://www.tradersinsight.news/ibkr-quant-news/building-and-regularizing-linear-regression-scikit-learn-2/
CC-MAIN-2020-24
refinedweb
470
51.89
The speedy-slice package Speedy slice sampling. This implementation of the slice sampling algorithm uses lens as a means to operate over generic indexed traversable functors, so you can expect it to work if your target function takes a list, vector, map, sequence, etc. as its argument. Additionally you can sample over anything that's an instance of both Num and Variate, which is useful in the case of discrete parameters. Exports a mcmc function that prints a trace to stdout, a chain function for collecting results in memory, and a slice transition operator that can be used more generally. import Numeric.MCMC.Slice import Data.Sequence (Seq, index, fromList) bnn :: Seq Double -> Double bnn xs = -0.5 * (x0 ^ 2 * x1 ^ 2 + x0 ^ 2 + x1 ^ 2 - 8 * x0 - 8 * x1) where x0 = index xs 0 x1 = index xs 1 main :: IO () main = withSystemRandom . asGenIO $ mcmc 10000 1 (fromList [0, 0]) bnn Properties Modules - Numeric Downloads - speedy-slice-0.3.0.tar.gz [browse] (Cabal source package) - Package description (included in the package) Maintainer's Corner For package maintainers and hackage trustees
http://hackage.haskell.org/package/speedy-slice
CC-MAIN-2017-22
refinedweb
181
54.42
In my namespace I have services k get svc NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE blue-service NodePort 10.107.127.118 <none> 80:32092/TCP 60m demo ClusterIP 10.111.134.22 <none> 80/TCP 3d I added blue-service to /etc/hosts It failes again wget -O- blue-service --2022-06-13 11:11:32-- Resolving blue-service (blue-service)... 10.107.127.118 Connecting to blue-service (blue-service)|10.107.127.118|:80... failed: Connection timed out. Retrying. I decided to chech with describe Name: blue-service Namespace: default Labels: app=blue Annotations: <none> Selector: app=blue Type: NodePort IP Family Policy: SingleStack IP Families: IPv4 IP: 10.107.127.118 IPs: 10.107.127.118 Port: <unset> 80/TCP TargetPort: 8080/TCP NodePort: <unset> 32092/TCP Endpoints: 172.17.0.39:8080,172.17.0.40:8080,172.17.0.41:8080 Session Affinity: None External Traffic Policy: Cluster Events: <none> Why? >Solution : The services you are referring to do not have an external IP (the External IP field is empty) so you cannot access those services. If you want to access those services, you either need to - Make them a LoadBalancer service type which will give them an external IP or - Use kubectl port-forwardto connect a local port on your machine to the service then use localhost:xxxxto access the service If you want to map a DNS name to the service, you should look at the External DNS project as mentioned in this answer which will allow you to create DNS entries in your provider’s DNS service (if you are running the cluster on a managed platform) OR, use nip.io if you’re only testing
https://devsolus.com/2022/06/13/why-kubernetes-services-can-not-be-resolved/
CC-MAIN-2022-27
refinedweb
288
60.85
# Complexity Waterfall and Architecture on Demand ![Logo](https://habrastorage.org/r/w1560/webt/g9/_9/wk/g9_9wkgu4h6i8xyelaq9p5nwmjy.png) When talking about "bad code" people almost certainly mean "complex code" among other popular problems. The thing about complexity is that it comes out of nowhere. One day you start your fairly simple project, the other day you find it in ruins. And no one knows how and when did it happen. But, this ultimately happens for a reason! Code complexity enters your codebase in two possible ways: with big chunks and incremental additions. And people are bad at reviewing and finding both of them. When a big chunk of code comes in, the reviewer will be challenged to find the exact location where the code is complex and what to do about it. Then, the review will have to prove the point: why this code is complex in the first place. And other developers might disagree. We all know these kinds of code reviews! ![Number of lines for review and comments ratio](https://habrastorage.org/r/w1560/getpro/habr/post_images/198/8ff/e0e/1988ffe0e3d5dc3b29b4743630b52e06.png) The second way of complexity getting into your code is incremental addition: when you submit one or two lines to the existing function. And it is extremely hard to notice that your function was alright one commit ago, but now it is too complex. It takes a good portion of concentration, reviewing skill, and good code navigation practice to actually spot it. Most people (like me!) lack these skills and allow complexity to enter the codebase regularly. So, what can be done to prevent your code from getting complex? We need to use automation! Let's make a deep dive into the code complexity and ways to find and finally solve it. In this article, I will guide you through places where complexity lives and how to fight it there. Then we will discuss how well written simple code and automation enable an opportunity of "Continous Refactoring" and "Architecture on Demand" development styles. Complexity explained -------------------- One may ask: what exactly "code complexity" is? And while it sounds familiar, there are hidden obstacles in understanding the exact complexity location. Let's start with the most primitive parts and then move to higher-level entities. Remember, that this article is named "Complexity Waterfall"? I will show you how complexity from the simplest primitives overflows into the highest abstractions. I will use `python` as the main language for my examples and [`wemake-python-styleguide`](https://github.com/wemake-services/wemake-python-styleguide) as the main linting tool to find the violations in my code and illustrate my point. ### Expressions All your code consists of simple expressions like `a + 1` and `print(x)`. While expressions themself are simple, they might unnoticeably overflow your code with complexity at some point. Example: imagine that you have a dictionary that represents some `User` model and you use it like so: ``` def format_username(user) -> str: if not user['username']: return user['email'] elif len(user['username']) > 12: return user['username'][:12] + '...' return '@' + user['username'] ``` It looks pretty simple, doesn't it? In fact, it contains two expression-based complexity issues. It [`overuses 'username'` string](https://wemake-python-stylegui.de/en/latest/pages/usage/violations/complexity.html#wemake_python_styleguide.violations.complexity.OverusedStringViolation) and uses [magic number](https://wemake-python-stylegui.de/en/latest/pages/usage/violations/best_practices.html#wemake_python_styleguide.violations.best_practices.MagicNumberViolation) `12` (why do we use this number in the first place, why not `13` or `10`?). It is hard to find these kinds of things all by yourself. Here's how the better version would look like: ``` #: That's how many chars fit in the preview box. LENGTH_LIMIT: Final = 12 def format_username(user) -> str: username = user['username'] if not username: return user['email'] elif len(username) > LENGTH_LIMIT: # See? It is now documented return username[:LENGTH_LIMIT] + '...' return '@' + username ``` There are different problems with expression as well. We can also have [overused expressions](https://wemake-python-stylegui.de/en/latest/pages/usage/violations/complexity.html#wemake_python_styleguide.violations.complexity.OverusedExpressionViolation): when you use `some_object.some_attr` attribute everywhere instead of creating a new local variable. We can also have [too complex logic conditions](https://wemake-python-stylegui.de/en/latest/pages/usage/violations/complexity.html#wemake_python_styleguide.violations.complexity.TooManyConditionsViolation) or [too deep dot access](https://wemake-python-stylegui.de/en/latest/pages/usage/violations/complexity.html#wemake_python_styleguide.violations.complexity.TooDeepAccessViolation). **Solution**: create new variables, arguments, or constants. Create and use new utility functions or methods if you have to. ### Lines Expressions form code lines (please, do not confuse lines with statements: single statement can take multiple lines and multiple statements might be located on a single line). The first and the most obvious complexity metric for a line is its length. Yes, you heard it correctly. That's why we (programmers) prefer to stick to `80` chars-per-line rule and not because it was [previously used](https://en.wikipedia.org/wiki/Characters_per_line) in the teletypewriters. There are a lot of rumors about it lately, saying that it does not make any sence to use `80` chars for your code in 2k19. But, that's obviously not true. The idea is simple. You can have twice as much logic in a line with `160` chars than in line with only `80` chars. That's why this limit should be set and enforced. Remember, this is *not a stylistic choice*. It is a complexity metric! The second main line complexity metric is less known and less used. It is called [Jones Complexity](https://wemake-python-stylegui.de/en/latest/pages/usage/violations/complexity.html#wemake_python_styleguide.violations.complexity.LineComplexityViolation). The idea behind it is simple: we count code (or `ast`) nodes in a single line to get its complexity. Let's have a look at the example. These two lines are fundamentally different in terms of complexity but have the exact same width in chars: ``` print(first_long_name_with_meaning, second_very_long_name_with_meaning, third) print(first * 5 + math.pi * 2, matrix.trans(*matrix), display.show(matrix, 2)) ``` Let's count the nodes in the first one: one call, three names. Four nodes totally. The second one has twenty-one `ast` nodes. Well, the difference is clear. That's why we use Jones Complexity metric to allow the first long line and disallow the second one based on an internal complexity, not on just raw length. What to do with lines with a high Jones Complexity score? **Solution**: Split them into several lines or create new intermediate variables, utility functions, new classes, etc. ``` print( first * 5 + math.pi * 2, matrix.trans(*matrix), display.show(matrix, 2), ) ``` Now it is way more readable! ### Structures The next step is analyzing language structures like `if`, `for`, `with`, etc that are formed from lines and expressions. I have to say that this point is very language-specific. I'll showcase several rules from this category using `python` as well. We'll start with `if`. What can be easier than a good-old `if`? Actually, `if` starts to get tricky really fast. Here's an example of how one can [`reimplement switch`](https://wemake-python-stylegui.de/en/latest/pages/usage/violations/complexity.html#wemake_python_styleguide.violations.complexity.TooManyElifsViolation) with `if`: ``` if isinstance(some, int): ... elif isinstance(some, float): ... elif isinstance(some, complex): ... elif isinstance(some, str): ... elif isinstance(some, bytes): ... elif isinstance(some, list): ... ``` What's the problem with this code? Well, imagine that we have tens of data types that should be covered including customs ones that we are not aware of yet. Then this complex code is an indicator that we are choosing a wrong pattern here. We need to refactor our code to fix this problem. For example, one can use [`typeclass`es](https://github.com/thejohnfreeman/python-typeclasses) or [`singledispatch`](https://docs.python.org/3/library/functools.html#functools.singledispatch). They the same job, but nicer. `python` never stops to amuse us. For example, you can write `with` with [an arbitrary number of cases](https://wemake-python-stylegui.de/en/latest/pages/usage/violations/consistency.html#wemake_python_styleguide.violations.consistency.MultipleContextManagerAssignmentsViolation), which is too mentally complex and confusing: ``` with first(), second(), third(), fourth(): ... ``` You can also write comprehensions with any number of [`if`](https://wemake-python-stylegui.de/en/latest/pages/usage/violations/consistency.html#wemake_python_styleguide.violations.consistency.MultipleIfsInComprehensionViolation) and [`for`](https://wemake-python-stylegui.de/en/latest/pages/usage/violations/complexity.html#wemake_python_styleguide.violations.complexity.TooManyForsInComprehensionViolation) expressions, which can lead to complex, unreadable code: ``` [ (x, y, z) for x in x_coords for y in y_coords for z in z_coords if x > 0 if y > 0 if z > 0 if x + y <= z if x + z <= y if y + z <= x ] ``` Compare it with the simple and readable version: ``` [ (x, y, z) for x, y, x in itertools.product(x_coords, y_coords, z_coords) if valid_coordinates(x, y, z) ] ``` You can also accidentally include [`multiple statements inside a try`](https://wemake-python-stylegui.de/en/latest/pages/usage/violations/complexity.html#wemake_python_styleguide.violations.complexity.TooLongTryBodyViolation) case, which is unsafe because it can raise and handle an exception in an expected place: ``` try: user = fetch_user() # Can also fail, but don't expect that log.save_user_operation(user.email) # Can fail, and we know it except MyCustomException as exc: ... ``` And that's not even 10% of cases that can and will go wrong with your `python` code. There are many, many [more edge cases](https://wemake-python-stylegui.de/en/latest/pages/usage/violations/complexity.html#summary) that should be tracked and analyzed. **Solution**: The only possible solution is to use [a good linter](https://wemake-python-stylegui.de) for the language of your choice. And refactor complex places that this linter highlights. Otherwise, you will have to reinvent the wheel and set custom policies for the exact same problems. ### Functions Expressions, statements, and structures form functions. Complexity from these entities flows into functions. And that's where things start to get intriguing. Because functions have literally dozens of complexity metrics: both good and bad. We will start with the most known ones: [cyclomatic complexity](https://en.wikipedia.org/wiki/Cyclomatic_complexity) and function's length measured in code lines. Cyclomatic complexity indicates how many turns your execution flow can take: it is almost equal to the number of unit tests that are required to fully cover the source code. It is a good metric because it respects the semantic and helps the developer to do the refactoring. On the other hand, a function's length is a bad metric. It does not coop with the previously explained Jones Complexity metric since we already know: multiple lines are easier to read than one big line with everything inside. We will concentrate on good metrics only and ignore bad ones. Based on my experience multiple useful complexity metrics should be counted instead of regular function's length: * Number of function decorators; lower is better * Number of arguments; lower is better * Number of annotations; higher is better * Number of local variables; lower is better * Number of returns, yields, awaits; lower is better * Number of statements and expressions; lower is better The combination of all these checks really allows you to write simple functions (all rules are also applied to methods as well). When you will try to do some nasty things with your function, you will surely break at least one metric. And this will disappoint our linter and blow your build. As a result, your function will be saved. **Solution**: when one function is too complex, the only solution you have is to split this function into multiple ones. ### Classes The next level of abstraction after functions are classes. And as you already guessed they are even more complex and fluid than functions. Because classes might contain multiple functions inside (that are called method) and have other unique features like inheritance and mixins, class-level attributes and class-level decorators. So, we have to check all methods as functions and the class body itself. For classes we have to measure the following metrics: * Number of class-level decorators; lower is better * Number of base classes; lower is better * Number of class-level public attributes; lower is better * Number of instance-level public attributes; lower is better * Number of methods; lower is better When any of these is overly complicated — we have to ring the alarm and fail the build! **Solution**: refactor your failed class! Split one existing complex class into several simple ones or create new utility functions and use composition. Notable mention: one can also track [cohesion](https://github.com/mschwager/cohesion) and coupling [metrics](https://stackoverflow.com/questions/3085285/difference-between-cohesion-and-coupling) to validate the complexity of your OOP design. ### Modules Modules do contain multiple statements, functions, and classes. And as you might have already mentioned we usually advise to split functions and classes into new ones. That's why we have to keep and eye on module complexity: it literally flows into modules from classes and functions. To analyze the complexity of the module we have to check: * The number of imports and imported names; lower is better * The number of classes and functions; lower is better * The average complexity of functions and classes inside; lower is better What do we do in the case of a complex module? **Solution**: yes, you got it right. We split one module into several ones. ### Packages Packages contain multiple modules. Luckily, that's all they do. So, he number of modules in a package can soon start to be too large, so you will end up with too many of them. And it is the only complexity that can be found with packages. **Solution**: you have to split packages into sub-packages and packages of different levels. Complexity Waterfall effect --------------------------- We now have covered almost all possible types of abstractions in your codebase. What have we learned from it? The main takeaway, for now, is that most problems can be solved with ejecting complexity to the same or upper abstraction level. ![Complexity Waterfall](https://habrastorage.org/r/w1560/getpro/habr/post_images/9b6/8ad/453/9b68ad45340cdf61f51a8deb2c07930d.png) This leads us to the most important idea of this article: do not let your code be overflowed with the complexity. I will give several examples of how it usually happens. Imagine that you are implementing a new feature. And that's the only change you make: ``` +++ if user.is_active and user.has_sub() and sub.is_due(tz.now() + delta): --- if user.is_active and user.has_sub(): ``` Looks ok, I would pass this code on review. And nothing bad would happen. But, the point I am missing is that complexity overflowed this line! That's what `wemake-python-styleguide` will report: ![wemake-python-styleguide-output](https://habrastorage.org/r/w1560/getpro/habr/post_images/c87/b9e/0e5/c87b9e0e584a8cd01235e0ae7695a6c0.png) Ok, we now have to solve this complexity. Let's make a new variable: ``` class Product(object): ... def can_be_purchased(self, user_id) -> bool: ... is_sub_paid = sub.is_due(tz.now() + delta) if user.is_active and user.has_sub() and is_sub_paid: ... ... ... ``` Now, the line complexity is solved. But, wait a minute. What if our function has too many variables now? Because we have created a new variable without checking their number inside the function first. In this case we will have to split this method into several ones like so: ``` class Product(object): ... def can_be_purchased(self, user_id) -> bool: ... if self._has_paid_sub(user, sub, delta): ... ... def _has_paid_sub(self, user, sub, delta) -> bool: is_sub_paid = sub.is_due(tz.now() + delta) return user.is_active and user.has_sub() and is_sub_paid ... ``` Now we are done! Right? No, because we now have to check the complexity of the `Product` class. Imagine, that it now has too many methods since we have created a new `_has_paid_sub` one. Ok, we run our linter to check the complexity again. And turns out our `Product` class is indeed too complex right now. Our actions? We split it into several classes! ``` class Policy(object): ... class SubcsriptionPolicy(Policy): ... def can_be_purchased(self, user_id) -> bool: ... if self._has_paid_sub(user, sub, delta): ... ... def _has_paid_sub(self, user, sub, delta) -> bool: is_sub_paid = sub.is_due(tz.now() + delta) return user.is_active and user.has_sub() and is_sub_paid class Product(object): _purchasing_policy: Policy ... ... ``` Please, tell me that it is the last iteration! Well, I am sorry, but we now have to check the module complexity. And guess what? We now have too many module members. So, we have to split modules into separate ones! Then we check the package complexity. And also possibly split it into several sub-packages. Have you seen it? Because of the well-defined complexity rules our single-line modification turned out to be a huge refactoring session with several new modules and classes. And we haven't made a single decision ourselves: all our refactoring goals were driven by the internal complexity and the linter that reveals it. That's what I call a "Continuous Refactoring" process. You are forced to do the refactoring. Always. This process also has one interesting consequence. It allows you to have "Architecture on Demand". Let me explain. With "Architecture on Demand" philosophy you always start small. For example with a single `logic/domains/user.py` file. And you start to put everything `User` related there. Because at this moment you probably don't know what your architecture will look like. And you don't care. You only have like three functions. Some people fall into architecture vs code complexity trap. They can overly-complicate their architecture from the very start with the full repository/service/domain layers. Or they can overly-complicate the source code with no clear separation. Struggle and live like this for years (if they will be able to live for years with the code like this!). "Architecture on Demand" concept solves these problems. You start small, when the time comes — you split and refactor things: 1. You start with `logic/domains/user.py` and put everything in there 2. Later you create `logic/domains/user/repository.py` when you have enough database related stuff 3. Then you split it into `logic/domains/user/repository/queries.py` and `logic/domains/user/repository/commands.py` when the complexity tells you to do so 4. Then you create `logic/domains/user/services.py` with `http` related stuff 5. Then you create a new module called `logic/domains/order.py` 6. And so on and so on That's it. It is a perfect tool to balance your architecture and code complexity. And get as much architecture as you truly need at the moment. Conclusion ---------- Good linter does much more than finding missing commas and bad quotes. Good linter allows you to rely on it with architecture decisions and help you with the refactoring process. For example, `wemake-python-styleguide` might help you with the `python` source code complexity, it allows you to: * Successfully fight the complexity at all levels * Enforce the enormous amount of naming standards, best practices, and consistency checks * Easily integrate it into a legacy code base with the help of [`diff` option](https://wemake-python-stylegui.de/en/latest/pages/usage/integrations/legacy.html) or [`flakehell`](https://wemake-python-stylegui.de/en/latest/pages/usage/integrations/flakehell.html) tool, so old violation will be forgiven, but new ones won't be allowed * Enable it into your [CI](), even as a [Github Action](https://github.com/marketplace/actions/wemake-python-styleguide) Do not let the complexity to overflow your code, [use a good linter](https://github.com/wemake-services/wemake-python-styleguide)!
https://habr.com/ru/post/472876/
null
null
3,239
51.44
I am trying to get the Label called "number" to show up directly over the center of the Ellipse. I have tried putting both in the same layout, in different layouts, in AnchorLayouts and RelativeLayouts, and I haven't been able to figure out how to to this. Here's a test version of my python showing the same issue: class BugTester(FloatLayout): def __init__(self): super().__init__() for i in range(1,6): temp = GamePiece(5, "Red") temp.pos = (i*100,i*200) self.add_widget(temp) class BugTestingApp(App): def build(self): return BugTester() class GamePiece(ToggleButton): def __init__(self, number, color, **kwargs): self.number = number self.player_color = color self.background_normal = "5.png" super(GamePiece, self).__init__() if __name__ == '__main__': BugTestingApp().run() And my kivy: <BugTester>: Button: background_disabled_normal: "background.jpg" disabled: True <GamePiece>: id: gamepiece size_hint:(None, None) group: self.player_color border: (0,0,0,0) AnchorLayout: id: layout center: root.center on_size: self.size = root.size anchor_x: "left" anchor_y: "bottom" canvas: Color: rgba: 0,0,0,1 Ellipse: #this is the ellipse in question id: circle size: (root.width/2.5, root.height/3) #pos: -15, -20 pos: root.pos Label: #this is the label I want centered over the ellipse id: number text: str(root.number) color: (1,1,1,1) font_size: root.height/4 bold: True #pos: root.pos Here's what it currently looks like: (one of the togglebuttons is pressed for illustration purposes) In your example, labels are as big as the anchor layouts they belong to, so you can't move them. If you want them to have some other size, then disable size_hint, and use a fixed size (for instance, as big as the ellipses): Label: #this is the label I want centered over the ellipse size_hint: None, None size: (root.width/2.5, root.height/3) id: number text: str(root.number) color: (1,1,1,1) font_size: root.height/4 bold: True #pos: root.pos Result:
http://www.dlxedu.com/askdetail/3/9c52e30def370b3265bbb730b137a55d.html
CC-MAIN-2018-30
refinedweb
326
60.51
Hi All I want to know if we can use Triple DES encyption with a J2ME midlet. And if not can any one tell me how we can do it in the Midlet applications Hi All I want to know if we can use Triple DES encyption with a J2ME midlet. And if not can any one tell me how we can do it in the Midlet applications Bouncy Castle have an encryption package suited for J2ME. shmoove Hi shmoove Thanks for support but when my add my encryption code to my midlet and try to compile it using J2ME wireless toolkit it always fail can u help in this issue. Maybe (and I'm sure others can also help), but you need to give some more information.Maybe (and I'm sure others can also help), but you need to give some more information.can u help in this issue Any error messages, exception, verification errors, etc? one of the errors listing are DEROutputStream.java:3: cannot resolve symbol symbol : class FilterOutputStream location: package io import java.io.FilterOutputStream; It seems that its looking for these files in its classpath to compile even I put the rt.jar of the J2SE in the lib directory and also extract it to the classes directory of the project created with the J2ME wireless toolkit It looks like you're not using the J2ME version. I have never used it so I can't tell you from my own expirience, but they should have a version that uses only J2ME classes. It's not 3DES, but if you want a cipher I've just released a pure Java (and J2ME) implementation of the Tiny Encryption Algorithm here : It's released under an LGPL licence, so you can use them in commercial products (provided you make an enhancements available on the same terms). hello sir good day !! can you please guide me in this problem sir ?? im a j2me programmer i have my form in my emulator named " REGISTRATION" then it have a textfields example NAME: ADDRESS: AGE: something like that then i have my button " SEND " all i want is if i click the button send the data that inserted in that field example NAME:Sushmita takeyi ADDRESS:South korea AGE:35 years old the high lighten color red will be sent to the receiver but that data is secured and it is encrypted when the receiver received it. thanks in regard ! gpd bless !! AnorEnaj2330, please keep the discussion in one or the other of the discussion threads where this problem of yours has already been discussed and answered for you. E.g., this one: In other words, please do not keep reviving old threads with the same questions. You're not likely to get any better results that way. Your next step, instead of repeating the question, is to take the advise you've already been provided, and try it out in your application.
http://developer.nokia.com/community/discussion/showthread.php/237651-LWUIT-Tabs?goto=nextoldest
CC-MAIN-2014-42
refinedweb
493
65.56
In a coding challenge I recently attempted, I found this as an alternative solution to converting numbers to Roman numerals. I don't really understand how this code works. I just figured out what divmod class Integer def to_roman roman_arr = { 1000 => "M", 900 => "CM", 500 => "D", 400 => "CD", 100 => "C", 90 => "XC", 50 => "L", 40 => "XL", 10 => "X", 9 => "IX", 5 => "V", 4 => "IV", 1 => "I" } num = self roman_arr.reduce("") do |res, (arab, roman)| whole_part, num = num.divmod(arab) res << roman * whole_part end end end reduce / fold is the functional programming equivalent to the looping constructs found in imperative languages. ruby is capable of both. foo.reduce("") { |a, i| a + i } is equivalent to a = "" foo.each {|i| a = a + i} a the num = self line saves the instance (the number which receives the to_roman method) in a local variable so you can use it in the block that you pass to reduce.
https://codedump.io/share/uXf82kNr6Vp9/1/roman-numerals-in-ruby
CC-MAIN-2018-17
refinedweb
153
69.72
Using Linux and DOS Together DOSEMU can access files in several different ways, which integrate with DOS and Linux in different ways. The methods are: - image A file which is arranged to look like a DOS hard disk. It is a “virtual” hard disk stored in a file. - partition Direct access to an MS-DOS partition. If the partition is also being used on Linux, it should not be writable. Be aware that you can use mounted partitions as DOSEMU file systems, which can destroy the file system. It is safest if they are both used readonly; if you want to make them writable you should only make one of them writable at a time. In addition, if the DOS partition is writable from DOSEMU, multiple DOSEMU sessions can cause the same kinds of filesystem destruction. - whole disk Use the whole disk directly. Be vary careful with this. When used, it is useful to set it [cw]readonly[ecw]. - redirected access Access any Linux directory via a redirector. This is extremely interesting—read on to learn more about this. Typically, DOSEMU boots off a small image file (a specially constructed file which appears to DOSEMU like a hard disk, with its own file system and master boot record). Floppy disks are treated like conventional floppy disks. DOSEMU can read them—and you need a bootable MSDOS floppy to start the process. To start setting up the virtual hard disk as C: drive, you first boot off the bootable MSDOS floppy, and then do: A>fdisk /mbr A>sys c: Then you can boot off the virtual hard disk C:. This is covered more fully in the DOSEMU documentation. The image hard disk is often used just to get DOSEMU going. You can treat this image as a large virtual hard disk, but the disadvantage is you can only access this disk from DOSEMU. The other forms, which will be explained, can all be accessed from Linux, and MS-DOS partitions can be accessed from raw MS-DOS. DOSEMU supports whole disk access (such as /dev/hdc) and partition access. I have never used whole disk access and there doesn't appear to be a good reason to do it. I have, however, used partition access. Those partitions cannot be mounted by Linux at the same time, since DOSEMU manipulates the physical partition, which will confuse the kernel, and potentially destroy the partition. DOSEMU needs to have access to the physical partitions (you have to make sure you have the permission to read and write). The most interesting method I've found is the redirector. This allows you to treat a Linux file system as a network drive. If you redirect the root of your Linux file system, you can easily access all your linux files in DOSEMU. If you have NFS mounts or an auto mounter running, you can even traverse to other machines seamlessly. Note that everything it finds it must convert to an 8+3 MS-DOS namespace. It works well if no munging is necessary. However, you may see this: F:\dir a* Volume in drive F is s2/dist/X11 Directory of F:\ ARCH 05-26-95 1:01a ACM-4~YX GZ 971,391 06-02-95 11:02p ARENA TAR 604,160 05-19-95 9:43p ARENA~D0 GZ 530,468 05-22-95 8:35p instead of leisner@compudyne$ ls -d a* acm-4.7.tar.gz arch/ arena-96.tar.gz arena.tar Most of the time you can figure out what is meant. I've noticed some problems identifying files which are spelled the same way except for the case of some characters. On Unix they're distinct, but DOS has no notion of case in file names (you will have a problem with makefile and Makefile, for instance). You shouldn't do much on your virtual hard disk beyond booting. I found it effective to have a directory ~/dos. My config.sys on the virtual hard disk looks like this: # make sure we support ems devicehigh=c:\ems.sys # the last drive is m, it can range up to z: # the default is f: lastdrive=m FILES=40 SWITCHES=/f # make a copy of c: drive on l: install=c:\subst.exe l: c:\ # this is the fun part # change the concept of c: drive install=c:\lredir.exe c: LINUX\fs>{home}\dos The last few lines are the most interesting. I'm making the virtual hard disk accessible to dosemu through the L: drive. If you want to “lock down” the virtual hard disk, you make the file readonly with the chmod command. Then, continue booting from the user's ~/dos directory (where an autoexec.bat is expected). This means that autoexec.bat is just a regular Linux file. You can edit it with any Linux editor, but you have to remember to put \r at the end of each line (that's a control-M character; in vi do control-v-m, in Emacs do control-q-m). In my autoexec.bat I have: lredir f: linux\fs\${PWD} lredir e: linux\fs\ set PATH=e:\dos\gnu\bin;e:\dos\c\dos;c:\;c:\bin f: The syntax ${...} allows environment variables to be substituted. PWD is the current working directory. Bash doesn't normally export it for you; I explicitly add export PWD to my .bashrc file. I just map the F: drive to my current working directory. This is very convenient, because when I'm working with DOS files on Linux, I can start up DOSEMU wherever I am at the moment. I map my entire filesystem to E:. This makes almost any file accessible under Linux also accessible under DOSEMU. This includes NFS files. Some programs have a problem with a redirector, since it acts as a network drive. For these programs, you need to use either partition access, image access or a ram
http://www.linuxjournal.com/article/1137?page=0,2
CC-MAIN-2015-35
refinedweb
991
73.68
How to develop GraphQL frontends with Angular and React © Fer Gregory/Shutterstock.com GraphQL, the web API query language developed by Facebook, has been gaining attention for several years now. And also here in the Java Magazine, several articles on the subject matter have appeared, such as in issue 5.18 and 7.18. But while those examined the server-side in detail, the client itself was left out. This article will focus on the usage of a GraphQL interface in the frontend, while also taking a closer look at both Angular and React. GraphQL is a query language, which allows data to be queried in a JSON-like form from a GraphQL interface. Unlike REST, GraphQL does not focus on individual resources with their respective URLs, but on a single GraphQL schema, which is offered by the server. Clients can send queries to this schema and receive the corresponding data from the server. The schema is statically typed, which means that the schema’s developers specify types, which describe what kind of data is offered, and how these correlate to each other. Listing 1 shows an example of a request, as it might occur in a blogging application, with blog articles, authors, and comments. All articles in the listing are queried, but not all of their field are included – only their id and title. The query also contains the authors and comments for each article. We are thereby able to query for the exact data, which is currently required, in a single request. A JSON structure, which corresponds exactly with this query, is the response. { articles { id title authors { name } comments { text } } } There are several options to actually use GraphQL in a client application. Theoretically, it would be possible of course to manually send the queries and in turn to manually prepare the result data for the display. However, there are also frameworks that can support developers in using GraphQL. This is especially useful in times of declarative UI libraries such as React, because it is also possible to declaratively describe data requirements besides the UI. A component then no longer states imperatively how the data is fetched, but only which data is required. The Apollo Client, which is available as open source software, is such a framework that supports this kind of development. Apollo enjoys a good reputation within the GraphQL community and is probably the most widely used client framework for GraphQL applications. But above all, it is also available for various UI frameworks, including React, Angular, Vue.js, native Android, and iOS applications. In this article, we want to focus on the integration and interaction with React, but we will also take a brief look at Angular at the end. The already mentioned blogging platform will serve as an exemplary context. The complete source code of this application can be found on GitHub, server included, which serves as the application’s backend, and provides a ready-made schema. We only need a current Node.js installation to start the React application, then we can use npx create-react-app <projekt-name> to create the app’s basic framework. The next step is to add some JavaScript packages for the Apollo framework: npm install --save apollo-client apollo-cache-inmemory apollo-link-http graphql graphql-tag react-apollo. We will take a closer look at what these packages do exactly in a moment’s notice. The basic idea behind Apollo is that there is a store in the fronted, which manages the application data. UI components describe which data they need via GraphQL, and receive this exact data from the Apollo store. The store takes care of loading the data from the server, if required, and manages them internally. A local cache is used for this purpose, in order to store the data. Therefore, it is transparent to the UI component whether a request from a UI component is supplied from the cache or from the server. Set-up The first step is to set up this exact Apollo store and integrate it into the React application. The code can be seen in Listing 2. The existing index.js file will be adjusted accordingly. The store is created with the class ApolloClient. For the configuration, the values link and cache must be filled. The link is used to tell Apollo where to find the server’s GraphQL schema. In the example, the URI is given as a relative path. Alternatively, complete URIs in the form of are also possible. The second parameter defines how the local caching shall take place. InMemoryCache is the usual variant, which stores data in the memory, but only for the duration of the browser session. There are, however, also alternative implementations, which use the LocalStorage functionalities of browsers, for example, to keep the data permanently available in the browser. In this way, they can also be refilled after a reload of the browser without new network communication. After that, the ApolloClient has to be made available for React. This is done via the component ApolloProvider. This wraps our actual app component and ensures that all underlying React components can use GraphQL. import { ApolloClient } from "apollo-client" import { HttpLink } from "apollo-link-http" import { InMemoryCache } from "apollo-cache-inmemory" import { ApolloProvider } from "react-apollo" const apolloClient = new ApolloClient({ link: new HttpLink({uri: "/api/graphql"}), cache: new InMemoryCache() }); ReactDOM.render( <ApolloProvider client={apolloClient}> <App /> </ApolloProvider> , document.getElementById('root')); Queries This completes the basic setup and we can write a React component, which retrieves and displays data. Therefore, we want to build a component that provides an overview of the existing blog articles. The first step is to consider which data the component needs, and what the corresponding GraphQL query looks like. It is quite common to pack the query into the same file that contains the actual component. This achieves a high level of encapsulation, since a developer who uses the component can no longer see which data sources are addressed and how. Therefore, you only need to touch a single point, if you need to make changes to the query and the display. The query is stored in a local variable and created with the function gql from the graphql-tag package, as shown in Listing 3. A relatively new JavaScript technique, called Tagged Template Strings, is used. This allows multi-line strings to be provided with template parameters, which in turn can be modified directly by a function (in our case gql). It is important that the string is enclosed with back ticks (also known as the French Accent Grave) and not with normal single or double quotation marks. The gql-tag function parses the query string and creates an abstract syntax tree, AST for short, which is then used to execute the query. This is done with the React component Query, which is imported from the react-apollo package. It accepts the previously defined query variable as an argument and takes care of executing the query. In order to react to the result, a function is defined as a child element, which is automatically called by Apollo as soon as a new state has set in with regard to the query. import gql from "graphql-tag" const articleQuery = gql` query articlesQuery { articles { id title text authors { id name } } } ` To do so, the function receives the arguments error and data. loading is a Boolean flag, which expresses whether we are currently still in the process of loading or whether it has already been completed. If an error occurred during loading, the error argument is filled. If successful, the data argument contains the result data. Within the function, you can react to this information and define how the display should look. In the example in Listing 4, a corresponding text is generated in both error cases . In the case of success, the data of the result set is iterated and an ad is generated for each blog article. const ArticleOverview = () => ( <Query query={articleQuery}> {({loading, error, data}) => { if (loading) { return <div><p>Loading...</p></div> } if (error) { return <div><p>Error: {error}</p></div> } return <div> {data.articles.map(article => ( <div key={article.id}> <h2>{article.title}</h2> <div> {article.text} </div> </div> ))} </div> }} </Query> ) Here, the declarative character of React also becomes apparent: There is no imperative reaction to events, and the DOM tree of the component is selectively updated correspondingly, as would be the case with classic jQuery applications, for example. Instead, a description is written that maps the state of the component on to a matching DOM description at any given point in time. Mutations Now we can display server data in the client via GraphQL. Most web applications must also be able to change data and trigger actions in the server though. In GraphQL these two aspects are separated from each other. In the schema of the application, the types Query for all offered queries and Mutation for changes exist at the highest level (additionally, there is still a Subscription, which we do not want to take a closer look at at this point). In contrast to REST, GraphQL allows you to define change operations in independence from the data model of the query page. Mutations in GraphQL are more similar to remote procedure calls (i.e. function calls), instead of uniformly defined operations on the same resources as it is the case with REST. Depending on the use case, the offered functions can also be strongly oriented towards business, but of course, simple CRUD operations (Create, Read, Update, Delete) can also be defined. In the example, we assume that our server offers a mutation like in listing 5, which allows adding a comment as a guest, who is not logged in. type Mutation { addCommentAsGuest( articleId: ID! authorName: String! text: String! ): Article } This Mutation function accepts as a mandatory parameter (marked by exclamation marks) the ID of the article to which the comment belongs, the name of the author, and the comment-text. In GraphQL, mutations always have a return type, in our case Article. Usually, these should be the objects changed by the mutation, so that a client can immediately display the changed data without having to start another query. For adding comments, we again create our own component AddComment. This component also consists of two parts: the GraphQL-Query and the code for display. The query can be seen in listing 6. Once again, the query is stored in a variable via the gql-tag function: a kind of local function definition with the type mutation is created in the first line of the query. The name we used here, as well as the identifiers for the parameters, can be freely chosen theoretically, but we use the name given to us by the schema as guidance. In the second line, the actual mutation of the schema is called, and the parameters of the external function are passed on. What may look like an unnecessary duplication at first, often turns out to be useful, because the flexibility is increased. The Mutation function is followed by an ordinary GraphQL query, which returns some of the changed data of the article. Here the IDs are especially important, because Apollo uses them to synchronize its local cache with the new data from the server. This local cache also allows all other locations, in which components display affected data, to be updated automatically, after the mutation has been executed – without requiring an additional request to the server. const addCommentMutation = gql` mutation addComment($text: String!, $authorName: String!, $articleId: ID!) { addCommentAsGuest(text: $text, authorName: $authorName, articleId: $articleId) { id comments { id text guestAuthor } } } ` In addition to the GraphQL mutation, we now also create the React component, which contains a form for entering the comment and actually executes the mutation after clicking a button. The source code can be seen in Listing 7. At this point, it makes sense to separate the two aspects mentioned above, i.e. the display of a form, and the placement of the mutation query. For this purpose, we first define a React component AddCommentForm, which itself has no dependencies to GraphQL or Apollo, but only displays the form and manages the local state of the form. As is usual for React forms, the local state of the form fields is updated using the setState method. When sending the form, we first prevent the standard behavior for HTML forms, namely the sending of a request, and the subsequent reloading of the page. Instead, we want to use JavaScript code to react directly. We assume here that an addComment function was passed to the component from outside, to which we only have to pass the necessary values for the execution of the mutation. We take the text and the author’s name of the commentator from the local state of the form. We also expect the comment’s article ID to be an external value. We keep the AddCommentForm component as an implementation detail within our JavaScript file. In order to actually execute the mutation, we create another React component, AddComment, which we also make visible to the outside by export default. Similar to the ArticleOverview component above, we also use a mutation component provided by the Apollo framework, which takes care of the actual work. We only have to pass our mutation query variable and define how we want the display to look. For this purpose, a function is defined again as a child element, which contains the GraphQL mutation as a JavaScript-function-argument. The name we used here corresponds to the one that we used as the local function name in our mutation query. We pass this function directly to our AddCommentForm component. As with the ArticleOverview component, it would also be possible to add further function parameters here. You could, for instance, react to the current loading state of the query or you could manually restart the mutation. But in this simple example, we want to do without it. class AddCommentForm extends React.Component { constructor() { super() this.state = {name: "", text: ""} } render() { return <div> <form onSubmit={e => { e.preventDefault() this.props.addComment({ variables: { text: this.state.text, authorName: this.state.name, articleId: this.props.articleId } }) }}> <div> <label>Author:</label> <input type="text" value={this.state.name} onChange={e => this.setState( {name: e.target.value} )}/> </div> <div> <textarea value={this.state.text} onChange={e => this.setState( {text: e.target.value} )}/> </div> <button type="submit">Add Comment</button> </form> </div> } } const AddComment = ({articleId}) => ( <Mutation mutation={addCommentMutation}> {(addComment) => <AddCommentForm articleId={articleId} addComment={addComment}/> } </Mutation> ) export default AddComment Now we’ve seen both of the Apollo Client framework’s essential parts in action. The novelty of the Apollo framework is that on the one hand there is a UI framework agnostic part (which includes, for example, the store and the caching), and on the other hand there are UI framework specific libraries (for the pleasant use of the general functionality in a familiar way). The variant, which is shown here (in which UI components can accept functions as child elements and, depending on the context, can call them up for display), corresponds to a pattern that is popular with the React community and it is called Render Props. In a framework designed with an object orientation mind, such as Angular, a functional variant such as this would probably be rather unusual or maybe even impossible from a technical perspective. Angular However, the Apollo Client can also be used with Angular, due to the UI-Framework specific integration libraries. Therefore, in the last part of this article, we will briefly build an Angular component for a comparison that provides the same article overview. We can reuse the query string from Listing 3 as it is. As it is usual for Angular, we create fields in the component class for the data to be displayed. In our case this is Boolean type, as well as article as arrays. In this simple example we do without explicit typing and, therefore, we use any for the article array as the type. In real projects one would certainly create dedicated TypeScript types. To get access to Apollo Client, we injected an instance of Apollo into the constructor. In order to work, Angular’s module system has to be configured accordingly beforehand of course. To connect the component to the Apollo Client, we use the OnInit Lifecycle Hook of Angular. In the corresponding ngOnInit method we call the method watchQuery from Apollo and pass the GraphQL query from Listing 3. As usual with Angular, RxJavaScript streams are used here as well. Accordingly, the watchQuery method returns such a stream, on which we can ultimately subscribe in order to be notified when data for this query has changed. In the subscriber, we react to the new data and store it in the corresponding fields of our class. To resolve the subscription after removing the component from Angular, we should also implement an OnDestroy Lifecycle Hook. To do this, we also create a field in the class for the subscription itself. The set-up of the GraphQL query is now complete. Now all that is missing is a template, which displays the corresponding data. The whole component can be seen in Listing 8. @Component({ selector: 'app-articles-overview-page', template: ` <div * <p>loading</p> </div> <div * <div * <h2>{{article.title}}</h2> <div>{{article.text}}</div> </div> </div> `, }) export class ArticlesOverviewPageComponent implements OnInit, OnDestroy { loading: boolean; articles: Array<any>; private querySubstription; constructor(private apollo: Apollo) { } ngOnInit() { this.querySubstription = this.apollo.watchQuery<any>({ query: articleQuery }) .valueChanges .subscribe(({data, loading}) => { this.loading = loading; this.articles = data.articles }) } ngOnDestroy() { this.querySubstription.unsubscribe() } } Conclusion We have seen that developing frontend applications with GraphQL and Apollo Client is not difficult. The aspect that can be abstracted from the technical details of the loading process in the UI components is especially interesting. Instead, the Apollo framework decouples and optimizes via the local cache. At the same time, Apollo also offers extensive options for fine-tuning the caching and loading mechanisms if required. The Apollo Client Developer Extension, offered for the Chrome DevTools, is also helpful here. This allows a deeper insight into the state of the local cache in order to get to the bottom of possible problems. Another interesting aspect of Apollo Client is that it is available for different UI frameworks. This is especially interesting in contexts, in which different technologies are to be used together. But the Apollo Client is not the only framework that allows working with GraphQL. The biggest competitor is probably Relay, developed by Facebook. As a framework, it is limited to React or React Native.
https://jaxenter.com/develop-graphql-frontends-with-angular-and-react-161373.html
CC-MAIN-2020-29
refinedweb
3,103
54.52
#include <list> #include <vector> #include <cstring> #include "TypeDef.h" #include "libmd5/MD5.h" Go to the source code of this file. Definition at line 479 of file SEI.h. delete list of SEI messages (freeing the referenced objects) Definition at line 79 of file SEI.cpp. remove a selection of SEI messages by payload type from the original list and return them in a new list. Definition at line 58 of file SEI.cpp. output a selection of SEI messages by payload type. Ownership stays in original message list. Definition at line 44 of file SEI.cpp. Definition at line 97 of file SEI.h.
http://hevc.info/HM-doc/_s_e_i_8h.html
CC-MAIN-2017-39
refinedweb
105
71
Not logged in Log in now Weekly Edition Recent Features Deadline scheduling: coming soon? LWN.net Weekly Edition for November 27, 2013 ACPI for ARM? LWN.net Weekly Edition for November 21, 2013 GNU virtual private Ethernet Re-sending the series of patches for the automatic kernel tunables feature: have done some fixes after the remarks sent back by Andrew and Randy. 1) All the type independent macros have been removed, except for the automatic tuning routine: it manages pointers to the tunable and to the value to be checked against that tunable, so it should rmain type independent IMHO. Now, I only left the auto-tuning routines for types int and size_t since these are the types of the tunables the framework is applied to. It will be easy to add the other types as needed in the future. This makes the code much lighter. 2) CONFIG_AKT has been moved from the FS menu to the "general setup" one. + all the other minor changes. --- Reminder that subsystem. - each tunable kobject has 3 associated attributes, all with a RW mode (i.e. the show() and store() methods are provided for them): . autotune: enables to (de)activate automatic tuning for the tunable . max: enables to set a new maximum value for the tunable . min: enables to set a new minimum value for the tunable patches should be applied to 2.6.20-rc4, in the following order: [PATCH 1/6]: tunables_registration.patch [PATCH 2/6]: auto_tuning_activation.patch [PATCH 3/6]: auto_tuning_kobjects.patch [PATCH 4/6]: tunable_min_max_kobjects.patch [PATCH 5/6]: per_namespace_tunables.patch [PATCH 6/6]: auto_tune_applied.patch -- Linux is a registered trademark of Linus Torvalds
http://lwn.net/Articles/219787/
CC-MAIN-2013-48
refinedweb
274
59.8
This tutorial will show you how to localize applications using the Aurelia framework, i.e. how to install and configure the aurelia-i18n plugin, where to store translations and how to load them asynchronously. We’ll also discuss how to format your data, add support for HTML translations, switch between locales and observe events. Shall we start? Creating the App If you would like to follow along, aurelia-cli will be required, so don’t forget to install it: Next, create a new application with any name: I have used a custom setup with the following settings: - RequireJS loader (note that Webpack plays very bad with the I18n plugin at the moment and you might have tough times getting it to work) - Web platform - Babel transpiler - No markup processing - Standard CSS with no pre-processing - No test runners (we are not going to tackle testing in this tutorial, but it is a good idea to do so in the real world) - Atom code editor Of course, the general approach to localizing Aurelia apps should work with other setups as well, but the code may slightly differ from case to case. After your dependencies are installed (which may take quite a lot of time), create a new User class. We are going to pretend that our app (for now) works only with an array of some users: Next, tweak the src/app.js file to require the newly created class and prepare an array of users: Now we may render them inside the src/app.html: So far so good: we have some minimalistic app and it is time to proceed to the next section and integrate aurelia-i18n package. Adding AureliaI18n Install all the necessary packages by running: Let me briefly cover what’ve installed: - aurelia-i18n is the main star today. It is a plugin that adds internationalization support and does all the heavy lifting for us. - i18next is a core plugin that aurelia-i18n relies on. To put it shortly, I18next is an open source internationalization framework used by numerous JavaScript apps out there. If you would like to learn more about vanilla I18next, you may skim through this article. - i18next-xhr-backend is an optional but very useful plugin that allows loading translation files in an asynchronous manner from the server. If you have the same setup as I’ve described in the previous section, tweak the aurelia_project/aurelia.json file by including all the installed plugins into the dependencies section, so that it looks like this: Note that aurelia-i18n supports other setups as well, including JSPM and Webpack (though, as mentioned above, it is pretty buggy). Configuration Tweak the src/main.js file to incorporate the newly installed plugin: I’ve pinpointed the lines that should be added to the file. Let’s move step-by-step here: - Import the necessary modules. TCustomAttributeis not really required, but I’ve added it for demonstration purposes. - Import the module to load translations asynchronously. - Hook up the plugin. Be warned that with some setups (for instance, when using Webpack) the plugin’s name should be written as PLATFORM.moduleName('aurelia-i18n'), not just aurelia-i18nas suggested in the docs. - This is an array of aliases that we would like to utilize in order to perform translations. tis the default one, whereas i18nis a custom one. - We specify which backend to use ( i18next-xhr-backendin this case). - Our application is going to have support for two languages: English and Russian. On this line, we specify that if translations for the English locale cannot be found, use Russian as a fallback language. Basically, all the settings here are described in the I18next docs. - Here we provide an array of locales to preload translations for. It is very convenient because the corresponding files are loaded in an asynchronous manner and later we don’t need to spend any time loading them once a user changes the site’s language. - That’s a namespace. In general, I18next may support multiple namespaces, but for this demo, a single one will do. We’ll see how this namespace is utilized in a moment. - Here we provide the aliases defined at step #4. - The default language. - Provide debugging information in the browser’s console. Disable this for production apps. - The path where to load translation files from. {{lng}}, of course, means “language” ( ruor en), whereas {{ns}}is a namespace. The files must be in JSON format. Next, what you need to do is create a locales folder in the root of the project (because we’ve specified the ./locales/{{lng}}/{{ns}}.json path in our settings above). Inside that folder create two nested directories named after the locales of your choice (en and ru in this demo). Inside these folders, in turn, create thethe global.json file that is going to host all the translations for the given language. “global” is the name of our namespace defined above. For larger apps, it is quite common to have multiple namespaces and, in turn, multiple files with translations for different sections of the site. Here is the content of the en/global.json file: And ru/translation.jsonfile: Note here that translation keys can be nested. Great! The next step is to actually utilize these translations, so proceed to the next section. Performing Translations in a Simple Way The simplest way to perform translations is by using an HTML attribute called t (or i18n which is an alias according to our settings). Tweak the src/app.html file like this: Now run the application using the following command: Note that the --watch flag must be provided in Windows environment to avoid a pretty nasty bug, preventing the application from opening at all. Next, navigate to and open the browser console. Among other debug messages you should see: It means that I18next has successfully initialized and loaded all translation files for us. You will also see that both the “Users” and “Name” text is shown on the page which shows that the translations were performed properly. Controlling Translations Behaviour By default, translations do not support HTML markup, so if you say something like: Then the em tag won’t be processed and instead will be printed out in a raw format. To overcome this problem, prepend the translation key with [html] prefix: Moreover, you may even control how the translation should be added to the given tag. By default, it replaces any text inside, but there are two other prefixes available: [prepend] [append] Note that these two prefixes implicitly allow HTML content as well. Formatting the Output It is possible to easily format numbers and dates with aurelia-i18n. For starters, let’s provide additional information about our users: salary and their birthdate: Set it in the following way: And now I would like to format these new values properly. Start with the salary that has to be displayed in a currency format: nf is a special value converted and here we are saying to format the given number as a currency, prefixed with a euro symbol. Formatting dates can be done in a similar manner: You may find more examples of using the plugin in the official docs. Now let’s proceed to the next feature and add the ability to switch between locales. Switching Locales In order to introduce this new feature, I propose creating a separate Locales class. We will need to inject I18N into it: Also, let’s provide an array of supported locales and store the currently set language: Now display locales on the page and bind a click event handler to them: Note that we are also providing a basic styling for a currently selected language using the css attribute. The next step is to process the click event inside the setLocale method: The idea is simple: we grab the locale’s code and check that it is not the same as the currently set one. If not — use the setLocale method of the i18n object to update locale. Note, by the way, that the i18n object can be used to perform translations programmatically. For example: The last step is to require these newly created files. First, the template inside the src/app.html file: Then the module inside the src/app.js: That’s it! Now try switching between locales — the text on the page should be translated accordingly. Observing Locale Changes Sometimes it is desirable to listen for a “locale changed” event and perform specific actions. Let me demonstrate how to do that: Here are the key points: - We load the BaseI18Nmodule - Also load the EventAggregator - Perform injection of all the necessary modules - Subscribe to a “locale change” event and update all translations inside the current element and all nested elements. - Also update translations as soon as the current class is attached to an element As you see, nothing complex here! Bundling Translation Files What’s interesting, your translation files can be easily packed into the Aurelia bundle. All you need to do is add the .json extension to the extensions section inside the aurelia_project/aurelia.json file: have seen how to introduce internationalization into Aurelia applications. We have seen what plugins are required to do that, how to install and setup them. Also, you’ve learned how and where to store the actual translations, how to utilize them and use various formatters. On top of that, we have added the ability to switch between locales and observe the “locale changed” event. Note that aurelia-i18n plugin has other features. Some of them can be found in the docs, whereas others are documented at the i18next.com website because, after all, Aurelia I18n is powered by this plugin. Hopefully, you found this article useful! As always, I thank you for staying with me and until the next time.
https://phrase.com/blog/posts/localizing-aureliajs-applications/
CC-MAIN-2019-51
refinedweb
1,638
62.78
0 Hi guys im trying to make a program that will work as " Slot Machine " and im stuck in one part that i can not resolve. Im trying to verify predetermined char in random array so i can know if some of char appear three times or more. I want to do that so i can deteremined how much player is going to win. It depends on how many lines of the same char do player get. Im new to programming so i would appreciate any help that i can get. Here my code that i need help with. #include <iostream> #include <ctime> #include <cstdlib> #include <cmath> #include <string> #include <algorithm> using namespace std; int main () { cout << endl ; cout << " Welcome to money making '' SLOT MACHINE '' game " << endl; cout << endl; int age; cout << " Please verify your age: "; cin >> age; cout << endl; if (age>17) { cout << "You are eligible to play" << endl; } else { cout << "You are not eligible to play" << endl; system("PAUSE"); return 0; } cout << endl ; int account; cout << "How much money would you like to withdraw from your account: " << endl; cout << endl; cin >> account; cout << endl; cout << account << " has been withdrawed from your account" << endl; cout << endl; bool running=true; while (running == true) { int bet=50||100||200; cout << "Now you are welcome to set your bet" << endl; cout << endl; cout << "You can bet a 50,100 or 200 " << endl; cout << endl; cout << "Choose how much you would like to bet: 50, 100 or 200" << endl; cout << endl; cin >> bet; cout << endl; if (bet == 50) { cout << "You have bet 50" << endl; } else if(bet == 100) { cout << "You have bet 100" << endl; } else if(bet == 200) { cout << "You have bet 200" << endl; } cout << endl; account-=bet; cout << "You have " << account << " left to play for" << endl; srand ( time(0)); char sign[3]; sign [0] = '$'; sign [1] = 'X'; sign [2] = 'O'; for (char i = 0; i < 3; ++i) { char r = rand() % 3; char s = rand() % 3; char d = rand() % 3; cout << "___ ___ ___\n"; cout << " "<<sign[r]<< " | " << sign[s] << " | " << sign[d] << " | " << "\n"; cout << "___|___|___|\n"; } system("PAUSE"); } }
https://www.daniweb.com/programming/software-development/threads/388784/slot-machine
CC-MAIN-2016-50
refinedweb
347
57.91
Thanks for your answer 2008/8/18 Graham Dumpleton <graham.dumpleton at gmail.com> > > 2008/8/18 Poletto Guillaume <polettog at gmail.com>: > > > > Yes, I'm new to both Python programming language and mod_python > > If you are new to Python and want to write web applications, any > reason why you didn't start out with one of the arguably more friendly > higher level frameworks such as Django? I don't know.. no doubt that Django is great, but i was seduced by writing my own handler and controlling requests by parsing URIs by hand. Note that if i'm new to Python, i'm experimented in web developement, and also in writing CGIs (although this is not CGI here, i know). I already know some low level things concerning HTTP headers (i wrote some tools in C to parse urlencoded query strings, POST data and netscape cookies). So except the import_module() part, i did assimilate most of the manual. If there was no "util" module to fetch form parameters, i would have taken a look to a higher level framework, but the base mod_python seems to provide all i need :) Also, i was interesting in writing Apache modules in C, so i thought using mod_python at low level was good to learn about how work handlers and apache internals > > I made a test and i modified a module imported by "import" statement in my handler module : the changes where taken in count without restarting apache > > Two things could be happening here. The first is that the module being > imported was in the same directory and was being managed by mod_python > module importer and on detecting a change, it reloaded code > appropriately. > > Alternatively, you have been deceived by the fact that > Apache/mod_python on UNIX is a multiprocess web server and so a > completely different processes which hadn't loaded it previously > handled the request and so code got loaded for first time, and wasn't > because of a reload at all. In this later case, it may not have even > been a candidate for reloading and might just be a standard Python > module/package. That was it ! Yesterday, i made, the test 3 or 4 times, but there were 6 apache processes, so at each request, the handler module was not yet imported. This is why i thought modules where "reloaded". > > If you have: > > PythonDebug On > > set in configuration and monitor the Apache error log files you should > be able to see when a code files is being handled by mod_python module > importer and when it is being first loaded and/or reloaded. If it > isn't in there, it is a standard module/package and reloading not > possible. This is a great trick to look at the apache error log, i'll remember that > If you are new to Python and have dropped down to the level of > mod_python module importer already, I would suggest you run away. > Instead have a look at one of the high level web frameworks for Python > as you will be able to get onto developing your application much > quicker and will not have to be worried about such low level details. > :-) Thanks for the advice but i think i'll look to a higher level framework in a future project. I've all the time ! Now i better understand what happens with "import" statements, i think i will use them instead of import_module() and gracefully restart apache at each update. Now there's another problem : what's the right way to add another import path ? Because i wanted to have the main source code outside the directory in which is the handler module. During my test, i did the tweak of adding dynamically my path to sys.path list, but i find this a bit dirty. So i found there was this apache directive "PythonPath" but according to the manual, this is not recommanded to use it. So what should i do? Thanks
http://modpython.org/pipermail/mod_python/2008-August/025548.html
CC-MAIN-2018-39
refinedweb
660
66.17
4 The Vertex Function Written by Marius Horga & Caroline Begbie So far, you’ve worked your way through 3D models and the graphics pipeline. Now, it’s time to look at the first of two programmable stages in Metal, the vertex stage — and more specifically, the vertex function. Shader Functions There are three types of shader functions: - Vertex function: Calculates the position of a vertex. - Fragment function: Calculates the color of a fragment. - Kernel function: Used for general-purpose parallel computations, such as image processing. In this chapter, you’ll focus only on the vertex function. In Chapter 7, “The Fragment Function”, you’ll explore how to control the color of each fragment. And in Chapter 16, “GPU Compute Programming”, you’ll discover how to use parallel programming with multiple threads to write to buffers and textures. By now, you should be familiar with vertex descriptors, and how to use them to describe how to lay out the vertex attributes from your loaded 3D model. To recap: MDLVertexDescriptor: You use a Model I/O vertex descriptor to read in the .obj file. Model I/O creates buffers with the desired layout of attributes, such as position, normals and texture coordinates. MTLVertexDescriptor: You use a Metal vertex descriptor when creating the pipeline state. The GPU vertex function uses the [[stage_in]]attribute to match the incoming data with the vertex descriptor in the pipeline state. As you work through this chapter, you’ll construct your own vertex mesh and send vertices to the GPU without using a vertex descriptor. You’ll learn how to manipulate these vertices in the vertex function, and then you’ll upgrade to using a vertex descriptor. In the process, you’ll see how using Model I/O to import your meshes does a lot of the heavy lifting for you. The Starter Project ➤ Open the starter project. This SwiftUI project contains a reduced Renderer so that you can add your own mesh, and the shader functions are bare-bones so that you can build them up. You’re not doing any drawing yet, so there’s nothing to see when you run the app. Rendering a Quad You create a quad using two triangles — and each triangle has three vertices, for a total of six vertices. ➤ Create a new Swift file named Quad.swift. ➤ Replace the existing code with: import MetalKit struct Quad { var vertices: [Float] = [ -1, 1, 0, // triangle 1 1, -1, 0, -1, -1, 0, -1, 1, 0, // triangle 2 1, 1, 0, 1, -1, 0 ] } As you know, a vertex is made of an x, y and z value. Each group of three Floats in vertices describes one vertex. Here, the winding order of the points is clockwise, which is important. ➤ Add a new vertex buffer property to Quad and initialize it: let vertexBuffer: MTLBuffer init(device: MTLDevice, scale: Float = 1) { vertices = vertices.map { $0 * scale } guard let vertexBuffer = device.makeBuffer( bytes: &vertices, length: MemoryLayout<Float>.stride * vertices.count, options: []) else { fatalError("Unable to create quad vertex buffer") } self.vertexBuffer = vertexBuffer } With this code, you initialize the Metal buffer with the array of vertices. You multiply each vertex by scale, which lets you set the size of the quad during initialization. ➤ Open Renderer.swift, and add a new property for the quad mesh: lazy var quad: Quad = { Quad(device: Renderer.device, scale: 0.8) }() Here, you initialize quad with Renderer’s device — and because you initialize device in init(metalView:), you must initialize quad lazily. You also resize the quad so that you can see it properly. (If you were to leave the scale at the default of 1.0, the quad would cover the entire screen. Covering the screen is useful for full-screen drawing since you can only draw fragments where you’re rendering geometry.) ➤ In draw(in:), after // do drawing here, add: renderEncoder.setVertexBuffer( quad.vertexBuffer, offset: 0, index: 0) You create a command on the render command encoder to set the vertex buffer in the buffer argument table at index 0. ➤ Add the draw call: renderEncoder.drawPrimitives( type: .triangle, vertexStart: 0, vertexCount: quad.vertices.count) Here, you draw the quad’s six vertices. ➤ Open Shaders.metal. ➤ Replace the vertex function with: vertex float4 vertex_main( constant float3 *vertices [[buffer(0)]], uint vertexID [[vertex_id]]) { float4 position = float4(vertices[vertexID], 1); return position; } There’s an error with this code, which you’ll observe and fix shortly. The GPU performs the vertex function for each vertex. In the draw call, you specified that there are six vertices. So, the vertex function will perform six times. When you pass a pointer into the vertex function, you must specify an address space, either constant or device. constant is optimized for accessing the same variable over several vertex functions in parallel. device is best for accessing different parts of a buffer over the parallel functions — such as when using a buffer with points and color data interleaved. [[vertex_id]] is an attribute qualifier that gives you the current vertex. You can use this as an entry into the array held in vertices. You might notice that you’re sending the GPU a buffer that you filled with an array of Floats. In the vertex function, you read the same buffer as an array of float3s, leading to an error in the display. ➤ Build and run. Although you might get a different render, the vertices are in the wrong position because a float3 type takes up more memory than three Float types. The SIMD float3 type is padded and takes up the same memory as the float4 type, which is 16 bytes. Changing this parameter to a packed_float3 will fix the error since a packed_float3 takes up 12 bytes. Note: You can check the sizes of types in the Metal Shading Language Specification at In the vertex function, change float3 in the first parameter to packed_float3. ➤ Build and run. The quad now displays correctly. Alternatively, you could have defined the Float array vertices as an array of simd_float3. In that case, you’d use float3 in the vertex function, as both types take 16 bytes. However, sending 16 bytes per vertex is slightly less efficient than sending 12 bytes per vertex. Calculating Positions Metal is all about gorgeous graphics and fast, smooth animation. As a next step, you’ll make your quad move up and down the screen. To do this, you’ll have a timer that updates every frame, and the position of each vertex will depend on this timer. The vertex function is where you update vertex positions, so you’ll send the timer data to the GPU. ➤ Open Renderer.swift, and add a new property to Renderer: var timer: Float = 0 ➤ In draw(in:), right before: renderEncoder.setRenderPipelineState(pipelineState) ➤ Add the following code: // 1 timer += 0.005 var currentTime = sin(timer) // 2 renderEncoder.setVertexBytes( ¤tTime, length: MemoryLayout<Float>.stride, index: 11) Let’s have a closer look: - For every frame, you update the timer. You want your cube to move up and down the screen, so you’ll use a value between -1 and 1. Using sin()is a great way to achieve this balance as sine values are always -1 to 1. You can change the speed of your animation by changing the value that you add to this timer for each frame. - If you’re only sending a small amount of data — say less than 4KB — to the GPU, setVertexBytes(_:length:index:)is an alternative to setting up an MTLBuffer. Here, you set currentTimeto index 11 in the buffer argument table. Keeping buffers 1 through 10 for vertex attributes — such as vertex positions — helps you to remember which buffers hold what data. ➤ Open Shaders.metal, and replace the vertex function: vertex float4 vertex_main( constant packed_float3 *vertices [[buffer(0)]], constant float &timer [[buffer(11)]], uint vertexID [[vertex_id]]) { float4 position = float4(vertices[vertexID], 1); position.y += timer; return position; } You receive the single value timer as a float in buffer 11. You add the timer value to the y position and return the new position from the function. In the next chapter, you’ll start learning how to project vertices into 3D space using matrix multiplication. But, you don’t always need matrix multiplication to move vertices; here, you can achieve the translation of the position in y using simple addition. ➤ Build and run the app, and you’ll see a lovely animated quad. More Efficient Rendering Currently, you’re using six vertices to render two triangles. Of those vertices, 0 and 3 are in the same position, as are 1 and 5. If you render a mesh with thousands — or even millions of vertices, it’s important to reduce duplication as much as possible. You can do this with indexed rendering. Create a structure of only unique positions, and then use indices to get the right position for a vertex. ➤ Open Quad.swift, and rename vertices to oldVertices. ➤ Add the following structures to Quad: var vertices: [Float] = [ -1, 1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ] var indices: [UInt16] = [ 0, 3, 2, 0, 1, 3 ] vertices now holds the unique four points of the quad in any order. indices holds the index of each vertex in the correct vertex order. Refer to oldVertices to make sure your indices are correct. ➤ Add a new Metal buffer to hold indices: let indexBuffer: MTLBuffer ➤ At the end of init(device:scale:), add: guard let indexBuffer = device.makeBuffer( bytes: &indices, length: MemoryLayout<UInt16>.stride * indices.count, options: []) else { fatalError("Unable to create quad index buffer") } self.indexBuffer = indexBuffer You create the index buffer the same way you did the vertex buffer. ➤ Open Renderer.swift, and in draw(in:) before the draw call, add: renderEncoder.setVertexBuffer( quad.indexBuffer, offset: 0, index: 1) Here, you send the index buffer to the GPU. ➤ Change the draw call to: renderEncoder.drawPrimitives( type: .triangle, vertexStart: 0, vertexCount: quad.indices.count) Use the index count for the number of vertices to render; not the vertex count. ➤ Open Shaders.metal, and change the vertex function to: vertex float4 vertex_main( constant packed_float3 *vertices [[buffer(0)]], constant ushort *indices [[buffer(1)]], constant float &timer [[buffer(11)]], uint vertexID [[vertex_id]]) { ushort index = indices[vertexID]; float4 position = float4(vertices[index], 1); return position; } Here, vertexID is the index into the buffer holding the quad indices. You use the value in the indices buffer to index the correct vertex in the vertex buffer. ➤ Build and run. Sure, your quad is positioned the same way as before, but now you’re sending less data to the GPU. From the number of entries in arrays, it might appear as if you’re actually sending more data — but you’re not! The memory footprint of oldVertices is 72 bytes, whereas the footprint of vertices + indices is 60 bytes. Vertex Descriptors A more efficient draw call is available when you use indices for rendering vertices. However, you first need to set up a vertex descriptor in the pipeline. It’s always a good idea to use vertex descriptors, as most often, you won’t only send positions to the GPU. You’ll also send attributes such as normals, texture coordinates and colors. When you can lay out your own vertex data, you have more control over how your engine handles model meshes. ➤ Create a new Swift file named VertexDescriptor.swift. ➤ Replace the code with: import MetalKit extension MTLVertexDescriptor { static var defaultLayout: MTLVertexDescriptor { let vertexDescriptor = MTLVertexDescriptor() vertexDescriptor.attributes[0].format = .float3 vertexDescriptor.attributes[0].offset = 0 vertexDescriptor.attributes[0].bufferIndex = 0 let stride = MemoryLayout<Float>.stride * 3 vertexDescriptor.layouts[0].stride = stride return vertexDescriptor } } Here, you set up a vertex layout that has only one attribute. This attribute describes the position of each vertex. A vertex descriptor holds arrays of attributes and buffer layouts. - attributes: For each attribute, you specify the type format and offset in bytes of the first item from the beginning of the buffer. You also specify the index of the buffer that holds the attribute. - buffer layout: You specify the length of the stride of all attributes combined in each buffer. It may be confusing here as you’re using index 0 to index into both layoutsand attributes, but the layoutsindex 0 corresponds to the bufferIndex0 used by attributes. Note: stridedescribes how many bytes are between each instance. Due to internal padding and byte alignment, this value can be different from size. For an excellent explanation of size, stride and alignment, check out Greg Heo’s article at To the GPU, the vertexBuffer now looks like this: ➤ Open Renderer.swift, and locate where you create the pipeline state in init(metalView:). ➤ Before creating the pipeline state in do {}, add the following code to the pipeline state descriptor: pipelineDescriptor.vertexDescriptor = MTLVertexDescriptor.defaultLayout The GPU will now expect vertices in the format described by this vertex descriptor. ➤ In draw(in:), remove: renderEncoder.setVertexBuffer( quad.indexBuffer, offset: 0, index: 1) You’ll include the index buffer in the draw call. ➤ Change the draw call to: renderEncoder.drawIndexedPrimitives( type: .triangle, indexCount: quad.indices.count, indexType: .uint16, indexBuffer: quad.indexBuffer, indexBufferOffset: 0) This draw call expects the index buffer to use UInt16, which is how you described your indices array in Quad. You don’t explicitly send quad.indexBuffer to the GPU because this draw call will do it for you. ➤ Open Shaders.metal. ➤ Replace the vertex function with: vertex float4 vertex_main( float4 position [[attribute(0)]] [[stage_in]], constant float &timer [[buffer(11)]]) { return position; } You did all the heavy lifting for the layout on the Swift side, so that takes the size of the vertex function way down. :] You describe each per-vertex input with the [[stage_in]] attribute. The GPU now looks at the pipeline state’s vertex descriptor. [[attribute(0)]] is the attribute in the vertex descriptor that describes the position. Even though you defined your original vertex data as three Floats, you can define the position as float4 here. The GPU can make the conversion. It’s worth noting that when the GPU adds the w information to the xyz position, it adds 1.0. As you’ll see in the following chapters, this w value is quite important during rasterization. The GPU now has all of the information it needs to calculate the position for each vertex. ➤ Build and run the app to ensure that everything still works. The resulting render will be the same as before. Adding Another Vertex Attribute You probably won’t ever have just one attribute, so let’s add a color attribute for each vertex. You have a choice whether to use two buffers or interleave the color between each vertex position. If you choose to interleave, you’ll set up a structure to hold position and color. In this example, however, it’s easier to add a new colors buffer to match each vertex. ➤ Open Quad.swift, and add the new array: var colors: [simd_float3] = [ [1, 0, 0], // red [0, 1, 0], // green [0, 0, 1], // blue [1, 1, 0] // yellow ] You now have four RGB colors to match the four vertices. ➤ Create a new buffer property: let colorBuffer: MTLBuffer ➤ At the end of init(device:scale:), add: guard let colorBuffer = device.makeBuffer( bytes: &colors, length: MemoryLayout<simd_float3>.stride * indices.count, options: []) else { fatalError("Unable to create quad color buffer") } self.colorBuffer = colorBuffer You initialize colorBuffer the same way as the previous two buffers. ➤ Open Renderer.swift, and in draw(in:) right before the draw call, add: renderEncoder.setVertexBuffer( quad.colorBuffer, offset: 0, index: 1) You send the color buffer to the GPU using buffer index 1, which must match the index in the vertex descriptor layout. ➤ Open VertexDescriptor.swift, and add the following code to defaultLayout before return: vertexDescriptor.attributes[1].format = .float3 vertexDescriptor.attributes[1].offset = 0 vertexDescriptor.attributes[1].bufferIndex = 1 vertexDescriptor.layouts[1].stride = MemoryLayout<simd_float3>.stride Here, you describe the layout of the color buffer in buffer index 1. ➤ Open Shaders.metal. ➤ You can only use [[stage_in]] on one parameter, so create a new structure: struct VertexIn { float4 position [[attribute(0)]]; float4 color [[attribute(1)]]; }; ➤ Change the vertex function to: vertex float4 vertex_main( VertexIn in [[stage_in]], constant float &timer [[buffer(11)]]) { return in.position; } This code is still short and concise. The GPU knows how to retrieve position and color from the buffers because of the [[attribute(n)]] qualifier in the structure, which looks at the pipeline state’s vertex descriptor. ➤ Build and run to ensure your blue quad still renders. The fragment function determines the color of each rendered fragment. You need to pass the vertex’s color to the fragment function. You’ll learn more about the fragment function in Chapter 7, “The Fragment Function”. ➤ Still in Shaders.metal, add this structure: struct VertexOut { float4 position [[position]]; float4 color; }; Instead of returning just the position from the vertex function, you’ll now return both position and color. You specify a position attribute to let the GPU know which property in this structure is the position. ➤ Replace the vertex function with: vertex VertexOut vertex_main( VertexIn in [[stage_in]], constant float &timer [[buffer(11)]]) { VertexOut out { .position = in.position, .color = in.color }; return out; } You now return a VertexOut instead of a float4. ➤ Change the fragment function to: fragment float4 fragment_main(VertexOut in [[stage_in]]) { return in.color; } The [[stage_in]] attribute indicates that the GPU should take the VertexOut output from the vertex function and match it with the rasterized fragments. Here, you return the vertex color. Remember from Chapter 3, “The Rendering Pipeline”, that each fragment’s input gets interpolated. ➤ Build and run the app, and you’ll see the quad rendered with beautiful colors. Rendering Points Instead of rendering triangles, you can render points and lines. ➤ Open Renderer.swift, and in draw(in:), change: renderEncoder.drawIndexedPrimitives( type: .triangle, ➤ To: renderEncoder.drawIndexedPrimitives( type: .point, If you build and run now, the GPU will render the points, but it doesn’t know what point size to use, so it flickers over various point sizes. To fix this problem, you’ll also return a point size when returning data from the vertex function. ➤ Open Shaders.metal, and add this property to VertexOut: float pointSize [[point_size]]; The [[point_size]] attribute will tell the GPU what point size to use. ➤ Replace the initialization of out with: VertexOut out { .position = in.position, .color = in.color, .pointSize = 30 }; Here, you assign the point size of 30. ➤ Build and run to see your points rendered with their vertex color: Challenge So far, you’ve sent vertex positions to the GPU in an array buffer. But this isn’t entirely necessary. All the GPU needs to know is how many vertices to draw. Your challenge is to remove the vertex and index buffers, and draw 50 points in a circle. Here’s an overview of the steps you’ll need to take, along with some code to get you started: - In Renderer, remove the vertex descriptor from the pipeline. - Replace the draw call in Rendererso that it doesn’t use indices but does draw 50 vertices. - In draw(in:), remove all of the setVertexBuffercommands. - The GPU will need to know the total number of points, so send this value the same way you did timerin buffer 0. - Replace the vertex function with: vertex VertexOut vertex_main( constant uint &count [[buffer(0)]], constant float &timer [[buffer(11)]], uint vertexID [[vertex_id]]) { float radius = 0.8; float pi = 3.14159; float current = float(vertexID) / float(count); float2 position; position.x = radius * cos(2 * pi * current); position.y = radius * sin(2 * pi * current); VertexOut out { .position = float4(position, 0, 1), .color = float4(1, 0, 0, 1), .pointSize = 20 }; return out; } Remember, this is an exercise to help you understand how to position points on the GPU without holding any equivalent data on the Swift side. So, don’t worry too much about the math. You can use the sine and cosine of the current vertex ID to plot the point around a circle. Notice that there’s no built-in value for pi on the GPU. You’ll see your 50 points plotted into a circle. Try animating the points by adding timer to current. If you have any difficulties, you can find the solution in the project challenge directory for this chapter. Key Points - The vertex function’s fundamental task is positioning vertices. When you render a model, you send the GPU the model’s vertices in its original position. The vertex shader will then reposition those vertices to the correct spot in your 3D world. - Shader code uses attributes such as [[buffer(0)]]and [position]extensively. To find out more about these attributes, refer to the Metal Shading Language specification document. - You can pass any data in an MTLBufferto the GPU using setVertexBuffer(_:offset:index:). If the data is less than 4KB, you don’t have to set up a buffer; you can, instead, pass a structure using setVertexBytes(_:length:index:). - When possible, use indexed rendering. With indexed rendering, you pass less data to the GPU — and memory bandwidth is a major bottleneck. - When possible, use vertex descriptors. With vertex descriptors, the GPU knows the format of the data being passed, and you’ll get fewer errors in your code when you change a type on the Swift side and forget to change the shader function.
https://www.raywenderlich.com/books/metal-by-tutorials/v3.0/chapters/4-the-vertex-function
CC-MAIN-2022-21
refinedweb
3,547
64.91
How to Deploy OpenCV on Raspberry Pi and Enable Machine Vision How to Deploy OpenCV on Raspberry Pi and Enable Machine Vision Want to learn how to enable machine vision on your Raspberry Pi? Check out this tutorial on how to deploy the OpenCV on your Raspberry Pi. Join the DZone community and get the full member experience.Join For Free OpenCV is an integral part of machine vision. In this tutorial, you will learn to deploy the OpenCV library on a Raspberry Pi, using Raspbian Jessie for testing. You’ll install OpenCV from source code in the Raspberry Pi board. How to Build OpenCV From the Source on a Raspberry Pi To start building the OpenCV library from source code on Raspberry Pi, you’ll first need to install development libraries. How to Install Development Libraries Type these commands on the Raspberry Pi terminal: $ sudo apt-get update $ sudo apt-get install build-essential git cmake pkg-config libgtk2.0-dev $ sudo apt-get install python2.7-dev python3-dev You also need to install the required matrix, image, and video libraries: $atlas-base-dev gfortran The next step is to download the OpenCV source code via Git: $ mkdir opencv $ cd opencv $ git clone $ git clone Using a Python virtual environment, deploy the OpenCV on Raspberry Pi with virtualenv. The benefit of this approach is that it isolates the existing Python development environment. How to build a home surveillance system using Raspberry Pi and camera How to build an IoT system using Raspberry Pi Install and Configure Virtualenv for OpenCV If your Raspbian hasn’t installed it yet, you can install it using pip: $ sudo pip install virtualenv virtualenvwrapper $ sudo rm -rf ~/.cache/pip Then, you can configure a virtualenv in your bash profile: $ nano ~/.profile Now, add the following scripts: export WORKON_HOME=$HOME/.virtualenvs source /usr/local/bin/virtualenvwrapper.sh Next, save your bash profile file when finished. To create a Python virtual environment, type this command: $ mkvirtualenv cv This command will create a Python virtual environment called cv. If you’re using Python 3, you can create the virtual environment with the following command: $ mkvirtualenv cv -p python3 You should see (cv) on your terminal. If you close the terminal or call a new terminal, you’d have to activate your Python virtual environment again: $ source ~/.profile</strong> $ workon cv The following screenshot shows a sample Python virtual environment form called cv: Inside the Python virtual terminal, continue installing NumPy as the required library for OpenCV Python. You can install the library using pip: $ pip install numpy Now, you’re ready to build and install OpenCV from the source. After cloning the OpenCV library, you can build it by typing the following commands: $ cd ~/opencv/ $ mkdir build $ cd build $ cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D INSTALL_C_EXAMPLES=ON \ -D INSTALL_PYTHON_EXAMPLES=ON \ -D OPENCV_EXTRA_MODULES_PATH=~/opencv/opencv_contrib/modules \ -D BUILD_EXAMPLES=ON .. Next, install the OpenCV library on your internal system from Raspbian OS: $ make -j4 $ sudo make install $ sudo ldconfig When you are done, you will have to configure the library so that Python can access it through Python binding. The following is a list of command steps for configuring with Python 2.7: $ ls -l /usr/local/lib/python2.7/site-packages/ $ cd ~/.virtualenvs/cv/lib/python2.7/site-packages/ $ ln -s /usr/local/lib/python2.7/site-packages/cv2.so cv2.so If you’re using Python 3.x (say, Python 3.4), perform the following steps on the terminal: $ ls /usr/local/lib/python3.4/site-packages/ $ The installation process is over. Verifying the OpenCV Installation on Raspberry Pi Now, you need to verify whether OpenCV has been installed correctly by checking the OpenCV version: $ workon cv $ python >>> import cv2 >>> cv2.__version__ You should see the OpenCV version on the terminal. A sample program output is shown in the following screenshot: How to use OpenCV to Enable Computer Vision The next demo displays an image file using OpenCV. For this scenario, you can use the cv2.imshow() function to display a picture file. For testing, log into the Raspberry Pi desktop to execute the program. Type the following script on a text editor: import numpy as np import cv2 img = cv2.imread('circle.png') cv2.imshow('My photo', img) cv2.waitKey(0) cv2.destroyAllWindows() Here, circle.png has been used as a picture source; you can use whichever file you want. Save the script into a file called ch03_hello_opencv.py; now, open the terminal inside your Raspberry Pi desktop and type this command: $ python ch03_hello_opencv.py If successful, you should see a dialog that displays a picture: The picture dialog shows up because you called cv2.waitKey(0) in the code. Press any key to close the dialog. Lastly, close the dialog by calling the cv2.destroyAllWindows() function after receiving a click event. And, there you have }}
https://dzone.com/articles/how-to-deploy-opencv-on-raspberry-pi-enabling-mach?fromrel=true
CC-MAIN-2019-22
refinedweb
813
56.05
From: Paul A Bristow (boost_at_[hidden]) Date: 2004-02-20 13:04:59 | -----Original Message----- | From: boost-bounces_at_[hidden] | [mailto:boost-bounces_at_[hidden]] On Behalf Of Darren Cook | Sent: 19 February 2004 23:49 | To: Boost mailing list | Subject: Re: [boost] Re: algorithms namespace | | I'm okay with writing std::cout or std::for_each. It only | adds 5 chars which | isn't enough to disturb me. If the standard library had instead been | namespace "standard" I'd probably always write "using | namespace standard" at | the top of all my programs. What is your objection to writing #include <iostream> using std::cout; using std::for_each; // etc either locally to a block or procedure, or with wider scope? IMHO this also helpfully documents for the user where things are coming from, avoids the clutter from full file specifications, and avoids the pitfalls with name clashes and selection surprises that 'using namespace std & boost etc' creates. If things move from boost:: to std::, say, I'd prefer to see the changes documented as explicitly as possible.
https://lists.boost.org/Archives/boost/2004/02/61473.php
CC-MAIN-2019-43
refinedweb
173
53.85
Okay, I seem unable to figure this out nor find an answer so I kindly ask for help. So I got an object with a simple "OnMouseUp" script that does nothing else than print a "clicked" message. I have a prefab, drag the object into the scene, press play, and it works just fine. it's clickable and it prints "clicked" just like it should. However, if I use the "instantiate" command within a a startup script to automatically load the object it does NOT work. The object loads fine and shows up on the screen and everything, but it is no longer clickable for some reason. It just seems to completely ignore it has a "OnMouseUp" command attached to it. Adding other things in the object script works fine too, but anything mouse-related, like OnMouseUp, OnMouseOver, etc does not work. Anyone have any idea why? The only thing I can think of is the script either not being enabled or not included in the prefab. I agree with @rabbitfang it seems as if the script isn't included in the prefab. However you say "adding other things in the script work fine too". You mean these extra things work on the instaniated prefab? Try a Debug.Log in the Awake() function which should fire for each instance of the prefab. Other things that spring to mind are, are you clicking the right object? Sounds silly but perhaps your instance is off camera and you're clicking something else. Just a thought What is the actual code that you are using for the OnMouseUp? Are you using tags to find the object? Or by the actual object's name?????? Answer by roamcel · Jan 02, 2012 at 01:24 PM There should be two reasons for this to happen: 1 - prefab not updated you have the object in your scene, which is different from the prefab you use in the instantiate instruction. be sure to create a new prefab using the working object in your scene, and using that new prefab in your script 2 - incorrect layering/ parenting or instantiation the instantiated object is declared as a TRANSFORM and you instantiate it as a GAMEOBJECT. Be sure to declare it as a GAMEOBJECT in your script. Answer by Pigghaj · Jan 02, 2012 at 02:30 PM Thanks for the answers. The script is definitely included in the prefab since other portions of the script works fine. And the prefab is also updated. If I have an empty scene, drag the prefab into the scene and press play it works. If I instantiate the same prefab using a script it does not. Here is my script on the object I want to click. I have removed everything else for debugging. function Start () { print("SCRIPT IS WORKING"); } function OnMouseUp () { print("Click!"); } And thats it. The code in the start function works fine when I instantiate, but the object does not become clickable. When I press play I run this script to instantiate. var smallChipTest : Transform; function Start () { var myObjectInstance1 : Transform = Instantiate(myObject, Vector3(0, 0, 0), Quaternion.identity); } And thats it. I've tried using GameObject instead of Transform but it does exactly the same. The code in the Start function works fine, but the OnMouseUp does not. It's like the OnMouseUp function is completely ignored when instantiating, but when manually adding the object to the scene, its there. I dont use layering or parenting in any way, as far as I know anyway. The only thing I can think of is a superimposition of colliders. If you instantiate your clickable object inside ANOTHER object which has a collider, it'll intercept the click. No, thats not it either. Very odd... Answer by ThePunisher · Jan 30, 2012 at 06:36 PM I'm not exactly sure what you are doing as you didn't provide enough information but I can guarantee you that the OnMouseUp works even if you instantiate the object. Take the following example: 1) Grab the following c# script and place it on an empty GameObject (ctrl+shift+n). It will give you a button to instantiate a prefab. using UnityEngine; using System.Collections; public class Example : MonoBehaviour { public GameObject prefab; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnGUI() { if(GUI.Button(new Rect(0,0, 100, 50), "Instantiate")) { Instantiate(prefab, Vector3.zero, Quaternion.Euler(Vector3.zero)); } } } 2)Now create a cube in your scene. Make sure it has a Collider component (it should by default), otherwise the object will not pick up any mouse clicks. 3)Drag the following c# script into that cube you just created: using UnityEngine; using System.Collections; public class ExampleClickableObject : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnMouseUp() { print("this works!"); } } 4)Drag this cube from your Hierarchy window to your Project window to create a prefab of it. 5)Now select the empty GameObject that you created in step #1 and drag the cube prefab onto the public prefab property to give the Example script a reference to the prefab. Now, delete whatever is on screen (which should be the cube you used to create the prefab) and run Unity. Click the Instantiate button and then try clicking the cube. You should see the message "this works!" appear in the console window. Take a look at what is different between your stuff and mine, and you should be able to figure out what you did wrong. I know you probably already got your answer but I'm posting this in case anybody else runs. Checking if object intersects? 1 Answer Script Not Working On Prefab 2 Answers NULL but I can see in the Inspector that its not! 1 Answer Problems with OnMouseUp 1 Answer Instantiate Random Object at Random Position 1 Answer
https://answers.unity.com/questions/201030/onmouseup-does-not-work-on-instantiated-object.html
CC-MAIN-2018-47
refinedweb
979
65.01
On Feb 11, 2009, at 8:14 AM, Diego Biurrun wrote: > On Wed, Feb 04, 2009 at 12:08:23PM -0800, David DeHaven wrote: >> >>. Someone with more x86 >>>>> assembly experience could probably find a better solution... I'm >>>>> just kinda hacking in the dark here. I was able to build 64 bit >>>>> dylibs though. >>>> >>>> yeah; me... >> >> --- libavcodec/x86/x86inc.asm (revision 16966) >> +++ libavcodec/x86/x86inc.asm (working copy) >> @@ -29,14 +29,10 @@ >> ; >> + %ifidn __OUTPUT_FORMAT__,macho >> fakegot: >> - %else >> - SECTION .rodata align=16 >> %endif >> + SECTION .rodata align=16 >> %endmacro > > What about this? > > Diego Re: an earlier suggestion for using .data: IIRC, Art tried .data and it crashed. IMHO, the above patch and moving the table up so it's under SECTION_RODATA is a far more appropriate solution. Unfortunately I haven't had the time to work up a test to drop into configure to verify that section .rodata alignment works in yasm yet. It can be done by assembling something like: cat << EOF > blah.asm SECTION .text foo: db 'blah' SECTION .rodata align=16 bar: db 'bleh' EOF yasm -f macho blah.asm The rodata section should end up at virtual address 16 (or some multiple thereof) in the object file which can be checked with either otool or objdump: otool -l blah.o | grep -A4 "segname __DATA" segname __DATA addr 0x00000010 size 0x00000004 offset 248 align 2^4 (16) i686-apple-darwin9-objdump -h blah.o | grep 'LC_SEGMENT.__DATA.__const' 2 LC_SEGMENT.__DATA.__const 00000004 00000010 00000010 000000f8 2**4 (second value is virtual address) So ultimately the problem becomes having to decide which tool can be used to check and then parsing the output of that tool... if cross- compiling for Mac, then it's most likely objdump since it's installed with binutils, but Apple does not ship objdump with XCode, just otool (I built it separately). In either case a regex pattern or two could extract the section address pretty easily. I think the easiest method would be to check if the last character is zero, if it's not then the section is not aligned properly. The section alignment value should also be verified ("2^4 (16)" from otool, "2**4" in objdump). Not a huge problem but it's time consuming work, a luxury I don't have at the moment. -DrD-
http://ffmpeg.org/pipermail/ffmpeg-devel/2009-February/064507.html
CC-MAIN-2018-05
refinedweb
386
66.84
When we talk about containers a big name that comes into picture is docker. Docker is a leading container platform and provides all the functionalities required in the life cycle of a container. In this article, we will talk about docker components and how they work together. Docker consists of the following components. Docker Daemon: Docker Daemon runs as dockerd and is a continuous running process. This daemon helps you in connecting docker-cli to containers itself. Docker talks to containerd using gRPC protocol. You can see by typing below command in your Linux machine. ps aux | grep docker /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock You can see the output contains dockerd and also tells that it is using containerd. Containerd: Containerd daemon runs and expose gRPC API to interact with it. It handles all the low-level container management tasks, storage, image distribution, network attachment, etc. If you wanna see this you can type below command. ps aux| grep container 0:01 /usr/bin/containerd This shows you that containerd daemon is running and no containerd-shim is running. Containerd-ctr: A lightweight CLI to directly communicate with containerd. You can control containerd using this cli tool. runc: It is used for actually running containers. This binary deal with the low-level things like cgroups and namespaces that are required to create a container. Whenever you run any container this process will come into the picture. To see this in action. Run the below commands in two different terminals. watch 'ps aux| grep runc' And then this docker run image_name You will see a process will appear, create the container and then exit. containerd-shim: Once runc launches containers it exits. This means there is no long-running process for this container. The flow is containerd asked containerd-shim to launch container which calls runc to create container and then exits leaving a few of the things like file descriptors so that container can pass essential signals to containerd-shim. If your container is running you can see containerd-shim is running like below root 16097 1.0 0.0 10612 4912 ? Sl 22:03 0:00 containerd-shim -namespace moby -workdir /var/lib/containerd/io.containerd.runtime.v1.linux/moby/61fd4688eae0b6b938aa07d609f55150cf0231af2d6043cd01d29cee5ee63d14 -address /run/containerd/containerd.sock -containerd-binary /usr/bin/containerd -runtime-root /var/run/docker/runtime-runc So here is a glance of how docker components talk to each other. Docker instruct containerd to launch a container, containerd tell containerd-shim to launch a container, containerd uses runc to launch the container and then keep the signals line open with it while runc exits.Recommended books for devops and linux admin This was how docker components interact with each other. To know more about Docker and Kubernetes keep following my blog. A lot of such articles will be coming soon. Please share and subscribe. Please join our facebook and linkedin groups.
https://www.learnsteps.com/docker-components-and-how-they-interact/
CC-MAIN-2022-27
refinedweb
488
50.53
In python moviepy, we can use ImageSequenceClip() function to convert a serial of images to a video. However, this method needs all image should be the same size. Can python moviepy convert images with different width and height to a video? concatenate_videoclips() Python moviepy concatenate_videoclips() method can allow us to convert images with different width and height to a video. It can concatenate several video clips. It will use two methods to concatenate images: method=”chain”: will produce a clip that simply outputs the frames of the succesive clips, without any correction if they are not of the same size of anything. method=”compose”, if the clips do not have the same resolution, the final resolution will be such that no clip has to be resized. We will use an example to show you how to use this method. Convert different size images (PNG, JPG) to video using python moviepy We should import some packages first. from moviepy.editor import * Then, we will use some images to create some video clips. files = ['1.png', '2.png', '3.png', '4.png'] frames = [ImageClip(f, duration = 4) for f in files] You should notice: duration = 4 means each image is 4 seconds. There are 4 images in this example, the total time of the final video is 4*4 = 16 seconds. Use concatenate_videoclips() to concatenate video clips above. clip = concatenate_videoclips(frames, method = "chain") clip.write_videofile("video.mp4", fps = 24) Here we use chain method to compose video clips, you also can use compose method. However, the effect may be not good if your images are poor quality.
https://www.tutorialexample.com/python-moviepy-convert-different-size-images-png-jpg-to-video-python-moviepy-tutorial/
CC-MAIN-2021-31
refinedweb
265
72.36
January 25, 2019 Single Round Match 747 Editorials SRM 747 was held on 19th Jan, 2019. Thanks to misof for the problems and editorials Sherlock In this problem we had to find out whether a name is similar enough to “Benedict Cumberbatch”. The solution is straightforward, we just check all the conditions listed in the problem statement. Note that the implementation can be made more pleasant if you know and use the correct string manipulation functions in your language. def howManyLetters(name, letterBank): return sum( x in letterBank for x in name ) def isBenedict(firstName, lastName): if len(firstName) < 5 or len(lastName) < 5: return False if firstName[0] != 'B' or lastName[0] != 'C': return False if howManyLetters(firstName, "BENEDICT") < 3: return False if howManyLetters(lastName, "CUMBERBATCH") < 5: return False return True CycleLength Each value is uniquely determined by the previous one. Thus, once a value in the sequence repeats, the sequence has entered a cycle. As there are only finitely many possible values (namely, exactly m), there has to be a repeated value among the first m+1 elements of the sequence. Thus, probably the easiest solution looks as follows: Generate the first m+1 elements. You are now guaranteed to be in the part that repeats. Let x be the current element. Generate following elements until x appears again, and count the steps. That number of steps is the length of the shortest period. This solution has no special cases and it needs no data structures – it needs just a constant number of variables. In the worst case it will generate about 2*m elements of the sequence, and thus its time complexity is O(m). public int solve(int seed, int a, int b, int m) { long state = seed; for (int i=0; i<m+47; ++i) state = (state*a+b) % m; long goal = state; for (int steps=1; ;++steps) { state = (state*a+b) % m; if (state == goal) return steps; } } Another short solution is to use a data structure. The most appropriate one is a map in which we use the value of an element as the key. The value we store with the key is the index at which the value appeared for the first time. We then generate the sequence one element at a time, and we store all elements into that map. As soon as an element repeats, we know that we found a period. Its length can be computed as the current index (i.e., the index of the second occurrence of the repeated value) minus the index of its first occurrence (which can be retrieved from the map). For an even smarter solution that can find the preperiod and period in optimal time, in constant space, and even without knowing an upper bound on the period length in advance, look up Floyd’s cycle-finding algorithm. MostFrequentLastDigit Silently, this was the most interesting problem of the round, especially for top Div1 contestants. I’ll get to the reason for this claim later. Of course, the problem was solvable in ways other than the one I had in mind when writing the previous paragraph. Let’s try to come up with a nice deterministic solution. One approach that might help us is a simple visualization of all possible sums of pairs. Here are all the possible sums for the sequence 1,3,1,2,2,4: We may notice that if we have multiple copies of the same number, they each produce the same multiset of sums. In the figure these appear as identical parts of rows/columns. More precisely, if we have two numbers X and Y with the same last digit, the last digits of the sums that involve X are the same as the last digits in the sums that involve Y. That sounds like a good way to make a lot of copies of the same result. Let’s see what happens if we only use two distinct values. In our example, let’s try using three 3s and three 7s. The yellow square shows that we now have nine sums that end in a zero: each 3 combined with each 7. Out of all fifteen sums, nine end in a zero and only six end in a different digit. That sounds promising. If we can make sure that our digit is more frequent than all other digits combined, it has to be the most frequent of all. And the figure shown above gives us an idea how to do it. Here’s the resulting algorithm: Find two non-zero digits x and y such that (x+y) mod 10 = d. Create an array with floor(n/2) copies of x and ceil(n/2) copies of y. Make sure that the numbers are all distinct. Why does it work? Step 1 can always be performed. For example, if d is at least 2, we can choose x=1 and y=d-1; and we can choose (5,6) for d=1 and (4,6) for d=0. In step 2 we will create an array for which the sums of many pairs will end in the digit d. Are there enough of those? If n = 2k, we have k*(2k-1) pairs and out of those k*k are good and only k*(k-1) are bad. And if n=2k+1, we have k*(2k+1) pairs and out of those k*(k+1) are good and only k*k are bad. Hence, in both cases our digit is clearly the most frequent one. This is easy to do. For example, we just add 10*i to the element at position i. TieForMax This problem has multiple polynomial-time solutions. I’ll show one that’s based on computing the complementary probability — i.e., the probability that the maximum is unique. We will do a three-dimensional dynamic programming. Let ways[a][b] be the number of sequences of actions in which we can distribute a tokens onto b piles so that each pile has at most c tokens. These values are easy to compute. We’ll leave the base cases as an exercise and we’ll only focus on the general case. The general case is computed as follows: ways[a][b] = sum( binomial[a][i] * ways[a-i][b-1] for i = 0..min(a,c) ) What’s going on in the formula? We try all possibilities for the number i of tokens on the first pile. Once we have fixed i, we have binomial[a][i] ways to choose the steps in which we placed those tokens, and for each of those ways we have ways[a-i][b-1] ways to distribute the remaining a-i tokens onto the remaining b-1 piles in a valid way. Now, once we have this precomputed, we can find the probability that a unique pile is maximal: we will just iterate over all possibilities for its size. For each x we will compute the probability that the unique maximal pile has size x, and as these events are distinct, the result is simply the sum of these probabilities. How many different sequences of actions will produce a result in which the unique maximal pile has size x? We have p options for which pile it is, we have binomial[t][x] ways to choose in which steps we placed a token onto this pile, and we have ways[t-x][p-1][x-1] ways to distribute the remaining tokens onto the remaining piles in such a way that all of them are smaller. Thus, the total number of valid sequences of actions is the sum of p*binomial[t][x]*ways[t-x][p-1][x-1] over all x. The total number of actions is simply p^t. Hence, the correct return value of our function is 1 – (the result from the previous paragraph, divided by p^t). The array “ways” has O(t*t*p) cells, and we can compute each of those in O(t) time. The final sum is negligible in comparison. Thus, our solution has the time complexity O(t^3*p) and space complexity(t^2*p). RochesterSequences This problem has a fairly straightforward dynamic programming solution that is correct but too slow. The solution looks as follows: Let best[i][j] be the length of the longest NRS (nondecreasing Rochester sequence) that starts with element i and ends with element j. To compute this, we will try all the possibilities for the second element and all possibilities for the second-to-last element, and we will return the best among those. Formally, best[i][j] = 1 + max best[p][q] overall p,q such that (i < p < q < j) and S[i]+S[j] <= S[p]+S[q]. This solution works in O(n^4). Can this solution be improved? Not directly. Usually if we want to take a maximum over some possibilities, we can do it faster if we use an efficient data structure, but in this case the condition is rather ugly, as we need to select the maximum of some ugly three-dimensional subspace. In cases like the one above it is sometimes possible to reduce the complexity by taking one dimension out into the order in which we evaluate the subproblems. This is precisely the technique that will help us solve this problem as well. Before we apply it, we’ll think about a better visualization of the problem we are solving. Instead of using the definition from the statement, we can define NRSs as follows: an NRS is a sequence of intervals with two properties: They are properly nested, i.e., each one lies strictly inside the previous one. Their weights are nondecreasing. (Here, the weight of [i,j] is defined as S[i]+S[j].) The general scheme of our solution will still be the same as above: for each interval we are trying to find the longest NRS that starts with this interval. Now comes the main trick. In standard interval DP problems we tend to sort the subproblems by length. In this case, that doesn’t help, as it still leads to the same problem as above. However, what does help is sorting the intervals by weight (and only using length as a tie-breaker). (Remark: Any other single dimension would also work, but as i, j are small and weights can be large, this is the most convenient way.) Imagine that we have all possible intervals sorted by weight (min to max), and intervals with the same weight sorted by length (max to min). By doing this sort, we eliminated one dimension of the original problem. We are now asking for the longest sequence of intervals with the following properties: It is a subsequence of this sequence. (This is now trivial.) The intervals are properly nested. In order to find the optimal solution, we will process our sorted sequence back to front. Whenever processing an interval, the optimal solution that starts with it can be found by taking a maximum over the solutions for all intervals that 1. have already been processed, and 2. lie strictly inside this interval. Thus, we can use a data structure that can perform point updates (we just computed a new value) and rectangular queries (what is the maximum among the already computed values in this range?). One such data structure is a 2-dimensional range tree. This data structure can perform the necessary operation in O(log^2 n), and thus the total time complexity becomes O(n^2 log^2 n). MostFrequentLastDigit revisited The cool thing about this problem is that it can be solved completely at random, which is quite a rare thing in programming contests 🙂 More precisely, here is a perfectly valid solution: while True: generate a random array of valid numbers if it has all other desired properties, return it Here’s the same thing actually implemented in Python. def valid_number(): while True: x = randint(0,10**9 - 1) if x % 10: return x def solve(n,d): while True: A, B = [ valid_number() for _ in range(n) ], [0]*10 for i in range(n): for j in range(i): B[ (A[i]+A[j]) % 10 ] += 1 if len(set(A)) == n and max(B) == B[d] and B.count(max(B)) == 1: return A Yep, that’s it. Why does it work? And, more importantly, how could one read the problem statement, come up with this approach and trust that it will work? I’ll answer these questions below. Note that I’ll intentionally skip most of the details. Everything below can be turned into exact computations, but the main point of the following text is precisely to show how to avoid those tedious computations and just make an educated guess. First of all, the random array will be very unlikely to contain collisions. From the birthday paradox we know that a collision becomes likely if the number of items approaches roughly the square root of the length of the array. Here, we are selecting 200 random numbers from among 900 million roughly evenly distributed ones. We should be safe, collisions should be quite rare. (Of course, this step can be skipped by the alternate easy construction where we set A[i] = randint(1,9)+10*i for all valid i. This guarantees no collisions and the same distribution of last digits, at the cost of having to think a little bit more.) Second, if we just take a random array and look at the last digits of its pairwise sums, some digit will usually win. Sometimes there will be a tie for the maximum (do you see how this relates to the div1 medium problem?) but quite often the maximum should be unique. If we a) didn’t have the asymmetry introduced by banning the last digit 0, and b) ignored the possibility of ties for the maximum, each digit would be the most frequent digit in pairwise sums with probability 1/10. And that would mean that on average generating 10 valid arrays should be enough to hit one correct answer. We now need to take into account the two factors we ignored above. How big is the bias, and how big is the possibility of a tie? When I first considered this problem, I did the following back-of-the-envelope estimates: If we have x,y from {1,2,…,9}, there are clearly 9 ways to get the sum 0 and 8 ways to get any other sum. Thus, for the code shown above, the expected value of B[0] is (9/81)*(the number of pairs), and for each other B[i] it is (8/81)*(the number of pairs). The number of pairs is roughly 20,000, so the expected number of 0s is about 250 higher than the expected number of any other digit. For a binomial distribution with n trials the standard deviation is on the order of sqrt(n), so the actual numbers in a trial will easily go a hundred or two up or down. That is enough to a) expect that max(B[1:10]) will be unique most of the time, because the range of possible values is large enough; and b) expect that max(B[1:10]) has a reasonable chance to beat B[0]. And if we need a small number of random trials to get an input for which max(B[1:10]) > B[0], we only need 9 times that many trials to get an input for which a specific B[d] is the unique maximum. In order to train your intuition, I suggest two things. First, work out the math I did at least a bit more precisely and think about what assumptions you can and cannot make. Second, play around with the implementation to see whether and how actual data you’ll measure matches the estimates you made. If there are discrepancies, try to find out where they came from. misof
https://www.topcoder.com/single-round-match-747-editorials/
CC-MAIN-2019-43
refinedweb
2,681
70.13
What is DynamoDB? DynamoDB is a hosted NoSQL database offered by Amazon Web Services (AWS). It offers: reliable performance even as it scales; a managed experience, so you won't be SSH-ing into servers to upgrade the crypto libraries; a small, simple API allowing for simple key-value access as well as more advanced query patterns. DynamoDB is a particularly good fit for the following use cases: Applications with large amounts of data and strict latency requirements. As your amount of data scales, JOINs and advanced SQL operations can slow down your queries. With DynamoDB, your queries have predictable latency up to any size, including over 100 TBs! Serverless applications using AWS Lambda. AWS Lambda provides auto-scaling, stateless, ephemeral compute in response to event triggers. DynamoDB is accessible via an HTTP API and performs authentication & authorization via IAM roles, making it a perfect fit for building Serverless applications. Data sets with simple, known access patterns. If you're generating recommendations and serving them to users, DynamoDB's simple key-value access patterns make it a fast, reliable choice. On aws we may want to use Dynamo for our APIs Lets see how we can do this with nestjs for Other database like SQL we always use some kind of ORM to deal with database like and may be some other ORM, now we are talking here about AWS managed solution Dynamo DB so we don't have pre installed local setup fpr this we have to access AWS managed database only from AWS account. Some simple javascript solution provided by data mapper library using which we can query dynamo Table We can setup new nestjs app Setting up a new project is quite simple with the Nest CLI. With npm installed, you can create a new Nest project with the following commands in your OS terminal: $ npm i -g @nestjs/cli $ nest new project-name The project-name directory will be created, node modules and a few other boilerplate files will be installed, and a src/ directory will be created and populated with several core files. In this article, I will show you how to make CRUD operations with Dynamoose on DynamoDB. Let’s do it😎 Dynamodb DynamoDB is a NoSQL database offered and hosted by AWS. Before starting, I will talk about DynamoDB with an ORM package. If you wanna use native functions without any package, you can reach the official documentation of DynamoDB and Node.js As I said at the start of this article, we will talk about how can we make CRUD operations with Dynamoose. Let’s explain the CRUD for those who don’t know. It is not an acrostic poem 😒Those are the names of the database operations as you know. But I nevertheless wanted to remind you. npm install dynamoose I suppose that you stored your AWS credentials in your .env file After the installation, you should import the package and declare your credentials in your file. Like this; const dynamoose = require(“dynamoose”); let AWS_ACCESS_KEY_ID = process.env.AWS_ACCESS_KEY_ID; let AWS_SECRET_ACCESS_KEY = process.env.AWS_SECRET_ACCESS_KEY; let AWS_REGION = process.env.AWS_REGION;] dynamoose setup After then we have to pass our credentials to dynamoose dynamoose.aws.sdk.config.update({ accessKeyId: AWS_ACCESS_KEY_ID, secretAccessKey: AWS_SECRET_ACCESS_KEY, region: AWS_REGION, })] dynamoose config If you used Mongoose or Sequelize you can know the schema approach. The schema represents the structure of each row of a table. Let’s define a schema and create a table using this schema. const dynamoose = require("dynamoose"); const schema = new dynamoose.Schema({ "id": String, "age": Number }, { "saveUnknown": true, "timestamps": true }); example import * as dynamoose from "dynamoose"; import {Document} from "dynamoose/dist/Document"; // Strongly typed model class Cat extends Document { id: number; name: string; } const CatModel = dynamoose.model<Cat>("Cat", {"id": Number, "name": String}); // Will raise type checking error as random is not a valid field. CatModel.create({"id": 1, "random": "string"}); // Will return the correct type of Cat const cat = await CatModel.get(1); const UserSchema = new dynamoose.Schema({ id:{ type: String, hashKey: true }, name: { type: String, required: true }, username: { type: String, required: true }, type: String, required: true }, phone: { type: String, required: true }, role: { type: String, required: true } }); const User = dynamoose.model(“User”, U) Define a schema and table Dynamoose We will use the User constant, which refers to the user table from Dynamoose. Create a new record (Insert) ➕ let newUser = new User({ name, username, password, phone, role }); return newUser.save(); dynamoose insert When the save() method run, the insertion process is performed. save() Update a record 🔃 dynamoose update by primary key update functions the first argument is the primary key of the record. And the second argument is the updated data of the record. These functions return a promise. Delete a record ❌ dynamoose delete by primary key Get a record 🗞️ dynamoose get one row by primary key Using the ‘where’ with a condition Let’s examine this login function 👌 User.login = async function (username, password) { let result = await User.scan({ “username”: { “eq”: username }, “eq”: password } }).exec(); if(result.count === 0){ return Promise.reject(“Username or password is incorrect”); }else{ return result[0]; } } Cat.query("name").eq("Will").exec((error, results) => { if (error) { console.error(error); } else { console.log(results); // [ Document { name: 'Will', breed: 'Terrier', id: 1 }, // lastKey: undefined, // count: 1, // queriedCount: 2, // timesQueried: 1 ] console.log(results[0]); // { name: 'Will', breed: 'Terrier', id: 1 } console.log(results.count); // 1 console.log(Array.isArray(results)); // true console.log(results.scannedCount); // 2 } }); Cat.scan().exec((error, results) => { if (error) { console.error(error); } else { console.log(results); // [ Document { name: 'Will', breed: 'Terrier', id: 1 }, // lastKey: undefined, // count: 1, // scannedCount: 2, // timesScanned: 1 ] console.log(results[0]); // { name: 'Will', breed: 'Terrier', id: 1 } console.log(results.count); // 1 console.log(Array.isArray(results)); // true console.log(results.scannedCount); // 2 } }); The example login function on the User model with Dynamoose As you can see, the scan function takes one argument and this argument includes the condition. And eq means equal. and, or etc. you can use. 🎯 eq and or This function is used to set the AWS.DynamoDB() instance to use the a local endpoint as opposed to the production instance of DynamoDB. By default the endpoint used will be. You can pass in a string for the endpoint parameter to change what endpoint will be used. dynamoose.aws.ddb.local(); dynamoose.aws.ddb.local("");
https://tkssharma.com/nestjs-with-aws-dynamo-db-using-dynamoose/
CC-MAIN-2022-40
refinedweb
1,055
57.47
Shared Library This is a collection of knowledge about shared/dynamic libraries. Libraries are an indispensable tool for any programmer. They are pre-existing code that is compiled and ready for you to use. Most larger software projects will contain several components, some of which you may find use for later on in some other project, or that you just want to separate out for organizational purposes. When you have a reusable or logically distinct set of functions, it is helpful to build a library from it so that you. Pros and Cons. - Smaller executable memory. From Source Code to Running a Program - C Preprocessor: This stage processes all the preprocessor directives. Basically, any line that starts with a #, such as #define and #include. - Compilation Proper: Once the source file has been preprocessed, the result is then compiled. Since many people refer to the entire build process as compilation, this stage is often referred to as compilation proper. This stage turns a .c file into an .o (object) file. - Linking: Here is where all of the object files and any libraries are linked together to make your final program. Note that for static libraries, the actual library is placed in your final program, while for shared libraries, only a reference to the library is placed inside. Now you have a complete program that is ready to run. You launch it from the shell, and the program is handed off to the loader. - Loading: This stage happens when your program starts up. Your program is scanned for references to shared libraries. Any references found are resolved and the libraries are mapped into your program. Steps 3 and 4 are where the magic (and confusion) happens with shared libraries. Now, on to our (very simple) example. foo.h: #ifndef foo_h__ #define foo_h__ extern void foo(void); #endif // foo_h__ foo.c: #include <stdio.h> void foo(void) { puts("Hello, I am a shared library"); } main.c: #include <stdio.h> #include "foo.h" int main(void) { puts("This is a shared library test..."); foo(); return 0; } foo.h defines the interface to our library, a single function, foo(). foo.c contains the implementation of that function, and main.c is a driver program that uses our library. Assume that for the purposes of this example, everything will happen in /home/username/foo. Step 1: Compiling with Position Independent Code We need to compile our library source code into position-independent code (PIC)1: $ gcc -c -Wall -Werror -fpic foo.c Step 2: Creating a shared library from an object file Now we need to actually turn this object file into a shared library. We will call it libfoo.so: $ gcc -shared -o libfoo.so foo.o Step 3: Linking with a shared library and end with .so or .a (.so is for shared object or shared libraries, and .a is for archive, or statically linked libraries). $ gcc -Wall -o test main.c -lfoo /usr/bin/ld: cannot find -lfoo collect2: ld returned 1 exit status Telling GCC where to find the shared library Uh-oh! The linker does not know where to find libfoo. GCC has a list of places it looks by default, but our directory is not in that list.2 We need to tell GCC where to find libfoo.so. We will do that with the -L option. In this example, we will use the current directory, /home/username/foo: $ gcc -L/home/username/foo -Wall -o test main.c -lfoo Step 4: Making the library available at runtime Good, no errors. Now let us run our program: $ ./test ./test: error while loading shared libraries: libfoo.so: cannot open shared object file: No such file or directory Or on Mac Mojave with gcc9 from another directory: $ ./ex1/test dyld: Library not loaded: libfoo.so Referenced from: .../ex1/test Reason: image not found Abort trap: 6: Using LD_LIBRARY_PATH $ echo $LD_LIBRARY_PATH There is nothing in there. Let us fix that by prepending our working directory to the existing LD_LIBRARY_PATH: $. Using rpath Now let s try rpath (first we will clear LD_LIBRARY_PATH to ensure it is rpath that is finding our library). Rpath, or the run path, is a way of embedding the location of shared libraries in the executable itself, instead of relying on default locations or environment variables. We do this during the linking stage. Notice the lengthy -rpath=/home/username/foo option. The -Wl portion sends comma-separated options to the linker, so we tell it to send the -rpath option to the linker with our working directory. $ unset LD_LIBRARY_PATH $ gcc -L/home/username/foo -Wl,-rpath=/home/username/foo -Wall -o test main.c -lfoo $ ./test This is a shared library test... Hello, I am a shared library Excellent, it worked. The rpath method is great because each program gets to list its shared library locations independently, so there are no issues with different programs looking in the wrong paths like there were for LD_LIBRARY_PATH. rpath vs. LD_LIBRARY_PATH There are a few downsides to rpath, however. First, it requires. Using ldconfig to modify ld.so What if we want to install our library so everybody on the system can use it? For that, you will need admin privileges. You will need this for two reasons: first, to put the library in a standard location, probably /usr/lib or /usr/local/lib, which normal users do not have write access to. Second, you will need to modify the ld.so config file and cache. As root, do the following: $ cp /home/username/foo/libfoo.so /usr/lib $ chmod 0755 /usr/lib/libfoo.so Now the file is in a standard location, with correct permissions, readable by everybody. We need to tell the loader it is available for use, so let us update the cache: $ ldconfig That should create a link to our shared library and update the cache so it is available for immediate use. Let us double check: $ ldconfig -p | grep foo libfoo.so (libc6) => /usr/lib/libfoo.so Now our library is installed. Before we test it, we have to clean up a few things: Clear our LD_LIBRARY_PATH once more, just in case: $ unset LD_LIBRARY_PATH Re-link our executable. Notice we covered how to build a shared library, how to link with it, and how to resolve the most common loader issues with shared libraries - as well as the positives and negatives of different approaches. Resources Shared libraries with GCC on Linux Creating dynamic libraries Because several different programs can all use one instance of your shared library, the library cannot store things at fixed addresses, since the location of that library in memory will vary from program to program. In PIC,. The -PIC compiler option is similar to -pic, but -PIC allows the global offset table to span the range of 32-bit addresses. directories specified by the -L parameter, in the order specified on the command line. DT_RPATHsection of the executable, unless there is a DT_RUNPATH section. LD_LIBRARY_PATH. This is skipped if the executable is setuid/setgid for security reasons. DT_RUNPATHsection of the executable unless the setuid/setgid bits are set (for security reasons). /etc/ld/so/cache(disabled with the -znodeflib linker option). - default directories /libthen /usr/lib(disabled with the -z nodeflib linker option).
https://henry2004y.github.io/blog/shared-library/
CC-MAIN-2022-05
refinedweb
1,209
67.15
I'm using visual studio 2017 community, I installed MonoGame for visualstudio.I saw somewhere that there was an option to directly create a IOS/Android MonoGame app But I don't have that option. So I created a "MonoGame shared project" with namespace "MG", I added a "MonoGame Android Project" with namespace "MG.Droid" and a "MonoGame IOS Project" with namespace "MG.IOS". I remove the game1.cs file in IOS and Android Project as I wan't to add those in the shared project. But The class is not detected and when I try to compile for android I get the error: `Error CS0246 The type or namespace name 'Game1' could not be found (are you missing a using directive or an assembly reference?) ARMG.Droid c:\Source\Repos\MG\MG.Droid\Activity1.cs` I'm not familiar with using namespaces so maybe I made a mistake ? The structure is like that: Solution||__Shared Project with MG namespace| |__Game1.cs||__Android project with MG.Droid namespace| |__Activity.cs||__IOS project with MG.IOS namespace |__Program.cs
http://community.monogame.net/t/no-option-to-create-a-monogame-ios-android-app-in-vs-2017/10966
CC-MAIN-2019-13
refinedweb
178
67.96
Ads Via DevMavens I’ve been struggling for the last few days with putting the finishing touch on a simple client side Tab control that I had built to provide the ability to break large pages into smaller pages that can be controlled via a simple tabstrip at the top. The control itself is super simple – basically a table with OnClick handlers, along with some generated script functions that activate the appropriate page using ID tags in the document. The control works well and requires a handful of lines of code added to a page. Something as simple as this: AdminTabs.AddTab("Main","default","Main"); AdminTabs.AddTab("Email","javascript:ActivateTab(this);ShowTabPage('Email');","Email"); AdminTabs.AddTab("CC Processing","default","CreditCard"); AdminTabs.AddTab("Configuration","default","Configuration"); if (!this.IsPostBack) AdminTabs.SelectedTab = "Main"; // or set this in the designer The tab control works all client-side, so there’s no server side event handling. The only thing that happens server side is the rendering and the state management of tracking the currently active page via a hidden variable on the form (rather than ViewState because the var is set on the client side via script code). Creating this control was a snap and using ASP.Net’s object model was a clean and efficient affair. It basically involved creating a TabPage class, a TabPageCollection class (based on CollectionBase) and then implementing the actual control and rendering mechanism. However, what wasn’t so easy was to create a design time interface. The tab control uses a collection of a TabPage class and getting this collection to properly persist into the HTML from the designer took some guess work and the help of several people who had gone through this before. I couldn't find all this in one place so I'm providing here what I found I needed. The control should work like this: <ww:wwwebtabcontrol <tabpages> <ww:tabpage< SPAN>ww:tabpage> <ww:tabpage< SPAN>ww:tabpage> <ww:tabpage< SPAN>ww:tabpage> < SPAN>tabpages> < SPAN>ww:wwwebtabcontrol> Just using the Collection on the control will not give you the above automatically. In fact the collection will not even be loaded with this data if you try to open the form with the collection. It will not even show up on the property sheet. Specifying how complex control members such as objects and collections persist is driven through attributes that must be specified on the control itself and on any complex members. For a collection this means something like this: Control Level [ToolboxData("<{0}:wwWebTabControl runat=server>")] [ToolboxBitmap(typeof(System.Web.UI.WebControls.Image))] [ParseChildren(true)] [PersistChildren(false)] public class wwWebTabControl : Control ParseChildren tells the control that it needs to run through the items and add them to the collection. Several people actually suggested to me that this attribute should be set to false but that caused items not to be parsed into the actual collection when the form first loaded. PersistChildren set to false indicates that the items are to be persisted as nested elements rather than as attributes on the control itself (using control-subproperty syntax). Both of these are vital! The control should also implement the AddParsedSubObject method which makes sure that the inner items can be parsed into the collection: protected override void AddParsedSubObject(object obj) { if (obj is TabPage ) { this.TabPages.Add((TabPage) obj); return; } } Collection Member Level The collection property on the control itself also requies a couple of attributes to make it work properly. [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [PersistenceMode(PersistenceMode.InnerProperty)] public TabPageCollection TabPages get { return Tabs; } private TabPageCollection Tabs = new TabPageCollection(); DesignerSerializationVisibility(DesignerSerializationVisibility.Content) determines how code is generated for this object. Specifically the above visibility creates individual TabPage object references in ASPX code behind file. Using visibility of Visible does not create code instances of the TabPages – which is actually desirable in this situation. You can always reference each of the pages dynamically through the collection itself. The PersistenceMode attribute determines how the designer persists the collection’s content so it can load it at design or run time. In this case I chose InnerProperty which means it creates child controls (TabPages) that contain all their content as attributes. You can also use InnerDefaultProperty for objects that have default properties and that persist as the element content – a asp:ListItem is a good example of this type of item. Generally if you use a collection use InnerProperty. In addition you can also use Attribute which persists the object as attributes in the parent control. This won’t work for a collection, but it is useful for sub objects which can persist as with special syntax into the parent object by using ParentName-ChildProperty=’value’ syntax. Item Implementation When you use the above attributes VS.Net provides its default Collection Editor for editing the individual items – TabPage items in this case. To get items to display in the editor it’s easiest to derive them from Control as Control implements the default type converter interfaces needed for the CollectionEditor to create the items and assign property values and be able to serialize the collection into the HTML. If you don’t derive from collection you need to implement a TypeConverter for your class and use the TypeConverter attribute to specify it. Using Control or any Control derived class is definitely easier although it adds a little overhead to your collection items. Designer Rendering One of the really cool things about ASP.Net (WinForms too) is that you can render controls at design time, so the user can actually see what the control will look like in the designer while building the control within the full page layout. What I wanted to do is have the user see the control right from the start rather than just the default display which is basically the name of the control as a string. ASP. Net controls in the designer still call the Render method to draw themselves. This means as soon as I add tabs to my control the control will actually display them in real time with all the attribute settings reflected in the rendering. Problem is that when there are no tabs, nothing gets rendered. So in order to do this I decided why not add a couple of dummy items to the collections when there are no items, render them, then remove them at the end of the process. The code to do this looks like this: protected override void Render(HtmlTextWriter writer) bool NoTabs = false; string Selected = null; // *** If no tabs have been defined in design mode write a canned HTML display if (this.DesignMode && (this.TabPages == null || this.TabPages.Count == 0) ) NoTabs = true; this.AddTab("No Tabs","default","Tab1"); this.AddTab("No Tabs 2","default","Tab2"); Selected = this.SelectedTab; this.SelectedTab="Tab2"; // *** Render the actual control this.RenderControl(); // *** Dump the output into the ASP out stream writer.Write(this.Output); // *** Call the base to let it output the writer's output base.Render (writer); if (NoTabs) this.TabPages.Clear(); this.SelectedTab = Selected; Figuring out whether we are in DesignMode can be done by checking (HttpContext.Current == null) which is assigned here to a private property of the object. Complete Tab Control Example Source For completeness and reference’s sake I’m providing the code for the wwWebTabControl in its entirety here so you can see all the points above put together and in action. This control works on the concept of hiding and displaying content based on ID tags in the client HTML document. When you click a button Id tags are activated and deactivated hiding or displaying content depending on the tab selection. You need to match up the TabPageClientId on each TabPage with an ID in the document that is to be displayed. For example: AdminTabs.AddTab("Main","javascript:ActivateTab(this);ShowTabPage('Main');","Main"); Main specifies that the tab caption. The second parameter is the script or Url that fires in response to a click. Here the code calls two generated functions which activate the tab specified and then show the the content that is wrapped in the Main ID tag in the HTML page. Main is the TabPageClientId that maps this tab to an ID in the HTML page. The two statements above are identical – default is merely a shortcut for the first line which is the most common thing you’ll want to do – Activate the tab selected and display the content that is related to it. In order to use the control you will likely want to add it your Tools window. From there you can simply drag and drop the control and start adding Tab Pages through the designer. You can download the control along with a simple example page from here:
http://west-wind.com/weblog/posts/200.aspx
crawl-002
refinedweb
1,454
52.29
Lock. Lockless programming is a valid technique for multithreaded programming, but it should not be used lightly. Before using it you must understand the complexities, and you should measure carefully to make sure that it is actually giving you the gains that you expect. In many cases, there are simpler and faster solutions, such as sharing data less frequently, which should be used instead. Using lockless programming correctly and safely requires significant knowledge of both your hardware and your compiler. This article gives an overview of some of the issues to consider when trying to use lockless programming techniques. Programming with Locks When writing multi-threaded code it is often necessary to share data between threads. If multiple threads are simultaneously reading and writing the shared data structures, memory corruption can occur. The simplest way of solving this problem is to use locks. For instance, if ManipulateSharedData should only be executed by one thread at a time, a CRITICAL_SECTION can be used to guarantee this, as in the following code: This code is fairly simple and straightforward, and it is easy to tell that it is correct. However, programming with locks comes with several potential disadvantages. For example, if two threads try to acquire the same two locks but acquire them in a different order, you may get a deadlock. If a program holds a lock for too long—because of poor design or because the thread has been swapped out by a higher priority thread—other threads may be blocked for a long time. This risk is particularly great on Xbox 360 because the software threads are assigned a hardware thread by the developer, and the operating system won't move them to another hardware thread, even if one is idle. The Xbox 360 also has no protection against priority inversion, where a high-priority thread spins in a loop while waiting for a low-priority thread to release a lock. Finally, if a deferred procedure call or interrupt service routine tries to acquire a lock, you may get a deadlock. Despite these problems, synchronization primitives, such as critical sections, are generally the best way of coordinating multiple threads. If the synchronization primitives are too slow, the best solution is usually to use them less frequently. However, for those who can afford the extra complexity, another option is lockless programming. Lockless Programming Lockless programming, as the name suggests, is a family of techniques for safely manipulating shared data without using locks. There are lockless algorithms available for passing messages, sharing lists and queues of data, and other tasks. When doing lockless programming, there are two challenges that you must deal with: non-atomic operations and reordering. Non-Atomic Operations An atomic operation is one that is indivisible—one where other threads are guaranteed to never see the operation when it is half done. Atomic operations are important for lockless programming, because without them, other threads might see half-written values, or otherwise inconsistent state. On all modern processors, you can assume that reads and writes of naturally aligned native types are atomic. As long as the memory bus is at least as wide as the type being read or written, the CPU reads and writes these types in a single bus transaction, making it impossible for other threads to see them in a half-completed state. On x86 and x64 there, is no guarantee that reads and writes larger than eight bytes are atomic. This means that 16-byte reads and writes of streaming SIMD extension (SSE) registers, and string operations, might not be atomic. Reads and writes of types that are not naturally aligned—for instance, writing DWORDs that cross four-byte boundaries—are not guaranteed to be atomic. The CPU may have to do these reads and writes as multiple bus transactions, which could allow another thread to modify or see the data in the middle of the read or write. Composite operations, such as the read-modify-write sequence that occurs when you increment a shared variable, are not atomic. On Xbox 360, these operations are implemented as multiple instructions (lwz, addi, and stw), and the thread could be swapped out partway through the sequence. On x86 and x64, there is a single instruction (inc) that can be used to increment a variable in memory. If you use this instruction, incrementing a variable is atomic on single-processor systems, but it is still not atomic on multi-processor systems. Making inc atomic on x86- and x64-based multi-processor systems requires using the lock prefix, which prevents another processor from doing its own read-modify-write sequence between the read and the write of the inc instruction. The following code shows some examples: Guaranteeing Atomicity You can be sure you are using atomic operations by a combination of the following: - Naturally atomic operations - Locks to wrap composite operations - Operating system functions that implement atomic versions of popular composite operations Incrementing a variable is not an atomic operation, and incrementing may lead to data corruption if executed on multiple threads. Win32 comes with a family of functions that offer atomic read-modify-write versions of several common operations. These are the InterlockedXxx family of functions. If all modifications of the shared variable use these functions, the modifications will be thread safe. Reordering A more subtle problem is reordering. Reads and writes do not always happen in the order that you have written them in your code, and this can lead to very confusing problems. In many multi-threaded algorithms, a thread writes some data and then writes to a flag that tells other threads that the data is ready. This is known as a write-release. If the writes are reordered, other threads may see that the flag is set before they can see the written data. Similarly, in many cases, a thread reads from a flag and then reads some shared data if the flag says that the thread has acquired access to the shared data. This is known as a read-acquire. If reads are reordered, then the data may be read from shared storage before the flag, and the values seen might not be up to date. Reordering of reads and writes can be done both by the compiler and by the processor. Compilers and processors have done this reordering for years, but on single-processor machines it was less of an issue. This is because CPU rearrangement of reads and writes is invisible on single-processor machines (for non-device driver code that is not part of a device driver), and compiler rearrangement of reads and writes is less likely to cause problems on single-processor machines. If the compiler or the CPU rearranges the writes shown in the following code, another thread may see that the alive flag is set while still seeing the old values for x or y. Similar rearrangement can happen when reading. In this code, one thread adds a new entry to the sprite array: In this next code block, another thread reads from the sprite array: To make this sprite system safe, we need to prevent both compiler and CPU reordering of reads and writes. Understanding CPU Rearrangement of Writes Some CPUs rearrange writes so that they are externally visible to other processors or devices in non-program order. This rearranging is never visible to single-threaded non-driver code, but it can cause problems in multi-threaded code. Xbox 360 While the Xbox 360 CPU does not reorder instructions, it does rearrange write operations, which complete after the instructions themselves. This rearranging of writes is specifically allowed by the PowerPC memory model. Writes on Xbox 360 do not go directly to the L2 cache. Instead, in order to improve L2 cache write bandwidth, they go through store queues and then to store-gather buffers. The store-gather buffers allow 64-byte blocks to be written to the L2 cache in one operation. There are eight store-gather buffers, which allow efficient writing to several different areas of memory. The store-gather buffers are normally written to the L2 cache in first-in-first-out (FIFO) order. However, if the target cache-line of a write is not in the L2 cache, that write may be delayed while the cache-line is fetched from memory. Even when the store-gather buffers are written to the L2 cache in strict FIFO order, this does not guarantee that individual writes are written to the L2 cache in order. For instance, imagine that the CPU writes to location 0x1000, then to location 0x2000, and then to location 0x1004. The first write allocates a store-gather buffer and puts it at the front of the queue. The second write allocates another store-gather buffer and puts it next in the queue. The third write adds its data to the first store-gather buffer, which remains at the front of the queue. Thus, the third write ends up going to the L2 cache before the second write. Reordering caused by store-gather buffers is fundamentally unpredictable, especially because both threads on a core share the store-gather buffers, making the allocation and emptying of the store-gather buffers highly variable. This is one example of how writes can be reordered. There may be other possibilities. x86 and x64 Even though x86 and x64 CPUs do reorder instructions, they generally do not reorder write operations relative to other writes. There are some exceptions for write-combined memory. Additionally, string operations (MOVS and STOS) and 16-byte SSE writes can be internally reordered, but otherwise, writes are not reordered relative to each other. Understanding CPU Rearrangement of Reads Some CPUs rearrange reads so that they effectively come from shared storage in non-program order. This rearranging is never visible to single-threaded non-driver code, but can cause problems in multi-threaded code. Xbox 360 Cache misses can cause some reads to be delayed, which effectively causes reads to come from shared memory out of order, and the timing of these cache misses is fundamentally unpredictable. Prefetching and branch prediction can also cause data to come from shared memory out of order. These are just a few examples of how reads can be reordered. There may be other possibilities. This rearranging of reads is specifically allowed by the PowerPC memory model. x86 and x64 Even though x86 and x64 CPUs do reorder instructions, they generally do not reorder read operations relative to other reads. String operations (MOVS and STOS) and 16-byte SSE reads can be internally reordered, but otherwise, reads are not reordered relative to each other. Other Reordering Even though x86 and x64 CPUs do not reorder writes relative to other writes, or reorder reads relative to other reads, they can reorder reads relative to writes. Specifically, if a program writes to one location followed by reading from a different location, the read data may come from shared memory before the written data makes it there. This reordering can break some algorithms, such as Dekker’s mutual exclusion algorithms. In Dekker's algorithm, each thread sets a flag to indicate that it wants to enter the critical region, and then checks the other thread’s flag to see if the other thread is in the critical region or trying to enter it. The initial code follows. volatile bool f0 = false; volatile bool f1 = false; void P0Acquire() { // Indicate intention to enter critical region f0 = true; // Check for other thread in or entering critical region while (f1) { // Handle contention. } // critical region ... } void P1Acquire() { // Indicate intention to enter critical region f1 = true; // Check for other thread in or entering critical region while (f0) { // Handle contention. } // critical region ... } The problem is that the read of f1 in P0Acquire can read from shared storage before the write to f0 makes it to shared storage. Meanwhile, the read of f0 in P1Acquire can read from shared storage before the write to f1 makes it to shared storage. The net effect is that both threads set their flags to TRUE, and both threads see the other thread's flag as being FALSE, so they both enter the critical region. Therefore, while problems with reordering on x86- and x64-based systems are less common than on Xbox 360, they definitely can still happen. Dekker’s algorithm will not work without hardware memory barriers on any of these platforms. x86 and x64 CPUs will not reorder a write ahead of a previous read. x86 and x64 CPUs only reorder reads ahead of previous writes if they target different locations. PowerPC CPUs can reorder reads ahead of writes, and can reorder writes ahead of reads, as long as they are to different addresses. Reordering Summary The Xbox 360 CPU reorders memory operations much more aggressively than do x86 and x64 CPUs, as shown in the following table. For more details, consult the processor documentation. Read-Acquire and Write-Release Barriers The main constructs used to prevent reordering of reads and writes are called read-acquire and write-release barriers. A read-acquire is a read of a flag or other variable to gain ownership of a resource, coupled with a barrier against reordering. Similarly, a write-release is a write of a flag or other variable to give away ownership of a resource, coupled with a barrier against reordering. The formal definitions, courtesy of Herb Sutter, are: - A read-acquire executes before all reads and writes by the same thread that follow it in program order. - A write-release executes after all reads and writes by the same thread that precede it in program order. When your code acquires ownership of some memory, either by acquiring a lock or by pulling an item off of a shared linked list (without a lock), there is always a read involved—testing a flag or pointer to see if ownership of the memory has been acquired. This read may be part of an InterlockedXxx operation, in which case it involves both a read and a write, but it is the read that indicates whether ownership has been gained. After ownership of the memory is acquired, values are typically read from or written to that memory, and it is very important that these reads and writes execute after acquiring ownership. A read-acquire barrier guarantees this. When ownership of some memory is released, either by releasing a lock or by pushing an item on to a shared linked list, there is always a write involved which notifies other threads that the memory is now available to them. While your code had ownership of the memory, it probably read from or wrote to it, and it is very important that these reads and writes execute before releasing ownership. A write-release barrier guarantees this. It is simplest to think of read-acquire and write-release barriers as single operations. However, they sometimes have to be constructed from two parts: a read or write and a barrier that does not allow reads or writes to move across it. In this case, the placement of the barrier is critical. For a read-acquire barrier, the read of the flag comes first, then the barrier, and then the reads and writes of the shared data. For a write-release barrier the reads and writes of the shared data come first, then the barrier, and then the write of the flag. // Read that acquires the data. if( g_flag ) { // Guarantee that the read of the flag executes before // all reads and writes that follow in program order. BarrierOfSomeSort(); // Now we can read and write the shared data. int localVariable = sharedData.y; sharedData.x = 0; // Guarantee that the write to the flag executes after all // reads and writes that precede it in program order. BarrierOfSomeSort(); // Write that releases the data. g_flag = false; } The only difference between a read-acquire and a write-release is the location of the memory barrier. A read-acquire has the barrier after the lock operation, and a write-release has the barrier before. In both cases the barrier is in-between the references to the locked memory and the references to the lock. To understand why barriers are needed both when acquiring and when releasing data, it is best (and most accurate) to think of these barriers as guaranteeing synchronization with shared memory, not with other processors. If one processor uses a write-release to release a data structure to shared memory, and another processor uses a read-acquire to gain access to that data structure from shared memory, the code will then work properly. If either processor doesn't use the appropriate barrier, the data sharing may fail. Using the right barrier to prevent compiler and CPU reordering for your platform is critical. One of the advantages of using the synchronization primitives provided by the operating system is that all of them include the appropriate memory barriers. Preventing Compiler Reordering A compiler's job is to aggressively optimize your code in order to improve performance. This includes rearranging instructions wherever it is helpful and wherever it will not change behavior. Because the C++ Standard never mentions multithreading, and because the compiler doesn't know what code needs to be thread-safe, the compiler assumes that your code is single-threaded when deciding what rearrangements it can safely do. Therefore, you need to tell the compiler when it is not allowed to reorder reads and writes. With Visual C++ you can prevent compiler reordering by using the compiler intrinsic _ReadWriteBarrier. Where you insert _ReadWriteBarrier into your code, the compiler will not move reads and writes across it. #if _MSC_VER < 1400 // With VC++ 2003 you need to declare _ReadWriteBarrier extern "C" void _ReadWriteBarrier(); #else // With VC++ 2005 you can get the declaration from intrin.h #include <intrin.h> #endif // Tell the compiler that this is an intrinsic, not a function. #pragma intrinsic(_ReadWriteBarrier) // Create a new sprite by filling in a previously empty entry. g_sprites[nextSprite].x = x; g_sprites[nextSprite].y = y; // Write-release, barrier followed by write. // Guarantee that the compiler leaves the write to the flag // after all reads and writes that precede it in program order. _ReadWriteBarrier(); g_sprites[nextSprite].alive = true; In the following code, another thread reads from the sprite array: // Draw all sprites. for( int i = 0; i < numSprites; ++i ) { // Read-acquire, read followed by barrier. if( g_sprites[nextSprite].alive ) { // Guarantee that the compiler leaves the read of the flag // before all reads and writes that follow in program order. _ReadWriteBarrier(); DrawSprite( g_sprites[nextSprite].x, g_sprites[nextSprite].y ); } } It is important to understand that _ReadWriteBarrier does not insert any additional instructions, and it does not prevent the CPU from rearranging reads and writes—it only prevents the compiler from rearranging them. Thus, _ReadWriteBarrier is sufficient when you implement a write-release barrier on x86 and x64 (because x86 and x64 do not reorder writes, and a normal write is sufficient for releasing a lock), but in most other cases, it is also necessary to prevent the CPU from reordering reads and writes. You can also use _ReadWriteBarrier when you write to non-cacheable write-combined memory to prevent reordering of writes. In this case _ReadWriteBarrier helps to improve performance, by guaranteeing that the writes happen in the processor's preferred linear order. It is also possible to use the _ReadBarrier and _WriteBarrier intrinsics for more precise control of compiler reordering. The compiler will not move reads across a _ReadBarrier, and it will not move writes across a _WriteBarrier. Preventing CPU Reordering CPU reordering is more subtle than compiler reordering. You can't ever see it happen directly, you just see inexplicable bugs. In order to prevent CPU reordering of reads and writes you need to use memory barrier instructions, on some processors. The all-purpose name for a memory barrier instruction, on Xbox 360 and on Windows, is MemoryBarrier. This macro is implemented appropriately for each platform. On Xbox 360, MemoryBarrier is defined as lwsync (lightweight sync), also available through the __lwsync intrinsic, which is defined in ppcintrinsics.h. __lwsync also serves as a compiler memory barrier, preventing rearranging of reads and writes by the compiler. The lwsync instruction is a memory barrier on Xbox 360 that synchronizes one processor core with the L2 cache. It guarantees that all writes before lwsync make it to the L2 cache before any writes that follow. It also guarantees that any reads that follow lwsync don't get older data from L2 than previous reads. The one type of reordering that it does not prevent is a read moving ahead of a write to a different address. Thus, lwsync enforces memory ordering that matches the default memory ordering on x86 and x64 processors. To get full memory ordering requires the more expensive sync instruction (also known as heavyweight sync), but in most cases, this is not required. The memory reordering options on Xbox 360 are shown in the following table. PowerPC also has the synchronization instructions isync and eieio (which is used to control reordering to caching-inhibited memory). These synchronization instructions should not be needed for normal synchronization purposes. On Windows, MemoryBarrier is defined in Winnt.h and gives you a different memory barrier instruction depending on whether you are compiling for x86 or x64. The memory barrier instruction serves as a full barrier, preventing all reordering of reads and writes across the barrier. Thus, MemoryBarrier on Windows gives a stronger reordering guarantee than it does on Xbox 360. On Xbox 360, and on many other CPUs, there is one additional way that read-reordering by the CPU can be prevented. If you read a pointer and then use that pointer to load other data, the CPU guarantees that the reads off of the pointer are not older than the read of the pointer. If your lock flag is a pointer and if all reads of shared data are off of the pointer, the MemoryBarrier can be omitted, for a modest performance savings. Data* localPointer = g_sharedPointer; if( localPointer ) { // No import barrier is needed--all reads off of localPointer // are guaranteed to not be reordered past the read of // localPointer. int localVariable = localPointer->y; // A memory barrier is needed to stop the read of g_global // from being speculatively moved ahead of the read of // g_sharedPointer. int localVariable2 = g_global; } The MemoryBarrier instruction only prevents reordering of reads and writes to cacheable memory. If you allocate memory as PAGE_NOCACHE or PAGE_WRITECOMBINE, a common technique for device driver authors and for game developers on Xbox 360, MemoryBarrier has no effect on accesses to this memory. Most developers don't need synchronization of non-cacheable memory. That is beyond the scope of this article. Interlocked Functions and CPU Reordering Sometimes the read or write that acquires or releases a resource is done using one of the InterlockedXxx functions. On Windows, this simplifies things; because on Windows, the InterlockedXxx functions are all full-memory barriers. They effectively have a CPU memory barrier both before and after them, which means that they are a full read-acquire or write-release barrier all by themselves. On Xbox 360, the InterlockedXxx functions do not contain CPU memory barriers. They prevent compiler reordering of reads and writes but not CPU reordering. Therefore, in most cases when using InterlockedXxx functions on Xbox 360, you should precede or follow them with an __lwsync, to make them a read-acquire or write-release barrier. For convenience and for easier readability, there are Acquire and Release versions of many of the InterlockedXxx functions. These come with a built-in memory barrier. For instance, InterlockedIncrementAcquire does an interlocked increment followed by an __lwsync memory barrier to give the full read-acquire functionality. It is recommended that you use the Acquire and Release versions of the InterlockedXxx functions (most of which are available on Windows as well, with no performance penalty) to make your intent more obvious and to make it easier to get the memory barrier instructions in the correct place. Any use of InterlockedXxx on Xbox 360 without a memory barrier should be examined very carefully, because it is often a bug. This sample demonstrates how one thread can pass tasks or other data to another thread using the Acquire and Release versions of the InterlockedXxxSList functions. The InterlockedXxxSList functions are a family of functions for maintaining a shared singly linked list without a lock. Note that Acquire and Release variants of these functions are not available on Windows, but the regular versions of these functions are a full memory barrier on Windows. // Declarations for the Task class go here. // Add a new task to the list using lockless programming. void AddTask( DWORD ID, DWORD data ) { Task* newItem = new Task( ID, data ); InterlockedPushEntrySListRelease( g_taskList, newItem ); } // Remove a task from the list, using lockless programming. // This will return NULL if there are no items in the list. Task* GetTask() { Task* result = (Task*) InterlockedPopEntrySListAcquire( g_taskList ); return result; } Volatile Variables and Reordering The C++ Standard says that reads of volatile variables cannot be cached, volatile writes cannot be delayed, and volatile reads and writes cannot be moved past each other. This is sufficient for communicating with hardware devices, which is the purpose of the volatile keyword in the C++ Standard. However, the guarantees of the standard are not sufficient for using volatile for multi-threading. The C++ Standard does not stop the compiler from reordering non-volatile reads and writes relative to volatile reads and writes, and it says nothing about preventing CPU reordering. Visual C++ 2005 goes beyond standard C++ to define multi-threading-friendly semantics for volatile variable access. Starting with Visual C++ 2005, reads from volatile variables are defined to have read-acquire semantics, and writes to volatile variables are defined to have write-release semantics. This means that the compiler will not rearrange any reads and writes past them, and on Windows it will ensure that the CPU does not do so either. It is important to understand that these new guarantees only apply to Visual C++ 2005 and future versions of Visual C++. Compilers from other vendors will generally implement different semantics, without the extra guarantees of Visual C++ 2005. Also, on Xbox 360, the compiler does not insert any instructions to prevent the CPU from reordering reads and writes. Example of a Lock-Free Data Pipe A pipe is a construct that lets one or more threads write data that is then read by other threads. A lockless version of a pipe can be an elegant and efficient way to pass work from thread to thread. The DirectX SDK supplies LockFreePipe, a single-reader, single-writer lockless pipe that is available in DXUTLockFreePipe.h. The same LockFreePipe is available in the Xbox 360 SDK in AtgLockFreePipe.h. LockFreePipe can be used when two threads have a producer/consumer relationship. The producer thread can write data to the pipe for the consumer thread to process at a later date, without ever blocking. If the pipe fills up, writes fail, and the producer thread will have to try again later, but this would only happen if the producer thread is ahead. If the pipe empties, reads fail, and the consumer thread will have to try again later, but this would only happen if there is no work for the consumer thread to do. If the two threads are well-balanced, and the pipe is big enough, the pipe lets them smoothly pass data along with no delays or blocks. Xbox 360 Performance The performance of synchronization instructions and functions on Xbox 360 will vary depending on what other code is running. Acquiring locks will take much longer if another thread currently owns the lock. InterlockedIncrement and critical section operations will take much longer if other threads are writing to the same cache line. The contents of the store queues can also affect performance. Therefore, all of these numbers are just approximations, generated from very simple tests: - lwsync was measured as taking 33-48 cycles. - InterlockedIncrement was measured as taking 225-260 cycles. - Acquiring or releasing a critical section was measured as taking about 345 cycles. - Acquiring or releasing a mutex was measured as taking about 2350 cycles. Windows Performance The performance of synchronization instructions and functions on Windows vary widely depending on the processor type and configuration, and on what other code is running. Multi-core and multi-socket systems often take longer to execute synchronizing instructions, and acquiring locks take much longer if another thread currently owns the lock. However, even some measurements generated from very simple tests are helpful: - MemoryBarrier was measured as taking 20-90 cycles. - InterlockedIncrement was measured as taking 36-90 cycles. - Acquiring or releasing a critical section was measured as taking 40-100 cycles. - Acquiring or releasing a mutex was measured as taking about 750-2500 cycles. These tests were done on Windows XP on a range of different processors. The short times were on a single-processor machine, and the longer times were on a multi-processor machine. While acquiring and releasing locks is more expensive than using lockless programming, it is even better to share data less frequently, thus avoiding the cost altogether. Performance Thoughts Acquiring or releasing a critical section consists of a memory barrier, an InterlockedXxx operation, and some extra checking to handle recursion and to fall back to a mutex, if necessary. You should be wary of implementing your own critical section, because spinning in a loop waiting for a lock to be free, without falling back to a mutex, can waste considerable performance. For critical sections that are heavily contended but not held for long, you should consider using InitializeCriticalSectionAndSpinCount so that the operating system will spin for a while waiting for the critical section to be available rather than immediately deferring to a mutex if the critical section is owned when you try to acquire it. In order to identify critical sections that can benefit from a spin count, it is necessary to measure the length of the typical wait for a particular lock. If a shared heap is used for memory allocations—the default behavior—every memory allocation and free involves acquiring a lock. As the number of threads and the number of allocations increases, performance levels off, and eventually starts to decrease. Using per-thread heaps, or reducing the number of allocations, can avoid this locking bottleneck. If one thread is generating data and another thread is consuming data, they may end up sharing data frequently. This can happen if one thread is loading resources and another thread is rendering the scene. If the rendering thread references the shared data on every draw call, the locking overhead will be high. Much better performance can be realized if each thread has private data structures which are then synchronized once per frame or less. Lockless algorithms are not guaranteed to be faster than algorithms that use locks. You should check to see if locks are actually causing you problems before trying to avoid them, and you should measure to see if your lockless code actually improves performance. Platform Differences Summary - InterlockedXxx functions prevent CPU read/write reordering on Windows, but not on Xbox 360. - Reading and writing of volatile variables using Visual Studio C++ 2005 prevents CPU read/write reordering on Windows, but on Xbox 360, it only prevents compiler read/write reordering. - Writes are reordered on Xbox 360, but not on x86 or x64. - Reads are reordered on Xbox 360, but on x86 or x64 they are only reordered relative to writes, and only if the reads and writes target different locations. Recommendations - Use locks when possible because they are easier to use correctly. - Avoid locking too frequently, so that locking costs do not become significant. - Avoid holding locks for too long, in order to avoid long stalls. - Use lockless programming when appropriate, but be sure that the gains justify the complexity. - Use lockless programming or spin locks in situations where other locks are prohibited, such as when sharing data between deferred procedure calls and normal code. - Only use standard lockless programming algorithms that have been proven to be correct. - When doing lockless programming, be sure to use volatile flag variables and memory barrier instructions as needed. - When using InterlockedXxx on Xbox 360, use the Acquire and Release variants. References - MSDN Library. "volatile (C++)." C++ Language Reference. - Vance Morrison. "Understand the Impact of Low-Lock Techniques in Multithreaded Apps." MSDN Magazine, October 2005. - Lyons, Michael. "PowerPC Storage Model and AIX Programming." IBM developerWorks, 16 Nov 2005. - McKenney, Paul E. "Memory Ordering in Modern Microprocessors, Part II." Linux Journal, September 2005. [This article has some x86 details.] - Intel Corporation. "Intel® 64 Architecture Memory Ordering." August 2007. [Applies to both IA-32 and Intel 64 processors.] - Advanced Micro Devices. "Multiprocessor Memory Access Ordering," section 7.2, AMD64 Architecture Programmer's Manual Volume 2: System Programming." September 2007. - Niebler, Eric. "Trip Report: Ad-Hoc Meeting on Threads in C++." The C++ Source, 17 Oct 2006. - Hart, Thomas E. 2006. "Making Lockless Synchronization Fast: Performance Implications of Memory Reclamation." Proceedings of the 2006 International Parallel and Distributed Processing Symposium (IPDPS 2006), Rhodes Island, Greece, April 2006. Build date: 11/16/2013
https://msdn.microsoft.com/en-us/library/ee418650(d=printer,v=vs.85).aspx
CC-MAIN-2015-18
refinedweb
5,532
52.29
. What is OpenCV? OpenCV(Open Source Computer Vision) is an open source computer vision algorithms library. It is written in C/C++, and is designed to take advantage of multiple cores. It provides interfaces for the C++, C, Python and Java programming languages and supports all the major operating system platforms including Windows, Linux, Mac OS, iOS, and Android. Github Repository The code for today’s demo application is available on github: day12-face-detection. Getting Started with OpenCV In order to get started with OpenCV, the first step is to download the latest OpenCV package for your operating system from the official website. In this blog, I will be using the 2.4.7 version. After downloading the package, extract the package using tar command. $ tar xvf opencv-2.4.7.tar.gz Change to the directory to opencv-2.4.7 $ cd opencv-2.4.7 Build OpenCV jar It took me lot of time to understand how to get the OpenCV jar file. The Java tutorial in the documentation assumes the OpenCV jar file is in the build folder. The tutorial works for windows users as the OpenCV package for windows includes the jar file. This is not true for Linux and Mac OS users. To build the OpenCV jar, executes the command shown below. $ cd opencv-2.4.7 $ mkdir build $ cd build/ $ cmake -G "Unix Makefiles" -D CMAKE_CXX_COMPILER=/usr/bin/g++ -D CMAKE_C_COMPILER=/usr/bin/gcc -D WITH_CUDA=ON .. $make -j4 $ make install The above commands will create the opencv-247.jar file in the opencv-2.4.7/build/bin directory. This is the Java binding to the native OpenCV installation. Download Eclipse If you do not have Eclipse installed on your machine, command shown below. $ tar -xzvf eclipse-jee-kepler-R-*.tar.gz On windows you can extract the zip file using winzip or 7-zip or any other software. After you have extracted Eclipse, there will be a folder named eclipse in the directory where you extracted the zip file. You can optionally create a shortcut of the executable file. Add the User Library Open the Eclipse IDE and then navigate to the project workspace. Go to Windows > Preferences > Java > Build Path > User Libraries, and select to add a new library. Give the user library a name like OpenCV-2.4.7 and then press OK. Click on Add External Jars, and add the opencv-247.jar file. Select the Native library location and then press Edit. Click on External Folder Give the location of lib directory under the opencv-2.4.7/build/lib folder. Finally, press OK. Now we have added OpenCV as the user library. Create New Java Project Create a new Java project by going to File > New > Other > Java Project. After the project is created, right click on the project and configure the build path. Go to the Libraries tab, and click on Add Library. Select the User Library Choose the OpenCV-2.4.7 user library we added in last step and click Finish. Finally, the Java project will include the OpenCV-2.4.7 user library. Write FaceDetector Create a new class in the java project we created in the last step and add the following code. package com.shekhar.facedetection;; public class FaceDetector { public static void main(String[] args) { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); System.out.println("\nRunning FaceDetector"); CascadeClassifier faceDetector = new CascadeClassifier(FaceDetector.class.getResource("haarcascade_frontalface_alt.xml").getPath()); Mat image = Highgui .imread(FaceDetector.class.getResource("shekhar.JPG").getPath()); MatOfRect faceDetections = new MatOfRect(); faceDetector.detectMultiScale(image, faceDetections); System.out.println(String.format("Detected %s faces", faceDetections.toArray().length)); for (Rect rect : faceDetections.toArray()) { Core.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0)); } String filename = "ouput.png"; System.out.println(String.format("Writing %s", filename)); Highgui.imwrite(filename, image); } } The code shown above does the following : - It loads the native OpenCV library so that we can use it using Java API. - We create an instance of CascadeClassifier passing it the name of the file from which the classifier is loaded. Next we convert the image to a format which the Java API will accept using the Highui class. Mat is the OpenCV C++ n-dimensional dense array class. Then we call the detectMultiScale method on the classifier passing it the image and MatOfRect object. After processing, the MatOfRect will have face detections. We iterate over all the face detections and mark the image with rectangles. Finally, we write the image to the output.png file. The output of the program is shown below. This is my pic before and after face detection. That’s it for today. Keep giving feedback. Next Steps - Sign up for OpenShift Online and try this out yourself - Promote and show off your awesome app in the OpenShift Application Gallery today. Automatic Updates Stay informed and learn more about OpenShift by receiving email updates.
https://blog.openshift.com/day-12-opencv-face-detection-for-java-developers/
CC-MAIN-2018-22
refinedweb
827
60.61
Building Modern Applications with Django, Vue.js and Auth0: Part 2 In this tutorial you will learn - What is Webpack and why you should use it? - The Webpack template used by the Vue CLI to generate Vue applications based on Webpack - how to integrate Vue with Django so you can serve the front end application using Django instead of having complete separate front end and back end apps - how to fix Hot Code Reloading when using Django to serve the Vue application - how to update the Callback URL for Auth0 authentication Introduction to Webpack In this section we you briefly get introduced to Webpack (and why you should use Webpack?) Essentially webpack is a static module bundler for modern JavaScript applications which becomes a fundamental tool with the rise of modern JavaScript front end frameworks such as Angular, React and Vue. It also can be easily configured to bundle other assets such as HTML, CSS and images via loaders. It will help you reduce the number of requests and round trips to your web servers, use modern standards such as ES6 and allows you to use npm modules in your front-end apps. Webpack basically works by processing your application then builds a dependency tree which contains all modules used by the application and finally bundles all those modules into one or multiple bundles (depending on your configuration) Webpack offers a plethora of features to bundle static assets (JavaScript, CSS, images etc.) for front-end web developers such as: - the splitting of dependencies into chunks - the support of a plethora of plugins - it's highly configurable - it's heavily customizable - it's very flexible thanks to loaders - you can interface with Webpack either from its CLI or API. Webpack has four core concepts entry, output, loaders and plugins The entry property allows you to define the entry point(s) for your Webpack configuration. It can either be a single string value, an array of values or an object. The output property allows you to define the information Webpack needs to write the bundled file(s) to the drive such as the filename and the path (minimum two properties) Loaders are powerful feature of Webpack as they are used to teach Webpack how to transform assets from other languages than JavaScript such as TypeScript, CSS, Sass etc. Plugins are used to extend Webpack of anything beyond what can be achieved using loaders. Webpack is a powerful tool that, once mastered, can help you to improve your front-end development workflow. Vue Webpack Configuration In this section we will briefly talk about the Webpack configuration for Vue Vue uses its own file format with the extension .vue for encapsulating the HTML,CSS and JavaScript code (using <template>, <style>, and <script> tags respectively) to construct components. You can also add your custom blocks. Vue supports the custom file format by using its own loader. vue-loader parses the .vue files, extract blocks inside the top-level tags ( <template>, <style>, and <script> and possibly custom tags) then convert them to CommonJS modules. You can also use languages that need pre-processing such as Sass or template languages that compile to HTML such as Jade by simply adding the lang attribue to a language block (for example <style lang="sass"></style>) The Webpack boilerplate (that you have used to scaffold the Vue project using the Vue CLI vue init webpack vueapp) can be used for large projects. It's based on vue-loader and assumes you are familiar with Webpack. This is the structure of your Vue application based on Webpack There are many folders and files in the project such as: package.json: this is the npm file that holds meta information about the package (such as the name, description, author and license etc.). This file also holds the name and version of every dependency that the package/project uses and custom build commands. index.html: this is the main HTML file for the Vue single page application. This file is generated in the dist folder both in development and production builds and links to all generated assets will be injected in this file (you can use it to run your Vue application but since you are going to build your own template for Django that will dynamically injects the static assets using Django Webpack loader you don't actually need this file) src: this one is obviously the source folder of your Vue application. Most development will take place inside this folder because it's where the actual application code lives. build: this folder contains the Webpack configuration files for development and production i.e webpack.dev.conf.js and webpack.prod.conf.js. This is where you are going to work in order to fix Hot Code Reloading and also to instruct Webpack to generate webpack-stats.json file using a plugin. build/config: this is the configuration folder that holds configuration settings for development and production. You are not going to touch this folder in this part but you'll be using it in the next part to set some variables required for production such as assetsPublicPath static: this the static folder, don't be confused by its name! It's only used to put static assets that don't need to be processed by Webpack. The files in this folder will be copied as-is where the other assets are generated. The Application Demo In the previous part you have started building the Django and Vue demo. You have generated both the front-end application with the Vue CLI and the Django project. You also added JWT authentication via Auth0 then setup the front-end to connect to the back-end and made a basic call that's secured with Auth0. In this second part you will continue building the demo application by integrating both the front-end application and the back-end application. Basically you want to make Django serve the Vue application so you'll need to make Django able to know about the static assets Webpack generates and also update Webpack configuration to fix HCR (Hot Code Reloading) of the Webpack Dev Server. Integrating Vue and Django In this section I'll show you step by step how to integrate Vue and Django First head over to your terminal or command prompt then you'll need to clone the project we have previously built git clone You can also skip this step and just continue with the project you have built yourself in the previous part. Please note that you need to have your previously created virtual environment activated before you install Django packages. You can activate a virtual environment by issuing the following command source env/bin/activate Where env is the name of the virtual environment. I assume that you have previously followed the steps in the part 1 to install the Django packages. if this is not the case use requirements.txt to install the requirements cd djangovue pip install -r requirements.txt You also need to install the Vue app dependencies, navigate inside the frontend folder and execute: npm install Next run the following command to install the Webpack loader package for integrating Webpack with Django pip install django-webpack-loader Then go to your project settings.py file and add webpack_loader to INSTALLED_APPS : INSTALLED_APPS = [ #... 'webpack_loader', 'catalog', #... ] Next you need to add the following object to settings.py to configure the Webpack loader WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': '', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), } } This tells Webpack loader to look for webpack-stats.json in the root folder of the project. This file holds information about the static assets that Webpack has generated (you will see next how to generate this file). Serving the Index Template Now you need to create and serve an index.html file, where you can mount the Vue application, using a Django view First create the index.html template in catalog/templates/index.html then add the following content. { % load render_bundle from webpack_loader % } <html lang="en"> <head> <meta charset="UTF-8"> <title>Django - Auth0 - Vue</title> </head> <body> <div id="app"> </div> { % render_bundle 'app' % } </body> </html> The page contains a <div> with the id app where you can mount the Vue application. The render_bundle tag (with app as an argument) is used to include the app bundle files. After creating the template, you can next use TemplateView to serve it. Go to your project urls.py` file then add the following: from django.contrib import admin from django.urls import path from django.views.generic import TemplateView from django.conf.urls import url from catalog import views urlpatterns = [ url(r'^api/public/', views.public), url(r'^api/private/', views.private), url(r'^$', TemplateView.as_view(template_name='index.html'), name='index'), path('admin/', admin.site.urls), ] Now reload your Django application, you will get the Yellow page with an error with Django complaining about not finding the webpack-stats.json file needed by the Webpack loader. Error reading /xxxx/xxxx/xxxx/django-auth0-vue-part-2/webpack-stats.json. Are you sure webpack has generated the file and the path is correct? This is a screen shot of the error that you will get To get rid of this error you need to generate the webpack-stats.json file using the Webpack plugin webpack-bundle-tracker so first install it from npm using (make sure you are inside the Vue application): cd frontend npm install webpack-bundle-tracker --save In frontend/build/webpack.dev.conf.js import webpack-bundle-tracker and include BundleTracker in Webpack plugins const BundleTracker = require('webpack-bundle-tracker') /*...*/ plugins: [ /*...*/ new BundleTracker({filename: '../webpack-stats.json'}) ] This tells webpack-bundle-tracker to generate the stats file in the root folder of your project. If you re-run you Webpack dev server, you'll have the webpack-stats.json file generated in root of your project If you visit you Django app now you'll get this error in the console <script>with source “”. You can fix this error by going to frontend/config/index.js next locate the assetsPublicPath setting and change its value from / to /*...*/ module.exports = { dev: { // Paths assetsSubDirectory: 'static', assetsPublicPath: '', proxyTable: {}, /*...*/ Next rerun your frontend app using npm run dev You should now be able to see your main Vue page by navigating with your browser to Fixing Hot Code Reloading This is what the docs says about Hot Code Reload: "Hot Reload" is not simply reloading the page when you edit a file. With hot reload enabled, when you edit a *.vue file, all instances of that component will be swapped in without reloading the page. It even preserves the current state of your app and these swapped components! This dramatically improves the development experience when you are tweaking the templates or styling of your components. Now in frontend/build/webpack.dev.conf.js you need to configure the Webpack Dev server to accept requests from other origins such as since the Django server will send XHR requests to for getting the source file changes. Add a headers object in devServer. javascript devServer: { headers: { 'Access-Control-Allow-Origin': '\*' }, }, This will fix Hot Code Reloading when using Django server to serve Vue files. To test that, just change something in your Vue application and you'll be able to see your web page hot reloaded to see the changes without having to manually reload it. That's all you need to do. Now re-run the Vue dev server then navigate with your browser to. You'll be now able to interact with your application served from the Django dev server. Updating Auth0 Callback URL Previously you have used the Auth0 authentication from page served from the Vue server. So if you click the Login In button you'll will be redirected to this Callback URL mismatch page Because now you are using the Django server to serve that page so you'll need to update (or add the Auth0 callback URL ) to to make the authentication works You also need to set this address in your frontend/src/auth/AuthService.js file as redirectUri auth0 = new auth0.WebAuth({ domain: '<YOUR_DOMAIN>', clientID: '<YOUR_CLIENT_ID>', redirectUri: '', audience: '<YOUR_AUDIENCE>, responseType: 'token id_token', scope: 'openid profile' }); Now you'll be able to authenticate using Auth0 to see this page and make a private API call Conclusion In this second part you have integrated your Vue application with Django so you can now use your web application by navigating with your browser to the address of Django development server (Django is now serving the Vue application instead of just exposing API endpoints). In development you still have to run and use the Vue/Webpack dev server so you have seen how to fix Hot Code Reloading so you can still have your web page hot reloaded even if you are using the Django server address. In the next part you will further continue developing the demo application by creating Vue views and wire them using the Vue Router for the front end. For the back end you will see how to create API endpoints using Django REST framework and see how you can prepare this setup (Django and Vue) for production.
https://www.techiediaries.com/django-vuejs-auth0/
CC-MAIN-2021-39
refinedweb
2,202
51.18
Handling of international domain names. More... #include "config.h" #include <stdint.h> #include <stdio.h> #include "mutt/lib.h" #include "config/lib.h" #include "core/lib.h" #include "idna2.h" Go to the source code of this file. Handling of international domain names. idna.c. Convert an email's domain from Punycode. If $idn_decode is set, then the domain will be converted from Punycode. For example, "xn--ls8h.la" becomes the emoji domain: ":poop:.la" Then the user and domain are changed from 'utf-8' to the encoding in $charset. If the flag MI_MAY_BE_IRREVERSIBLE is NOT given, then the results will be checked to make sure that the transformation is "undo-able". Definition at line 144 of file idna.c. Convert an email's domain to Punycode. The user and domain are assumed to be encoded according to $charset. They are converted to 'utf-8'. If $idn_encode is set, then the domain will be converted to Punycode. For example, the emoji domain: ":poop:.la" becomes "xn--ls8h.la" Definition at line 264 of file idna.c. Create an IDN version string. Definition at line 314 of file idna.c.
https://neomutt.org/code/idna_8c.html
CC-MAIN-2021-49
refinedweb
189
64.78
Due Date: Sept 9, 2008 This project tests your basic programming ability, your ability to code in Java (or how fast you can learn Java), your knowledge of simple data structures and algorithms, and how well you can read and follow instructions. This project is a typical undergraduate project, but with a shorter deadline. If this project is not easy for you, this course may overwhelm you. This project is a good way for us to get to know each other. :) Your goal is to produce two simple Java implementations of a Dictionary interface, LinkedListDictionary and HashDictionary, that map a String key to an Object value. You should test your your code well including all boundary conditions as you will not see the test harness I will use to check out your project. You must implement this project successfully without knowing precisely how I will test it. There are two reasons: This project is primarily meant to test your basic Java skills: If you do not know how to implement a hash table or linked list, you must learn this outside of class; either by reading or talking to friends. IMPORTANT: You are to actually implement a hashtable and linked list, not simply wrap Java's existing java.util.Hashtable and java.util.LinkedList classes (or HashMap, etc...). In fact, you must not reference these classes at all. You are to build at least two Java classes called LinkedListDictionary and HashDictionary, which must implement the Dictionary interface: package dict; public interface Dictionary { /** Add an object to the dictionary. Do not allow null keys or values. Do nothing upon invalid key or value. put() may be called with the same key multiple times; you do not have to collate these values in a list and associate with a single key. Just keep adding key/value pairs to the appropriate buckets. Add objects to any linked lists at the end of the list to preserve order of addition. */ public void put(String key, Object value); /** Delete the first object you find associated with key from * dictionary and return it. Return null if not found. */ public Object remove(String key); /** Return the first value object you find associated with key from * dictionary; return null if not found. */ public Object get(String key); /** Return a string of the key/value pairs in the dictionary. The string should look EXACTLY like this for both implementations: [key1:value1, ..., keyN:valueN] If there are multiple values with the same key, list the key multiple times. The element separator is ", " (comma space) and there NO newline character as I will print that myself during testing. I will be automatically testing your projects! */ public String toString(); } Please include this interface dict.Dictionary in the jar file you submit. You will create a jar file called dict.jar containing source and *.class files and place in your lib directory: To jar your stuff up, you will "cd" to the directory containing the dict subdirectory and create the jar in the lib dir: cd ~/cs601/dictionary/trunk/src jar cvf ~/cs601/dictionary/trunk/lib/dict.jar dict You will see something like this: adding: META-INF/ (in=0) (out=0) (stored 0%) adding: META-INF/MANIFEST.MF (in=56) (out=56) (stored 0%) adding: dict/ (in=0) (out=0) (stored 0%) adding: dict/Dictionary.class (in=309) (out=189) (deflated 38%) adding: dict/Dictionary.java (in=418) (out=200) (deflated 52%) 40%) adding: dict/HashDictionary.class (in=2820) (out=1470) (deflated 47%) adding: dict/HashDictionary.java (in=2434) (out=722) (deflated 70%) adding: dict/LinkedListDictionary.class (in=1778) (out=954) (deflated 46%) adding: dict/LinkedListDictionary.java (in=1362) (out=490) (deflated 64%) adding: dict/timestamp.inf (in=394) (out=141) (deflated 64%) etc... Total: ------ (in = 29765) (out = 10864) (deflated 63%) The jar will contain .java and .class files as well as any other file you have in there; be careful not to store your personal diary in there <wink>. You should test your project by running as I will run it per the Grading section below. Please bring a print out of each java file in your project including your test harness. I will run your program by pulling your dict.jar file from the repository and running like this: java -cp .:dict.jar TerenceTestDictionary It will launch my TerenceTestDictionary.main() method, which will dynamically load your classes (dict.HashDictionary, dict.LinkedListDictionary) from your submitted jar file. Note that you should include interface dict.Dictionary in the jar. My test harness exercising your implementations of the dict.Dictionary interface will be of the form: import dict.*; public class MyTestDictionary { public static void main(String[] args) { HashDictionary hd = new HashDictionary(); LinkedListDictionary lld = new LinkedListDictionary(); // Dictionary d = hd; // test hash dictionary Dictionary d = lld; // test linked list dictionary d.put("Terence", "parrt@cs.usfca.edu"); System.out.println(d);// calls toString() ... } } You may discuss this project in its generality with anybody you want and may look at any code on the internet except for a classmate's code. You should physically code this project completely yourself but can use all the help you find other than cutting-n-pasting or looking at code from a classmate or other Human being. Your grade is a floating point number from 0..10.
http://www.cs.usfca.edu/~parrt/course/601/projects-Fall-2008/dictionary.html
CC-MAIN-2018-05
refinedweb
877
66.03
I don't know enough java, so I am probably doing this wrong. What I would like to have, is a String that has the second octet of an IP address, weather it is an 8 or 58 or 103, just as an example. import java.net.*; import java.io.*; import javax.swing.JOptionPane; public class findip { public static void main(String [] args) throws IOException{ String myip,myip2; InetAddress thisIp =InetAddress.getLocalHost(); //System.out.println("IP of my system is := "+thisIp.getHostAddress()); myip=thisIp.getHostAddress(); myip2=myip.charAt(3)+myip.charAt(4); //need to just show or have 2nd octet JOptionPane.showMessageDialog(null,"IP:__"+myip+"\n\nSchool Num:__"+myip2); }}
http://www.javaprogrammingforums.com/whats-wrong-my-code/16692-wanting-2nd-octet-ip-address.html
CC-MAIN-2015-35
refinedweb
111
54.83
I want build an offline application using plotly for displaying graphs . I am using python(flask) at the back end and HTML(javascript) for the front end . Currently I am able to plot the graph by sending the graph data as JSON object to front end and building the graph using plotly.js at the front end itself . But what I actually want is to build the graph at the server(backend ie python) side itself and then display the data in HTML . I have gone through the plotly documentation that builds the graph in python , but I dont know how to send the build graph to front end for display :( Can someone help me on that ? PS : I want to build an offline application Updated Code $(window).resize(function() { var divheight = $("#section").height(); var divwidth = $("#section").width(); var update = { width:divwidth, // or any new width height:divheight // " " }; var arr = $('#section > div').get(); alert(arr[1]); Plotly.relayout(arr[0], update); }).resize(); }); My suggestion would be to use the plotly.offline module, which creates an offline version of a plot for you. The plotly API on their website is horrendous (we wouldn't actually want to know what arguments each function takes, would we??), so much better to turn to the source code on Github. If you have a look at the plotly source code, you can see that the offline.plot function takes a kwarg for output_type, which is either 'file' or 'div': So you could do: from plotly.offline import plot from plotly.graph_objs import Scatter my_plot_div = plot([Scatter(x=[1, 2, 3], y=[3, 1, 6])], output_type='div') This will give you the code (wrapped in <div> tags) to insert straight into your HTML. Maybe not the most efficient solution (as I'm pretty sure it embeds the relevant d3 code as well, which could just be cached for repeated requests), but it is self contained. To insert your div into your html code using Flask, there are a few things you have to do. In your html template file for your results page, create a placeholder for your plot code. Flask uses the Jinja template engine, so this would look like: <body> ....some html... {{ div_placeholder }} ...more html... </body> In your Flask views.py file, you need to render the template with the plot code inserted into the div_placeholder variable: from plotly.offline import plot from plotly.graph_objs import Scatter ...other imports.... @app.route('/results', methods=['GET', 'POST']) def results(): error = None if request.method == 'POST': my_plot_div = plot([Scatter(x=[1, 2, 3], y=[3, 1, 6])], output_type='div') return render_template('results.html', div_placeholder=Markup(my_plot_div) ) # If user tries to get to page directly, redirect to submission page elif request.method == "GET": return redirect(url_for('submission', error=error)) Obviously YMMV, but that should illustrate the basic principle. Note that you will probably be getting a user request using POST data that you will need to process to create the plotly graph.
https://codedump.io/share/PZgsJNjIbNom/1/plotting-graph-using-python-and-dispaying-it-using-html
CC-MAIN-2016-44
refinedweb
494
65.73
We all watch movies for entertainment, some of us never rate it, while some viewers always rate every movie they watch. This type of viewer helps in rating movies for people who go through the movie reviews before watching any movie to make sure they are about to watch a good movie. So, if you are new to data science and want to learn how to analyze movie ratings using the Python programming language, this article is for you. In this article, I will walk you through the task of Movie Rating Analysis using Python. Movie Rating Analysis using Python Analyzing the rating given by viewers of a movie helps many people decide whether or not to watch that movie. So, for the Movie Rating Analysis task, you first need to have a dataset that contains data about the ratings given by each viewer. For this task, I have collected a dataset from Kaggle that contains two files: - one file contains the data about the movie Id, title and the genre of the movie - and the other file contains the user id, movie id, ratings given by the user and the timestamp of the ratings You can download both these datasets from here. Now let’s get started with the task of movie rating analysis by importing the necessary Python libraries and the datasets: import numpy as np import pandas as pd movies = pd.read_csv("movies.dat", delimiter='::') print(movies.head()) In the above code, I have only imported the movies dataset that does not have any column names, so let’s define the column names: movies.columns = ["ID", "Title", "Genre"] print(movies.head()) ID Title Genre Now let’s import the ratings dataset: ratings = pd.read_csv("ratings.dat", delimiter='::') print(ratings.head()) 1 0114508 8 1381006850 The rating dataset also doesn’t have any column names, so let’s define the column names of this data also: ratings.columns = ["User", "ID", "Ratings", "Timestamp"] print(ratings.head()) User ID Ratings Timestamp Now I am going to merge these two datasets into one, these two datasets have a common column as ID, which contains movie ID, so we can use this column as the common column to merge the two datasets: data = pd.merge(movies, ratings, on=["ID", "ID"]) print(data.head()) ID Title ... Ratings Timestamp 0 10 La sortie des usines Lumière (1895) ... 10 1412878553 1 12 The Arrival of a Train (1896) ... 10 1439248579 2 25 The Oxford and Cambridge University Boat Race ... ... 8 1488189899 3 91 Le manoir du diable (1896) ... 6 1385233195 4 91 Le manoir du diable (1896) ... 5 1532347349 [5 rows x 6 columns] As it is a beginner level task, so I will first have a look at the distribution of the ratings of all the movies given by the viewers: ratings = data["Ratings"].value_counts() numbers = ratings.index quantity = ratings.values import plotly.express as px fig = px.pie(data, values=quantity, names=numbers) fig.show() So, according to the pie chart above, most movies are rated 8 by users. From the above figure, it can be said that most of the movies are rated positively. As 10 is the highest rating a viewer can give, let’s take a look at the top 10 movies that got 10 ratings by viewers: data2 = data.query("Ratings == 10") print(data2["Title"].value_counts().head(10)) Joker (2019) 1479 Interstellar (2014) 1382 1917 (2019) 819 Avengers: Endgame (2019) 808 The Shawshank Redemption (1994) 699 Gravity (2013) 653 The Wolf of Wall Street (2013) 581 Hacksaw Ridge (2016) 570 Avengers: Infinity War (2018) 534 La La Land (2016) 510 Name: Title, dtype: int64 So, according to this dataset, Joker (2019) got the highest number of 10 ratings from viewers. This is how you can analyze movie ratings using Python as a data science beginner. Summary So this is how you can do movie rating analysis by using the Python programming language as a data science beginner. Analyzing the ratings given by viewers of a movie helps many people decide whether or not to watch that movie. I hope you liked this article on Movie rating analysis using Python. Feel free to ask your valuable questions in the comments section below.
https://thecleverprogrammer.com/2021/09/22/movie-rating-analysis-using-python/
CC-MAIN-2021-43
refinedweb
702
71.24
Why does underscore for last output not work in worksheets uploaded from local SageMath to Cocalc? My commands are like this: vector([x1,y1,z1]) r1 = _ And I get this message: Error in lines 1-1 Traceback (most recent call last): File "/cocalc/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 995, in execute exec compile(block+'\n', '', 'single') in namespace, locals File "", line 1, in <module> NameError: name '_' is not defined However, copying and pasting commands into a new worksheet make that feature work again. Why? I have links to illustrate it, but my karma is insufficient to post them here. It seems now I can post links. Here's the uploaded worksheet:-... Here's the worksheet created from scratch:-...
https://ask.sagemath.org/question/38820/why-does-underscore-for-last-output-not-work-in-worksheets-uploaded-from-local-sagemath-to-cocalc/
CC-MAIN-2020-45
refinedweb
124
64.3
OpenStack Nova presents a metadata API to VMs similar to what is available on Amazon EC2. Neutron is involved in this process because the source IP address is not enough to uniquely identify the source of a metadata request since networks can have overlapping IP addresses. Neutron is responsible for intercepting metadata API requests and adding HTTP headers which uniquely identify the source of the request before forwarding it to the metadata API server. The purpose of this document is to propose a design for how to enable this functionality when OVN is used as the backend for OpenStack Neutron. The following blog post describes how VMs access the metadata API through Neutron today. In summary, we run a metadata proxy in either the router namespace or DHCP namespace. The DHCP namespace can be used when there’s no router connected to the network. The one downside to the DHCP namespace approach is that it requires pushing a static route to the VM through DHCP so that it knows to route metadata requests to the DHCP server IP address. For proper operation, Neutron and Nova must be configured to communicate together with a shared secret. Neutron uses this secret to sign the Instance-ID header of the metadata request to prevent spoofing. This secret is configured through metadata_proxy_shared_secret on both nova and neutron configuration files (optional). [0] The current metadata API approach does not translate directly to OVN. There are no Neutron agents in use with OVN. Further, OVN makes no use of its own network namespaces that we could take advantage of like the original implementation makes use of the router and dhcp namespaces. We must use a modified approach that fits the OVN model. This section details a proposed approach. The proposed approach would be similar to the isolated network case in the current ML2+OVS implementation. Therefore, we would be running a metadata proxy (haproxy) instance on every hypervisor for each network a VM on that host is connected to. The downside of this approach is that we’ll be running more metadata proxies than we’re doing now in case of routed networks (one per virtual router) but since haproxy is very lightweight and they will be idling most of the time, it shouldn’t be a big issue overall. However, the major benefit of this approach is that we don’t have to implement any scheduling logic to distribute metadata proxies across the nodes, nor any HA logic. This, however, can be evolved in the future as explained below in this document. Also, this approach relies on a new feature in OVN that we must implement first so that an OVN port can be present on every chassis (similar to localnet ports). This new type of logical port would be localport and we will never forward packets over a tunnel for these ports. We would only send packets to the local instance of a localport. Step 1 - Create a port for the metadata proxy When using the DHCP agent today, Neutron automatically creates a port for the DHCP agent to use. We could do the same thing for use with the metadata proxy (haproxy). We’ll create an OVN localport which will be present on every chassis and this port will have the same MAC/IP address on every host. Eventually, we can share the same neutron port for both DHCP and metadata. Step 2 - Routing metadata API requests to the correct Neutron port This works similarly to the current approach. We would program OVN to include a static route in DHCP responses that routes metadata API requests to the localport that is hosting the metadata API proxy. Also, in case DHCP isn’t enabled or the client ignores the route info, we will program a static route in the OVN logical router which will still get metadata requests directed to the right place. If the DHCP route does not work and the network is isolated, VMs won’t get metadata, but this already happens with the current implementation so this approach doesn’t introduce a regression. Step 3 - Management of the namespaces and haproxy instances We propose a new agent in networking-ovn called neutron-ovn-metadata-agent. We will run this agent on every hypervisor and it will be responsible for spawning the haproxy instances for managing the OVS interfaces, network namespaces and haproxy processes used to proxy metadata API requests. Step 4 - Metadata API request processing Similar to the existing neutron metadata agent, neutron-ovn-metadata-agent must act as an intermediary between haproxy and the Nova metadata API service. neutron-ovn-metadata-agent is the process that will have access to the host networks where the Nova metadata API exists. Each haproxy will be in a network namespace not able to reach the appropriate host network. Haproxy will add the necessary headers to the metadata API request and then forward it to neutron-ovn-metadata-agent over a UNIX domain socket, which matches the behavior of the current metadata agent. In neutron-ovn-metadata-agent. Port_Bindingtable of the OVN Southbound database and look for all rows with the chassiscolumn set to the host the agent is running on. For all those entries, make sure a metadata proxy instance is spawned for every datapath(Neutron network) those ports are attached to. The agent will keep record of the list of networks it currently has proxies running on by updating the external-idskey neutron-metadata-proxy-networksof the OVN Chassisrecord in the OVN Southbound database that corresponds to this host. As an example, this key would look like neutron-metadata-proxy-networks=NET1_UUID,NET4_UUIDmeaning that this chassis is hosting one or more VM’s connected to networks 1 and 4 so we should have a metadata proxy instance running for each. Ensure any running metadata proxies no longer needed are torn down. neutron-ovn-metadata-agentwill watch OVN Southbound database ( Port_Bindingtable) to detect when a port gets bound to its chassis. At that point, the agent will make sure that there’s a metadata proxy attached to the OVN localport for the network which this port is connected to. network:dhcpso that it gets auto deleted upon the removal of the network and it will remain DOWNand not bound to any chassis. The metadata port will be created regardless of the DHCP setting of the subnets within the network as long as the metadata service is enabled. network:dhcp). Launching a metadata proxy includes: Creating a network namespace: $ sudo ip netns add <ns-name> Creating a VETH pair (OVS upgrades that upgrade the kernel module will make internal ports go away and then brought back by OVS scripts. This may cause some disruption. Therefore, veth pairs are preferred over internal ports): $ sudo ip link add <iface-name>0 type veth peer name <iface-name>1 Creating an OVS interface and placing one end in that namespace: $ sudo ovs-vsctl add-port br-int <iface-name>0 $ sudo ip link set <iface-name>1 netns <ns-name> Setting the IP and MAC addresses on that interface: $ sudo ip netns exec <ns-name> \ > ip link set <iface-name>1 address <neutron-port-mac> $ sudo ip netns exec <ns-name> \ > ip addr add <neutron-port-ip>/<netmask> dev <iface-name>1 Bringing the VETH pair up: $ sudo ip netns exec <ns-name> ip link set <iface-name>1 up $ sudo ip link set <iface-name>0 up Set external-ids:iface-id=NEUTRON_PORT_UUID on the OVS interface so that OVN is able to correlate this new OVS interface with the correct OVN logical port: $ sudo ovs-vsctl set Interface <iface-name>0 external_ids:iface-id=<neutron-port-uuid> Starting haproxy in this network namespace. Add the network UUID to external-ids:neutron-metadata-proxy-networks on the Chassis table for our chassis in OVN Southbound database. Tearing down a metadata proxy includes: Other considerations This feature will be enabled by default in networking-ovn, but there should be a way to disable it in case operators who don’t need metadata don’t have to deal with the complexity of it (haproxy instances, network namespaces, etcetera). In this case, the agent would not create the neutron ports needed for metadata. There could be a race condition when the first VM for a certain network boots on a hypervisor if it does so before the metadata proxy instance has been spawned. Right now, the vif-plugged event to Nova is sent out when the up column in the OVN Northbound database’s Logical_Switch_Port table changes to True, indicating that the VIF is now up. To overcome this race condition we want to wait until all network UUID’s to which this VM is connected to are present in external-ids:neutron-metadata-proxy-networks on the Chassis table for our chassis in OVN Southbound database. This will delay the event to Nova until the metadata proxy instance is up and running on the host ensuring the VM will be able to get the metadata on boot. We’ve been building some features useful to OpenStack directly into OVN. DHCP and DNS are key examples of things we’ve replaced by building them into ovn-controller. The metadata API case has some key differences that make this a less attractive solution: The metadata API is an OpenStack specific feature. DHCP and DNS by contrast are more clearly useful outside of OpenStack. Building metadata API proxy support into ovn-controller means embedding an HTTP and TCP stack into ovn-controller. This is a significant degree of undesired complexity. This option has been ruled out for these reasons. In this approach, we would spawn a metadata proxy per virtual router or per network (if isolated), thus, improving the number of metadata proxy instances running in the cloud. However, scheduling and HA have to be considered. Also, we wouldn’t need the OVN localport implementation. neutron-ovn-metadata-agent would run on any host that we wish to be able to host metadata API proxies. These hosts must also be running ovn-controller. Each of these hosts will have a Chassis record in the OVN southbound database created by ovn-controller. The Chassis table has a column called external_ids which can be used for general metadata however we see fit. neutron-ovn-metadata-agent will update its corresponding Chassis record with an external-id of neutron-metadata-proxy-host=true to indicate that this OVN chassis is one capable of hosting metadata proxy instances. Once we have a way to determine hosts capable of hosting metadata API proxies, we can add logic to the networking-ovn ML2 driver that schedules metadata API proxies. This would be triggered by Neutron API requests. The output of the scheduling process would be setting an external_ids key on a Logical_Switch_Port in the OVN northbound database that corresponds with a metadata proxy. The key could be something like neutron-metadata-proxy-chassis=CHASSIS_HOSTNAME. neutron-ovn-metadata-agent on each host would also be watching for updates to these Logical_Switch_Port rows. When it detects that a metadata proxy has been scheduled locally, it will kick off the process to spawn the local haproxy instance and get it plugged into OVN. HA must also be considered. We must know when a host goes down so that all metadata proxies scheduled to that host can be rescheduled. This is almost the exact same problem we have with L3 HA. When a host goes down, we need to trigger rescheduling gateways to other hosts. We should ensure that the approach used for rescheduling L3 gateways can be utilized for rescheduling metadata proxies, as well. In neutron-server (networking-ovn). Introduce a new networking-ovn configuration option: [ovn] isolated_metadata=[True|False] Events that trigger scheduling a new metadata proxy: neutron-ovn-metadata-agentinstances. Events that trigger unscheduling an existing metadata proxy: neutron-ovn-metadata-agent. To schedule a new metadata proxy: Chassistable of the OVN Southbound database. Look for chassis that have an external-id of neutron-metadata-proxy-host=true. neutron-metadata-proxy-chassis=CHASSIS_HOSTNAMEas an external-id on the Logical_Switch_Port in the OVN Northbound database that corresponds to the neutron port used for this metadata proxy. CHASSIS_HOSTNAMEmaps to the hostname row of a Chassis record in the OVN Southbound database. This approach has been ruled out for its complexity although we have analyzed the details deeply because, eventually, and depending on the implementation of L3 HA, we will want to evolve to it. Except where otherwise noted, this document is licensed under Creative Commons Attribution 3.0 License. See all OpenStack Legal Documents.
https://docs.openstack.org/networking-ovn/latest/contributor/design/metadata_api.html
CC-MAIN-2019-09
refinedweb
2,104
50.16
There is a frustrating side to working with properties. We kinda saw this side in the previous tutorial. Passing properties from one component to another is nice and simple when you are dealing with only one layer of components. When you wish to send a property across multiple layers of components, things start getting complicated. Things getting complicated is never a good thing, so in this tutorial, let's see what we can do to make working with properties across multiple layers of components easy. Onwards! OMG! A React Book Written by Kirupa?!! To kick your React skills up a few notches, everything you see here and more (with all its casual clarity!) is available in both paperback and digital editions.BUY ON AMAZON Problem Overview Let's say that you have a deeply nested component, and its hierarchy (modeled as awesomely colored circles) looks as follows: What you want to do is pass a property from your red circle all the way down to our purple circles where it will be used. What we can't do is this very obvious and straightforward thing: You can't pass a property directly to the component or components that you wish to target. The reason has to do with how React works. React enforces a chain of command where properties have to flow down from a parent component to an immediate child component. This means you can't skip a layer of children when sending a property. This also means your children can't send a property back up to a parent. All communication is one-way from the parent to the child. Under these guidelines, passing a property from our red circle to our purple circle looks a little bit like this: Every component that lies on the intended path has to receive the property from its parent and then re-send that property to its child. This process repeats until your property reaches its intended destination. The problem is in this receiving and re-sending step. If we had to send a property called color from the component representing our red circle to the component representing our purple circle, its path to the destination would look something like this: Now, imagine we have two properties that we need to send: What if we wanted to send three properties? Or four? We can quickly see that this approach is neither scalable nor maintainable. For every additional property we need to communicate, we are going to have to add an entry for it as part of declaring each component. If we decide to rename our properties at some point, we will have to ensure that every instance of that property is renamed as well. If we remove a property, we need to remove the property from being used across every component that relied on it. Overall, these are the kinds of situations we try to avoid when writing code. What can we do about this? Detailed Look at the Problem In the previous section, we talked at a high level about what the problem is. Before we can dive into figuring out a solution, we need to go beyond diagrams and look at a more detailed example with real code. We need to take a look at something like the following: var Display = React.createClass({ render: function() { return( <div> <p>{this.props.color}</p> <p>{this.props.num}</p> <p>{this.props.size}</p> </div> ); } }); var Label = React.createClass({ render: function() { return ( <Display color={this.props.color} num={this.props.num} size={this.props.size}/> ); } }); var Shirt = React.createClass({ render: function() { return ( <div> <Label color={this.props.color} num={this.props.num} size={this.props.size}/> </div> ); } }); ReactDOM.render( <div> <Shirt color="steelblue" num="3.14" size="medium"/> </div>, document.querySelector("#container") ); Take a few moments to understand what is going on. Once you have done that, let's walk through this example together. What we have is a Shirt component that relies on the output of the Label component which relies on the output of the Display component. (Try saying that sentence five time fast!) Anyway, the component hierarchy looks as follows: When you run this code, what gets output is nothing special. It is just three lines of text: The interesting part is how the text gets there. Each of the three lines of text that you see maps to a property we specified at the very beginning inside ReactDOM.render: <Shirt color="steelblue" num="3.14" size="medium"/> The color, num, and size properties (and their values) make a journey all the way to the Display component that would make even the most seasoned world traveler jealous. Let's follow these properties from their inception to when they get consumed, and I do realize that a lot of this will be a review of what you've already seen. If you find yourself getting bored, feel free to skip on to the next section. With that said... Life for our properties starts inside ReactDOM.render when our Shirt component gets called with the color, num, and sizeproperties specified: ReactDOM.render( <div> <Shirt color="steelblue" num="3.14" size="medium"/> </div>, document.querySelector("#container") ); We not only define the properties, we also initialize them with the values they will carry. Inside the Shirt component, these properties are stored inside the props object. To transfer these properties on, we need to explicitly access these properties from the props object and list them as part of the component call. Below is an example of what that looks like when our Shirt component calls our Label component: var Shirt = React.createClass({ render: function() { return ( <div> <Label color={this.props.color} num={this.props.num} size={this.props.size}/> </div> ); } }); Notice that the color, num, and size properties are listed again. The only difference from what we saw with the ReactDOM.render call is that the values for each property are taken from their respective entry in the props object as opposed to being manually entered. When our Label component goes live, it has its props object properly filled out with the color, num, and size properties stored. You can probably see a pattern forming here. If you need to let out a big yawn, feel free to. The Label component continues the tradition by repeating the same steps and calling the Display component: var Label = React.createClass({ render: function() { return ( <Display color={this.props.color} num={this.props.num} size={this.props.size}/> ); } }); Notice that the Display component call contains the same listing of properties and their values taken from our Label component's props object. The only good news from all this is that we are almost done here. The Display component just displays the properties as they were populated inside its props object: var Display = React.createClass({ render: function() { return( <div> <p>{this.props.color}</p> <p>{this.props.num}</p> <p>{this.props.size}</p> </div> ); } }); Phew. All we wanted to do was have our Display component display some values for color, num, and size. The only complication was that the values we wanted to display were originally defined as part of ReactDOM.render. The annoying solution is the one you see here where every component along the path to the destination needs to access and re-define each property as part of passing it along. That's just terrible. We can do better than this, and you will see how in a few moments! Meet the Spread Operator The solution to all of our problems lies in something new to JavaScript known as the spread operator. What the spread operator does is a bit bizarre to explain without some context, so I'll first give you an example and then bore you with a definition. Take a look at the following snippet: var items = ["1", "2", "3"]; function printStuff(a, b, c) { console.log("Printing: " + a + " " + b + " " + c); } We have an array called items that contains three values. We also have a function called printStuff that takes three arguments. What we want to do is specify the three values from our items array as arguments to the printStuff function. Sounds simple enough, right? Here is one really common way of doing that: printStuff(items[0], items[1], items[2]); We access each array item individually and pass them in to our printStuff function. With the spread operator, we now have an easier way. You don't have to specify each item in the array individually at all. You can just do something like this: printStuff(...items); The spread operator is the ... characters before our items array, and using ...items is identical to calling items[0], items[1], and items[2] individually like we did earlier. The printStuff function will run and print the numbers 1, 2, and 3 to our console. Pretty cool, right? Now that you've seen the spread operator in action, it's time to define it. The spread operator allows you to unwrap an array into its individual elements. The spread operator does a few more things as well, but that's not important for now. We are going to only use this particular side of the spread operator to solve our property transferring problem! Properly Transferring Properties We just saw an example where we used the spread operator to avoid having to enumerate every single item in our array as part of passing it to a function: var items = ["1", "2", "3"]; function printStuff(a, b, c) { console.log("Printing: " + a + " " + b + " " + c); } // using the spread operator printStuff(...items); // without using the spread operator printStuff(items[0], items[1], items[2]); The situation we are facing with transferring properties across components is very similar to our problem of accessing each array item individually. Allow me to elaborate. Inside a component, our props object looks as follows: var props = { color: "steelblue", num: "3.14", size: "medium" } As part of passing these property values to a child component, we manually access each item from our props object: <Display color={this.props.color} num={this.props.num} size={this.props.size}/> Wouldn't it be great if there was a way to unwrap an object and pass on the property/value pairs just like we were able to unwrap an array using the spread operator? As it turns out, there is a way. It actually involves the spread operator as well. I'll explain how later, but what this means is that we can call our Display component by using ...props: <Display {...props}/> By using ...props, the runtime behavior is the same as specifying the color, num, and size properties manually. This means our earlier example can be simplified as follows (pay attention to the highlighted lines): var Display = React.createClass({ render: function() { return( <div> <p>{this.props.color}</p> <p>{this.props.num}</p> <p>{this.props.size}</p> </div> ); } }); var Label = React.createClass({ render: function() { return ( <Display {...this.props}/> ); } }); var Shirt = React.createClass({ render: function() { return ( <div> <Label {...this.props}/> </div> ); } }); ReactDOM.render( <div> <Shirt color="steelblue" num="3.14" size="medium"/> </div>, document.querySelector("#container") ); If you run this code, the end result is going to be unchanged from what we had earlier. The biggest difference is that we are no longer passing in expanded forms of each property as part of calling each component. This solves all the problems we originally set out to solve. By using the spread operator, if you ever decide to add properties, rename properties, remove properties, or do any other sort of property-related shenanigans, you don't have to make a billion different changes. You make one change at the spot you define your property. You make another change at the spot you consume the property. That's it. All of the intermediate components that merely transfer the properties on will remain untouched, for the {this.props} expression contains no details of what goes on inside it. Conclusion As designed by the ES6/ES2015 committee, the spread operator is designed to only work on arrays. It working on object literals like our props object is due to React extending the standard. As of now, no browser currently supports using the spread object on object literals. The reason our example works is because of Babel. Besides turning all of our JSX into something our browser understands, Babel also turns cutting-edge and experimental features into something cross-browser friendly. That is why we are able to get away with using the spread operator on an object literal, and that is why we are able to elegantly solve the problem of transferring properties across multiple layers of components!!
https://www.kirupa.com/react/transferring_properties.htm
CC-MAIN-2017-09
refinedweb
2,110
56.35
Exercise 3 of chapter 4 wants us to do some specific things with cstrings. We can use strcpy and strcat member functions from the cstring class to make our third string adhere to the requirements. Here is my solution : #include <iostream> #include <cstring> #include <string> using namespace std; int main() { char firstName[20]; char lastName[20]; char str[50]; // Gather input cout << "Enter your first name: "; cin >> firstName; cin.ignore(); cout << "Enter your last name: "; cin >> lastName; // C string member functions strcpy_s(str, lastName); strcat_s(str, " , "); strcat_s(str, firstName); cout << "Here's the information in a single string: " << str << endl; cin.get(); return 0; } Advertisements
https://rundata.wordpress.com/2012/10/18/c-primer-chapter-4-exercise-3/
CC-MAIN-2017-26
refinedweb
105
68.91
You can help Tails! The first release candidate for the upcoming version 2.0 is out. We are very excited and cannot wait to hear what you think about it :) What's new in 2.0? Tails 2.0 will be the first version of Tails based on Debian 8 (Jessie). As such, it upgrades essentially all included software. The most noticeable change is probably the move to GNOME Shell, configured in Classic mode. This desktop environment provides a modern and actively developed replacement for the aging GNOME "Flashback". GNOME Shell also paves the way for better supporting touchscreens in the future. Under the hood, an amazing amount of code was ported to more modern technologies. This, in turn, allowed us to do lots of small changes all around the place, that will make the Tails experience both safer, and more pleasant. For example, all custom system services are harder to exploit thanks to the use of Linux namespaces, set up by systemd. And the way Tails tells the user that "Tor is ready" is now more accurate. But really, there are simply too many changes to describe them all here, so try Tails 2.0~rc1 yourself! Technical details of all the changes are listed in the Changelog. There is one piece of bad news, that makes us a bit sad, though: we had to remove the Windows camouflage feature, since our call for help to port it to GNOME Shell (issued in January, 2015) was unsuccessful. What's new since Tails 2.0~beta1? New features - Fix the passphrase strength indicator of GNOME Disks. Upgrades and changes - Remove Claws Mail: Icedove is now the default email client. - Upgrade Tor Browser to 5.5a6. - Install xserver-xorg-video-intel from Jessie Backports (currently: 2.99.917-2~bpo8+1). This adds support for recent chips such as Intel Broadwell's HD Graphics. Fixed problems - Stop offering the option to open downloaded files with external - applications in Tor Browser (Closes: #9285). Our AppArmor confinement was blocking most such actions anyway, resulting in poor UX. Fix the performance issue of Tails Upgrader that made automatic upgrades very slow to apply. Fix Electrum by installing the version from Debian testing. Restore default file associations. Repair Dotfiles persistence feature. Fix ability to reconfigure an existing persistent storage. Associate armored OpenPGP public keys named *.keywith Seahorse. Update the list of enabled GNOME Shell extensions, which might fix - the "GNOME Shell sometimes leaves Classic mode" bug seen in 2.0~beta1: How to test Tails 2.0~rc1? Keep in mind that this is a test image. We have ensured that it is not broken in any obvious way, but it might still contain undiscovered issues. Download the ISO image and its signature: Or try the automatic upgrade from 2.0~beta1 even though it is very slow. Note that there is no automatic upgrade from 1.8.2 to this release. Verify the ISO image. Have a look at the list of known issues of this release and the list of longstanding known issues. Test wildly! If you find anything that is not working as it should, please report to us on tails-testers@boum.org. Bonus points if you first check if it is a known issue of this release or a longstanding known issue. Known issues in 2.0~rc1 The documentation was not updated yet. Tor Browser does not support MPEG-4 video streaming in Tails 2.0 and newer (#10835). Instead, in some cases you can download them and play them with the video player included in Tails. On the other hand, web sites that propose WebM video streaming work fine. Sometimes, some of the icons located on the top right corner of the screen are not displayed entirely, or at all. For example, the Vidalia icon, or the icon that allows to change to another keyboard layout, may be hidden. Other information, such as the clock, may not be visible. Restarting Tails often solves this problem. (#10576 and #10807) Network interfaces sometimes remain turned off (#9012). If this happens to you, please report the error so we can get enough debugging information to fix it. Graphics display operations are slow on computers with graphics adapters of the Nvidia GeForce 900 series, such as the GeForce GTX 960. It is not possible to add and configure printers (#10893). Longstanding known issues
https://tails.boum.org/news/test_2.0-rc1/
CC-MAIN-2020-40
refinedweb
731
76.01
Savas Triantafillou wrote: > Old index contains a file named ns_mapping.properties inside index > directory > where new index contains a file ns_idx.properties inside namespaces > directories and ns_mapping.proeprties does not exists > > Somehow if these two files exists at the same time queries upon old nodes > are impossible If both exists then the ns_mapping.properties takes precedence. See: > Restructuring of the index, at least in our case, is mandatory during > migration to 1.2 I quickly checked a migration from 1.1.1 to 1.2.1 and the queries still worked fine. Can you please describe the exact steps how you updated your jackrabbit instance? regards marcel
http://mail-archives.apache.org/mod_mbox/jackrabbit-dev/200702.mbox/%3C45D04C74.3050100@day.com%3E
CC-MAIN-2014-42
refinedweb
107
61.53
Red Hat Bugzilla – Bug 218196 Evolution mail client can no longer see folders outside of "INBOX/" imap namespace Last modified: 2008-03-11 22:57:02 EDT Description of problem: Evolution mail client can no longer access folders outside of the "INBOX/" imap namespace on our Cyrus IMAP server. It worked in all releases up to and including FC4 release but broke in FC5 and is still broken in FC6. Version-Release number of selected component (if applicable): Presently running FC6 with evolution components: evolution-webcal-2.7.1-6 evolution-sharp-0.11.1-10.fc6 beagle-evolution-0.2.10-7.fc6 evolution-data-server-1.8.1-2.fc6 evolution-2.8.1.1-3.fc6 How reproducible: Configure Evolution Account using IMAP server type Steps to Reproduce: 1. Configure Evolution Account using IMAP server type and on "Receiving Options" tab, check the "Override server-supplied folder namespace. 2. Log into new server account to view mail 3. Only INBOX and subfolders of INBOX appear. Folders under "" and "user/" are not shown. Actual results: Only INBOX and "INBOX/" are shown in the interface Expected results: There should be folders in INBOX/*, user/* and MySharedFolders/* shown in the evolution interface. Additional info: Evolution has the server defined as IMAP and have tried with "Override server-supplied folder namespace" checked (how it used to work) and unchecked. When the cyrus imap server is queried from a telnet session, it is properly supplying the namespaces Connected to ****.****.** (***.***.***.***). Escape character is '^]'. * OK somehost.somedomain.com Cyrus IMAP4 2.2.12-6.fc4 server ready . OK User logged in . NAMESPACE * NAMESPACE (("INBOX/" "/")) (("user/" "/")) (("" "/")) . OK Completed * BYE LOGOUT received . OK Completed Connection closed by foreign host. Encountered the same problem, but only if account was created with FC6's evolution. Folders outside of INBOX are shown by FC6's evolution if the account was created with FC4's evolution. Comparing both entries in ~/.gconf/apps/evolution/mail/%gconf.xml showed that the working entry has "override_namespace;namespace" in '<url>...</url>' while the newly created account only has "override_namespace". Adding ";namespace" with the gconf-editor fixed the problem with the new account. I seem to recall this being fixed awhile back. Can you please check whether this is fixed in Fedora 7 or later?.] Created a clean account and tried this with Fedora 8. The problem remains in this version of the distro as well. Moving this upstream. Please see [1] for further updates. [1]
https://bugzilla.redhat.com/show_bug.cgi?id=218196
CC-MAIN-2017-47
refinedweb
411
59.4
Fitting). A naive algorithm might attempt to minimize the sum of the squares of the algebraic distances, $$ d(\boldsymbol{a}) = \sum_{i=1}^N F(\boldsymbol{x}_i)^2, $$ with respect to the parameters $\boldsymbol{a} = [a,b,c,d,e,f]^\mathrm{T}$. However, there are two problems to overcome: firstly, such an algorithm will almost certainly find the trivial solution in which all parameters are zero. To avoid this, the parameters must be constrained in some way. A common choice, noting that $F(x, y)$ can be multiplied by any non-zero constant and still represent the same conic, is to insist that $f=1$ (other algorithms set $a+c=1$ or $||\boldsymbol{a}||^2=1$). The second problem however, is that there is no guarantee that the conic best fitted to an arbitrary set of points is an ellipse (for example, their mean squared algebraic distance to a hyperbola might be smaller). This is more likely to be the case where the points only lie near elliptical arc rather than around an entire ellipse. The appropriate constraint on the parameters of $F(x,y)$ in order for the conic it represents to be an ellipse, is $b^2 - 4ac < 0$. Some iterative algorithms seek to minimise $F(x,y)$ in steps, ensuring this constraint is met before each step. However, a direct least squares fitting to an ellipse (using the algebraic distance metric) was demonstrated by Fitzgibbon et al. (1999). They used the fact that the parameter vector $\boldsymbol{a}$ can be scaled arbitrarily to impose the equality constraint $4ac - b^2 = 1$, thus ensuring that $F(x,y)$ is an ellipse. The least-squares fitting problem can then be expressed as minimizing $||\boldsymbol{Da}||^2$ subject to the constraint $\boldsymbol{a}^\mathrm{T}\boldsymbol{C}\boldsymbol{a} = 1$, where the design matrix $$ \boldsymbol{D} = \begin{pmatrix} x_1^2 & x_1y_1 & y_1^2 & x_1 & y_1 & 1\\ x_2^2 & x_2y_2 & y_2^2 & x_2 & y_2 & 1\\ \vdots & \vdots & \vdots & \vdots & \vdots & \vdots\\ x_n^2 & x_ny_n & y_n^2 & x_n & y_n & 1 \end{pmatrix} $$ represents the minimization of $F$ and the constraint matrix $$ \boldsymbol{C} = \begin{pmatrix} 0 & 0 & 2 & 0 & 0 & 0\\ 0 & -1 & 0 & 0 & 0 & 0\\ 2 & 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 & 0 & 0 \end{pmatrix} $$ expresses the constaint $\boldsymbol{a}^\mathrm{T}\boldsymbol{C}\boldsymbol{a} = 1$. The method of Lagrange multipliers (as introduced by Gande (1981)) yields the conditions: \begin{align} \boldsymbol{S}\boldsymbol{a} &= \lambda\boldsymbol{C}\boldsymbol{a}\\ \boldsymbol{a}^\mathrm{T}\boldsymbol{C}\boldsymbol{a} &= 1, \end{align} where the scatter matrix, $\boldsymbol{S} = \boldsymbol{D}^\mathrm{T}\boldsymbol{D}$. There are up to six real solutions, $(\lambda_j, \boldsymbol{a}_j)$ and, it was claimed, the one with the smallest positive eigenvalue, $\lambda_k$ and its corresponding eigenvector, $\boldsymbol{a}_k$, represent the best fit ellipse in the least squares sense. Fitzgibbon et al. provided an algorithm, in MATLAB, implementing this approach, which was subsequently improved by Halíř and Flusser (1998) for reliability and numerical stability. It is this improved algorithm that is provided in Python below. Note that the algorithm is inherently biased towards smaller ellipses because of its use of the algebraic distance as a metric for the goodness-of-fit rather than the geometric distance. As noted by both sources for the algorithm used in this post, this issue is discussed by Kanatani (1994) and is not easily overcome. import numpy as np import matplotlib.pyplot as plt def fit_ellipse(x, y): """ Fit the coefficients a,b,c,d,e,f, representing an ellipse described by the formula F(x,y) = ax^2 + bxy + cy^2 + dx + ey + f = 0 to the provided arrays of data points x=[x1, x2, ..., xn] and y=[y1, y2, ..., yn]. Based on the algorithm of Halir and Flusser, "Numerically stable direct least squares fitting of ellipses'. """ D1 = np.vstack([x**2, x*y, y**2]).T D2 = np.vstack([x, y, np.ones(len(x))]).T S1 = D1.T @ D1 S2 = D1.T @ D2 S3 = D2.T @ D2 T = -np.linalg.inv(S3) @ S2.T M = S1 + S2 @ T C = np.array(((0, 0, 2), (0, -1, 0), (2, 0, 0)), dtype=float) M = np.linalg.inv(C) @ M eigval, eigvec = np.linalg.eig(M) con = 4 * eigvec[0]* eigvec[2] - eigvec[1]**2 ak = eigvec[:, np.nonzero(con > 0)[0]] return np.concatenate((ak, T @ ak)).ravel() def cart_to_pol(coeffs): """ Convert the cartesian conic coefficients, (a, b, c, d, e, f), to the ellipse parameters, where F(x, y) = ax^2 + bxy + cy^2 + dx + ey + f = 0. The returned parameters are x0, y0, ap, bp, e, phi, where (x0, y0) is the ellipse centre; (ap, bp) are the semi-major and semi-minor axes, respectively; e is the eccentricity; and phi is the rotation of the semi- major axis from the x-axis. """ # We use the formulas from # which assumes a cartesian form ax^2 + 2bxy + cy^2 + 2dx + 2fy + g = 0. # Therefore, rename and scale b, d and f appropriately. a = coeffs[0] b = coeffs[1] / 2 c = coeffs[2] d = coeffs[3] / 2 f = coeffs[4] / 2 g = coeffs[5] den = b**2 - a*c if den > 0: raise ValueError('coeffs do not represent an ellipse: b^2 - 4ac must' ' be negative!') # The location of the ellipse centre. x0, y0 = (c*d - b*f) / den, (a*f - b*d) / den num = 2 * (a*f**2 + c*d**2 + g*b**2 - 2*b*d*f - a*c*g) fac = np.sqrt((a - c)**2 + 4*b**2) # The semi-major and semi-minor axis lengths (these are not sorted). ap = np.sqrt(num / den / (fac - a - c)) bp = np.sqrt(num / den / (-fac - a - c)) # Sort the semi-major and semi-minor axis lengths but keep track of # the original relative magnitudes of width and height. width_gt_height = True if ap < bp: width_gt_height = False ap, bp = bp, ap # The eccentricity. r = (bp/ap)**2 if r > 1: r = 1/r e = np.sqrt(1 - r) # The angle of anticlockwise rotation of the major-axis from x-axis. if b == 0: phi = 0 if a < c else np.pi/2 else: phi = np.arctan((2.*b) / (a - c)) / 2 if a > c: phi += np.pi/2 if not width_gt_height: # Ensure that phi is the angle to rotate to the semi-major axis. phi += np.pi/2 phi = phi % np.pi return x0, y0, ap, bp, e, phi def get_ellipse_pts(params, npts=100, tmin=0, tmax=2*np.pi): """ Return npts points on the ellipse described by the params = x0, y0, ap, bp, e, phi for values of the parametric variable t between tmin and tmax. """ x0, y0, ap, bp, e, phi = params # A grid of the parametric variable, t. t = np.linspace(tmin, tmax, npts) x = x0 + ap * np.cos(t) * np.cos(phi) - bp * np.sin(t) * np.sin(phi) y = y0 + ap * np.cos(t) * np.sin(phi) + bp * np.sin(t) * np.cos(phi) return x, y if __name__ == '__main__': # Test the algorithm with an example elliptical arc. npts = 250 tmin, tmax = np.pi/6, 4 * np.pi/3 x0, y0 = 4, -3.5 ap, bp = 7, 3 phi = np.pi / 4 # Get some points on the ellipse (no need to specify the eccentricity). x, y = get_ellipse_pts((x0, y0, ap, bp, None, phi), npts, tmin, tmax) noise = 0.1 x += noise * np.random.normal(size=npts) y += noise * np.random.normal(size=npts) coeffs = fit_ellipse(x, y) print('Exact parameters:') print('x0, y0, ap, bp, phi =', x0, y0, ap, bp, phi) print('Fitted parameters:') print('a, b, c, d, e, f =', coeffs) x0, y0, ap, bp, e, phi = cart_to_pol(coeffs) print('x0, y0, ap, bp, e, phi = ', x0, y0, ap, bp, e, phi) plt.plot(x, y, 'x') # given points x, y = get_ellipse_pts((x0, y0, ap, bp, e, phi)) plt.plot(x, y) plt.show() Comments are pre-moderated. Please be patient and your comment will appear soon. There are currently no comments New Comment
https://scipython.com/blog/direct-linear-least-squares-fitting-of-an-ellipse/
CC-MAIN-2021-39
refinedweb
1,350
65.22
The 'start'. The layout of the components inside the gun body is shown in the picture below. The LCD and its controller are mounted on the barrel. An HDMI wire and an additional power cord (carrying 5V) connects the body of the gun to the barrel. The components were connected to the body using short male-female or female-female spacers. One side of the spacer is glued to the body, to create clean, screw-free look. It was first placed using a small drop of Cyanoacrylate ("super-glue") and then surrounded with a fair amount of epoxy. This configuration seem to work very well and give strong and reliable connection. The barrel (which can be removed from the gun body, as seen) holds a glass epoxy structure which holds the LCD panel and the beamsplitter glass. They are placed 45 degrees to each other. The surrounding of the LCD panel is covered by a black painted piece of cardboard (not shown in the picture). The lower side of the barrel holds the LCD controller. hi astroids_db.bin and trans.png not found and i have a mpu9255 but self.data is (0,0,0) def run(self): while(self.running): if self.imu.IMURead(): self.data = self.imu.getFusionData() time.sleep(self.wait_s) not read fusiondata
https://hackaday.io/project/2124-astrogun/discussion-6592
CC-MAIN-2021-17
refinedweb
217
75.91
A clean, elegant URL scheme is an important detail in a high-quality Web application. Django lets you design URLs however you want, with no framework limitations. See Cool URIs don’t change, by World Wide Web creator Tim Berners-Lee, for excellent arguments on why URLs should be clean and usable. To design URLs for an app, you create a Python module informally called a URLconf (URL configuration). This module is pure Python code and is a mapping between URL path expressions to Python functions (your views). This mapping can be as short or as long as needed. It can reference other mappings. And, because it’s pure Python code, it can be constructed dynamically. Django also provides a way to translate URLs according to the active language. See the internationalization documentation for more information. When a user requests a page from your Django-powered site, this is the algorithm the system follows to determine which Python code to execute: HttpRequestobject has a urlconf attribute (set by middleware), its value will be used in place of the :setting:`ROOT_URLCONF` setting. urlpatterns. This should be a sequence of django.urls.path() and/or django.urls.re_path() instances. kwargsargument to django.urls.path() or django.urls.re_path(). Here’s a sample URLconf: from django.urls import path from . import views urlpatterns = [ path('articles/2003/', views.special_case_2003), path('articles/ /', views.year_archive), path('articles/ / /', views.month_archive), path('articles/ / / /', views.article_detail), ] Notes: <int:name>to capture an integer parameter. If a converter isn’t included, any string, excluding a /character, is matched. articles, not /articles. Example requests: . For more complex matching requirements, you can define your own path converters. A converter is a class that includes the following: regexclass attribute, as a string. to_python(self, value)method, which handles converting the matched string into the type that should be passed to the view function. It should raise ValueErrorif it can’t convert the given value. A ValueErroris interpreted as no match and as a consequence a 404 response is sent to the user. to_url(self, value)method, which handles converting the Python type into a string to be used in the URL. For example:/ /', views.year_archive), ... ] [0-9]{4})/$', views.year_archive), re_path(r'^articles/(?P [0-9]{4})/(?P [0-9]{2})/$', views.month_archive), re_path(r'^articles/(?P [0-9]{4})/(?P [0-9]{2})/(?P [\w-]+)/$', views.article_detail), ] This accomplishes roughly the same thing as the previous example, except: When switching from using path() to re_path() or vice versa, it’s particularly important to be aware that the type of the view arguments may change, and so you may need to adapt your views. comments can be reversed. A convenient trick is to specify default parameters for your views’ arguments. Here’s an example URLconf and view: # URLconf from django.urls import path from . import views urlpatterns = [ path('blog/', views.page), path('blog/page /',. Each regular expression in a urlpatterns is compiled the first time it’s accessed. This makes the system blazingly fast. urlpatterns should be a sequence of path() and/or re_path() instances. When Django can’t find a match for the requested URL, or when an exception is raised, Django invokes an error-handling view. The views to use for these cases are specified by four variables. Their default values should suffice for most projects, but further customization is possible by overriding their default values.400– See django.conf.urls.handler400. handler403– See django.conf.urls.handler403. handler404– See django.conf.urls.handler404. handler500– See django.conf.urls.handler500. At any point, your urlpatterns can “include” other URLconf modules. This essentially “roots” a set of URLs below other ones. For example, here’s an excerpt of the URLconf for the Django website itself. It includes a number of other URLconfs:/ /', credit_views.report), path('charge/', credit_views.charge), ] urlpatterns = [ path('', main_views.homepage), path('help/', include('apps.help.urls')), path('credit/', include(extra_patterns)), ] In this example, the /credit/reports/ URL will be handled by the credit_views.report() Django view. This can be used to remove redundancy from URLconfs where a single pattern prefix is used repeatedly. For example, consider this URLconf: from django.urls import path from . import views urlpatterns = [ path(' - /history/', views.history), path(' - /edit/', views.edit), path(' - /discuss/', views.discuss), path(' - /permissions/', views.permissions), ] We can improve this by stating the common path prefix only once and grouping the suffixes that differ: from django.urls import include, path from . import views urlpatterns = [ path(' - /', include([ path('history/', views.history), path('edit/', views.edit), path('discuss/', views.discuss), path('permissions/', views.permissions), ])), ] An included URLconf receives any captured parameters from parent URLconfs, so the following example is valid: # In settings/urls/main.py from django.urls import include, path urlpatterns = [ path(' / /',: Consider again this URLconf entry: from django.urls import path from . import views urlpatterns = [ #... path('articles/ /', views.year_archive, name='news-year-archive'), #... ] According to this design, the URL for the archive corresponding to year nnnn is /articles/<nnnn>/. You can obtain these in template code by using: 2012 Archive {# Or with the year in a template context variable: #} {% for yearvar in year_list %} - {{ yearvar }} Archive{% endfor %} login,: 'admin'. argument to the reverse() function. The :ttag:`url` template tag uses the namespace of the currently resolved view as the current application in a RequestContext. You can override this default by setting the current application on the request.current_app attribute. If there is no current application, Django looks for a default application instance. The default application instance is the instance that has an instance namespace matching the application namespace (in this example, an instance of polls called the polls application from the tutorial: one called 'author-polls' and one called 'publisher-polls'. Assume we have enhanced that application so that it takes the instance namespace into consideration when creating and displaying polls. urls.py from django.urls import include, path urlpatterns = [ path('author-polls/', include('polls.urls', namespace='author-polls')), path('publisher-polls/', include('polls.urls', namespace='publisher-polls')), ] polls/urls.py from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path(' /', polls that. polls/urls.py from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path(' /', views.DetailView.as_view(), name='detail'), ... ] urls.py: ( , ) For example: from django.urls import include, path from . import views polls_patterns = ([ path('', views.IndexView.as_view(), name='index'), path(' /',.
https://getdocs.org/Django/docs/2.2.x/topics/http/urls
CC-MAIN-2021-49
refinedweb
1,064
53.78
Hi! - GastroGeek last edited by I have a custom plugin which basically wraps the Notify plugin with some custom config… import { Notify } from 'quasar' let defaults = { color: 'white', textColor: 'black', timeout: 2000, position: 'top' } let notifyInstance = (options) => { if (typeof options !== 'object') { options = Object.assign({}, defaults, { message: options }) } let optionsToUse = Object.assign({}, defaults, options) return Notify.create(optionsToUse) } export default ({ Vue }) => { Vue.prototype.$notify = notifyInstance } export { // for use outside components notifyInstance as Notify } @GastroGeek Thanks for your help. That’s an option but I don’t like that much. Do we have an option to load the options with the plugin or something like that should be cleaner? @trongdong the Quasar plugins (like Notify, Dialog, etc) initialization is done in the Quasar source code. You should not modify that because updates will overwrite it. The best way is to wrap them as @GastroGeek showed. This is true for any plugin like this show for axios - nothingismagick last edited by @GastroGeek is indeed using the right approach here, as things stand in the repo. If you really want to be able to configure it in quasar.conf.jsthen you should file a feature-request for it at github. - rstoenescu Admin last edited by This is one feature that will land in Quasar v0.16.1 (do not mistake this with CLI version).
https://forum.quasar-framework.org/topic/2317/global-config-for-quasar-plugin-like-notify/2?lang=en-US
CC-MAIN-2021-21
refinedweb
220
58.38
Cloud risk No. 3: Authentication, authorization, and access control Obviously, your cloud vendor's choice of authentication, authorization, and access control mechanisms is crucial, but a lot depends on process as well. How often do they look for and remove stale accounts? How many privileged accounts can access their systems -- and your data? What type of authentication is required by privileged users? Does your company share a common namespace with the vendor and/or indirectly with other tenants? Shared namespaces and authentication to create single-sign-on (SSO) experiences are great for productivity, but substantially increase risk. Data protection is another huge concern. If data encryption is used and enforced, are private keys shared among tenants? Who and how many people on the cloud vendor's team can see your data? Where is your data physically stored? How is it handled when no longer needed? I'm not sure how many cloud vendors would be willing to share detailed answers to these questions, but you have to at least ask if you want to find out what is known and unknown. Cloud risk No. 4: Availability When you're a customer of a public cloud provider, redundancy and fault tolerance are not under your control. Heck, usually what's provided and how it's done are not disclosed. It's completely opaque. Every cloud service claims to have fantastic fault tolerance and availability, yet month after month we see the biggest and the best go down for hours or even days with service interruptions. Of even bigger concern are the few instances in which customers have lost data, either due to an issue with the cloud provider or with malicious attackers. The cloud vendor usually states that they do awesome, triple-protected data backups. But even in cases where vendors said that data backups were guaranteed, they've lost data -- permanently. If possible, your company should always back up the data it's sharing with the cloud or at least insist on legalese that has the right amount of damages built in if that data is lost forever. Cloud risk No. 5: Ownership This risk comes as a surprise to many cloud customers, but often the customer is not the only owner of the data. Many public cloud providers, including the largest and best known, have clauses in their contracts that explicitly states that the data stored is the provider's -- not the customer's. Cloud vendors like owning the data because it gives them more legal protection if something goes wrong. Plus, they can search and mine customer data to create additional revenue opportunities for themselves. I've even read of a few cases where a cloud vendor went out of business, then sold their customers' private data as part of their assets to the next buyer. It's shocking. Make sure you have this known unknown on lockdown: Who owns your data and what can the cloud provider do with it? Cloud visibility Even when the cloud computing risks are known, they're difficult to calculate with real accuracy. We simply do not have enough history and evidence to determine the likelihood of security or availability failures, especially for a particular vendor, or whether such risks will lead to substantial customer damage. The best you can do is pull a Rumsfeld and least let your management in on the known unknowns. But first, endeavor to minimize the unknown unknowns. You want as much transparency as possible; if nothing else, at least get a copy of the last successful, relevant audit report. Ask your vendor about previous instances of tenant data compromises and losses, as well as the policy on reporting them to you. Nail down as best you can the limits of the cloud vendor's responsibility. Only by asking the hard questions can you begin to understand the total risks of public cloud computing. Although it may sound as if I'm down on public cloud computing, I'm actually a huge fan of it. I believe that most public cloud vendors do a far better job securing data than their customers do. But you need to know where your cloud vendor stands and the measures it takes to mitigate risk as compared to what your company alone could provide. This story, "The 5 cloud risks you have to stop ignoring," was originally published at InfoWorld.com. Keep up on the latest developments in network security and read more of Roger Grimes' Security Adviser blog at InfoWorld.com. For the latest business technology news, follow InfoWorld.com on Twitter.
http://www.infoworld.com/article/2614369/security/the-5-cloud-risks-you-have-to-stop-ignoring.html?page=2
CC-MAIN-2017-09
refinedweb
762
62.88
I have a project including a number of vendored javascripts, e.g. jQuery. I'm including these scripts as git submodules. However, for my build process, I need the built script, not the whole repository of that script. So I'm trying to set up a rake task to build each script - preferably using the script's own rakefile - and then copy the built script into my asset directory. file "app/vendor/scriptname.js" do # Call the task that builds the script here sh "cp app/vendor/script-submodule/dist/scriptname.js app/vendor/" end desc "Make vendor scripts available for build" task :vendor => "app/vendor/scriptname.js" do end If I use import 'app/vendor/scriptname/Rakefile' in my Rakefile, I should have access to the rake task that builds the script, right? How would I call it? Or should I just use sh "cd app/vendor/script-submodule/ && rake dist" and call it good? I'm working out a similar problem and it would seem to work just fine by calling the rake task as you normally would. Here's what my example looks like, see if you can get yours to fit. # Rakefile #!/usr/bin/env rake # Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. require File.expand_path('../config/application', __FILE__) load 'engines/foo_engine/Rakefile' MyApp::Application.load_tasks Then in my submodule's Rakefile: # engines/foo_engine/Rakefile Dir[File.join(File.dirname(__FILE__), 'tasks/**/*.rake')].each do |f| load f end And a sample rake task: # engines/foo_engine/lib/tasks/foo/bar/task.rake namespace :foo do namespace :bar do desc "FooBar task" task :foo_bar => :environment do # perform task end end end Then from the command prompt: rake foo:bar:task Similar Questions
http://ebanshi.cc/questions/1964890/how-can-i-call-a-rake-task-on-a-git-submodule
CC-MAIN-2017-22
refinedweb
305
57.47
The movie Star Trek: The Wrath of Khan introduced a device called the Genesis Torpedo that rearranged matter on a subatomic level to produce life-bearing planets. Talk about your mad scientist stuff! eXtensible Stylesheet Language for Transformations (XSLT) is the XML equivalent to Star Trek's Genesis; it rearranges XML at the element level to produce the desired results. However, unlike Genesis, the desired results are not limited to a single type, but rather can be any conceivable XML or text-based format. In addition, instead of the original document being modified, a new document is created in the desired format, which could be identical to the original document or vastly different. An XSLT document, sometimes referred to as a style sheet, is a well-formed XML document that uses the XSLT namespace (xmlns:xsl=) to describe the rules for transforming the source XML document into the result XML document. XSLT is always used in conjunction with XPath, which specifies the location of various elements within the source document. XSLT, on the other hand, describes the structure of the result document. Listing 10-1 contains a simple style sheet whose purpose is to simply copy the source XML document to the result XML document. Because no specific node names are used, this style sheet works equally well with all XML documents. <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns: <xsl:output <xsl:template <xsl:copy-of </xsl:template> </xsl:stylesheet> The XSL style sheet shown in Listing 10-1 works like this. First, the XML declaration describes the version of XML and the character set encoding. The xsl:stylesheet element describes the document as a style sheet, and the attributes specify the version of XSLT and the namespace. The xsl:output element defines the result document's XML declaration. The xsl:template defines a relationship between the source XML document and the result document. For example, the match attribute with the / specifies the source document's root node; all child elements of this element will be applied to the root element. Finally, the xsl:copy-of specifies to perform a deep copy of the context node; in other words, copy the context node and all descendants recursively. This chapter covers the following topics: Recursive versus iterative style sheets XPath in the style sheet Elements XSLT functions XSLT concepts Client-side transformations
http://www.yaldex.com/ajax_tutorial_2/ch10.html
CC-MAIN-2022-27
refinedweb
397
50.67
2287. [HZOI 2015] Crazy robot The question : Starting from the origin , go n Time , Every time up and down, left and right , Only in the first quadrant , Finally, back to the origin, the number of solutions That's not to mention , The combination number is written to find convolution NTT, And then I didn't think about the first quadrant gg In fact, that is Carter LAN number It's just here \(C(i)\) It's No \(\frac{i}{2}\) term , The odd number is 0 Make \(f[n]\) To go n The number of times to go back to the origin ,$$ f[n]=\sum_{i=0}{n}C(i)C(n-i)\binom{n}{i}=n!\sum_{i=0}{n}C(i)\frac{1}{i!}C(n-i)\frac{1}{(n-i)!} Pay attention to factorial and factorial inverse, don't multiply wrong , Don't lose anything !!! ```cpp #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> using namespace std; typedef long long ll; const int N=(1<<18)+5, INF=1e9; const ll P=998244353; inline int read(){ char c=getchar();int x=0,f=1; while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();} while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();} return x*f; } ll Pow(ll a, ll b, ll P) { ll ans=1; for(; b; b>>=1, a=a*a%P) if(b&1) ans=ans*a%P; return ans; } namespace NTT{ int n, rev[N], g; void ini(int lim) { g=3; n=1; int k=0; while(n<lim) n<<=1, k++; for(int i=0; i<n; i++) rev[i] = (rev[i>>1]>>1) | ((i&1)<<(k-1)); } void dft(ll *a, int flag) { for(int i=0; i<n; i++) if(i<rev[i]) swap(a[i], a[rev[i]]); for(int l=2; l<=n; l<<=1) { int m=l>>1; ll wn=Pow(g, flag==1 ? (P-1)/l : P-1-(P-1)/l, P); for(ll *p=a; p!=a+n; p+=l) { ll w=1; for(int k=0; k<m; k++) { ll t = w*p[k+m]%P; p[k+m] = (p[k] - t + P)%P; p[k] = (p[k] + t)%P; w = w*wn%P; } } } if(flag==-1) { ll inv=Pow(n, P-2, P); for(int i=0; i<n; i++) a[i] = a[i]*inv%P; } } void mul(ll *a, ll *b) { dft(a, 1); for(int i=0; i<n; i++) a[i]=a[i]*a[i]%P; dft(a, -1); } }using NTT::dft; using NTT::ini; using NTT::mul; int n; ll inv[N], fac[N], facInv[N]; ll a[N], b[N]; ll C(int n, int m) {return fac[n]*facInv[m]%P*facInv[n-m]%P;} int main() { //freopen("in","r",stdin); freopen("crazy_robot.in","r",stdin); freopen("crazy_robot.out","w",stdout); n=read(); ini(n+n+1); inv[1]=1; fac[0]=facInv[0]=1; for(int i=1; i<=n; i++) { if(i!=1) inv[i] = (P-P/i)*inv[P%i]%P; fac[i] = fac[i-1]*i%P; facInv[i] = facInv[i-1]*inv[i]%P; } a[0]=b[0]=1; for(int i=2; i<=n; i+=2) a[i]=b[i]= C(i, i>>1) * inv[(i>>1)+1] %P * facInv[i] %P; mul(a, b); for(int i=0; i<=n; i++) a[i]=a[i]*fac[i]%P; ll ans=0; for(int m=0; m<=n; m+=2) (ans += C(n, m) * a[m]%P) %=P; printf("%lld\n", ans); } ```\] BZOJ 2287. [HZOI 2015] Crazy robot [FFT Combination count ] More articles about - 【COGS】2287:[HZOI 2015] Crazy robot FFT+ Carter LAN number + Permutation and combination [ The question ][COGS 2287][HZOI 2015] Crazy robot [ Algorithm ]FFT+ Carter LAN number + Permutation and combination [ Answer key ] Consider the one-dimensional case first , Support +1 and -1, Prefix sum cannot be negative , It's in the form of Cartesian numbers . set up C(n) It means the first one ... - [COGS 2287][HZOI 2015] Crazy robot Description Question bank link Now there's a robot at the origin in the two-dimensional plane , He can choose to go right every time , turn left , Go down , Go up or not ( You can only walk one space at a time ). The robot can't go to the point where the abscissa is negative or the ordinate is negative . to ... - ... - COGS2287 ... - HDU4609 FFT+ Combination count HDU4609 FFT+ Combination count Portal : The question : find n The probability that three sticks from one stick can form a triangle Answer key : ... - BZOJ 4555: [Tjoi2016&Heoi2016] Sum up [ Divide and conquer FFT Combination count | Polynomial inverse ] 4555: [Tjoi2016&Heoi2016] Sum up The question : seek \[ \sum_{i=0}^n \sum_{j=0}^i S(i,j)\cdot 2^j\cdot j! \\ S It's the second kind of Stirling ... - BZOJ 4555: [Tjoi2016&Heoi2016] Sum up [FFT Combination count Principle of tolerance and exclusion ] 4555: [Tjoi2016&Heoi2016] Sum up The question : seek \[ \sum_{i=0}^n \sum_{j=0}^i S(i,j)\cdot 2^j\cdot j! \\ S It's the second kind of Stirling ... - 【BZOJ 3027】 3027: [Ceoi2004]Sweet ( Principle of tolerance and exclusion + Combination count ) 3027: [Ceoi2004]Sweet Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 71 Solved: 34 Description John ... - cojs Crazy center of gravity Crazy robot Problem solving report Crazy center of gravity It should be easy for people who have played fantasy country strategy games to cut off this topic Let's consider a tree with a leaf , Then the center of gravity moves towards the leaf at most 1 Distance of We only need to record the number of points in the subtree to judge whether to move or not That is to say ... Random recommendation - firefox flash plug-in unit 1. Unzip the file : tar -xzvf ***.tar.gz It will work out a file :libflashplayer.so And a directory usr 2. Will file libflashplayer.so Copy to directory /us ... - JavaScript String practical common operations String interception 1. substring()xString.substring(start,end)substring() Is the most commonly used string interception method , It can take two parameters ( Parameter cannot be negative ), They are the beginning of interception ... - Deploy the project to weblogic Prompt that the file is locked , Result in an error Deploy the project to weblogic One of them “ Yellow sigh !”. An error is as follows : (1) Deployment is out of date due to changes in the underlying projec ... - JDK Installation and configuration of detailed graphic tutorial Purpose : I'm forgetful , It's inevitable that the system will be re installed in the future , It's common for software to be unloaded , Here is a detailed tutorial , First, it's convenient for you to have a look when you reload later : Second, if a beginner is lucky enough to come , You can also give a little reference . I'll start with JDK The download . install . Environmental change ... - linux --> Get the system start time Get the system start time One . Preface Time is very important to the operating system , From the kernel level to the application layer , The expression and precision of time are the same .linux The kernel uses a jiffes To calculate the time stamp . The application layer has time.getdaytim ... - Use .net core efcore Automatically generate entity class according to database structure Source code github, Updated code The use of DB yes mysql, All first nuget once mysql.data establish t4 Templates ... - ISP PIPLINE ( 6、 ... and ) AWB What is WB(white balance)? When the human visual and nervous systems see white objects , Basically not affected by changes in the environment and serious illusion . Like cloudy days , a sunny day , indoor , Outside , Fluorescent lamp , Incandescent lamp, etc , People still regard white paper as ... - Understand thoroughly Scrapy Middleware ( One ) Middleware is Scrapy One of the core concepts . Middleware can be used to customize the data before the request of the crawler is initiated or after the request is returned , So we can develop crawlers that can adapt to different situations . " middleware " This Chinese name is the same as the previous chapter ... - lxde Installation and uninstall of and precautions ,lubuntu install : $ sudo apt install lxde $ sudo apt install lxde-common After installation , May not be able to shut down and logout, You can use the following installation : $ sudo apt ... - No blowing, no beating ,Python Programming 【315+ Problem 】 Write it at the front It's graduation season , At the end of the course, everyone “ expect + Helpless pain ” There is no better time than the content review and interview question and answer section every morning [ Near graduation, every day before class 40-60 Minutes to review the previous content . Questions and supplements , Select the students who don't like to talk and answer ]. expect ...
https://chenhaoxiang.cn/2021/06/20210604170758781l.html
CC-MAIN-2022-05
refinedweb
1,464
54.46
poll - Monitor conditions on multiple file descriptors #include <poll.h> int poll( struct pollfd filedes [], nfds_t nfds, int timeout ); Interfaces documented on this reference page conform to industry standards as follows: poll(): XSH4.0, XSH4.2, XSH5.0, XNS4.0, XNS5.0 Refer to the standards(5) reference page for more information about industry standards and associated tags. Points to an array of pollfd structures, one for each file descriptor of interest. Each pollfd structure includes the following members: The file descriptor The requested conditions The reported conditions Specifies the number of pollfd structures in the filedes array. Specifies the maximum length of time (in milliseconds) to wait for at least one of the specified events to occur. The poll() function provides users with a mechanism for multiplexing input/output over a set of file descriptors that reference open streams. For each member of the array pointed to by filedes, poll() examines the given file descriptor for the event(s) specified in events. The poll() function identifies those streams on which an application can send or receive messages, or on which certain events have occurred. The filedes parameter specifies the file descriptor to be examined and the events of interest for each file descriptor. It is a pointer to an array of pollfd structures. The fd member of each pollfd structure specifies an open file descriptor. The poll() function uses the events member to determine what conditions to report for this file descriptor. If one or more of these conditions is true, the poll() function sets the associated revents member. The events and revents members of each pollfd structure are bitmasks. The calling process sets the events bitmask, and poll() sets the revents bitmasks. These bitmasks contain inclusive ORed combinations of condition options. The following condition options are defined: An error has occurred on the file descriptor. This option is only valid in the revents bitmask; it is not used in the events member. For STREAMS devices, if an error occurs on the file descriptor and the device is also disconnected, poll() returns POLLERR; POLLERR takes precedence over POLLHUP. The device has been disconnected. This event is mutually exclusive with POLLOUT; a stream can never be writable if a hangup occurred. However, this event and POLLIN, POLLRDNORM, POLLRDBAND or POLLPRI are not mutually exclusive. This option is only valid in the revents bitmask; it is ignored in the events member. Data other than high-priority data may be read without blocking. This option is set in revents even if the message is of zero length. In revents, this option is mutually exclusive with POLLPRI. [Tru64 UNIX] Data may be read without blocking. The value specified for fd is invalid. This option is only valid in the revents member; it is ignored in the events member. Normal (priority band equals 0) data may be written without blocking. High-priority data may be received without blocking. This option is set in revents even if the message is of zero length. In revents, this option is mutually exclusive with POLLIN. Data from a non-zero priority band may be read without blocking. This option is set in revents even if the message is of zero length. Normal data (priority band equals 0) may be read without blocking. This option is set in revents even if the message is of zero length. Priority data (priority band greater than 0) may be written. This event only examines bands that have been written to at least once. Same as POLLOUT. The poll() function ignores any pollfd structure whose fd member is less than 0 (zero). If the fd member of all pollfd structures is less than 0, the poll() function will return 0 and have no other results. The conditions indicated by POLLNORM and POLLOUT are true if and only if at least one byte of data can be read or written without blocking. There are two exceptions: regular files, which always poll true for POLLNORM and POLLOUT, and pipes, when the rules for the operation specify to return zero in order to indicate end-of-file. The condition options POLLERR, POLLHUP, and POLLNVAL are always set in revents if the conditions they indicate are true for the specified file descriptor, whether or not these options are set in events. For each call to the poll() function, the set of reportable conditions for each file descriptor consists of those conditions that are always reported, together with any further conditions for which options are set in events. If any reportable condition is true for any file descriptor, the poll() function will return with options set in revents for each true condition for that file descriptor. If no reportable condition is true for any of the file descriptors, the poll() function waits up to timeout milliseconds for a reportable condition to become true. If, in that time interval, a reportable condition becomes true for any of the file descriptors, poll() reports the condition in the file descriptor's associated revents member and returns. If no reportable condition becomes true, poll() returns without setting any revents bitmasks. If the timeout parameter is a value of -1, the poll() function does not return until at least one specified event has occurred. If the value of the timeout parameter is 0 (zero), the poll() function does not wait for an event to occur but returns immediately, even if no specified event has occurred. The behavior of the poll() function is not affected by whether the O_NONBLOCK option is set on any of the specified file descriptors. The poll() function supports regular files, terminal and pseudo-terminal devices, STREAMS-based files, FIFOs, and pipes. The behavior of poll() function on elements of file descriptors that refer to other types of files is unspecified. For sockets, a file descriptor for a socket that is listening for connections indicates it is ready for reading after connections are available. A file descriptor for a socket that is connecting asynchronously indicates it is ready for writing after a connection is established. [Tru64 UNIX] For compatibility with BSD systems, the select() function is also supported. [Tru64 UNIX] This function supports up to 64K open file descriptors per process if that capability is enabled. Upon successful completion, the poll() function returns a nonnegative value. If the call returns 0 (zero), poll() has timed out and has not set any of the revents bitmasks. A positive value indicates the number of file descriptors for which poll() has set the revents bitmask. If the poll() function fails, -1 is returned and errno is set to indicate the error. If the poll() function fails, errno may be set to one of the following values: Allocation of internal data structures failed. A later call to the poll() function may complete successfully. A signal was caught during the poll() function and the signal handler was installed with an indication that functions are not to be restarted. [Tru64 UNIX] The timeout parameter is a negative number other than -1. [Tru64 UNIX] The nfds parameter is greater than the process's soft file descriptor limit. The nfds parameter is greater than OPEN_MAX, or one of the fd members refers to a stream or multiplexer that is linked (directly or indirectly) downstream from a multiplexer. [Tru64 UNIX] The filedes parameter in conjunction with the nfds parameter addresses a location outside of the allocated address space of the process. Functions: getmsg(2), putmsg(2), read(2), write(2), setsysinfo(2), streamio(7) Standards: standards(5) Network Programmer's Guide poll(2)
https://nixdoc.net/man-pages/Tru64/man2/poll.2.html
CC-MAIN-2020-45
refinedweb
1,254
62.68
On Wed, 2008-06-11 at 00:43 +0200, Christian Heimes wrote: > John Krukoff wrote: > > Since you probably want access to these from many different places in > > your code, I find the simplest way is to create a logging module of your > > own (not called logging, obviously) and instantiate all of your loggers > > in that namespace, then import that one module as needed. > > No, don't do that. Simple do > > import logging > log = logging.getLogger("some_name") > > The logging module takes care of the rest. The logging.getLogger() > function creates a new logger *only* when the name hasn't been used yet. > > Christian > > -- > Nifty, I never noticed that function, thanks for pointing it out as it'll make my application a bit simpler. Now, if they'd only add a syslog module that uses the libc syslog interface (sure, it wouldn't be thread safe, but at least it'd be portable to AIX, unlike the current one), I'll be a happy camper. -- John Krukoff <jkrukoff at ltgc.com> Land Title Guarantee Company
https://mail.python.org/pipermail/python-list/2008-June/514157.html
CC-MAIN-2014-15
refinedweb
173
70.43
. The problem with the original example was not in the way boost::tokenizer was used. The issue was that the code assume one record per line. Because of that assumption it reads one line from file at a time and processes it with the parser. This post shows code that handles line breaks in csv fields. Example As we can see there are fields that contain line breaks as well as a field that spans 3 lines. Updated Record Reading Algorithm To fix the problem the reading part of the algorithm has to detect if the line, that was read from a file, contains full record or if the record continues on the next line. Here is the updated code: string line; string buffer; bool inside_quotes(false); size_t last_quote(0); while (getline(in,buffer)) { last_quote = buffer.find_first_of('"'); while (last_quote != string::npos) { inside_quotes = !inside_quotes; last_quote = buffer.find_first_of('"', last_quote + 1); } line.append(buffer); if (inside_quotes) { line.append("\n"); continue; } // line now contains full record, // use boost::tokenizer to parse it } The way I implemented this check is to scan the line and check the number of quote characters. If we have odd number of quote characters the record is not complete and we need to read another line. Custom Separator for Semicolons I have updated the tokenizer to deal with semi-colon delimiter instead of the original comma, as per the format used in the original question (posted in comments to the previous post): typedef tokenizer< escaped_list_separator<char> > Tokenizer; escaped_list_separator<char> sep('\\', ';', '\"'); Tokenizer tok(line, sep); The only difference is that I have to initialize separator with custom values, replacing comma with semicolon as the second parameter, and passing the new separator to Tokenizer object on creation. Full code listing #include <iostream> #include <fstream> // fstream #include <vector> #include <string> #include <algorithm> // copy #include <iterator> // ostream_operator #include <boost/tokenizer.hpp> int name_address_sport_parser() { using namespace std; using namespace boost; string data("name_address_sport.csv"); ifstream in(data.c_str()); if (!in.is_open()) return 1; typedef tokenizer< escaped_list_separator<char> > Tokenizer; escaped_list_separator<char> sep('\\', ';', '\"'); vector< string > vec; string line; string buffer; bool inside_quotes(false); size_t last_quote(0); while (getline(in,buffer)) { // --- deal with line breaks in quoted strings last_quote = buffer.find_first_of('"'); while (last_quote != string::npos) { inside_quotes = !inside_quotes; last_quote = buffer.find_first_of('"',last_quote+1); } line.append(buffer); if (inside_quotes) { line.append("\n"); continue; } // --- Tokenizer tok(line, sep); vec.assign(tok.begin(),tok.end()); line.clear(); // clear here, next check could fail // example checking // for correctly parsed 3 fields per record if (vec.size() < 3) continue; copy(vec.begin(), vec.end(), ostream_iterator<string>(cout, "|")); cout << "\n----------------------" << endl; } in.close(); return 0; } int main() { name_address_sport_parser(); } Input Data and Generated Output Example input Generated output, I have inserted pipe character between fields in a record and extra line between records to show how the values were extracted:| ---------------------- Feel free to point out any issues with the code. This example, and the one in the previous post, is supposed to show how to use boost::tokenizer more than how to deal with all possible csv formats. I hope this demonstrates how to fix the code to handle embedded line breaks. Good program, one question: What if the new line inside the quota is "\r\n", then by appending in this way would change the original record: if (inside_quotes) { line.append("\n"); continue; } Great job. One oversight though: If the quoted text has an escaped ", the algorithm will fail. To correct this, the following need to be changed while (last_quote != string::npos) { if (buffer[ last_quote - 1 ] != '\\') { inside_quotes = !inside_quotes; } last_quote = buffer.find_first_of('"',last_quote+1); } Hi, Thank you for the code I was tryint to find an example of tokenizer. When you use getline, the function stops when arrive to the first '\n', isn't it? I thnik the code will be incorrect to support '\n' inside '"'.
http://mybyteofcode.blogspot.com/2010/11/parse-csv-file-with-embedded-new-lines.html
CC-MAIN-2014-52
refinedweb
630
55.84
Float to String Conversion - JS javascript number to string format parseint javascript how can you convert the string of any base to integer in javascript javascript float precision javascript decimal converting into string in js typescript convert number to string So I am currently working on that function const countSixes = n => { if (n === 0) return 0; else if (n === 1) return 1; else n = (countSixes(n-1) + countSixes(n-2)) / 2; return n; } And so my question is how to convert the final floating-point value into a string? Every time after calling the function and trying to convert the float number it returns NaN What I've Tried - "" + value - String(value) - value.toString() - value.toFixed(2) Hope to get the answer Thank you! The first option works for me <script> const countSixes = n => { if (n === 0) return 0; else if (n === 1) return 1; else n = (countSixes(n-1) + countSixes(n-2)) / 2; return n; } alert(countSixes(12) + "") </script> JavaScript parseFloat() Function, Definition and Usage. The parseFloat() function parses a string and returns a floating point number. This function determines if the first character in the specified! The problem is really interesting. Its return NaN because when you return n as String, as the function is called recursively so it cannot perform arithmetic operations in next level. It will never end for certain numbers like 55 function countSixes(n,firstTime=true){ if (n === 0) return 0; else if (n === 1) return 1; else n = (countSixes(n-1,false) + countSixes(n-2,false)) / 2; if(firstTime) return n.toFixed(10); // return string else return parseFloat(n.toFixed(10)); // return float } Convert float to string with at least one decimal place (javascript , If you want to append .0 to output from a Number to String conversion and keep precision for non-integers, just test for an integer and treat it Introduction to Javascript string to float. Conversion of String to Float is generally used if the string including float numbers is to perform mathematical operations. When you get text field or text field data, you must receive data entered as a string. You could convert the final value to a string with the wanted decimals. const countSixes = n => { if (n === 0) return 0; if (n === 1) return 1; return (countSixes(n - 1) + countSixes(n - 2)) / 2; } console.log(countSixes(30).toFixed(15)); JavaScript Convert Number to String, toString() method that belongs to the Number.prototype object, takes an integer or floating point number and converts it into a String type. There are multiple ways Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java and XML. JavaScript, The parseFloat() is an inbuilt function in JavaScript which is used to accept the string and convert it into a floating point number. If the string does not contain a How to convert a float number to the whole number in JavaScript? There are various methods to convert float number to the whole number in JavaScript. Math.floor (floating argument): Round off the number passed as parameter to its nearest integer in Downward direction . JavaScript, Below are some examples to illustrate the working of toString() function in JavaScript: Converting a number to a string with base 2: To convert a number to a string Float to String Conversion - JS. Ask Question Asked 1 year, 4 months ago. Active 1 year, 4 months ago. Viewed 163 times 0. So I am currently working on that function parseFloat(), The parseFloat() function parses an argument (converting it to a string first if needed) and returns a floating point number. Introduction [/javascript-convert - what value do you expect? please add an example. - I copied your function exactly as posted, ran it in the chrome console and added a toString() at the end of the call and got a string output, what value are you calling this function with? - Each of those should work , can you give a larger example and explain what you want and what happens instead? - Issue is you are using it in recursive manner so you probably were using inside the function call so you were subtracting strings? Hard to tell since you did not show how you were converting it to a string. - I would define countSixes()as entry and countSixesHelper()as recursive part. - I would also do that but i posted this in hurry
https://thetopsites.net/article/54427631.shtml
CC-MAIN-2021-25
refinedweb
736
60.45
Java5 Language Features in JDO 1.1 and 2.0 This activity clarifies the JDO spec on persistence-capable classes using the new language features in Java 5, namely enums and generics. Generics - generics as persistent field types ... JDO implementations need the information about field types that in JDO 1 is provided by the metadata element collection and map. The user can specify the type of the elements of the collection and the types of the key and value of the map. For example, class Employee { ... Map<Project, Integer> projectNumbers; Set<Skill> skillSet; ... } - generics with wildcards as persistent field types... Generic wildcards allow the user to bound the types of persistent collection elements, or map keys and values. For example, if we know that a Set can only contain Number elements, we might declare it as a Set<? extends Number> skills;. Mapping this persistent field to the datastore is similar to the issue of mapping a field of a superclass to the datastore, e.g. Number skill;. And it is similar to mapping Set<Number>. We believe that as far as JDO is concerned, the implementation can consider Set<? extends Number> exactly as Set<Number>. - fields of type identifier type ... The only implementation class for type identifiers is Class, which cannot be persistent. I (clr) propose to wait until a use-case is developed. - generics arrays ... This seems to apply only to methods of generic classes and not to persistent behavior. I (clr) propose to wait until a use-case is developed. - as persistence-capable classes ... This usage is not well-defined. I (clr) think that most uses would involve some kind of wrapper or holder that was type-specific. I (clr) propose to wait until a use-case is developed. Enums Java 5 has introduced linguistic support for enumerated types in form of enum declarations, for example: enum Season { WINTER, SPRING, SUMMER, FALL }; In Java, enum declarations have a number (surprising) features, which exceed their counterparts in other languages: An enum declaration defines a fully fledged class (dubbed an enum type). - An enum type may have arbitrary methods and fields and may implement arbitrary interfaces. Enum types have efficient implementations of all the Object methods, are Comparable and Serializable, and the serial form is designed to withstand arbitrary changes in the enum type. To point out commonalities, Java enum types are no different from other user-defined classes, except that - the number of instances is fixed at compile time, - there are no constructors that can be called, there's a generated method static public T[] values() returning an array of all instances, there are new, reflective methods for enums, like Class.isEnum() and Class.getEnumConstants(). For enum type support in JDO, we have to discuss - enum types as managed field types ... - enum types as persistence-capable classes ... the new collection types EnumSets and EnumMaps ... JDO Specific Annotations For managed relations, we may add javax.jdo.annotation.Inverse for use in a PC class: public class Department { ... @javax.jdo.annotation.Inverse("department") Set<Employee> employees; ... } public class Employee { ... Department department; ... } This annotation may be used to generate 'mapped by' metadata.
https://wiki.apache.org/jdo/Java5FeaturesAndJdo
CC-MAIN-2017-09
refinedweb
520
58.28
Introduction Vite is a build tool developed by Evan You, the author of Vue. It uses native ES Module imports and provide a fast running development environment with no bundling required. Vue3, React and Preact are also supported. In this article, I'll use Vite to build a Preact project environment. You can find the result template in here. To do I will introduce the minimum tools necessary for development. The goal is making it close to the default preact/cli template. The following is a step-by-step explanation of each tool, so that you can introduce them individually. - Typescript - ESLint - Prettier - Stylelint - husky and lint-staged - Path Alias Building Environments First, let's expand the vite template. yarn create vite-app <project-name> --template preactcd <project-name>yarn Once the development server is up, you'll be impressed by how fast it is. Typescript Then, let's typescript the project. In a minimal configuration, you only need to do two things. 1.Change all .jsx files to .tsx. 2.Change the src of the script tag of index.html to /src/main.tsx. Now you can start up the development server and see that it runs without any problems. It should work, but I'll add a few more settings to improve the user experience in the editor. Place the tsconfig.json in your project root. This will tell the editor to recognize the project as a Typescript"]} VSCode shows an error in the .tsx file at this point, so fix it. Add this sentence to all the .tsx files. import { h } from 'preact' If you are using Fragment, import it as well. import { h, Fragment } from 'preact' Next, fix the entry point, main.tsx. Now that it's in Typescript, a type error has been detected. The document.getElementById returns HTMLElement or null, give it a null check. const el = document.getElementById('app')if (el) {render(<App />, el)} Then make some changes to vite.config.js. const config = {jsx: {factory: 'h',fragment: 'Fragment'},plugins: [preactRefresh()]}export default config I was able to make Typescript with minimal configuration. You don't have to do the following. Change vite.config.js to .ts to eliminate .js files. Also, change it to the ES Module format to make the whole project more consistent. The vite.config.ts should look like this import preactRefresh from '@prefresh/vite'import type { UserConfig } from 'vite'const config: UserConfig = {jsx: {factory: 'h',fragment: 'Fragment',},plugins: [preactRefresh()],}export default config That's the end of Typescript. Introducing ESLint Development without a linter is tough, so be sure to install it. yarn add -D eslint eslint-config-preact @typescript-eslint/parser typescript {"env": {"browser": true,"es2021": true},"extends": ["eslint:recommended","preact"],"parser": "@typescript-eslint/parser","parserOptions": {"ecmaFeatures": {"jsx": true},"ecmaVersion": 12,"sourceType": "module"},"rules": {}} It is easy to prepare a linting command in the script of the package.json for later. It will be easier later on if you have a command for linting in the package.json script of the package.json. "scripts": {"lint:script": "eslint --ext .ts,tsx -,tsx}": , as they are less visible. yarn add -D prettier eslint-config-prettier {"trailingComma": "es5","semi": false,"singleQuote": true} When ESLint and Prettier are used together, I need to fix the .eslintrc to avoid duplicate rules. {"extends": ["eslint:all","preact",// Added under other rules"prettier","prettier/@typescript-eslint"]} command to execute the formatter. yarn prettier -w -u . We want to apply automatic formatting before committing, so we add the setting to lint-staged. {"lint-staged": {"*.{ts,tsx}": "eslint --fix","*": "prettier -w -u" // Prettier is the last one to go}} file a target for linting as well. yarn add -D stylelint stylelint-config-recommended stylelint-config-standard {"extends": ["stylelint-config-recommended", "stylelint-config-standard"]} Edit the package.jsoon and set the commands and lint-staged. {"scripts": {"lint:style": "stylelint src/**/*.{css,scss}"},"lint-staged": {"*.{ts,tsx}": "eslint --fix","*.{css,scss}": "stylelint --fix","*": "prettier -w -u"}} VSCode users can format it automatically with the following settings. Extensions are required, so if you don't have them, install them here. That's the end of the basic setup of the linker and formatter. Configuring Path Alias Module import is relative by default, but we want to set alias to always refer to the same root. Change the vite.config.ts and tsconfig.json to set the alias. import { join } from 'path'import type { UserConfig } from 'vite'const config: UserConfig = {alias: {'/@/': join(__dirname, 'src'),}} {"compilerOptions": {"baseUrl": ".","paths": {"/@/*": ["src/*"]}},"include": ["src"]} Now you can set up alias. We'll use it like this. import { App } from '/@/app' It's a little strange that it has to start from /, but it seems to combine with the alias of the package name. For more information, please refer to here. That's the minimum environment you can build. Edit this page on GitHub
https://miyauchi.dev/posts/vite-preact-typescript/
CC-MAIN-2021-43
refinedweb
808
60.31
[ ] Davanum Srinivas commented on AXIS-1609: ---------------------------------------- Please follow instructions here on how to submit a patch: thanks, dims > No option available to map all MIME type to javax.activation.DataHandler as required by JAX-RPC 1.1 specification. > ------------------------------------------------------------------------------------------------------------------ > > Key: AXIS-1609 > URL: > Project: Axis > Type: Bug > Components: WSDL processing > Versions: 1.2 Beta > Environment: Axis 09/23/2004 > Reporter: Sébastien Tardif > Attachments: docHarbor.wsdl > > My use case is to use SwA and doing streaming from end to end. The type of attachment is not known. So as suggested by many documents I use the mime type: "application/octet-stream". Wsdl2Java utility use org.apache.axis.attachments.OctetStream to represent the data. It's a class specific to Axis which is one of my concern. > Take a look a the class: > public class OctetStream { > private byte[] bytes = null; > public OctetStream() { > } > public OctetStream(byte[] bytes) { > this.bytes = bytes; > } > public byte[] getBytes() { > return this.bytes; > } > public void setBytes(byte[] bytes) { > this.bytes = bytes; > } > } > It doesn't support streaming! It's probably the reason why people will use attachment instead of the most compatible way: "xsd:base64Binary". > As a third issues: > The JAX-RPC 1.1 specification said: > 7.5 Mapping between MIME types and Java types > The following table specifies the standard Java mapping for a subset of the MIME types. > The Java to WSDL/XML and WSDL/XML to Java mapping for the MIME types is > required to conform to the above mapping. This mapping is reflected in the mapped Java > method signatures and WSDL description. A WSDL/XML to Java mapping tool is > required to provide an option to map the above set of MIME types to the > javax.activation.DataHandler class. The DataHandler class provides methods to > get access to the stream representation of the data for a MIME type. > A Java to WSDL mapping tool is required to provide a facility for specifying metadata > related to the above mapping between Java and MIME types. This metadata identifies > whether a Java type is mapped to a MIME type (using the WSDL MIME binding) or is > mapped to an XML schema type (based on the section 4.2, "XML to Java Type > Mapping"). For example, a java.lang.String can be mapped to either an xsd:string > or MIME type text/plain. The mapping metadata identifies a specific mapping. > If a MIME type is mapped to the javax.activation.DataHandler, the getContent > method of the DataHandler class must return instance of the corresponding Java type > for a specific MIME content type. > A JAX-RPC implementation is required to support the above MIME types (as specified > in the TABLE 7-1) and provide implementation of the required > javax.activation.DataContentHandler classes. > ... > A JAX-RPC implementation is not required to support MIME types beyond that > specified in the above table. These additional MIME types may be mapped and > supported using the javax.activation.DataHandler class and Java Activation > Framework. > TABLE 7-1 Mapping of MIME Types > MIME Type Java Type > image/gif java.awt.Image > image/jpeg java.awt.Image > text/plain java.lang.String > multipart/* javax.mail.internet.MimeMultipart > text/xml or application/xml javax.xml.transform.Source > Here the approch of another stack: > From: > JAXRPC specification uses the JavaBeans Activation Framework to support various MIME content types. The DataHandler class provides a consistent interface to the data represented in various MIME types. A DataHandler class uses the DataContentHandler interface to convert between a stream and specific Java object based on the MIME type. JAXRPC uses SAAJ, which provides DataContentHandlers for the MIME types supported by JAXRPC. If the MIME type is not one of the JAXRPC supported MIME types, then the user has to register corresponding DataContentHandlers. Here "text/plain" and "text/xml" are both JAXRPC supported MIME types and is taken care of automatically. A DataHandler can be instantiated using the constructor DataHandler(Object obj, String mime_type). The method DataHandler.getContentType returns the MIME type of the encapsulatd data and DataHandler.getContent method retruns a Java object based on the MIME type of the encapsulated data. If you do not want the MIME types to map to coresponding Java types, you can use wscompile with -datahandleronly option to map all MIME types to DataHandler. -- This message is automatically generated by JIRA. - If you think it was sent incorrectly contact one of the administrators: - If you want more information on JIRA, or have a bug to report see:
http://mail-archives.apache.org/mod_mbox/axis-java-dev/200411.mbox/%3C1634526925.1100537073513.JavaMail.apache@nagoya%3E
CC-MAIN-2017-43
refinedweb
737
50.02
import shapefile # Create a reader instance r = shapefile.Reader("Building_Footprint") # Create a writer instance w = shapefile.Writer(shapeType=shapefile.POLYGON) # Copy the fields to the writer w.fields = list(r.fields) # Grab the geometry and records from all features # with the correct county name selection = [] for rec in enumerate(r.records()): if rec[1][1].startswith("Hancock"): selection.append(rec) # Add the geometry and records to the writer for rec in selection: w._shapes.append(r.shape(rec[0])) w.records.append(rec[1]) # Save the new shapefile w.save("HancockFootprints") I originally used python list comprehensions for the two loops in this example. They usually run faster than "for" loops. However some basic testing showed them to be about the same speed in this case and a little harder to read. If your selection were more complex you probably want to use a for loop anyway to select by multiple attributes or other filters. As usual the code for this example can be found on the "geospatialpython" Google Code project in the source tree. The shapefile can be found on the same site in the download section. Thanks! This is exactly what I am looking for. Also would like to see the alternative list comprehension way Nice post,it's very informative.i found the best information.I updated my knowledge with this blog.it can help me to crack GIS jobs in Hyderabad.
http://geospatialpython.com/2010/12/subsetting-shapefile-by-attributes.html
CC-MAIN-2018-51
refinedweb
235
60.11
Introduction - look at these memory segments with a simple example. The example is just for understanding the purpose and it does nothing actually excepting printing something. Memory Segments - An example The complete example is shown below: // CPPTST.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <conio.h> //MemSeg01: Declare a Global Variable int x = 10; //MemSeg02: Store address of the Global variable in a Global Pointer int* px = &x; //MemSeg03: Function definition. Takes a number and prints it void PrintNo(int x) { int y; y = x; printf("The given number is %d", x); } int _tmain(int argc, _TCHAR* argv[]) { //MemSeg04: Declare a loval variable and declare a pointer and store the address of local variable int m = 12; int* pm = &m; //MemSeg05: Local pointer storing the Global Address int* pgx = &x; //MemSeg06: Local pointer storing the heap address and assigning a value to the heap int *pInt = new int; *pInt = 22; //MemSeg07: Local pointer to a function that returns void and takes int void (*pFun)(int); //MemSeg08: Pointer storing the base address of the function pFun = &PrintNo; //MemSeg09: Calling the function through function pointer pFun(117); return 0; } Let us explore the example in terms of the memory segmentations. Code Memory Segment Well. The code is displayed above. What will you do with it? The first thing is compiling it and then linking the code. Let use assume that the above code is placed in the MyProgram.CPP file. When you compile, the compiler will translate this human readable language into something that called as object code. If there are 20 such files, the job of the compiler is to generate twenty different object files and prompt any errors that do not comply to the C++ syntax. Then the linker will go through all 20-object files to form an executable that is the .exe file. What happens when you double click the exe name? The exe is considered as a process by the operating system and once the process is committed, the M/c code (exe) is loaded into the memory and processor will access these machine instructions to perform specified action. This memory is called Code Segment. In out example, the translated code goes as exe, and when the exe is executed, the instructions are loaded into the memory called code segment. Let us take the first statement in the Program entry: //MemSeg04: Declare a local variable and declare a pointer and store the address of local variable int m = 12; The above code will be translated and packed in the exe as a machine-readable language. In the VS2005 IDE, I kept a breakpoint on the above-shown statement and once the breakpoint is hit, using the context menu I asked for show Assembly code. The Assembly revealed is shown below: The address marked in Red box shows it stores the assembly command MOV (It may be mapped to number and then in terms of zeros and ones that is low and high voltage. We no need to go that much deep into the electronics of it). The Address in the Red box is actually allocated in the Code Segment. A pointer can store this address also. Data Memory Segment As the name implies it is the segment for application data. Do you heard your senior asking multiple questions when you declare a global variable? He asks, because the global variables go and sit in the data segment of the memory. So what? If it sits there, it lives until the program dies and there is no ways to say get lost. Think about a big project and 1000 of people worked on it (Even in maintenance) for last 10 to 20 years declared plenty of global variables even when it is avoidable by alternate techniques. When the program loads (in Code segment) it needs to allocate space for all those variables and allocated space is never cleared until the program exits. That is why we call these global variables and constants are application data. The memories associated to these global are known as data segment memory and it will get cleared when the program is removed. In our example the following two statements are occupying the memory in the data segment. //MemSeg01: Declare a Global Variable int x = 10; //MemSeg02: Store address of the Global variable in a Global Pointer int* px = &x; Note that the pointer px is holdling the address of some data segment memory allocated to variable integer x. Also, the space required for holding that address also allocated in the data segment. Here, the value in the px, x can be changed. But, the space allocated for it cannot be washed out. Heap Memory Segment Allocating and clearing the memory in the memory segment for Stack, Code and data is taken care by the system. But, heap memory is given in the hands of C++ programmer. They can create byes of memory as well as clear it whenever they want. So the programmer determines the lifetime of the memory allocated. Consider the statement below taken from the example: //MemSeg06: Local pointer storing the heap address and assigning a value to the heap int *pInt = new int; *pInt = 22; In the above statements, space required to store an integer value is allocated in the heap. The allocated address is stored in the variable pInt. The variable pInt is inside the main function and so the space for variable pInt is allocated in the stack holding address in the heap (Enough to store an integer). So when we go out of the function all the stack memory associated to it is cleared. But, the allocated heap becomes un attended or blocked stating in use. Because system will not clear it and programmer should do that. To clear that heap, before you lose the address in the stack for pInt, you should use the statement delete pInt. What happens if the above two statements are next to the comment MemSeg01 that is not inside any of the function? Well. Heap memory is stored in data segment variable pInt. Stack Memory Segment It is the memory segment where almost everybody declares and uses the variables. When you declare a variable inside the function that goes to the stack segment of the memory. All the stack segments wiped out once you go out of the function and when you come inside the some other function a new stack segment for that function is created. So this is a less costly segment as it lives till corresponding function returns back to the caller. Let us assume Program main calls the function A. Here first the Stack Segment for Main is created, then when you are inside the function A, main programs stack segment becomes un-accessible and at the same time stack segment for Function A is created. When the function A return the control to main program, stack segment for A is cleared and stack segment for program main (Still lives, it became temporarily un-accessible) becomes available. You can refer my previous post for detailed example about stack segment. In our example the below two statements in the main is created in stack segment: //MemSeg04: Declare a loval variable and declare a pointer and store the address of local variable int m = 12; int* pm = &m; Before we close Below is the Illustration of memory segment and variable involved in our sample. We know that a pointer can hold an address. In our example, Pm – is holding the address of memory in stack segment Pgx – is holding the address of the memory in the data segment Pint – is holding the address of the memory in the heap segment PFun – is holding the address of the memory (Starting address or base address of the void PrintNo(int x) ) in the code segment. Pfun? That is function pointer, I will write about it later. There is a nice movie in HBO, I will spend sometime there.
http://cppandmfc.blogspot.com/2011_10_01_archive.html
CC-MAIN-2017-30
refinedweb
1,333
59.03
On Jan 28, 2010, at 11:19 PM, Stefan Bodewig wrote: > On 2010-01-28, Matt Benson <gudnabrsam@gmail.com> wrote: > >> Okay,)}" /> > >> Now, programmatically, this type is ridiculously trivial: > >> public class ParsedResource extends ResourceDecorator { > >> public void setParse(Resource r) { >> addConfigured(r); > > If macrodef could be used to define types it could wrap around > > <resourcelist> > <string value="$${file(foo.txt)}"/> > </resourcelist> > > as well. Nice solution--I thought Peter had submitted a BZ report with a patch for macroing types, but I can't find it now. I had forgotten about resourcelist, but it does look like what you've proposed is a capable solution, and gives us the ability to do what I've suggested without having to create anything new. > >>. > > You know I'm not really into names ... > > My gut feeling is that there should be a way to do it with/by > extending > a built-in resource rather creating a new one. And then it occured to > me that the <property> resource would be a great fit. > > Maybe it would be better (from a naming perspective) if you could do > > <property name="file(foo.txt)"/> > > instead. I realize this would require bigger code changes. > Yeah, quite... although I think you've identified a--I hesitate to say "critical", but... "indisputable"--shortcoming in the current PropertyResource implementation in light of the recent PropertyHelper changes. I have to concede that it is perfectly reasonable to expect, given PropertyHelper's ability to resolve arbitrary Objects, that such a resolved property ought to transparently behave as the parsed Resource, including name and all other properties. I will code this ASAP and commit when I finish or after 1.8.0 is released, whichever is later. While I do think this behavior is a reasonable expectation once a user has thought of it, I wouldn't necessarily call it the most obvious think either, so another solution might still be in order. > The other idea I had was to add the functionality to the <resources> > resource collection, where the implementation would be as trivial as > shown in your code. > > <resource add="${file(foo.txt)}"/> > Your paragraph says <resources> but your example uses <resource>; I'm going to assume you mean the latter. <resource> is, of course, already available for using references. A solution using this approach might be to make ResourceDecorator concrete, add a resource property setter for XML attribute accessibility, redefine a ResourceDecorator to, by default, refer to itself and call super method implementations, and replace the <resource> definition in types/defaults.properties to point to ResourceDecorator instead of Resource. This way I think we would be able to overload the <resource> XML element to accept a property parsed resource in addition to the refid and brute-force property setting attributes already allowed. But such convoluted solution, though typical of me, I fear may elicit some controversy, so let the games begin! ;) -Matt > (now add becomes the name to talk about ...) > >> Finally, I'd be delighted if, once a nomenclature is settled upon, if >> the community said "hey, this is both trivial from a risk perspective >> yet potentially quite useful--let's include it in 1.8.0!", but I >> certainly won't insist upon it. ;) > > IIRC Antoine hinted he wanted to build 1.8.0 today, so it would be too > late anyway. > >
http://mail-archives.apache.org/mod_mbox/ant-dev/201001.mbox/%3C0ED054B4-AF7D-4441-9568-C1B0626E24B9@gmail.com%3E
CC-MAIN-2017-30
refinedweb
551
53
Hey Fellas, I was wondering if I could write a simple code that erases the input display information once a user enters it. For example, I was going to write a simple program that asks for the user's name and then have the trailing display information erased from the program. Here's the code that I wrote: When the user enters their information their screen would look like this:When the user enters their information their screen would look like this:Code:#include <iostream> using namespace std; int main () { char name [10]; cout << "May I have your name please?" << endl; cin >> name; cin.ignore(); cout << "Hey, " << name; cin.get(); return 0; } May I have your name please? You Hey, You ....so my question basically is how do I get rid of "May I have your name please?" so that it looks like this on their screen: Hey, You ____ Thanks in advance!
http://cboard.cprogramming.com/cplusplus-programming/73934-how-do-you-erase-display-information-once-%27s-been-entered-onto-screen.html
CC-MAIN-2014-23
refinedweb
153
80.41
#include "llvm/DebugInfo/GSYM/Header.h" The GSYM header. The GSYM header is found at the start of a stand alone GSYM file, or as the first bytes in a section when GSYM is contained in a section of an executable file (ELF, mach-o, COFF). The structure is encoded exactly as it appears in the structure definition with no gaps between members. Alignment should not change from system to system as the members were laid out so that they shouldn't align differently on different architectures. When endianness of the system loading a GSYM file matches, the file can be mmap'ed in and a pointer to the header can be cast to the first bytes of the file (stand alone GSYM file) or section data (GSYM in a section). When endianness is swapped, the Header::decode() function should be used to decode the header. Definition at line 45 of file Header.h. Check if a header is valid and return an error if anything is wrong. Check the header and detect any errors. This function can be used prior to encoding a header to ensure it is valid, or after decoding a header to ensure it is valid and supported. Check a correctly byte swapped header for errors: Definition at line 41 of file Header.cpp. References AddrOffSize, llvm::createStringError(), llvm::gsym::GSYM_MAGIC, llvm::gsym::GSYM_MAX_UUID_SIZE, llvm::gsym::GSYM_VERSION, Magic, llvm::Error::success(), UUIDSize, and Version. Decode an object from a binary data stream. Definition at line 64 of file Header.cpp. References llvm::createStringError(), llvm::Data, llvm::gsym::GSYM_MAX_UUID_SIZE, H, and Offset. Encode this object into FileWriter stream. Definition at line 85 of file Header.cpp. The size in bytes of each address offset in the address offsets table. Definition at line 56 of file Header.h. Referenced by checkForError(), llvm::gsym::GsymReader::dump(), llvm::gsym::GsymCreator::encode(), llvm::gsym::GsymReader::getAddress(), llvm::gsym::GsymReader::getAddressIndex(), and llvm::gsym::operator==(). The 64 bit base address that all address offsets in the address offsets table are relative to. Storing a full 64 bit address allows our address offsets table to be smaller on disk. Definition at line 62 of file Header.h. Referenced by llvm::gsym::GsymReader::addressForIndex(), llvm::gsym::GsymCreator::encode(), llvm::gsym::GsymReader::getAddressIndex(), and llvm::gsym::operator==(). The magic bytes should be set to GSYM_MAGIC. This helps detect if a file is a GSYM file by scanning the first 4 bytes of a file or section. This value might appear byte swapped Definition at line 49 of file Header.h. Referenced by checkForError(), llvm::gsym::GsymCreator::encode(), and llvm::gsym::operator==(). The number of addresses stored in the address offsets table. Definition at line 64 of file Header.h. Referenced by llvm::gsym::GsymReader::dump(), llvm::gsym::GsymCreator::encode(), llvm::gsym::GsymReader::getNumAddresses(), and llvm::gsym::operator==(). The file relative offset of the start of the string table for strings contained in the GSYM file. If the GSYM in contained in a stand alone file this will be the file offset of the start of the string table. If the GSYM is contained in a section within an executable file, this can be the offset of the first string used in the GSYM file and can possibly span one or more executable string tables. This allows the strings to share string tables in an ELF or mach-o file. Definition at line 72 of file Header.h. Referenced by llvm::gsym::GsymCreator::encode(), and llvm::gsym::operator==(). The size in bytes of the string table. For a stand alone GSYM file, this will be the exact size in bytes of the string table. When the GSYM data is in a section within an executable file, this size can span one or more sections that contains strings. This allows any strings that are already stored in the executable file to be re-used, and any extra strings could be added to another string table and the string table offset and size can be set to span all needed string tables. Definition at line 80 of file Header.h. Referenced by llvm::gsym::GsymCreator::encode(), and llvm::gsym::operator==(). The UUID of the original executable file. This is stored to allow matching a GSYM file to an executable file when symbolication is required. Only the first "UUIDSize" bytes of the UUID are valid. Any bytes in the UUID value that appear after the first UUIDSize bytes should be set to zero. Definition at line 86 of file Header.h. Referenced by llvm::gsym::GsymCreator::encode(), and llvm::gsym::operator==(). The size in bytes of the UUID encoded in the "UUID" member. Definition at line 58 of file Header.h. Referenced by checkForError(), llvm::gsym::GsymCreator::encode(), and llvm::gsym::operator==(). The version can number determines how the header is decoded and how each InfoType in FunctionInfo is encoded/decoded. As version numbers increase, "Magic" and "Version" members should always appear at offset zero and 4 respectively to ensure clients figure out if they can parse the format. Definition at line 54 of file Header.h. Referenced by checkForError(), llvm::gsym::GsymCreator::encode(), and llvm::gsym::operator==().
https://www.llvm.org/doxygen/structllvm_1_1gsym_1_1Header.html
CC-MAIN-2021-43
refinedweb
859
57.77
Date: Mon, 22 Jan 2001 22:33:02 -0500 From: Guido van Rossum (guido@digicool.com) To: python-list@python.org, python-dev@python.org Subject: [Python-Dev] Python 2.1 alpha 1 released! Thanks to the PythonLabs developers and the many hard-working volunteers, I'm proud to release Python 2.1a1 -- the first alpha release of Python version 2.1. The release mechanics are different than for previous releases: we're only releasing through SourceForge for now. The official source tarball is already available from the download page: Additional files will be released soon: a Windows installer, Linux RPMs, and documentation. Please give it a good try! The only way Python 2.1 can become a rock-solid product is if people test the alpha releases. Especially if you are using Python for demanding applications or on extreme platforms we are interested in hearing your feedback. Are you embedding Python or using threads? Please test your application using Python 2.1a1! Please submit all bug reports through SourceForge: Here's the NEWS file: What's New in Python 2.1 alpha 1? ================================= Core language, builtins, and interpreter - - There is a new Unicode companion to the PyObject_Str() API called PyObject_Unicode(). It behaves in the same way as the former, but assures that the returned value is an Unicode object (applying the usual coercion if necessary). - - The comparison operators support "rich comparison overloading" (PEP 207). C extension types can provide a rich comparison function in the new tp_richcompare slot in the type object. The cmp() function and the C function PyObject_Compare() first try the new rich comparison operators before trying the old 3-way comparison. There is also a new C API PyObject_RichCompare() (which also falls back on the old 3-way comparison, but does not constrain the outcome of the rich comparison to a Boolean result). The rich comparison function takes two objects (at least one of which is guaranteed to have the type that provided the function) and an integer indicating the opcode, which can be Py_LT, Py_LE, Py_EQ, Py_NE, Py_GT, Py_GE (for <, <=, ==, !=, >, >=), and returns a Python object, which may be NotImplemented (in which case the tp_compare slot function is used as a fallback, if defined). Classes can overload individual comparison operators by defining one or more of the methods__lt__, __le__, __eq__, __ne__, __gt__, __ge__. There are no explicit "reflected argument" versions of these; instead, __lt__ and __gt__ are each other's reflection, likewise for__le__ and __ge__; __eq__ and __ne__ are their own reflection (similar at the C level). No other implications are made; in particular, Python does not assume that == is the Boolean inverse of !=, or that < is the Boolean inverse of >=. This makes it possible to define types with partial orderings. Classes or types that want to implement (in)equality tests but not the ordering operators (i.e. unordered types) should implement == and !=, and raise an error for the ordering operators. It is possible to define types whose rich comparison results are not Boolean; e.g. a matrix type might want to return a matrix of bits for A < B, giving elementwise comparisons. Such types should ensure that any interpretation of their value in a Boolean context raises an exception, e.g. by defining __nonzero__ (or the tp_nonzero slot at the C level) to always raise an exception. - - Complex numbers use rich comparisons to define == and != but raise an exception for <, <=, > and >=. Unfortunately, this also means that cmp() of two complex numbers raises an exception when the two numbers differ. Since it is not mathematically meaningful to compare complex numbers except for equality, I hope that this doesn't break too much code. - - Functions and methods now support getting and setting arbitrarily named attributes (PEP 232). Functions have a new __dict__ (a.k.a. func_dict) which hold the function attributes. Methods get and set attributes on their underlying im_func. It is a TypeError to set an attribute on a bound method. - - The xrange() object implementation has been improved so that xrange(sys.maxint) can be used on 64-bit platforms. There's still a limitation that in this case len(xrange(sys.maxint)) can't be calculated, but the common idiom "for i in xrange(sys.maxint)" will work fine as long as the index i doesn't actually reach 2**31. (Python uses regular ints for sequence and string indices; fixing that is much more work.) - - Two changes to from...import: 1) "from M import X" now works even if M is not a real module; it's basically a getattr() operation with AttributeError exceptions changed into ImportError. 2) "from M import *" now looks for M.__all__ to decide which names to import; if M.__all__ doesn't exist, it uses M.__dict__.keys() but filters out names starting with '_' as before. Whether or not __all__ exists, there's no restriction on the type of M. - - File objects have a new method, xreadlines(). This is the fastest way to iterate over all lines in a file: for line in file.xreadlines(): ...do something to line... See the xreadlines module (mentioned below) for how to do this for other file-like objects. - - Even if you don't use file.xreadlines(), you may expect a speedup on line-by-line input. The file.readline() method has been optimized quite a bit in platform-specific ways: on systems (like Linux) that support flockfile(), getc_unlocked(), and funlockfile(), those are used by default. On systems (like Windows) without getc_unlocked(), a complicated (but still thread-safe) method using fgets() is used by default. You can force use of the fgets() method by #define'ing USE_FGETS_IN_GETLINE at build time (it may be faster than getc_unlocked()). You can force fgets() not to be used by #define'ing DONT_USE_FGETS_IN_GETLINE (this is the first thing to try if std test test_bufio.py fails -- and let us know if it does!). - - In addition, the fileinput module, while still slower than the other methods on most platforms, has been sped up too, by using file.readlines(sizehint). - - Support for run-time warnings has been added, including a new command line option (-W) to specify the disposition of warnings. See the description of the warnings module below. - - Extensive changes have been made to the coercion code. This mostly affects extension modules (which can now implement mixed-type numerical operators without having to use coercion), but occasionally, in boundary cases the coercion semantics have changed subtly. Since this was a terrible gray area of the language, this is considered an improvement. Also note that __rcmp__ is no longer supported -- instead of calling __rcmp__, __cmp__ is called with reflected arguments. - - In connection with the coercion changes, a new built-in singleton object, NotImplemented is defined. This can be returned for operations that wish to indicate they are not implemented for a particular combination of arguments. From C, this is Py_NotImplemented. - - The interpreter accepts now bytecode files on the command line even if they do not have a .pyc or .pyo extension. On Linux, after executing echo ':pyc:M::\x87\xc6\x0d\x0a::/usr/local/bin/python:' > /proc/sys/fs/binfmt _misc/register any byte code file can be used as an executable (i.e. as an argument to execve(2)). - - %[xXo] formats of negative Python longs now produce a sign character. In 1.6 and earlier, they never produced a sign, and raised an error if the value of the long was too large to fit in a Python int. In 2.0, they produced a sign if and only if too large to fit in an int. This was inconsistent across platforms (because the size of an int varies across platforms), and inconsistent with hex() and oct(). Example: >>> "%x" % -0x42_ '-42' # in 2.1 'ffffffbe' # in 2.0 and before, on 32-bit machines >>> hex(-0x42L) '-0x42L' # in all versions of Python The behavior of %d formats for negative Python longs remains the same as in 2.0 (although in 1.6 and before, they raised an error if the long didn't fit in a Python int). %u formats don't make sense for Python longs, but are allowed and treated the same as %d in 2.1. In 2.0, a negative long formatted via %u produced a sign if and only if too large to fit in an int. In 1.6 and earlier, a negative long formatted via %u raised an error if it was too big to fit in an int. - - Dictionary objects have an odd new method, popitem(). This removes an arbitrary item from the dictionary and returns it (in the form of a (key, value) pair). This can be useful for algorithms that use a dictionary as a bag of "to do" items and repeatedly need to pick one item. Such algorithms normally end up running in quadratic time; using popitem() they can usually be made to run in linear time. Standard library - - In the time module, the time argument to the functions strftime, localtime, gmtime, asctime and ctime is now optional, defaulting to the current time (in the local timezone). - - The ftplib module now defaults to passive mode, which is deemed a more useful default given that clients are often inside firewalls these days. Note that this could break if ftplib is used to connect to a *server* that is inside a firewall, from outside; this is expected to be a very rare situation. To fix that, you can call. - - The module site now treats .pth files not only for path configuration, but also supports extensions to the initialization code: Lines starting with import are executed. - - There's a new module, warnings, which implements a mechanism for issuing and filtering warnings. There are some new built-in exceptions that serve as warning categories, and a new command line option, -W, to control warnings (e.g. -Wi ignores all warnings, -We turns warnings into errors). warnings.warn(message[, category]) issues a warning message; this can also be called from C as PyErr_Warn(category, message). - - A new module xreadlines was added. This exports a single factory function, xreadlines(). The intention is that this code is the absolutely fastest way to iterate over all lines in an open file(-like) object: import xreadlines for line in xreadlines.xreadlines(file): ...do something to line... This is equivalent to the previous the speed record holder using file.readlines(sizehint). Note that if file is a real file object (as opposed to a file-like object), this is equivalent: for line in file.xreadlines(): ...do something to line... - - The bisect module has new functions bisect_left, insort_left, bisect_right and insort_right. The old names bisect and insort are now aliases for bisect_right and insort_right. XXX_right and XXX_left methods differ in what happens when the new element compares equal to one or more elements already in the list: the XXX_left methods insert to the left, the XXX_right methods to the right. Code that doesn't care where equal elements end up should continue to use the old, short names ("bisect" and "insort"). - - The new curses.panel module wraps the panel library that forms part of SYSV curses and ncurses. Contributed by Thomas Gellekum. - - The SocketServer module now sets the allow_reuse_address flag by default in the TCPServer class. - - A new function, sys._getframe(), returns the stack frame pointer of the caller. This is intended only as a building block for higher-level mechanisms such as string interpolation. Build issues - - For Unix (and Unix-compatible) builds, configuration and building of extension modules is now greatly automated. Rather than having to edit the Modules/Setup file to indicate which modules should be built and where their include files and libraries are, a distutils-based setup.py script now takes care of building most extension modules. All extension modules built this way are built as shared libraries. Only a few modules that must be linked statically are still listed in the Setup file; you won't need to edit their configuration. - - Python should now build out of the box on Cygwin. If it doesn't, mail to Jason Tishler (jlt63 at users.sourceforge.net). - - Python now always uses its own (renamed) implementation of getopt() -- there's too much variation among C library getopt() implementations. - - C++ compilers are better supported; the CXX macro is always set to a C++ compiler if one is found. Windows changes - - select module: By default under Windows, a select() call can specify no more than 64 sockets. Python now boosts this Microsoft default to 512. If you need even more than that, see the MS docs (you'll need to #define FD_SETSIZE and recompile Python from source). - - Support for Windows 3.1, DOS and OS/2 is gone. The Lib/dos-8x3 subdirectory is no more! -- Guido van Rossum (home page:) Advertiser Disclosure:
https://www.linuxtoday.com/developer/2001012300220PS
CC-MAIN-2021-21
refinedweb
2,124
65.73
What is MRAA and UPM?. The way that MRAA abstracts the hardware is through a pin mapping at the user space level. So when you use MRAA, you need to set your platform so the mapping is done correctly for your specific board. A full list of supported boards can be found at. For example, if you want you can use a regular Arduino* board connected via USB to add sensors to a laptop, you can use the Arduino board as a sub-platform. You’d need to first flash the Arduino board with the StandardFirmata.ino sketch, and then add it as a sub-platform at the top of your code: mraa_add_subplatform(MRAA_GENERIC_FIRMATA, "/dev/ttyACM0"); An Arduino device is typically added as ttyACM0, but sometimes as ttyACM1 or higher. The easiest way to check is to enter: ls /dev/ttyACM* How do I use MRAA in Arduino Create*? You can use the MRAA APIs directly for added functionality or if you just prefer that. For example: void setup() { mraa_add_subplatform(MRAA_GENERIC_FIRMATA, "/dev/ttyS1"); pinMode(516, OUTPUT); } void loop() { digitalWrite(516, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(516, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second } And mraa_gpio_context gpio; void setup() { mraa_add_subplatform(MRAA_GENERIC_FIRMATA, "/dev/ttyS1"); gpio = mraa_gpio_init(516); mraa_gpio_dir(gpio, MRAA_GPIO_OUT); } void loop() { mraa_gpio_write(gpio, 1); // turn the LED on delay(1000); // wait for a second mraa_gpio_write(gpio, 0); // turn the LED off delay(1000); // wait for a second } Do the same thing. Take note of the following: Subplatforms still need to be added using mraa_add_subplatform even if you’re using the Arduino API If using the MRAA API you need to set mraa_gpio_context and initialize gpio = mraa_gpio_init(516), this is already taken care of for you using the Arduino API To see another example using mraa, see this tutorial. The MRAA github repository includes lots of examples and that can be ported to Arduino Create. How do I use UPM in Arduino Create*? In order for any UPM library to work, you need to include the header file corresponding to that particular sensor. Unfortunately, if you search for the library in Arduino Create and include it, all the UPM sensor libraries will be included, and you probably only need one or two. The solution is to find your sensor first in the list Then copy the name of the .h file. At the top of your sketch include it, for example: #include <jhd1313m1.h> To see how it’s instantiated see A more generic example can be found here: For more such intel IoT resources and tools from Intel, please visit the Intel® Developer Zone
https://www.digit.in/features/apps/mraa-and-upm-basics-in-arduino-create-38129.html
CC-MAIN-2019-26
refinedweb
454
55.78
#include <bsm/libbsm.h> The setauevent() function resets the database access session for audit_event(5), so that the next call to getauevent() will start with the first entry in the database. The endauevent() function closes the audit_event(5) database session. The getauevent() function returns a reference to the next entry in the audit_event(5) database. The getauevnam() function returns a reference to the entry in the audit_event(5) database with a name of name. getauevnum() returns a reference to the entry in the audit_event(5) database with an event number of event_number. The getauevnonam() function returns a reference to an audit event number using the audit_event(5) database. The Basic Security Module (BSM) interface to audit records and audit event stream format were defined by Sun Microsystems. These routines are thread-safe, but not re-entrant, so simultaneous or interleaved use of these functions will affect the iterator. Please direct any comments about this manual page service to Ben Bullock. Privacy policy.
https://nxmnpg.lemoda.net/3/getauevnonam
CC-MAIN-2020-05
refinedweb
162
54.32
NAME Bot::Infobot - a Bot::BasicBot::Pluggable based replacement for the venerable infobot USAGE First write a config file (see below for details of the format) making sure that you have a [ Store ] section. Then run % infobot-import <dsn> <username> <password> and sit back and watch the show. This can take anything from 5 minutes to 6 hours depending on size of the brain and the store method (Storable is fastest, then then the DBM::Deep based Deep driver and then DBI). Finally just type % infobot in the same directory and everything will just work. Probably. CONFIG The infobot and Bot::Infobot::Config documentation have more information but, essentially you have a main namespace and then sub namespaces for the different plugins including one special Store namespace for configuring the store. You can get a list of config values for the bot on the infobot manpage but the minimum config you should have to get yourself up and running are something like nick = mybotsnick server = irc.perl.org channels = #bottest [ Store ] type = Storable The format is .ini style and currently there's no way to pass in an alternative config file but there probably should be. DESCRIPTION After hacking in a couple of features to dipsy, #london.pm's slightly loopy infobot I felt, well, dirty. The infobt code is horrible to the point of profane depravity. The next wednesday, burdened with a monster hangover and a thorny problem percolating through my brain I hacked up a quick Bot::BasicBot::Pluggable framework as a replacement and played with porting the various plugins I could find over to this new, shiny way of doing anythings. A few sprinkled hours later and I'd done pretty much everything and began to write a brain slurper to import the distilled wisdom of 5 odd years of ramblings. Along the way there was various bits of Yak Shaving. Some of the results of that are up on CPAN. The original patches that inspired this are here - VERSION CONTROL The master repository for this code is at AUTHOR Simon Wistow <simon@thegestalt.org> Distributed under the same terms as Perl itself. SEE ALSO Bot:::BasicBot::Pluggable, Bot::Infobot::Config, infobot, infobot-import,
https://metacpan.org/pod/distribution/Bot-Infobot/lib/Bot/Infobot.pod
CC-MAIN-2018-17
refinedweb
367
60.45
having issue with stack using linked list. 1) the num didnt give any value tho with the cout in count() 2) how to return string from pop()? i tried many ways like return ptr->s and stuff but didnt work could anyone pls point out where my mistake is? thanks heaps! header file Code:class Element{ public: std::string s; Element *next; }; Element * start = NULL; class Stack { public: //temporary pointer Element * ptr, *ptr2; unsigned long num; Stack(); ~Stack(); void push(std::string n); unsigned long count(); std::string pop(); }; cpp.file Code:#include <iostream> #include <string> #include <stdlib.h> #include "stack.h" using namespace std; Stack::Stack(){ num = 0; } void Stack :: push(std::string n){ ptr = new Element; //create space ptr->s = n; // pointing at string ptr->next = NULL; if (start == NULL){ //empty start = ptr;} //ptr and start pointing at the same spot else{ //if start already has element ptr2 = start; while (ptr2->next != NULL){ ptr2 = ptr2->next; // keep moving to next element } //if next element is null,add new element ptr2->next = ptr; num++; } /*cout << ptr->s << endl;*/ } std:: string Stack::pop(){ //pop until stack is empty std::string n2 = ptr->s ; if ( start != NULL ){ ptr = start; //if next element where ptr is pointing is null,delete current ptr if (ptr->next == NULL){ delete ptr; start = NULL; } else { while (ptr->next != NULL){ ptr2 = ptr; ptr = ptr->next;} delete ptr; ptr2->next = NULL; } num--; } cout << n2 << endl; return n2; } unsigned long Stack::count(){ cout << num; return num; } Stack :: ~Stack () { while (start != NULL){ Element* temp = start; start = start->next; delete temp; } } int main(){ Stack s; s.push("Hello"); s.push("world"); s.pop(); s.pop(); }
http://cboard.cprogramming.com/cplusplus-programming/119647-stack-using-linked-list-problem.html
CC-MAIN-2015-32
refinedweb
274
74.93
How to create a static archive library in C++ (G++) Get FREE domain for 1st year and build your brand new site To create a static or archive library in C++ using G++, compile the C++ library code using GCC/ G++ to object file and convert the object file to archive file using ar. The code can be converted to executable by linking the archive file using G++. // Convert library code to Object file g++ -c -o library.o library.c // Create archive file/ static library ar rcs library.a library.o Archive library is to transfer the library code to the executable so that the executable does not depend on external library dependencies. This increases the size of the executable. There are four steps: Compile C++ library code to object file (using g++) Create archive file using object file (ar) Compile the C++ code using the header library file using the archive library (using g++) Run the executable (using a.out) Step 1: Compile C code to object file gcc -c -o code.o code.c - Step 2: Create archive file using object file ar rcs library.a code.o ar is an utility that is used to create, modify and extract archive files. The "rcs" signify the following: r: insert object file by replacing existing code c: create new archive file s: write an index Step 3: Compile C++ code g++ -std=c++14 code.cpp library.a - Step 4: Run the archive code ./a.out This involves four major files: - library.hpp: Library header file - library.cpp: Library C++ file - library.o: Object file of library.cpp - library.a: Archive file/ static library of the above library - code.cpp: C++ code using the library through header file - a.out: executable Example In this example, we will create a C++ library and use it in a C++ code. We will build our library as an archive: ar rcs library.a library.o Using the library #include <stdio.h> #include "library.hpp" int main ( void ) { print_value(10); return 0; } Create the executable: g++ -std=c++14 code.cpp library.a This will create the executable a.out which will run on any compatible machine without the header/ library files as we have inserted the library file within the executable. ./a.out With this, we have created an archive file and generated an executable using it. Enjoy.
https://iq.opengenus.org/create-archive-library-in-cpp/
CC-MAIN-2021-17
refinedweb
397
65.73
Today, we are excited to introduce HorovodRunner in our Databricks Runtime 5.0 ML! HorovodRunner provides a simple way to scale up your deep learning training workloads from a single machine to large clusters, reducing overall training time. Motivated by the needs of many of our users who want to train deep learning models on datasets that do not fit on a single machine and reduce overall training time, HorovodRunner addresses this requirement by distributing training across your clusters, hence processing more data per second and decreasing the training time from hours to minutes. As part of an effort to integrate distributed deep learning with Apache Spark, leveraging Project Hydrogen, HorovodRunner utilizes barrier execution mode introduced in Apache Spark 2.4. This new model of execution is different from the generic Spark execution model and is catered to distributed training in its fault-tolerance needs and modes of communication between tasks on each worker node in the cluster. In this blog, we describe HorovodRunner and how you can use HorovodRunner’s simple API to train your deep learning model in a distributed fashion, letting Apache Spark handle all the coordination and communication among tasks on each worker node in the cluster. HorovodRunner’s Simple API Horovod, Uber’s open source distributed training framework, supports TensorFlow, Keras, and PyTorch. HorovodRunner, built on top of Horovod, inherits the support of these deep learning frameworks and makes it much easier to run. Under the hood, HorovodRunner shares code and libraries across machines, configures SSH, and executes the complicated MPI commands required for distributed training. As result, data scientists are freed from the burden of operational requirements and can now focus on tasks at hand—building models, experimenting, and deploying them to production quickly. Also, HorovodRunner provides a simple interface that allows you to easily distribute your workloads on a cluster. For example, the snippet below runs the train function on 4 worker machines. This can help you achieve good scaling of your workloads, accelerate model experimenting, and shorten the time to production. from sparkdl import HorovodRunner hr = HorovodRunner(np=4) hr.run(train, batch_size=512, epochs=5) The train method below contains the Horovod training code. The sample code outlines the small changes to your single-node workloads to use Horovod. With a few lines of code changes and using HorovodRunner, you can start leveraging the power of a cluster in a matter of minutes. import horovod.keras as hvd import keras def train(batch_size=512, epochs=12): # initialize horovod here hvd.init() model = get_model() # split your training and testing data based on # Horovod rank and size (x_train, y_train), (x_test, y_test) = get_data(hvd.rank(), hvd.size()) opt = keras.optimizers.Adadelta() # Overwrite your optimizer with Horovod Distributed Optimizer opt = hvd.DistributedOptimizer(opt) # compile your model model.compile(loss=keras.losses.categorical_crossentropy,optimizer=opt, metrics[‘accuracy’]) # fit the model model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=2, validation_data=(x_test, y_test)) Integrated Workflow on Databricks HorovodRunner launches Horovod training jobs as Spark jobs. So your development workflow is exactly the same as other Spark jobs on Databricks. For example, you can check training logs from Spark UI as shown in the animated Fig 1. below. Or you can just as easily trace the error back to a notebook cell and code as shown in animated Fig 2. here. Tools like TensorBoard and Horovod Timeline are also supported within Databricks. To get started, check out example notebooks to classify MNIST dataset using TensorFlow, Keras, or PyTorch in Databricks Runtime 5.0 ML! To migrate your single node workloads to a distributed setting, you can simply follow the steps outlined in this documentation. Try Databricks today with Apache Spark 2.4 and Databricks Runtime 5.0. - Read about HorovodRunner Documentation - Listen to the Project Hydrogen: State of the Art Deep Learning on Apache Spark webinar - Find out more about Databricks Runtime 5.0 ML Get more info on Horovod and HorovodEstimator
https://databricks.com/blog/2018/11/19/introducing-horovodrunner-for-distributed-deep-learning-training.html
CC-MAIN-2021-39
refinedweb
655
53.21
For forums, blogs and more please visit our Developer Tools Community. By: Nick Hodges Abstract: This article describes the capabilities of developing for Mono using Delphi Prism Delphi Prism provides support for compiling code against multiple CLR platforms, including Mono for Linux and for the Mac. If it can be done in Mono, it can be done with Delphi Prism. This article covers the basics of working with Mono and what you can expect when using Delphi Prism. Delphi Prism produces pure Intermediate Language (IL) code for running on the Common Language Runtime (CLR). Since Mono implements the CLR, Delphi Prism applications will fully support the Mono platform. Therefore, Delphi Prism developers can deploy their applications to anywhere that the Mono platform is present. In as much as the Mono platform supports IL and the CLR, Delphi Prism code will run. Hide imageMono is a third-party set of libraries that need to be present for developing and deploying Mono applications. Mono is available for numerous platforms and can be found at The Mono Project. To develop Mono-based projects with Delphi Prism, Mono for Windows should be installed along side Delphi Prism, and Mono-based applications need to be made aware of the specific location of the Mono binaries. Unless specifically deselected, Mono is installed as part of the Delphi Prism installation and is installed by default in the C:\Program Files\Mono-2.0.1 directory. Delphi Prism supports the full capabilities of the Mono framework on whatever platform it is found. Developers should note that there are differences between the features and capabilities of the Mono platform and those of Microsoft’s .NET implementation on Windows. Generally, developers will need to test their applications very carefully to ensure that resources that they need are available. Thus, if Mono doesn’t support a given call, method or namespace, then code that requires those resources will not run. Delphi Prism developers are strongly encouraged to use the Mono Migration Analyzer (MoMA) tool to determine how well as a given application built with Mono in mind will run on non-Windows platforms and what specific areas need to be adjusted in order for that application to run properly on Mono. Because Delphi Prism produces standard, IL-based assemblies, developers can partition code into different binaries, making it easy to share code between Mac, Windows, and Linux versions of an application. Using proper MVC partitioning, the user interface code can be made specific to different operating systems and user interface frameworks and toolkits. Since Mono is an implementation of the CLR, it differs from the .NET framework. With respect to Mono, .NET can be viewed as Microsoft’s implementation of the CLR on Windows. Mono for Windows exists, but mainly as a supplement to .NET. Mono itself implements large portions of the CLR, mainly on Linus and Mac OS X. However, Mono is not as complete an implementation of the CLR as .NET is, and thus Mono has some limitations in the support it provides for the CLR. Below is a chart that discusses some of these limitations, and how each framework in Delphi Prism and the CLR are supported by Mono on Linux and the Mac. Feature Mono for Linux Mono for the Mac Compiler Since the compiler is itself a managed code binary, it will run on the Mono for Linux framework. Since the compiler is itself a managed code binary, it will run on the Mono for Mac framework. Command Line/Server/Daemon Apps Prism apps of this sort should work just fine with Mono on Linux. Prism apps of this sort should work just fine with Mono on the Mac Debugging Applications meant for deployment on Mono for Linux are best debugged while running on Windows as much as is possible. Mac OS X applications cannot be run inside Visual Studio, but developers can properly decouple code and then run and debug Model and Controller code on Windows. dbExpress dbExpress is bound to Windows and the Windows database clients, and thus applications using dbExpress won’t run on Mono. However, Mono supports ADO.NET, and thus Delphi Prism developers can access data that way. ASP.NET Delphi Prism applications built for ASP.NET will run on Mono for Linux and Apache utilizing the mod_mono plugin. In addition, Mono on Linux provides the xsp2 executables are available for debugging. ASP.NET applications built with Delphi Prism should run on Mono for Mac and Apache utilizing the mod_mono plugin. More information can be found on the ASP.NET for Mono page. WinForms Winforms is supported on Mono for Linux. Many applications will run without modification, but others will require some developer work to run. See for more information. Developers can also use the Mono Migration Analyzer (MoMA) tool mentioned above to determine how well a given application will run on Mono and what specific areas need to be adjusted. Mono for the Mac provides support for Winforms, but that support is currently in its early stages and should be considered no better than alpha quality. Developers should also note that a Winforms application will not appear like a “normal” Mac application. Windows Presentation Foundation (WPF) WPF is not supported on the Mono for Linux platform. WPF is not supported on the Mono for Mac platform. Silverlight Mono implements a project called “Moonlight” in cooperation with Microsoft and Delphi Prism applications can execute against that framework. It is currently in alpha stage. Silverlight is officially supported by Microsoft on the Mac OS X platform. Windows Communication Foundation (WCF) Mono has a project called Olive that is in its early stages of support for WCF. Mono has a project called Olive that is in its early stages of support for WCF. Delphi Prism provides specific support for developing for Mac OS X. The standard user interface framework for Mac OS X is Cocoa. Cocoa is a collection of frameworks, APIs, and accompanying runtimes that make up the development layer of Mac OS X. Mono includes a wrapper around the key classes of Cocoa called Cocoa#. The file containing that wrapper is cocoa-sharp.dll and is part of the Mono framework. Delphi Prism developers can make use of the Cocoa# framework to provide interaction between Hide imageDelphi Prism classes and user interface files created for Cocoa with Interface Builder. Interface Builder is a user interface design tool included with Mac OS X. Delphi Prism includes templates and support for building applications against the Cocoa# framework. Cocoa utilizes the “Model-View-Controller” method of development. Developers can build a “View” using Interface Builder and then use Delphi Prism to provide the “Model” and “Controller” portions of an application. Delphi Prism will also automatically generate all the necessary “glue” code for the files generated by Interface Builder. For example, if a button is added to the interface using Interface Builder, Prism will see that and generate the proper code in the partial class in the associated file in Delphi Prism. These features make for a very powerful and capable development experience on the Mac when using Delphi Prism. Note, as well, that while it is possible to use Delphi Prism to develop .NET Winforms applications that will run on OS X, such applications will lack the native ‘look and feel’ of applications created with Apple’s Cocoa UI frameworks. In addition, Delphi Prism provides “MacPack” -- package deployment for Mac applications, which wraps up all the necessary files for deployment and puts them in a shared network location for easy execution on the Mac machine. Probably the simplest way to develop Delphi Prism applications for OS X is to install Windows in a virtual machine such as Parallels or VMWare Fusion on a Mac computer, and ensure that a shared file location on the Mac is visible to the Windows virtual machine. Or, developers can place application inside of a network share that resides on a Mac machine, and then run the application from the Mac. Developers should remember that the resulting application will, in fact, be a Mac OSX application and thus won’t run on Windows as Cocoa is not available on Windows. Hide image Figure 3 -- A Delphi Prism application inside of Mac OS X A tutorial and thorough discussion of using Prism to build applications for Cocoa and the Mac can be found here: Creating Cocoa# applications for the Mac using Delphi Prism Delphi Prism provides full support for developing on Mono – including code generation and deployment assistance for the Mac. While that support is limited to the capabilities of Mono itself, overall, Delphi Prism is an excellent tool for supporting Mono development. And as Mono’s capabilities and support for the CLR grows from its already considerable capabilities, so will Delphi Prism’s support for it. Server Response from: ETNASC03
http://edn.embarcadero.com/article/39017
CC-MAIN-2019-39
refinedweb
1,471
52.9