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
#include <EBISLevel.H> Defines the level. Calls the geoserver to fill the layout with geometric information. Defines the level from a finer level (factor of two refinement ratio). Fills in all the coarse-fine information in both levels. read from file from top level only file writes the given level for writeAllLevels Checks to see the vofs are in the correct cells. Checks to see that the faces are over the correct cells. Checks that volume fractions, area fractions are positive. Bail out with MayDay::Error if anything fails. References m_tolerance. References D_TERM6, and m_tolerance. whether this has higher order moment info
http://davis.lbl.gov/Manuals/CHOMBO-RELEASE-3.2/classEBISLevel.html
CC-MAIN-2020-50
refinedweb
102
69.89
CSortedListCtrl reusable base class WEBINAR: On-Demand How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 I found several articles about sorting a CListCtrl, adding visual feedback in the header... on the codeguru page and I have encapsulated this into a reusable base class CSortedListCtrl that encapsulates code from several other articles. With this class, the user doesn't have to care about all this sorting stuff, header control, sorting callback... He just has to override some virtual routines to implement its sorting algorithm. The Zip file contains a Word 97 DOC for the documentation (ed. which is duplicated here), the SortedListCtrl project encapsulating all the code from previous articles and a project (TestListCtrl) showing how to use the CSortedListCtrl class. It has been compiled with Visual Studio 97. I hope this will be useful to other programmers just like the articles on the CodeGuru page were for me. Introduction This is a reusable CSortedListCtrl class based on several articles from the ListView Control section of CodeGuru : - "Indicating sort order in header control - Zafir Anjum" - "Sorting the list when user clicks on column header - Zafir Anjum" - "Vertical lines for column borders - Zafir Anjum" How to use the class I have put all the CSortedListCtrl stuff in a separate library file so I can use it from all my projects. To use the class, you need the "SortedListCtrl" project which will produce a library. Insert this project into your project (in the sample, I have used a Dialog based app called TestListCtrl) that will be using the CSortedListCtrl and set a dependency so it will recompile automatically. CSortedListCtrl acts as a base class like CDialog. So you will need to derive your own class : let's say CMyListCtrl. You can make it using Class Wizard : you drop a CListCtrl on your dialog box, set it in report mode and add a class CMyListCtrl setting CListCtrl as a base class but you will have to change CListCtrl into CSortedListCtrl in Wizard generated code (in .h and message map) You will also need to #include "SortedListCtrl.h", add an additional include directory (the SortedListCtrl directory) in the project settings, define a variable for your list control (m_ListCtrl in the example) and set its type to CMyListCtrl (not CListCtrl). I use a ListCtrl with two columns and no image. Let's say a column Name of type string and a column Number of type integer to illustrate the sorting routine with two different types. You need to build the list columns in the OnInitDialog routine. To clearly show the code added, this is done in an ExtraInit function called from OnInitDialog : void CTestListCtrlDlg::ExtraInit() { CRect Rect1; m_ListCtrl.GetWindowRect(Rect1); int cx = (Rect1.Width() - 4) >> 1; m_ListCtrl.InsertColumn(0, "Name", LVCFMT_LEFT, cx); m_ListCtrl.InsertColumn(1, "Number", LVCFMT_LEFT, cx); FillList(); // Add full row selection to listctrl m_ListCtrl.SetFullRowSel(TRUE); // Sort the list according to the Name column m_ListCtrl.SortColumn(0, TRUE); } SetFullRowSel is a method of CSortedListCtrl that allows to select the entire line, not only the first column while the SortColumn method allows you to sort the list on a given column and choosing ascending or descending order (sorting mechanism is explained later). Now let's have a look at the FillList routine : void CTestListCtrlDlg::FillList() { CMyItemInfo *pItemInfo; int iItem = 0; CString Name; int Number; Name = "Sharon Stone";); iItem++; Name = "Julia Roberts";); } It just fills the list with two items but won't compile yet because it needs another class used by the sorting mechanism. Sorting the list using the standard mechanism provided by CListCtrl requires that you attach some item data to your items because what will be given to you in the compare routine (see later) will be pointers to these item data. In order to hide the callback mechanism used by CListCtrl and be able to use polymorphism, the data attached to the item is encapsulated in a class. I give you a base class CitemInfo from which you can derive your own class, let's say CMyItemInfo. You can do this with class wizard, specifying a generic class deriving publicly from CItemInfo (ItemInfo.h is provided in the SortedListCtrl project). You will have to do some #includes with ItemInfo.h and MyItemInfo.h. Now, you can just add some class members, constructor and methods to your MyItemInfo class to set and retrieve easily information. To make it easy, I have put everything in the MyItemInfo.h file : #include "ItemInfo.h" class CMyItemInfo : public CItemInfo { public: CMyItemInfo(int iItem, CString& Name, int Number) : CItemInfo(iItem), m_Name(Name), m_Number(Number) {m_NumberAsString.Format("%d",Number); }; virtual ~CMyItemInfo() {}; CString& GetName() {return m_Name;} int GetNumber() {return m_Number;} CString& GetNumberAsString() {return m_NumberAsString;} private: CMyItemInfo(); CString m_Name; CString m_NumberAsString; int m_Number; }; The basic idea for the sort to work is to put the data inside the MyItemInfo class which will be passed to the comparison routine. In order not to duplicate data (it's a time/space compromise choice here), the LPSTR_TEXTCALLBACK is used. To make it work, you must add the following line in MyListCtrl.h : afx_msg void OnGetDispInfo(NMHDR* pNMHDR, LRESULT* pResult); and the following one in the message map of MyListCtrl.cpp : ON_NOTIFY_REFLECT(LVN_GETDISPINFO, OnGetDispInfo) Then, you have to implement the OnGetDispInfo routine : void CMyListCtrl::OnGetDispInfo(NMHDR* pNMHDR, LRESULT* pResult) { LV_DISPINFO* pDispInfo = (LV_DISPINFO*)pNMHDR; if (pDispInfo->item.mask & LVIF_TEXT) { CMyItemInfo* pAppItem = reinterpret_cast (pDispInfo->item.lParam); switch (pDispInfo->item.iSubItem) { case 0 : lstrcpy (pDispInfo->item.pszText, pAppItem->GetName()); break; case 1 : lstrcpy (pDispInfo->item.pszText, pAppItem->GetNumberAsString()); break; } } *pResult = 0; } It's not finished yet ! You have to give a correct constructor for the CMyListCtrl class : CMyListCtrl::CMyListCtrl() : CSortedListCtrl(TRUE, TRUE) { } The first constructor parameter tells the base class if you want to sort the column (it's normally what you want here !) and the second parameter informs the base class to handle the deletion of the item data itself. In fact, if you remember the code in FillList, we allocate objects of type CMyItemInfo on the heap to attach to the list items. When elements of the list are deleted, these MyItemInfo must be also deleted and the base class can do it for you. This is possible because CMyItemInfo derives from ItemInfo and the CItemInfo destructor is virtual. Now, we must still provide a comparison routine : this is done by overridding a virtual function from CSortedListCtrl that is used to sort the elements in the list. This is just an OO translation of the callback mechanism used by the standard control that's now hidden in the base class. Just add the following method declaration in your MyListCtrl.h file : int CompareItems(CItemInfo *pItemInfo1, CItemInfo *pItemInfo2); and the following definition in the MyListCtrl.cpp file : int CMyListCtrl::CompareItems(CItemInfo *pItemInfo1, CItemInfo *pItemInfo2) { CMyItemInfo *pInfo1 = static_cast (pItemInfo1); CMyItemInfo *pInfo2 = static_cast (pItemInfo2); int nResult; switch (GetSortedColumn()) { case 0 : // Sort on column 'Name' nResult = pInfo1->GetName().CompareNoCase(pInfo2->GetName()); break; case 1 : // Sort on column 'Number' { int Number1 = pInfo1->GetNumber(); int Number2 = pInfo2->GetNumber(); if (Number1 < Number2) { nResult = -1; } else { nResult = (Number1 != Number2); } break; } default : nResult = 0; break; } return IsAscSorted() ? nResult : -nResult; } In fact, this function will be called for each pair of item in the list that must be compared and you receive as parameters, the item data attached to each of the element (I will describe below how to attach these ItemInfo to the list items). In this function, you are likely to use two functions from the base class : GetSortedColumn and IsAscSorted which are telling you respectively the column to be sorted and the sort order (ascending or descending). The return value has the same semantic as the callback routine from CListCtrl or the strcmp functions (-1, 0 or 1). Note also the safe static_cast here because CMyItemInfo inherits from CItemInfo. That's all folks ! Last updated: 6 June 1998
https://www.codeguru.com/cpp/controls/listview/miscellanious/article.php/c971/CSortedListCtrl-reusable-base-class.htm
CC-MAIN-2018-05
refinedweb
1,303
52.49
CSS is a technology that can be your best or worst friend. While it's incredibly flexible and can produce what seems like magic, without the proper care and attention, it can become hard to manage like any other code. How can Tailwind CSS help us to take control of our styles? - What is Tailwind? - So what makes Tailwind great? - Part 1: Adding Tailwind CSS to a static HTML page - Part 2: Adding Tailwind CSS to a React app What is Tailwind? Tailwind CSS is a "utility-first" CSS framework that provides a deep catalog of CSS classes and tools that lets you easily get started styling your website or application. The underlying goal is that as you're building your project, you don't need to deal with cascading styles and worrying about how to override that 10-selector pileup that's been haunting your app for the last 2 years. So what makes Tailwind great? Taildwind's solution is to provide a wide variety of CSS classes that each have their own focused use. Instead of a class called .btn that is created with a bunch of CSS attributes directly, in Tailwind, you would either apply a bunch of classes like bg-blue-500 py-2 px-4 rounded to the button element or build a .btn class by applying those utility class to that selector. While Tailwind has a lot more going for it, we're going to focus on these basics for this tutorial, so let's dig in! Part 1: Adding Tailwind CSS to a static HTML page We're going to start off by applying Tailwind CSS straight to a static HTML page. The hope is that by focusing on Tailwind and not the app, we can get a better understanding of what's actually happening with the framework. Step 1: Creating a new page You can get started by simply creating a new HTML file. For the content, you can use whatever you want, but I'm going to use fillerama.io so the filler content is a bit more fun. If you want to simplify this step, you can just copy the file I created to get started. Follow along with the commit! Step 2: Adding Tailwind CSS via CDN Tailwind typically recommends that you install through npm to get the full functionality, but again, we're just trying to understand how this works first. So let's add a link to the CDN file in the <head> of our document: <link href="^1.0/dist/tailwind.min.css" rel="stylesheet"> Once you save and reload the page, the first thing you'll notice is that all of the styles were stripped! This is expected. Tailwind includes a set of preflight styles to fix cross-browser inconsistencies. For one, they include the popular normalize.css which they build upon with their own styles. But we're going to learn how to use Tailwind to add back our styles and set things up how we want! Follow along with the commit! Step 3: Using Tailwind CSS to add styles to your page Now that we have Tailwind installed, we've added the ability to make use of their huge library of utility classes that we'll now use to add styles back to our page. Let's start off by adding some margin to all of our paragraphs ( <p>) and our list elements ( <ol>, <ul>). We can do this by adding the .my-5 class to each element like so: <p class="my-5"> Bender, quit destroying the universe! Yeah, I do that with my stupidness. I never loved you. Moving along… Belligerent and numerous. </p> The class name follows a pattern that you'll notice with the rest of the utility classes – .my-5 stands for margin (m) applied to the y-axis (y) with a value of 5 which in Tailwind's case, it uses rem, so the value is 5rem. Next, let's make our headers look like actual headers. Starting with our h1 tag, let's add: <h1 class="text-2xl font-bold mt-8 mb-5"> Here's what's happening: text-2xl: set the text size (font-size) to 2xl. In Tailwind, that 2xl will equate to 1.5rem font-bold: set the weight of the text (font-weight) to bold mt-8: Similar to my-5, this will set the margin top (t) to 8rem mb-5: And this will set the margin bottom (b) to 5rem With those classes added to the h1, let's apply those same exact classes to the rest of our header elements, but as we go down the list, reduce the size of the font size, so it will look like: - h2: text-xl - h3: text-lg Now let's make our list elements look like lists. Starting with our unordered list ( <ul>), let's add these classes: <ul class="list-disc list-inside my-5 pl-2"> Here's what we're adding: list-disc: set the list-style-stype to disc (the markers on each line item) list-inside: sets the position of the list markers using relative to the list items and the list itself with list-style-position to inside my-5: set the margin of the y axis to 5rem pl-2: set the left padding to 2rem Then we can apply the exact same classes to our ordered list ( <ol>), except instead of list-disc, we want to change our style type to list-decimal, so that we can see numbers given it's an ordered list. <ol class="list-decimal list-inside my-5 pl-2"> And we have our lists! Finally, let's make our content a little easier to read by setting a max width and centering the content. On the <body> tag, add the following: <body class="max-w-4xl mx-auto"> /Note: Typically you wouldn't want to apply these classes to the <body> itself, rather, you can wrap all of your content with a <main> tag, but since we're just trying to get an idea of how this works, we'll roll with this. Feel free to add the <main> tag with those classes instead if you prefer!/ And with that, we have our page! Follow along with the commit! Step 4: Adding a button and other components For the last part of our static example, let's add a button. The trick with Tailwind, is they intentionally don't provide pre-baked component classes with the idea being that likely people would need to override these components anyways to make them look how they wanted. So that means, we're going to have to create our own using the utility classes! First, let's add a new button. Somewhere on the page, add the following snippet. I'm going to add it right below the first paragraph ( <p>) tag: <button>Party with Slurm!</button> You'll notice just like all of the other elements, that it's unstyled, however, if you try clicking it, you'll notice it still has the click actions. So let's make it look like a button. Let's add the following classes: <button class="text-white font-bold bg-purple-700 hover:bg-purple-800 py-2 px-4 rounded"> Party with Slurm! </button> Here's a breakdown of what's happening: text-white: we're setting our text color to white font-bold: set the weight of the text to bold (font-weight) bg-purple-700: set the background color of the button to purple with a shade of 700. The 700 is relative to the other colors defined as purple, you can find these values on their palette documentation page hover:bg-purple-800: when someone hovers over the button, set the background color to purple shade 800. Tailwind provides these helper classes that allow us to easily define interactive stiles with things like hover, focus, and active modifiers py-2: set the padding of the y-axis to 2rem px-4: set the padding of the x-axis to 4rem rounded: round the corners of the element by setting the border radius. With tailwind, it sets the border-radius value to .25rem And with all of that, we have our button! You can apply this methodology to any other component that you'd like to build. Though it's a manual process, we'll find out how we can make this process easier when building in more dynamic projects like those based on React. Follow along with the commit! Part 2: Adding Tailwind CSS to a React app For more of a real-world use case, we're going to add Tailwind CSS to an app created with Create React App. First, we'll walk through the steps you need to take to add tailwind to your project using a fresh install of Create React App, then we'll use our content from our last example to recreate it in React. Step 1: Spinning up a new React app I'm not going to detail this step out too much. The gist is we'll bootstrap a new React app using Create React App. To get started, you can follow along with the directions from the official React documentation: And once you start your development server, you should now see an app! Finally, let's migrate all of our old content to our app. To do this, copy everything inside of the <body> tag of our static example and paste it inside of the wrapper <div className="App"> in the new React project. Next, change all class=" attributes from the content we pasted in to className=" so that it's using proper React attributes: And lastly, replace the className App on our wrapper <div> to the classes we used on our static <body>. Once you save your changes and spin back up your server, it will look deceivingly okay. React includes some basic styles itself, so while it looks okay, we're not actually using Tailwind yet. So let's get started by installing it! Follow along with the commit! Step 2: Installing Tailwind in your React app There are a few steps we'll need to go through in order to get Tailwind up and running on our app. Make sure you follow these steps carefully to ensure it's properly configured. First, let's add our dependencies: yarn add tailwindcss postcss-cli autoprefixer # or npm install tailwindcss postcss-cli autoprefixer Per Tailwind's documentation, we need to be able to process our styles so that they can be properly added to our pipeline. So in the above, we're adding: - tailwindcss: the core Tailwind package - postcss-cli: Create React App already uses postcss, but we need to configure Tailwind to be part of that build process and run it's own processing - autoprefixer: Tailwind doesn't include vendor prefixes, so we want to add autoprefixer to handle this for us. This runs as part of our postcss configuration We're also going to add two dev dependencies that make it easier to work with our code: yarn add concurrently chokidar-cli -D # or npm install concurrently chokidar-cli --save-dev - concurrently: a package that lets us set up the ability to run multiple commands at once. This is helpful since we'll need to watch both the styles and React app itself. - chokidar-cli: let's us watch files and run a command when changed. We'll use this to watch our CSS file and run the build process of the CSS on cahnge Next, let's configure postcss, so create a new file in the root of your project called postcss.config.js and include the following: // Inside postcss.config.js module.exports = { plugins: [ require('tailwindcss'), require('autoprefixer') ], }; This will add the Tailwindcss and Autoprefixer plugins to our postcss config. With our configuration, we need to include it as part of the build and watch processes. Inside package.json, add the following to definitions to your scripts property: "build:css": "tailwind build src/App.css -o src/index.css", "watch:css": "chokidar 'src/App.css' -c 'npm run build:css'", Additionally, modify the start and build scripts to now include those commands: "start": "concurrently -n Tailwind,React 'npm run watch:css' 'react-scripts start'", "build": "npm run build:css && react-scripts build", With our configuration ready to go, let's try our styles back to where they were when we left off from the static example. Inside the App.css file, replace the entire content with: @tailwind base; @tailwind components; @tailwind utilities; This is going to import Tailwind's base styles, components, and utility classes that allow Tailwind to work as you would expect it to. We can also remove the App.css import from our App.js file because it's now getting injected directly into our index.css file. So remove this line: import './App.css'; Once you're done, you can start back up your development server! If it was already started, make sure to restart it so all of the configuration changes take effect. And now the page should look exactly like it did in our static example! Follow along with the commit! Step 3: Creating a new button component class with Tailwind Tailwind doesn't ship with prebaked component classes, but it does make it easy to create them! We're going to use our button that we already created as an example of creating a new component. We'll create a new class btn as well as a color modifier btn-purple to accomplish this. The first thing we'll want to do is open up our App.css file where we'll create our new class. Inside that file, let's add: .btn { @apply font-bold py-2 px-4 rounded; } If you remember from our HTML, we're already including those same classes to our <button> element. Tailwind let's us "apply" or include the styles that make up these utility classes to another class, in this case, the .btn class. And now that we're creating that class, let's apply it to our button: <button className="btn text-white bg-purple-700 hover:bg-purple-800"> Party with Slurm! </button> And if we open up our page, we can see our button still looks the same. If we inspect the element, we can see our new .btn class generated with those styles. Next, let's create a color modifier. Similar to what we just did, we're going to add the following rules: .btn-purple { @apply bg-purple-700 text-white; } .btn-purple:hover { @apply bg-purple-800; } Here, we're adding our background color and our text color to our button class. We're also applying a darker button color when someone hovers over the button. We'll also want to update our HTML button to include our new class and remove the ones we just applied: <button className="btn btn-purple"> Party with Slurm! </button> And with that change, we can still see that nothing has changed and we have our new button class! Follow along with the commit! Applying these concepts to more components Through this walkthrough, we learned how to create a new component class using the Tailwind apply directive. This allowed us to create reusable classes that represent a component like a button. We can apply this to any number of components in our design system. For instance, if we wanted to always show our lists the way we set them up here, we could create a .list-ul class that represented an unordered list with the Tailwind utilities list-disc list-inside my-5 pl-2 applied. What tips and tricks do you like to use with Tailwind? Share with me on Twitter!
https://www.freecodecamp.org/news/what-is-tailwind-css-and-how-can-i-add-it-to-my-website-or-react-app/
CC-MAIN-2022-05
refinedweb
2,645
69.72
sudo add-apt-repository ppa:jonathonf/python-3.6 sudo apt-get update sudo apt-get install python3.6 Part 1: Creating and testing Flask REST API Carvia Tech | August 31, 2019 | 7 min read | 31 views | Flask - Python micro web framework This concise tutorial will walk you through Flask REST API from development to production. Part 1. Introduction to Flask and creating REST API Part 2. WSGI Gunicorn setup and Nginx Reverse Proxy Setup Part 3. Docker, Jenkins and CI/CD setup Prerequisite MacBook or an Ubuntu Machine with root privileges Python 3.6+ Any IDE like PyCharm or IntelliJ IDEA Docker Jenkins What will you learn? Setting up environment Installing Python 3.6 on Mac/Ubuntu What is PIP Why use virtual environment, setup virtual environment Introduction to flask What is Flask? Installing Flask Creating a Flask app What is REST API why to use it Creating a REST api in Flask Running the Flask app Testing REST endpoint using curl Testing REST endpoint using POSTMAN Setup environment Getting PyCharm (Community or Pro) You can download PyCharm IDE for development from Jetbrains website. There are two flavours available: Community Edition (Free) and Pro Edition (Paid). Here is the feature comparision between Pro and Community edition: Installing Python 3.6 on Mac In this tutorial, we will be working using python 3.6. To install python 3.6 on mac, you need to follow this link : From here you can download python installer as per mac’s configuration. Be sure to download python3.6 installer which will be in .dmg format. Open the .dmg file and click on continue to install python3.6 Installing Python 3.6 on Ubuntu For installing python 3.6 on ubuntu, just follow the following commands PIP Why use Virtual Environment? We normally have to use different versions of pythons in different projects as per need basis (web projects, batch jobs, command line tools, machine learning programs). Even the dependencies and package versions may be different for each of project. Virtual environment help us in creating a completely isolated environment for the given project. That means each of project can have its own python version, dependencies and package version rather than one universal version for all projects. This approach has many benefits: Its very easy to move a project through different stages of its lifecycle - dev to qa to stage and finally production. Virtual environment will keep its own version of packages for the given project. Completely isolated environment reduces chances of environment related issues in project. So testing becomes easy and scope for bugs is reduced. Setup virtual environment Run the below command on the terminal to install virtual environment on your machine $ pip install virtualenv $ Now if you already have a requirements file, you can install all the project specific dependencies in this virtual environment using below command: $ pip install -r requirements.txt If you want to install additional dependencies that are not present in requirements.txt, you can run the below command: $ pip install flask $ pip freeze -l > requirements.txt $ deactivate Any python command will now use the system’s default python environment after we deactivate the virtual environment. Introduction to Flask What is Flask? Flask is a micro web framework written in python, which is frequently used by developers to create REST endpoints. It is part of the categories of the micro-framework which are normally known as a framework with little to no dependencies to external libraries. This has pros and cons both. Installing Flask We will be installing flask module using pip $ pip install flask Creating a Flask App What is REST API why to use it A RESTful API is an API (application program interface ) that uses HTTP requests to GET, PUT, POST and DELETE data. GET To retrieve a resource, you shall use HTTP GET. We should not modify the state of resources using HTTP GET method ever. To create a resource on the server, use HTTP POST. An example could be new user registration REST endpoint, it will create a new user in the system. PUT To change the state of a resource or to update it on the server, use PUT DELETE To remove or delete a resource on server, use DELETE Creating a REST api in Flask In this section, we will create a hello world flask application that will have two endpoints: GET / will return hello world GET /health.json will return a json with hardcoded status for the app from flask import Flask, jsonify (1) app = Flask(__name__) (2) @app.route("/") def home(): return "Hello, World!" @app.route("/health.json") (3) def health(): return jsonify({"status": "UP"}), 200 (4) if __name__ == "__main__": app.run(debug=True) Run flask app To run the flask app, we will be following these steps: Open terminal Go to project folder Activate virtual environment Run the main file cd project_directory source venv/bin/activate python src/main.py * Serving Flask app "main" Since, we haven’t give any specific host and port to flask app, so it will run on default host and port which are 127.0.0.1 and 5000 respectively. If you want to change host & port then you can add these arguments in app.run like: app.run(host='12.23.34.45',port=7777,debug=True) Testing REST endpoint using curl If you have curl installed on your system, you can use below command to test the behavior of Flask REST endpoint. $ curl -v -X GET * HTTP 1.0, assume close after body < HTTP/1.0 200 OK < Content-Type: application/json < Content-Length: 21 < Server: Werkzeug/0.15.1 Python/3.6.7 < Date: Mon, 01 Apr 2019 17:52:05 GMT < { "status": "UP" } As we can see, server is returning a application/json mimetype of response with the health status json. Testing REST endpoint using POSTMAN Postman is the only complete API development environment, and flexibly integrates with the software development cycle. We can test REST APIs through POSTMAN easily. Now we will accessing endpoint via POSTMAN. We can use any of localhost or 127.0.0.1 for accessing endpoint. You can see the images below for referring on how it will look like on postman - Blueprints in Flask API Development.
https://www.javacodemonk.com/part-1-creating-and-testing-flask-rest-api-07bf2ac0
CC-MAIN-2019-47
refinedweb
1,043
64.1
So far in this series, I’ve look at the following: - Setting up an App Service in the cloud - Local Development - Authentication – Server Flow - Authentication – Client Flow - Custom Authentication What I haven’t done is taken a look at the data interface – a central component to the Azure Mobile Apps story. If you are using the node.js server SDK (which includes if you are using in-portal editing), then you really only have an option of using a SQL Azure (or local SQL Server) database. ASP.NET users have more options available to them (but that’s another blog post). In todays post, I’m going to talk about that data interface and do some simple changes to it. What is the data interface Azure Mobile Apps exposes an OData v3 interface to your SQL database. OData itself is a mechanism of describing queries to retrieve and publish data, so it’s a natural extension of databases into the web world. It’s RESTful in nature. Azure Mobile Apps adds a few fields to every record to support sync scenarios – most notably offline capabilities, row level conflict resolution and incremental sync. Let’s start with the fields. - The ‘createdAt’ field is a DateTimeOffset field (in SQL data format terms) that represents the date and time that the record was created. - The ‘updatedAt’ field is also a DateTimeOffset field that represents the date and time of the last update. - The ‘version’ field is a base-64 encoded string that represents a unique version. - The ‘id’ field is a string – it can be anything, but it has to be unique as the id is a primary key. If you don’t specify it, Azure Mobile Apps will assign the string representation of a v4 GUID to this field. - The ‘deleted’ field is a boolean – it represents that the record has been deleted and is used to support cross-device (soft) deletion cases. All tables have an endpoint in the /tables namespace and are case-insensitive. If you have a SQL table that you define called TodoItem (the typical starter project), then it can be accessed through /tables/todoitem and individual records can be accessed through /tables/todoitem/:id where you replace the :id with the id of the record. For example, to get the records within my todoitem table: And to get the specific ID: Defining a Table There are lots of ways to define a table, but let’s get to the basics – I want a table. I am developing, so I want a dynamic schema – that way I can define the record structure on the client. To do that, I create a tables directory in my server project and create a tables/todoitem.js file: var azureMobileApps = require('azure-mobile-apps'); // Create a new table definition var table = azureMobileApps.table(); module.exports = table; Then, within the app.js, I want to import all the tables and initialize the database: var express = require('express'), azureMobileApps = require('azure-mobile-apps'); // Set up a standard Express app var app = express(); var mobileApp = azureMobileApps({ homePage: true, swagger: true }); mobileApp.tables.import('./tables'); mobileApp.api.import('./api'); mobileApp.tables.initialize() .then(function () { app.use(mobileApp); app.listen(process.env.PORT || 3000); }); Line 11 imports the tables from the tables directory. Line 14 updates the database. The initialize() method returns a Promise – when the promise is resolved (i.e. the database is updated), I add the mobile API to the express app and start listening for connections. Requiring authentication This is the same table that I’ve been using all along. In fact, the authentication I’ve been setting up hasn’t actually prevented anyone from accessing the table via Postman or another app – it just means my app is doing the right thing. It’s time to require authentication for the entire table. To do that, I alter the table script (also known as a table controller): var azureMobileApps = require('azure-mobile-apps'); // Create a new table definition var table = azureMobileApps.table(); // Require authentication table.access = 'authenticated'; module.exports = table; Once I deploy this version of the script, I can go back to Postman and try out another GET operation on the table: I’m now getting an unauthorized message. Working through my Apache Cordova app will still work because I am authenticated there. If you aren’t getting an Unauthorized message, make sure you are using v2.0.2 or later of the azure-mobile-apps server SDK. Multi-user applications This still isn’t the holy grail though. All my apps, irrespective of my authentication, still use the same records. That’s nice for sharing a todo list, but I want a little more control over my data. I want to be able to limit the data so that the logged in user can see just their records. To do that, I need to modify the table controller with some custom code. There are four script snippets that you can add. - table.insert() for CREATE operations - table.read() for READ operations - table.update() for UPDATE operations - table.delete() for DELETE operations One method for each of the typical CRUD operations. Each one allows you to adjust the query or the inserted data. Here is the general form: table.read(function (context) { // Do something pre-execution context.execute() // .then(function (data) { // Do something post-execution // // return data; // }); }); context.execute() will return a Promise – the returned value upon resolution will be the inserted, updated or deleted item, or the list of items that are read (in the case of a read operation). There is a bunch of good stuff in the context object. For the purposes of my investigation into authentication, I’m going to concentrate on just three items: useris an object describing the authenticated user queryis a queryjs object (if you are familiar with LINQ, think of it as LINQ-lite) – this is used to convert an OData query into an SQL query itemis the item to be inserted In particular, there is a user.id element – that is the sub field of the JWT that is passed to ensure authentication and is normally an identity provider based value. Let’s change this table controller to use the user.id to set up a personal table view: var azureMobileApps = require('azure-mobile-apps'); // Create a new table definition var table = azureMobileApps.table(); // Require authentication table.access = 'authenticated'; // CREATE operation table.insert(function (context) { context.item.userId = context.user.id; return context.execute(); }); // READ operation table.read(function (context) { context.query.where({ userId: context.user.id }); return context.execute(); }); // UPDATE operation table.update(function (context) { context.query.where({ userId: context.user.id }); context.item.userId = context.user.id; return context.execute(); }); // DELETE operation table.delete(function (context) { context.query.where({ userId: context.user.id }); return context.execute(); }); module.exports = table; I’ve also set up a HTML-based client – it does the server-flow authentication and it is designed to act just like the apps. I find this method is better for testing than app based testing for the server since you can use browser-based development tools. You can check out the code on the GitHub Repository. You will have to do some adjustments to the auth settings, but you have the tools now to do those adjustments. Refer to the Day 3 article if you are in doubt. If you have stored items before doing this, you will notice on running this that you no longer have any items in the list. The items are not gone – they are just not accessible any more because the userId field does not match. My project logs the token (just like I did on day 2), and I can use that to access the protected area. To do that, I add an X-ZUMO-AUTH header to the request in Postman – the value of which is the token. Finding the User Identity Note the user Id. That’s not exactly friendly. How do I, for example, get rid of user data when the user wants to close their account? Generally, users don’t know their security ID. They know their email address. I want to have the records linked to an email address instead. Let’s first of all take a look at what is in the token on the server, where we are doing the record adjustments. To do this, I added a logging statement to the read operations in tables/todoitem.js: // READ operation table.read(function (context) { console.log('context.user = ', JSON.stringify(context.user)); context.query.where({ userId: context.user.id }); return context.execute(); }); Use the Azure Portal to turn on Application Logs – this is located in the Diagnostics Logs section of the Settings blade. You can then go to Tools -> Log Stream to stream the log: Note that the user object has nothing of value in it. The next thing to check is the decode of the token – I do this on. Just cut and paste the token into the Encoded box and see what the decode is: Once again, nothing is really of value here. I am still looking at a sid. Fortunately, there is one other area that is available with Azure App Service Authentication: the /.auth/me endpoint: This has all the claims that we are allowed to get from the original identity provider. The Azure Mobile Apps Server SDK has a method for this called getIdentity() – it’s available on the context.user object. The method returns a Promise that resolves to the contents of the /.auth/me file. If I change my table.read method to this, I’ll be able to see the contents: // READ operation table.read(function (context) { return context.user.getIdentity().then(function (userInfo) { console.log('user.getIdentity = ', JSON.stringify(userInfo)); context.query.where({ userId: context.user.id }); return context.execute(); }); }); Looking at the data from this, I can see that the information I need is in userInfo.aad.claims.emailaddress property. I can use this to affect the table. The new set of functions become this: // CREATE operation table.insert(function (context) { return context.user.getIdentity().then(function (userInfo) { context.item.userId = userInfo.aad.claims.emailaddress; return context.execute(); }); }); // READ operation table.read(function (context) { return context.user.getIdentity().then(function (userInfo) { context.query.where({ userId: userInfo.aad.claims.emailaddress }); return context.execute(); }); }); // UPDATE operation table.update(function (context) { return context.user.getIdentity().then(function (userInfo) { context.query.where({ userId: userInfo.aad.claims.emailaddress }); context.item.userId = userInfo.aad.claims.emailaddress; return context.execute(); }); }); // DELETE operation table.delete(function (context) { return context.user.getIdentity().then(function (userInfo) { context.query.where({ userId: userInfo.aad.claims.emailaddress }); return context.execute(); }); }); When I use these functions and access the table via Postman, I get the following: Note that the userId property is now the email address. If I use the Auth0 custom authentication – where I provide a choice between Facebook, Twitter, Google, MSA and potentially AAD – the email address will always be the same, so this allows me to do cross-platform authentication. What about performance? The getIdentity() method a HTTPS request underneath to obtain the response from the /.auth/me endpoint. As a result, it isn’t going to be as performant as just dealing with the JWT. There are a couple of methods of dealing with this and we will cover these in a later blog post. Next Steps Todays foray into the table controller is not the last time we will visit this topic. We are really still covering authentication. In the next blog post, we’ll take a look at what you should do when the authentication token is about to expire. Until then, you can find todays code on my GitHub Repository.
https://shellmonger.com/2016/04/11/30-days-of-zumo-v2-azure-mobile-apps-day-6-personal-tables/
CC-MAIN-2017-51
refinedweb
1,955
58.99
> I had to modify the MPMs so they wouldn't try to set ap_scoreboard_fname > any more. This #define is now fully owned by the scoreboard.c file. > (Might we want to namespace-protect that #define? I don't know.) > > I'm posting this here for feedback because it is a big change and could > use some testing on other platform/MPM combos, but I'd also like to > wait until the current release process finishes. > This works well with perfork and worker under Linux. I have a couple of comments though: 1) There are some not infrequent cases I have run into where apache needs to be killed (for unrelated reasons) and the shared memory segment does not get cleaned up. When this happens, you can't restart the server. You get a "file exists" error and apache refuses to start up. This is easy to fix with ipcrm but the error is confusing and does not make the solution obvious. It would be nice if apache would clean up the shared memory segement if it sees it, or have a more meaningfull error. 2) Unless I am missing something, there does not seem to be an easy way for an external application accessing the scoreboard to know how to navigate the data structure. You have to know the server limit and thread limit or else you run into problems. It would be nice to be able to derive those values from the scoreboard image instead of the httpd.conf file. -adam
http://mail-archives.apache.org/mod_mbox/httpd-dev/200202.mbox/%3C20020215015031.F7538@vishnu.vidya.com%3E
CC-MAIN-2016-40
refinedweb
252
70.73
Bioinformatics Tools Programming in Python with Qt. Part 1. Hello and welcome to “Bioinformatics Tools Programming in Python with Qt” article/video series. In this series we will start developing a Qt framework based application using Python programming language. Qt. This series is semi-connected to the “DNA Toolkit” series, also available on this website. Application code and structure we will be developing here is universal for the most part. It can be applied to any kind of project, but we will focus on a concrete example: adding a GUI (graphical user interface) to a class and a set of functions we developed in “DNA Toolkit” series. Prerequisites: - Medium to Advanced Python and OOP knowledge. - Python 3.7+ configured code editor. (VSCodium Setup) - Linux preferably as that is what I use, but other OS is fine too as long as you can easily replicate our steps. While previous Qt framework experience is good to have, it is not necessary as I will guide you though and also link to good resources on the topic. We will start by setting up PyQt and a virtual environment for our project and run a Test App. After that we will generate our first UI file and load it into our project. Segment 1: Python, PyQt and pipenv setup Open a terminal or a cmd and let’s create a project folder called ‘dna_engine‘. Navigate (cd) into that directory and install/activate virtual environment. Commands are listed below: mkdir dna_engine cd dna_engine pipenv install pipenv shell If you successfully activated the virtual environment you should see something like this: . /home/jurisl/.local/share/virtualenvs/dna_engine-REfk1eAd/bin/activate (dna_engine) [jurisl@JurisLinuxPC dna_engine]$ Now we need to install a few packages into our virt-env. This can be done with the following command: pipenv install pyqt5 pyqt5-tools autopep8 And you should see something like this: Installing pyqt5… Adding pyqt5 to Pipfile's [packages]… ✔ Installation Succeeded Installing pyqt5-tools… Adding pyqt5-tools to Pipfile's [packages]… ✔ Installation Succeeded Installing autopep8… Adding autopep8 to Pipfile's [packages]… ✔ Installation Succeeded - pyqt5 – Qt Framework. - pyqt5-tools – Qt designer, UI file converter and other tools. - autopep8 – just a code linter/formatter. Now we should be ready to test our setup and run a test application. Segment 2: Test application While in a ‘dna_engine‘ project folder in your terminal window, type one of the following commands to open vscode/vscodium editor in that directory. This will also load a project into a newly opened window. (dna_engine) [jurisl@JurisLinuxPC dna_engine]$ vscodium ./ OR (dna_engine) [jurisl@JurisLinuxPC dna_engine]$ vscode ./ OR (dna_engine) [jurisl@JurisLinuxPC dna_engine]$ codium ./ OR (dna_engine) [jurisl@JurisLinuxPC dna_engine]$ code ./ If you are using a different editor, you can try typing the name of your editor with ./ appended or just adding our project folder into your editor by hand (drag and drop). Now we should have something like this (a folder ‘dna_engine‘ and two config files): Let’s add a new file, called “main.py” and paste a very basic code that will just create a Qt based window: import sys from PyQt5.QtWidgets import QApplication, QWidget if __name__ == '__main__': app = QApplication(sys.argv) w = QWidget() w.resize(250, 150) w.move(300, 300) w.setWindowTitle('Test Window!') w.show() sys.exit(app.exec_()) This is what we should have at this point: Variable/Method names are very descriptive, and we will not discuss them in here. We need to make sure we have a working project first. Now, let’s run our project. If you are using the setup I use, described in my dev tools video here, and you have a Code Runner installed (definitely recommended) you can just use “Ctrl + Alt + N” and you should see an empty window pop up: If you see that small window, it means everything is working correctly. Segment 3: Qt Designer Now let’s take a look at how we can create a UI and use it in our newly created project. While in ‘dna_engine‘ folder in your terminal, just type ‘designer‘: (dna_engine) [jurisl@JurisLinuxPC dna_engine]$ designer NOTE: this works on Linux and should work on the Mac. I will link an additional video at the bottom of this article if you are running Windows. You might need to restart your Windows PC after we installed pyqt5-tools package to make sure Qt Tools folder is in the system path. After we execute the above command, we should see ‘New Form‘ window. Select ‘Widget‘ and click ‘Create‘. Now we are in the Designer. If you have never worked with UI creation tools like this Designer, don’t worry. You don’t have to understand and learn all of what you see. The basic concept is that we have different elements like buttons, forms, text fields, etc. and every element has a lot of different properties; like name, ID, size, position, etc. By understanding how one element like a Push Button works, using other elements will be easy and intuitive. We will start using and programming elements in our next article/video. As we can see, the default Designer project is an empty window. Lets drag-and-drop a few elements from the menu on the left. In my case I will drop a ‘Push Button’, a ‘Check Box’, and a ‘Line Edit’. But you can drop any and as many as you want. Try making the main window smaller: Now you should start getting the feeling of how easy it is to create a user interface like that. It is very intuitive and can also be done by a designer and passed on to a developer to write the actual code. Save the UI file (File -> Save) in the root directory of our project ‘dna_engine‘ and name it ‘dna_engine.ui‘. This file is in XML format. We will need to convert it to a Python file later. Now let’s change the code in our ‘main.py‘ file to a class based Qt template. This template will be the basis for our project structure: import sys from PyQt5 import QtWidgets as QtW from PyQt5 import QtCore as QtC from PyQt5 import QtGui as QtG class MainWindow(QtW.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Application Logic goes here: self.show() if __name__ == '__main__': app = QtW.QApplication(sys.argv) window = MainWindow() sys.exit(app.exec_()) Nothing really special here. We import a few Qt framework modules, create a MainWindow class, and create an instance of our window/application in the __main__ function. If we run this, we should see exactly the same result as before: an empty window. Now we need to use one other tool that is a part of pyqt5-tools package, ‘pyuic5‘. It will convert our .ui file into a .py file. While in your terminal and in a ‘dna_engine‘ folder, type the following command: pyuic5 dna_engine.ui -o engine_ui.py - pyuic5 – .ui -> .py converter tool. - dna_engine.ui – name of the source ui file. - -o – output. - engine_ui.py – output file. You can also execute this command from within your code editor (Ctrl + `) if you are in VSCode) like I did here: After we have executed this command, we should see a new file added to our project. Segment 4: Loading UI file Let’s open our new file, pyuic5 tool generated for us in the previous segment and see what’s inside. Well, we see that is just a simple class that utilizes Qt framework, and it contains elements we added to our form and some additional properties associated with those elements. While this file looks nice and clean, this might and probably will grow in size and complexity significantly. But as we will import this file into our main project and just access the elements, that is not a problem. Our main application code will “live” separately from this file. This way we can also keep modifying and regenerating this ui file, while we keep developing the core of our application. Remember, application code is separate from our UI file. This will become more clear when we start working on our project file/class structure. Now let’s add just 3 lines of code and load that UI we have created: import sys from PyQt5 import QtWidgets as QtW from PyQt5 import QtCore as QtC from PyQt5 import QtGui as QtG from engine_ui import Ui_Form class MainWindow(QtW.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_Form() self.ui.setupUi(self) # Application Logic goes here: self.show() if __name__ == '__main__': app = QtW.QApplication(sys.argv) window = MainWindow() sys.exit(app.exec_()) - Line 6 – importing Ui_Form class from our ui file. - Line 14 – creating a ui class instance (will be used throughout the application). - Line 15 – calling a setup method of a ui class. Now if we run our project (Ctrl + Alt + N), we will see our mock-up window: Conclusion In this article we: - Configured PyQt and PyQt Tools. - Tested our configuration with a test app/window. - Used Designer to create a test window with a few elements. - Loaded the ui file into our project. In our next article we will start creating a structure for our project, and organize files and class. I also have a ‘From Python to Rust‘ series, where we port some of our bioinformatics code to Rust, and these two series will converge at some point as we will add a ‘Rust Plugin System’ to our DNA Engine. This will enable us to extend DNA Engine functionality by writing computationally heavy code in Rust and add it as a plugin. Example of what the first version of DNA Engine might look like, utilizing the DNA Toolkit: Video version of this article: Links: - PyQT5 + Designer installation and use on Windows Video. - Alan D Moore’s amazing PyQT and Designer Video. Also, not required but a highly recommended book by Alan D Moore: Buy: US / UK GitLab: Video version of this article: Video version: 1 Comment Bioinformatics Tools Programming in Python with Qt. Part 2. - rebelScience · June 24, 2020 at 10:48 […] ‘DNA_Engine’ folder. Open up your terminal and execute the command we learned in the previous […]
https://rebelscience.club/2020/06/08/bioinformatics-tools-programming-in-python-with-qt-part-1/
CC-MAIN-2021-39
refinedweb
1,687
65.12
I'm a developer for a digital marketing company. I have been tasked with updating and cataloging our portfolio of around 400 sites. Firstly I'd like to get an idea of what sites are at what version. I decided Python would be the tool to use and took to learning. It's still early days but I'm coming up against an annoying problem, maybe you guys could help? So this executes without a problem. However, setting the 'if htmlSource.find(ver) == 1:' line to either 1 or -1 produces odd results.So this executes without a problem. However, setting the 'if htmlSource.find(ver) == 1:' line to either 1 or -1 produces odd results.Code: import csv import urllib2 import time import httplib with open('domains.csv','r') as csvfile: urls = [row[0] for row in csv.reader(csvfile)] L = ['Wordpress 0.7','Wordpress 1.2','Wordpress 1.5','Wordpress 2.0','Wordpress 2.1','Wordpress 2.3','Wordpress 2.5','Wordpress 2.6','Wordpress 2.7','Wordpress 2.8','Wordpress 2.9','Wordpress 2.9','Wordpress 3.0','Wordpress 3.1','Wordpress 3.2','Wordpress 3.3','Wordpress 3.4','Wordpress 3.5.1'] for url in urls: sock = urllib2.urlopen(url) htmlSource = sock.read() sock.close for ver in L: if htmlSource.find(ver)== 1: print url + " | Wordpress | " + ver sock.close It will either just return url+ "|WordPress |" + ver for all iterations of the loop, for all urls, or it returns nothing. Basically, I want to check if the string Wordpress X.X is found (x.x being the version number). The source code for all those pages contains a meta tag with the value "WordPress X.X" however I don't seem to be detecting it Thanks!
http://www.codingforums.com/python/296382-x-y-need-help-iterating-through-my-list-print.html
CC-MAIN-2015-11
refinedweb
292
61.83
This is a question is an extension of What's the most Pythonic way to identify consecutive duplicates in a list?. Suppose you have a list of tuples: my_list = [(1,4), (2,3), (3,2), (4,4), (5,2)] my_list = sorted(my_list, key=lambda tuple: tuple[1]) # [(3,2), (5,2), (2,3), (1,4), (4,4)] [(3,2), (5,2)] [(1,4), (4,4)] reverse_runs(my_list) # [(5,2), (3,2), (2,3), (4,4), (1,4)] my_list = [(1,"A"), (2,"B"), (5,"C"), (4,"C"), (3,"C"), (6,"A"),(7,"A"), (8,"D")] reverse_runs [(7,"A"), (6,"A"), (1,"A"), (2,"B"), (3,"C"), (4,"C"), (5,"C"), (8,"D")] TimSort sorted(my_list,key=lambda t: t[1]) [(1, 'A'), (6, 'A'), (7, 'A'), (2, 'B'), (5, 'C'), (4, 'C'), (3, 'C'), (8, 'D')] "C" (5, 'C'), (4, 'C'), (3, 'C') reverse_runs sorted(my_list, key=lambda tuple: tuple[1]) The most general case requires 2 sorts. The first sort is a reversed sort on the second criteria. The second sort is a forward sort on the first criteria: pass1 = sorted(my_list, key=itemgetter(0), reverse=True) result = sorted(pass1, key=itemgetter(1)) We can sort in multiple passes like this because python's sort algorithm is guaranteed to be stable. However, in real life it's often possible to simply construct a more clever key function which allows the sorting to happen in one pass. This usually involves "negating" one of the values and relying on the fact that tuples order themselves lexicographically: result = sorted(my_list, key=lambda t: (t[1], -t[0])) In response to your update, it looks like the following might be a suitable solution: from operator import itemgetter from itertools import chain, groupby my_list = [(1,"A"), (2,"B"), (5,"C"), (4,"C"), (3,"C"), (6,"A"),(7,"A"), (8,"D")] pass1 = sorted(my_list, key=itemgetter(1)) result = list(chain.from_iterable(reversed(list(g)) for k, g in groupby(pass1, key=itemgetter(1)))) print(result) We can take apart the expression: chain.from_iterable(reversed(list(g)) for k, g in groupby(pass1, key=itemgetter(1))) to try to figure out what it's doing... First, let's look at groupby(pass1, key=itemgetter(1)). groupby will yield 2-tuples. The first item ( k) in the tuple is the "key" -- e.g. whatever was returned from itemgetter(1). The key isn't really important here after the grouping has taken place, so we don't use it. The second item ( g -- for "group") is an iterable that yields consecutive values that have the same "key". This is exactly the items that you requested, however, they're in the order that they were in after sorting. You requested them in reverse order. In order to reverse an arbitrary iterable, we can construct a list from it and then reverse the list. e.g. reversed(list(g)). Finally, we need to paste those chunks back together again which is where chain.from_iterable comes in. If we want to get more clever, we might do better from an algorithmic standpoint (assuming that the "key" for the bins is hashible). The trick is to bin the objects in a dictionary and then sort the bins. This means that we're potentially sorting a much shorter list than the original: from collections import defaultdict, deque from itertools import chain my_list = [(1,"A"), (2,"B"), (5,"C"), (4,"C"), (3,"C"), (6,"A"),(7,"A"), (8,"D")] bins = defaultdict(deque) for t in my_list: bins[t[1]].appendleft(t) print(list(chain.from_iterable(bins[key] for key in sorted(bins)))) Note that whether this does better than the first approach is very dependent on the initial data. Since TimSort is such a beautiful algorithm, if the data starts already grouped into bins, then this algorithm will likely not beat it (though, I'll leave it as an exercise for you to try...). However, if the data is well scattered (causing TimSort to behave more like MergeSort), then binning first will possibly make for a slight win.
https://codedump.io/share/t6ptEav33fka/1/python-3-reverse-consecutive-runs-in-sorted-list
CC-MAIN-2019-04
refinedweb
673
57.71
Up to [cvs.NetBSD.org] / src / lib / libc / citrus Request diff between arbitrary revisions Default branch: MAIN Current tag: netbsd-6-1-4-RELEASE Revision 1.4 / (download) - annotate - [select for diffs], Sun Jun 13 04:14:57 2010 UTC (10 years ago) by tnozaki.3: +3 -3 lines Diff to previous 1.3 (colored) 1. split runetype_local.h -> runetype_file.h and remove renameing _Rune* -> _NBRune* namespace protection. FreeBSD traditionaly exposes struct _Rune* in runetype.h which included by ctype.h. it may cause conflicting type error in our cross build process, former we use renaming namespace to avoid this problem, now i reworked more resonable way. 2. merge rune_local.h to runetype_local.h, and remove it. 3. split bsdctype.h -> bsdctype_{file,local}.h This form allows you to request diff's between any two revisions of a file. You may select a symbolic revision name using the selection box or you may type in a numeric name using the type-in text box.
http://cvsweb.netbsd.org/bsdweb.cgi/src/lib/libc/citrus/citrus_lc_messages.c?sortby=rev&only_with_tag=netbsd-6-1-4-RELEASE
CC-MAIN-2020-29
refinedweb
165
60.41
I'm trying to get access to the shaded region of a matplotlib plot, so that I can remove it without doing plt.cla() [since cla() clears the whole axis including axis label too] If I were plotting I line, I could do: import matplotlib.pyplot as plt ax = plt.gca() ax.plot(x,y) ax.set_xlabel('My Label Here') # then to remove the line, but not the axis label ax.lines.pop() However, for plotting a region I execute: ax.fill_between(x, 0, y) So ax.lines is empty. How can I clear this shaded region please? As the documentation states fill_between returns a PolyCollection instance. Collections are stored in ax.collections. So ax.collections.pop() should do the trick. However, I think you have to be careful that you remove the right thing, in case there are multiple objects in either ax.lines or ax.collections. You could save a reference to the object so you know which one to remove: fill_between_col = ax.fill_between(x, 0, y) and then to remove: ax.collections.remove(fill_between_col) EDIT: Yet another method, and probably the best one: All the artists have a method called remove which does exactly what you want: fill_between_col.remove()
http://databasefaq.com/index.php/answer/3758/python-matplotlib-plot-fill-object-oriented-access-to-fill-between-shaded-region-in-matplotlib
CC-MAIN-2018-47
refinedweb
202
60.21
Reshape¶ Prerequisites Outcomes Understand and be able to apply the melt/ stack/ unstack/ pivotmethods Practice transformations of indices Understand tidy data # Uncomment following line to install on colab #! pip install import numpy as np import pandas as pd %matplotlib inline Tidy Data¶ While pushed more generally in the R language, the concept of “tidy data” is helpful in understanding the objectives for reshaping data, which in turn makes advanced features like groupby more seamless. Hadley Wickham gives a terminology slightly better-adapted for the experimental sciences, but nevertheless useful for the social sciences. A dataset is a collection of values, usually either numbers (if quantitative) or strings (if qualitative). Values are organized. – Tidy Data (Journal of Statistical Software 2013) With this framing, A dataset is messy or tidy depending on how rows, columns and tables are matched with observations, variables, and types. In tidy data: - Each variable forms a column. - Each observation forms a row. - Each type of observational unit forms a table. The “column” and “row” terms map directly to pandas columns and rows, while the “table” maps to a pandas DataFrame. With this thinking and interpretation, it becomes essential to think through what uniquely identifies an “observation” in your data. Is it a country? A year? A combination of country and year? These will become the indices of your DataFrame. For those with more of a database background, the “tidy” format matches the 3rd normal form in database theory, where the referential integrity of the database is maintained by the uniqueness of the index. When considering how to map this to the social sciences, note that reshaping data can change what we consider to be the variable and observation in a way that doesn’t occur within the natural sciences. For example, if the “observation” uniquely identified by a country and year and the “variable” is GDP, you may wish to reshape it so that the “observable” is a country, and the variables are a GDP for each year. A word of caution: The tidy approach, where there is no redundancy and each type of observational unit forms a table, is a good approach for storing data, but you will frequently reshape/merge/etc. in order to make graphing or analysis easier. This doesn’t break the tidy format since those examples are ephemeral states used in analysis. Reshaping your Data¶ The data you receive is not always in a “shape” that makes it easy to analyze. What do we mean by shape? The number of rows and columns in a DataFrame and how information is stored in the index and column names. This lecture will teach you the basic concepts of reshaping data. As with other topics, we recommend reviewing the pandas documentation on this subject for additional information. We will keep our discussion here as brief and simple as possible because these tools will reappear in subsequent lectures. url = "" bball = pd.read_csv(url) bball.info() bball <class 'pandas.core.frame.DataFrame'> RangeIndex: 9 entries, 0 to 8 Data columns (total 8 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Year 9 non-null int64 1 Player 9 non-null object 2 Team 9 non-null object 3 TeamName 9 non-null object 4 Games 9 non-null int64 5 Pts 9 non-null float64 6 Assist 9 non-null float64 7 Rebound 9 non-null float64 dtypes: float64(3), int64(2), object(3) memory usage: 704.0+ bytes Long vs Wide¶ Many of these operations change between long and wide DataFrames. What does it mean for a DataFrame to be long or wide? Here is long possible long-form representation of our basketball data. # Don't worry about what this command does -- We'll see it soon bball_long = bball.melt(id_vars=["Year", "Player", "Team", "TeamName"]) bball_long And here is a wide-form version. # Again, don't worry about this command... We'll see it soon too bball_wide = bball_long.pivot_table( index="Year", columns=["Player", "variable", "Team"], values="value" ) bball_wide 3 rows × 24 columns set_index, reset_index, and Transpose¶ We have already seen a few basic methods for reshaping a DataFrame. set_index: Move one or more columns into the index. reset_index: Move one or more index levels out of the index and make them either columns or drop from DataFrame. T: Swap row and column labels. Sometimes, the simplest approach is the right approach. Let’s review them briefly. bball2 = bball.set_index(["Player", "Year"]) bball2.head() bball3 = bball2.T bball3.head() stack and unstack¶ The stack and unstack methods operate directly on the index and/or column labels. stack¶ stack is used to move certain levels of the column labels into the index (i.e. moving from wide to long) Let’s take ball_wide as an example. bball_wide 3 rows × 24 columns Suppose that we want to be able to use the mean method to compute the average value of each stat for each player, regardless of year or team. To do that, we need two column levels: one for the player and one for the variable. We can achieve this using the stack method. bball_wide.stack() Now, we can compute the statistic we are after. player_stats = bball_wide.stack().mean() Now suppose instead of that we wanted to compute the average for each team and stat, averaging over years and players. We’d need to move the Player level down into the index so we are left with column levels for Team and variable. We can ask pandas do this using the level keyword argument. bball_wide.stack(level="Player") Now we can compute the mean. bball_wide.stack(level="Player").mean() variable Team Assist GSW 5.92 OKC 2.90 ORL 1.10 TOR 0.70 Games GSW 67.80 OKC 75.00 ORL 56.00 TOR 23.00 Pts GSW 26.66 OKC 20.40 ORL 15.10 TOR 14.20 Rebound GSW 6.02 OKC 7.50 ORL 6.80 TOR 6.80 dtype: float64 Notice a few features of the stack method: Without any arguments, the stackarguments move the level of column labels closest to the data (also called inner-most or bottom level of labels) to become the index level closest to the data (also called the inner-most or right-most level of the index). In our example, this moved Teamdown from columns to the index. When we do pass a level, that level of column labels is moved down to the right-most level of the index and all other column labels stay in their relative position. Note that we can also move multiple levels at a time in one call to stack. bball_wide.stack(level=["Player", "Team"]) In the example above, we started with one level on the index (just the year) and stacked two levels to end up with a three-level index. Notice that the two new index levels went closer to the data than the existing level and that their order matched the order we passed in our list argument to level. unstack¶ Now suppose that we wanted to see a bar chart of each player’s stats. This chart should have one “section” for each player and a different colored bar for each variable. As we’ll learn in more detail in a later lecture, we will need to have the player’s name on the index and the variables as columns to do this. Note In general, for a DataFrame, calling the plot method will put the index on the horizontal (x) axis and make a new line/bar/etc. for each column. Notice that we are close to that with the player_stats variable. We now need to rotate the variable level of the index up to be column layers. We use the unstack method for this. player_stats.unstack() And we can make our plot! player_stats.unstack().plot.bar() <AxesSubplot: This particular visualization would be helpful if we wanted to see which stats for which each player is strongest. For example, we can see that Steph Curry scores far more points than he does rebound, but Serge Ibaka is a bit more balanced. What if we wanted to be able to compare all players for each statistic? This would be easier to do if the bars were grouped by variable, with a different bar for each player. To plot this, we need to have the variables on the index and the player name as column names. We can get this DataFrame by setting level="Player" when calling unstack. player_stats.unstack(level="Player") player_stats.unstack(level="Player").plot.bar() <AxesSubplot: Now we can use the chart to make a number of statements about players: Ibaka does not get many assists, compared to Curry and Durant. Steph and Kevin Durant are both high scorers. Based on the examples above, notice a few things about unstack: It is the inverse of stack; stackwill move labels down from columns to index, while unstackmoves them up from index to columns. By default, unstackwill move the level of the index closest to the data and place it in the column labels closest to the data. Note Just as we can pass multiple levels to stack, we can also pass multiple levels to unstack. We needed to use this in our solution to the exercise below. Exercise See exercise 1 in the exercise list. Summary¶ In some ways set_index, reset_index, stack, and unstack are the “most fundamental” reshaping operations… The other operations we discuss can be formulated with these four operations (and, in fact, some of them are exactly written as these operations in pandas’s code base). Pro tip: We remember stack vs unstack with a mnemonic: Unstack moves index levels Up melt¶ The melt method is used to move from wide to long form. It can be used to move all of the “values” stored in your DataFrame to a single column with all other columns being used to contain identifying information. Warning When you use melt, any index that you currently have will be deleted. We saw used melt above when we constructed bball_long: bball # this is how we made ``bball_long`` bball.melt(id_vars=["Year", "Player", "Team", "TeamName"]) Notice that the columns we specified as id_vars remained columns, but all other columns were put into two new columns: variable: This has dtype string and contains the former column names. as values value: This has the former values. Using this method is an effective way to get our data in tidy form as noted above. Exercise See exercise 2 in the exercise list. pivot and pivot_table¶ The next two reshaping methods that we will use are closely related. Some of you might even already be familiar with these ideas because you have previously used pivot tables in Excel. If so, good news. We think this is even more powerful than Excel and easier to use! If not, good news. You are about to learn a very powerful and user-friendly tool. We will begin with pivot. The pivot method: Takes the unique values of one column and places them along the index. Takes the unique values of another column and places them along the columns. Takes the values that correspond to a third column and fills in the DataFrame values that correspond to that index/column pair. We’ll illustrate with an example. # .head 8 excludes Ibaka -- will discuss why later bball.head(6).pivot(index="Year", columns="Player", values="Pts") We can replicate pivot using three of the fundamental operations from above: Call set_indexwith the indexand columnsarguments Extract the valuescolumn unstackthe columns level of the new index # 1--------------------------------------- 2--- 3---------------------- bball.head(6).set_index(["Year", "Player"])["Pts"].unstack(level="Player") One important thing to be aware of is that in order for pivot to work, the index/column pairs must be unique! Below, we demonstrate the error that occurs when they are not unique. # Ibaka shows up twice in 2016 because he was traded mid-season from # the Orlando Magic to the Toronto Raptors bball.pivot(index="Year", columns="Player", values="Pts") --------------------------------------------------------------------------- ValueError Traceback (most recent call last) Input In [22], in <cell line: 3>() 1 # Ibaka shows up twice in 2016 because he was traded mid-season from 2 # the Orlando Magic to the Toronto Raptors ----> 3 bball.pivot(index="Year", columns="Player", values="Pts") File /usr/share/miniconda3/envs/lecture-datascience/lib/python3.9/site-packages/pandas/core/frame.py:7885, in DataFrame.pivot(self, index, columns, values) 7880 @Substitution("") 7881 @Appender(_shared_docs["pivot"]) 7882 def pivot(self, index=None, columns=None, values=None) -> DataFrame: 7883 from pandas.core.reshape.pivot import pivot -> 7885 return pivot(self, index=index, columns=columns, values=values) File /usr/share/miniconda3/envs/lecture-datascience/lib/python3.9/site-packages/pandas/core/reshape/pivot.py:520, in pivot(data, index, columns, values) 518 else: 519 indexed = data._constructor_sliced(data[values]._values, index=multiindex) --> 520 return indexed.unstack(columns_listlike) File /usr/share/miniconda3/envs/lecture-datascience/lib/python3.9/site-packages/pandas/core/series.py:4157, in Series.unstack(self, level, fill_value) 4114 """ 4115 Unstack, also known as pivot, Series with MultiIndex to produce DataFrame. 4116 (...) 4153 b 2 4 4154 """ 4155 from pandas.core.reshape.reshape import unstack -> 4157 return unstack(self, level, fill_value) File /usr/share/miniconda3/envs/lecture-datascience/lib/python3.9/site-packages/pandas/core/reshape/reshape.py:491, in unstack(obj, level, fill_value) 489 if is_1d_only_ea_dtype(obj.dtype): 490 return _unstack_extension_series(obj, level, fill_value) --> 491 unstacker = _Unstacker( 492 obj.index, level=level, constructor=obj._constructor_expanddim 493 ) 494 return unstacker.get_result( 495 obj._values, value_columns=None, fill_value=fill_value 496 ) File /usr/share/miniconda3/envs/lecture-datascience/lib/python3.9/site-packages/pandas/core/reshape/reshape.py:140, in _Unstacker.__init__(self, index, level, constructor) 133 if num_cells > np.iinfo(np.int32).max: 134 warnings.warn( 135 f"The following operation may generate {num_cells} cells " 136 f"in the resulting pandas object.", 137 PerformanceWarning, 138 ) --> 140 self._make_selectors() File /usr/share/miniconda3/envs/lecture-datascience/lib/python3.9/site-packages/pandas/core/reshape/reshape.py:192, in _Unstacker._make_selectors(self) 189 mask.put(selector, True) 191 if mask.sum() < len(self.index): --> 192 raise ValueError("Index contains duplicate entries, cannot reshape") 194 self.group_index = comp_index 195 self.mask = mask ValueError: Index contains duplicate entries, cannot reshape pivot_table¶ The pivot_table method is a generalization of pivot. It overcomes two limitations of pivot: It allows you to choose multiple columns for the index/columns/values arguments. It allows you to deal with duplicate entries by having you choose how to combine them. bball Notice that we can replicate the functionality of pivot if we pass the same arguments. bball.head(6).pivot(index="Year", columns="Player", values="Pts") But we can also choose multiple columns to be used in index/columns/values. bball.pivot_table(index=["Year", "Team"], columns="Player", values="Pts") bball.pivot_table(index="Year", columns=["Player", "Team"], values="Pts") AND we can deal with duplicated index/column pairs. # This produced an error # bball.pivot(index="Year", columns="Player", values="Pts") # This doesn't! bball_pivoted = bball.pivot_table(index="Year", columns="Player", values="Pts") bball_pivoted pivot_table handles duplicate index/column pairs using an aggregation. By default, the aggregation is the mean. For example, our duplicated index/column pair is ("x", 1) and had associated values of 2 and 5. Notice that bball_pivoted.loc[2016, "Ibaka"] is (15.1 + 14.2)/2 = 14.65. We can choose how pandas aggregates all of the values. For example, here’s how we would keep the max. bball.pivot_table(index="Year", columns="Player", values="Pts", aggfunc=max) Maybe we wanted to count how many values there were. bball.pivot_table(index="Year", columns="Player", values="Pts", aggfunc=len) We can even pass multiple aggregation functions! bball.pivot_table(index="Year", columns="Player", values="Pts", aggfunc=[max, len]) Exercise See exercise 3 in the exercise list. Visualizing Reshaping¶ Now that you have learned the basics and had a chance to experiment, we will use some generic data to provide a visualization of what the above reshape operations do. The data we will use is: # made up # columns A and B are "identifiers" while C, D, and E are variables. df = pd.DataFrame({ "A": [0, 0, 1, 1], "B": "x y x z".split(), "C": [1, 2, 1, 4], "D": [10, 20, 30, 20,], "E": [2, 1, 5, 4,] }) df.info() df <class 'pandas.core.frame.DataFrame'> RangeIndex: 4 entries, 0 to 3 Data columns (total 5 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 A 4 non-null int64 1 B 4 non-null object 2 C 4 non-null int64 3 D 4 non-null int64 4 E 4 non-null int64 dtypes: int64(4), object(1) memory usage: 288.0+ bytes df2 = df.set_index(["A", "B"]) df2.head() df3 = df2.T df3.head() stack and unstack¶ Below is an animation that shows how stacking works. df2 df2_stack = df2.stack() df2_stack A B 0 x C 1 D 10 E 2 y C 2 D 20 E 1 1 x C 1 D 30 E 5 z C 4 D 20 E 4 dtype: int64 And here is an animation that shows how unstacking works. df2 df2.unstack() Exercises¶ Exercise 1¶ Warning This one is challenging Recall the bball_wide DataFrame from above (repeated below to jog your memory). In this task, you will start from ball and re-recreate bball_wide by combining the operations we just learned about. There are many ways to do this, so be creative. Our solution used set_index, T, stack, and unstack in that order. Here are a few hints: Hint Think about what columns you will need to call set_indexon so that their data ends up as labels (either in index or columns). Hint Leave other columns (e.g. the actual game stats) as actual columns so their data can stay data during your reshaping. Don’t spend too much time on this… if you get stuck, you will find our answer here. Hint You might need to add .sort_index(axis=1) after you are finished to get the columns in the same order. Hint You may not end up with a variable header on the second level of column labels. This is ok. bball_wide Exercise 2¶ What do you think would happen if we wrote bball.melt(id_vars=["Year", "Player"])rather than bball.melt(id_vars=["Year", "Player", "Team", "TeamName"])? Were you right? Write your thoughts. Read the documentation and focus on the argument value_vars. How does bball.melt(id_vars=["Year", "Player"], value_vars=["Pts", "Rebound"])differ from bball.melt(id_vars=["Year", "Player"])? Consider the differences between bball.stackand bball.melt. Is there a way to make them generate the same output? Write your thoughts. Hint You might need to use both stackand another method from above Exercise 3¶ First, take a breath… That was a lot to take in. Can you think of a reason to ever use pivotrather than pivot_table? Write your thoughts. Create a pivot table with column Playeras the index, TeamNameas the columns, and [Rebound, Assist]as the values. What happens when you use aggfunc=[np.max, np.min, len]? Describe how Python produced each of the values in the resultant pivot table.
https://datascience.quantecon.org/pandas/reshape.html
CC-MAIN-2022-40
refinedweb
3,187
58.18
- Creating a Package - Using a Custom Class - Next in the Series code. AS has really matured over the years, and version 3 has raised the bar for object-oriented approaches by providing the ability to create packages, forcing strict typing through the compiler, and much more. In addition, the Flex environment has made it much easier to debug code and see errors or warnings while writing code. The Flash to Flex series will focus on helping you migrate your work environment from Flash to Flex by learning the differences between and comparing the two applications. Last time, we covered how to integrate AS with MXML; this week we’ll take it a step further by focusing on AS 3 and how to use it to create packages and classes and then incorporate them into a Flex project. If you have questions about creating a new Flex project, incorporating ActionScript, or triggering events, take a look at my previous article, "Integrating ActionScript with MXML." Creating a Package The concept of a package did not exist in previous versions of AS. In fact, classes were not even possible until the release of AS 2, and in AS 1 developers were left creating prototype objects, much like in JavaScript. Thankfully, AS 3 has kept the same concept of classes from AS 2 and has also incorporated packages. Packages are essentially the folder structure that you define for particular classes. For instance, my company is studiosedition.com, so the base package for all of my company classes will be the same as Listing 1. Listing 1 Creating a base package com.studiosedition Let’s say that I have some utility classes, such as a class that only handles all alerts, named it Alert.as, and added it to a utilities folder. The full class path for this object would look like Listing 2 in AS 2. Listing 2 Creating a full class path in AS 2 com.studiosedition.utilities.Alert Listing 3 shows an example of how AS 3 enables developers to actually use the package keyword as other languages do. Listing 3 Packages in ActionScript 3 package com.studiosedition.utilities { public class Alert { } } A bonus of Flex is that it streamlines the creation of classes and packages by incorporating a dialog for creating new AS classes. The dialog enables you to browse for a package, name the class, choose whether it is public or internal, choose dynamic and/or final, browse for a superclass if it extends another class, and add interfaces. Beyond that it even provides the ability to automatically create the constructor, generate functions from an interface, and add comments. This helps save a lot of typing when you have a large project and are creating a lot of classes. Take a look at Figure 1 to see the dialog used to create a new AS class. Note that the folder structure needs to exist in the Flex project in order to use it. For example, to use the package com.studiosedition.utilities, I needed to first create a com directory with a subdirectory named studiosedition, with another subdirectory named utilities. Now that our class has been started we can take a look at how to start using it in the project.
http://www.peachpit.com/articles/article.aspx?p=772304&amp;seqNum=3
CC-MAIN-2017-17
refinedweb
541
60.85
Solaris Cluster boot fails with errors in globaldevices service (Doc ID 2407337.1) Last updated on JUNE 20, 2018 Applies to:Solaris Cluster - Version 3.2 and later Information in this document applies to any platform. Symptoms Solaris Cluster boot up fails with these error messages. efi_disk_path:link: Permission denied add_logical_efi_devices:ftw: Permission denied May 25 03:36:31 schost1 Cluster.CCR: Cannot reconfig Solaris namespace. Configuring DID devices obtaining access to all attached disks You may also notice that some files in / (root) can not be modified by or written to as root with permission denied error even though the file has write permission. In the same time new files can be written to the filesystem itself.
https://support.oracle.com/knowledge/Sun%20Microsystems/2407337_1.html
CC-MAIN-2018-39
refinedweb
118
57.47
120. Re: Will not boot into Safe Modelaughing_badger Feb 26, 2013 1:53 PM in response to kallisti Sure. Someone had posted that he had done a verbose safe boot and had seen the hang happened while fsck was checking the disk. So I wanted to make safe boot skip this step to see if that allowed the safe boot to complete, and to see if that then cured the log message issue. I did this by replacing the fsck binary that is called as part of a safe boot with something else. cd /sbin Go to where the fsck_hfs binary is. I found this by doing 'which fsck' and then by knowing that fsck calls another binary specific to the type of filesystem that is being checked. OSX uses HFS, so I needed to disable fsck_hfs. sudo mv fsck_hfs fsck_hfs_orig Move it to a new filename so that we keep a copy. sudo cp ~/true fsck_hfs Put a new binary in it's place. This is a simple bit of code that just returns the value zero. This is what fsck does if the disk was OK. So here we are setting up a trick that makes the safe boot process think that the disk has been checked and it was OK. For reference, the program was: #include <stdlib.h> int main( int argc, char* argv[] ) { return 0; } Standard C code, compiled with gcc. sudo chmod ugo+rx fsck_hfs This changes the file permissions to match what they were set to for the real binary. nvram boot-args="-x -v" This sets some flags in non-volatile RAM that will cause the machine to always boot with a verbose safe boot until told to do otherwise. reboot, log in Reboot the machine to let the safe boot proceed with our trick binary and wait until everything has completed and we can log into the machine. sudo nvram boot-args="" Clear the flags that we set earlier so that we get a normal boot next time. reboot Get the machine back into the state that we normally have it in. cd /sbin sudo mv fsck_hfs_orig fsck_hfs Clean up after ourselves by putting the original (working) binary for fsck into place. 121. Re: Will not boot into Safe Modekallisti Feb 26, 2013 2:24 PM in response to laughing_badger Thanks Badger! you're awesome 122. Re: Will not boot into Safe ModeJan Wessel Feb 26, 2013 2:24 PM in response to laughing_badger Thank you laughing_badger For me too this was very instructive 123. Re: Will not boot into Safe Modekallisti Feb 26, 2013 2:36 PM in response to laughing_badger alright, so if I understand, the following sequence should also work: cd /sbin sudo mv fsck_hfs fsck_hfs_orig sudo cp -p /usr/bin/true fsck_hfs nvram boot-args="-x -v" reboot, log in sudo nvram boot-args="" reboot cd /sbin sudo mv fsck_hfs_orig fsck_hfs 124. Re: Will not boot into Safe ModeOlaf Barthel Feb 27, 2013 12:09 AM in response to kallisti Just in case: changing the boot-args is not strictly necessary to make your computer go through the safe boot process. You could omit the 'nvram boot-args="-x -v"' command, restart your Mac and hold down any shift key until the safe boot process starts. Note that with the 'fsck_hfs' command taken out of the picture, the safe boot process can finish very quickly, and you may not even see the grey progress bar which is normally a sign that a safe boot is underway. 125. Re: Will not boot into Safe ModeSyth Feb 28, 2013 6:45 AM in response to Olaf Barthel Olaf Barthel wrote: Note that with the 'fsck_hfs' command taken out of the picture, the safe boot process can finish very quickly, and you may not even see the grey progress bar which is normally a sign that a safe boot is underway. This is useful to know because, yes, the boot process finishes very quickly and there is no really obvious way to know you're in safe mode. 126. Re: Will not boot into Safe ModeDavid Losada Mar 1, 2013 1:34 AM in response to Syth I tried again with a new DIMM. If I have the 8 RAM slots in my MacPro 5.1 populated I can't start in safe mode because the boot process gets stuck at "checking extranded attributes file". If I remove on of the DIMM, I can safe boot without problems. I can't understand it. 127. Re: Will not boot into Safe ModeOlaf Barthel Mar 1, 2013 2:07 AM in response to Syth If your Mac is set up to require that you enter a password before you can use it, there will be a message in the top right corner of the login screen (in red) to notify you that safe boot is in effect. I do not know if there is any similar hint message visible if your Mac is set up to log you in automatically. Truth be told, I triggered safe boot three times in a row before I noticed the message and realized that the first attempt was successful after all. 128. Re: Will not boot into Safe Modelaughing_badger Mar 1, 2013 2:20 AM in response to David Losada My guess is that there is a bug in the code for fsck_hfs that is only triggered with large amounts of memory available, and in the specific memory layout that occurs in safe boot. The next step would be to get a debuggable version of the code and have the safe boot process drop into the debugger before it does the disk check. More work than I have the time to go into at present, sadly. 129. Re: Will not boot into Safe ModeJeff Biggus Mar 4, 2013 5:29 PM in response to laughing_badger Many thanks badger on the great workaround for fsck. Works like a charm. You'd think a "safe" boot should be safer. (Sadly, it didn't end up curing my mdimport / lsboxd bug that I have been trying to cure by doing a safe boot to begin with, but it was good to know how to get it to work.) Fwiw, if it makes things easier for anyone, to make "true", all you need is this one line of code: int main(){} If you save that as true.c, compile it like this: clang -o true true.c (Clang knows to have the program return 0 by default. The import and the arguments to main aren't needed.) 130. Re: Will not boot into Safe ModeOlaf Barthel Mar 5, 2013 2:17 AM in response to Jeff Biggus It is simple enough if you have the software development tools installed Simpler still is just copying the existing "true" command from "/usr/bin/true", like so: sudo cp -pn /usr/bin/true fsck_hfs The "-pn" options make sure that the access rights to the command are preserved and that no existing file is overwritten (you need to move the original "fsck_hfs" command out of the way before you can plug in the dummy replacement). 131. Re: Will not boot into Safe ModeGraham Perrin Mar 14, 2013 3:02 PM in response to Graham Perrin In January I wrote: > I may have a workaround but it's too early to disclose. About the OS X Mountain Lion v10.8.3 Update does not mention safe boot, but safe boot began working for me whilst I tested a pre-release build of the update. To any user of OS X 10.8.2 who can not boot in safe mode, please: 1) update to 10.8.3 2) let us know whether 10.8.3 resolves the bug for you. If not resolved by 10.8.3, I'll offer my workaround. 132. Re: Will not boot into Safe ModeWidber Mar 14, 2013 3:07 PM in response to Graham Perrin Hello Graham, unfortunately the released v.10.8.3 didn't solve this safe boot issue 133. Re: Will not boot into Safe ModeJeff Biggus Mar 14, 2013 3:29 PM in response to Graham Perrin Hi Graham, No progress for me either on 10.8.3. Stalls at the same step. 134. Re: Will not boot into Safe ModeJan Wessel Mar 14, 2013 5:00 PM in response to Graham Perrin Hi Graham, Seem here, installed 10.8.3, but safe boot still stalls.
https://discussions.apple.com/message/21513028
CC-MAIN-2014-23
refinedweb
1,411
75.54
Html.RenderAction and Html.Action One of the upcoming new features being added to ASP.NET MVC 2 Beta is a little helper method called Html.RenderAction and its counterpart, Html.Action. This has been a part of our ASP.NET MVC Futures library for a while, but is now being added to the core product. Both of these methods allow you to call into an action method from a view and output the results of the action in place within the view. The difference between the two is that Html.RenderAction will render the result directly to the Response (which is more efficient if the action returns a large amount of HTML) whereas Html.Action returns a string with the result. For the sake of brevity, I’ll use the term RenderAction to refer to both of these methods. Here’s a quick look at how you might use this method. Suppose you have the following controller. public class MyController { public ActionResult Index() { return View(); } [ChildActionOnly] public ActionResult Menu() { var menu = GetMenuFromSomewhere(); return PartialView(menu); } } The Menu action grabs the Menu model and returns a partial view with just the menu. <%@ Control Inherits="System.Web.Mvc.ViewUserControl<Menu>" %> <ul> <% foreach(var item in Model.MenuItem) { %> <li><%= item %></li> <% } %> </ul> In your Index.aspx view, you can now call into the Menu action to display the menu: <%@ Page %> <html> <head><title></title></head> <body> <%= Html.Action("Menu") %> <h1>Welcome to the Index View</h1> </body> </html> Notice that the Menu action is marked with a ChildActionOnlyAttribute. This attribute indicates that this action should not be callable directly via the URL. It’s not required for an action to be callable via RenderAction. We also added a new property to ControllerContext named IsChildAction. This lets you know whether the action method is being called via a RenderAction call or via the URL. This is used by some of our action filters which should do not get called when applied to an action being called via RenderAction such as AuthorizeAttribute and OutputCacheAttribute. Passing Values With RenderAction Because these methods are being used to call action methods much like an ASP.NET Request does, it’s possible to specify route values when calling RenderAction. What’s really cool about this is you can pass in complex objects. For example, suppose we want to supply the menu with some options. We can define a new class, MenuOptions like so. public class MenuOptions { public int Width { get; set; } public int Height { get; set; } } Next, we’ll change the Menu action method to accept this as a parameter. [ChildActionOnly] public ActionResult Menu(MenuOptions options) { return PartialView(options); } And now we can pass in menu options from our action call in the view <%= Html.Action("Menu", new { options = new MenuOptions { Width=400, Height=500} })%> Cooperating with the ActionName attribute {.clear} Another thing to note is that RenderAction honors the ActionName attribute when calling an action name. Thus if you annotate the action like so. [ChildActionOnly] [ActionName("CoolMenu")] public ActionResult Menu(MenuOptions options) { return PartialView(options); } You’ll need to make sure to use “CoolMenu” as the action name and not “Menu” when calling RenderAction. Cooperating With Output Caching Note that in previous previews of the RenderAction method, there was an issue where calling RenderAction to render an action method that had the OutputCache attribute would cause the whole view to be cached. We fixed that issue by by changing the OutputCache attribute to not cache if it’s part of a child request. If you want to output cache the portion of the page rendered by the call to RenderAction, you can use a technique I mentioned here where you place the call to RenderAction in a ViewUserControl which has its OutputCache directive set. Summary Let us know how this feature works for you. I think it could really help simplify some scenarios when composing a user interface from small parts. 56 responses
https://haacked.com/archive/2009/11/18/aspnetmvc2-render-action.aspx/
CC-MAIN-2019-13
refinedweb
656
64
On Mon, 6 May 2002 22:53, Darrell DeBoer wrote: > On Mon, 6 May 2002 20:30, Peter Donald wrote: > > Hi, > > > > I just went and updated some of my older tasks to latest stuff you are > > doing with Librarys. Anyways before I got too far with that I was > > wondering where exactly you are going with the library stuff. Have you > > got a grand unified plan and if so want to xml-ize it and add it to our > > xdocs :) > > Hi Pete, > > Not exactly what you're asking, but I've been playing around with something > related, which I think will prove quite powerful. excellent. > The idea is to provide a namespace mechanism for type names, so that > multiple types with the same name can coexist. The idea runs as follows: woohoo! > 1) Types/TypeLibs can be registered under a namespace, which *may* be taken > from the AntlibDescriptor (say, an AntLib name attribute), but can also be > specified in other ways (eg <typelib library="ant1compat" >) I would prefer it to be based on the name of the antlib (ie internal name specified in manifest). I suppose we could support aliasing but I would like the importing to be very obvious that it is aliasing that is occuring. Maybe something like <typelib library="ant1compat" namespace- > 2) As works currently, Type name resolution occurs by first looking in the > local context, and then up through the parent contexts. yep. Same as propertys, and resources and anything else we add? > 3) When a TypeFactory is requested from the TypeManager, the name used can > be fully qualified (has a namespace), or not. A fully-qualified name > requests a named type registered under a particular namespace, whereas an > unqualified name involves searching all namespaces for the type name. If > the name cannot be resolved unambiguously within the context, an error > occurs. Sounds good. Basically this is the same way as imports are handled in java yes? > 4) The core antlibs (ant/lib/*) will be registered under an antlib name, +1 > 4a) Perhaps types explicitly type-def'd (not an entire library, a single > type), would be considered higher precedence again, above <import>ed > library types. +1 > 5) I'm also thinking about separating the TypeManager interface into a > superinterface (TypeRegistry?) with just the lookup methods, together with +1 (Matches how Converter evolved). > Question: > Is it appropriate to use XML namespaces for ant type namespaces? It has been -1'ed before due to complexity and extra cruft that it adds. We could still use ":" as separator but type resolution should follow the java import tules which I believe what you propose does ;) However I would prefer "." > (And if not, are we planning to utilise XML namespaces for anything?). At one stage I played with idea of basing "aspects" on namespaces but that turned out to be too complex an idea and most of its benefits can be got by simpler/better mechanisms (ie use ContainerTasks rather than aspects). Considering aspects are largely axed atm I am not sure I can see it be using at all ... -- Cheers, Peter Donald -- To unsubscribe, e-mail: <mailto:ant-dev-unsubscribe@jakarta.apache.org> For additional commands, e-mail: <mailto:ant-dev-help@jakarta.apache.org>
http://mail-archives.eu.apache.org/mod_mbox/ant-dev/200205.mbox/%3C200205081943.59291.peter@apache.org%3E
CC-MAIN-2020-10
refinedweb
536
58.52
is it possible in C++ to receive a word(String) as input and add that string in a statement (if -else or anything ) like python . giving a python code below num1 = int(input("Enter the first number ")) num2 = int(input("Enter the second number ")) print("Type Sum for calculate sum ") print("Type Sub for calculate .. Category : user-input Quite simply, I have passed a large string as an input to GMP’s mpz_class constructor, and the value is a different integer. These values were acquired through vs code’s debugger. From the main file: User john(1024, "340282366920938463463370103832140841039", "340282366920938463463370103832140841051", 17); The User constructor: User::User(const int k, std::string p, std::string q, const int e) { this->m_k = .. I have tried so many things to try and get this working. I am very new to dynamic SQL, and the Internet doesn’t seem to be helping me very much. I am trying to get this query working, but I don’t understand how to implement the ? with taking in any of the input. I .. I’m facing a bug where, after taking in the user input from a while loop, my code does not accept the last value. This bug happens on ONE specific example, and I have no clue why this is happening. So, for example, the user inputs: 7 3 1 4 0 0 2 0 The output .. So I am making a tic tac toe game, user vs pc with a simple random generator. What I was planning was to make a counter of how many times the user inputs a choice on the tic tac toe board. That way I can generate a random number, and place it in a vector, .. #include <iostream> #include "multiplication.h" #include "subtraction.h" using namespace std; int main() { multiplication out; subtraction out2; int x, y, z; int product; int difference; cout << "Enter two numbers to multiply by: "; cin >> x; cin >> y; product = out.mult(); cout << "the product is: " << product; cout << "Now enter a .. I am trying to program a school bulletin (I’m sorry if that’s not the right word, what I meant with "bulletin" is the thing were are the grades of each student. English isn’t my 1° language) and I want to ask the user the name of the student and then create a int student_name; so .. Recently I have been starting to participate in c++ contests but I cannot find the best way to handle user input when given in this format. E.g. 4 and 3 are the dimensions of the next block of input 4 3 1 2 4 5 1 6 7 4 1 5 0 0 The problem .. I want to use Octal/Hexadecimal numbers in my program. Is there any way to directly input an Octal/Hexadecimal number in C++? Source: Windows Que.. In my case, I have to make sure the user input is either 1 or 2, or 3. Here’s my code: #include <iostream> using namespace std; void invalid_choice_prompt() { string msg = "nInvalid Command! Please try again."; cout << msg << endl; } int ask_user_rps_check_input(int user_choice) { if (user_choice == 1 || user_choice == 2 .. Recent Comments
https://windowsquestions.com/category/user-input/
CC-MAIN-2022-05
refinedweb
524
71.65
Namespace style opinions I’m currently finishing development on a [pattr] based preset system that will use a family of Max Abstractions and JavaScripts. Once development is complete, I am planning on looking into rewriting the system with some native objects in C. I was curious if anyone had any thoughts of how I should handle the namespaces between the Max versions and the C versions. At first I thought I would give them the same names because in my own work, I would be aware of the name conflict and be able to avoid problems due to potential conflicts. Have any of you done developed projects this way? Have any thoughts on how to handle the namespaces between versions? Thanks! In terms of using namespace-style organization in Max (not specific to externals in C). I give each project (or library, or large complex object that will be used in more than one project) a prefix. Then, when i’m adding patches or externals, i divide them up into "namespaces" based on what they do (and i generally end up with more than one level of these). Then each new patch or external (or even images and data files) is named starting with it’s namespace followed by it’s specific name. For example, a project of mine called scrlt contains stuff like this: scrlt.main.maxpat – main root patch scrlt.midi.bcr.maxpat – sub-patch that handles midi interaction with a BCR2000 scrlt.midi.bcr.node.knob.maxpat – sub-patch that represents a single knob on the BCR2000 and so on. Dealing with situations where i’m re-writing components is a bit less clear. Often, if i know that i’m doing a quick prototype patch and i know that i’m going to end up rewriting it, i’ll add a suffix of some sort to the file name. Something like scrlt.bigobject.proto.maxpat. Then i use the normal name, i.e. scrlt.bigobject.mxe for the new version. When i want to switch patches that use the object to the new version, i all of the relevant patches in a text editor, and do a find/replace on the name to remove the suffix (if you’re using pre-Max5, save them in the mxt text format).
http://cycling74.com/forums/topic/namespace-style-opinions/
CC-MAIN-2014-35
refinedweb
383
70.53
Agenda See also: IRC log <trackbot> Date: 25 August 2009 <Bob> trackbot, start telecon <trackbot> Meeting: Web Services Resource Access Working Group Teleconference <trackbot> Date: 25 August 2009 <Bob> scribe: Li Li <Bob> scribenick: Li agenda agreed <Bob> minutes link RESOLUTION: Minutes of 2009-08-18 accepted Yves confirms that he will be able to chair Logistics info at ram had some comments dug and ram figure out which comments and agree they are resolved <dug> comments at RESOLUTION: Incorporated resolutions in 2009-07-24 snapshots of mex and rt accepted Bob: Notes that good progress has been made on action items and and reminds members to keep an eye on due dates ram: needs a few more days to polish bob: fpwd needs to be out by sept (next month) in order to hold our schedule ram: that's acceptable bob: objection to proposal? RESOLUTION: Issue-7365 resolved as proposed <dug> Dug: explains issue and proposal <dug> ** New dialect <dug> definitions MUST include sufficient information for proper application. <dug> For example, it would need to include the context (which data) over which <dug> the filter operates. *** bob: append proposed text to previous proposal? asir: when does context change? dug: context of xpath changes from envelope to event data context may change for other uri too, like actionURI Asir: i don't recall discussing change of context being discussed <dug> "... a new dialect might be defined to support filtering based on data not included in the notification message itself." Gil: generic use of xpath is insufficient as it doesn't tell the context therefore, ws-e needs a new uri to convey the context Asir: it's new to me that uri indicates context Dug: filter always needs context Tom: do we need context to complicate thing? Dug: yes, we have filter on action, topic, etc. beside just event data itself Asir: uri needs to point to stable xpath Dug: maybe to separate flexibility to another issue Bob: we can define a uri for backward compability, folks will be able to define a filter accordingly Asir: it's ok if this is a simple case <asir> Asir: if we were to define our own namespace name then this would be a unique case and not set any precedence Dug: we have to do it as gil explained the use cases Asir: it's not clear what is replaced Dug: two parts: one is to swap out uri; the other is the text <dug> new text is in: figuring out the consolidated proposal... asir: make uri to xpath 1.0? daves: a different uri for xpath 2.0 then? <asir> Here is the draft proposal <asir> 1. Append to Section '[Body]/wse:Subscribe/wse:Filter/@Dialect <asir> ' <asir> *** New dialect definitions MUST include sufficient informalion for proper application. For example, it would need to include the context (which data) over which the filter operates. *** <asir> 2. Replace with <dug> 3. and similar for enum bob: any object to the above proposal to 7235? RESOLUTION: Issue-7235 resolved with proposal above without objection <dug> Unless otherwise noted, all URIs are absolute URIs and URI comparison MUST be performed according to [RFC 3986] section 6.2.1. <Ram> test yves: it's better to stay within uri instead of iri Bob: any objections to the proposal? ram: any exception to the general rule? dug: i couldn't find any... RESOLUTION: Issue-7270 resolved as proposed RESOLUTION: Issue- 7160 resolved as proposed RESOLUTION: Issue-7426 accepted as a new issue bob: ban the use of iri where uri comparison is used? <dug> can we see some text? AI for yves to propose text for 7426 <asir> ACTION: Yves to propose text for issue 7426 [recorded in] <trackbot> Created ACTION-97 - Propose text for issue 7426 [on Yves Lafon - due 2009-09-01]. <asir> Didn't you resolve it last week? <asir> doubly resolved! RESOLUTION: Issue-7196 resolved (or resolution confirmed) yves: explains the issue dug: why do we need this? yves: we need to specify the property of that operation dug: do we need to do the same for "getstatus"? yves: we should spell out for all safe operations <gpilz> +1 dug: then we need to apply it to all specs asir: why not idempotent? <asir> Here is a link to Feb discussion ... yves: we could do that if people like it gil: this is a constraint on implementations ... we should do it for other specs as well <dug> +1 obviously gil: find all safe operations first <scribe> ACTION: yves to include all safe operations in all specs [recorded in] <trackbot> Created ACTION-98 - Include all safe operations in all specs [on Yves Lafon - due 2009-09-01]. <gpilz> gil: explains the new proposal 6401 looks ok to me <dug> interesting - I'm missing the section header for appendix A when I look at the html version too - but the word doc is ok <dug> dug: some editorial changes, remove duplicates about mex <Bob> Dug presents an amended proposal <Ram> I would like to understand this sentence in Dug's revision: "An Event Source there MUST NOT exist more than one EventDescription document." ram: why that constraint? dug: it's in the original proposal gil: more than ED document complicates relations to NW asir: i don't fully understand the requirement ... to relate ED and NW dug: one ED doc should be returned, more than one adds complexity ... one ED doc hides complexity asir: multiple docs is supported by mex in multi sections <Zakim> dug, you wanted to ask a clarifying question dug: what subscriber do with multi docs? asir: client handles multi-docs according to the standards gil: we are profiling mex ... we make it clear how different parts are related <asir> Gil - i was only trying to help you! Nothing more. <dug> sorry - power went out gil: if two ED docs and two NW docs are returned, then which goes which is not clear <asir> Vow .. are we closing 6401? +q <dug> never! :-) <dug> I can send in a new rev with the typo that Ram noticed fixed <dug> if people want li: would like to read it ram: we would like to postpone it until next week bob: review dug's proposal next week as basis of 6401 <DaveS> Goodnight <gpilz> good job li! bob: declare victory for today...
http://www.w3.org/2002/ws/ra/9/08/2009-08-25.html
CC-MAIN-2016-50
refinedweb
1,058
56.49
23 May 2012 10:45 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> The Chinese economy performed far below expectations in April when growth in industrial production, imports, exports, fixed-asset investment and bank lending all slowed. Worse news for May is widely expected, according to analysts. “This has caused increasing concern to policy makers,” said Zhang Junfeng, senior analyst at Shenzhen-based broker China Merchants Securities (CMS). The forthcoming measures would focus on boosting domestic consumption, the analysts said. The most effective and direct method would be to lower lending costs to motivate consumers and businesses to spend. “We expect that the country will lower banks’ reserve requirement ratio [RRR] further in mid-June after the release of the data for May,” Zhang said, adding that an interest rate cut may be announced in July should the RRR policy fail to deliver. RRR had been reduced twice this year, on 24 February and 18 May. The government may also broaden tax reductions. “The government has realised that tax rates are quite high for many industries and a lower tax burden would help stimulate consumption,” said Wu Huaiguo at Guangzhou-based broker United Securities. Measures on boosting investment would be limited, analysts said, saying it was unlikely that the government would relax restrictions on property markets. On Wednesday, the World Bank cut its economic growth forecast
http://www.icis.com/Articles/2012/05/23/9562542/china-mulls-stimulus-policy-to-boost-economy-analysts.html
CC-MAIN-2015-14
refinedweb
225
53
Error module not found: Can't resolve 'react' in ReactJs I'm trying to connect my Redux store to my React project, but I keep getting this error: ../node_modules/react-redux/es/components/Provider.js Module not found: Can't resolve 'react' in 'C:\Users.\Documents..\node_modules\react-redux\es\components' I've installed both react-redux and redux import React, { Component } from 'react'; import ReactDOM, { render } from 'react-dom'; import { Provider} from 'react-redux'; How can I resolve it? - N0 Nguyen Truong Giang Jun 06 2021 Try removing package-lock.json, run npm installand then npm startagain. Please also share your package.jsonfile. If it doesn't help, install an older version of npm (e.g. 3.x). 5.x is still fairly buggy and might be causing this. I'll close because it is not an issue on our side. npm just failed to install the reactmodule for some reason. - T0 Tu Hoang Jun 06 2021 This could be caused by your node_modules At the first delete your node_modules, package-lock.json, yarn.lock then install all dependencies again using like rm -rf node_modules rm -rf package-lock.json rm -rf yarn.lock then run npm install I hope it resolves that issue for you. * Type maximum 2000 characters. * All comments have to wait approved before display. * Please polite comment and respect questions and answers of others.
https://quizdeveloper.com/faq/error-module-not-found-cant-resolve-react-in-reactjs-aid1228
CC-MAIN-2021-31
refinedweb
229
59.8
Changes for version 1.302015 - 2016-05-09 - Add Test::Alien to breakage info - Add Device::Chip to breakage info - Add subtest outdent to transition.pod Changes for version 1.302014_010 - 2016-05-03 (TRIAL RELEASE) - RC10 - Update x-breaks, Breakage.pm, and Transition.POD - Fix shared memory leak - Fix typos and clarify docs. Changes for version 1.302014_009 - 2016-04-27 (TRIAL RELEASE) - RC9 - No logic changes - Update x-breaks stuff - Update email addresses Changes for version 1.302014_008 - 2016-04-26 (TRIAL RELEASE) - RC8 - Fix bug when using defined, but empty (or space) as a test name in a subtest - Better notificatons for late Test::Builder load - Recommend Test2::Transition if you have outdated modules - Document Test::Builder::TodoDiag and Test::Builder::Formatter Changes for version 1.302014_007 - 2016-04-24 (TRIAL RELEASE) Changes for version 1.302014_006 - 2016-04-24 (TRIAL RELEASE) - RC6 - Remove reduntant and problematic parts of 00-report.t - No changes to actual code, just a test that provides diags Changes for version 1.302014_005 - 2016-04-24 (TRIAL RELEASE) - RC5 - Prevent the breakage reporter from being a test failure - No changes to actual code, just a test that provides diags Changes for version 1.302014_004 - 2016-04-23 (TRIAL RELEASE) - RC4 - Update breakage info - Fix IPC files driver to use the most significant data in the shm (needs test) Changes for version 1.302014_003 - 2016-04-23 (TRIAL RELEASE) - RC3 - Localize $@ and $! when loading Data::Dumper in explain() Changes for version 1.302014_002 - 2016-04-22 (TRIAL RELEASE) - RC2 - Restore X-Breaks meta info - Keep dist.ini in the tarball Changes for version 1.302014_001 - 2016-04-22 (TRIAL RELEASE) - RC1 - Merge Test2 into the Test-Simple dist - Remove experimental status - Update copyright dates - Better error messages when using Carp in Hashbase init() - Document 2 methods on Events - Fix Test2 #17 (typo fix in docs) - Report version mismatches between Test::Builder and Test2 - Update transition docs - Breakage library and warnings - BELOW THIS POINT ARE THE SEPERATE CHANGELOGS FOR Test-Simple, Test2, AND * - Test-Stream. * - Test-Simple 1.302013_019 2016-04-13 20:23:18-07:00 America/Los_Angeles (TRIAL RELEASE) - Expand no_numbers support to custom formatters - Test-Simple 1.302013_018 2016-04-07 21:23:03-07:00 America/Los_Angeles (TRIAL RELEASE) - Support Test2 using an alternative formatter - Test-Simple 1.302013_017 2016-04-05 11:13:50-07:00 America/Los_Angeles (TRIAL RELEASE) - Support subtest identification for events - Bump minimum Test2 version - Test-Simple 1.302013_016 2016-04-04 21:33:20-07:00 America/Los_Angeles (TRIAL RELEASE) - Support some newer event features from Test2 - Bump minimum Test2 version - Test-Simple 1.302013_015 2016-03-29 09:24:10-07:00 America/Los_Angeles (TRIAL RELEASE) - Bump minimum Test2 version to protect from segv - Test-Simple 1.302013_014 2016-03-08 10:00:50-08:00 America/Los_Angeles (TRIAL RELEASE) - Skip test added in last release when threading is not avilable - Test-Simple 1.302013_013 2016-03-08 09:19:39-08:00 America/Los_Angeles (TRIAL RELEASE) - Test-Simple 1.302013_012 2016-01-28 20:38:16-08:00 America/Los_Angeles (TRIAL RELEASE) - $Level effects all contexts once Test::Builder is loaded - Requires Test2 0.000023 - Test-Simple 1.302013_011 2016-01-14 21:55:28-08:00 America/Los_Angeles (TRIAL RELEASE) - Performance enhancements - Test-Simple 1.302013_010 2016-01-12 05:57:43-08:00 America/Los_Angeles (TRIAL RELEASE) - Changes needed for Test2 0.000018 - Test-Simple 1.302013_009 2016-01-11 16:35:57-08:00 America/Los_Angeles (TRIAL RELEASE) - Test-Simple 1.302013_008 2016-01-10 13:21:02-08:00 America/Los_Angeles (TRIAL RELEASE) - Bump minimum Test2 version requirement (to fix downstream) - Test-Simple 1.302013_007 2016-01-07 19:30:04-08:00 America/Los_Angeles (TRIAL RELEASE) - Bump minimum Test2 version requirement - Test-Simple 1.302013_006 2016-01-06 11:21:48-08:00 America/Los_Angeles (TRIAL RELEASE) - Update for Test2 0.000013 - Delay loading Data::Dumper - Test2::API::test2_no_wait(1) when threads/forking are on - Fix Test::Tester to use context - More downstream dists for testing - Test-Simple 1.302013_005 2015-12-29 13:01:32-08:00 America/Los_Angeles (TRIAL RELEASE) - Updates for Test2 0.000012 - Helper for Test::SharedFork - Test-Simple 1.302013_004 2015-12-28 13:12:23-08:00 America/Los_Angeles (TRIAL RELEASE) - Fix diag/note bugs from refactor - Test-Simple 1.302013_003 2015-12-22 09:41:46-08:00 America/Los_Angeles (TRIAL RELEASE) - Fix bug in details() structure for subtests when the parent is todo - Test-Simple 1.302013_002 2015-12-21 13:21:51-08:00 America/Los_Angeles (TRIAL RELEASE) - Updates for Test2 0.000010 - Test-Simple 1.302013_001 2015-12-21 10:07:42-08:00 America/Los_Angeles (TRIAL RELEASE) - Switch to using Test2 under the hood - Use Dist::Zilla for releases - Reformat Changes file - Test-Simple 1.302012_004 2015-Nov-16 07:45:11-08:00 PST - Test-Simple 1.302012_003 2015-Oct-27 00:02:44-08:00 PST - Fix typo that called wrong 'try' - Test-Simple 1.302012_002 2015-Oct-02 21:57:19-08:00 PST - Test-Simple 1.302012_001 2015-Oct-01 15:47:39-08:00 PST - Support for Test::Stream 1.302012 - Test-Simple 1.302010_001 2015-Sep-29 21:18:38-08:00 PST - Support for Test::Stream 1.302010 - Some upstream package names changed - Test::Stream's interface changed, tests needed to change too. - Test-Simple 1.302007_004 2015-Jul-27 21:13:39-08:00 PST - Work around perlbug 125702 - Test-Simple 1.302007_003 2015-Jul-24 08:34:46-08:00 PST - Remove singleton from closure - Test-Simple 1.302007_002 2015-Jul-18 17:38:26-08:00 PST - Fix subtest + Test::Stream::Tester - Test-Simple 1.302007_001 2015-Jun-24 08:06:00-08:00 PST - Tests no longer copy thread/fork checks - Bump minimum Test::Stream version - Test-Simple 1.302004_001 2015-Jun-17 08:33:00-08:00 PST - Test-Simple 1.302003_001 2015-Jan-06 21:52:00-08:00 PST - Convert internals to use Test-Stream - Optimizations for performance - Note this is a completely new branch off of legacy/master, not taken from the old stream branches - Test-Simple 1.001014 2014-Dec-28 08:31:00-08:00 PST - Write a test to ensure this changes file gets updated - Update changes file for 1.001013 - Test-Simple 1.001013 2014-Dec-28 08:00:00-08:00 PST - Fix a unit test that broke on some platforms with spaces in the $^X path - Test-Simple 1.001012 2014-Dec-23 07:39:00-08:00 PST - Move test that was dropped in the wrong directory - Test-Simple 1.001011 2014-Dec-20 09:08:00-08:00 PST - Remove POD Coverage test - Test-Simple 1.001010 2014-Dec-19 20:16:00-08:00 PST - Test-Simple 1.001009 2014-Nov-2 22:31:08-08:00 PST - Fix bug in cmp_ok - Test-Simple 1.001008 2014-Oct-15 20:10:22-08:00 PST - Updated Changes file - Test-Simple 1.001007 2014-Oct-15 16:37:11-08:00 PST - Fix subtest name when skip_all is used - Test-Simple 1.001006 2014-Sep-2 14:39:05-08:00 PST - Reverted change that is now part of alpha branch - Test-Simple 1.001005 2014-Sep-2 19:47:19-08:00 JST - Changed install path for perl 5.12 or higher. - Test-Simple 1.001004_003 2014-May-17 13:43-08:00 PST - Test-Simple 1.001004_002 2014-May-17 13:43-08:00 PST - Minor doc fix to solve test bug - Test-Simple 1.001004_001 2014-May-10 08:39-08:00 PST - Doc updates - Subtests accept args - Outdent subtest diag - Test-Simple 1.001003 2014-Mar-21 21:12-08:00 PST - Doc updates for maintainer change - Test-Simple 1.001002 2013-Nov-4 15:13-08:00 EST - no changes since 0.99 - Test-Simple 1.001001_001 2013-Oct-30 20:47-08:00 EDT - no code changes, just a new version number with more room to grow - Test-Simple 0.99 2013-Oct-29 13:21:03-08:00 EDT - restore ability to use regex with test_err and test_out (Zefram) [rt.cpan.org #89655] [github #389] [github #387] - Test-Simple 0.99 2013-Oct-12 15:05-08:00 EDT - no changes since 0.98_06 - Test-Simple 0.98_06 2013-Sep-27 10:11-08:00 EDT Bug Fixes - Fix precedence error with (return ... and ...) (nthykier) [github #385] - Test-Simple 0.98_05 2013-Apr-23 17:33-08:00 PDT) - Test-Simple 0.98_04 2013-Apr-14 10:54-08:00 BST) - Test-Simple 0.98_03 2012-Jun-21 13:04-08:00 PDT. - Test-Simple 0.98_02 2011-Nov-24 01:13-08:00 PST Bug Fixes - use_ok() in 0.98_01 was leaking pragmas from inside Test::More. This looked like Test::More was forcing strict. [rt.cpan.org 67538] (Father Chrysostomos) - Test-Simple 0.98_01 2011-Nov-8 17:07-08:00 PST] - Test-Simple 0.98 2011-Fev-23 14:38:02 +1100 Bug Fixes - subtest() should not fail if $? is non-zero. (Aaron Crane) - Docs - The behavior of is() and undef has been documented. (Pedro Melo) - Test-Simple 0.97_01 2010-Aug-27 22:50-08:00 PDT] - Test-Simple 0.96 2010-Aug-10 21:13-08:00 PDT Bug Fixes - You can call done_testing() again after reset() [googlecode 59] - Other - Bug tracker moved to github - Test-Simple 0.95_02 2010-May-19 15:46-08:00 PDT) - Test-Simple 0.95_01 2010-Mar-3 15:36-08:00 PST. - Test-Simple 0.94 2009-Sep-2 11:17-08:00 PDT Releasing 0.93_01 as stable. - Test-Simple 0.93_01 2009-Jul-20 09:51-08:00 PDT Bug Fixes - Make sure that subtest works with Test:: modules which call Test::Builder->new at the top of their code. (Ovid) - Other - subtest() returns! - Test-Simple 0.92 2009-Jul-3 11:08-08:00 PDT Test Fixes - Silence noise on VMS in exit.t (Craig Berry) - Skip Builder/fork_with_new_stdout.t on systems without fork (Craig Berry) - Test-Simple 0.90 2009-Jul-2 13:18-08:00 PDT Docs - Note the IO::Stringy license in our copy of it. - test-more.googlecode.com 47 - Other - This is a stable release for 5.10.1. It does not include the subtest() work in 0.89_01. - Test-Simple 0.89_01 2009-Jun-23 15:13-08:00 EDT - Test-Simple 0.88 2009-May-30 12:31-08:00 PDT Turing 0.87_03 into a stable release. - Test-Simple 0.87_03 2009-May-24 13:41-08:00 PDT New Features - isa_ok() now works on classes. (Peter Scott) - Test-Simple 0.87_02 2009-Apr-11 12:54-08:00 PDT. - Test-Simple 0.87_01 2009-Mar-29 09:56-08:00 BST. - Test-Simple 0.86 2008-Nov-9 01:09-08:00 PST Same as 0.85_01 - Test-Simple 0.85_01 2008-Oct-23 18:57-08:00 PDT. - Test-Simple 0.84 2008-Oct-15 09:06-08:00 EDT Other - 0.82 accidentally shipped with experimental Mouse dependency. - Test-Simple 0.82 2008-Oct-14 23:06-08:00 EDT Bug Fixes - 0.81_01 broke $TODO such that $TODO = '' was considered todo. - Test-Simple 0.81_02 2008-Sep-9 04:35-08:00 PDT] - Test-Simple 0.81_01 2008-Sep-6 15:13-08:00 PDT] - Test-Simple 0.80 2008-Apr-6 17:25-08:00 CEST Test fixes - Completely disable the utf8 test. It was causing perl to panic on some OS's. - Test-Simple 0.79_01 2008-Feb-27 03:04-08:00 PST Bug fixes - Let's try the IO layer copying again, this time with the test fixed for 5.10. - Test-Simple 0.78 2008-Feb-27 01:59-08:00 PST Bug fixes - Whoops, the version of Test::Builder::Tester got moved backwards. - Test-Simple 0.77 2008-Feb-27 01:55-08:00 PST(). - Test-Simple 0.76_02 2008-Feb-24 13:12-08:00 PST Bug fixes - The default test output filehandles will NOT use utf8. They will now copy the IO layers from STDOUT and STDERR. This means if :utf8 is on then it will honor it and not warn about wide characters. - Test-Simple 0.76_01 2008-Feb-23 20:44-08:00 PST. - Test-Simple 0.75 2008-Feb-23 19:03-08:00 PST. - Test-Simple 0.74 2007-Nov-29 15:39-08:00 PST Misc - Add abstract and author to the meta information. - Test-Simple 0.73_01 2007-Oct-15 20:35-08:00 EDT Bug fixes - Put the use_ok() fix from 0.71 back. - Test-Simple 0.72 2007-Sep-19 20:08-08:00 PDT Bug unfixes - The BEGIN { use_ok } fix for [rt.cpan.org 28345] revealed a small pile of mistakes in CPAN module test suites. Rolling the fix back to give the authors a bit of time to fix their tests. - Test-Simple 0.71 2007-Sep-13 20:42-08:00 PDT. - Test-Simple 0.70 2007-Mar-15 15:53-08:00 PDT Bug Fixes - The change to is_fh() in 0.68 broke the case where a reference to a tied filehandle is used for perl 5.6 and back. This made the tests puke their guts out. - Test-Simple 0.69 2007-Mar-14 06:43-08:00 PDT Test fixes - Minor filename compatibility fix to t/fail-more.t [rt.cpan.org 25428] - Test-Simple 0.68 2007-Mar-13 17:27-08:00 PDT] - Test-Simple 0.67 2007-Jan-22 13:27-08:00 PST Test fixes - t/pod_coverage.t would fail if Test::Pod::Coverage between 1.07 and 1.00 were installed as it depended on all_modules being exported. - rt.cpan.org 24483 - Test-Simple 0.66 2006-Dec-3 15:25-08:00 PST - Restore 5.4.5 compatibility (unobe@cpan.org) [rt.cpan.org 20513] - Test-Simple 0.65 2006-Nov-10 10:26-08:00 CST - Test-Simple 0.64_03 2006-Nov-5 13:09-08:00 EST - - Test-Simple 0.64_02 2006-Sep-9 12:16-08:00 EDT - Last release broke Perls earlier than 5.8. - Test-Simple 0.64_01 2006-Sep-4 04:40-08:00 EDT -. - Made the failure diagnostic message file and line reporting portion match Perl's for easier integration with Perl aware editors. (so its "at $file line $line_num." now) - 5.8.0 threads are no longer supported. There's too many bugs. - Test-Simple 0.64 2006-Jul-16 02:47-08:00 PDT -. - Test-Simple 0.63 2006-Jul-9 02:36-08:00 PDT -. - Test-Simple 0.62 2005-Oct-8 01:25-08:00 PDT - - Test-Simple 0.61 2005-Sep-23 23:26-08:00 PDT - - Test-Simple 0.60_02 2005-Aug-9 00:27-08:00 PDT -. - Test-Simple 0.60_01 2005-Jul-3 18:11-08:00 PDT -. - Test-Simple 0.60 2005-May-3 14:20-08:00 PDT - Test-Simple 0.59_01 2005-Apr-26 21:51-08:00 PDT -. - Test-Simple 0.54 2004-Dec-15 04:18-08:00 EST - - Test-Simple 0.53_01 2004-Dec-11 19:02-08:00 EST -] - Test-Simple 0.53 2004-Nov-29 04:43-08:00 EST - Apparently its possible to have Module::Signature installed without it being functional. Fixed the signature test to account for this. (not a real bug) - Test-Simple 0.52 2004-Nov-28 21:41-08:00 EST - plan() now better checks that the given plan is valid. - rt.cpan.org 2597 - Test-Simple 0.51_02 2004-Nov-27 01:25-08:00 EST -. - Test-Simple 0.51_01 2004-Nov-26 02:59-08:00 EST -. - Test-Simple 0.51 2004-Nov-23 04:51-08:00 EST - Fixed bug in fail_one.t on Windows (not a real bug). - TODO reasons as overloaded objects now won't blow up under threads. - Autrijus Tang - skip() in 0.50 tickled yet another bug in threads::shared. Hacked around it. - Test-Simple 0.50 2004-Nov-20 00:28-08:00 EST - - Test-Simple 0.49 2004-Oct-14 21:58-08:00 EDT - t/harness_active.t would fail for frivolous reasons with older MakeMakers (test bug) [thanks Bill Moseley for noticing] - Test-Simple 0.48_02 2004-Jul-19 02:07-08:00 EDT - - Test-Simple 0.48_01 2002-Nov-11 02:36-08:00 EST -. - Test-Simple 0.47 2002-Aug-26 03:54-08:00 PDT -. - Test-Simple 0.46 2002-Jul-20 19:57-08:00 EDT -] - Test-Simple 0.45 2002-Jun-19 18:41-08:00 EDT - Test-Simple 0.44 2002-Apr-25 00:27-08:00 EDT -) - Test-Simple 0.43 2002-Apr-11 22:55-08:00 EDT - Adrian Howard added TB->maybe_regex() - Adding Mark Fowler's suggestion to make diag() return false. - TB->current_test() still not working when no tests were run via TB itself. Fixed by Dave Rolsky. - Test-Simple 0.42 2002-Mar-6 15:00-08:00 EST -. - Test-Simple 0.41 2001-Dec-17 22:45-08:00 EST - chromatic added diag() - Internal eval()'s sometimes interfering with $@ and $!. Fixed. - Test-Simple 0.40 2001-Dec-14 15:41-08:00 EST -. - Test-Simple 0.36 2001-Nov-29 14:07-08:00 EST - Matthias Urlichs found that intermixed prints to STDOUT and test output came out in the wrong order when piped. - Test-Simple 0.35 2001-Nov-27 19:57-08:00 EST - Little glitch in the test suite. No actual bug. - Test-Simple 0.34 2001-Nov-27 15:43-08:00 EST - **API CHANGE** Empty string no longer matches undef in is() and isnt(). - Added isnt_eq and isnt_num to Test::Builder. - Test-Simple 0.33 2001-Oct-22 21:05-08:00 EDT - It's now officially safe to redirect STDOUT and STDERR without affecting test output. - License and POD cleanup by Autrijus Tang - Synched up Test::Tutorial with the wiki version - Minor VMS test nit. - Test-Simple 0.32 2001-Oct-16 16:52-08:00 EDT - Finally added a separate plan() function - Adding a name field to isa_ok() (Requested by Dave Rolsky) - Test::More was using Carp.pm, causing the occasional false positive. (Reported by Tatsuhiko Miyagawa) - Test-Simple 0.31 2001-Oct-8 19:24-08:00 EDT -) - Test-Simple 0.30 2001-Sep-27 22:10-08:00 EDT -. - Test-Simple 0.20 *UNRELEASED* - Test-Simple 0.19 2001-Sep-18 17:48-08:00 EDT -. - Test-Simple 0.18 2001-Sep-5 20:35-08:00 EDT - ***API CHANGE*** can_ok() only counts as one test - can_ok() has better diagnostics - Minor POD fixes from mjd - adjusting the internal layout to make it easier to put it into the core - Test-Simple 0.17 2001-Aug-29 20:16-08:00 EDT - Added can_ok() and isa_ok() to Test::More - Test-Simple 0.16 2001-Aug-28 19:52-08:00 EDT - vmsperl foiled my sensible exit codes. Reverting to a much more coarse scheme. - Test-Simple 0.15 2001-Aug-28 06:18-08:00 EDT *UNRELEASED* - Now using sensible exit codes on VMS. - Test-Simple 0.14 2001-Aug-22 17:26-08:00 EDT - Added a first cut at Test::Tutorial - Test-Simple 0.13 2001-Aug-14 15:30-08:00 EDT - Added a reason to the skip_all interface - Fixed a bug to allow 'use Test::More;' to work. (Thanks to Tatsuhiko Miyagawa again) - Now always testing backwards compatibility. - Test-Simple 0.12 2001-Aug-14 11:02-08:00 EDT - Fixed some compatibility bugs with older Perls (Thanks to Tatsuhiko Miyagawa) - Test-Simple 0.11 2001-Aug-11 23:05-08:00 EDT - Will no longer warn about testing undef values - Escaping # in test names - Ensuring that ok() returns true or false and not undef - Minor doc typo in the example - Test-Simple 0.10 2001-Jul-31 15:01-08:00 EDT - Test::More is now distributed in this tarball. - skip and todo tests work! - Extended use_ok() so it can import - A little internal rejiggering - Added a TODO file - Test-Simple 0.09 2001-Jun-27 02:55-08:00 EDT - VMS fixes - Test-Simple 0.08 2001-Jun-15 14:39-08:00 EDT - Guarding against $/ and -l - Reformatted the way failed tests are reported to make them stand out a bit better. - Test-Simple 0.07 2001-Jun-12 15:55-08:00 BST - 'use Test::Simple' by itself no longer causes death - Yet more fixes for death in eval - Limiting max failures reported via exit code to 254. - Test-Simple 0.06 2001-May-9 23:38-08:00 BST - Whoops, left a private method in the public docs. - Test-Simple 0.05 2001-May-9 20:40-08:00 BST - Forgot to include the exit tests. - Trouble with exiting properly under 5.005_03 and 5.6.1 fixed - Turned off buffering - 5.004 new minimum version - Now explicitly tested with 5.6.1, 5.6.0, 5.005_03 and 5.004 - Test-Simple 0.04 2001-Apr-2 11:05-08:00 BST - Fixed "require Test::Simple" so it doesn't bitch and exit 255 - Now installable with the CPAN shell. - Test-Simple 0.03 2001-Mar-30 08:08-08:00 BST - ok() now prints on what line and file it failed. - eval 'die' was considered abnormal. Fixed. - Test-Simple 0.02 2001-Mar-30 05:12-08:00 BST . - Test-Simple 0.01 2001-Mar-28 06:44-08:00 BST - First working version released to CPAN - Test2 0.000044 2016-04-30 13:56:25-07:00 America/Los_Angeles - Remove things that should nto have been backported from Test-Simple merger - Test2 0.000043 2016-04-30 05:21:51-07:00 America/Los_Angeles - Test2 0.000042 2016-04-15 13:17:21-07:00 America/Los_Angeles - Let TAP render generic events - Add the no_display method to the Event API - Improve T2_FORMATTER parsing - Test2 0.000041 2016-04-13 20:21:38-07:00 America/Los_Angeles - Do not use custom formatter in sensitive tests - Test2 0.000040 2016-04-05 11:09:52-07:00 America/Los_Angeles - Track subtest info inside subtest events - Test2 0.000039 2016-04-04 21:32:08-07:00 America/Los_Angeles - Formatters can pick buffered subtest behavior - Add sets_plan() method to event base class - Add diagnostics() method to event base class - Test2 0.000038 2016-04-03 15:41:39-07:00 America/Los_Angeles - Add summary() method to event base class - Test2 0.000037 2016-04-01 08:41:22-07:00 America/Los_Angeles - Change Formatter to load Test2::API on demand - Add test to insure Test2::API is not loaded by some modules - Test2 0.000036 2016-03-28 11:44:53-07:00 America/Los_Angeles - Do not warn if unimportant INIT block cannot be run - Change how TAP duplicates IO handles, use 3 arg form of open - Test2 0.000035 2016-03-25 09:41:46-07:00 America/Los_Angeles (TRIAL RELEASE) - Test2 0.000034 2016-03-24 10:32:57-07:00 America/Los_Angeles (TRIAL RELEASE) - Fix depth bug introduced in the last trial - Test2 0.000033 2016-03-24 08:39:51-07:00 America/Los_Angeles (TRIAL RELEASE) - Test2 0.000032 2016-03-23 23:54:40-07:00 America/Los_Angeles (TRIAL RELEASE) - Test2 0.000031 2016-03-20 13:45:43-07:00 America/Los_Angeles - Test2 0.000030 2016-03-15 08:04:21-07:00 America/Los_Angeles - Re-Add transition document - Test2 0.000029 2016-03-09 10:04:19-08:00 America/Los_Angeles - Add pid to Files driver temp dir name - Test2 0.000028 2016-03-09 09:03:26-08:00 America/Los_Angeles - Environment var to control IPC::Driver::Files temp dir templates - Test2 0.000027 2016-03-07 12:16:34-08:00 America/Los_Angeles - Ability to disable skip_all subtest abort construct - Test2 0.000026 2016-03-06 20:15:19-08:00 America/Los_Angeles - Version number in all modules (autarch) - Fix rare/minor Race condition in Files IPC driver - skip-all plan is not global anymore (never should have been) - skip-all properly aborts in child proc/thread - don't override defined but falsy pid/rid in traces - Test2 0.000025 2016-02-02 12:08:32-08:00 America/Los_Angeles - Fix occasional warning in cleanup - Test2 0.000024 2016-01-29 21:16:56-08:00 America/Los_Angeles - Add no_context() (needed for external tool) - Test2 0.000023 2016-01-28 20:34:09-08:00 America/Los_Angeles - Add context_do() - Add context_aquire hooks - Documentation updates - Typo fixes (thanks rjbs) - Minor enhancement to test tools - Test2 0.000022 2016-01-18 11:58:40-08:00 America/Los_Angeles - Fix test that broke in the last release (oops) - Test2 0.000021 2016-01-18 10:54:54-08:00 America/Los_Angeles - Fix bug where default diagnostics were not shown for subtests. - Test2 0.000020 2016-01-14 21:52:43-08:00 America/Los_Angeles - Change how contexts are stacked - More/better messages when contexts are abused - better handling of $@, $!, and $? - Add pre_filter and pre_unfilter to Hubs - Test2 0.000019 2016-01-12 16:08:11-08:00 America/Los_Angeles - Make third-party meta-data interface consistent. - Test2 0.000018 2016-01-12 05:53:29-08:00 America/Los_Angeles - Better solution to the $?, $!, and $@ problem - error vars are stored/restored by the context - Test2 0.000017 2016-01-11 16:33:55-08:00 America/Los_Angeles - Fix $! squashing - Test2 0.000016 2016-01-10 11:54:57-08:00 America/Los_Angeles - Better encapsulation of API::Instance - API methods to get lists of hooks - Minor fixes to IPC shm logic - Preload event types when API is loaded - Added IPC acceptance tests - Test2 0.000015 2016-01-07 19:26:58-08:00 America/Los_Angeles - Make it possible to use a custom new() with HashBase - Test2 0.000014 2016-01-07 07:31:23-08:00 America/Los_Angeles - Silence a warning in older perls (warning breaks Test-Simple tests) - Test2 0.000013 2016-01-06 11:12:21-08:00 America/Los_Angeles - Remove diag from inside todo (separation of concerns, less TAP influence) - Remove internal TODO tracking (not needed, less TAP influence) - Make context less magic (Follwing advice from Graham Knop and RJBS) - Remove State.pm (part of Hub.pm again, no longer needs to be separate) - Make it possible to subclass the TAP formatter - Minor optimization in Event->meta - Better messaging if subtest plan is wrong - HashBase in subclass will not override accessors from parent (Graham Knop) - TAP formatter doc updates - Optimizations for Hub->process and TAP->Write - IPC File-Driver Optimizations - IPC use SHM when possible to notify about pending events - Test2 0.000012 2015-12-29 12:59:26-08:00 America/Los_Angeles - Restructure file layout - Document namespaces - Combine Global and API into a single module - Test2 0.000011 2015-12-28 13:09:38-08:00 America/Los_Angeles - Fix TAP output to match what Test::More produced - Test2 0.000010 2015-12-21 13:13:33-08:00 America/Los_Angeles - Rename Test2.pm to Test2/API.pm. - Turn Global.pm into and exporter. - Test2 0.000009 2015-12-21 10:13:18-08:00 America/Los_Angeles - Fix typo in Test2::Event - Test2 0.000008 2015-12-21 09:54:58-08:00 America/Los_Angeles - Bring back 'release' export of Test2. - Test2 0.000007 2015-12-20 12:09:04-08:00 America/Los_Angeles - Fix version number string - Fix typo - Test2 0.000006 2015-12-15 20:30:46-08:00 America/Los_Angeles - Port 00-report.t from old form - Prevent TAP from killing $! - Fix Instance.t - Typo fix - Comment Contex.pm better, fix minor bug - Better error in Trace.pm constructor - Test2.pm, comments, and do not use try - Improve try, remove protect - Remove unused imports - Fix profling scripts - Improve HashBase - IPC improvements - Doc fix - Test2 0.000005 2015-12-14 20:21:34-08:00 America/Los_Angeles - Pull out guts into Test2 namespace - Restructure module paths - Simplify HashBase - Combine Util and Capabilities - Update Profiling scripts - Rename DebugInfo to Trace - Rename SyncObj to Global/Instance - Slim down Util.pm - Stop using Test::Stream::Exporter - Reduce complexity of Capabilities checker - Use event todo instead of debuginfo todo - Add 'todo' fields for Diag and Ok events - Break out Skip into an event type - Add event registration to TAP formatter - Move to_tap logic into formatter - Test-Stream 1.302026 2015-11-09 14:34:30-08:00 America/Los_Angeles - Test-Stream 1.302025 2015-11-06 16:33:06-08:00 America/Los_Angeles (TRIAL RELEASE) - Add back cmp_ok in Core plugin - Add Classic plugin for legacy is/like/is_deeply/etc - Make docs recommend people moving from Test::More use -Classic - Test-Stream 1.302024 2015-11-04 11:15:14-08:00 America/Los_Angeles - Add missing undef compare test - Test-Stream 1.302023 2015-11-04 00:12:49-08:00 America/Los_Angeles (TRIAL RELEASE) - String and Number comparisons no longer allow undef (backwords incompatible change, sorry) - Doc spelling fixes (Evan Zacks) - Add Undef type in deep check - Fix docs for buffered subtests (Noticed by Magnolia.K) - Test-Stream 1.302022 2015-11-03 09:43:39-08:00 America/Los_Angeles - Test-Stream 1.302021 2015-10-31 08:15:22-07:00 America/Los_Angeles - Remove all number vs string guessing - Doc fixes (thanks Magnolia.K) - Add details to test report - Test-Stream 1.302020 2015-10-29 08:02:25-07:00 America/Los_Angeles - No changes, just removing trial - Test-Stream 1.302019 2015-10-28 22:32:06-07:00 America/Los_Angeles (TRIAL RELEASE) - Declare Test::Stream experimental phase complete - Updated Readme - Add tooling manual page - Better Trace::Mask behavior - Added Components manual page - Remove or modify experimental notice - Remove stray debugging statements - Slight change in module list in t/00-report.t - Test-Stream 1.302018 2015-10-26 16:47:45-07:00 America/Los_Angeles - Better stack traces in spec - Remove duplicate module from the report - Rename subs in try {} and protect {} - Fix loop in SkipWithout - Fix Typo in Context pod - Test-Stream 1.302017 2015-10-15 21:32:50-07:00 America/Los_Angeles - Change minimum module versions (they were wrong) - Typo fixes in Test::Stream docs - Remove unused variable - Fix Compare line number bug - Test-Stream 1.302016 2015-10-12 18:49:35-07:00 America/Los_Angeles - Workflows/Spec: Argument tolerence, custom line numbers - Remove Block.pm - Add sub_info and sub_name to Util.pm - Workflows: Set sub name if possible (better debugging) - Add "Test" that prints deps and versions - Add 'class', 'skip_without', and 'srand' to Test::Stream as options - Even Core deps now listed in dist.ini - Add some missing docs and tests to Util.pm - Test-Stream 1.302015 2015-10-04 13:46:56-07:00 America/Los_Angeles - Remove spec isolation logic, this can be an external plugin - Test-Stream 1.302014 2015-10-03 20:30:14-07:00 America/Los_Angeles - Another Delta.t fix - Test-Stream 1.302013 2015-10-02 21:51:45-07:00 America/Los_Angeles - Fix Util.t for some Term::ReadKey versions - Test-Stream 1.302012 2015-10-01 15:42:27-07:00 America/Los_Angeles - Remove reservations file - Documentation updates (add missing docs) - Fix output handle in subtest diagnostics - Better subtest diagnostics - Whitespace fixes - Better error handling in threads in the workflows - Better support real fork vs pseudo fork - Test-Stream 1.302011 2015-09-30 21:05:57-07:00 America/Los_Angeles - Documentation updates, typo fixes - Be safer, and less verbose, when detecting term size - Fix isolation in the spec plugin in windows - Skip sync test on windows (temporary measure) - Skip the hub.t fork check on windows (temporary measure) - Add some debugging to CanThread - Fix global event handling on platforms that do not use '/' for path - Fix Delta.t on systems with large memory addresses - Test-Stream 1.302010 2015-09-29 22:23:28-07:00 America/Los_Angeles - Add spec plugin (with basic workflows modules) - Switch to plugin architecture, Test::Stream is just a loader - Add plugins (many of these were non-plugins before) AuthorTest BailOnFail Capabilities Capture Class Compare Context Core Defer DieOnFail Exception ExitSummary Grab IPC Intercept LoadPlugin Mock SRand SkipWithout Spec Subtest TAP UTF8 Warnings - CanFork is now a plugin - CanThread is now a plugin - Subtest stack fallback fix - Better Compare library - Documentation is fleshed out and mostly complete - Unit testing coverage is now satisfactory - Better detection of broken threads on 5.10.0 - Ability to set/change encoding - is_deeply() is now combined into is() - mostly_like() and like() are combined - DeepCheck library removed in favor of Compare library - deep checks now render a table - Test directory restructuring - Mocking library - Workflow library - Fix typos - Fix a GC destruction issue (b3a96db) - Test-Stream 1.302009 2015-07-03 21:16:08-07:00 America/Los_Angeles - Fix MANIFEST.SKIP so tests are not skipped - Change import aliasing syntax to match prior art - Fix bug in does_ok - Documentation updates - Test-Stream 1.302008 2015-06-27 15:21:55-07:00 America/Los_Angeles - Fix 2 bugs with threading on 5.8.x - Fix a diag rendering bug with subtests - Test-Stream 1.302007 2015-06-24 08:03:38-07:00 America/Los_Angeles - Add CanThread and CanFork libraries - Remove prefix when subtests are buffered - Fix bug where Exporter might remove other tools exports - Fix bug in unmunge and unlisten - Add helper for specifying a context in which to run - Add causes_fail method for events - Fix rendering bug in subtest diags - Fix bug where IPC abort would fail to set exit code - Remove XS support code - Fix bug when threads are auto-joined - Test-Stream 1.302006 2015-06-18 09:53:04-07:00 America/Los_Angeles - MANIFEST.SKIP fix - Remove files accidentally included in the last dist - Test-Stream 1.302005 2015-06-18 09:37:38-07:00 America/Los_Angeles - Remove broken test script - Test-Stream 1.302004 2015-06-17 08:32:31-07:00 America/Los_Angeles - Add Support for XS - Improve release_pp with refcount from internals - Test-Stream 1.302003 2015-06-06 21:44:42-07:00 America/Los_Angeles - Documentation added - Make IPC::Files safe in cleanup - Test-Stream 1.302002 2015-06-06 14:06:57-07:00 America/Los_Angeles - Fix Win32 support - Test-Stream 1.302001 2015-06-05 22:40:57-07:00 America/Los_Angeles - Initial Version Object to manage a stack of Test2::Hub instances. Base class for events Bailout! Diag event type Exception event Note event type Ok event type The event of a plan Skip event type Event for subtest types Tell all procs/threads it is time to be done. Tools used by Test2 and friends. Allow third party tools to safely attach meta-data to your instances. Base class for classes that use a hashref of a hash. Debug information for events Provides in lib/Test/Builder/Tester.pm in lib/Test/Tester/Delegate.pm
https://metacpan.org/release/EXODIST/Test-Simple-1.302015
CC-MAIN-2021-04
refinedweb
5,856
68.26
import "github.com/upspin/upspin/errors" Package errors defines the error handling used by all Upspin software. Separator is the string used to separate nested errors. By default, to make errors easier on the eye, nested errors are indented on a new line. A server may instead choose to keep each error on a single line by modifying the separator string, perhaps to ":: ". E builds an error value from its arguments. There must be at least one argument or E panics. The type of each argument determines its meaning. If more than one argument of a given type is presented, only the last one is recorded. The types are: upspin.PathName The Upspin path name of the item being accessed. upspin.UserName The Upspin name of the user attempting the operation. errors.Op The operation being performed, usually the method being invoked (Get, Put, etc.). string Treated as an error message and assigned to the Err field after a call to errors.Str. To avoid a common class of misuse, if the string contains an @, it will be treated as a PathName or UserName, as appropriate. Use errors.Str explicitly to avoid this special-casing. errors.Kind The class of error, such as permission failure. error The underlying error that triggered this one. If the error is printed, only those items that have been set to non-zero values will appear in the result. If Kind is not specified or Other, we set it to the Kind of the underlying error. Errorf is equivalent to fmt.Errorf, but allows clients to import only this package for all error handling. Is reports whether err is an *Error of the given Kind. If err is nil then Is returns false. MarshalError marshals an arbitrary error and returns the byte slice. If the error is nil, it returns nil. It returns the argument slice unchanged if the error is nil. If the error is not an *Error, it just records the result of err.Error(). Otherwise it encodes the full Error struct. MarshalErrorAppend marshals an arbitrary error into a byte slice. The result is appended to b, which may be nil. It returns the argument slice unchanged if the error is nil. If the error is not an *Error, it just records the result of err.Error(). Otherwise it encodes the full Error struct. Match compares its two error arguments. It can be used to check for expected errors in tests. Both arguments must have underlying type *Error or Match will return false. Otherwise it returns true iff every non-zero element of the first error is equal to the corresponding element of the second. If the Err field is a *Error, Match recurs on that field; otherwise it compares the strings returned by the Error methods. Elements that are in the second argument but not present in the first are ignored. For example, Match(errors.E(upspin.UserName("joe@schmoe.com"), errors.Permission), err) tests whether err is an Error with Kind=Permission and User=joe@schmoe.com. Code: path := upspin.PathName("jane@doe.com/file") user := upspin.UserName("joe@blow.com") err := errors.Str("network unreachable") // Construct an error, one we pretend to have received from a test. got := errors.E(errors.Op("Get"), path, user, errors.IO, err) // Now construct a reference error, which might not have all // the fields of the error from the test. expect := errors.E(user, errors.IO, err) fmt.Println("Match:", errors.Match(expect, got)) // Now one that's incorrect - wrong Kind. got = errors.E(errors.Op("Get"), path, user, errors.Permission, err) fmt.Println("Mismatch:", errors.Match(expect, got)) Output: Match: true Mismatch: false Str returns an error that formats as the given text. It is intended to be used as the error-typed argument to the E function. UnmarshalError unmarshals the byte slice into an error value. If the slice is nil or empty, it returns nil. Otherwise the byte slice must have been created by MarshalError or MarshalErrorAppend. If the encoded error was of type *Error, the returned error value will have that underlying type. Otherwise it will be just a simple value that implements the error interface. type Error struct { // Path is the Upspin path name of the item being accessed. Path upspin.PathName // User is the Upspin name of the user attempting the operation. User upspin.UserName // Op is the operation being performed, usually the name of the method // being invoked (Get, Put, etc.). It should not contain an at sign @. Op Op // Kind is the class of error, such as permission failure, // or "Other" if its class is unknown or irrelevant. Kind Kind // The underlying error that triggered this one, if any. Err error // contains filtered or unexported fields } Error is the type that implements the error interface. It contains a number of fields, each of different type. An Error value may leave some values unset. Code: path := upspin.PathName("jane@doe.com/file") user := upspin.UserName("joe@blow.com") // Single error. e1 := errors.E(errors.Op("Get"), path, errors.IO, "network unreachable") fmt.Println("\nSimple error:") fmt.Println(e1) // Nested error. fmt.Println("\nNested error:") e2 := errors.E(errors.Op("Read"), path, user, errors.Other, e1) fmt.Println(e2) Output: Simple error: Get: jane@doe.com/file: I/O error: network unreachable Nested error: Read: jane@doe.com/file, user joe@blow.com: I/O error: Get: network unreachable MarshalAppend marshals err into a byte slice. The result is appended to b, which may be nil. It returns the argument slice unchanged if the error is nil. MarshalBinary marshals its receiver into a byte slice, which it returns. It returns nil if the error is nil. The returned error is always nil. UnmarshalBinary unmarshals the byte slice into the receiver, which must be non-nil. The returned error is always nil. Kind defines the kind of error this is, mostly for use by systems such as FUSE that must act differently depending on the error. const ( Other Kind = iota // Unclassified error. This value is not printed in the error message. Invalid // Invalid operation for this type of item. Permission // Permission denied. IO // External I/O error such as network failure. Exist // Item already exists. NotExist // Item does not exist. IsDir // Item is a directory. NotDir // Item is not a directory. NotEmpty // Directory not empty. Private // Information withheld. Internal // Internal error or inconsistency. CannotDecrypt // No wrapped key for user with read access. Transient // A transient error. BrokenLink // Link target does not exist. ) Kinds of errors. The values of the error kinds are common between both clients and servers. Do not reorder this list or remove any items since that will change their values. New items must be added only to the end. Op describes an operation, usually as the package and method, such as "key/server.Lookup". Package errors imports 8 packages (graph). Updated 2019-12-07. Refresh now. Tools for package owners.
https://godoc.org/github.com/upspin/upspin/errors
CC-MAIN-2020-40
refinedweb
1,154
61.93
Gwibber shows "BUG:00:00:59:63" instead of "<x> seconds ago" in Twitter timeline Bug Description Binary package hint: gwibber Ubuntu Release: 10.10 Gwibber version: 2.32.2-0ubuntu2 Shortly after a timeline update, apparently if an update is younger than one second, the time is not displayed correctly as "less than 1 second ago", but rather as "BUG:00:00:59:xx" (followed by "from <application>" as usual). I see an inconsistency in the following code from util.py (condensed): elif d.seconds < 3600 and d.seconds >= 60: # ... elif round(d.seconds) < 60: # ... else: return "BUG: %s" % str(d) Note the different handling of d.seconds: it is rounded in one expression but not the other. But I'm not fluent in Python so I don't know if this is significant or not. I concocted a small test program that mimics the logic in util.py: ---- def testit(v): print(v) if v >= 60: print ">= 60" elif round(v) < 60: print "< 60" else: print "err" testit(59.4) testit(59.5) testit(59.6) testit(60) ---- Output: 59.4 < 60 59.5 err 59.6 err 60 >= 60 This seems to confirm my hypothesis. This patch removes the rounding in the last elif condition, to avoid an error when the seconds part is between 59.5 and 60.0. Ken, can you look at this patch please? :) This bug was fixed in the package gwibber - 2.91.91.1-0ubuntu1 --------------- gwibber (2.91.91. *) -- Ken VanDine <email address hidden> Fri, 11 Mar 2011 15:07:28 -0500 Seen this too, confirming. Same version as bug reporter.
https://bugs.launchpad.net/ubuntu/+source/gwibber/+bug/705424
CC-MAIN-2015-22
refinedweb
270
78.04
WIN! ROBOT ARM & FLICK HATS The official Raspberry Pi magazine Issue 63 November 2017 raspberrypi.org/magpi NERF GUN ROBOT FRED-209: You have 20 seconds to comply MAKE A MIDI SOUND BOX Make your own sound machine CONTROL LEGO MINDSTORMS Use LEGO robotics kits with Raspberry Pi Also inside: > REVIEWED! MONSTERBORG, PIJUICE AND OLED BONNET > CLEARING LAND-MINES WITH AN EXPLOSIVE PI ROBOT > 3D BODY SCANNING WITH 27 PI ZERO W DEVICES > NEW PI-TOP LAPTOP REVEALED INSIDE JUNIOR PI PROJECTS THE ONLY MONTHLY MAGAZINE WRITTEN BY AND FOR THE PI COMMUNITY Hacks & makes to inspire your kids Issue 63 • Nov 2017 • £5.99 11 9 772051 998001 WELCOME TO THE OFFICIAL MAGAZINE ands up who wanted their own arcade machine when young. Everyone, right? This month we feature a full-on, full-size, full-scale, actual honest-to-goodness arcade machine; wooden cabinet, sticks, buttons and all. You’ll find it standing tall on page 16. Now, I could talk all day about how important making is for education; how arcade games are a path for youngsters to coding and electronics. (And we do that in Pi Junior Projects on page 66.) I could also talk about how the new pi-top laptop is transforming education by providing kids with a hackable alternative to shiny tablets (page 6) or how building a MIDI sound synth will inspire kids who love music more than machines and need a reason to learn code (page 42). Or, how Raspberry Pi is capable of performing real change in the world. Like clearing land-mines (page 36). Or how Raspberry Pi robots like MonsterBorg (reviewed on page 74) are so powerful, and popular, that Rolls-Royce itself is using them to scout for the next generation of engineers (page 8). But in all truth: this month we just wanted our very own arcade machine. PAGE 3 2 H SEE PAGE 32 FOR DETAILS THIS MONTH: 06 NEW PI-TOP LAPTOP First-look at the brand new pi-top computer 16 BUILD AN ARCADE MACHINE Make a classic arcade cabinet with a Raspberry Pi inside 42 MAKE A MIDI SOUND BOX Build your own electric synth and make some noise 66 JUNIOR PI PROJECTS Lucy Hattersley Editor – The MagPi Raspberry Pi projects to inspire younger makers FIND US ONLINE raspberrypi.org/magpi EDITORIAL DESIGN PUBLISHING DISTRIBUTION SUBSCRIPTIONS CONTRIBUTORS Editor: Lucy Hattersley lucy@raspberrypi.org Features Editor: Rob Zwetsloot rob@raspberrypi.org Sub Editors: Phil King and Jem Roberts, Daiva Bumelyte, and Mike Kay Illustrator: Sam Alder Select Publisher Services Ltd PO Box 6337 Bournemouth BH1 9EH | +44 (0)1202 586 848 For advertising & licensing: Publishing Director: Russell Barnes russell@raspberrypi.org | +44 (0)7904 766523 Director of Communications: Liz Upton CEO: Eben Upton Alex Bate, Bob Clagett, Mike Cook, Kylie Cooper, David Crookes, Kent Elchuk, Phil King, Ben Nuttall, Binsen Qian, Matt Richardson, Richard Smedley, Clive Web. November April 2016 2017 3 Contents raspberrypi.org/magpi Issue 63 November 2017 TUTORIALS COVER FEATURE > MAKE A MIDI BOX Another sweet musical project from Mike’s Pi Bakery 42 > BUILD A HYDROPONIC GARDEN 48 How to automate plant growing with your Pi > CONTROL LEGO WITH PI 52 > PI 101: DO MATHS IN PYTHON 54 Use MINDSTORMS with a Pi for awesome projects Crunch some numbers with code IN THE NEWS NEW PI-TOP 16 ARCADE BUILD See the all-new updated pi-top! 06 PI WARS 2018 UPDATE IOT BOOTCAMP ROLLS-ROYCE & PIBORG PiBorg teams up with Rolls-Royce for a unique competition 4 November 2017 08 Over 100 teams take on new challenges 10 Meet Eben Upton at this three-day virtual event 12 raspberrypi.org/magpi Contents THE BIG FEATURE & ROBOT ARM KIT JUNIOR PI PROJECTS! Get your young ones into coding 66 97 In association with REGULARS YOUR PROJECTS > NEWS 06 62 80 98 > TECHNICAL FAQ > BOOK REVIEWS > FINAL WORD COMMUNITY > NOTAGRAMA INTERVIEW 38 FRED-209 You have 20 seconds to comply… 3D SCANNER 34 27 Pis power this DIY body scanner C-TURTLE > THIS MONTH IN RASPBERRY PI 84 Spooky projects, competitions, and more! > WORLD MAKER FAIRE REPORT 88 Fun at the (Maker) Faire in New York City > PAUL BEECH PROFILE 90 > EVENT SCHEDULE 92 > LETTERS 94 Meet the Pi logo creator and noted pirate retailer Raspberry Pi events you can go to this month You ask us questions, we answer them 36 Clearing land-mines with a Pi robot REVIEWS > MONSTERBORG CAT DOOR A flap that only opens for your cat 40 74 76 78 79 > PIJUICE > OLED BONNET > STATUS BOARD raspberrypi.org/magpi 82 We talk to the maker of this fun music learning project November 2017 5 News NEW PI-TOP LAPTOP LAUNCHED NEW PI-TOP LAPTOP LAUNCHED Updated Raspberry Pi laptop with sliding keyboard mechanism new version of pi-top, the modular laptop based on a Raspberry Pi, has been revealed. It features a whole new design with an impressive sliding keyboard. The keyboard is, to our eyes, the most interesting new feature. It’s connected via a flexible cable and it slides down to provide access to the Raspberry Pi and other electronic components. The fresh design enables a larger keyboard with a clickable trackpad now located below, in A the typical position for a laptop. It also features a larger 14-inch display and an internal battery providing 8–10 hours of power. Build quality is said to be improved and we find it a more professional-looking laptop, but one that still offers great potential for hacking and making. “The first thing you do with pi‑top is build it,” says Jesse Lozano, CEO of pi-top. Because students understand the internals, they “really focus on what you can build”, he tells us. Raspberry Pi inside A Raspberry Pi 3 is used as the brains of the laptop. The laptop runs pi-topOS, an operating system based on Raspbian. As well as programs like Scratch and Minecraft Pi, pi-topOS has office apps likes Google Docs and LibreOffice, and Google Drive cloud storage support. It also comes with dedicated coding tools such as pi-topCODER and CEEDuniverse (an adventure game in which students need to solve visual programming puzzles). It’s the only education technology platform endorsed by the UK awarding board OCR (Oxford Cambridge RSA Examinations). Two magnetic rails are used to quickly connect and remove components to the kit A Raspberry Pi 3 provides the brains of the laptop, enabling it to run the Raspbian-based pi-topOS with all the software and coding capabilities of a Raspberry Pi The keyboard slides down, enabling access to the Raspberry Pi and electronic components 6 November 2017 raspberrypi.org/magpi News Left The new design looks like a typical laptop, but you build it yourself and can add electronic components to the inside Inventor’s Kit Included with the package is an Inventor’s Kit. This contains 20 parts and instructions for electronic projects. We saw a motion-activated robot, wire game, and a music machine built using LEDs and buttons. The parts are used with the included pi-topPROTO+, a breadboard with GPIO breakout pins. The piTopPROTO+ clips into a hub connected to the Raspberry Pi, and sits on top of the new magnetic sliding module rail. This enables students to quickly add (and remove) components, such as a speaker, to the laptop. “pi-top’s mission is to provide powerful, inspiring products that bring science, technology, engineering, arts and mathematics to life,” states Jesse Lozano. “Our Because students understand the internals, they really focus on what you can build newest generation of modular laptops helps achieve that goal. Now, anyone from young musicians to scientists to software developers to inventors can explore and Below The pi-top comes with parts and instructions for 20 electronic and maker projects raspberrypi.org/magpi create wonderful new projects using the pi-top laptop. We’re offering learning beyond the screen and keyboard, enabling wider exploration of computer science and basic electronics, ensuring that young learners have the opportunity to be inspired by a world of STEAMbased learning.” The new pi-top is available now, direct from the pi-top store (magpi.cc/2i904QK), priced at $319.99. It is also available without a Raspberry Pi for $284.99. UK pricing had not been confirmed at the time we went to press, but ModMyPi was listing it for pre-order at £259.99 (magpi.cc/2i8Bn73). The laptop kit is also available at The Pi Hut, Adafruit, RS, and other retailers. November 2017 7 News ROLLS-ROYCE HOOKS UP WITH FORMULA PI ROLLS-ROYCE HOOKS UP WITH FORMULA PI New challenge for robot racers designed to find the next generation of Rolls-Royce engineers oll R Below Entrants will race two robots around a Formula Pi track, one with a camera facing forwards, the other facing backwards 8 November 2017 Rolls-Royce’s RaceYourCode competition will use the MonsterBorg robots from Formula Pi Innovation. “We’re looking to find people who are analytically minded but creative,” explains Andrew. “It’s quite a rare talent, actually.” Rolls-Royce also wants people who can “understand the data,” adds Andy Appleyard, Global Resource and Capability Manager, Digital. which have to cross the start/ finish line. These robots are controlled by a Raspberry Pi 3, with a WiFi connection to the internet and to each other. The challenge is that your leading robot can only ‘see’ the track in front of it and your trailing robot can only ‘see’ behind it (each via We’d love to hear from you, regardless of wherever you are in the world... It’s a quirky competition. Each driver will have control of two MonsterBorg robots, one ‘leading’ and the other ‘trailing’, both of a small on-board camera with limited range). “The competitors get 45 minutes to look at the code,” explains Timothy Freeburn, PiBorg Director. “They can tinker with the code. Then, at the end of it, they get three laps to race the robots around.” Like Formula Pi, the RaceYourCode event will use MonsterBorg robot kits (check out our review of the latest MonsterBorg on page 74). The final races will be on either Monday 11 December or Tuesday 12 December. Full instructions for the event can be found here: magpi.cc/2icaLlO. Folks interested in the RaceYourCode event can sign up at magpi.cc/2i8GtjH. “We’d love to hear from you, regardless of wherever you are in the world.” says Andrew Hutson-Smith. raspberrypi.org/magpi News OVER 100 TEAMS IN PI WARS 2018 OVER 100 TEAMS IN PI WARS 2018 he new rules and challenges for Pi Wars 2018 have been revealed, so we caught up with co-founder and co-organiser Mike Horne to see what’s new for the next Wars. Teams entering Pi Wars must build a single robot that can tackle a range of challenges, including an obstacle course, a straight-line speed test, and an event called ‘Slightly Deranged Golf’. Two events from last year – Skittles and Line-Following – have T TIPS FOR PI WARS 2018 We talked to Pi Wars veteran Brian Corteil to get his take on 2018’s design challenges. Asked whether the new challenges require specific designs, Brian says, “I hear that some people are redesigning their robots … making their robots smaller to cope better with the minimal maze turns.” “The new Over The Rainbow challenge would benefit from motors with encoders,” Brian suggests. “The new motors may require a redesign of the robot’s chassis. The Duck Shoot challenge can be covered by a simple add-on.” “Omnidirectional robots seem to be becoming more common,” according to Brian, while “another trend I have noticed is that the robots are getting better each year; more reliable and powerful.” “Building your first robot from a kit is a good way to start,” Brian confirms, but “avoid kits with trolley wheels” which will struggle with some challenges. Brian advocates using a video game controller to steer your robot, an on-board running mode switch, and plenty of spare batteries. Some returning challenges have updated rules. “The New challenges, new rules (magpi.cc/2hLjyeh). High standard Mike confirmed that more than one hundred teams have applied for 2018’s Wars, and that “the quality of the applications, and the amount of detail they’ve given, is much higher this year.” It sounds as if 2018 is going to be fiercely competitive. Pi Wars 2018 takes place in the William Gates Building of the Cambridge Computer Laboratory, from 21 to 22 April. Robots face many tricky challenges throughout the Pi Wars competition 10 November 2017 raspberrypi.org/magpi PI-POWERED TURTLE ROVER PI-POWERED TURTLE ROVER News NOW TRENDING The stories we shared that flew around the world Explore Earth with this rugged rover F ollowing our interview last month with Kell Ideas’ CEO Szymon Dzwonczyk, the Turtle Rover has exceeded its Indiegogo funding target by over €6,000. Szymon tells us, “Everyone will still be able to buy the At the heart of the Turtle Rover is a Pi 3. As Szymon explains, “We love the computer and need to encourage people to play with the rover software using open-source code from the Pi community.” The bespoke Turtle HAT uses “H-bridges and an STM32 We love the computer and need to encourage people to play with the rover software Rover via Indiegogo [see magpi.cc/2hIuGZf], and by the end of the year from our shop.” The kit Rover costs $990 (roughly £750) plus shipping, while a built Rover costs $1,972 (roughly £1,500) plus shipping. TWIN YOUR PI WITH AN ARDUINO magpi.cc/2h8NAVj A Raspberry Pi might have loads of GPIO pins to interact with sensors and control motors, but for an extra level of finesse and accuracy, you can pair a Pi with an Arduino board. [microcontroller] to drive the robotic arm.” The Turtle Rover is rugged, waterproof, and fully customisable, with wireless control (via an app) at up to 200 m. The internal battery should last for 4 hours of driving time. AIY PROJECTS PRE-ORDER magpi.cc/2hJeQ0f Find out where to pre-order the new AIY Projects Voice Kit with a 76-page Essentials Guide. Here it comes! PI DECK – PLAY DIGITAL MUSIC LIKE A DJ magpi.cc/2eSICeA Designed by Mars Rover prototype engineers, the Turtle can do the same job on Earth raspberrypi.org/magpi With a Raspberry Pi inside, these turntables allow Daniel James to scratch and mix digital tracks as if they were on vinyl, but without lugging boxes of records to every gig. November November February 2017 11 News FREE IOT BOOTCAMP WITH EBEN FREE IOT BOOTCAMP WITH EBEN Practical, hands-on advice from industry leaders, including Raspberry Pi CEO Eben Upton Above The Adafruit pack to accompany the bootcamp is extensive, but we bet you’ve got most of the bits already ADAFRUIT IOT VIRTUAL BOOTCAMP CHECKLIST 1 × Raspberry Pi 3 Model B 1 × Raspberry Pi 3 case 1 × 8GB microSD card with NOOBS 2.0 1 × 5 V 2.4 A Raspberry Pi power supply 1 × Slim HDMI Cable - 450 mm / 1.5 feet long 1 × Assembled Adafruit Feather HUZZAH ESP8266 WiFi 1 × Micro servo 1 × PIR (motion) sensor 1 × USB cable – A/Micro B 1 × Fast vibration switch 1 × Magnetic contact switch (door sensor) 2 × DHT22 temperature-humidity sensor 1 × Full-sized breadboard 1 × Male/male jumper wires – 40 × 6˝ 1 × Female/female Jumper Wires – 20 × 3˝ (75 mm) 1 × Female/male Jumper Wires – 20 × 3˝ (75 mm) 1 × Male/male Jumper Wires – 20 × 3˝ (75 mm) 1 × Male/male Jumper Wires – 20 × 6˝ (150 mm) 1 × Assembled Pi Cobbler Plus 1 × USB to TTL Serial cable 1 × HDMI 7˝ 800×480 Display Backpack – with Touchscreen Electronics: 6 × 12 mm Tactile switches 1 × Breadboard trim potentiometer 10K 2 × Diffused 10 mm green LED 2 × Diffused 10 mm red LED 1 × Diffused 10 mm blue LED 1 × Diffused RGB (tri-color) LED 10 × 10K 5% ¼ W Resistor 10 × 560 Ω 5% ¼ W Resistor 1 × Electrolytic capacitor – 1.0 μF 1 × Piezo buzzer 2 × Photo cell light sensor 1 × Breadboard-friendly SPDT slide switch 12 November 2017 he Raspberry Pi Foundation, Microsoft, Adafruit, and Hackster.io are pooling resources to deliver a three-day Internet of Things (IoT) Virtual Bootcamp. Since it’s virtual, you can attend from anywhere, and the price of attendance is free. Day two features a Raspberry Pi focus, with a talk from Raspberry Pi co-founder Eben Upton along with hands-on labs based around the Raspberry Pi. T on demonstrations during the three days for hobbyist makers to learn from. Virtually hands-on The hands-on labs have been made possible by Adafruit, which has created a pack of hardware and components that will be used by the course leaders (magpi.cc/2hIjpbd). This pack includes a Raspberry Pi 3, a touchscreen, and Adafruit’s Feather Huzzah ESP8266 WiFi. Limor It’s your best chance to learn more about IoT from the experts, and in real time As Limor Fried, founder and engineer of Adafruit (better known as ‘Lady Ada’), tells us, “The goals of the bootcamp are to enable partners to get started with IoT through simple exercises; provide accessible and scalable IoT technical education; and educate the audience on Enterprise solutions.” Adam Benzion, Hackster.io cofounder, adds, “This IoT bootcamp … will be rich in hands-on labs, code sharing, and live practice. It’s your best chance to learn more about IoT from the experts and in real time.” As such, the bootcamp is perfect for anyone considering a commercial IoT product. However, there will be plenty of hands- describes this as “our WiFi-enabled microcontroller, programmable using the Arduino IDE, and one of our easiest platforms to help you break into the IoT world.” This pack should be available to buy in the UK, as The Pi Hut owner Jamie Mann tells us, “We’ll more than likely stock the kit, yes. However, it’s currently out of stock at Adafruit.” We’ve listed all the components, as you may well have most of them already. The Pi Hut (thepihut.com) and Pimoroni (shop.pimoroni.com) carry a wide range of specific Adafruit parts and packs. To attend the virtual bootcamp, sign up with Microsoft (magpi.cc/2hJsrow). raspberrypi.org/magpi NEW PI HAT RIVALS TOP-END HI-FI News NEW PI HAT RIVALS TOP-END HI-FI Raspberry Pi high-end audio streaming device DigiOne ndian firm Allo is making a name for itself with a series of high-end audio HATs for Raspberry Pi. Following the £55 Boss and £35 MiniBoss DAC HATs is its latest audio upgrade, the DigiOne. At £95 (from thepihut.com), the DigiOne costs almost the same as three Pi 3s, but that’s not quite the point, as Allo’s CMO Andre Strul explains: “We believe the Raspberry Pi has the potential to become the new audio platform for the streaming generation.” Allo is gunning for the likes of Sonos, in a market where prices of £500 for a single speaker unit are common. That makes a £35 Pi with a £95 audio HAT look like a great deal! The DigiOne is a ‘transport’, aiming to circumvent the Pi’s audio hardware entirely. Andre explained that the Pi could only produce frequencies of 44.138 kHz or 44.0366 kHz, both of which would cause I jitter in 44.1 kHz audio. Instead, the DigiOne generates its own clock, and combines that ability with heaps of filtering, noise reduction, and signal realignment to output audio at up to 192 kHz/24-bit, with jitter as low as 0.6 picoseconds and noise of 50 µV. Allo says reaction to the DigiOne has been “tremendous. We see interest not only from EU and USA, but from countries like Vietnam, Taiwan, and Brazil.” raspberrypi.org/magpi November 2017 13 Feature THE BIG BUILD Grab some wood, a Raspberry Pi, and some quarters and let’s take it back to the Eighties s kids, many of us dreamed about owning arcade machines when we grew up. Whether they were early classics such as Pac-Man or tournament mainstays like Street Fighter II, the idea of having a little slice of our local arcade just sitting in our living room was extremely appealing. The reality in 2017 is not great, with arcade machines getting old and maintenance becoming prohibitively expensive. We could talk to you at length about the importance and cost of video game preservation, but instead we’re going to show you how to go one better than a grungy X-Men cabinet with dodgy sound, to build your own perfect and brand new arcade emulation machine with Raspberry Pi and a bit of elbow grease. Insert some credit and let’s start. A 16 November 2017 This arcade build was made by Bob Clagett of I Like to Make Stuff iliketomakestuff.com raspberrypi.org/magpi BUILD AN ARCADE MACHINE raspberrypi.org/magpi Feature November 2017 17 Feature THE BIG BUILD TOOLS JOB CIRCULAR SAW DRILL/DRIVER ROTARY TOOL All you need to build your dream arcade machine JIGSAW his is not a small project, so you’ll need to have plenty of tools for this job. Bob built this with a lot of precision, although at some steps you can make do with something a little simpler if you don’t have the specific tool. T UTILITY KNIFE WARNING! Not all these tools are necessary. Read through the build first to figure out what you’ll need. SOLDERING IRON CLAMPS MEASURING TAPE, STEEL RULER & PROTRACTOR Get Bob’s digital plans for the arcade cabinet online: magpi.cc/2yboyPp CABINET MATERIALS Plywood (recommended) for the exterior, MDF for inside 48″ (122 cm) piano hinge 24″ (61 cm) soft-close drawer slides 2 × ½″ (12.7 mm) overlay face frame concealed hinge (optional) Magnetic catch (optional) ¾″ (19 mm) T-Molding (optional) - magpi.cc/2ybmvus 18 November 2017 raspberrypi.org/magpi BUILD AN ARCADE MACHINE Feature ELECTRICAL COMPONENTS What you need to make – and power – your retro cabinet 27″ LCD MONITOR Old-school arcade machines had a CRT monitor, but they’re heavy and prone to failure. LCDs just work better. RASPBERRY PI The brains of your entire project. We recommend a Raspberry Pi 3. Want to copy Bob’s build exactly? Find his parts list on his blog: magpi.cc/2yU6whx COMPUTER SPEAKERS Want to hear your games? You’ll need speakers. SPEAKER GRILLES magpi.cc/2ybuZ58 These allow you to hear what’s playing through the speakers. LED ARCADE BUTTONS shop.pimoroni.com Bash these buttons. You can get them from Pimoroni. ARCADE JOYSTICK magpi.cc/2za1AWI Joysticks is the name of a bad Eighties comedy. These are better. I-PAC OPTIONAL ARDUINO UNO A microcontroller to control some of the electronics. LED STRIPS Cool lights for your new retro cabinet. magpi.cc/2yDyLFi This makes connecting your controls to the Pi as easy as… you get the idea. PIR SENSOR 12 V POWER SUPPLY RELAY SHIELD Want to light up your cool LED arcade buttons? They need power. Building power control into the project? You’ll need this. A motion sensor unique to this specific build. SWITCHES & ASSORTED WIRES raspberrypi.org/magpi November 2017 19 Feature THE BIG BUILD LET’S GET BUILDING Mario was a carpenter before he was a plumber. Time to borrow his old skills 01 MEASURE TWICE 02 CUT ONCE 03 STRUCTURAL INTEGRITY 04 HIDDEN DRAWERS 20 If you’ve bought Bob’s design, you can start measuring out the side panels on the plywood. If you want to go with your own design, make sure to do some research on the shape of the style of arcade cabinets you want to go with, and plan it out on paper or with CAD software first. Begin cutting your panels out with your circular saw. Cut as close to the corners as you can and use a jigsaw or handsaw to finish them off. You can use this first side panel to trace an outline for the second side panel if you wish. Now it’s time to measure and cut out the main structure of the cabinet between the side panels using MDF sheets; this includes two MDF panels to hold the side panels together – albeit with a twist. In this build, one of the sides can open to reveal six hidden drawers. This is great for easily accessing the electronics inside and also using the cabinet for storage. Draw reference lines for six of the drawer sliders on each side and then attach them. November 2017 raspberrypi.org/magpi BUILD AN ARCADE MACHINE 05 TOP TO BOTTOM 06 FRONT BOOKSHELF Feature Make the top and bottom panels out of MDF and attach them using screws. Bob also added a bit of glue but reckons it’s not entirely necessary. Add a bit of scrap wood in the open side just to help keep the shape for now. As well as drawers, there are hidden shelves inside the cabinet. These go at the front of the build and are short enough to be hidden by the front of the side panel. Create the basic rectangle/square shape of the shelves, and then add 1-inch (25.4 mm) spacers to the bottom of the frame before adding the bottom shelf on top for added strength and support. 07 SHELF FASCIA 08 ADD SHELVES Using the plywood, add a fascia to the front of the shelves to bring some consistency to the build. It will also look a bit nicer than the MDF on its own! These can be glued in place, but make sure they sit flush. Create two shelves out of plywood and screw them into place. Use your tools to make sure they’re inserted straight and level. You can also make doors for the shelves using extra plywood! raspberrypi.org/magpi November 2017 21 Feature THE BIG BUILD 09 COMBINE THE STRUCTURE 10 ADD A SIDE 11 TAKE SOME MEASUREMENTS Using clamps, make sure the rear cabinet section and front bookshelf section are properly lined up, and then drive screws through the back cabinet section to connect the two. Use clamps again to line the permanent cabinet side up with the side of the build. Make sure it’s the opposite side to where you want the slide-out drawers to open. Screw it in on both the back cabinet and front shelf section to make sure it’s secure. For the classic top of the arcade cabinet (where we’ll house the speakers), you need to measure around the top of the side panel that’s jutting out over and in front of the back pieces. Draw some guidelines starting from 1 inch (25.4 mm) away from the edge, and take into account the width of the wood, so you can figure out the exact size of the top piece. 12 22 FAKE SIDE PIECE One side of the cabinet is going to swing open, which won’t be good for the structure of the top piece. Create an extra top corner piece to help support the top bit, and screw it into place.. November 2017 raspberrypi.org/magpi BUILD AN ARCADE MACHINE 13 ADD SOME SUPPORT 14 CUT THE TOP PIECE 15 TOP BACK COVER 16 SPEAKER PANEL Feature Use scrap pieces on the fixed side to add support to the top piece – make sure they’re inside the lines you measured out in step 11. Using all your measurements, cut the very top piece for the top section. Use your protractor, digital or otherwise, to create the mitre on the piece so the parts will fit together smoothly. Attach it to the supports with screws. Bob cut a panel for the back cover and laid it over the top – it’s not nailed down, so you can quickly access the inside of the top sections. The bottom panel of the top section is where the speakers will be attached. Again, using the guides you’ve made, cut out the piece and check to see if it fits. raspberrypi.org/magpi November 2017 23 Feature THE BIG BUILD 17 SPEAKER HOLES 18 ADD THE SPEAKER PANEL 19 MARQUEE PREP 20 CONTROL BOX 24 Disassemble your speakers and draw the outline of where you want to place them on the panel. Bob used a pencil to draw a couple of lines across the outline to find their centre, and then cut a big hole into it with a drill. Once you’ve cut the hole, double-check that the speakers line up with it. Screw in the speaker panel to the top sections. The front of the top section is used for the marquee, the front art, or lights in this case. To make the front look a little smarter, Bob added another bit of scrap wood just inside the hole to create a flush surface to add a better fascia onto the top section. Bob made a simple tray-like piece that will house the controls. It sits on top of the shelves at the front and does not extend beyond the dimensions of the side panels. November 2017 raspberrypi.org/magpi BUILD AN ARCADE MACHINE 21 CONTROL BOARD 22 MONITOR PANEL 23 MONITOR SUPPORTS Feature The board where the buttons and joystick will live merely covers this box. Bob added some blocks to the underneath of this board so that it can just easily and snugly rest on top of the control box for easy access. The monitor panel needs to be angled so you can look down and see the screen. Cut and mitre a piece of plywood so that it fits in the confines of side panel, top unit, and control board. Cut a hole in the centre to the size of the monitor you plan to use. Bob went one step further and used a CNC machine to cut holes that gave the illusion of a curved CRT TV, like in classic machines! Add a little strip of wood, mitred to the angle of the monitor panel, onto the control board to help support the panel. This way you don’t have to permanently attach the monitor panel to the cabinet. Bob cut the strip into several small pieces that interlocked, with one piece on the control board and one on the monitor panel for extra stability. 24 CUT THE BUTTON HOLES Mark the holes for the buttons and joystick on the control board and cut them out. raspberrypi.org/magpi November 2017 25 Feature 25 THE BIG BUILD BRACE THE MONITOR Tape down the monitor and measure to make sure it’s correctly centred. Add two blocks to either side and then attach a piece over them to snugly clamp the monitor in place over the hole you created for it. 26 MAKE THE DRAWERS 27 AINT EVERYTHING! 28 Remember the drawer runners we added to the rear section of the cabinet? It’s time to make the drawers for them. You can make them simply with a bottom and four sides if you wish, as long as it will fit. Don’t add the runners yet, though. It’s time to paint the cabinet! Use some masking tape to cover up anything you’d rather not paint (like the runners) and get to it. You can use varnish or spray paint – Bob used a spray gun and did a light bit of sanding between coats. You’ll need plenty of room for this! If you want to add vinyls, add them when the paint is dry! If you want to add the T-Molding, you can do that now! Cut a small indent into the edge of the side panels and then use a rubber mallet to gently knock it into place. ADD THE BUTTONS Once the paint is dry, you can add the buttons and joystick to the control board. Affix them in place with screws. 26 November 2017 raspberrypi.org/magpi BUILD AN ARCADE MACHINE 29 ADD THE MARQUEE 30 ADD THE SPEAKERS Feature In this build, the marquee is a print on something like clear acrylic so it can be lit up from inside. If you are doing something like this, merely glue it into the little hole of the top unit. Otherwise, attach a final piece of plywood to fill the hole. Paint a cool little graphic on there, though: it will look good. Add the speaker grilles to the outside of the top unit with screws, and then screw in the speakers on the inside. 31 FINISH THE DRAWERS Remove one part of the runners for the drawers and carefully attach them to the side of the painted drawers before slotting them in. 32 CABINET DOOR Cut the piano hinge in half with a rotary tool, before attaching the halves to the back board on the open side of the cabinet. Attach the other side to the back edge of the side panel so that it can open and close. The standard build is now complete! raspberrypi.org/magpi Want to do more? The original tutorial on Bob’s website shows you how to add motion-activated LEDs to the build – great for a party piece: magpi.cc/2hBcDQK November 2017 27 Feature THE BIG BUILD SET UP RASPBERRY PI Here’s how to get your beautiful new cabinet to play some games tand back and admire your work. You’ve built an arcade machine with your own fair hands! It’s quite the achievement. We’re not quite done yet, as we need to get the Raspberry Pi set up and everything connected. In comparison, this is the easy part. S CONFIGURE RETROPIE 28 GET RETROPIE INITIAL SETUP LOAD YOUR ROMS Head to the RetroPie website and grab the latest image of RetroPie (magpi.cc/25UDXzh). You’ll then need to install it to an SD card using Etcher – you can follow along to our tutorial video to do this if it’s your first time: magpi.cc/etchervid. Put the SD card in and boot up your Raspberry Pi. Go through the initial setup just to get it going – you’ll have to do the controller configuration again once you install it into the cabinet, though. It’s easier to get any of your ROMs loaded onto the SD card now, before you put the Pi into your arcade cabinet. You can always take it out later as we built it to be accessible if you want to add or remove ROMs, though. You can find the info on how to do this here: magpi.cc/2hBznjB. November 2017 raspberrypi.org/magpi BUILD AN ARCADE MACHINE WIRE UP THE CONTROLS Feature CONNECT IT ALL UP PREPARE THE WIRES THE CONTROL BOX As we’re using light-up buttons, we need to provide power for the LEDs in them. You can do this by creating a daisy chain of power and ground wires that will connect all the lights. This is most neatly done by adding them to female plugs that slot onto each button’s connectors. You’ll also need individual wires for each button and joystick output, and a daisy chain of connectors like the power and ground ones for the ground connections of the inputs. Your Pi can now live in the control box under the buttons. All you need to do is run power for the Pi and the HDMI cable for the monitor through the box – you can do this with some well-placed holes behind the monitor or through the back of the cabinet. POWERING IT ALL WIRE IT UP Connect the individual control wires and input ground to the corresponding ports on the I-PAC board, and also connect your daisy-chained power and ground wires to the buttons/joysticks on one end and the screw terminal at the other. CONNECT TO PI The I-PAC can now be connected to the Raspberry Pi using the USB cable. Load up control configurations to set the correct inputs for players one and two. raspberrypi.org/magpi You’ll need several plugs to power all of this, even in its most basic configuration. The Pi, LEDs in the buttons, and monitor will all need power. You can just plug them all into the wall, but we suggest getting a (surge-protected) power strip and plugging all the parts into that. Have a lead run out of the back to plug it in and turn the whole system on. If you’re doing Bob’s full build, you can go a bit further and add a relay switch and more. TURN IT ON! You’re ready to game. Get a soda and some Doritos to complete the experience and enjoy your own personal arcade cabinet. Happy gaming! November 2017 29 Feature THE BIG BUILD OTHER ARCADES Want an arcade machine, but would like to try something a little different than our build? Here are some alternatives… SUPER PIE magpi.cc/2yFTPes Still want a classic arcade cabinet you can stand up, but don’t want to bother with the extra storage? Pierre Sobarzo’s Super Pie is a simpler build, albeit with many of the same considerations for electronics. His also has coin slots for added authenticity. The Imgur album doesn’t quite have the same build instructions, but you can absolutely use it as a guide to simplify the build on the previous pages. ARCADE PI magpi.cc/1Q5gGw8 The simplest way to experience the arcade at home, and with comfort, is to just build an all-in-one arcade stick with a Pi – and therefore games – hidden inside. All you need is a long HDMI cable. You can buy ready-made kits that will let you build these, but this version has full instructions you can copy along to. We like these style of plug-and-play controllers as they’re quick to make, look great, and are extremely versatile. 30 November 2017 raspberrypi.org/magpi BUILD AN ARCADE MACHINE BARTOP ARCADE MACHINE Feature magpi.cc/1qOxaVh What makes up the arcade experience? Do you have to be in the corner of the room standing at a bulky device purely to play games? Bartop arcade machines like the Galactic Starcade take up less space, but still give the arcade experience of playing with a stick. This build is also a lot easier to do as you don’t have to paint and move a massive wooden structure around. You can also just plonk it on a table when you want to get it out and play some Elevator Action. PIK3A magpi.cc/1qOxwLG The cocktail arcade machine is a popular oldschool variant of the traditional arcade cabinet, especially for custom builds. It allows you to use the space as a table as well, and two players don’t have to crowd around one side of the machine to play multiplayer. This Pik3a uses the LACK side table from IKEA in its construction, giving it a very unique look, but there are plenty of other cocktail arcade machines you could take inspiration from. MINI ARCADE magpi.cc/1V8XEvY Want a full arcade cabinet but also the space and portability of the bartop arcade? How about a mini replica of your favourite arcade machine? Tiburico de la Carcova has a selection of mini arcade machine replicas, but the most popular one is his Galaga setup. It includes accurate art stuck to the panels and, more importantly, it’s only a couple of feet high. He keeps his on display and only playing a single game, but there’s no reason not to make yours multipurpose. raspberrypi.org/magpi November 2017 31 SUBSCRIBE Tutorial WALKTHROUGH TODAY AND RECEIVE A FREE PI ZERO W Subscribe in print for 12 months today and receive: A free Pi Zero W (the latest model) Free Pi Zero W case with three covers Free Camera Module connector Free USB and HDMI converter cables L OFFRIOCCIA ASE PI ZE WITH 3 COVERS AND FREE CAMERA MODULE CONNECTOR AND USB / HDMI CONVERTER CABLES Other benefits: Save up to 25% on the price Free delivery to your door Exclusive Pi offers and discounts Get every issue first (before stores) 32 November 2017 raspberrypi.org/magpi Pricing Get six issues: £30 (UK) £45 (EU) $69 (USA) £50 (Rest of World) SUBSCRIPTION FORM Tutorial YES! I’d like to subscribe to The MagPi magazine and save money This subscription is: n For me n A gift for someone* YOUR DETAILS Mr n Mrs n Miss n Ms Mag#63 .................................................................. Subscribe for a year: £55 (UK) £80 (EU) $129 (USA) £90 (Rest of World) PAYMENT OPTIONS Get three issues: £12.99 (UK) (Direct Debit) $37.50 (US) (quarterly) SUBSCRIPTION PRICING WHEN PAYING BY CHEQUE OR CREDIT/DEBIT CARD 6 ISSUES How to subscribe: magpi.cc/Subs-2 (UK / ROW) imsnews.com/magpi (USA) Call +44(0)1202 586848 (UK/ROW) n n / n n/ n n Banks and building societies may not accept Direct Debit instructions for some types of account. November 2017 33 Projects SHOWCASE POPPY MOSBACHER A Sustainable Design student at the University of Brighton who won a Blue Peter robot design competition, aged eight. magpi.cc/2xRmUjR When someone stands inside the frame, Take Photo is pressed on the laptop software, and the images are taken and saved Pi Zero Ws and cameras are housed in laser-cut 5 mm singlewalled corrugated cardboard Tubes, of varying lengths, are attached to each other using connectors and selfadhesive touch fasteners 3D BODY SCANNER Poppy Mosbacher has created a relatively inexpensive full-body 3D scanner, and she hopes maker groups will enjoy replicating her project! Quick Facts > The project’s Pis are named after Marvel characters > Poppy wanted the build to cost less than £1,000 > The images are processed using Autodesk ReMake > Build Brighton members got fully involved in the project > It uses mains electricity, so be careful! 34 hile learning to make her own clothes, Poppy Mosbacher wanted to visualise how they would look before she made them, and she began to think about how digital technology tools could help. At first, she considered using a body scanner, but after talking to a friend, she learned that high-end 3D scanners using DSLR cameras can cost as much as £40,000. Just as bad, the cheapest alternative – of simply walking around an object or person and taking lots of photos with a single camera – proved slow and frustrating. It was then that her friend and member of the not-for-profit makerspace Build Brighton, Paul Hayes, suggested that it might be easier to make a DIY version of a 3D scanner using Raspberry Pis. Before W November 2017 long, Poppy had secured a £1,000 grant from Santander, which she used to buy 27 Pi Zero Ws (each snapped up by a different Build Brighton member to get around the one-per-customer rule). She also bought 27 Camera Modules, 27 Pi Zero camera cables, and 27 USB to micro USB cables, as well as an assortment of battery packs, power regulators, wire connectors and other electrical items. When everything is set up, the 3D Scanner Camera Coordinator software allows the user to access the dashboard and click the Take Photo button raspberrypi.org/magpi 3D BODY SCANNER Projects PREPARING THE PIS >STEP-01 >STEP-02 >STEP-03 Prior to her project, Poppy had only used the Raspberry Pi once, at a workshop at the Mozilla Festival in 2015. Arthur Guy wrote the actual code, which needs to run constantly. After setting up the server so that the cameras know which fixed IP address to send the photos to, a computer is connected. The cameras are then hooked up to the Pi Zero Ws. The Pi Zero Ws and the cameras are housed in these cardboard cases, which are then placed around the structure. A 5 V power regulator can be connected to up to three Pis. Code the Pi Cardboard engineering Inspired by Richard Garsthagen (magpi.cc/2xVr3Vr), Poppy then looked at making the scanner affordable and portable. “The idea of having a portable rig that people could step into and take a picture in a few seconds was appealing,” she says. By using Zero Ws, she hoped Connect the camera House the Pis Coding challenges “The photos are sent wirelessly to the laptop and they are automatically saved in a new folder,” Poppy explains. Raspbian Jessie Lite is installed on the Pis, and the main server runs a node application. Another friend, Arthur Guy, wrote the code for the scanner Twelve 3 mm thick cardboard tubes were used, on which the Pis and their cameras were mounted the scanner could be replicated in the future for less than £1,000. To keep costs low, and to make the build easier for Poppy and the Build Brighton team, twelve 3 mm–thick cardboard tubes were used, on which the Pis and their cameras were mounted. Poppy says the cardboard proved to be “a great material to cut and make holes in.” As well as the cardboard frame, a cardboard case was designed for the Pi Zero Ws. “It also helps hide the wires,” she adds. Created to work within the smallest possible diameter so that it can remain portable, the idea was to connect the Pis to a laptop to trigger the photos, so that all the cameras would take a snap simultaneously. raspberrypi.org/magpi in JavaScript, building it up week by week, and adding features such as getting the Pis to look for updates on startup so that they all use the latest version of the software. There were still some issues along the way, and a fair bit of trial and error, especially in positioning the cameras so that the photogrammetry software could digitally stitch the images together. There was also a problem with Poppy’s shiny long hair, which became apparent when she stood inside the structure. “I looked online, and it suggests putting powder on anything shiny, but I haven’t tried it yet.” Some problems proved easy to overcome. Figuring out which cameras weren’t working was solved by assigning them names, and Arthur also learned to change the white balance on the cameras to improve the image quality. Yet there are problems with time lag. “Some Pis take a photo instantly, and others take a few seconds, so we have to stay still until all the photos have been taken,” Poppy says. Nevertheless, she is excited about future applications for the project. “It opens up new possibilities, such as of scans of children who won’t stay still long enough for the single camera method; building a personal database of scans taken at regular intervals to see the effects of aging; and making avatars for VR environments.” Above Eight cross joints and four T-junctions were 3D printed using an Ultimaker 2+ November 2017 35 Projects SHOWCASE KEVIN S LUCK Kevin S Luck is a PhD student at Arizona State University working on robots and new machine learning methods with Joseph Campbell and Michael A Jansen. magpi.cc/2yzh4pu Quick Facts > The total cost of a C-Turtle is about £50 > The goal is to create an autonomous fleet > The experimental learning algorithm was written in MATLAB > C-Turtle learned to move optimally in an hour > It will blow up discovered land-mines – and itself C-TURTLE Building a Pi-based robot only to blow it up may sound like a waste, but this mine detector could save lives t’s a sad truth, but right now the world is littered with an estimated 110 million land-mines. Clearing I them all could take as long as 1000 years and cost $30 billion, but leaving them in situ is not an option. The number of people killed or injured by these hidden weapons recently reached a tenyear high – so how amazing would it be if the Raspberry Pi could help tackle this ever-present problem? Cardboard demining Scientists at Arizona State University have been putting their heads together to do just that. They have devised the C-Turtle, a cardboard robot with turtle flippers which has a Raspberry Pi at its heart. It uses machine learning to figure out how to walk across the most unusual and hazardous of terrain, constantly adapting to its surroundings. Modelled on a sea turtle (hence the name), it is not only inexpensive, but easy to transport. “We were looking to develop a cheap and simple robot for the detection of land-mines,” says PhD student Kevin S Luck, who has worked on the project with Joseph Campbell and Michael A Jansen. “Undetected land-mines are a problem in many countries, and often these mines are particularly difficult to detect in sandy environments. The problem is that sand in a desert moves over time and so the location and depth of the land-mines is constantly shifting.” Inspired by nature The C-Turtle is well equipped to cope with this issue. Housed within a single-sheet laminate comprised of layers of paper, foil and adhesive, it mimics the movement of a sea turtle. The scientific trio had noted how quickly sea turtle hatchlings can move over sand and how adults crawl while lifting their immense weight. This led to Michael developing a workable fin shape, and Kevin and Joseph figuring out how the Pi could best power the robot. A Raspberry Pi Zero powers the robot, while a 16-channel, 12-bit motor driver from Adafruit communicates with the moving parts This pair of laterally mounted fins moves with two degrees of freedom The front end is curved to prevent it from digging into the ground as it moves 36 November 2017 raspberrypi.org/magpi C-TURTLE “We envisioned a system where each robot can carry sensors to detect and mark land-mines, but also where the loss of a single robot is relatively inconsequential for demining operations, thus reducing the risk for humans or bigger demining robots,” explains Kevin. During the design process, some key decisions were made. They ruled out using wheels – “they usually have issues with slippage on sand, and they would create a more complex manufacturing process,” says Kevin – and were unanimous in wanting to use a Raspberry Pi Zero. Lightweight connectivity “The Pi felt perfect,” Kevin continues. “We not only wanted the ability to send commands to the robot via WLAN, but also to perform simple data processing and machine learning directly on the robot – a requirement for using multiple robots in a fully autonomous fleet. The Zero also requires relatively little power. Because of that, we’re exploring the possibility of using solar panels for recharging batteries during the daytime.” Below Tests are ongoing to find out how well the robot, and the Pi, cope in extreme temperatures Kevin and Joseph have worked on an algorithm which allows the turtle bot to adapt its crawling technique. “The whole code infrastructure on the turtle robot, from motor control to the joint server and sensor collections, was written in Python,” Kevin reveals. “We used TCP/IP connections to send joint commands to the robot and also to collect data for evaluation.” Projects CREATE THE C-TURTLE’S BODY Real-world learning This was put to the test when they drove out into the desert with their first prototypes. “We got a real-time feed of what was happening with our robot, and were able to test and debug different variations of the learning scenarios,” Kevin tells us. By using trial-and-error learning, the robot gets good and bad feedback which enables it to develop. Through this process, the robot has managed to work out effective trajectories over poppy seeds as well as sand, but the scientists are continuing to refine the technology and their ambitions remain high. “We’d like to take the robots into space, too,” says Kevin. “It would be fantastic to use them to explore Mars.” >STEP-01 Laser-cut the layers The cardboard layers are laser cut. For each of the five layers (two cardboard, two adhesive, and one foil), holes are cut in specific locations to allow hinges to be fitted later. >STEP-02 Begin the lamination Once the layers are cut, they are laminated together to form a single layered sheet using a heating press. >STEP-03 Ready for assembly The shapes of the individual parts are cut from the laminated sheet. The holes are mounting holes, designed to be used with rivets. raspberrypi.org/magpi November 2017 37 Projects SHOWCASE DAVID PRIDE Currently studying for a PhD with the OU, David is a well-known member of the Pi community. Previous projects include a LEGO-sorting robot arm and Connect 4-playing robot. piandchips.co.uk Wall-mounted alien targets drop down when shot by FRED-209 The custom 3D-printed firing mechanism shoots the foam darts from a Nerf magazine Built on a Rover 5 chassis, the robot has caterpillar tracks for extra grip Quick Facts > It currently runs on 14 AA batteries > The firing mechanism is mainly 3D-printed > David plans to add a camera > He’ll upload the STL files for 3D printing > FRED-209 is sadly too big for Pi Wars 38 FRED-209 Say hello to David Pride’s Nerf-toting robot! You have 20 seconds to comply… hile well-known Pi community member David Pride admits that Nerf guns hadn’t been invented when he was a youngster, his interest was sparked when he saw two tables full of Nerf gear at a car boot sale. “I started wondering whether you could operate the trigger mechanism with a servo – turns out you can!” Following some successful experiments firing smaller, singleshot Nerf guns using a servo, David turned his attention to larger Nerf W November 2017 models. “[I] realised that there are essentially two types: the pump action ones and those which use two flywheels to propel the dart. I didn’t know exactly how the mechanism worked until I actually took one to bits!” Initially, David simply strapped an upside-down Nerf gun to the top of his 2017 Pi Wars robot, X-Bot. “I realised that this wasn’t really going to cut it, so set about designing and 3D-printing a complete setup that I could mount on top of a bot. It uses the original Nerf flywheels, and the original Nerf magazine which can hold six darts. The rest is all 3D-printed. I also designed a simple mechanism to translate servo movement into lateral movement to push the dart into the launcher.” During the two months of evenings and weekends he spent working on the project over the summer, several design changes were made. “The biggest disappointment was that the huge chunky motors I had didn’t have enough torque to turn the raspberrypi.org/magpi FRED-209 Projects BUILD A NERF DART-FIRING ROBOT Above A long threaded bar converts motor rotation into lateral movement to tilt the whole firing mechanism (not shown) up or down for aiming purposes bot successfully. Getting the right motors is an area where I am definitely still learning and it’s a critical factor to get right in building a successful bot.” Since he’d already bought a Dagu Rover 5 chassis, David opted to mount his Nerf mechanism on that until he obtained some stronger motors. He also dropped the the Raspberry Pi. A tilt mechanism for aiming is controlled by the joypad’s shoulder buttons. David describes the robot’s public debut at the Cotswold Jam as ‘controlled chaos’. “It went down extremely well. I built some ‘evil alien’ targets to give the participants something to aim at – apart from each other!” >STEP-01 Servo pusher David 3D-printed most of the parts for his Nerf firing mechanism, including the servo pusher. An arm connected to the servo moves a rod forward to push the dart from the magazine. It uses the original Nerf flywheels, and the original Nerf magazine which can hold six darts original chunky wheels in favour of smaller ones with caterpillar tracks. Controlled manually using a wireless PS3 joypad, FRED-209 can fire multiple foam darts at the chosen target(s). Its twin motors are driven using a ZeroBorg board, while the firing servo is connected directly to the GPIO 18 PWM pin on Continuing work on the project, David plans to power it with LiPo batteries – “It currently runs on 14 (!) AA batteries which really don’t last very long as the drive motors and flywheel motors are pretty greedy.” He also plans to add a camera to enable FRED-209 to find and fire at targets automatically. “I did some very simple vision processing for 4-Bot, my Raspberry Pi Connect 4 robot, but this takes it up several levels. I am currently learning OpenCV and SimpleCV for vision processing… The plan is the bot will recognise colour/shape to locate target. I can see it working well as a burglar detector... providing the burglar is wearing a black and white stripy shirt and carrying a bag marked ‘swag’!” Left David originally tried mounting a standard Nerf gun on the top of a robot, but soon realised that it wasn’t really going to work that well raspberrypi.org/magpi >STEP-02 Flywheel flinger The dart is pushed into twin rotating flywheels which propel it rapidly down the barrel. These, along with the robot’s drive motors, require a lot of battery power. >STEP-03 Completed mechanism The 3D-printed lid has a slot to load the upside-down Nerf gun magazine. A roller underneath moves along to tilt the whole mechanism up and down to aim. November 2017 39 Projects SHOWCASE JEREMIAH MATTISON Jeremiah is a Software Engineer for the PNI Sensor Corporation in Santa Rosa, California. He spends his free time tinkering with sensors and writing software for them. magpi.cc/2ko6qMG Quick Facts > Build details are on Hackster (magpi.cc/ 2ko6qMG) > The cats wear Tile Bluetooth tracker tags > Magnetic switches limit the door’s movement > The software is all in Node-RED RPI 3 BLE CAT DOOR To limit access to his home to just his own four cats, Jeremiah Mattison built a Bluetooth tag-sensing motorised pet door > Jeremiah is adding a camera to the door A motorised car radio antenna is used to lift and lower the sliding door Mounted in a metal box, the Pi 3 detects the cats’ individual Bluetooth tags iving in Santa Rosa, California, Jeremiah Mattison had a major problem with critters getting into his house through his pet door. “There are many cats in the neighbourhood and I was getting woken up every night by them trying to get into the bulk food. Additionally during the fall, in what I have coined ‘Racktober’, we have a problem with raccoons as well.” L The solution was to create a tag-sensing motorised pet door to enable his four cats to get in, but keep other animals out. After a failed attempt based on an Arduino and passive RFID tags, Jeremiah found the purr‑fect solution using a Pi 3 and Bluetooth Low Energy (BLE) tracking tags. “The [RFID] tags had to be really close to the antenna,” he recalls. “The BLE tags are battery powered, so they Below The door will stay open so long as the Bluetooth tag is in range; when not, it closes after 15 seconds The door only opens to allow Jeremiah’s cats in, keeping other animals out 40 November 2017 raspberrypi.org/magpi RPI 3 BLE CAT DOOR have greater range and I can use the RSSI metric to control the distance at which they trigger the door.” To slide open the Ideal RuffWeather pet door, Jeremiah originally planned to use a stepper motor with a track or pulley system, but ended up using a motorised car antenna instead. “[I] somehow found myself on a forum thread with people talking about using automotive antennas for DIY automated chicken coop doors. They were just using a simple timer to open and close the door, which wouldn’t work for my project, but the antenna part was perfect.” Controlling the door Mounted in a metal box to one side of the pet door, the Pi 3 is stacked with two Adafruit Perma-Proto HATs wired up with the extra electronics required – including an H-bridge circuit to drive the motor, and three status LEDs. The blue LED flashes whenever the Pi – programmed using Node-RED – senses a permitted Bluetooth tag within range, currently set to around 2 metres. “This allows the door to open far enough in advance not to spook the cats, but still minimise the time open so other animals can’t sneak in.” The door waits 15 seconds after the last BLE trigger before closing, which Jeremiah says should be Projects CREATE A SMART PET DOOR >STEP-01 >STEP-02 Jeremiah used a 12 V motorised car antenna, mounted upside-down, to lift and lower the sliding pet door. He ripped out the control circuit and used the motor wires directly. Wired up on a Perma-Pro HAT, the H-bridge circuit that controls the antenna motor features an Adafruit TB6612 breakout board, plus 1N4001 diodes to protect from reverse voltage. Motorised door H-bridge motor driver >STEP-03 Node-RED flow After trying to use Python, Jeremiah opted to use Node-RED for the software, employing a BLE scanner node to detect the named Bluetooth tags worn by his four cats. The reaction of his cats to the new door has been mixed. “Two of them are mostly outdoor cats and they had no problem adjusting to the cat door, and even still use it when the garage door next to it Jeremiah found the purr-fect solution using a Pi 3 and Bluetooth Low Energy (BLE) tracking tags more than enough time for the cats to make it through safely. “There was one time where one of the cats had come into the garage and I walked out and spooked him, sending him running out the cat door right as it was closing so it nicked him a bit; but there’s not much resistance on the automotive antenna so it didn’t really do anything.” raspberrypi.org/magpi is open. The other two are skittish, mostly indoor cats and are still getting used to it.” To enhance the project, Jeremiah has just mounted a security camera outside the cat door and – as well as snapping photos of critters to tweet via a Twitter bot – plans to use it for image recognition to enable tighter RSSI settings for more accurate door triggering. Above Each cat wears a Tile Bluetooth tag which is detected by the Pi when in range, to trigger the door November 2017 41 Tutorial WALKTHROUGH MIKE COOK MIKE’S PI BAKERY Veteran magazine author from the old days and writer of the Body Build series. Co-author of Raspberry Pi for Dummies, Raspberry Pi Projects, and Raspberry Pi Projects for Dummies. magpi.cc/259aT3X MIDI sound box for this project MIDI USB converter lead so we can connect the sound box to the Pi Headphone or amplifier socket so we can listen to it You’ll Need > Raspberry Pi 3 > Adafruit Music Maker FeatherWing board magpi.cc/ 2yv8d57 > 6N138 optical isolator > 1N4001 diode > 3V3 regulator and capacitors > 5-pin DIN socket > 2.1 mm power jack > Stripboard and resistors > 16-way and 12-way female header sockets 42 MIDI Make a standalone MIDI sound generator couple of months back, in issue 61, we showed you how to make a Polyrhythmic Sequencer, which used a MIDI output. While it is possible to find second-hand MIDI sound generators, there are not many new ones available these days. For the computer hobbyist, hardware sound generators are great for use in experimental projects. There is a popular chip, the VS1053, which is used in a lot of MP3-playing modules. What is not well known is that this chip also has a direct MIDI input. In fact, many boards that use this chip do not even track out this pin, so it tends to be overlooked. This month, we have taken a board that features this chip, and used it to make a standalone MIDI sound generator. A November 2017 SOUND BOX The chip is used in several Adafruit Music Maker products. We have taken the cheapest of these boards, the Music Maker FeatherWing, and hacked it so it will work alone. The board is designed to be plugged into one of a series of small processor boards called Feathers, but for a straight MIDI interface this will not be needed. All we have to do is provide the Music Maker FeatherWing with a 3V3 voltage, and build a MIDI interface to feed the serial MIDI input. The circuit A MIDI input interface consists of an optically isolated input from a standard-size 5-pin DIN socket. There is a diode on the input to prevent any damage (for example if a cable has been wired the wrong way raspberrypi.org/magpi MIDI SOUND BOX Tutorial Figure 1 Schematic of the MIDI sound box project ADAFRUIT MUSIC MAKER FEATHERWING Opto Isolator 470R 8 6N138 2 5 1N4001 All pin numbers on long strip from left with the sound output on your right 10K MIDI IN Regulator +5V 2.1mm Power Jack BAO33 (2nd Pin) 3V 3V3 (4th Pin) Gnd 0.33uF 22uF Looking at the back of the socket MIDI RX (15th Pin) (Pin 26 on VS1053) 7 3 220R 6 Gnd round), and also a current-limiting resistor for the LED inside the optical isolator. On the output side, a Darlington transistor pair picks up the infrared light from the LED and amplifies it. This signal can then be sent to the MIDI input of the VS1053. We need to feed the board with 3V3, so we have included a voltage regulator to do this. The whole circuit is rather simple, and is shown in Figure 1. Note that the input capacitor value shown on the schematic is a minimum value – in fact, we used a surface mount 47 uF capacitor here, because we had one to hand. Make sure that this capacitor has a voltage rating big enough to cope with the voltage you intend to use to power the project. Construction details are shown in the illustrated step-by step section of this article. The software While the Polyrhythmic Sequencer was written in the Processing language, Python can handle MIDI as well, and we will show you how to do this here. First, you need to load in the real-time MIDI module; it’s called RtMidi. It has a few dependences which you may, or may not, already have installed. Into a Terminal window, type: raspberrypi.org/magpi sudo apt-get install libjack0 sudo apt-get install libjack-dev Figure 2 This screen allows you to test different sounds sudo apt-get install build-essential sudo apt-get install libasound2-dev sudo apt-get install libjack-dev sudo pip3 install python-rtmidi November 2017 43 Tutorial WALKTHROUGH voiceTest.py 001. 002. 003. 004. 005. 006. import pygame, time, os import rtmidi midiout = rtmidi.MidiOut() pygame.init() # initialise graphics interface Language >PYTHON DOWNLOAD: magpi.cc/1NqJjmV PROJECT VIDEOS Check out Mike’s Bakery videos at: 007. magpi.cc/1NqJnTz 008. os.environ['SDL_VIDEO_WINDOW_POS'] = 'center' 009. pygame.display.set_caption("Genral MIDI Instrument test") 010. pygame.event.set_allowed(None) 011. pygame.event.set_allowed([pygame.KEYDOWN, pygame. MOUSEBUTTONDOWN, pygame.QUIT, pygame.MOUSEBUTTONUP]) 012. 013. screenWidth = 1030 ; screenHeight = 530 014. screen = pygame.display.set_mode([screenWidth,screenH eight],0,32) 015. textHeight = 18 ; sq = 12 # square size 016. font = pygame.font.Font(None, textHeight) 017. font2 = pygame.font.Font(None, textHeight*4) 018. backCol = (220,200,128) # background colour 019. xList = [5,184,368,542,740,880] # column positions 020. currentVoice = 0 ; currentNote = -1 021. whiteNotes = [48,50,52,53,55,57,59,60,62,64,65,67,69, 71,72] 022. blackNotes = [49,51,54,56,58,61,63,66,68,70] 023. channel = 0 # change from 0 to 15 use 9 for percussion 024. keyboardShift = 0 025. 026. def main(): print("MIDI Sound Box - Instrument test") 027. init() # open MIDI port 028. loadResorces() 029. drawScreen() 030. initMIDI() 031. findBox((10,17)) # hi-light initial voice 032. while True: 033. checkForEvent() 034. 035. 036. def loadResorces(): global whiteKeys, blackKeys,iNames,voiceBox 037. whiteKeys = [] 038. blackKeys = [] 039. voiceBox = [] 040. for i in range(0,15): 041. whiteKeys.append((280+i*34,420,30,80)) 042. for i in range(0,13): 043. if not(i ==2 or i == 6 or i == 9): 044. blackKeys.append((299+i*34,420,26,40)) 045. nameF = open("GM_Instruments.txt","r") 046. iNames = [] 047. for i in nameF.readlines(): 048. n = i[:-1] # remove CR at end of name 049. 44 November 2017 Figure 3 Using the Feather M0 and FeatherWing together When the installation is complete, reboot and try the voiceTest.py program. This displays a small section of a piano keyboard under a list of all 128 different instruments that the chip can produce (Figure 2). This is the General MIDI or GM sound set, and is normally implemented on all MIDI sound generators. Click a box to select a sound, and the instrument or voice number is displayed in the lower left-hand corner of the window. The note number on the right changes as you click on the piano keyboard. This software makes use of a file entitled GM_Instruments.txt, which is simply a list of the instrument names in order. You can type this in from the screenshot, but we copied it from the VS1053’s PDF data sheet into a text file, then imported it into a spreadsheet using the CSV format. We put the three columns into a single column, and sorted it. Finally, we saved it as a text file and reimported it to the spreadsheet so the numbers were in a separate column, deleted that column, and saved just the instrument names as a text file. The sound quality The sounds of the GM set are not the best you’ve ever heard, but they are far from being the worst. As well as the sound waveform, there are other things that add to the perception of a real instrument: the register, or note range; and the style of playing. For example, a real piccolo only plays high notes, but on a MIDI sound set it can play any note. Some instruments, such as the strumming of a guitar, are raspberrypi.org/magpi MIDI SOUND BOX MAKING THE MIDI SOUND BOX >STEP-01 Making the board Take a piece of stripboard, 21 by 19 holes (you might want to make it 21 by 20 holes, to give a bit more room to break the tracks between the FeatherWing board and the MIDI input circuitry). Drill holes for mounting, as shown in the photograph. Build the optical isolator MIDI input circuitry, and then add the female headers for the FeatherWing board. Make sure the FeatherWing board just hangs over the end of the stripboard to allow the audio socket to poke through the mounting panel.. not easy to emulate on a keyboard. These differences add up, and your ear picks them up as fake instruments. Nevertheless, the VS1053 makes a good stab at trying to reproduce realistic sounds. We noticed several problems with the voices. All four saxophone sounds, 84 to 87, were identical, as were the string ensembles 48 and 49. The oboe, voice 69, dramatically changes timbre between note 51 and note 52. Some notes ‘develop’ when the key is held down for a few seconds, especially voices 88 to 103, and the reverse cymbal, voice 119. raspberrypi.org/magpi 090. 091. 092. 093. 094. 095. 096. 097. 098. 099. 100. Tutorial iNames.append(n) nameF.close() #print(iNames) def init(): available_ports = midiout.get_ports() print("MIDI ports available:-") for i in range(0,len(available_ports)): print(i,available_ports[i]) if available_ports: midiout.open_port(1) else: midiout.open_virtual_port("My virtual output") def initMIDI(): midiout.send_message([0xB0 | channel,0x07,127]) # set to max volume midiout.send_message([0xB0 | channel,0x00,0x00]) # set default bank def drawScreen(): cp = screenWidth/2 pygame.draw.rect(screen,backCol,(0,0,screenWidth,screenH eight),0) for i in range(0,len(whiteKeys)): pygame.draw.rect(screen,(255,255,255),whiteKeys[i],0) for i in range(0,len(blackKeys)): pygame.draw.rect(screen,(0,0,0),blackKeys[i],0) drawLables() drawWords("Voice",60,400,4) drawWords("Note",847,400,4) pygame.display.update() def updateNote(n): # note displayed pygame.draw.rect(screen,backCol,(870,462,103,49),0) if n != -1: drawWords(str(n),874,460,4) pygame.display.update() def updateVoice(n): pygame.draw.rect(screen,backCol,(87,462,103,49),0) drawWords(str(n),88,460,4) pygame.display.update() midiout.send_message([0xC0 | channel,n]) # program change message def drawWords(words,x,y,s) : textSurface = pygame.Surface((14*s,textHeight*s)) textRect = textSurface.get_rect() textRect.left = x textRect.top = y if s == 1: # font size textSurface = font.render(words, True, (0,0,0), (20,20)) else: textSurface = font2.render(words, True, (0,0,0), (20,20)) November 2017 45 Tutorial WALKTHROUGH screen.blit(textSurface, textRect) 101. 102. 103. def drawLables(): for i in range(0,128): 104. point = getPoint(i) 105. pygame.draw.rect(screen,(0,0,0),(point[0],point 106. [1],sq,sq),1) drawWords(iNames[i],point[0]+20,point[1],1) 107. 108. 109. def getPoint(index): x = xList[ index // 22 ] 110. y = 10+(index % 22)*18 111. return (x,y) 112. 113. 114. def findBox(point): global currentVoice 115. i=0 ; found = False 116. while(i<128 and not found): 117. testPoint = getPoint(i) 118. testRect = pygame.Rect(testPoint[0],testPoint[ 119. 1],sq,sq) if testRect.collidepoint(point) : 120. found = True 121. else: 122. i += 1 123. if found : 124. oldPoint = getPoint(currentVoice) # remove 125. previously checked box pygame.draw.rect(screen,backCol,(oldPoint[0],ol 126. dPoint[1],sq,sq),0) pygame.draw.rect(screen,(0,0,0),(oldPoint[0],ol 127. dPoint[1],sq,sq),1) pygame.draw.rect(screen,(200,0,0),(testPoint[0] 128. ,testPoint[1],sq,sq),0) updateVoice(i) 129. currentVoice = i 130. 131. 132. def handleMouse(pos): #print(pos) 133. if pos[0] > 275 and pos[0] < 790 and pos[1] 134. > 409 : i = 0; found = False 135. while(i<len(blackKeys) and not found): 136. currentRect = pygame.Rect(blackKeys[i]) 137. if currentRect.collidepoint(pos): 138. found = True 139. else: 140. i +=1 141. if found : 142. #print("black key number",i) 143. playNote(blackNotes[i]) 144. else : 145. i = 0; found = False 146. while(i<len(whiteKeys) and not found): 147. currentRect = pygame.Rect(whiteKeys[i]) 148. if currentRect.collidepoint(pos): 149. found = True 150. 46 November 2017 >STEP-02 The underside of the board Make sure the solder link is made on the back of the FeatherWing board – you can see it next to the ‘F’ in FeatherWing. Cut the tracks as shown to prevent short circuits, in accordance with the schematic. The regulator we used was a surface-mount type, so we mounted it on this side, along with the 330 nF capacitor on the right, and the 22 uF on the left. The board takes less than 100 mA, so you can easily substitute any other similar fixed voltage regulator in place of the one we used. Note that this chip is polyphonic, which means that it can play more than one note at once, although the test software will only play one at a time. The chip is capable of processing up to 64 notes at a time, but the data sheet warns that for sustained notes, this number reduces to 40. Pressing the + and - keys will shift the on-screen keyboard up or down by an octave. Note that extremely high or low notes don’t sound good on any MIDI system we have heard. A USB interface This project uses a conventional MIDI interface, which means you can plug it into any standard interface, including a keyboard. However, this means that you need a USB-to-MIDI lead to connect the MIDI box to your computer. If you want to connect the MIDI sound box directly to your computer, you need to add a processor that can both act as a USB MIDI device, and talk to the VS1053 chip. An Adafruit Feather M0, or 32u4 processor board with female pin connectors, stacked with a Music Maker FeatherWing, offers an easy solution. The raspberrypi.org/magpi MIDI SOUND BOX >STEP-03 Finishing off Plug in the FeatherWing board and add the 5-pin DIN socket. Connect the input power jack to the flying leads from the board. At this point, test that the board is working correctly. After testing, you can mount it in a box – either a ready-made plastic box, or a home-made arrangement as shown here. We used a Dymo LetraTag label maker, using a clear plastic label cartridge, to label the front panel sockets and the box lid. only interface is then your USB lead, as shown in Figure 3. However, you will need some code to tell the computer to listen to the MIDI. We have written some for you, and it is available in our GitHub repository. As an alternative, the Bare Conductive Touch Board has the same hardware capabilities, and we have written software for that method as well. Taking it further Some versions of the Music Maker boards contain amplifiers. You could use one of these to give the project built-in speakers. You need to supply 5 V to drive the amplifier: simply route the regulator input to the Vcc pin of the FeatherWing board. We will be looking at more applications for this chip next year, but for the time-being, try changing the software so the MIDI box uses channel 9. This brings up a set of percussion sounds instead of the instrumental sets. Note that sounds are only generated for note numbers between 27 and 87. Check page 33 of the VS1053 data sheet for a list of available sounds. raspberrypi.org/magpi. Tutorial else: i +=1 if found : #print("white key number",i) playNote(whiteNotes[i]) if pos[1] < 409 : findBox(pos) def playNote(note): global currentNote note += keyboardShift note = note & 0x7F if note != currentNote: midiout.send_message([0x90 | channel,note,68]) # channel 1, note, velocity 68 currentNote = note updateNote(note) def terminate(): # close down the program global midiout print ("Closing down please wait") del midiout pygame.quit() # close pygame os._exit(1) def checkForEvent(): # handle events global currentNote, keyboardShift event = pygame.event.poll() if event.type == pygame.QUIT : terminate() if event.type == pygame.KEYDOWN : if event.key == pygame.K_ESCAPE : terminate() if event.key == pygame.K_EQUALS : keyboardShift += 12 # move up an octave if keyboardShift > 55 : keyboardShift -= 12 print("Shift",keyboardShift // 12, "octaves") if event.key == pygame.K_MINUS : keyboardShift -= 12 # move up an octave if keyboardShift < -48 : keyboardShift += 12 print("Shift",keyboardShift // 12, "octaves") if event.key == pygame.K_s : # screen dump os.system("scrot") if event.type == pygame.MOUSEBUTTONDOWN : handleMouse(pygame.mouse.get_pos()) if event.type == pygame.MOUSEBUTTONUP : if currentNote != -1: midiout.send_message([0x80 | channel,currentNote,0]) currentNote = -1 # no note playing updateNote(currentNote) # Main program logic: if __name__ == '__main__': main() November 2017 47 Tutorial WALKTHROUGH KENT ELCHUK A Raspberry Pi enthusiast, web developer and multi-published gardening author who is likely coding, gardening or doing family stuff. growlode.com SET UP AND MONITOR A You’ll Need > Motion magpi.cc/ 2gVrlp2 > USB webcam > Remote hosting account (e.g. GoDaddy, Bluehost, HostGator) HYDROPONIC GARDEN Follow up last month's tutorial with everything you need to know to build a hydroponic garden n the modern era, with urban farming and increasing food costs, it’s time to take charge and build affordable hydroponic gardens for everyone’s favourite produce: lettuce, tomatoes, peppers, onions, jalapeños, and cucumbers, to name a few. With a Raspberry Pi at each garden location, a quick automatic snapshot can be taken and the image sent to that user’s account on a remote server. The remote server admin can easily display those images from each account into a password-protected webpage and watch every garden from anywhere on the planet. When something looks off, a garden can be checked and fixed. Last month, we learned to use a sensor to monitor the watering of a garden and access that information over the web. This time around, we’re going to look I Below Setting up a FTP user account is fast and simple; just provide the basics like user name and password. This info will be added to the send.sh script on a user's Raspberry Pi PART 02 at remote garden monitoring using a webcam and expand on the actual gardening part. By the end of this tutorial, hooking up Raspberry Pis with USB webcams to more than one garden location and keeping an eye on the progress of all gardens will be as easy as one-two-three. Let’s dive into the monitoring aspect, as it is very crucial – seeing is believing. Unlike the previous lesson about water sensors, a webcam helps you monitor for other potential issues like wind damage, plants in need of extra support and the pure pleasure of watching beautiful gardens over which we have complete control. Plant monitoring In a nutshell, plant monitoring is performed with the Motion package for Linux. In the previous tutorial (magpi.cc/2zbzZ6Y), all the setup and configuration was explained in precise detail, so refer to that when needed. You will be able to do this for information regarding installing Linux Motion, setting permissions to folders, and testing it with a browser. Remote file transfer There are various means with which files can be transferred from the Raspberry Pi to the remote server; SCP, FTP, SFTP, FTPS, to name just a few. If we keep things simple and manage both servers with a single admin, any of these methods are good to use. On the other hand, if we plan to have cameras from various foreign networks and want all the images on 48 November 2017 raspberrypi.org/magpi SET UP AND MONITOR A HYDROPONIC GARDEN the same remote server, that takes more work. To do that, we can create FTP accounts for each Raspberry Pi monitoring a remote garden. Then, each Pi will authenticate and upload the file to its own account. In the case of multiple machines, each unit will need its own user name and password and the file will be transferred with the curl command. That’s about it, because once the server interprets the user name and password, it already knows which folder will receive the file. Since the monitoring is intended to be automated, cron jobs can be used to make sure the command runs at the desired time. In the example crontab file code below, we can see a list of the various means by which the files can go from point A to point B. All cron jobs listed below run each minute. The first three commands send the lastsnap.jpg file. Notice how the first command actually runs a file that has the command, while the others are commands. Before we go too much further, let’s take a look the first command, which is a basic FTP transfer. We can make a file called send.sh and give it executable rights. The rest just takes care of itself. The chmod +x /var/lib/motion/send.sh Tutorial The plug-and-play USB webcam takes pictures and stores them on the Pi command will make the file executable. Meanwhile, the code is included with this tutorial and all you have to change is the FTP host, username, and password. Moving on, let’s take a look at the other methods. */1 * * * * /var/lib/motion/send.sh > / dev/null 2>&1 */1 * * * * /usr/bin/curl --ftp-ssl -T "/var/lib/motion/lastsnap.jpg" -k -u "member@members.growlode.com@growlode. com:MemberPassword" "" For best results, we configure Linux Motion to match the resolution of the webcam Optional moisture sensor – read more about this in The MagPi #62 article *1/ * * * * scp /var/lib/motion/lastsnap. jpg pi@ipaddress:/tmp */1 * * * * scp -r /var/lib/motion pi@ ipaddress:/tmp The last command in our crontab list sends the entire folder, which can pile up as there is a new pic every 100 seconds. The other examples only send the lastsnap.jpg file which continually overwrites the previous one, therefore no files pile up and each user account only stores a few kilobytes. However, while sending the entire directory would be a nice ‘see all’, it may not be practical as you will likely want to remove excess files at some point. Now that we have covered the details regarding how a Raspberry Pi can send images to a remote server, let’s look a little into the remote server itself. Although the remote server could be another Raspberry Pi on a home internet connection, using a web hosting account would be the way to go. raspberrypi.org/magpi FEEDING INTERVALS AND TIMER The pump running on a timer 2-3 times a day makes feeding a breeze and maintenance almost non‑existent. November 2017 49 Tutorial WEBCAM RESOLUTION Linux Motion allows you to match the resolution of the webcam. Thus, more pixels will allow for larger, clearer images; even those taken from indoors. Below The ¼-inch feeder lines are connected to the ½-inch header line with ¼-inch barbed fittings. The other end is connected to a dripper WALKTHROUGH For starters, web hosting is cheap, up and running more than 99.99% of the time, and is configured to work fine even with multiple FTP accounts. If we choose a plan that includes cPanel, life is real easy. When FTP is used with a hosting account, all we have to do is create an FTP user and password. All this is done with a simple GUI. To do this with cPanel, we log in and click ‘FTP Accounts’. After that, we add a user name and password and create the user. The information for the user, such as the host, user name and password, is modified in the send.sh file we created. Those credentials for each user will be specific to each Raspberry Pi that monitors gardens. Another benefit of web hosting is that when we have an issue, technical support is only a phone call away. The downside of using a home web server to be the mother machine is that we must alter router port forwarding settings for receiving files via FTP and server reliability. Hydroponic system setup Last time around, some system feeding and basics were covered. This time, we dive right into a 50-pot setup, which is plenty to feed a small family. To start off, we buy the following list of items: 50 × quad pots 50ft roll of ½-inch poly tubing 100ft roll of ¼-inch poly tubing 20 × 2 gallon-per-hour drippers 550 gallon-per-hour pump 55-gallon reservoir 1 × ¾-inch through-hull fitting 5 × ½-inch PVC elbows 1 × ½-inch PVC end cap 1 × line punch 10 × 8ft lengths of ¾-inch electrical conduit pipe 10 × 18-inch pieces of 1.5-inch schedule 40 PVC 40 × 6-7 inch lengths of 1-inch PVC spacers for each pot, depending on manufacturer 1 × fence post pounder 10 × 3-gallon round nursery pots soilless mix or coco coir 10 × 2 by 6 wood squares 20 × plant stakes 10 × 1-inch PVC Ts The first step is to pound the fence posts 2 ft (61 cm) deep at a spacing of 4 ft (122 cm) centres. We will have two rows of five posts. After that, we cut holes in 2×6 wood and the 3-gallon pots with a 1-inch holesaw or spade bit, and put them over the pipe until they are on the bottom, with the wood being first and the pot second. Then, the 1.5-inch PVC pipe is placed over top of the steel pipe. Keep in mind that mitre saws make perfect cuts for wood and all PVC. Now, it’s time to add the pots. The first quad pot is strung through the pipe until it lands on top of the 1.5-inch PVC pipe. Larger pots may need spacers between each pot. Thus, we put the 6-7 inch spacers made from 1-inch PVC over the pipe until it goes to the bottom of the pot. The spacer fits at a height so the next stacked pot locks with the one below, yet has support from the spacer in the middle section. After the spacer, we add medium to each pot before the next pot is stacked on top. We repeat the process for each pot until the fifth pot on top. Pot #5 will not need a spacer. After repeating this process with each tier, we have a system with pots and medium. Now, we need to set up irrigation. We now take the blue tank and move it to one end between both pipes. We cut a hole near the top of the tank and insert a through-hull fitting with the extended end outside the tank. Then, we connect the pump to ½-inch tubing with a ½-inch PVC elbow at the far end from the pump. 50 November 2017 raspberrypi.org/magpi SET UP AND MONITOR A HYDROPONIC GARDEN Tutorial CRON JOBS Cron jobs allow you to run a command or script at any time and interval you please. send.sh Language >BASH #!/usr/bin/env bash Above Setup showing pipes with bottom pots, PVC supports, pots and medium, and header lines We then attach another piece of ½-inch PVC to the elbow on one end and to the through-hull fitting on the other side. After that, we connect a small 6-inch piece of ½-inch tubing to the through-hull fitting followed by another ½-inch PVC elbow. Then, we add ½-inch hose to the elbow until it reaches the first steel pipe. Now, we add another elbow and run a long line of ½-inch PVC along the top and through 1-inch PVC Ts that are placed on top of each pipe. At the end of the first row, we add another ½-inch poly elbow followed by a single ½-inch poly that runs about 4 ft to the other row. This 4 ft length also has an elbow attached that will point towards the second row of pipes. Then, another long line runs through 1-inch PVC Ts that are placed on the tops of the second row of pipes. At the very end (which is back where the tank is), we add a ½-inch PVC end cap. The header line is done. Finally, two holes are punched in the line above each column and they are filled with ¼-inch barbed fittings that are connected to ¼-inch tubing that runs to the top pot. At the ends of the ¼-inch lines are a dripper. These lines are supported with plant stakes. raspberrypi.org/magpi DOWNLOAD: PASSWORD=MemberPasswordl magpi.cc/2y3W7D2 HOST='' USER='member@members.growlode.com' FILE='lastsnap.jpg' cd /var/lib/motion ftp -n $HOST <<END_SCRIPT quote USER $USER quote PASS $PASSWORD binary put $FILE quit END_SCRIPT exit 0 Enjoy your work WATERING AND FERTILIZING We now have the tools and techniques to build a garden monitor and view the status from anywhere in the whole wide world. Believe it or not, we can now easily make trips out of town and have our daily timer set at the proper feeding intervals, and enjoy that long weekend without wondering about the unknown. Happy remote gardening! Mixing dry fertilizer (always much cheaper than liquid) the night before allows the solution to mix well and raise the water temperature from cold, tap water. Optimal temp is 18°C (65°F) to 27°C (80°F). November 2017 51 Tutorial WALKTHROUGH BINSEN QIAN Binsen Qian is a PhD candidate in Mechanical Engineering at University of California, Davis, and Research Associate at the UC Davis C-STEM Center. magpi.cc/2xEGEa9 Programming with Ch will launch ChIDE, which supports all the programming for your robot Ch Mindstorms Controller will launch an interactive GUI for connecting to and controlling your robots Ch Raspberry Pi will launch a simple GUI to interact with the GPIO pins CONTROLLING LEGO MINDSTORMS ROBOTS WITH A RASPBERRY PI You’ll Need > C-STEMbian OS magpi.cc/ 2p3JUNP > A monitor or display > MINDSTORMS NXT/EV3 robots (up to seven) Discover an alternative and user-friendly platform to control multiple MINDSTORMS robots-touse platform for 4- to 19-year-old students to learn I Computing, Science, Technology, Engineering, and Maths with LEGO MINDSTORMS NXT and EV3 robots.. Software Combining LEGO MINDSTORMS and Raspberry Pi offers the opportunity for creativity in building and programming 52 November 2017friendly environment for computing, robotics, and cyber-physical systems. If your Raspberry Pi is already running Raspbian, you can install the C-STEM software modules individually. All the necessary software, including raspberrypi.org/magpi CONTROLLING LEGO MINDSTORMS ROBOTS group_fourMindstorms.ch /* Control multiple robots simultaneously using the CMindstormsGroup class*/ Tutorial Language >C/C++ DOWNLOAD: magpi.cc/2yaWpbX #include <mindstorms.h> CMindstorms robot1, robot2, robot3, robot4; CMindstormsGroup group; double radius = 1.1; // radius of the wheels (inches) double trackWidth = 4.54; // track width of the robots (inches) Above The Motion Control panel features many options for individual motor control, and displays information about the current positions of each motor C-STEMbian, is available from the C-STEM website (magpi.cc/2p3JUNP), along with instructions to guide you through the installation process, and to help you connect to your Raspberry Pi. Connecting to your MINDSTORMS robot(s). /* add the four robots as members of the group */ group.addRobot(robot1); group.addRobot(robot2); group.addRobot(robot3); group.addRobot(robot4); group.driveDistance(5, radius); // drive robots forward 5 inches group.turnLeft(90, radius, trackWidth); // turn robots left 90 degrees group.driveDistance(10, radius); //drive robots forward 10 inches Controlling your MINDSTORMS robots PROGRAMMING IDEAS AND HELP Open the Learn Mindstorms folder in the Code in Curriculum section of C-STEM Studio to find Ch programs for MINDSTORMS.’s Above The Vehicle Control panel provides options for driving by distance, angle, and time, and can plot the resulting data raspberrypi.org/magpi To program the robots, you need to keep them connected in the controller, then open ChIDE and start programming. You can program up to seven robots, which is hard to do using other platforms. ADVANCED APPLICATIONS Explore the Demos folder (in Code in Curriculum) for additional examples and applications using sensors, Linkbots, and different robot configurations. November 2017 53 Tutorial RASPBERRY PI 101: MATHS ON THE RASPBERRY PI MATHS ON THE RASPBERRY PI Ditch the calculator and get your Raspberry Pi to do your sums You’ll Need > Raspberry Pi > Raspbian our Raspberry Pi is an amazing tool for learning maths and working with mathematical equations. In fact, we’ve stopped using calculators for maths problems, and started using our Raspberry Pi instead; and we think Maths on a Pi it’s a great thing to learn. One of the best ways to understand a maths problem is to program a computer to solve it. And solving maths problems is a great way to practise programming. It’s a win-win! The stock version of Raspbian comes with a calculator app built in: officially it’s GCalculator, but marked as just ‘Calculator’ in the interface. Y Add a customised function to the Calculator using the Functions tab in Preferences 54 November xxxx 2016 2017 Raspbian comes with a powerful calculator with a scientific mode User-defined functions (set in Preferences) are used with the Fun key Calculator is used in Basic and Scientific Mode. In Scientific Mode it also has a handy ‘Fun’ key that can be used to implement user-defined functions. Powerful though Calculator is, a far more versatile option is Python. You can access Python in a Terminal window, or by using one of the Python IDE (integrated development environment) apps. Our current favourite is Thonny, which we’ll use for most of this tutorial. In this guide we’ll look at using Calculator and Python to perform calculations, and graph functions using Matplotlib and NumPy, two popular Python modules. The Matplotlib module provides functions for producing neat figures from Python code You can adjust the style and colour of the chart displayed in the figure Captions and legends can be added to the figure raspberrypi.org/magpi MATHS ON THE RASPBERRY PI Tutorial HOW TO: SOLVE MATHS PROBLEMS WITH YOUR RASPBERRY PI >STEP-01 03 Calculator If all you want to do is run a few sums, then the Calculator app (Menu > Accessories > Calculator) is a good call. Click the buttons with a mouse or use your keys on the keyboard. Under View you’ll see three options: Basic Mode, Scientific Mode, and Paper Mode (a text entry mode that is useful for keeping track of previous calculations). 01 >STEP-02 values in the calculator, such as 0.1, 0.01, 0.001. Click Fun and choose the f(x) function to work out the result. Functions One neat trick with the Calculator app is the Fun key. This enables you to apply functions to numbers. There are three functions included by default. The first, abs(x)=sqrt(x^2), returns the positive value for any number. Enter 2 and press the +/- key to set it to negative. Now click Fun and choose abs(x)=sqrt(x^2) to convert it to positive. 02 >STEP-04 Switch to Python While Calculator is a great app, it offers no real advantage over a good scientific calculator. Python, on the other hand, is a powerful programming language with a huge amount of maths support built in. You can quickly access Python in interactive mode from the Terminal app: just enter python3 to switch to interactive mode for Python 3. 04 >STEP-03 Create functions You can create functions using Edit > Preferences and choosing the Functions tab. Suppose you’re being asked to find the limit of sin(x)/x as x approaches 0. Rather than working out sin(x)/x for each number, you can create a function. Enter ‘f’ in the Name field, ‘x’ in the Variable field, and sin(x)/x in the Expression field. Click Add and Close to create the function. Now enter raspberrypi.org/magpi xxxxx 2016 November 2017 55 Tutorial RASPBERRY PI 101: MATHS ON THE RASPBERRY PI 05 >STEP-05 Enter calculations It’s possible to enter calculations directly into the Python interactive shell. If you enter ‘2 + 2’ then you will get the answer, ‘4’. In the interactive shell you don’t need to pass calculations through the print() function (although you do when scripting a program). >STEP-06 Operator precedence 06 One thing that may well trip you up is operator precedence. If you enter 2 + 2 * 4 on many basic calculators, you’ll get 16. Enter the same sum in Python (or many scientific calculators) and you’ll get 10. This is because Python performs multiplication before addition. So it works out 2 * 4 = 8; then 2 + 8 = 10. It does this according to PEMDAS rules (see the ‘Order of operations’ box, page 59). >STEP-07 Parentheses To take control of your operations, you need to include parentheses around the items you want to work on first. To add our 2 + 2 together, then multiply that sum by four, we’d write: (2 + 2) * 4 07 Parentheses have the highest order of operation in any equation, overriding everything else. You can nest parentheses inside equations, adjusting which parts are worked on first. All of these give different results: 2 + 2 * 2 ** 2 = 10 (2 + 2) * 2 ** 2 = 16 2 + (2 * 2) ** 2 = 18 ((2 + 2) * 2) ** 2 = 64 08 Experiment with parentheses until you get the hang of it. For more details on order of operations, visit this TutorialsPoint page: magpi.cc/2hMl7IC. >STEP-08 Integer vs float Numbers in Python are not all equal. The number 1 is not the same as the number 1.0. Even though they have the same value, they are a different type. The number 1 (without a decimal point) is an integer; the number 1.0 is a float. If you’re using Python 3, then most of the time this doesn’t matter. But if you’re using regular Python 2 then it does, because in Python 2 these two sums return different results. 56 November xxxx 2016 2017 raspberrypi.org/magpi MATHS ON THE RASPBERRY PI f.py 9 / 2 = 4 9.0 / 2 = 4.5 import math 9 / 2.0 = 4.5 def f(x): return math.sin(x)/x What gives? In Python 2, an integer is a whole number and dividing 9 / 2 returns an integer (a whole number). And rather than round up the .5 at the end, it’s simply truncated (removed), leaving you with 4. If you divide a float by an integer (or an integer by a float) then Python 2 automatically returns a float, giving you the precise answer. In Python 3, though, things are a little more sensible. Python 3 returns a float for all equations that contain a division symbol. Tutorial Language >PYTHON DOWNLOAD: magpi.cc/ MathsPython values = [0.1, 0.01, 0.001, 0.0001] for val in values: print(f(val)) sine_function.py import matplotlib.pyplot as plt import numpy as np 9 / 2 = 4.5 You can see this in Python using the type() function: def f(x): return np.sin(x)/x type(2 + 2) # returns <class 'int'> x = np.arange(-15.0, 15.0, 0.1) type(2 / 2) # returns <class float> plt.plot(x, f(x)) plt.show() 09 multiple_vs_exponent.py import matplotlib.pyplot as plt import numpy as np >STEP-09 Storing numbers Another advantage Python has over many calculators is the ability to quickly store numbers as variables. These can then be reused in your calculations. For example, there’s approximately 3.28 feet in a meter, or 39.37 inches. metres_to_feet = 3.28 metres_to_inches = 39.37 5 * metres_to_feet = 16.4 x = np.arange(-10, 10, 1) plt.plot(x, x * 2, 'r^') plt.plot(x, x ** 2, 'bo') plt.show() sine_cosine.py import matplotlib.pyplot as plt import numpy as np def f(x): return np.sin(x)/x 5 * metres_to_inches = 196.85 You can even store your variables and answers as other variables: def g(x): return np.cos(x) x = np.arange(-15.0, 15.0, 0.1) size_in_metres = 5 size_in_feet = size_in_metres * metres_to_feet size_in_feet raspberrypi.org/magpi plt.plot(x, f(x), 'r', label="sin(x)/x") plt.plot(x, g(x), 'b', label="cos(x)") plt.legend() plt.show() xxxxx 2016 November 2017 57 Tutorial RASPBERRY PI 101: MATHS ON THE RASPBERRY PI 10 >STEP-10 The math module To expand Python beyond the basic arithmetic operators, you use the math module. This provides instant access to constants, like pi and e (the base of natural logarithms, approximately 2.718). It also offers a range of built-in functions such as sine, cosine, and absolute. See the ‘Useful math functions’ box on page 61 for some of the most common, or the Python Numeric and Mathematical Modules documentation for a full list (magpi.cc/2xhtRsx). Gain access to all these using an import statement. Then use math and dot notation to access the function: 11 import math math.sqrt(256) # returns 16.0 …and you’ll get the square root of 256, which is 16 (it returns as a float so you actually get 16.0). >STEP-11 Creating functions Another fundamental aspect of Python is that you can create functions to perform conversions. Creating functions is a stock feature in all programming languages, but it really comes into its own when you’re working with mathematical functions. Take our earlier function (from Calculator) where we tried to find the limit of sin(x)/x as x approaches 0. This function would typically be described as. f(x) = sin(x)/x We’re going to open Thonny now (Programming > Thonny Python IDE). We can easily create a function in Python like this: def f(x): 12 return sin(x)/x Then you can call the function with values, such as f(0.1) and f(0.01) to get the results. Or you could write a whole program to output a range. Enter the code from f.py. >STEP-12 Matplotlib Another advantage of working in Python is the ability to create graphs with two popular modules: NumPy and Matplotlib. NumPy is installed by default, but Matplotlib needs installing. Make sure your Raspberry Pi is connected to the internet. Open Terminal and enter the following: sudo apt-get install -y python3-matplotlib 58 November xxxx 2016 2017 raspberrypi.org/magpi MATHS ON THE RASPBERRY PI Tutorial ORDER OF OPERATIONS 14 Equations in Python work are calculated in strict order of operations, known as PEMDAS. Operators on the top of this list are calculated before ones on the bottom. () Parentheses ** Exponentiation * Multiplication / Division + Addition – Subtraction >STEP-13 Using plt and np Return to Thonny and create a new file. Start with the following code: plt.plot([1, 2, 4, 8]) import matplotlib.pyplot as plt plt.show() import numpy as np Both np and plt are fairly standard abbreviations, and you’ll find them commonly used in Matplotlib tutorials, so it’s best to use them consistently. 13 Look at the graph and you’ll see that the first value (1) is at position 0 on the x line (the horizontal line). The 2 is at position 1, the 4 at position 3. These match the index number of the list. Click the X icon to close the window. >STEP-15 Set values manually It is possible to set the x and y (horizontal and vertical) values manually. 15 >STEP-14 Create a plot Creating a plot with plt couldn’t be easier. You pass a list of values to a plot() function, then use a show() function to open a window displaying them... raspberrypi.org/magpi xxxxx 2016 November 2017 59 Tutorial RASPBERRY PI 101: MATHS ON THE RASPBERRY PI 16 x = [1, 2, 3, 4] y = [1, 2, 4, 8] plt.plot(x, y) plt.show() Now the x values (on the bottom of the graph) are numbered 1 to 4. They could be any numbers you like, such as 1, 4, 8, 12. But the amount of items in both the x and y lists must match when setting the values manually. >STEP-16 Run a function 17 It’s rare that you pass values manually to a plot. What’s more likely is you’ll use NumPy’s arange function to create a range of numbers. The function looks like this: x = np.arange(-15.0, 15.0, 0.1) We pass three arguments into np.arange(). A start value, and end value, and a step. Our x-axis is going to run from -15 to 15 in increments of 0.1. >STEP-17 Run the code We then pass the x values to a function and plot the y values using our function, using this line of code: plt.plot(x, f(x)) 18 The full code for this can be seen in the listing sine_function.py. Notice that we’ve replaced math.sin() with np.sin(). It performs the same function. Run the code and you’ll see a rather lovely sine wave in Terminal. >STEP-18 Multiple plots It’s possible to chart more than one line in a Pyplot chart. Do this using more than one plt.plot() function. When using more than one plot, it’s often handy to set different colours. You do this using a two-letter marker after the co-ordinate values. The first letter is for the colour, and the second is for the style of line. So ro would indicate red circles, and b^ indicates blue triangles. A complete list of markers can be found on the Matplotlib website (magpi.cc/2hQBwvC). You can use a hyphen to indicate the default line, such as g- for a green line, or just use the letter on its own. The code in multiply_vs_exponent.py demonstrates this. 60 November xxxx 2016 2017 raspberrypi.org/magpi MATHS ON THE RASPBERRY PI Tutorial >STEP-19 19 I am legend It’s also a good idea to create a legend when putting together charts. Add the label tag to the plt.plot() function with some corresponding text, such as this: plt.plot(x, np.cos(x), label="cos(x)") Then use the legend() function to add the legend to the plot (before you use the show() function). plt.legend() In sine_cosine.py we have created a nice graph that compares sin(x)/x and cos(x). This code adds labels to the legend, and adjusts the colour of the lines. >STEP-20 Interact You can interact with your graphs using the icons on the bottom. Use the Zoom icon and draw a marquee around an area of the plot to zoom in on it. Then use the Back and Forward icons to move between the full view and the zoomed one. Hover the mouse over areas of the graph to view the co-ordinate values at that point. Finally, you can save the figure as a PNG using the ‘Save As’ icon. USEFUL MATH FUNCTIONS > abs() for absolute value > divmod() to find a quotient and remainder simultaneously > pow() to raise a number to a certain power > round() to round a number to a certain decimal point > sum() to calculate the sum of the items in an iterable data type 20 raspberrypi.org/magpi xxxxx 2016 November 2017 61 YOUR QUESTIONS ANSWERED FREQUENTLY ASKED QUESTIONS NEED A PROBLEM SOLVED? Email magpi@raspberrypi.org or find us on raspberrypi.org/forums to feature in a future issue. Your technical hardware and software problems solved… USING RASPBERRY PI FOR HOME AUTOMATION WHAT IS HOME AUTOMATION? An automatic home Imagine if your house reacted to you and your life. Turning lights on as you walk into the room. Drawing the curtains when it gets dark. Setting the house alarm when you leave. Simple things that a computer can handle with the right timing and triggers. The benefits As well as being a cool party piece and making you feel like you live on the USS Enterprise, it’s useful for people with disabilities. In the latter case it’s known as assistive domotics and is focused more on safety; however, this does create crossover in functionality. Better control With the advent of more powerful voice assistants, home automation also allows for easier control of your house. Using voice commands to play music or turn on your TV is very Star Trek and thanks to Google Home and Amazon Echo devices, it’s very easy to set up now. HOW DOES THE RASPBERRY PI WORK IN HOME AUTOMATION? Control unit Home automation devices Products that are designed for home automation generally run on certain standards which easily connect to the Pi, such as the Phillips Hue range of lights. These can be controlled on their own or hooked up to your Pi using automation software. WHAT RESOURCES ARE THERE FOR RASPBERRY PI HOME AUTOMATION? Documentation and instructions Software like openHAB has plenty of documentation on how to connect up devices with itself. Many home automation products come with relevant instructions as well, so you’ll be able to follow along to them to get started. Project guides You’ll find plenty of inspiration and even step-bystep guides from other makers online, such as this one on Instructables: magpi.cc/2yJXRTf. There are lots of others as well – from some using hands-free automation, all the way down to using control panels in your house to interact with everything. Community As always, the Raspberry Pi forums are a great place to go if you want to get some help with something specific. Use the search function to see if your issue has been covered before, but otherwise you can ask a question and usually get a great answer: raspberrypi.org/forums. The Raspberry Pi won’t be able to directly interact with all your appliances and such in the same way you can control LEDs with GPIO Zero in Python, but you’ll be able to connect it to specially made connected products like wireless light bulbs and plug adapters. Using home automation software, you can then arrange for the Pi to control them all. Control software Control software such as openHAB (openHAB.org) runs off the Raspberry Pi and is accessible via a browser. You then program the behaviour of individual devices from the web interface, allowing you to modify and optimise from wherever you have access to a network. 62 November 2017 raspberrypi.org/magpi YOUR QUESTIONS ANSWERED FROM THE RASPBERRY PI FAQ RASPBERRYPI.ORG/HELP WHAT DO I GET WHEN I BUY ONE? You get the Raspberry Pi board itself. A power supply and SD card are not included, but can be purchased at the same time from most places that sell the Raspberry Pi. You can also purchase preloaded microSD cards; we recommend buying these from us or our licensed distributors rather than from third parties on eBay, as our software is updated regularly and cards sold by third parties can quickly become outdated. CAN I BUY A RASPBERRY PI KIT? Raspberry Pi resellers produce some fantastic bundles for people who would rather get everything they need from a single source. In 2016, we put together our own Raspberry Pi Official Starter Kit. The kit is available to order online in the UK from our partners element14 (magpi.cc/2cCT8pk) and RS Components (magpi.cc/2nrY33i), priced at £99+VAT, and from distributors and resellers around the world. WHY IS THE PRICE IN US DOLLARS? YOU ARE A UK COMPANY! The components we buy are priced in dollars, and we negotiate manufacturing in dollars. Because currency markets are so volatile, we price the final board in dollars as well so we don’t have to keep changing the price. IS THERE A BUY-ONE-GIVE-ONE PROGRAMME? Not at the current time. We may implement a programme of this sort one day, but the scale of an undertaking like this is something our small team isn’t equipped to handle. You can, of course, simply buy an extra Raspberry Pi to donate to the person or organisation of your choice. READ US ANYWHERE Subscribe from £2.29 £26.99 or Magazine Available now for smartphones & tablets rolling subscription full year subscription SAVE 45% with an annual subscription Download it today – it’s free! Get all 30 legacy issues free Instant downloads every month Fast rendering performance Live links & interactivity raspberrypi.org/magpi November 2017 63 Feature JUNIOR PI PROJECTS Raspberry Pi projects that inspire kids, teens, and young adults to become digital makers T he Raspberry Pi was created to boost interest in computer science, and to inspire kids to create stuff with the digital tools around them. It’s important for your kids to make stuff: to go behind tapping app icons and learn code; and then to start computing and digital making. And teaching them to make will help them no end in life. We all have to start somewhere, and in this feature we’re going to explore some projects for kids and teens; projects designed to encourage the next generation of makers. This feature is about moving kids from playing games, to coding in Scratch, and mucking around with hardware. Plus all of the amazing events, resources, and equipment you can use to instil a love of the digital in your kids. Making is fun, and that’s also why it’s important. So don’t just let your kids sit around playing games; help them to make their own games and projects using hardware they understand. 66 November 2017 raspberrypi.org/magpi JUNIOR PI PROJECTS FLAPPY PARROT Make a version of this mobile arcade favourite 68 SLUG! SNAKE ON SENSE HAT 70 Create the classic game, Snake, using the LED lights on a Sense HAT Feature MAKING MATTERS Digital making inspires young people to learn hands-on learning and tinkering skills. As makers and hackers, we naturally think this is a good thing, but it’s not just about feeling good. Kids who learn to tinker around with stuff get a deeper understanding of how something works. Makers have a deeper understanding of what objects in the modern world are, and their purpose and limitations. We think it’s vital that kids grow up to make stuff, and not just consume it. 72 BUILD A ROBOT BUGGY Take your making to the next level with a code-controlled robot raspberrypi.org/magpi November 2017 67 Feature FLAPPY PARROT YOU’LL NEED > Raspberry Pi > Raspbian > Scratch 2.0 LANGUAGE >SCRATCH FILE: FlappyParrot.sb2 DOWNLOAD: magpi.cc/ 2gbaNJO ‘Choose sprite from library’, select Parrot, and click OK. Right-click on the Parrot sprite and choose Info. Change the name of your sprite to Flappy. Click on Shrink and click on the Parrot 15 times to shrink it down to size. Now give little Flappy the following script: Make your own frenetic arcade game ou may bristle at the thought of your kids wasting time on video games, but it turns out they are a great way to sneakily introduce kids to coding techniques. It’s known as ‘stealth education’, and Raspberry Pi comes with the greatest stealth education kit of all built in: Scratch. With Scratch, kids can develop their own video games and interactive animations. In this project, we’ll make our own version of the highly popular mobile game Flappy Bird. The project requires Scratch 2.0, which is in the latest version of Raspbian. Y Flappy Bird was a huge hit; it’s also a very simple game to program, with just up and down movement of the bird and a single button interaction. Our program here uses a keyboard input, but you could easily use Scratch 2.0 with the GPIO pins to hook the game up to a physical button. >STEP-01 Meet Flappy From the Raspbian Menu, select Programming > Scratch 2 and start a new Scratch project. Delete the cat by right-clicking it and selecting Delete. Click the ‘Choose backdrop from library’ icon and select desert. Click OK. Now click >STEP-02 Make Flappy fly Next, we want Flappy to flap upwards when you press the SPACE bar. Flappy must respond every time we press SPACE; we also use a variable, flaps, to count the times it has been pressed, so Flappy will respond to further presses during the animation loop. Add the following two scripts: The pipes are randomly generated and move from right to left The Flappy Bird moves up and down Press the SPACE bar to flap and try to navigate through the gaps in the pipes 68 November 2017 raspberrypi.org/magpi JUNIOR PI PROJECTS Feature >STEP-03 Add the pipes Now, we’ll add some obstacles for Flappy to fly through. First, click on the ‘Paint new sprite’ button and name the costume ‘pipe’. Click on the ‘Convert to vector’ button. Click Rectangle and click on the ‘Filled rectangle’ button. Click and drag two boxes, one from the top middle and one from the bottom middle, as shown below. You can shade your pipes by clicking on the ‘Color a shape’ button and click on the ‘Horizontal gradient’ button. Choose two shades of the same colour, one for the foreground and one for the background. When you click to fill the shapes, the colours will fade between your chosen shades. Rename the sprite Pipe. >STEP-05 Detect collision with the pipes To make the game a challenge, the player needs to guide Flappy through the gaps without touching the pipes or the edges of the screen. Now we’ll add some blocks to detect if Flappy hits something. Click on the Pipe sprite and add these scripts: JOIN A CLUB >STEP-04 Make the pipes move Next we’ll use some blocks to make the pipes move and arrange them randomly to provide an obstacle course for Flappy. >STEP-06 Getting your kids into a coding club is the best way to spark a love of hacking and making with code. Code Club UK is a nationwide network of volunteers and educators who run free coding clubs for young people aged 9–13 (codeclub.org.uk). If you’re outside the UK, take a look at codeclubworld.org. CoderDojo (coderdojo.com) is also a network of free, volunteer-led, community-based programming clubs for young people aged 7 to 17. Add scoring Finally, the player should score a point every time Flappy makes it through a pipe. Let’s add that next. Check your code for both the Flappy sprite and Pipe sprite against the full code listing (top of page). Click the green flag to play a game of Flappy Parrot. Good luck! raspberrypi.org/magpi SCRATCH ESSENTIALS Created by the boffins at MIT, Scratch enables children and adults without any prior knowledge to start programming within minutes. In the Scratch Essentials book, we help you get started and guide you stepby-step through the process of creating all sorts of projects: games, animations, quizzes, electronics circuits, and more. November 2017 69 Feature SLUG! SNAKE ON SENSE HAT YOU’LL NEED > Raspberry Pi > A Sense HAT magpi.cc/ 1TGGUt5 > Sense HAT emulator Create the classic game, Snake, using the LED lights on a Sense HAT ow that you’ve got your kids creating games in Scratch, it’s time to introduce them to Python. There are lots of games recreated in Python, and we have a whole book called Make Games with Python (magpi.cc/2h2m0vh) which you can download for free. This code hooks up Python to the amazing Sense HAT hardware to create a fun and frantic version of the classic game Snake. Guide the slug around the screen to let N The Sense HAT Emulator lets you test out the program on your Raspberry Pi 70 November 2017 The snake (in our game it’s a slug) is made up of three white dots on the Sense HAT LED display. The red dots are food for the slug to eat her eat vegetables, watch her grow, and increase your score. Don’t let her bite into herself, though, or it’s game over! >STEP-01 Sense HAT or simulation Attach the Sense HAT to your Raspberry Pi and connect it to a television and keyboard as normal. You will program the Raspberry Pi directly using the keyboard and screen, but then play the game using the Sense HAT joystick and The slug is controlled using the Joystick buttons in the Sense HAT Emulator, or the joystick on the physical Sense HAT hardware LED display. If you don’t have a Sense HAT, don’t worry: you can still play the game using the Sense HAT Emulator built into Raspbian. >STEP-02 Enter the code Open Thonny (Menu > Programming > Thonny Python IDE) and choose File > Save. Enter slug.py as the File name and click Save. Now carefully enter the code from slug.py into the editor window. >STEP-03 Test the code Click the green Run button to test out the code. The Sense HAT emulator should open with the slug moving from left to right. Use the buttons to control the code. Close the emulator window and click the red Interrupt button to stop the program running. >STEP-04 Run the code Now, in the first line, change sense_emu to sense_hat. It should read like this: from sense_hat import SenseHat Click Run again and the slug game will run on the Sense HAT itself. You can now control the game using the joystick on the Sense HAT. Above The Sense HAT is a fun piece of hardware for the Raspberry Pi that is packed with sensors along with a joystick and LED display. It’s an ideal introduction for kids to physical computing raspberrypi.org/magpi JUNIOR PI PROJECTS slug. from sense_hat import SenseHat from time import sleep from random import randint Feature LANGUAGE 061. 062. 063. 064. 065. 066. # Did I die? if next in slug: dead = True >PYTHON FILE: slug.py DOWNLOAD: # Add this pixel at the magpi.cc/ end of the slug list 2zguynp sense = SenseHat() slug.append(next) 067. 068. # Variables --------------------------# Set the new pixel to the slug's colour 069. slug = [[2,4], [3,4], [4,4]] sense.set_pixel(next[0], next[1], white) 070. white = (255, 255, 255) 071. blank = (0, 0, 0) if next in vegetables: 072. red = (255, 0, 0) vegetables.remove(next) 073. direction = "right" score += 1 074. vegetables = [] 075. score = 0 if score % 5 == 0: 076. pause = 0.5 remove = False 077. dead = False pause = pause * 0.8 078. 079. # Functions --------------------------if remove == True: 080. def draw_slug(): # Set the first pixel in the slug list to blank 081. for segment in slug: sense.set_pixel(first[0], first[1], blank) 082. sense.set_pixel(segment[0], segment[1], white) 083. # Remove the first pixel from the list 084. def move(): slug.remove(first) 085. global score, pause, dead 086. remove = True 087. 088. def joystick_moved(event): # Find the last and first items in the slug list global direction 089. last = slug[-1] direction = event.direction 090. first = slug[0] 091. next = list(last) # Create a copy of the last item 092. def make_veg(): new = slug[0] 093. # Find the next pixel in the direction the slug is while new in slug: 094. currently moving x = randint(0, 7) 095. if direction == "right": y = randint(0, 7) 096. new = [x, y] 097. # Move along the column sense.set_pixel(x, y, red) 098. if last[0] + 1 == 8: vegetables.append(new) 099. next[0] = 0 100. else: 101. # Main program -----------------------next[0] = last[0] + 1 102. sense.clear() 103. draw_slug() elif direction == "left": 104. 105. sense.stick.direction_any = joystick_moved if last[0] - 1 == -1: 106. next[0] = 7 107. while not dead: else: move() 108. next[0] = last[0] - 1 sleep(pause) 109. 110. elif direction == "down": # Have a 20% chance of making a veggie if there 111. aren't many about if last[1] + 1 == 8: if len(vegetables) < 3 and randint(1, 5) > 4: 112. next[1] = 0 make_veg() 113. else: 114. next[1] = last[1] + 1 115. sense.show_message( str(score) ) elif direction == "up": if last[1] - 1 == -1: next[1] = 7 else: next[1] = last[1] - 1 raspberrypi.org/magpi November 2017 71 Feature BUILD A ROBOT BUGGY Take your making to the next level with a code-controlled robot YOU’LL NEED > Raspberry Pi > Motor controller board > 2 × DC motors > A 6 V AA battery pack > 2 × Wheels > Ball caster (or suitable alternative) > Plastic container > Blu Tack or similar 72 nce you’ve made games with your kids, it’s a great idea to move them to a pure hardware project. One of the best around is a robot kit. You can build a robot buggy that you can program to move around using simple Python commands. The components in this project are all included in the CamJam EduKit 3, which you can purchase from The Pi Hut for just £18 (magpi.cc/2yfsXAN). Or you can pick up all the parts separately. O >STEP-01 Set up the motor control unit Take your motor controller board and, using a small screwdriver, loosen the screws in each of the three terminal blocks. The battery November 2017 Terminal blocks pack must be connected so that the red wire goes into port labelled VIN. The black wire goes into the port labelled GND. Make sure the battery pack is turned off when you do this. The motors can be connected to their terminal blocks any way around. Then tighten the screws again. >STEP-02 Attach the motor control unit The kind of motor controller board used in this project can sit directly on the Raspberry Pi GPIO header pins, and uses GPIO 7, 8, 9, and 10. With the motors and battery connected and the Pi switched off, you can place the board over the GPIO pins as shown above. powered up, you can test that the motors are both working. With your motor controller board and motors wired up, you can use a little bit of Python to control the motors. Open Thonny by clicking on Menu > Programming > Thonny Python IDE. Save your file as motor_test.py and add the following code: >STEP-03 from gpiozero import Motor motor_1 = Motor(7, 8) Once you have assembled the hardware and your Raspberry Pi is Now you can use the following commands to drive your motors: Test the motors raspberrypi.org/magpi JUNIOR PI PROJECTS robot.py LANGUAGE from gpiozero import Robot robot = Robot(left = (7, 8), right = (9, 10)) while True: robot.forward() sleep(3) robot.stop() robot.right() sleep(1) robot.stop() FILE: >PYTHON DOWNLOAD: magpi.cc/ 2zviWPw MEARM PI magpi.cc/2y7E5xq This robot arm includes a HAT with twin on-board joysticks, so you have everything you need in one kit. Manual control using the joysticks is great fun, but programming it is ultimately more rewarding. If you want to control both motors simultaneously, you can use the Robot class, as we will do here. Test the robot It is important to know which is your left motor and which is your right motor. You also need to know which way they are driving to go forward, and which way they are driving to go backwards. Choose either of the motors. Use a marker pen to label it ‘right’ and draw an arrow on it to indicate which way is forward. Label the other motor ‘left’ and draw an arrow on it pointing in the same direction as your first one. >STEP-05 Motor control Enter and run the code from robot.py. If one of the motors runs backwards, you’ll need to swap around the black and yellow wires for that robot on the motor control unit (switch everything off first). THREE ROBOTS robot.py motor_1.forward() motor_1.backward() motor_1.stop() >STEP-04 Feature If your left and right are mixed up you can swap wires on the motor control unit or change GPIO values in the robot variable: robot = Robot(right = (7, 8), left = (9, 10)) >STEP-06 Assemble the robot There is no right way to build your robot chassis. The motors are held in place with a little Blu Tack. With the wheels in place, a ball caster can be screwed to the container to act as a third wheel. You can power your Raspberry Pi using a power brick. At this stage, you’re probably going to want to connect to the Raspberry Pi remotely. You can do this via SSH or VNC (see Remote-control your Raspberry Pi, magpi.cc/2iqniNO). GOPIGO 3 magpi.cc/2vsYrzQ GoPiGo is one of the most impressive robot kits available for the Raspberry Pi, and especially useful for teachers. The two motors have encoders built in, measuring the precise rotation of the wheels. MONSTERBORG piborg.org/monsterborg This heavy-duty racing robot stars in Formula Pi, a series of robotic racing events around the UK. It can be set up as an RC racer thanks to its chunky wheels and four 300 rpm motors. But kids also learn programming skills with the robot following coloured lines on racetracks. raspberrypi.org/magpi November 2017 73 Review MONSTERBORG Maker Says A beast of a kit designed to be taken off road or driven autonomously PiBorg MONSTERBORG Off-road robot stomps onto Raspberry Pi in style. Lucy Hattersley reviews the rough, gruff, and tough MonsterBorg e see many robots here at MagPi Towers: some are highly educational, others are fun hackable toys; a few have industrial aspirations; but the MonsterBorg is in its own league. With its massive 105 mm wheels, sturdy 3 mm aluminium chassis, and four stonkingly powerful 300 rpm motors, it’s a beast. The MonsterBorg mocks educational robots, smirks at toy rovers and tears off around the off-road track. As you might have guessed, we had a lot of fun testing out the MonsterBorg. You can control it with a wireless gamepad, use a web interface (along with an optional Camera Module for a spy-cam), or you can program MonsterBorg to run autonomously. At its heart is the equally extreme-sounding ThunderBorg motor controller. This is a powerful new 5 amp dual motor controller for the Raspberry Pi. It runs between W Related GOPIGO3 STARTER KIT The refined, precise, and thoughtful GoPiGo3 is almost the polar opposite of the MonsterBorg. It's a completely different experience for around the same price. £199 / $199 magpi.cc/2vsYrzQ 74 November 2017 7 V and 35 V, and more boards can be plugged in to handle up to 200 motors if you want to go all ‘Jeremy Clarkson’ on your robots. The MonsterBorg kit hooks a single ThunderBorg up to four 300 rpm Zhengke 37 mm motors (pre-soldered), one for each of the chunky wheels. It needs ten AA batteries for three hours of runtime and you can run it around the garden, on the track, or around the park. All of this is held together on a 3 mm thick aluminium chassis that sits in the middle of the wide tyres (so it can keep rolling if flipped over). The build quality of the MonsterBorg mightily impressed us. Every part fits together neatly and precisely, and the components are all high quality. It feels capable of taking a few hard knocks. You need to bring your own Raspberry Pi to the party. It supports Pi 3, Pi 2, B+ or Pi Zero W devices, raspberrypi.org/magpi MONSTERBORG Review piborg.org £200 / $261 although we think it’s best to use a Pi 3 or Pi Zero W as they have builtin wireless networking (there’s not much space for dongles). You also need to add your own microSD card and an optional (but highly recommended) Pi Camera Module, which makes the web UI option PiBorg has created software installation instructions (magpi.cc/2xtYMlh) and a photo build guide (magpi.cc/2xu9fNI). We found the whole build process simple and straightforward. With the software installed, you can control MonsterBorg You can control MonsterBorg by joystick, via a web interface, or create a canned sequence possible... All of which does push the price up a bit if you don’t have plenty of spares. Putting together the MonsterBorg took around an hour and, thanks to its chunky wheels, sturdy frame, and whopper motors, it’s a fun build. We found the nest of wires the only real sticking point: it took us a while to get them all tucked inside the kit. It’s also nigh-on impossible to reach the USB sockets or microSD card once you’ve set up the robot. So make sure you set up the Raspberry Pi for SSH or VNC before assembling the kit. It’s also a good idea to fix the Raspberry Pi IP address on your router so it doesn’t lose track of it. raspberrypi.org/magpi by joystick, via a web interface, or create a canned sequence. Perhaps more interesting is the Self Drive mode where the MonsterBorg follows a single coloured track. This is the technique used in Formula Pi events (formulapi.com), and the MonsterBorg is now the Formula Pi standard robot. This integration with Formula Pi shouldn’t be underestimated. Far too often when you build a robot, the question is ‘what to do with it?’. With MonsterBorg you have an answer: set it up for racing meets. It lacks all the finesse and precision of another robot we love, the GoPiGo3, with its built-in encoders. Mind you: the MonsterBorg has got its 300 rpm motors and they put a wide smile on our face. So it’s six of one and half a dozen of the other. MonsterBorg is one of the few Raspberry Pi robots that encourages you to take it outside and play. This, along with the Pi Camera Module and web-based UI functionality, makes for a go-getting outdoor rover. An approach that we feel could be far more interesting to budding roboticists than the school lab environment that many other robots find themselves trapped in. MonsterBorg is an utterly unpretentious robot that’s unrepentantly good fun. Don’t be fooled by its rough and ready approach: this is a wellengineered piece of kit with some clever software and a good team behind it. Last word It's rough and tumble but it's fun to assemble, easy to get running and packs a lot of power. We loved the MonsterBorg and could happily spend all day playing with it. It's equally at home on the race track and in the park, and is the perfect blend of RC-style racing with robotic intelligence. November 2017 75 Review PIJUICE Maker Says A portable project platform for every Raspberry Pi PiSupply PIJUICE Use your Pi anywhere with this smart portable power solution ou, Y Related LIPO SHIM Formerly known as the Zero LiPo, this little shim can be soldered to the Pi’s GPIO pins and hooked up to a LiPO battery back and charger (not supplied). £10 / $13 magpi.cc/2xyhCYH 76 November 2017iter. raspberrypi.org/magpi PIJUICE Review pijuice.com From £25 / $33 SOLAR POWER PiSupply also sells a Solar kit (£65/$86) which comprises a PiJuice and a specially made 6 W solar panel to charge it out in the field. The latter folds out of a soft case, with a pull-out flap that can be used to hold its twin mini panels at an angle. You’ll probably need bright direct sunlight to provide a good level of current (about 1 amp at most) – ours was weak when we tried it out on a grey autumn day – but it’s a nice option. We were also supplied with a 40 W What’s my level? version (with six mini panels) which should provide a greater current output and, with twin USB ports and a barrel jack, could be used to charge several devices at once. in the GUI config options, to turn a shutdown Pi back on at a specific time or even charge level. Another interesting option is the watchdog timer that monitors a software ‘heartbeat’ and, if it’s A much neater solution than most portable power methods – no messy wiring here raspberrypi.org/magpi. Last word As well as an all-in-one portable power solution that’s far neater than the alternatives, the PiJuice offers advanced power management features with an impressive number of settings and custom options for maximum versatility. Three userdefinable push buttons and a built-in real-time clock are a major bonus. November 2017 77 Review 128×64 OLED BONNET magpi.cc/2xzuC3h £24 / $32 Maker Says A compact display, with buttons and a joystick Adafruit 128×64 OLED BONNET A high-contrast mini OLED display, complete with controls ooking for a low-power yet bright mini display for your Pi project? Adafruit’s latest OLED screen could well fit the bill. An OLED (organic lightemitting diode) display offers high contrast combined with a low power draw, since it doesn’t require a backlight. While numerous OLED screens are available, including a range from Adafruit itself, most require you to wire them up manually to the Raspberry Pi (or whatever device you’re using). The Pi Zerosized OLED Bonnet takes the hassle out of connection: pre-assembled with a female header, it simply slots onto the Pi’s GPIO pins. Available from Pimoroni in the UK, the OLED Bonnet is the big sibling of the 128×32 PiOLED (magpi.cc/2xAq7po), doubling the latter’s screen area while adding a mini joystick (four-way plus L Related SCROLL PHAT HD Packing 17×7 white pixels, with full PWM brightness control, this display is ideal for scrolling text messages. £12 / $16 magpi.cc/2wShYcf 78 November 2017 central push function) and two buttons. This would make it ideal for use as a mini menu system in, for example, a music player. While the screen is monochrome – white on black – and obviously too low-res to use as a main Pi display, its high contrast enables it to show text with great clarity. Any standard TTF font can be used, and one of the Python examples downloaded after cloning the relevant GitHub repo is an oldschool sine-wave scrolling text demo. Basic images, which may be converted to bitmaps and resized via PIL, can also be displayed. Unlike an e-ink screen, the OLED Bonnet is even able to handle basic animations. While the frame rate is rather sluggish by default, it can be speeded up to about 15 fps by raising the I2C core baud rate to 1 MHz in the Raspberry Pi’s /boot/config.txt file. As well as two GPIO pins for I2C communication with the Pi, the OLED Bonnet uses seven others for joystick and button inputs. That still leaves plenty of GPIO pins available for use in projects, although due to the full-size female header, you’ll need to break them out using something like a Pico HAT Hacker. Last word With its high contrast and clarity, the OLED Bonnet is ideal as a mini status display or – taking advantage of the joystick and buttons – menu system. The screen’s low power draw (around 40 mA on average) is also an advantage for portable projects using battery power. raspberrypi.org/magpi STATUS BOARD Review magpi.cc/2zfbbLq £6 / $8 Maker Says Monitor all of the things! Pi Hut STATUS BOARD Keep an eye on projects with this dry-wipe marker HAT he Status Board from Pi Hut is one of the most fundamentally simple ideas we’ve seen. It has five dry-wipe strips sitting next to controllable LEDs. A smaller (and slightly cheaper) Status Zero board has just three strips. T Related PAPIRUS ZERO Add an e-paper display to your Raspberry Pi and use it to display a status message indefinitely, without using any electricity. £26 / $35 magpi.cc/2goftfw raspberrypi.org/magpi (magpi.cc/2ysqzqm). Simply import the StatusBoard method from GPIO Zero and then create a StatusBoard object (here called sb) to control. from gpiozero import StatusBoard sb = StatusBoard() (magpi.cc/ 2ysWw1U) along with a whole bunch of code examples, including a London Tube Line status board and a Donald Trump news alert. Last word It’s incredibly basic, but the Status Board has charm and is very easy to use. It’s a good device for learning about various online data service APIs and how to respond to data points with a board. November 2017 79 Review BOOKS RASPBERRY PI BESTSELLERS DESIGNING FOR DATA The Internet of Things generates unprecedented levels of data: learn how to handle more... USAGE-DRIVEN DATABASE DESIGN Author: George Tillmann Publisher: Apress Price: £27.99 ISBN: 978-1484227213 magpi.cc/2x14taj A framework that combines the static logical data model with the dynamic flow of the process model for a practical solution across different database management systems. DESIGNING DATAINTENSIVE APPLICATIONS Author: Martin Kleppmann Publisher: O’Reilly Price: £35.99 ISBN: 978-1449373320 magpi.cc/2x1rNoc If you’ve got a lot of data, it’s time to choose between the trade‑offs in consistency and availability. Kleppmann brings practical experience and useful theory to his explanations. EFFECTIVE SQL Authors: John L Viescas, Douglas J Steele, Ben G Clothier Publisher: Addison-Wesley Price: £35.99 ISBN: 978-0134579061 magpi.cc/2x1Jns5 There’s plenty of mileage left in RDBMS (and N1QL shows that SQL will live into the NoSQL age). Effective SQL will fill in gaps in your SQL problem-solving knowledge. 80 November 2017 THE MANGA GUIDE TO MICROPROCESSORS Authors: M ichio Shibuya, Takashi Tonagi, Office Sawa Publisher: No Starch Price: £19.99 ISBN: 978-1593278175 magpi.cc/2x14laP You may have been wondering how the processor inside your computer works, but were you looking for a guide in manga format? Surprisingly, framing the explanations around cartoons and a slightly contrived story involving two Japanese school students – a computer genius and a shogi (Japanese chess) prodigy – works very well. The narrative framework supports a well-ordered and worked through set of explanations, which should enlighten both techies and intellectually curious non-coders. Starting with simple explanations – like arithmetic operations versus FUNCTIONAL PROGRAMMING: A PRAGPUB ANTHOLOGY Author: Michael Swaine Publisher: Pragmatic Bookshelf Price: £38.50 ISBN: 978-1680502336 magpi.cc/2x1s7n1 Here’s an idea for trying to explain functional programming (FP). Take several articles on FP by different writers from 100 issues of PragPub magazine, each covering different languages and approaches to FP. Add in a short interview with Rich Hickey (creator of Clojure), and build towards more advanced concepts. This should give readers a broad appreciation of FP, and an idea of which language to choose for a more involved exploration. After explaining why FP has recently become so important (spoiler: immutable data makes concurrent programs easier to reason about), Scala - which logic operations, and the gates and Boolean logic that make up the latter – Shibuya and his team show the parts of a relatively simple CPU, what they do, and how they do it. The relatively matter-of-fact technical explanations enabled by the story ensure that everything from bitwise operations to variations on flip-flop circuits can be absorbed by the reader. Even the circuit architecture of the TI 74S181 microcontroller is not too frightening. By the end, the reader will have a real appreciation of opcodes, the stack, memory addresses, branch instructions, status flags, and everything else that makes a set of zeroes and ones move through tracks of silicon in such useful ways. Recommended! Score bridges object orientation and FP - makes a gentle introduction, before the Clojure section shows how programming changes when data and code are interchangeable. Elixir, bringing Ruby’s winning style to Erlang’s Beam VM, provides a gentle introduction to pattern matching (which returns later), functions, and concurrency. Haskell brings functional thinking, with data and data types foremost. Swift is the surprise guest here, with some strongly functional features. These five languages are then used for ‘going deeper’ into functional thinking (plus a surprise appearance by Lua). By combining articles from several PragPub authors, many concepts get a good airing. While the approach is not always cohesive, the overall effect is fairly enlightening. Score raspberrypi.org/magpi BOOKS LEARN PYTHON 3 THE HARD WAY Author: Zed A Shaw Publisher: Addison-Wesley Price: £21.99 ISBN: 978-0134692883 magpi.cc/2x153ov Zed Shaw is a nononsense professor, who knows where the student needs to go, where she is now, and how to guide her along the path to learning. The ‘hard way’ of the title is typing in the examples (copying and pasting won’t fix programming into your brain or muscles). The parallel is with scales and arpeggios repeated often while learning a musical instrument: running the programs, and finding and fixing your mistakes along the way. Not everyone will learn best this way, but many (if not most) people can finally learn programming THE DATA SCIENCE HANDBOOK Author: Field Cady Publisher: Wiley Price: £48.50 ISBN: 978-1119092940 magpi.cc/2x168N8 We all know that the world needs more data scientists – and it’s a very lucrative career – but the breadth of skills required is daunting: strong maths, in particular (but not limited to) statistics; programming skills; domain knowledge for various businesses; data wrangling; and presentation. But a meaningful introduction is possible, even in 400 pages, given a clarity of view of the data science field, and the problems tackled by bringing code to big messy data sets. That mess of data is a ubiquitous problem for data scientists. After encouraging the reader to first raspberrypi.org/magpi over the course of Shaw’s 52 exercises and accompanying study drills. Along the way there are pauses to review what’s been learned so far. Much of the coverage is of the expected (and necessary) topics, but chapter 23’s deep look at character encoding, and non-Latin alphabets, is one example of Shaw going above and beyond the expected content. Although you need discipline to stay the course and stick to the study drill, wings will be stretched by the later sections. Give it a go – and if you really don’t like it, pass it on to someone else and get yourself a copy of Head First Python – but give Learn Python 3 The Hard Way a good try first. Score Review ESSENTIAL READING: NETWORK SECURITY They’re out to get you! Don’t stick your head in the sand – learn the attacks and defences. Network Security Assessment Author: Chris McNab Publisher: O’Reilly Price: £39.99 ISBN: 978-1491910955 magpi.cc/2x1kY69 An update of the O’Reilly classic, with a comprehensive treatment of most of the threats you should be worrying about. Hacking the Hacker Author: Roger A Grimes Publisher: Wiley Price: £20.99 ISBN: 978-1119396215 magpi.cc/2x1dJuR Get a different insight into security through short ethical hacker bios, and profiles of various attack techniques. Fascinating. Penetration Testing Essentials frame the problem by asking the right questions – and negotiate a clear idea of what ‘done’ might look like – Cady gives a set of questions to ask about the data, and techniques for dealing with it. The language roundup favours Python and its libraries. Pandas – with DataFrame and Series – is quickly introduced, followed by visualisation. A good chunk of machine learning, and a nicely relevant chapter on presentation, round off the first section. Then it’s time to tackle specialised but necessary knowledge including data encoding, unsupervised learning, NLP, probability, and even a look at performance. This is a well-rounded introduction that will leave you ready to start tackling real data science problems. Score Author: Sean-Philip Oriyano Publisher: Sybex Price: £42.50 ISBN: 978-1119235309 magpi.cc/2x26KSA Learn the tools for attacking your own network – broad coverage, but beginner-friendly. Incident Management for Operations Authors: Rob Schnepp, Ron Vidal, Chris Hawley Publisher: O’Reilly Price: £27.99 ISBN: 978-1491917626 magpi.cc/2x1FHqi Built on Jesse Robbins’s adaptation of firefighter techniques for managing emergency incidents – essential preparation for unplanned interruptions. Network Forensics Author: Ric Messier Publisher: Wiley Price: £50.00 ISBN: 978-1119328285 magpi.cc/2x1sQo8 A hands-on guide to investigating network breaches that will give you all the theory you need, too. November 2017 81 Community INTERVIEW NOTAGRAMA INTERVIEW This unique music reader that uses the Raspberry Pi and a camera is the creation of Daniel Marcial. We talk to him about his project he subject of a developing crowdfunding campaign, Notagrama caught our eye last month as a really interesting way of teaching music on the Raspberry Pi in a way very different to Sonic Pi. We reached out to creator Daniel Marcial to chat about it. T Below The Pi and Camera Module make up the majority of the tech behind the Notagrama project What is Notagrama? The Notagrama is an educational product consisting of a large sheet with two staves, chips in the form of musical symbols, and a computer capable of reproducing the melody formed by the chips. It works with machine vision technology: it has a camera placed above the sheet with which the computer determines the position and shape of the chips to constitute a melody and reproduce it by the speakers. The Notagrama can be used to practise reading and writing scores, composing melodies, imparting music classes, or to have fun playing with musical notes. It is a project that allows interaction with musical symbols in a tangible and innovative way. What’s your music background? I studied piano for six years and I’ve been playing since I was nine years old. I have also taken courses on music Daniel Marcial Occupatiuon: Teacher, musician production, mixing, harmony, and singing. I like playing the piano and composing music with Ableton Live. How did the idea come about? When I was at university, I made a project with machine vision technology: a score system for a real pool game. I liked the machine vision concept, so I wanted to build a music application with it. First I made sequencers and sliders with chips and illustrations, and afterwards I replaced circular chips with music symbols. That’s how Notagrama started. 82 November 2017 raspberrypi.org/magpi NOTAGRAMA Community Above The ‘chips’ are notes you can place on the sheet. These are read by the Pi Why use the Raspberry Pi? I like Raspberry Pi because it’s very accessible and cheap. The most important thing for me is the large amount of information What are your hopes for Notagrama? I want to see a Notagrama in music classes around the world. I would like to know that I have Notagrama allows interaction with musical symbols in a tangible and innovative way on the web about it. I built the Notagrama prototype with my first Pi, a Raspberry Pi 3. Have you ever used Sonic Pi? Yes, I have used it. I like it because it’s a very different way to compose. I have composed music in the traditional way, but when I discovered Sonic Pi I found a new way to do it. It’s very funny to listen your code! raspberrypi.org/magpi contributed to the world’s music student community. Anything else you want to add? I want to invite you to follow my social networks – if there are some educators interested in collaborating on my project, we can talk! (facebook.com/danielmarcial22, youtube.com/danielmarcial22, Instagram: danielmarcial22) FOLLOW DANIEL Want to check out Daniel’s work and maybe collaborate with him? You can follow him on social media and YouTube under his handle danielmarcial22. November 2017 83 Community FEATURE THE MONTH IN RASPBERRY PI Everything else that happened this month in the world of Raspberry Pi FRIGHTFULLY GOOD PI PROJECTS THESE SPOOKY HALLOWEEN PROJECTS ARE ABS-GHOUL-UTELY TERRIFIC e didn’t bring you a Halloween feature last month, breaking our recent streak of doing them. Fear not, though: we’ve been on the lookout for the scariest and most inventive Raspberry Pi Halloween projects from the community. Feast your eyes on these terrifying treats. W THE POPLAWSKIS’ HOLIDAY FRIGHTS magpi.cc/2yMfIse Control the Halloween decorations on the Poplawkis’ lawn. There’s a camera recording the whole thing, and you can control one decoration for a minute at a time for 10¢. Keep an eye on it during actual Halloween night to scare the plastic masks off unsuspecting trick-or-treaters. HAUNTED JACK-IN-THE-BOX magpi.cc/2yMcogZ This automated jack-in-the-box uses a camera to detect if someone is around. If you turn up in front of it, surprise! Pop goes the weasel and also about three years off your life. Put it in an inconspicuous part of your house to scare the bejeesus out of friends and children. POSSESSED PORTRAIT HALLOWEEN MAGIC MIRROR magpi.cc/2yMfQrI The picture for this project doesn’t really do it justice, so take a quick look at the video: magpi.cc/2yMgAgu. It’s a very effective and scary project that uses a little illusion and a motion sensor to make you think the painting is moving. And attacking. magpi.cc/2yKRn6c One of the first traditional magic mirror projects we saw had some timed functions such as showing a scary face during Halloween. This one takes it a step further by making the mirror actually look like a normal mirror… until a phantom appears. 84 November 2017 raspberrypi.org/magpi THIS MONTH IN PI Community SAVE THE PLANET WITH P.A.’S COMPETITION PA Consulting’s 2018 competition is now open – win £1000 for your school or college ant to save the planet with a Raspberry Pi and earn £1000 for your school in the process? Then the PA Consulting Raspberry Pi competition for 2018 may be just what you’re looking for... These PA Raspberry Pi competitions have been going on for five years now, with 2017’s teams being tasked with creating projects that would help those with disabilities. There were some amazing entries, such as the junior school winners who invented a system to help deaf-blind people know when someone is at the door. “The new theme is sustainability.” PA announced. “We’re challenging you to use the Raspberry Pi to invent something that will help save the planet.” W Be a Planeteer the energy created by every kick. Or a scanner that helps us cut food waste. Or a bin that automatically recycles paper. Let your imagination run wild and see what inventions you can come up with. We know from previous years that you’ll come up with some great ideas and we’re looking forward to seeing them.” The rules There are three categories for the competition, separated by age group: > Primary School Award: academic years 4-6 > Secondary School Award: academic years 7-11 > Sixth Form & College Award: academic years 12-13 What exactly is sustainability in this context? PA further explains: “The main threats to our planet centre around energy use, food production and scarcer resources. So we’re interested in inventions that could help meet those challenges. Maybe a football that stores Each category winner gets £1000 for their school or college, and the first 100 entrants get a free Raspberry Pi starter kit. The competition is open to all schools and colleges in the UK and ends on Monday 5 March 2018. You can register here: magpi.cc/2zcyFRg 2017 WINNERS Here are the winning projects from last year PRIMARY SCHOOL AWARD A door entry system paired with a wearable device that helps deafblind people identify visitors to their residence. raspberrypi.org/magpi SECONDARY SCHOOL AWARD SIXTH FORM & COLLEGE AWARD A monitoring tool for carers of elderly people to address the risks of unattended falls. A learning game designed to assist and support those with attentiondeficit disorders and dyslexia. November 2017 85 Community HELP RASPBERRY PI CELEBRATE ITS BIRTHDAY! The Raspberry Pi Foundation wants to put on a global celebration for its sixth birthday – here’s how you can help! or co‑ordinating Raspberry Jams all over the world to take place over the Raspberry Jam Big Birthday Weekend, 3–4 March 2018. F, and we’ll also be sending out party kits to registered Jams. 86 November 2017 Get involved If you’re keen to start a new Jam, there’s no need to wait until March – why not get up and running now? Then you’ll be an expert by the time the Raspberry Jam Big Birthday Weekend comes around. Visit rpf.io/jam for more information, and submit your event to the map when you’re ready. Once your Jam is up and running, register it for the birthday party: rpf.io/bdayjamform. If you don’t fancy organising a Jam for our Big Birthday Weekend, but would still like to celebrate with us, keep an eye on our website for an update early next year. We’ll publish a full list of Jams participating in the festivities so you can find one near you. NEED HELP STARTING A JAM? First of all, check out the Raspberry Jam page to read all about Jams, and take a look at our recent blog post explaining the support that we offer: rpf.io/jam. If there’s no Jam near you yet, the Raspberry Jam Big Birthday Weekend is the perfect opportunity to start one yourself! If you’d like some help getting your Jam off the ground, we’ve produced a free Raspberry Jam Guidebook full of advice gathered from the amazing people who run Jams in the UK. Download it from magpi.cc/2q9DHfQ. If you have more queries, email: jam@raspberrypi.org. raspberrypi.org/magpi Community KICKSTART THIS! The best crowdfunding hits this month for you to check out… LORANGA kck.st/2hAfVaA A special board for IoT, this add-on allows the Pi to easily connect to the LoRa IoT network. It uses mobile network data to connect to the internet, which allows for long-range and low-cost communication. It’s completely open source (it even has open hardware) and at the time of writing it’s very close to its goal, so take a look if you want to extend your IoT. BEST OF THE REST Here are some other great things we saw this month magpi.cc/2hI5XRf GAMING CALCULATOR While we obviously don’t condone ignoring your teacher to play games, this calculator hack with a Pi and RetroPie is pretty genius. magpi.cc/2hIp2CJ VHS PI I’M BACK kck.st/2xSyvRi A ‘second chance’ for your old analogue camera, I’m Back is a special product that transforms cameras that take 35mm film into a digital camera thanks a Raspberry Pi Zero. This means you can use the lenses and other great equipment for your old camera while still making digital photos. There’s a more advanced version as well that uses proprietary hardware if you’re more inclined. raspberrypi.org/magpi We love a bit of retro upcycling and weird Pi cases, so we were immediately drawn to this VHS tape that has a Pi inside. There’s access to the SD card on one side, and a USB hub on the other. Lifting up the flap at the front exposes the I/O ports as well. It’s a lovely and fun build. magpi.cc/2hJ5D4I BRAILLEBOX Accessibility in tech is something a lot more people should be familiar with, so it’s cool to see this excellent project that turns text from news feeds into Braille so people with visual impairments can read the news like the rest of us. Lovely. November 2017 87 Community EVENT REPORT NEW YORK WORLD MAKER FAIRE Fun at the faire with makers from around the globe! hen we think of Maker Faires, the first image that pops up is that of people showing off their amazing inventions. It’s usually full of huge fire-breathing dragon vans, electronic sculptures, complicated wooden machinery and the like. That’s only one side of Maker Faires, though – stalls were also showing off medical applications W The kids were keen to see what they could do with code for new tech, hydroponic projects from school students, and even educational tech. That last category is where the Raspberry Pi Foundation’s stall fell, debuting a brand new demo to help ‘plant seeds’ of computing enthusiasm into hundreds of young minds. The Raspberry Pi demo was quite simple. People were presented with three different wooden blocks with a Raspberry Pi, LED, or button attached to them. Nails were connected to the GPIO pins on the Pi and the connectors of the components, and the challenge was to use crocodile clips and Python to get the Pi to interact with the light or button. Activity sheets walked people through it, and while this might seem easy to readers of The MagPi, it was something a lot FAIRE HIGHLIGHTS! Here’s just a small taste of some of the cool stuff we saw 88 CRICKET PI MUGSY KERMIT THE FROG Next to the Raspberry Pi booth, young maker Jieruei Chang showed off his special Pi project that uses voice control to create MIDI backing tracks for violin playing. It’s a cool project and provided a lovely soundtrack to the weekend. A robot coffee maker? Yes please. As long as it grinds the beans fresh and makes sure the water is the perfect temperature before brewing. Also, if it could just then wheel over and hand cups to us every hour, that would be great. We’re not sure if this is Pi-powered but we love it anyway – the ubiquitous leader of The Muppets was cycling around the Faire and enthralling everyone. We especially like the letter blocks he uses to reach the pedals. It’s not easy being green, after all. November 2017 raspberrypi.org/magpi NEW YORK WORLD MAKER FAIRE Local Raspberry Pi Certified Educators gave talks in how to use the Raspberry Pi for learning of kids had never done before. We supervised many young people being wowed at how easy it was to get the LED to blink, or have a eureka moment as they worked out how to go beyond the activity sheet and get the button to control the LED. The booth was surrounded by other Pi projects and stalls, including one for Piper, the laptop you Educators and parents left with aspirations to help teach young people build yourself and then use to learn about physical computing through Minecraft. The area was packed for both days of the Faire, but we managed to break off for a couple of times to explore the rest of what was on offer. Community People of all ages tried out the project at our booth Use of the Raspberry Pi was seen throughout the Faire, whether it was in the block of tables dedicated to medical equipment, or visible on many robots in the corner dedicated to them. Inside the New York Hall of Science, some Pi projects that have previously appeared in the magazine were on show, including the digital film converter. The venue was huge and it took us a couple of days to see it all. As well as cool projects on show, many people were there selling cool and unique items like cardboard pinball machines, PVC pipe dart guns, custom 3D prints, and more. Whether you like the creative or technical side of making, there was something there to have a look at – and that’s before you got to the custom go-kart races and drone flying races. It was a fun event – although hot – and many kids went home inspired, while a lot of educators and parents left with aspirations to help teach young people about digital making. And that’s the primary goal of Raspberry Pi. HISTORIC FLUSHING MEADOWS The site of the World Maker Faire is Flushing Meadows Park in Queens, New York. It’s an important site for lovers of tech as it was also the location of the famous 1964 World’s Fair. The Space Age was taking off, with humankind a few years away from landing on the moon but reaching for it, and a lot of what was on show here reflected that. Walt Disney, a great lover of World’s Fairs, had a big presence here: he debuted his Abraham Lincoln robot (or audio-animatronic) at the Illinois state pavilion in a little show called Great Moments with Mr Lincoln. It was a massive advancement in lifelike robotics, and you can still see an updated version of that show in Disneyland. raspberrypi.org/magpi Image credit: CC-BY-SA-2.0 Anthony Conti and PLCjr November 2017 89 Community COMMUNITY PROFILE COMMUNITY PROFILE PAUL BEECH Creator of the Raspberry Pi logo, maker of things, and Pirate Captain of Pimoroni Paul Beech Category: Pirate Captain Day job: Co-owner of Pimoroni Website: twitter.com/guru pimoroni.com Below Paul is the designer of the official Raspberry Pi logo, using self-taught skills in graphic design to create the winning competition entry aul Beech’s experience with coding can be traced back to early days of typing programs into his brother’s ZX81. This experience thoroughly hooked him onto computing, with the likes of the MSX, C64, Amiga, and Archimedes making appearances in his day-to-day life. From there, he studied briefly at university before teaching himself graphic design in Corel Xara and Adobe Illustrator – something that would play a big part in his early role within the Raspberry Pi community. P Winning design An early Raspberry Pi article by BBC tech journalist Rory CellanJones caught Paul’s interest and directed him toward the upcoming device and the blog entries surrounding its future release. And on 5 August 2011, Raspberry Pi’s Director of Communications, Liz Upton, put out the call for someone to design a logo for the brand. Paul won the competition. “I followed all the news, and when the competition was posted on the blog I went for it,” explains Paul when thinking back to his conception of the now highly recognisable logo. “I struggled with concepts that used the Greek letter π or any kind of actual pi. I knew that a big idea like a computer for $25 needed a logo that was simple and bold and could be photocopied in black and white five times and still be recognised from across a room. As soon as I stopped trying to include the ‘Pi’ bit and just went for ‘Raspberry’, it got a lot easier.” Paul submitted his design idea, along with some supporting material, and despite his confidence in the design, he’s still having issues coming to terms with the fact that he won. “It’s never quite landed.” Sheffield-based Pimoroni are also the UK’s largest Adafruit reseller. As well as being cartoon pirates, of course Paul, Jon, and the Pimoroni team have made waves in the Sheffield industry, consistently ranking high as a major influence within the creative scene 90 November 2017 raspberrypi.org/magpi PAUL BEECH The Picade’s panels are powder-coated in black so the end result feels like a finished, quality product “We want to solve problems we have in a way that’s helpful to a bunch of people. We want everyone to be able to tinker and play and learn” Pirates launch Prior to this step into the community, Paul was already becoming a sound digital maker. Having met Jon Williamson in 2003 at a LAN party, the two instantly clicked and spent their free time tinkering while filling Community Above “We want to solve problems we have in a way that’s helpful to a bunch of people. We want everyone to able to tinker and play and learn” realised that we probably should be those people.” From the success of the Pibow, the pair went on to launch the We brought our web and design and geek thing to the making and tinkering world their days with web and startup work. When the Raspberry Pi came to the retail market in 2012, the pair made their mark by creating the Pibow, a multilayer, laser-cut case for the Raspberry Pi. “After we complained about early cases, we thought someone should do something about it. Eventually we crowdfunding campaign for the Picade, a Raspberry Pi arcade machine kit build, and from there, Pimoroni was born. “We brought our web and design and geek thing to the making and tinkering world and it felt right and good and is the best thing we’ve ever been involved with.” HIGHLIGHT This is a great issue for DIY arcade machines; Picade is a neat build THE COMMUNITY “I like how many new skills I have and that I get to put positivity into the world,” explains Paul when discussing what makes him proud of his role within the Raspberry Pi community, and of others he’s met along the way. “The community is amazing and I’m surrounded by lovely, talented people who know stuff all the time. We support almost 40 people now at Pimoroni; that’s scary and amazing.” raspberrypi.org/magpi November 2017 91 Community EVENTS RASPBERRY JAM EVENT CALENDAR Find out what community-organised, Raspberry Pi-themed events are happening near you… 2 FUSION ESPRIT RASPBERRY JAM Tunis, Tunisia FIND OUT ABOUT JAMS 7 Want a Raspberry Jam in your area? Want to start one? MELBOURNE PI USER GROUP Warranwood, VIC, Australia ben@raspberrypi.org HIGHLIGHTED EVENTS COFFEE, CAKE AND CODING When: Thursday 2 November Where: King Edward VI Sheldon SH MAKERSPACE RASPBERRY JAM When: Sunday 12 November Where: The Boileroom, Heath Academy, Birmingham, UK magpi.cc/2yN1iIF Meetings and workshops aimed at sharing good coding practice in a relaxed and informal setting. Guildford, UK magpi.cc/2yMwbNm This Jam is primarily a show-andtell event where people bring along their projects for others to try out. FUSION ESPRIT RASPBERRY JAM QUANTUM TECHNOLOGY CLUB Tunis, Tunisia magpi.cc/2yLmgYj Want to know more about the Raspberry Pi? Be shown and taught everything you need to know. Ormskirk, UK magpi.cc/2yMptXI Make some electronic circuits and control them with simple code on Raspberry Pi or Arduino. When: Wednesday 8 November Where: Esprit – Night Schools, 92 REGULAR EVENTS November 2017 When: Thursday 16 November Where: Cottage Lane Mission, CORNWALL TECH JAM When: Saturday 11 November Where: Cornwall College, Redruth, UK cornwalltechjam.uk For all ages and abilities. Ask questions and learn about programming in Scratch, Python, Minecraft, and more. TORBAY TECH JAM When: Saturday 11 November Where: Paignton Library and Information Centre, Paignton, UK torbaytechjam.org.uk Torbay Tech Jam is designed to be a fun, informal, and family-friendly event, for all ages and experience levels. raspberrypi.org/magpi EVENTS Community WE’VE HIGHLIGHTED SOME OF THE AREAS IN NEED OF A JAM! CAN YOU HELP OUT? 8 HULL RASPBERRY JAM 1 COFFEE, CAKE AND CODING 4 QUANTUM TECHNOLOGY CLUB 3 SURREY & HAMPSHIRE MAKERSPACE RASPBERRY JAM Hull, UK Birmingham, UK Ormskirk, UK Guildford, UK 6 TORBAY TECH JAM 5 CORNWALL TECH JAM Paignton, UK Redruth, UK MELBOURNE PI USER GROUP When: Tuesday 21 November Where: Melbourne Rudolf Steiner School, Warranwood, VIC, Australia magpi.cc/2mx2y7Y The group’s aim is to bring likeminded people together to talk about how they’re using the Raspberry Pi. HULL RASPBERRY JAM When: Saturday 25 November Where: Hull Central Library, Hull, UK magpi.cc/2hIscGC Get hands-on with digital making activities through workshops and a hackspace area to share projects. raspberrypi.org/magpi RASPBERRY JAM ADVICE FUNDRAISING “We hand out free raffle tickets while we shake the donation tin. Then we pull winning tickets from a box and they win a prize we’ve had donated, like a HAT or something.” Andrew Oakley Cotswold Jam Every Raspberry Jam is entitled to apply for a Jam starter kit, which includes magazine issues, printed worksheets, stickers, flyers, and more. Download the Raspberry Jam Guidebook at magpi.cc/2q9DHfQ. November 2017 93 Community YOUR LETTERS YOUR LETTERS Etcher errors Above Etcher is easy to use, but it does have the odd graphical bug Going headless I recently got a Raspberry Pi Zero W and wanted to use it headlessly and connect it to my WiFi. This way I can then use it via my laptop without having to attach a monitor to it. I’ve installed Raspbian to the SD card, but I’ve run into a bit of a dead-end as I’m unable to set the wireless LAN password without actually connecting it to a monitor. How can I fix this? Prakash If you do have access to a monitor, then the good news is you can do the initial setup from the graphical interface and then use it headlessly from then on. All you need to do is connect to your wireless LAN and then open Raspberry Pi Configuration in Menu > Preferences. Find the Interfaces tab and enable SSH, and then go back to the first tab and change the boot method so that it boots into the command line. This way you save a little power. If you don’t have access to a monitor at all, then all is not lost. First of all, SSH can be very easily activated by dropping an empty file called ssh or ssh.txt into the boot partition of the Raspbian SD card. For the wireless LAN, you can add another file to the boot partition called wpa_supplicant.conf that contains details for your wireless network. This is usually as simple as: network={ ssid="WiFi name" psk="WiFi password" } But you can check the following link for more info on setting up your wireless LAN connection via the command line: magpi.cc/2hQhwW4. 94 November 2017 I have been attempting to burn a copy of the new Raspbian Stretch to my SD card using Etcher. All works well when attempting it from my Linux box, but I have not been successful when running from my Windows 10 box. I have used the same SD card and adapter, as well as downloaded files from Raspberry Pi. On Linux, things work very well all the way through, but I get an error on the verify section when running on my Windows 10 box. I have been running Etcher as ‘administrator’ on my Windows box, but no luck. I am fine burning my personal SD cards on my Linux box, but I am attempting to teach some newbies about the Pi and they only have Windows boxes. I have successfully burnt SD cards for earlier versions of Raspberry, but Stretch won’t work on Windows. Any ideas of what I can do to make things work on Windows? Lee This could be something as simple as the download of the Stretch image being slightly corrupted so it doesn’t pass the MD5 hash test. Re-download the image and see if you get the same issue. However, in our experience, Etcher does this regularly on Windows 10 and yet the SD card still works just fine in the Raspberry Pi. Give it a test in a Pi and see how you get on. English versions of MagPi Mini I’ve been collecting every issue of your magazine for a while now as PDFs. I was just checking your back catalogue to make sure I had every issue and noticed that I didn’t have the PDFs for The MagPi Minis that were released. I went to the page and found downloads for the translated versions; however, I was unable to download an English version from the image of the English cover. How can I get it? Below The translated editions use content from old issues of The MagPi, so don’t worry about missing anything! Tina The translated editions are unfortunately not available in the original English. However, as they use content from previous issues of The MagPi, you’re not missing anything! These versions are for people who perhaps cannot speak English or have difficulty doing so. You can always quickly browse through one and find out which tutorials it uses, though. raspberrypi.org/magpi YOUR LETTERS Learning through games I was reading Matt Richardson’s article ‘Creating to learn’ in the latest MagPi magazine and thought to drop a line. I learned programming over 30 years ago as a teenager when computers (and also gaming) were considered for nerds and seriously uncool. I started on a Tandy TRS-80 model III and learned MS-DOS batch and BASIC (compiler) programming, and wrote software my parents used for their company and also for some other companies. Some software is still in use today. A lot has changed since then. Gaming became cool because of, among others, Nintendo and Sony’s PlayStation. And the Raspberry Pi has made programming cool. Especially the interaction between code, the internet, and real-life components like LED, LCDs, speakers, sensors, motors, robotic parts, etc. makes it interesting for many more people, also young ones. For the last 25 years I didn’t do much programming, except for some maintenance. But the Raspberry Pi (and Arduino) got me interested in building some projects again. I started with this one: DIY arcade cabinet - Raspberry Pi running RetroPie, then Community followed that with a DIY photo booth powered by a Raspberry Pi (inspired by an article in The MagPi). Recently I built an Arduino-powered stereo VU meter and yesterday I built an Arduino date, time, and temperature LED matrix display. Now, getting to the point of this message: I didn’t know anything about programming in Python or C (Arduino Sketch) before these projects. Neither was I interested in it – why should I learn it? However, I needed to write code for the last three projects. So having an idea and being focused on wanting the project to get finished makes you dig into it, do research, learn, make mistakes, fix them, and finish and enjoy the end result. It is very rewarding having turned an idea into reality all by yourself. So hats off to the Raspberry Pi project and the people and companies who encourage us all to create – keep up the good work! Eric Thanks for the kind words, Eric! We’re always happy when people get excited with what they can do with code and a few components, whatever their experience level or age is! Huge kudos on your own projects as well. FROM THE FORUM: RECYCLING MAGPIS I s there a way to pass old copies of the magazine onto a school, or code club? Seems a shame to just bin/recycle them. richard238 We don’t currently have a system for this, but perhaps we should! If you have any old issues of The MagPi you want to give away, drop Rob a line at rob.zwetsloot@raspberrypi.org or tweet @TheMagP1 and we’ll try to see if we can find them a good home where they’d be needed. raspberrypi.org/magpi The Raspberry Pi Forum is a hotbed of conversations and problem-solving for the community. Join in via raspberrypi.org/forums WRITE TO US Have you got something you’d like to say? Get in touch via magpi@raspberrypi.org or on The MagPi section of the forum at: raspberrypi.org/forums November 2017 95 & ROBOT ARM KIT In association with The Flick HAT is an incredible new 3D tracking and gesture board for the Raspberry Pi. One lucky reader will win all the following: Flick Large and Flick Large case Plus! Flick HAT and Flick HAT case M aplin Robot Arm R aspberry Pi 3 Runner-up prizes! Learn how to use the Flick HAT 3D to control a robot arm with hand gestures magpi.cc/2hGAn9Q × Flick HAT and Flick HAT cases 3 5 × Flick HAT Zeros All of these are courtesy of Pi Supply (pi-supply.com). For a chance to win one of these great Flick HAT and Case kits, you just need to go online and enter our competition. You could be one of the lucky winners! Enter now at magpi.cc/WinNov17 Terms & Conditions Competition opens on 25 October and closes on 30 November 2017. Prize is offered to participants worldwide aged 13 or over, except employees of the Raspberry Pi Foundation, the prize supplier, their families or friends. Winners will be notified by email no more than 30 days after the competition closes. By entering the competition, the winner consents to any publicity generated from the competition, in print and online. Participants agree to receive occasional newsletters from The MagPi magazine. We don’t like spam: participants’ details will remain strictly confidential and won’t be shared with third parties. Prizes are non-negotiable and no cash alternative will be offered. This promotion is in no way sponsored, endorsed or administered by, or associated with, Instagram or Facebook. raspberrypi.org/magpi November 2017 97 Column THE FINAL WORD MATT RICHARDSON Matt Richardson is the Executive Director of the Raspberry Pi Foundation North America and author of Getting Started with Raspberry Pi. Contact him on Twitter @MattRichardson. GAMING AS A GATEWAY Matt Richardson’s take on how gaming leads to learning s you’ll see from the cover story of this issue of The MagPi, the Raspberry Pi makes a great computer for gaming projects. In fact, I would guess that setting up a Raspberry Pi for retro gaming is one of the most popular ways for people outside of the maker community to use our affordable credit card-sized computer. A whole generation of young computer gamers has grown up into adulthood. And while we’ve come a long way, going from Frogger to Fallout 4, there’s a strong feeling of nostalgia for classic retro games these days. Couple this nostalgia with higher levels of comfort with computer technology among the masses and you can understand why gaming with Raspberry Pi is so popular right now. A GAME PI This presents a great opportunity for our Raspberry Pi community to grow. A person may purchase a Raspberry Pi because they want to play a few games from their childhood. Going through the process of setting up their Raspberry Pi-based game console, that person may well learn a little bit about computers. Maybe they’ll also see all the other possible things they can create with Raspberry Pi. Hopefully the experience will spark the curiosity about how else their Raspberry Pi can be used, not only for entertainment, but also for utility. For the mainstream public, I see gaming with Raspberry Pi as a gateway to all the possibilities that the product, the resources, and the community have to offer. This is nothing new. Gaming and computing have gone hand-in-hand since the early days of computers. And ever since those early days, gaming has been a great motivation for people to learn about computers. Whether you’re setting up a Raspberry Pi for retro gaming, speccing out a high-performance gaming 98 November 2017 tower, or writing code to develop your own game, there’s a lot of ways that an interest in video gaming can lead to more serious learning about technology. I suspect that most of the people who work today as video game developers started with a passion for games as opposed to a passion for the technology alone. I especially admire the work of video game developers because they require more than just technical chops. Creating a video game is a wonderful blend of technology, storytelling, user experience, music, sound effects, character development, art, design, and performance. Video games have a wonderful blend of creativity and technology that I absolutely love. At the Raspberry Pi Foundation, we’re particularly interested in helping young people understand that computers intersect with many different disciplines, subjects, industries, interests, and passions. In other words, they don’t have to be interested in computers themselves in order to use them in a way that is meaningful to them. Empowering youngsters to create their own games is an especially effective way to inspire them to experiment with technology in a way that’s more meaningful to them. Take a look at the learning resources on raspberrypi.org. For good reasons, many of them are centred around creating a game in Scratch or Python. And if you visit a CoderDojo, you’ll find a common rule: “If you didn’t make it, you can’t play it.” It encourages members to dedicate that time to making their own games to play as opposed to playing games they’ve downloaded from the internet. It doesn’t matter if you’re making games or just playing them for fun. Because there are so many ways that gaming can lead to learning about technology or even a creative career path, the potential upside goes far beyond fun. raspberrypi.org/magpi Tutorial ESSENTIALS LEARN | CODE | MAKE OUT NOW IN PRINT ONLY £3.99 from raspberrypi.org/magpi ESSENTIALS raspberrypi.org/magpi From the makers of the official Raspberry Pi magazine GET THEM DIGITALLY: April 2016 99
https://issuu.com/fgbfgbnmtre/docs/28dfvdfv
CC-MAIN-2018-30
refinedweb
31,505
62.07
Please note that there are better answers below. When a picture is taller than it is wide, it means the camera was rotated. Some cameras can detect this and write that info in the picture's EXIF metadata. Some viewers take note of this metadata and display the image appropriately. PIL can read the picture's metadata, but it does not write/copy metadata when you save an Image. Consequently, your smart image viewer will not rotate the image as it did before. Following up on @Ignacio Vazquez-Abrams's comment, you can read the metadata using PIL this way, and rotate if necessary: import ExifTags import Image img = Image.open(filename) print(img._getexif().items()) exif=dict((ExifTags.TAGS[k], v) for k, v in img._getexif().items() if k in ExifTags.TAGS) if not exif['Orientation']: img=img.rotate(90, expand=True) img.thumbnail((1000,1000), Image.ANTIALIAS) img.save(output_fname, "JPEG") But be aware that the above code may not work for all cameras. phatch is a batch photo editor written in Python which can handle/preserve EXIF metadata. You could either use this program to make your thumbnails, or look at its source code to see how to do this in Python. I believe it uses the pyexiv2 to handle the EXIF metadata. pyexiv2 may be able to handle EXIF better than the PIL's ExifTags module. Or to read the EXIF data beforehand and apply the transformation manually. Thanks to both of you for your answers. I'm trying to strip all EXIF data, but then add back the data if it has to be rotated. This is turning into much more of a PITA than I originally assumed it would be. Just a matter of working out the script to do it now. Thanks again! Since you're resizing, you probably don't care, but don't forget that even a simple rotation is sometimes a lossy operation on jpegs. I upvoted the version that handles all 8 orientations. Also, here's a great set of test images github.com/recurser/exif-orientation-examples from Dave Perrett. python - PIL thumbnail is rotating my image? - Stack Overflow rb Image.open(imgFileName) The only mode Image.open() accept is r mode (which is default). See here I have tried it that way, still gives me the same error. How do you download an image and extract Exif data using Python PIL? -... You can try loading the image with the Python Image Lirbary (PIL) and then save it again to a different file. That should remove the meta data. Python: Remove exif info from images - Stack Overflow import Image image_file = open('image_file.jpeg') image = Image.open(image_file) # next 3 lines strip exif data = list(image.getdata()) image_without_exif = Image.new(image.mode, image.size) image_without_exif.putdata(data) image_without_exif.save('image_file_without_exif.jpeg') Python: Remove exif info from images - Stack Overflow For listing files in a directory, os.listdir(directory) will get you a list of files AND subdirectories. files=[os.path.join(directory, f) for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))] #Get only files, not directories for f in files: #open file, do EXIF stuff select directory + extract exif using python - Stack Overflow import pyexiv2 from PIL import Image file_path = '/home/../img/a.JPG' metadata = pyexiv2.ImageMetadata(file_path) metadata.read() thumb = metadata.exif_thumbnail thumb.set_from_file(file_path) thumb.write_to_file('512_' + "a") thumb.erase() metadata.write() Now I open the image using Phatch Image Inspector , I can see the exif data python - Preserve exif data of image with PIL when resize(create thumb... This depends on the image format heavily. For example, if you have a TIFF file, there is no knowing a priori where the EXIF data, if any, is within the file. It could be right after the header and before the first IFD, but this is unlikely. It could be way after the image data. Chances are it's somewhere in the middle. If you want the EXIF information, extract that on the server (cache, maybe) and ship that down packaged up nicely instead of demanding client code do that. Your second paragraph assumes he owns the server storing the images, which might not necessarily be the case :) As for where the EXIF data is located, if I understand this answer correctly, in JPG files the EXIF data will be around the beginning of the file - do you know if this is correct? Yes, I'm wondering the same myself. Most images are in .jpg, so that would be great. APP1 section appears after the APP0 section (if it exists). The APP0 marker can be followed by up to 64K of data by the spec, so you should be prepared to handle that. And there may be multiple APP1 sections. Were it me and I was hell-bent on doing this, I'd build a stream solution where I can cut off image delivery at any point (in this case after I have the EXIF, if any). @plinth How would you build such a stream solution? (ie. the downloading-and-cutting-off-image-delivery-part.) Get EXIF data without downloading whole image - Python - Stack Overflo... You can tell the web server to only send you parts of a file by setting the HTTP range header. See This answer for an example using urllib to partially download a file. So you could download a chunk of e.g. 1000 bytes, check if the exif data is contained in the chunk, and download more if you can't find the exif app1 header or the exif data is incomplete. Thanks for that, but this is dependent on remote compliance with range header, which is not good enough. Need some way of cancelling curl after x bytes or similar, I'm thinking. Get EXIF data without downloading whole image - Python - Stack Overflo... Every time you read() you move the file pointer. If you want to read the same thing repeatedly (why?) then you can use to rewind the file pointer to the beginning of the file. Python reading a .jpg file in binary for beginner - Stack Overflow Developed a simple app in Python but.... the method get_original_metadata() give me always "None" (and i'm sure that the image has Exif, i got this from exif.org/samples.html) Google Appengine Java - Get EXIF data from Image - Stack Overflow Although PIL can read EXIF metadata, it doesn't have the ability to change it and write it back to an image file. A better choice is the pyexiv2 library. With this library it's quite simple flip the photo's orientation. Here's an example: import sys import pyexiv2 image = pyexiv2.Image(sys.argv[1]) image.readMetadata() image['Exif.Image.Orientation'] = 6 image.writeMetadata() Actually, the camera already set the Exif.Image.Orientation tag, I want to write the image in the right Orientation to enable browser to display it even if they cannot understand EXIF information. Anyway, pyexiv2 is the library I needed. As you can see in my code behind. python - How to use PIL to resize and apply rotation EXIF information ... You have to use syntax as metadata['Exif.Image.Copyright'] = pyexiv2.ExifTag('Exif.Image.Copyright', copyrightName) Note: copyrightName value should be string for "Exif.Image.Copyright" import pyexiv2 metadata = pyexiv2.ImageMetadata(image_name) metadata.read() metadata.modified = True metadata.writable = os.access(image_name ,os.W_OK) metadata['Exif.Image.Copyright'] = pyexiv2.ExifTag('Exif.Image.Copyright', 'copyright@youtext') metadata.write() Sign up for our newsletter and get our top new questions delivered to your inbox (see an example). python - Copying and Writing EXIF information from one image to anothe... With pyexiv2 version 0.3, the solution of @user2431382 will not allow to write the EXIF tags to destination_file != source_file. The following version works for me: m1 = pyexiv2.ImageMetadata( source_filename ) m1.read() # modify tags ... # m1['Exif.Image.Key'] = pyexiv2.ExifTag('Exif.Image.Key', 'value') m1.modified = True # not sure what this is good for m2 = pyexiv2.metadata.ImageMetadata( destination_filename ) m2.read() # yes, we need to read the old stuff before we can overwrite it m1.copy( m2 ) m2.write() python - Copying and Writing EXIF information from one image to anothe... I think the title.human_value data is in UTF-8, having already been decoded from the raw UTF-16 bytes of title. In the python shell, running in a terminal window on OSX: >>> # this should be the same as your title.human_value: >>> print ''.join( chr(x) for x in [208, 156, 208, 184, 208, 187, 208, 190, 208, 185, 32, 208, 156, 208, 176, 208, 188, 209, 131, 208, 187, 208, 181, 32, 208, 190, 209, 130, 32, 208, 156, 208, 176, 208, 185, 208, 184, 44, 32, 49, 49, 32, 209, 143, 208, 189, 208, 178, 208, 176, 209, 128, 209, 143, 32, 49, 57, 52, 52, 46]) , 11 1944. Your console may not support Cyrillic characters. You might try setting the font in the Command Prompt to "Lucida Console" -- a more modern vector font is more likely to support it correctly than the historical bitmapped fonts that cmd defaults to. print u'' ?????? , 11 1944. I don't think it's a Python 2 issue (I'm using Python 2.6), I think it's a terminal encoding issue. At the python prompt, try import sys; print sys.stdout.encoding. none Try setting it to 'utf-8' and printing your string again? I'm not sure how my sys encoding gets set... I feel myself helpless. I don't know how to set it. Moreover, some functions, mentioned at the help pages (e.g. sys.getdefaultencoding), are not appearing in my Python! Probably, I should first get some Python experience and then return to this issue. In the meantime, I'm using a workaround: display Unicode strings using PyQt. Python: extract Cyrillic string from EXIF - Stack Overflow ''' Rotate Image ''' import pyexiv2 import wx import cStringIO import os def rotateImage(infile, device): try: # Read Metadata from the image metadata = pyexiv2.metadata.ImageMetadata(infile) metadata.read(); # Let's get the orientation orientation = metadata.__getitem__("Exif.Image.Orientation") orientation = int(str(orientation).split("=")[1][1:-1]) # Extract thumbnail thumb = metadata.exif_thumbnail angle = 0 # Check the orientation field in EXIF and rotate image accordingly if device == "iPhone" or device == "iPad": # Landscape Left : Do nothing if orientation == ORIENTATION_NORMAL: angle = 0 # Portrait Normal : Rotate Right elif orientation == ORIENTATION_LEFT: angle = -90 # Landscape Right : Rotate Right Twice elif orientation == ORIENTATION_DOWN: angle = 180 # Portrait Upside Down : Rotate Left elif orientation == ORIENTATION_RIGHT: angle = 90 # Resetting Exif field to normal print "Resetting exif..." orientation = 1 metadata.__setitem__("Exif.Image.Orientation", orientation) # Rotate if angle != 0: # Just rotating the image based on the angle print "Rotating image..." angle = math.radians(angle) img = wx.Image(infile, wx.BITMAP_TYPE_ANY) img_centre = wx.Point( img.GetWidth()/2, img.GetHeight()/2 ) img = img.Rotate( angle, img_centre, True ) img.SaveFile(infile, wx.BITMAP_TYPE_JPEG) # Create a stream out of the thumbnail and rotate it using wx # Save the rotated image to a temporary file print "Rotating thumbnail..." t = wx.EmptyImage(100, 100) thumbStream = cStringIO.StringIO(thumb.data) t.LoadStream(thumbStream, wx.BITMAP_TYPE_ANY) t_centre = wx.Point( t.GetWidth()/2, t.GetHeight()/2 ) t = t.Rotate( angle, t_centre, True ) t.SaveFile(infile + ".jpg", wx.BITMAP_TYPE_JPEG) thumbStream.close() # Read the rotated thumbnail and put it back in the rotated image thumb.data = open(infile + ".jpg", "rb").read(); # Remove temporary file os.remove(infile + ".jpg") # Write back metadata metadata.write(); except Exception, e: print "Error rotating image... : " + str(e) ios - Rotating an image with orientation specified in EXIF using Pytho... Not entirely sure, as I've never used this module or played with images, for that matter. Can you not just do something like this? I looked at the documentation and it says that metadata.exif_keys is a list. It seems you would only have to check whether or not the list is empty. if metadata.exif_keys: print(metadata.exif_keys) python - Find if an image has EXIF or not - Stack Overflow it is running both on Windows and Ubuntu, and you can get all you need (codec, aspect, fps, bitrate, orientation...). how to get a video file's orientation in Python - Stack Overflow I used Python and the Flickr api. I stripped the metadata/exif from the searching image, and stored it. I then used this information store on the image to build a search query that flickr would search for, finding similar images. This involved taking date and time to limit how many results I got back, and so forth. I purposely made sure any images I wanted to search matches these requirements, along with having some suitable search tags, and an estimated location, specified by the user. The images found were done using Flickr's api to make sure that any image found contained a gps address. Therefore, any suitable/similar images found would have a location that could be compared against the estimated location, provided by the user. (This is a broken down, simple version of the process, without going too deep into how the algorithm works.) Any images found are then put through a comparison process in OpenCV. Naturally, the IM2GPS research paper was of great use to me for this.
https://recalll.co/app/?q=python%20-%20Exif%20reading%20library
CC-MAIN-2019-43
refinedweb
2,199
58.89
sandbox/joubert/libosmesa6-dev_bug_fix Here is almost a copy/paste of the instruction written by Quentin Magdelaine that you can find here to fix off-screen rendering bug using OSMesa after the recent libosmesa update on Debian10.1/19.0.2-1ubuntu1.1~18.04.1 distribution. Instructions. First, remove the new OSmesa library which does not work: sudo apt remove libosmesa6-dev Then download an older version: wget mesa3d.org/archive/mesa-18.2.8.tar.gz Then decompress it (change [username] for yours (ex: toto)): tar -zxvf mesa-18.2.8.tar.gz cd mesa-18.2.8 ./configure --prefix=/home/[username]/local --enable-osmesa \ --with-gallium-drivers=swrast \ --disable-driglx-direct --disable-dri --disable-gbm --disable-egl If it doesn’t find zlib, install zlib1g-dev with: sudo apt install zlib1g-dev Try again. If it still doesn’t work instak pkg-config: sudo apt install pkg-config and try again, it should work. Compile the library: make (This step is quite long.) And install it: make install The library is not installed in the standard path (/usr/lib/), so you need to tell gcc and basilisk about it. First, enter in your terminal: export LD_LIBRARY_PATH=/home/[username]/local/lib:$LD_LIBRARY_PATH and, to not have to do it again as soon as you open a new terminal: echo "export LD_LIBRARY_PATH=/home/[username]/local/lib:$LD_LIBRARY_PATH" >> ~/.bashrc Then in the config file in basilisk/src/, change the line OPENGLIBS = -lfb_osmesa -lGLU -lOSMesa for OPENGLIBS = -L/home/[username]/local/lib -lfb_osmesa -lGLU -lOSMesa And in fb_osmesa.c in basilisk/src/gl/, change the line #include <GL/osmesa.h> for #include </home/[username]/local/include/GL/osmesa.h> You can now compile the libraries provided by basilisk in basilisk/src/gl: make libglutils.a libfb_osmesa.a and the bview-servers in basilisk/src/: make bview-servers You should be able to compile and run successfully all your codes using the standar Makefile of Basilisk. Here is a test of the Bview functionnalities. cp $BASILISK/test/view.c . make view.tst Or if you do not use makefile, you have to use the following compilation line: qcc view.c -lm -L/home/[username]/local/lib/ -L$BASILISK/gl/ -lOSMesa -lglutils -lfb_osmesa -lGLU Note that you may experienced some trouble to play with vlc .mp4 videos generated with this fix. A quick fix to this is to use cvlc.
http://basilisk.fr/sandbox/joubert/libosmesa6-dev_bug_fix
CC-MAIN-2020-24
refinedweb
397
55.34
#include <Semaphore.hpp> A semaphore. In computer science, particularly in operating systems, is then used as a condition to control access to some system resource. A useful way to think of a semaphore as used in the real-world systems Referenced Wediapedia Of course, semaphore is already defined in linux C and MFC in Window. But it is dependent on each operating system, so that cannot be compiled in another OS with those semaphores. There's not a class like semaphore in STL yet. It's the reason why Semaphore is provided. As that reason, if STL supports the semaphore in near future, the Semaphore can be deprecated. Library - Critical Section Definition at line 47 of file Semaphore.hpp. Constructor. Definition at line 78 of file Semaphore.hpp. References capacity(). Set size. Set permitted size of the semaphore. Definition at line 88 of file Semaphore.hpp. Get size. Returns size which means the permitted count of the semaphore Definition at line 104 of file Semaphore.hpp. Referenced by Semaphore(). Get acquired size. Definition at line 112 of file Semaphore.hpp. Acquire admission. Acquires an admission and increases count of admission by 1. If the count is over permitted size, wait until other admissions to be released. Definition at line 128 of file Semaphore.hpp. Referenced by samchon::library::UniqueAcquire::acquire(), and samchon::library::SharedAcquire::acquire(). Try to acquire admission. If admission count is below the permitted size, acquire admission and increase the count by 1 and return true which means succeded to get admission. Else, do not acquire admission and return false which means failed to get admmission. Definition at line 152 of file Semaphore.hpp. Release an admission. Releases an admission what you've acquired. If the admission count was over the limited size, unlock the mutex. Definition at line 174 of file Semaphore.hpp. Referenced by samchon::library::UniqueAcquire::release(), samchon::library::SharedAcquire::release(), samchon::library::SharedAcquire::~SharedAcquire(), and samchon::library::UniqueAcquire::~UniqueAcquire(). The size. Permitted size of the semaphore Definition at line 54 of file Semaphore.hpp. Referenced by capacity(). Acquired count. Definition at line 62 of file Semaphore.hpp. Referenced by acquired(). Locker. Manages lock and unlock of the semaphore Definition at line 70 of file Semaphore.hpp.
http://samchon.github.io/framework/api/cpp/d9/d88/classsamchon_1_1library_1_1Semaphore.html
CC-MAIN-2022-27
refinedweb
372
52.66
Read Part 1 here: How to do Unit Test using NUnit : Part 1 In last post we talked about how to start with Unit Testing using NUnit. In this post I will discuss about following two topics, - Test Setup - Test Teardown You need Test Setup and Test Teardown to remove any dependency between tests. Assume a scenario that - You want to create instance of a particular object before execution of any test - You want to delete a particular file from file system before execution of any test - You want to insert some test data or create some test data before execution of any test etc.. In above stated scenario you may want to create a Test Setup. Test Setup is a piece of code get executed before execution of any test. Other use case could be that you want to perform a particular task after execution of each test. So once test got executed a certain task should get done and we call that Test Teardown. There could be scenario that - You want to destruct an instance after execution of any test - You want to remove test data after execution of any test - You want to delete a file from file system after execution of any test etc. In above scenario you may want to create Test Teardown. Test Teardown is piece of code get executed after execution of any test. In NUnit you can create Test Setup and Test Teardown by using [Setup] and [TearDown] attribute on a function. So Test Setup can be created as following, And you can create Test Teardown as following If there are 5 tests in your test class then these two functions will get executed 5 times. Now let us put our discussion into concrete example. Assume that you are writing Unit Test for a Product class. Product class is defined as following, namespace MyAppToTest { public class Product { double productPrice; public double ProductPrice { get { return productPrice; } set { productPrice = value; } } } } A Unit Test is written to test valid product price as following, [Test] public void IsValidProductPrice() { p.ProductPrice = 100; if (p.ProductPrice > 0) { result = true; } Assert.IsTrue(result, "Product Price is valid"); } You can write Test SetUp and TearDown as following, Product p; bool result; [SetUp] public void TestSetup() { p = new Product(); result = false; } [TearDown] public void TestTearDown() { p = null; result = false; } The above two function will get executed each time before execution of test and after execution of test. In writing Unit Test , Test SetUp and Test TearDown are very handy and useful. I hope you find this post useful. Thanks for reading. 3 thoughts on “Test SetUp and TearDown in Unit Testing using NUnit : Part 2”
https://debugmode.net/2013/06/17/test-setup-and-teardown-in-unit-testing-using-nunit-part-2/
CC-MAIN-2022-05
refinedweb
444
59.64
23 August 2012 17:31 [Source: ICIS news] LONDON (ICIS)--The European Renewable Ethanol Association (ePURE) on Thursday rejected claims that biofuels production has resulted in higher global food prices. “Global grain use for biofuels is miniscule and nowhere near enough to inflate prices significantly. Singling out biofuels for blame for rising food prices is simply reckless and only serves to damage public confidence in good biofuels,” said Rob Vierhout, secretary general of ePURE. According to ePURE, the EU will use an estimated 3m tonnes of corn for ethanol production during 2012, and it says this represents 1% of total EU grain production. ePURE said 4.6m tonnes of wheat will also be used for ethanol production in 2012 and that this represents around 1.5% of total EU grain production. Meanwhile, the EU is using 166.5m tonnes of grain production for animal feed alone, ePURE added. On a global scale, ePURE reasons that world ethanol production accounts for gross 4% of total cereal use, which represents 3% of net global grain use when ethanol animal feed co-products are taken into account. There have been calls from the UN and food organisations in the ?xml:namespace> Furthermore, Dirk Niebel, However, sources from the fuel ethanol industry said that even if blending mandates are waived, oil companies will still continue to blend ethanol with gasoline, as it is the cheapest octane booster available. “ "It is truly unbelievable that, while critics continue to blame biofuels for creating a food crisis, last year
http://www.icis.com/Articles/2012/08/23/9589605/epure-rejects-claims-biofuels-production-causes-higher-food-prices.html
CC-MAIN-2014-10
refinedweb
252
60.85
[Date Index] [Thread Index] [Author Index] Re: Data functions (like ElementData) and physical units - To: mathgroup at smc.vnet.net - Subject: [mg83048] Re: Data functions (like ElementData) and physical units - From: Chris Chiasson <chris.chiasson at gmail.com> - Date: Thu, 8 Nov 2007 06:16:30 -0500 (EST) - References: <fgs95u$56i$1@smc.vnet.net> On Nov 7, 5:56 am, John Jowett <John.M.Jow... at gmail.com> wrote: > I am self-censoring my comments about the overall utility of the data functions (and the physical constants package) for real work. On to your question. The main goal in the design decision to use strings seems to have been to prevent an increase in the number of symbols "crowding" default namespaces. Of course, this does not apply to your case, because the units could have been returned as 1/ Units`Kelvin, for example. The Units package would not even need to be loaded to do that. Therefore, I don't see a good reason to use string units.
http://forums.wolfram.com/mathgroup/archive/2007/Nov/msg00219.html
CC-MAIN-2018-22
refinedweb
169
66.03
import "github.com/mailru/easygo/netpoll" Package netpoll provides a portable interface for network I/O event notification facility. Its API is intended for monitoring multiple file descriptors to see if I/O is possible on any of them. It supports edge-triggered and level-triggered interfaces. To get more info you could look at operating system API documentation of particular netpoll implementations: - epoll on linux; - kqueue on bsd; The Handle function creates netpoll.Desc for further use in Poller's methods: desc, err := netpoll.Handle(conn, netpoll.EventRead | netpoll.EventEdgeTriggered) if err != nil { // handle error } The Poller describes os-dependent network poller: poller, err := netpoll.New(nil) if err != nil { // handle error } // Get netpoll descriptor with EventRead|EventEdgeTriggered. desc := netpoll.Must(netpoll.HandleRead(conn)) poller.Start(desc, func(ev netpoll.Event) { if ev&netpoll.EventReadHup != 0 { poller.Stop(desc) conn.Close() return } _, err := ioutil.ReadAll(conn) if err != nil { // handle error } }) Currently, Poller is implemented only for Linux. epoll.go handle.go handle_unix.go netpoll.go netpoll_epoll.go util.go const ( EPOLLIN = unix.EPOLLIN EPOLLOUT = unix.EPOLLOUT EPOLLRDHUP = unix.EPOLLRDHUP EPOLLPRI = unix.EPOLLPRI EPOLLERR = unix.EPOLLERR EPOLLHUP = unix.EPOLLHUP EPOLLET = unix.EPOLLET EPOLLONESHOT = unix.EPOLLONESHOT ) EpollEvents that are mapped to epoll_event.events possible values. const ( // EventHup is indicates that some side of i/o operations (receive, send or // both) is closed. // Usually (depending on operating system and its version) the EventReadHup // or EventWriteHup are also set int Event value. EventHup Event = 0x10 EventReadHup = 0x20 EventWriteHup = 0x40 EventErr = 0x80 // EventPollerClosed is a special Event value the receipt of which means that the // Poller instance is closed. EventPollerClosed = 0x8000 ) Event values that could be passed to CallbackFn as additional information event. var ( // ErrNotFiler is returned by Handle* functions to indicate that given // net.Conn does not provide access to its file descriptor. ErrNotFiler = fmt.Errorf("could not get file descriptor") // ErrClosed is returned by Poller methods to indicate that instance is // closed and operation could not be processed. ErrClosed = fmt.Errorf("poller instance is closed") // ErrRegistered is returned by Poller Start() method to indicate that // connection with the same underlying file descriptor was already // registered within the poller instance. ErrRegistered = fmt.Errorf("file descriptor is already registered in poller instance") // ErrNotRegistered is returned by Poller Stop() and Resume() methods to // indicate that connection with the same underlying file descriptor was // not registered before within the poller instance. ErrNotRegistered = fmt.Errorf("file descriptor was not registered before in poller instance") ) CallbackFn is a function that will be called on kernel i/o event notification. type Config struct { // OnWaitError will be called from goroutine, waiting for events. OnWaitError func(error) } Config contains options for Poller configuration. Desc is a network connection within netpoll descriptor. It's methods are not goroutine safe. Handle creates new Desc with given conn and event. Returned descriptor could be used as argument to Start(), Resume() and Stop() methods of some Poller implementation. HandleListener returns descriptor for a net.Listener. HandleRead creates read descriptor for further use in Poller methods. It is the same as Handle(conn, EventRead|EventEdgeTriggered). HandleReadOnce creates read descriptor for further use in Poller methods. It is the same as Handle(conn, EventRead|EventOneShot). HandleReadWrite creates read and write descriptor for further use in Poller methods. It is the same as Handle(conn, EventRead|EventWrite|EventEdgeTriggered). HandleWrite creates write descriptor for further use in Poller methods. It is the same as Handle(conn, EventWrite|EventEdgeTriggered). HandleWriteOnce creates write descriptor for further use in Poller methods. It is the same as Handle(conn, EventWrite|EventOneShot). Must is a helper that wraps a call to a function returning (*Desc, error). It panics if the error is non-nil and returns desc if not. It is intended for use in short Desc initializations. NewDesc creates descriptor from custom fd. Close closes underlying file. Epoll represents single epoll instance. func EpollCreate(c *EpollConfig) (*Epoll, error) EpollCreate creates new epoll instance. It starts the wait loop in separate goroutine. func (ep *Epoll) Add(fd int, events EpollEvent, cb func(EpollEvent)) (err error) Add adds fd to epoll set with given events. Callback will be called on each received event from epoll. Note that _EPOLLCLOSED is triggered for every cb when epoll closed. Close stops wait loop and closes all underlying resources. Del removes fd from epoll set. func (ep *Epoll) Mod(fd int, events EpollEvent) (err error) Mod sets to listen events on fd. type EpollConfig struct { // OnWaitError will be called from goroutine, waiting for events. OnWaitError func(error) } EpollConfig contains options for Epoll instance configuration. EpollEvent represents epoll events configuration bit mask. func (evt EpollEvent) String() (str string) String returns a string representation of EpollEvent. Event represents netpoll configuration bit mask. Event values that denote the type of events that caller want to receive. Event values that configure the Poller's behavior. String returns a string representation of Event. type Poller interface { // Start adds desc to the observation list. // // Note that if desc was configured with OneShot event, then poller will // remove it from its observation list. If you will be interested in // receiving events after the callback, call Resume(desc). // // Note that Resume() call directly inside desc's callback could cause // deadlock. // // Note that multiple calls with same desc will produce unexpected // behavior. Start(*Desc, CallbackFn) error // Stop removes desc from the observation list. // // Note that it does not call desc.Close(). Stop(*Desc) error // Resume enables observation of desc. // // It is useful when desc was configured with EventOneShot. // It should be called only after Start(). // // Note that if there no need to observe desc anymore, you should call // Stop() to prevent memory leaks. Resume(*Desc) error } Poller describes an object that implements logic of polling connections for i/o events such as availability of read() or write() operations. New creates new epoll-based Poller instance with given config. Package netpoll imports 7 packages (graph) and is imported by 2 packages. Updated 2018-10-05. Refresh now. Tools for package owners.
https://godoc.org/github.com/mailru/easygo/netpoll
CC-MAIN-2018-51
refinedweb
994
52.56
> : Bye, bearophile On 19-apr-10, at 12:32, bearophile wrote: >>: > that is for C compatibility, D has always defined size_t and ptrdiff_t (without needing to import anything) exactly like that. On 04/19/2010 11:47 AM, Fawzi Mohamed wrote: > no the opposite is safe (pointer -> size_t) but there is no way > size_t->pointer can be safe... Michel Fortin wrote: > So you shouldn't be able to *cast a value to a pointer*. The reverse, > casting a pointer to a value, makes sense in my opinion: On 04/18/2010 02:46 PM, Walter Bright wrote: > *These* are allowed in safe functions. (emphasis mine) I was trying to visualize a point.). >If restrict is used incorrectly, however, undefined behavior can result.< And one of the few ways out of this, while keeping the language safe, is the ownership/lent/etc extensions to the type system, that are cute, but they are not so easy to learn to use and can become a little burden for the D programmer. Another solution is the restrict keyword as in C. In a D program the restrict keyword can be useful only in few numeric kernels, often less than 30 lines of code, that perform tons of computations in few loops. In such loops the knowledge of distinct pointers can be significantly useful to improve the code. In all other parts of the program such keyword is useless or not essential (such loops can even enjoy a harder form or compilation, almost a supercompilation. The programmer can even give an attribute like @hot to this loop/function. GCC too has a 'hot' function attribute, but I think in GCC it's not very useful). I don't know what to think about this. Being D a system language, the language is expected to offer unsafe features too, as this one. So maybe offering restrict, to be used in very limited situations, can be acceptable in D too. In many situations the numerical kernels work over arrays, and D arrays have both a pointer and a length, so it's easy to test if a pointer is inside such interval and if two interval are fully distinct. Such tests can be done in nonrelease mode to give a little more safety to the restrict keyword. Some of such tests can even be kept in release mode if they are outside the heavy loops. Maybe it can be invented something like restrict but more limited, that works on D arrays only. An extension of the D type system that's useful for numerical kernels that work on arrays. Something like: @enforce_restrict(array1, array2, ...) { // numerical kernel that uses the arrays } Inside that enforce the D type system knows they are distinct, it's like a restrict applied to their pointers. I don't know if this can work in practical situations. Maybe there's an acceptable solution to this problem of D2. --------------- I think in C you can't reliably cast a pointer from a type to a different type. I think because the C compiler (and D compiler, I presume) can optimize away some things, making this unsafe/undefined. This conversion is sometimes done using an union, that's a bit safer than the reinterpret cast: union Foo2Bar { int* iptr; double* dptr; } But I think the C standard says that from a union you can't read a field different from the last field you have written, so that too is unsafe: import std.stdio; union U { int i; float f; } void main() { U u; u.i = 10; writeln(u.i); // defined U u; u.f = 10; writeln(u.f); // defined writeln(u.i); // undefined } I think this not because of endianeess problems, but because the compiler can keep values in registers and optimize away the read/write inside the union. D language can state this is defined, making unions a safer way to statically convert ints to floats, or it can follow the C way to make code a little faster. Strict aliasing means that two objects of different types cannot refer to the same location in memory. See also the -fno-strict-aliasing GCC compiler switch, and related matters: >>In C99, it is illegal to create an alias of a different type than the original. This is often refered to as the strict aliasing rule.<< I don't know if D here follows C99 or not. Bye and thank you, bearophile bearophile wrote: >). Array operations address the same as issue as restrict, but are much easier for the compiler. (They don't completely overlap in functionality, but the most important cases are covered by both). AFAIK 'restrict' hasn't been a terribly successful feature in the C world. Don: > (They don't completely overlap in > functionality, but the most important cases are covered by both). I will need to use array ops more to if you are right. > AFAIK 'restrict' hasn't been a terribly successful feature in the C world. I agree. (And I am not sure compilers use it well). Bye, bearophile
http://forum.dlang.org/thread/hq5jdt$q2d$1@digitalmars.com?page=3
CC-MAIN-2013-48
refinedweb
841
71.14
Technical Article ARX Import Restrictions for NetApp Volumes Updated 22-Feb-2012•Originally posted on 22-Feb-2012 by Jim McCarron F5 article news storage techtip Summary Deciding the optimal points to import a customer’s NetApp filer can be challenging. Ideally the ARX should import at the highest point possible on the filer in order to keep the total ARX Managed Volume count low. On a NetApp filer the highest possible point would be the volume level. For various technical reasons, which will be discussed below, importing at the NetApp volume level is restricted to a limited set of configurations and should only be used if all technical requirements are met. Some of these restrictions have been lifted with newer versions of ARX code. For environments where importing at the NetApp volume is not possible, the recommended design involves importing at the individual qtree level which may require additional Managed Volumes and hence a larger ARX configuration. This App Note will cover the various options for Volume vs. qtree level import. NetApp Qtree Overview Some ARX features are bounded by restrictions of certain operations when qtrees are used within NetApp volumes. A qtree is defined as a special subdirectory in a volume that acts as a virtual sub-volume with special attributes, primarily quotas and permissions. Below is an example of a NetApp volume with multiple qtrees. Note that a qtree can only exist at the root path of the volume. Since qtrees are essentially separate file systems that can even store different permissions sets such as UNIX vs. NTFS some operations are simply not possible between qtree boundaries. This is true for any NFS or CIFS client as well as for the ARX. Namespace Design Considerations When sizing a customer environment to determine the number of Managed Volumes needed within the ARX, a determination must be made on the optimal point for the ARX to import the existing file systems. Both the NetApp volume and the qtrees within the volume can be considered possible points of import. Since there is a finite number of Managed Volumes within each ARX system, the namespace design needs to ensure the number of supported Managed Volumes is not exceeded. How Many Managed Volumes are Required? When sizing a customer environment, the total number of ARX Managed Volumes is needed to properly select the right ARX platform. To accomplish this, a determination must be made on the optimal point for the ARX to import the existing file systems. There may be more than one option when picking which locations are best for import into ARX Managed Volumes. A Managed Volume consists of shares which are NFS exports or CIFS shares mapping to a physical file system. A Managed Volume with four shares Since there is a finite number of Managed Volumes per ARX the namespace design needs to ensure the number of supported Managed Volumes is not exceeded. If the total number of Managed Volumes required will exceed the limits of the chosen ARX platform, then an alternate design may be needed, or possibly a larger ARX platform or additional ARX’s will be required. Below is a summarization of the Managed Volume limits per ARX platform, and per Volume Group within the respective platforms. Platform Managed Volumes per ARX ARX-VE (Production) 32 ARX-1500 48 ARX-1500E 96 ARX-2000 192 ARX-2500E 192 ARX-4000 256 If there are CIFS shares or NFS exports nested under the ARX import level they will simply be re-exported/re-shared by the ARX. Below is an example of an ARX design where one ARX Managed Volume will be dedicated per NetApp qtree. Note that they may still be exported from the ARX under the same global server name. Importing at the NetApp Volume Level It is always best to find the highest point within the file system for the ARX to import to reduce the number of ARX Managed Volumes required. There are cases where the highest possible export or share cannot be used. Using a NetApp filer as an example the highest level exports/shares that exist are at the NetApp Volume level. Although importing at the NetApp Volume would be ideal for the ARX because there are fewer volumes than qtrees, it is not always possible. NetApp volumes may contain qtrees, which are file systems unto themselves so importing at the NetApp volume layer may hide certain file system characteristics from the ARX. In general the ARX can only import at the NetApp Volume level if the security style (UNIX/NTFS) of the volume, and all child qtrees within the volume are identical. NetApp MIXED mode security style is not supported by ARX under any circumstances. MIXED mode qtrees or volumes must be converted to NTFS or UNIX and re-permissioned before importing into an ARX Managed Volume. If there is a mix of different security styles within the volume then import must occur at the qtree level to avoid potential conflicts in file system capabilities. Below is a summary of what environments are right for import at the NetApp volume level and which ones are not. Within a NetApp filer, volumes and qtrees may be configured to support different security styles; either NTFS, UNIX, or MIXED. In order for the ARX to import a NetApp Volume that contains qtrees, the volume as well as all child qtrees within the volume must be configured for the same security style. They must be all NTFS or all UNIX, the ARX does not support MIXED mode. Prior to DMOS version 6.1.0 the ARX did not support import at the NetApp Volume level if the volume was accessed in a Multiprotocol manner (CIFS + NFS concurrently). This restriction has now been lifted in DMOS 6.1.0 and later so that the ARX can now import at the Volume level in any case as long as the security styles are consistent within the Volume. Below is an example of NetApp volumes that contain qtrees that are configured for the same security style. As long as DMOS 6.1.0 or later is used, these can now be imported at the NetApp Volume level even if they are accessed using multiprotocol. If the NetApp Volume contains no qtrees currently, and will not in the future, then ARX import at the NetApp Volume level is supported. ARX Import at the NetApp Volume level is not supported if the Volume or any of its child qtrees contain differing security styles. The Volume and its child qtrees must either be all NTFS, or all UNIX. Below is an example of a NetApp volume with both NTFS and UNIX qtree security styles. In this case Volume level import is not possible, so the ARX will be forced to import the individual qtrees or the customer must re-align their volumes so that they have uniform security styles. If the NetApp Volume is exported multiprotocol (NFS and CIFS concurrently) then import at the NetApp Volume level is not supported unless DMOS 6.1.0 or later is used, even if the Volumes and all qtrees are all the same security style. Below is an example of non-supported configurations for volume level import because of multiprotocol with qtrees and the older DMOS versions. Upgrading to DMOS 6.1.0 or later will allow Volume level import in these cases. Other Considerations for Volume Level Import Importing at the NetApp Volume level will also prevent two ARX features from working. The Save-on-Migrate feature, also known as migrate-retain-files, will not work when NetApp Volume level import is performed. ARX Shadow Copy replication is not allowed on any ARX Managed Volume where an import occurred at the NetApp Volume level. These unsupported configurations for NetApp volume level import are depicted below: Other considerations for NetApp Volume level import are quotas, and qtree creation. The ARX will track and report free space based on the level it imports using the proxy user or root to query free space. If there are qtree quotas then the ARX will may not report them correctly. There are free space enhancements in DMOS 6.1.0 that may allow the ARX to report free space more accurately in these environments. Check with your F5 SE for more details. Qtrees will appear as normal directories in the root of the Managed Volume to the ARX. If a new qtree needs to be added after a NetApp volume has been imported it will result in a metadata inconsistency. Qtrees cannot be created by NFS or CIFS clients accessing the NetApp through ARX, they must be created via the NetApp CLI or GUI. This will be analogous to creating a new directory behind the ARX from a client. In order for this new qtree to be visible to clients the ARX metadata must be updated. A manual sync directory must be run to add the new qtree to ARX metadata and then it will be accessible to clients through the ARX. This can be done via the ARX CLI or GUI after the qtree has been added. The qtree must be empty in order for the directory sync to detect and add the new qtree to ARX metadata. How to Reduce Managed Volume Count with Qtree Level Imports If the environment has more file systems than can be handled by the desired ARX platform, then alternate cut-in techniques such as using the ARX’s presentation namespace, aggregating more than one file system per Managed Volume, or possibly larger ARX platforms needs to be explored. Below is an example of merging multiple NetApp file systems (qtrees) into a single ARX Managed Volume to reduce total Managed Volume count on the ARX. In this case four file systems are being merged into a single Managed Volume. Although NetApp was used in this example the same concept applies to any vendors file systems. When merging more than one file system into a single Managed Volume a detailed collision analysis must be performed. This can be done via the no-modify import functionality on the ARX to generate reports of any potential conflicts. Once collisions are understood they can be corrected manually before import, or the ARX can rename offending collisions during import if given permission to do so by the administrator. If there are any common directory names, then they will merge (assuming permissions are the same) as long as the parent directory structure is the same. Clients connecting to this Managed Volume through the ARX will see the aggregated content from all file systems. Below is an example of a client’s view of the merged file systems. If each file system has unique top level directories then the merging will be clean, and no collisions will occur. Clients that connect to the root share or export will end up seeing the aggregated top level directory structure from all the file systems as seen on the left of the diagram below. Clients that map to shares exporting below this level, (or NFS mounting below this level) will not see any merged content as long as the parent directory structure is unique on each file system. This is seen on the right of the diagram below. Some installations have chosen to manually introduce a unique top level directory per file system to eliminate potential merging of data and collisions. Just before ARX import, all top level folders are moved into the unique empty top level directory. This will guarantee a clean merge of the file systems, and client presentation can still be preserved by sharing out from the unique top level directory or any sub-directory as seen below: The aggregation example above is useful if a migration is required to move all these file systems to a single target. Since the ARX policies operate within the confines of a Managed Volume the file systems need to be merged before they are migrated. Instead of running a collision analysis the data could be pushed down into a unique top level directory which would ensure that there are no collisions. ARX migration policies do not run between Managed Volumes. If data is to be migrated from one file system to another they must reside within the same ARX Managed Volume. Many F5 customers have taken advantage of this flexibility to re-layout their data as part of the migration. Author Bio Jim McCarron is a Manager of Field Systems Engineering for the F5 Data Solutions (ARX/Data Manager/ARX-CE) Sales business unit. 0 Ratings Log in to rate this content Print Download Share
https://devcentral.f5.com/articles/arx-import-restrictions-for-netapp-volumes
CC-MAIN-2017-13
refinedweb
2,106
59.03
java installing - Java Beginners java installing HI sir.... can any tell me in detail that how can I download java software and install in my system(windows vista 2007...:// Hope Installing Java Installing Java  .... The combination of two features Platform Independent and Object Oriented makes the java... the flexible applications by using the conventional toolsets, java made it easy Java problem - Java Beginners Java problem what are threads in java. what are there usage. a simple thread program in java Hi Friend, Please visit the following link: Thanks Java Problem - Java Beginners Java Problem How to create executable file of a java program.That is steps to create a Jar File of a Java Program Hi Friend, Try the following code: import java.io.*; import java.util.jar.*; public class java problem - Java Beginners java problem Write a program to model a simple calculator. Each data line should consist of the next operation to be performed from the list below.../java/example/java/swing/calculator-in-swing.shtml Thanks java problem - Java Beginners java problem Suppose list is an array of five components of the type int.What is stored in list after the following Java code executes? for (i = 0; i < 5; i++) { list[i] = 2 * i + 5; if (i % 2 == 0) list[i] = list[i for a problem in coading - Java Beginners for a problem in coading what is the problm in following coading...(String[] args) { mywindow (); } } Hi Friend, There is no problem... mywindows.java Run : java mywindows Thanks RoseIndia Team programming problem - Java Beginners .. programming problem Hello..could you please tell me how can I code problem - Java Beginners code problem Dear sir, my problem is that I've a string value if this String value has "quit" then output should be "bye". i want to make this program using SWITCH CASE statement. how to implement String value in Switch plz java input problem - Java Beginners java input problem I am facing a Java input problem Problem in coding - Java Beginners Problem in coding How many times do you have to roll a pair of dice before they come up snake eyes? You could do the experiment by rolling the dice... friend, Code to help in solving the problem. public class Stimulates ; Hi friend, Code to help in solving the problem : import java.io.... in Java visit to : Thanks code problem - Java Beginners code problem Dear sir, my problem is given below: suppose a file Carries the following lines- Name: john age: 45 Address: goa phone...; Hi friend, Code to help in solving the problem : import java.io. Problem with picture - Java Beginners Problem with picture Hi, I Develope a School Automated System that takes a details from the user interface and deposited into the database (MSSQL), i make the registrar to be able to upload the student picture from code problem - Java Beginners your problem in details. Which keyword search the line. Thanks code problem - Java Beginners code problem Dear sir, I have an excel file in D: drive called today.xls, i want to open it thru java program, what code would be compatible plz help me Hi friend, Code to help in solving the problem : import problem with main - Java Beginners problem with main import javax.swing.*; import java.awt.... a problem. when i compile it appears this message: java.lang.NoSuchMethodError: main... it with html file. applet.html: Java Applet Demo Thanks code problem - Java Beginners of program. thnx Hi friend, Code to help in solving the problem arraylist problem - Java Beginners arraylist problem Hello.... I wrote the following code for adding a string array into an array list along with other strings... and to display the string array... But there's a problem with this... import java.util. code problem - Java Beginners code problem Dear sir, I've some string called "JohnSon" that has to be crypted first and then decrypted, how to crypt and decrypt data plz tell me. Hi friend, Code to help in solving the problem : public ()); } } } Dear sir, my problem is that suppose i enter line number: 3 if line instalation problem - Java Beginners instalation problem i try to install java ver 3-4-5 but. when progres going on that cant configuration. its stop when the indicator running in 1/4 progres.. thanx Programming problem - Java Beginners Programming problem Good afternoon Ma'am/Sir, Can you help me with my research? I just want to know why most Computer Science Students find it difficult to learn java programming? Based on my survey it seems that java but after installing 1.4 and setting up the classpath also i am getting... link: date problem - Java Beginners information on java visit to : Thanks GUI problem - Java Beginners GUI problem how to write java program that use JTextField to input data and JTextField to display the output when user click Display Button?? Handle the actionPerformed event for JButton and try doing something like path problem - Java Beginners -FINAL-20081019.jar in jdk's lib folder. I entered path as "C:\Program Files\Java code problem - Java Beginners and methods. Java provides some access modifiers like: public, private etc coding problem - Java Beginners coding problem hi! i declared date as date datatype in oracle now i need to retrieve date from database to my java code.how can i please help me urgent Hi Friend, We are providing you a code that will retrieve problem - Java Beginners "); } } ------------------------------------- Read for more information. Thanks code problem - Java Beginners date problem - Java Beginners logout problem - Java Beginners script problem - Java Beginners Inheritance problem - Java Beginners coding problem - Java Beginners syntax problem - Java Beginners Layout problem - Java Beginners scanner problem - Java Beginners Code problem - Java Beginners Grid Problem - Java Beginners loop problem - Java Beginners programming problem - Java Beginners htmlcode problem - Java Beginners Problem in java 1.6 - Java Beginners Problem in java 1.6 Am facing problem in java 1.6 . Ex. In a Frame...... Hi friend, Give source code where you having the problem For read more information on java visit to : programming problem - Java Beginners Java programming problem could anyone help me to solve this problem... Implement a superclass Person. Make two classes, Student and Instructor that inherit from Person. A Person has name, year of birth and day. Student has type casting problem - Java Beginners java type casting problem what is type casting? what is the type of type casting? explain with example? Hi Friend, Please visit the following link: Java Compilation Problem - Java Beginners Java Compilation Problem I defines a class named as class Authors. import java.util.*; import jsns.model.AbstractAgent; import... on Java visit to : Thanks java programing problem - Java Beginners java programing problem Create a class named Movie that can be used with your video rental business. The Movie class should track the Motion picture Association of America rating , ID Number, and movie title with appropriate Java Coding Problem - Java Beginners Java Coding Problem Q.1 How to write a while loop that displays all even numbers till 40? Q.2 How to write a method that accepts an integer...) { System.out.print(" " + i + " "); } } } } For more information on Java visit jsp code problem - Java Beginners jsp code problem Hi, I have a problem with else part. It did not show the message box when the result set is null. plz, help me. thank u in advance servlet program problem - Java Beginners file to run it Hi Friend, Please clarify your problem. Thanks
http://www.roseindia.net/tutorialhelp/comment/54243
CC-MAIN-2014-10
refinedweb
1,244
54.22
_Alignof operator From cppreference.com Queries the alignment requirement of its operand type. [edit] Syntax This operator is typically used through the convenience macro alignof, which is provided in the header stdalign.h [edit] Explanation Returns the alignment requirement of the type named by type-name. If type-name is an array type, the result is the alignment requirement of the array element type. The type-name cannot be function type or an incomplete type. The result is an integer constant of type size_t. The operand is not evaluated (so external identifiers used in the operand do not have to be defined) [edit] Notes The use of alignof with expressions is allowed by some C compilers as a non-standard extension. [edit] Keywords [edit] Example Run this code #include <stdio.h> #include <stddef.h> #include [edit] References - C11 standard (ISO/IEC 9899:2011): - 6.5.3.4 The sizeof and _Alignof operators (p: 90-91)
http://en.cppreference.com/w/c/language/_Alignof
CC-MAIN-2017-43
refinedweb
155
51.04
You should complete the "Writing your first Behavior" guide before doing this since we will use the SampleBehavior class here. Read through the Doxygen documentation on the MotionCommand class, we will be inheriting from it. Create a file named SampleMC.h (or whatever you want to call it) in your project directory. By convention, we've been ending the names of our MotionCommands with MC to make it clear what they are. Set up the usual C++ boilerplate for a class which inherits from the MotionCommand class. The functions are described below. //-*-c++-*-#ifndef INCLUDED_SampleMC_h_#define INCLUDED_SampleMC_h_#include "Motion/MotionCommand.h"class SampleMC : public MotionCommand {public: // Constructor SampleMC() : MotionCommand() {} // Abstract functions: // These must be defined by every MotionCommand virtual int updateOutputs() {} virtual int isDirty() {} virtual int isAlive() {}};#endif This isn't quite valid yet - several of the required functions have return codes which we are ignoring. But first, a brief description of the functions: updateOutputs() is called once per "cycle". It should return the number of "dirty" outputs. ("dirty" means outputs which have changed since the last cycle.) Currently the return value is unused, but in the future MotionManager may use this information to avoid redundant calculations. If this would be expensive to calculate precisely, at least be sure to return a non-zero value if there are any dirty outputs. virtual int updateOutputs() { //by convention, return the number of dirty joints //(or non-zero if unknown) return NumLegJoints; } We are using the legs, so a nice way to say that is to use the constants defined in the RobotInfo namespace. Since we're going to be using all of the leg joints, we return NumLegJoints. isDirty() is not called at present, but should return the same value as updateJointCmds(). But just for this example, we'll always return true. virtual int isDirty() { return true; } isAlive() should return true as long as the MotionCommand is active. If this returns false and the MotionCommand is set to autoprune, MotionManager will remove it. This is handy for "throw away" motion primitives. virtual int isAlive() { return true; } Our MotionCommand never really reaches an end condition, so we'll always return true. After adding these lines, the MotionCommand should be valid, although it doesn't do anything. Now lets add SampleMC to the SampleBehavior.h so you can test it out. Not that it will do anything yet, but you will be able to test incremental changes from now on. First, include the header file and create a new MC_ID member variable to hold SampleMC's ID number: // [...]#include "SampleMC.h"class SampleBehavior : public BehaviorBase {public: // [...]protected: // [...] MotionManager::MC_ID mirror_id;}; We'll call it the mirror command since it mirrors the leg positions. (or will, eventually) Now add lines to DoStart() and DoStop() to create and remove SampleMC when the behavior is activated or deactived: virtual void DoStart() { // [...] mirror_id=motman->addPersistentMotion(SharedObject<SampleMC>()); } virtual void DoStop() { motman->removeMotion(mirror_id); // [...] } And that's it! From this point we customize what we want SampleMC to do that makes it unique. Note that if your MotionCommand has a definite stopping point and uses isAlive() to reflect this status, you may instead wish to use addPrunableMotion(), and skip removeMotion(). If you do this and care to know when the MC has finished, you can listen for the appropriate deactivate event from motmanEGID.
http://www.tekkotsu.org/FirstMotionCommand.html
crawl-001
refinedweb
554
56.25
I am running into a baffling problem with my code. I am supposed to write a program to average the test scores for an entire class of students. In each case, the student should have taken 5 tests. You are to average the 5 tests. The program run should look like this. How many students are in the class ? 3 Enter five test scores for student number 1 90 90 70 90 80 The average for student number 1 is 84 Enter five test scores for student number 2 100 60 60 90 80 The average for student number 2 is 78 Enter five test scores for student number 3 90 70 50 70 90 The average for student number 3 is 74 Here is what I have: #include <iostream> #include <iomanip> using namespace std; void handleOneStudent(int N); int main() { int NumberOfStudents; cout << "How many students are in the class ?" << endl; cin >> NumberOfStudents; cout << endl; for (int i=1; i <= NumberOfStudents; i++) handleOneStudent(i); return 0; } void handleOneStudent(int N) { const int num_quizzes = 5; int score[num_quizzes]; double average; cout << setprecision(2) << setiosflags(ios::fixed) << setiosflags(ios::showpoint); cout << "Enter five test scores for student number " << N << endl; cin >> score[num_quizzes]; average = (score[1] + score[2] + score[3] + score[4] + score[5])/5; cout << endl << endl; cout << "The average for student number " << N << " is " << average << endl; } When I run the code I get the following error: Error message: Debug error! Run-Time Check Failure #2 - Stack around the variable 'score' was corrupted.
https://www.daniweb.com/programming/software-development/threads/198564/debug-error-run-time-check-failure-2
CC-MAIN-2017-17
refinedweb
253
53.44
Working with MSXML and System.Xml Using the InfoPath 2003 Object Model Last modified: May 29, 2009 Applies to: InfoPath 2010 | InfoPath Forms Services | Office 2010 | SharePoint Server 2010 | Visual Studio | Visual Studio Tools for Microsoft Office Form template projects that work with the InfoPath 2003 object model use Microsoft XML Core Services (MSXML) internally to work with XML. In managed code, it is often easier to use the XML support provided by the System.Xml namespace in the .NET Framework class library. MSXML and System.Xml cannot exchange objects natively, so whenever you need to pass XML data between InfoPath and other managed code, XML data needs to be converted. You can exchange XML data from System.Xml objects with InfoPath form code by using the techniques in this topic. To use members of the System.Xml namespace in a managed code project that uses the InfoPath 2003 object model, you must add a reference to System.Xml on the .NET tab of the Add Reference dialog box in Microsoft Visual Studio Tools for Applications. Notes To view reference information about MSXML, see the MSXML SDK. Members of the MSXML object model that are wrapped by the Microsoft.Office.Interop.InfoPath.SemiTrust namespace cannot be assigned to delegates in the form code of managed-code form templates. If you update the code of your form template to use the object model provided by members of the Microsoft.Office.InfoPath namespace, System.Xml is used natively. However, when doing so, you must manually convert all of your code to use the new object model. To convert your form template to use the new object model, in the Programming category of the Form Options dialog box, click Upgrade OM. The following code sample demonstrates how to load an entire XML DOM from System.Xml code using the InfoPath CreateDOM method and the members of Microsoft XML Core Services that are wrapped by members of the Microsoft.Office.Interop.InfoPath.SemiTrust namespace. The following examples require a using or Imports directive for System.Xml in the declarations section of the form code module. Additionally, because the Load method of the XmlDocument class requires System.Security.Permissions.FileIOPermission, you must configure the security level of the form template as Full Trust using the Security and Trust category of the Form Options dialog box. // Create a System.Xml XmlDocument and load an XML file. XmlDocument doc = new XmlDocument(); doc.Load("c:\\temp\\MyFile.xml"); // Create an MSXML DOM object. IXMLDOMDocument newDoc = thisXDocument.CreateDOM(); // Load the DOM with the XML from the System.XML object. newDoc.loadXML(doc.DocumentElement.OuterXml); The following code sample shows a function that demonstrates how to clone a single node from a System.Xml.XmlElement using the wrapped MSXML createNode method. The following examples require a using or Imports directive for System.Xml in the declarations section of the form code module. // This function takes a System.Xml XmlElement object and // an MSXML IXMLDOMDocument object, and returns an MSXML // IXMLDOMNode object that is a copy of the XmlElement object. public IXMLDOMNode CloneSystemXmlElementToMsxml( XmlElement systemXmlElement, IXMLDOMDocument msxmlDocument) { IXMLDOMNode msxmlResultNode; // Create a new element from the MSXML DOM using the same // namespace as the XmlElement. msxmlResultNode = msxmlDocument.createNode( DOMNodeType.NODE_ELEMENT, systemXmlElement.Name, systemXmlElement.NamespaceURI); // Set the element's value. msxmlResultNode.text = systemXmlElement.Value.ToString(); return msxmlResultNode; }
https://msdn.microsoft.com/en-us/library/aa948640(v=office.14).aspx
CC-MAIN-2015-11
refinedweb
554
50.73
import java.awt.*; import java.applet.*; public class Simple extends Applet { public void paint(Graphics g) { g.drawString("A simple Applet", 20, 20); } } Every Applet application must import two packages - java.awt and java.applet. java.awt.* imports the Abstract Window Toolkit (AWT) classes. Applets interact with the user (either directly or indirectly) through the AWT. The AWT contains support for a window-based, graphical user interface. java.applet.* imports the applet package, which contains the class Applet. Every applet that you create must be a subclass of Applet class. The class in the program must be declared as public, because it will be accessed by code that is outside the program.Every Applet application must declare a paint() method. This method is defined by AWT class and must be overridden by the applet. The paint() method is called each time when an applet needs. Note: The stop() method is always called before destroy() method. you name it as run.htm, then the following command will run your applet program. f:/>appletviewer run.htm
https://www.studytonight.com/java/java-applet.php
CC-MAIN-2020-05
refinedweb
174
69.07
At 09:29 AM 11/25/2004, Gerrit P. Haase wrote: >Hi, > >just finished the 3.4.2 cygwin-special build, all compiles ok, however >gcj compiled binaries are not working, any hints appreciated: > >$ echo 'public class hello_j {' > hello_j.java >$ echo 'public static void main(String[] args) {' >> hello_j.java >$ echo ' System.out.println("Just another Java hacker,");' >> >hello_j.java >$ echo ' }' >> hello_j.java >$ echo '}' >> hello_j.java >$ /usr/bin/gcj --main=hello_j hello_j.java -o hello_j >$ ./hello_j >Signal 11 Were you able to avoid build failures, due to overflow of the argument lines passed to ld or ar? I had the impression their was no intent to support gcj on any Windows platform any longer. Tim Prince
https://gcc.gnu.org/pipermail/java/2004-November/020168.html
CC-MAIN-2020-45
refinedweb
115
54.9
The Mind Electric's ElectricXML [] is yet another tree-based API for processing XML documents with Java. It has a reputation for being particularly easy to use. It's also small. The JAR archive for ElectricXML 4.0 is about 10 percent the size of the JAR archive for dom4j 1.3. Finally, the Mind Electric has d j vu. The creation of the XML-RPC request document is very similar to the way it's done in dom4j. Navigation of the response document to locate the double element is very similar to the way it it has achieved its reputation for ease of use as it is free to ignore anything else it doesn't need; but the parser is not free to make that decision for the client application. Worse yet, the ElectricXML namespace model focuses on namespace prefixes rather than namespace URIs. This certainly matches how most developers expect namespaces to work, but it is not in fact how they do work. I agree that the XML's namespace syntax is needlessly complicated and confusing. Nonetheless, an XML API cannot fix the problem by pretending that namespaces are less complicated than they really are. ElectricXML may feel easier at first than more XML-compatible APIs such as SAX, DOM, and JDOM, but it's bound to cause more pain in the long run. I also have one major nontechnical concern about ElectricXML. Whereas all of the other APIs discussed here are released as various forms of open source, ElectricXML is not. The license [] limits what you're allowed to do with the software, including preventing you from competing with it, thereby prohibiting necessary forks. Still, ElectricXML is free beer, and source code is provided.
https://flylib.com/books/en/1.131.1.56/1/
CC-MAIN-2021-31
refinedweb
287
63.49
Fixed a bug in the ConvertToLowerCase method that was not working with tag with attributes. This article presents a simple class that can be used to adjust the HTML code generated by ASP.NET in order to make it a valid XHTML document. A valid XHTML document is a document that has been successfully tested using the W3C Markup Validation Service (see). This free service checks XHTML documents for conformance to W3C recommendations. This is not only useful to guarantee that your site will be correctly managed by any W3C compliant browser, but this kind of compliance could also be a specific requirement coming from your customer. The problem is that if you try to create a XHTML document using ASP.NET, you will probably fail since the code generated by the ASP.NET engine is not XHTML. Just create a simple ASPX page and then run the W3C validator. Here is a list of errors you will find: XHTML is all lower-case and it is case sensitive. Tags like HTML or HEAD are undefined for the XHTML validator. For this kind of problems, you could simply fix it by hand editing the HTML directly using the Visual Studio editor. Unfortunately, each time you add a new control on the page and you go back and forth from the design to the HTML view, the Visual Studio editor make the tags HTML and HEAD all uppercase. In XHTML (as in XML), all the tags must have a correspondent close tag or they must be self-close. Tags like <br> or <link href="style.css" rel="stylesheet"> are not XHTML valid. You should use <br /> and <link href="style.css" rel="stylesheet" /> instead. Some valid HTML attributes have been deprecated by XHTML. For instance, the name attribute is substitute by the id. If you take a look at the ASP.NET HTML code, you will see the following script (that is actually used to handle the ASP.NET postback mechanism). <form name="Form1" method="post" action="Index.aspx" id="Form1"> <input type="hidden" name="__EVENTTARGET" value="" ID="Hidden1"/> <input type="hidden" name="__EVENTARGUMENT" value="" ID="Hidden2"/> <input type="hidden" name="__VIEWSTATE" value="ReuDDhCfGkeYOyM6Eg==" ID="Hidden3"/> <script language="javascript">; theform.submit(); } </script> The form attribute name need to be removed in order to make this code XHTML compliant. Note that this code is generated only when the page is created. You have no way to change it at design time. The above script has another problem. In the script tag, the type="text/javascript" attribute is missing. This attribute is mandatory according to the XHTML specification. Still considering the content of the Form1, the hidden input tags are not correctly placed. In fact, according to XHTML specifications, an input tag has to be inside one of the following tags: " p", " h1", " h2", " h3", " h4", " h5", " h6", " div", " pre", " address", " fieldset", " ins", " del". A possible solution is to intercept the HTML code just before it is sent to the client web browser and make the needed corrections. The XHTMLPage class inherits from the System.Web.UI.Page class, and it overrides the Render method. protected override void Render(HtmlTextWriter output) { StringWriter w; w = new StringWriter(); HtmlTextWriter myoutput = new HtmlTextWriter(w); base.Render(myoutput); myoutput.Close(); m_sXHTML = w.GetStringBuilder().ToString(); ReplaceDocType(); switch (m_XHTMLFormat) { case _XHTMLFormat.XHTML10_Strict: ConvertToXHTMLStrict(); break; case _XHTMLFormat.XHTML10_Transitional: ConvertToXHTMLTransactional(); break; } output.Write(m_sXHTML); } In the XHTMPage::Render method, first of all, the base class method base.Render is called using an instance of a new HtmlTextWriter object that has been created locally. The HtmlTextWriter is based on an underlying StringWriter object; in this way, the HTML code generated by ASP.NET can be placed inside the m_sXHTML string and then it can be treated. The methods ConvertToXHTML� take care of replacing the non-valid XHMTL parts with equivalent XHTML code. In order to make any ASP.NET page an XHTML valid page, you just need to inherit from XHTMLPage instead of System.Web.UI.Page. public class Index : XHTMLPage //public class Index : System.Web.UI.Page The XHTMLPage can be configured using the XHTMLFormat property; this can be set to Strict or Transitional (that is the default) in order to make the page valid according to the XHTML Strict or SHTML Transitional specification. base.XHTMLFormat = XHTMLPage._XHTMLFormat.XHTML10_Strict; Here I presented a problem that you may meet when trying to get a valid XHTML page using ASP.NET. Could be that this problem will be solved in the next version of Visual Studio, but in the mean time, I presented a simple solution you may find useful. In the sample code I attached, I did not care too much about performance, but it is obvious that parsing the HTML generated by ASP.NET takes some time. ConvertToLowerCasemethod that was not working with tag with attributes. General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/aspnet/ASPNET2XHTML.aspx
crawl-002
refinedweb
812
58.08
Jim Fulton wrote: Am I right in assuming that there aren't any good narrative docs for test layers? AdvertisingThis is obviously in the eye of the beholder. I'm sure the people who created narratives tried to do a good job. Perhaps you can do better. I may be missing some then... which narratives are you thinking of?And yes, I'm hoping to do better unless I've just missed some existing docs... I've attached a test file which opened my eyes... how do I go about weaving this into a doctest?I've attached a test file which opened my eyes... how do I go about weaving this into a doctest?. How so? Here's a sample of why I'm struggling: class ZODB: @classmethod def setUp(cls): ... open zodb connection ... begin transaction @classmethod def tearDown(cls): ... abort transaction ... close connection class LayerX(ZODB): @classmethod def setUp(cls): cls.savepoint = transaction.savepoint() ... create X instance @classmethod def tearDown(cls): cls.savepoint.rollback() class LayerY(ZODB): def setUp(cls): cls.savepoint = transaction.savepoint() ... create Y instance @classmethod def tearDown(cls): cls.savepoint.rollback() class MyLayer(LayerX,LayerY): pass class MyTests(TestCase): layer = '.MyLayer' def setUp(self): self.savepoint = transaction.savepoint() def tearDown(self): self.savepoint.rollback() def test_1(self): passBasically, will the above work or will the savepoints become a horrible jumbled mess and I end up with several ZODB connections as well? cheers, ChrisPS: can I use '.MyLayer' as a layer, or do I always need to put the full dotted path in? -- Simplistix - Content Management, Zope & Python Consulting - from unittest import TestSuite, makeSuite, TestCase class MyLayer: @classmethod def setUp(self): # do something here print 'L1 setup' print self @classmethod def tearDown(self): # undo it here print 'L1 teardown' class MyExtendedLayer(MyLayer): @classmethod def setUp(self): # do additional stuff here # don't call super print 'L2 setup' @classmethod def tearDown(self): # undo it only the additional stuff here # don't call super print 'L2 teardown' raise RuntimeError('fubar MyExtendedLayer.tearDown') class T1(TestCase): layer = 'Products.MyProduct.tests.test_layers.MyLayer' def setUp(self): print "T1 setup" def tearDown(self): print "T1 teardown" def test_1(self): print 'T1.1' def test_2(self): print 'T1.2' def test_3(self): print 'T1.3' raise RuntimeError('fubar T1.test_3') class T2(TestCase): layer = 'Products.MyProduct.tests.test_layers.MyExtendedLayer' def setUp(self): print "T2 setup" def tearDown(self): print "T2 teardown" raise RuntimeError('fubar') def test_1(self): print 'T2.1' def test_2(self): print 'T2.2' def test_3(self): print 'T2.3' raise RuntimeError('fubar T2.test_3') class T3(TestCase): def setUp(self): print "T3 setup" raise RuntimeError('fubar') def tearDown(self): print "T3 teardown" def test_1(self): print 'T3.1' def test_suite(): suite = TestSuite() suite.addTest(makeSuite(T1)) suite.addTest(makeSuite(T2)) suite.addTest(makeSuite(T3)) return suite _______________________________________________ Zope3-dev mailing list Zope3-dev@zope.org Unsub:
https://www.mail-archive.com/zope3-dev@zope.org/msg06684.html
CC-MAIN-2017-04
refinedweb
477
52.76
Author:. This book aims to give you a big push - with Python 3.. Once you have mastered the basics there can still be a long haul up the slope to learn how to do things properly. This book aims to give you a big push. However before you rush out and buy it you need to know that it is all about Python 3, and while there are plenty of references to how things have changed this is really only for Python 3 programmers. The book starts off with a look at the Zen of Python. Essentially these are the philosophical principles that should guide a Python programmer. If you want to get into Python it is by no means essential that you sign up to all of these principles and in fact there are a few that I would argue with - even though the majority are common sense. The book properly starts at Chapter 2 with a mixed collection of "Advanced Basics". There is no particular logic to this chapter it just rambles through exceptions, loops, the with statement, list comprehensions and so on. There are occasional notes on how things have changed prior to 3.0 and the occasional quoting of principles from Chapter 1. What you make of the chapter depends very much on how well you know Python 3.0. There isn't much in this chapter that would come as a revelation if you simply learned the basics of each topic - but if you haven't covered the ideas it's a useful random walk. The next chapter deals with functions - basically different ways of creating clever functions with different types of parameters, using closures, decorators, generators, lambdas and so on. The chapter includes a lot of bigger examples but if you are not already familiar with the idea of closure or generator say then you might find the treatment a bit on the brief side. From functions we move on to classes with a look at inheritance and multiple inheritance in particular. Python is one of the few modern languages to make a virtue out of multiple inheritance and much of the chapter is spent on explaining the why and how of using it correctly. The change in the way objects are handled is perhaps one of the biggest changes in version 3.0 and there are lots of compatibility notes. Chapter 5 is called "Common Protocols" and it is a strange collection of how to implement custom behavior in ways that fit in with the existing types. It explains how to override operators and the behaviour of fundamental types. The next chapter deals with another vague topic - object management - which is all about namespaces, garbage collection and pickling, shallow and deep copies. Chapter 7 is a close look at strings. - encoding, formatting, conversion and so on. From this point the book moves off into more general territory. Chapter 8 seems to be about documentation but it is also about writing code that self documents. Then we move on to test driven development and Chapter 10 is about distribution of Python programs. Chapter 11 is a bit odd as it is a case study - Sheets a CSV framework - which is all about converting files to Comma Separated Value format. The book is rounded off with the republication of a set of PEP texts - which are freely available on the web - and use up some 30 pages. Overall I enjoyed reading this book. If you want a sort of advanced Python reader almost just to check that you understand Python well then this isn't bad. It doesn't have a particularly logical structure and occasionally it could spend more time explaining difficult ideas but overall it does cover a lot of advanced Python. The book runs out of steam a bit towards the end with coverage of general topics and it has some padding but if you want an advanced Python reader then it's not bad. Author: [ ... ]
http://www.i-programmer.info/bookreviews/62-python/2477-pro-python.html
CC-MAIN-2016-22
refinedweb
664
68.3
public class ArrayContainer<T> { protected T[][] array; public ArrayContainer( T[][] array) { this.array = array; } public T[][] getArray() { return array; } public void setArray( T[][] pattern ) { this.pattern = pattern; } public Double[][] getArrayAsDouble() { if (arrayinstanceof Double[][]) { return (Double[][]) array; } else if (array instanceof Integer[][]) { return (IntegerToDouble(array)); } ..... return null; } public int getArraryAsInt() { } protected Double[][] IntegerToDouble(T[][] values) { .... } ..... } Are you are experiencing a similar issue? Get a personalized answer when you ask a related question. Have a better answer? Share it in a comment. From novice to tech pro — start learning today. Open in new window This should be done to very large arrays, so it has to be efficient. Open in new window Your question, your audience. Choose who sees your identity—and your question—with question security. Or you could have Class arrayClass = Object.class and have a setClass(Class class) method. Then just call setClass(Integer.class) and in your setValues you can check the values being entered are instanceof class @CEHJ: Thats what I was looking for. Looks like a good solution to my problem. I'm gonna try it out. Thank you both very much for you quick and good help.
https://www.experts-exchange.com/questions/24415545/Container-for-different-primitive-types-and-type-casting.html
CC-MAIN-2018-22
refinedweb
192
61.83
Anyone know how to code a line break in a plain text file (if it's any help, the file extn is .txt). Whitespace, including line breaks, are preserved in text files, so if you're hardcoding it, simply add a regular line break. If you have to generate the file, you can add a new line with \. \ (Note that, technically, you should use the 0x0d 0x0a character sequence in single-byte character sets, and 0x000d 0x000a sequence in double-byte character sets, but I have never encounted any problems with the single \). 0x0d 0x0a 0x000d 0x000a Should according to whom? Note that 0x0a and 0x000a are exactly the same number. It doesn't matter whether you specify the number as 10 or 0010 or 00000000010 it is still TEN. Adding extra zeros to the front of a number no matter what the number base doesn't change it. \ is just a convenient shortcut that has been assigned so that people don't have to remember that a new line character (which is what the n represents) is the tenth character in the ASCII and Unicode character sets. All the 0x on the front of the number means is that it is base 16 instead of base 10. 0 1 2 3 4 5 6 7 8 9 a b c d e f 10 SimonRFC 2616, section 3.7.1 and RFC 959, section 3.1.1.1. Probably also others. But, as I also mentioned, \ will to the trick. It's a bit like how browsers should display a lot of >'s around the interwebs, because of faux-XHTML and NET-enabled HTML. > StephenI know, but in the (probably very unlikely) event that the original poster decides to code the text files in a hex editor in Unicode, and used 0x0a 0x0d in stead of 0x000a 0x000d, it would give unexpected results. Not in character encoding it isn't... Well, it is and it isn't... You send 0x000A to a 8 bit character set, you'll get null followed by a carriage return, instead of just a null -- on little endian systems. Big endian it's the other way around. Null could be bad, as most C strings are null terminated. Could result in the entire rest of the file not even displaying if you sent the word-length version to the wrong encoding. Oh, and it would help if we were to say what the characters ARE instead of just spouting off their numbers. Carriage return (0x0D - /r) and Line feed (0x0A - /n)... which stem back to the typewriter, teletype and serial terminal days. TECHNICALLY by what the characters mean in ASCII, line feed should ONLY move the cursor down without setting it to beginning of line, which is why DEC PDP, CP/M, TOS, and anything DOS based requires both /r/n. CR+LF. Apple (from the II right up to MacOS-9), old Trash-80's, use carriage return only... This was mostly done originally to save that one byte. Naturally like everything else *nix, they use the one that makes the least sense, linefeed only. This actually makes *nix incompatible with a lot of older terminals unless you tell it what the terminal is and have software translate it. Thankfully across most systems the unrecognized character is usually ignored -- and at worst you just get double-spacing... so CR+LF works on 99% of the world. Unless you're messing around with old Sinclairs it's unlikely to be an issue - though it is why most editors still let you chose how newlines are handled. quote for truthiness: Of course when you need numbers to be a specific length then of course you need to pad them with zeros. So it should only be if you pad with zeros unnecessarily that you would get a problem as then it can be misidentified as being multiple characters. Not including the leading zeros should mean that you don't need to concern yourself with little-endian versus big-endian as the system should add the zeros in the right place provided that the program is intelligent enough to know how numbers work. An assumption I wouldn't make about any compiler or interpreter -- but I'm an assembly language coder at heart; where all things have to be precise and specific... Assuming the compiler, interpreter or assembler even lets you do it in the first place, which is where I think a lot of the real problem lies in things like PHP and HTML -- WAY too permissive and allows you to make too many assumptions; net result being sloppy coding and people making poor decisions because they never learn how it works under the hood. Many thanks for the ideas on this - it's appreciated. I tried \r\ but they actually came out in the emails exactly like that? If it helps, it's for auto emails (activation) from a phpbb forum. Can we see the code you are inserting it into? Were you using single quotes or double quotes to add them? They only encode from double quotes... (IMHO the only LEGITIMATE reason to use double quotes on ANYTHING) Though yeah, I think we need to see some code. But then, with single quotes, those line breaks could just as easily by simply adding the line break to the text. It's all just plain text, no code. So should it be : "\\r\ " or '\\r\ ' As originally stated, if it's plain text, you can simply add the line breaks using [Return]. Yep, and that doesn't work! If you are using double quotes (") and the file is being parsed as PHP and the escape characters (\\r\) are still showing, then it has to do with how the scrips handles the files. My guess (based on your saying that it's phpBB) would be that the code is not being parsed as PHP at all, but rather as HTML. Does it work if you use <br>? " \\r\ <br> Silly question, but what are you doing with said plaintext file? Is some editor you are trying to use stripping them? Are they not showing up when you echo.... Being you asked in the HTML forum, are you outputting it in HTML? If so, you need to put it inside PRE tags for the carriage returns to show... That or replace all \ with <br />... or if it's inside some other tag, add white-space: pre; in the CSS. HTML is whitespace neutral -- so all carriage returns and spaces between words are collapsed into single spaces -- that's the only situation I can think of where what you describe would happen. Though that's a wild guess. Again, without seeing the file and what you are trying to do with the file -- we're all just guessing. Educated guesses, but still just guessing. I am also facing this problem of inserting a linefeed LF CR in geany / gedit linux. In geany, when I open a file I can see the characters LF for line feeds. But which shortcut key we have to use for inserting the visible letters LF ? Purpose of above: Use LF or LFCR as delimiter for exploding a string into small pieces using PHP explode function.
http://community.sitepoint.com/t/line-breaks-in-plain-text/8091
CC-MAIN-2015-35
refinedweb
1,213
70.73
Applies To: Windows Server 2016 You can use this topic to learn how to enter netsh contexts and subcontexts, understand netsh syntax and command formatting, and how to run netsh commands on local and remote computers. contexts Netsh interacts with other operating system components by using dynamic-link library (DLL) files. Each netsh helper DLL provides an extensive set of features called a context, which is a group of commands specific to a networking server role or feature. These contexts extend the functionality of netsh by providing configuration and monitoring support for one or more services, utilities, or protocols. For example, Dhcpmon.dll provides netsh with the context and set of commands necessary to configure and manage DHCP servers. Obtain a list of contexts You can obtain a list of netsh contexts by opening either command prompt or Windows PowerShell on a computer running Windows Server 2016 or Windows 10. Type the command netsh and press ENTER. Type /?, and then press ENTER. Following is example output for these commands on a computer running Windows Server 2016 Datacenter. PS C:\Windows\system32>. branchcache - Changes to the `netsh branchcache' context. bridge - Changes to the `netsh bridge' context. bye - Exits the program. commit - Commits changes made while in offline mode. delete - Deletes a configuration entry from a list of entries. dhcpclient - Changes to the `netsh dhcpclient' context. dnsclient - Changes to the `netsh dns. ipsecdosprotection - Changes to the `netsh ipsecdosprotection' context. lan - Changes to the `netsh lan' context. namespace - Changes to the `netsh namespace'. rpc - Changes to the `netsh rpc' context. set - Updates configuration settings. show - Displays information. trace - Changes to the `netsh trace' context. unalias - Deletes an alias. wfp - Changes to the `netsh wfp' context. winhttp - Changes to the `netsh winhttp' context. winsock - Changes to the `netsh winsock' context. The following sub-contexts are available: advfirewall branchcache bridge dhcpclient dnsclient firewall http interface ipsec ipsecdosprotection lan namespace netio ras rpc trace wfp winhttp winsock To view help for a command, type the command, followed by a space, and then type ?. Subcontexts Running netsh commands:. For example, if a command has a parameter named -UserName, you must type the actual user name. - Text in Bold is information that you must type exactly as shown while you type the command. - Text followed by an ellipsis (...) is a parameter that can be repeated several times in a command line. - Text that is between brackets [ ] is an optional item. - Text that is between braces { } with choices separated by a pipe provides a set of choices from which you must select only one, such as {enable|disable}. - Text that is formatted with the Courier font is code or program output. Running Netsh commands from the command prompt or Windows PowerShell To start Network Shell and enter netsh at the command prompt or in Windows PowerShell, you can use the following command. AliasFile] [ -c Context ] [-r RemoteComputer] [ -u [ DomainName\ ] UserName ] [ -p Password | *] [{NetshCommand | -f ScriptFile}] Parameters . -r Optional. Specifies that you want the command to run on a remote computer. Important When you use some netsh commands remotely on another computer with the netsh –r parameter, the Remote Registry service must be running on the remote computer. If it is not running, Windows displays a “Network Path Not Found” error message. UserName. NetshCommand Optional. Specifies the netsh command that you want to run. -f Optional. Exits netsh after running the script that you designate with ScriptFile. ScriptFile Optional. Specifies the script that you want to run. /? Optional. Displays help at the netsh prompt. Note. Typing parameter string values for netsh commands"
https://docs.microsoft.com/en-us/windows-server/networking/technologies/netsh/netsh-contexts
CC-MAIN-2017-26
refinedweb
592
58.79
On 6/7/05, Reed Sheridan <address@hidden> wrote: > A self-explanatory snippet: > > #> (define-macro (foo) "foo") > #> (foo) > "foo" > #> (define foo 1) > #> foo > Error: invalid syntax in macro form: foo > #> (foo) > "foo" > #> > > That's without the -hygienic flag. With the -hygienic flag, foo is > redefined as 1 as you would expect. Macros and procedures live in a different namespace in the low-level macro system. The example above is simply wrong, but admittedly the error message could be improved. > > Now for my question for the BDFL: when do you think error checking is > important? When is an unchecked argument a bug and when is it a > performance feature? I would prefer it if everything checked its > arguments and gave an informative error message rather than garbage > output or something like "Error: (car) bad argument type: 1" when the > erroneous input finally reaches a function that checks its arguments 3 > stack frames down. But my performance needs are not very demanding, > and since you went for fast and dangerous and disabled argument checks > in SRFI-14 (leading to erroneous output if you give some functions bad > arguments, which I almost reported before realizing that checks were > purposely disabled), it's obvious that my opinion is not unanimous. I > don't want to waste my time or yours with bogus "bug" reports. > I disabled the calls to `check-arg' in srfi-14.scm since the checks are made anyway, albeit a bit deeper inside the library functions. This will give less informative error messages, that's true. I can enable it again, if you like - no problem. Or you can send me a patch. Just to make things clear: I'm not trying to be fast and dangerous. Mostly I just like to remove redundancy. I'm not performance-centric. I just have limited time and resources for keeping up with chicken maintenance. cheers, felix
http://lists.gnu.org/archive/html/chicken-users/2005-06/msg00020.html
CC-MAIN-2014-15
refinedweb
313
63.29
Learning Haxe Using Haxe Haxe is a strongly-typed multi-paradigm programming language that also supports cross-platform compiling into many different source and byte-code languages such as ActionScript 3, JavaScript, Java, C++, C#, PHP, Python, Lua, and Node.js. Importing To work across multiple files, Haxe includes the functionality to import classes from other files. import The import keyword is used to add a class or module to the current file. Through this process, the classes specified are then available for usage. Wildcards For loading all classes within a file, Haxe supports wildcard importing. Use of the asterisk after the name of a name and followed by a period imports all of the classes in that file or module. This process only imports one level deep. Aliasing Previous to Haxe 3.2.0, the use of the in could be used to import a class through naming its contents another variable. After Haxe 3.20, the keyword as can also be used for the same purpose. Packages (Namespaces) Haxe supports using namespaces, shared naming in modules, through the keyword package. A package is defined through both the keyword and path location. A package named “com.example” would be found in “com/example”.
https://videlais.com/2019/01/07/using-haxe-part-2-importing/?share=google-plus-1
CC-MAIN-2019-22
refinedweb
204
66.84
#include<iostream> #include<cmath> #include<iomanip> using namespace std; int main () { double Input_number; cout << "Enter a non-number e to stop entering numbers.\n"; cout << "Enter number : "; while(cin >> Input_number) { cout << "Enter number [float or 'e' to end.]: "; Input_number } return 0; } Ok, this is what i have right now. What I want to know to how to get is the "x" amount of numbers from the user input. For example. If the user inputs 1, 2, 3, and 4 from the loop, and the output average is 10/4. I want to figure out how to get all the variables into one number. like x1,x2,x3,and x4 into one number or individually so i can make a statement to calculate with. Then I would also please like to know how to get the number of inputs into a variable. Like since there are 4 inputs how would like get 4 inputs to use as a variable? PS. The user can input as many numbers as he/she wants, i just want to know how to get those numbers with a loop. thanks very much. This post has been edited by nevereap: 27 January 2010 - 08:45 PM
http://www.dreamincode.net/forums/topic/152381-how-to-do-somethings-with-loop/
CC-MAIN-2018-17
refinedweb
199
72.56
lp:~siretart/gnucash/ubuntu.aqbanking3 Created by Reinhard Tartler on 2008-07-07 and last modified on 2008-07-07 - Get this branch: - bzr branch lp:~siretart/gnucash/ubuntu.aqbanking3 Only Reinhard Tartler can upload to this branch. If you are Reinhard Tartler please log in for upload directions. Branch merges Related bugs Related blueprints Branch information - Owner: - Reinhard Tartler - Status: - Development Recent revisions - 11386. By Reinhard Tartler on 2008-07-07 short circuit svn branch detection in configure.in - 11385. By Reinhard Tartler on 2008-07-07 improve bzr support - 11384. By Reinhard Tartler on 2008-07-07 add support for bzr to util/gnc-svnversion - 11383. By Reinhard Tartler on 2008-07-07 import packaging branch -. Branch metadata - Branch format: - Branch format 6 - Repository format: - Bazaar pack repository format 1 with rich root (needs bzr 1.0)
https://code.launchpad.net/~siretart/gnucash/ubuntu.aqbanking3
CC-MAIN-2021-17
refinedweb
139
58.48
:> > Commenting out the SIGCHLD signal masking part seems to fix this issue = :for me. :> > But i'm not sure if this is a correct fix or not. :> :> Could you try the attached fix? :> :> cheers :> simon :... :> RCS file: /home/dcvs/src/sys/sys/signal2.h,v :> retrieving revision 1.1 :> diff -u -p -r1.1 signal2.h :> --- sys/signal2.h 25 Feb 2007 23:17:13 -0000 1.1 :> +++ sys/signal2.h 24 Jan 2008 09:27:00 -0000 :> @@ -103,9 +103,8 @@ __cursignb(struct lwp *lp) :> p =3D lp->lwp_proc; :> tmpset =3D lwp_sigpend(lp); :> SIGSETNAND(tmpset, lp->lwp_sigmask); :> - if ((!(p->p_flag & P_TRACED) && SIGISEMPTY(tmpset))) { :> + if (SIGISEMPTY(tmpset)) :> return(FALSE); :> - } :> return (TRUE); :> } : :This fix from Simon seems to work for me. Are there any objections to :commiting this? : :Thanks, :Nuno H? -Matt Matthew Dillon <dillon@backplane.com>
https://www.dragonflybsd.org/mailarchive/bugs/2008-01/msg00096.html
CC-MAIN-2017-09
refinedweb
136
79.67
LaravelLaravel & VueJsVueJs Implementing Slick carousel using the Vue Slick component for Vue.js vue-slick A carousel of images is a pretty way of showing an array of images, and easy way to scroll through images. For Vue.js projects, one solution can be the Vue Slick component, a wrapper for the Slick-carousel, the last carousel you’ll ever need. You can see the official slick-carousel documentation here along with demos. NOTE: slick-carousel official package appears to use jquery as a dependency in the package.json, despite it, would be more appropriate to use it as a peer dependency to avoid a possibility of using multiple versions of jquery. Be aware of that., When using webpack you can solve this problem with aliases & supports only Vue >= 2. Example Installation via yarn yarn add vue-slick Import it in your Vue project as a component import Slick from 'vue-slick'; new Vue({ components: { Slick }, data() { return { slickOptions: { //options can be used from the plugin documentation slidesToShow: 4, infinite: true, accessibility: true, adaptiveHeight: false, arrows: true, dots: true, draggable: true, edgeFriction: 0.30, swipe: true } } }, // All slick methods can be used too, example here methods: { next() { this.$refs.slick.next() }, prev() { this.$refs.slick.prev() }, reInit() { // Helpful if you have to deal with v-for to update dynamic lists this.$refs.slick.reSlick() } } }) The options which can be used with the vue-slick are the same with the those used to the original slick carousel available here. Then in your templates, you can bind the slickOptions declared in the data function and use them in your component <slick ref="slick" : <a href=""> <img src="" alt=""> </a> ... <a href=""> <img src="" alt=""> </a> </slick> The image will also contain a link which you can set to your preferred destination. Sliding through the place holder images The Vue component wrapper for the Slick-carousel is available on GitHub. Source link
https://www.laravel-vuejs.com/implementing-slick-carousel-using-the-vue-slick-component-for-vue-js/
CC-MAIN-2019-13
refinedweb
319
61.26
Not long ago, a project I was working on came up with an unusual requirement - basically a piece of content should be infinitely sliding across the screen. It could be anything - text, images - you name it, and depending on the situation it should slide either left or right, and at different speeds. So why not create an infinite loop component? This is more or less what it looks like. An additional requirement was that the content should be horizontally repeated as many times as needed to cover the entire width of its parent element (most often the full width of the viewport). A large image would perhaps only need a couple of instances, whereas something smaller might need some more. I wanted to be able to just drop some content into a component, pass in the speed and direction, and let it deal with the rest. <InfiniteLooper speed="1" direction="left"> // the stuff you want to loop </InfiniteLooper> The component should be responsible for making the content repeat across the screen, as well as animating. First though, let's look at the animation. Animating the content What we need to do is simply translate each instance of the content 100% horizontally. When you do that with several instances side by side, the end position of each instance will be the initial position of the next one, before snapping back to its initial state. This creates the impression of continuous horizontal motion. Remember, translating an element 100% means 100% of it's own width, not the parent element's width. So, let's get started:> ); } @keyframes slideAnimation { from { transform: translateX(0%); } to { transform: translateX(-100%); } } .looper { width: 100%; overflow: hidden; } .looper__innerList { display: flex; justify-content: center; width: fit-content; } .looper__listInstance { display: flex; width: max-content; animation: slideAnimation linear infinite; } looperInstances defines how many times the content will be repeated. To get started we can just hardcode it, but further on we'll see how to get it to work dynamically. As for CSS, we have a keyframe animation to translate from 0% to -100%, with the duration and direction set by the props we pass in. Basically, if we're sliding from left to right, the content translates from -100% to 0%, and the opposite happens for right to left. It might seem strange to go from -100 to 0 when we want to travel right. Why not just start at 0 and go to 100? However, if we did that, then the leftmost instance of content would just leave a blank space to its left while it translated to 100, breaking the whole impression of looping. By starting at -100, that leftmost item starts offscreen, and never leaves a blank space behind it. Also note that the speed prop is used directly by the animation duration. This means that higher values equal slower speeds. You may notice that the animation can be slightly janky at times in Firefox. Honestly, I haven't found a way to significantly improve this yet, though so far it hasn't proven to be too much of a problem. Either way, it's something to address eventually. Repeating the content Next we have to work out how many times the content needs to be repeated to cover the entire area we place it in. The basic idea is to compare the width of the innerRef and outerRef and set looperInstances accordingly. Something like this: export default); const setupInstances = useCallback(() => { if (!innerRef?.current || !outerRef?.current) return; const { width } = innerRef.current.getBoundingClientRect(); const { width: parentWidth } = outerRef.current.getBoundingClientRect(); const instanceWidth = width / innerRef.current.children.length; if (width < parentWidth + instanceWidth) { setLooperInstances(looperInstances + Math.ceil(parentWidth / width)); } }, [looperInstances]); useEffect(() => { setupInstances(); }, []);> ); } The setupInstances function compares the outer and inner ref widths. If the innerWidth (the width of all our content) is less than the width of the parent plus the one instance of content, that means we need to increase looperInstances. So we work out approximately how many more instances we need with parentWidth / width. We use that extra instanceWidth to provide a safety margin - without that you can sometimes have a "blank" space at the edges of the component. What about responsiveness? Great, so now we've got a working component! But it's not quite responsive yet. It will work fine on different screens, but what if the container element's width is increased for some reason? (Yes, by "some reason", I mostly mean developers obsessively resizing their screens). This can be addressed by adding a resize event listener that calls setupInstances again: useEffect(() => { window.addEventListener("resize", setupInstances); return () => { window.removeEventListener("resize", setupInstances); }; }, []); But there's a catch: if looperInstances is incremented the new elements will be rendered, but the CSS animation will be out of sync, and you'll see things randomly overlapping or flickering. To fix this, we need to somehow reset the animation. Forcing a re-render with useState won't work. In this case I set the animation property of each instance to "none" by setting data-animate="false" on their parent, before toggling it back to "true" - resetting the animations. Just note that you need a slight delay when toggling data-animate, forcing a reflow. function resetAnimation() { if (innerRef?.current) { innerRef.current.setAttribute("data-animate", "false"); setTimeout(() => { if (innerRef?.current) { innerRef.current.setAttribute("data-animate", "true"); } }, 50); } } function setupInstances() { ... resetAnimation(); } And the CSS updates: .looper__innerList[data-animate="true"] .looper__listInstance { animation: slideAnimation linear infinite; } .looper__listInstance { display: flex; width: max-content; animation: none; } Here I chose to set the data attribute only on a single element ( .looper__innerList), changing it's children's animation via CSS. You could also manipulate each child element directly in the resetAnimation function, though personally I find the former solution simpler. Wrapping up And that's it! We could still take it further - we could pass in props to pause and play the animation via the animation-play-state property, or have a neater solution for the animation speed, rather than just passing in seconds for the animation-duration. Who knows, we could even add vertical animation. Hopefully this demonstrates how you can use simple CSS animations in a React component to achieve whatever strange visual requirements your projects have. Stay safe! Discussion (0)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/finiam/infinite-looping-react-component-3135
CC-MAIN-2022-33
refinedweb
1,033
56.05
There is a lot of news coming from Microsoft's \\Build conference going on this week. Much of this is around Windows 10, Office 365, HoloLens, and other large investments. In the IoT space, the focus is on the announcement of Windows IoT Core (code named Athens) which is the Windows core applied to embedded devices. Of special interest is IoTCore running on the Raspberry Pi. Although we are not the biggest news item at the show, NETMF does have a significant presence as part of the overall platform solution offerings for the Internet of Things. We decided to specifically showcase some of the new things that we are working on for 4.4. At the QuickStart labs, attendees can get hands on experience with a number of technologies. For the new Windows IoT Core, attendees can program a weather app and send data to Azure with a Raspberry Pi running IoT Core and a weather shield . IoT Core includes extensions to the WinRT (UAP*) namespaces for APIs that were not needed in Windows apps before (GPIO, I2C, PWM, SPI, Analog IO,...) With 4.4, NETMF is adding support for these same WinRT namespaces (and more as time goes on). So in the QuickStart labs, the attendees can also program a new Netduino 3 WiFi board with the same weather shield using the same APIs. Our goal for the labs was to use the exact same instructions for both and the only significant differences turned out to be the result of the NETMF lab using Wifi instead of Ethernet. In addition to the labs, there is a NETMF demo in Steve Teixeira's IoT keynote on Window's IoT Core. Unfortunately, this demo, which had been solid all week, failed on stage. For some reason, the phone lost the Alljoyn connection. The way the demo did work is that he 'ask's' a Windows phone whether there are any NETMF devices present. When it relies that there are, he asks for the temperature in the room and it tells him the temperature. Finally he tells the NETMF device to send that data to the TV. The temperature shows up on the TV display. There are several interesting technologies in this demo. First, the communication is set up using Alljoyn. In 4.4, NETMF will have an implementation of the AllJoyn Thin Client. Microsoft is a member of the Allseen alliance and Alljoyn will be support in all of the Microsoft platforms. Alljoyn allows for devices to 'advertise' their presence and their 'type' and for other devices to find and consume the services that they offer. With Alljoyn supported on all the Microsoft platforms and a growing number of other devices like the LG TV we used, setting up flexible and dynamic connections between devices is really easy. This same demo that is in Steve's talk is in a booth dedicated to the Alljoyn story at Microsoft. The other technology that I think is killer is the voice support in Windows 10. Steve made a call to not utilize the Cortana portion of the demo in his talk because there had been so much already shown on Cortana but I think this is something of particular interest in small devices. UI is often a challenge on these devices. You may decide to not have any UI on your device but that misses the opportunity to impact it's functioning externally or to query it. You could elect to put buttons and LEDs on it but that is an inflexible option and not that informative. You could opt to put a touch display on the device. This improves the flexibility of the interface but it is also expensive. Voice is extremely flexible and as easy to change as modifying the Voice Command Definition in XML. There is not any explicit support for voice or Cortana in NETMF yet but with the voice capabilities on a Windows phone and Alljoyn, it is easy to implement this kind of command and control where small devices are integrated with higher end platforms. During Channel 9 interviews, Pete Brown and Steve Teixeira highlighted the work that GHI is doing to improve the Raspberry Pi connectivity to modules and the new Netduino boards. What does all this add up to? For a number of years, the Microsoft platform story was fragmented. There was Windows, Mobile, Windows Compact Edition, and NETMF as separate platforms specific to their target devices. These platforms were even in different organizations inside Microsoft further fragmenting the messaging. Now all of these technologies are in the OSG group with the direct intention of creating a powerful IoT platform suite. With UAP (now UWP) and architectural work in Windows core, the current story is Windows Standard, Windows Mobile, Windows IoT Core, and NETMF- three of the platforms are built from the same code. In the NETMF team very focused at this point to making sure that our platform for the processors that can't run one of the full OS options is still highly compatible and well integrated with them. Our two goals going forward are convergence with the rest of Windows development experience and increasing the range of applications that Microsoft has solutions for in the MCU space by increasing our performance and decreasing our memory requirements. We continue to build the team to do all this with a larger investment than the platform has had in years. Let us know what your thoughts are on all these changes. We're looking forward to an exciting year. * I am using the UAP acronym because it is probably more familiar to everyone but with \\Build, this has been renamed to the Universal Windows Platform (UWP) Thanks for the update! Do I understand it correctly that AllJoyn tries to address the same thing the DPWS stack does and is DPWS going to be deprecated in NETMF in favour of AllJoyn? So much great news for .NET Micro Framework from BUILD. Thanks for sharing this with us, Colin. And thanks to the whole team for continuing to make NETMF an amazing platform for microcontrollers and makers! Hi Jan, Alljoyn is the future direction. Is anyone concerned if we deprecate DPWS? I haven't heard much about that interface for a while. For us it is just too little too late… Even the today's news, albeit exciting, are still just more of the future plans whereas we need a platform that can be used in commercial applications today. Reliably! After having dealt with major network stability issues in NETMF we have abandoned the platform and moved on to Linux. It's a real shame, because we really wanted to use NETMF to leverage our knowledge of C#, Visual Studio and other familiar technologies. Alas, the product has to be used in the real world and rebooting the board 5-10 times per day due to a locked up network stack was just too much to bear. I hope that NETMF will rebound and turn into a solid platform and who knows, maybe we will give it another try sometime in the future, when that future is finally here. So long and good luck. Colin, are you aware that demo activities are expected to fail perhaps one time out of one hundred? It is considered to be normal in the regular computer (read too big to carry market). What happened should be considered a lesson in not trusting Murphy to keep his hands off of something. I would like to know why are you not fixing any of those bugs reported on codeplex? It looks like you have completely forgot about them. Could you please provide any comments? Hi Imn, We are fixing bugs and perhaps we should have made more noise about that at \build. The 4.4 beta that we put out a few months ago was the first set of fixes. It included addressing stability issues in the WiFi stack and performance and reliability in deployment and debugging. These were the two biggest issues we saw. We continue to work through the rest of the list. Are there any specific bugs that you are concerned with that you want to see addressed immediately? Hi Gregg, Yes, I know that demos are fraught with risk. No one wants so see features that have been available for some time so we tend to demo what we are working on. Still, you never want to see the demo fail to communicate the work we are doing. What about to improve the performance of NETMF. (Native compilation or JIT?). Without this it is too limited for real commercial use cases… If this is not a planned feature, then better you focus on Windows 10 Core IoT… Hi Alex, This is on the list of things we are looking at. No dates at this point. I agree that performance is a key opportunity for us. We want to make sure we have a solution for MCU class devices as well as devices that can run Windows. Colin, I think that community would really appreciate seeing bug list on codeplex being reduced. For example, you could sort bugs by received the most votes and go one-by-one fixing them. Personally, I would like to see #2179 and #2194 (can be merged with #2067 and #2066) addressed first. Good suggestion Imn. Our plan, as announced with the GitHub move, is to vet the issues and move them over to GitHub as we replicate them. We can certainly do this in order of the votes. I'll solicit any additional input. I have attended most of the Iot sessions at Ignite, disappointed to see lots of slides/talk about RTOS support on ARM as an Iot agent, not one slide or talk mentioned netmf, even when asking the presenters they seemed confused between the micro and compact framework. Hi Colin, I'm curious how NETMF relates to UWP. We've seen the new "device families", will the NETMF be part of one of them (e.g. the "(headless) IoT family")? Or will it stay a separate API, with only some aligned namespaces? Hi Colin, we know now that there will be something called "device families" for UWP apps, will NETMF be part of the "(headless) IoT family"? Will we be able to have one code-base for win10 UWP apps and NETMF, or will only some namespaces be aligned? I guess I have to agree with Alex O. After 30 years of embedded development I have heard this story many times before (I have even given similar talks and demos a few times). I guess I really don't see the business value of running a very proprietary piece of software (Windows 10 core) on a very proprietary piece of hardware (Raspberry Pi) just to turn on a light?. The only compelling idea I see coming out of this is the core running on embedded Linux, at least with that you have the power to tailor your custom hardware and not be dependent on MS to catch up. Raspberry PI is already yesterdays news, Raspberry Pi 2 is out with a much more powerful core …but don't try to find any info on the SoC its proprietary too.
https://blogs.msdn.microsoft.com/netmfteam/2015/04/30/netmf-at-build/
CC-MAIN-2017-34
refinedweb
1,878
69.92
Happy. My Haskell solution (see for a version with comments): let digits = let rec go l n = if n = 0 then l else go (n mod 10 :: l) (n / 10) in go [] let sumsqdig = List.fold_left (fun s d -> s + d*d) 0 % digits let fixpoint f x = let rec go x y = if x = y then x else go (f (f x)) (f y) in go (f x) x let is_happy n = fixpoint sumsqdig n = 1 Decided to maintain state so that future calls can rely on the calculations of earlier calls. Bad whitespace removing function, bad. [ I fixed your previous comment. See the instructions in the HOWTO at the top of the page so you can do it yourself next time. PP] Thanks for the fix. I also introduced a bug; line 31 should be sum of (current), not (i). Ability to edit comments would be really nice, since I saw the FAQ on code posting after I messed up my code :) […] July 23, 2010 jchiu1106 Leave a comment Go to comments The problem was posted on Programming Praxis. The algorithm itself is pretty straightforward, anyone can do it with a few if/else/fors, but to […] My Scala version: […] Todays problem had to do with Happy Numbers. […] There are 143,070 happy numbers less than 1,000,000. Hmmm. Some spaces/tabs got mucked up there. One more try: I was hoping I’d be the first to use this particular “cycle detector”, but I see that Gambiteer and Giovanni both beat me to the punch. Quel dommage. Mark: And 12005034444292997293 less than 10^20. See A068571. To see such concise implementations in languages like Scala and Haskell is humbling. Awesome, guys! A “larger” Java solution can be seen here. use v6; sub n($num){ [+] $num.split(”).map: * ** 2 } sub isHappy($num){ my @seen; for $num, {n($^a)} … * { when any(@seen) { return False } when 1 { return True } @seen.push($_); } } sub happyTo($num){ [1 ..^ $num].grep: {isHappy($^a)} } say happyTo(50).perl; Oops. Didn’t realize there was magic to formatting submissions. Let’s see how cpp formats it. In Redcode, but it took closer to 30 minutes: Here’s the shorter version I made in Python. Similar to other ones already posted, but uses a dictionary (hash) instead of a set for the sequence generated from n (still maintains constant search time, though). A longer, well-documented version with multiple definitions of is_happy() is available on codepad.org here. // about the formatting // my first post @programmingpraxis // for the mistakes in formatting // trying one more time…. // please delete the previous posts // took a LOT of time // and also copied filter and sys stuff // from others here The ability to switch between treating Perl variables as strings and numbers is a neat parlor trick. A JavaScript version… Short, no tricks, easy to understand. Took me ’bout 15 minutes, mostly because of the syntax in JS… Here’s a Common Lisp version with a bit of memoization. It looks a bit long now that I’ve seen the other solutions… probably took me 30 minutes. This is the java version that i have wrote: public abstract class HappyNumbers { public static ArrayList TRIED_NUMBERS; public static void main(String args[]) { System.out.println("HAPPY NUMBERS"); for(int i = 0; i < 10000; i++) { TRIED_NUMBERS = new ArrayList(); if(isHappy(i, 0)) { System.out.println("The number is happy : " + i); } } } public static boolean isHappy(int p_nNumber, int p_nTries) { TRIED_NUMBERS.add(new Integer(p_nNumber)); int nSums = 0; while(p_nNumber > 0) { int nSquare = p_nNumber % 10; nSquare *= nSquare; nSums += nSquare; p_nNumber /= 10; } if(nSums == 1) { return true; } else { if(TRIED_NUMBERS.contains(new Integer(nSums))){ return false; } else { return isHappy(nSums, p_nTries + 1); } } } } Clojure naive version. Tested against list of known Happy numbers below 500, found at. A bit improved version of Mark VandeWettering. Alright, I have done this, too. Implemented in Java. Granted, I am not entirely sure if I went overboard or not, as I ended up with 3 classes in total. However, each of theses classes is pretty short and to the point, so that is quite nice again :) In more detailed fashion, I have an iterator which implements the sequence of numbers starting at a certain number. This is consistent with what others did, like generators in python or lazy lists in haskell. I have a second class, which overall performs the check if a sequence cycles or stops. I put this in a separate class, because that allowed me to keep everything I need for this algorithm in attributes, which cuts down the boilerplate of parameters, which is kinda nice, I guess. The third class is just a tiny class to tie everything together into a nice package. Anyway, stats: – Used about 40 minutes in total, 30 minutes writing precise unit tests, and 10 minutes actually programming everything. – 200 loc in java (with comments) – almost 100% test coverage (could not bother to check that remove really throws an error on the iterator ;) ) After talking to the folks on #perl6 I cleaned up the perl6 version to make it a little more idiomatic and to add manual memoizing. The new version is about 30% longer because of the memoizing, but it runs in 1/3 of the time. ;; Common Lisp, with memoization and a hack (knowing that all loops necessarily go through the number 4) (defparameter *memo* (make-hash-table)) (defun happy (n &optional (it 50) (seen ‘()) (now n)) (let ((the-sum (loop for d across (write-to-string n) sum (expt (parse-integer (string d)) 2)))) (cond ((or (= 1 the-sum) (eq t (gethash the-sum *memo*))) (dolist (elt seen) (setf (gethash elt *memo*) t)) now) ((or (zerop it) (= 4 the-sum) (eq ‘nope (gethash the-sum *memo*))) (dolist (elt seen) (setf (gethash elt *memo*) ‘nope))) (t (happy the-sum (1- it) (cons the-sum seen) now))))) (defun main (&optional (up-to 500) (it 50)) (loop for n from 1 to up-to when (happy n it) collect n)) A naive ruby version. my c++ solution: A different Clojure implementation, tested against Wikipedia’s list of happy numbers under 500. I wrote a version in Factor and blogged about it: […] (mostly numeric ones) to be solved in any programming language. I was implementing the solution for Happy Numbers and something strange happened, first let’s see my Ruby […] Hi, as I do much Emacs Lisp these days, here’s it (30 mins) ;;; happy-numbers.el — Dimitri Fontaine ;; ;; ;; (require ‘cl) ; subseq (defun happy? (&optional n seen) “return true when n is a happy number” (interactive) (let* ((number (or n (read-from-minibuffer “Is this number happy: “))) (digits (mapcar ‘string-to-int (subseq (split-string number “”) 1 -1))) (squares (mapcar (lambda (x) (* x x)) digits)) (happiness (apply ‘+))) ELISP> (happy? “7”) t ELISP> (happy? “17”) nil ELISP> (find-happy-numbers “50”) (1 7 10 13 19 23 28 31 32 44 49) Oh, and the plain SQL version too, thanks to PostgreSQL. A couple of ruby versions which are closer to what a ruby programmer actually would write. The first looping and the second recursive. Should perhaps be methods on the integer class though. def happy?(n) seen={} begin seen[n] = true n = n.to_s.each_char.map { |x| x.to_i ** 2 }.reduce { |x,y| x + y } end until seen[n] return n == 1 end def happy?(n, seen={}) sum = n.to_s.each_char.map { |x| x.to_i ** 2 }.reduce { |x,y| x + y } return true if n == 1 return false if seen[sum] seen[sum] = true return happy?(sum, seen) end Javascript version that shares unhappy numbers between calls to `is_happy` This is my Python version. Is it ok? sorry I missed the inputs: Forth version, works in current BASE. and a Java solution: import java.util.HashSet; import java.util.Set; public class HappyNumber { String str; Set checkedValues = new HashSet(); int sum = 0; public void printHappyNumbers(int limit) { for (int i = 1; i <= limit; i++) { checkedValues = new HashSet(); if (isHappy(i)) System.out.println(i); } } public boolean isHappy(int value) { sum = 0; str = Integer.toString(value); for (int i = 0; i < str.length(); i++) { sum = sum + (int) Math.pow(Character.getNumericValue(str.charAt(i)), 2); } if (sum == 1) { return true; } else if (checkedValues.contains(sum)) { return false; } else { checkedValues.add(sum); return isHappy(sum); } } public static void main(String[] args) { HappyNumber hn = new HappyNumber(); hn.printHappyNumbers(50); } } check my code it is very optimized:- #include #include void main() { int a,b,c=0; clrscr(); printf(“enter a number”); scanf(“%d”,&a); while(a!=0) { { b=a%10; c=c+(b*b); a=a-b; a=a/10; } if(a==0) if(c>=10) { a=c; c=0; } } if(c==1) { printf(“your number is happy”); } else { printf(“Not a happy number”); } getch(); } static int calculateHappyNum(int num) { if (num == 1) return 1; int sum = 0; List lst = new ArrayList(); while (num > 0) { int x = num % 10; sum = sum + (x * x); num = num / 10; boolean isRepeated = false; if (sum != 1 && num < 1) { if (!lst.contains(sum)) { lst.add(sum); } else { isRepeated = true; } num = sum; System.out.println(num); sum = 0; // counter++ } if (isRepeated) return 0; } return sum; } Can u do it on Blue-j windows thank you so much brooo………………………. vinay singh can anybody tell me whats the problem in this code /*Question : Write your code to find whether the number is a happy number or not (for max 10 cycles). int number : The number to be determined whether it is happy or not int finalNumber : Store the resultant value in this variable int cycle_no : Store the number of iterations done to determine whether the ‘number’ is happy or not */ void detectHappy(int number, int &finalNumber, int &cycle_no) { for(int c=1;c0) { int rem; rem=number%10; squareSum += rem*rem; } return squareSum; } if(squareSum==1){ cycle_no=c; finalNumber=1; break; } else{ finalNumber=squareSum; number=squareSum; } } }
https://programmingpraxis.com/2010/07/23/happy-numbers/?like=1&_wpnonce=81a70c627a
CC-MAIN-2017-17
refinedweb
1,639
61.97
Scala is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. Scala is a pure object-oriented language in the sense that every value is an object [1]. Types and behavior of objects are described by classes [2] and traits [3]. Classes are extended by subclassing [4] and a flexible mixin-based composition [5] mechanism as a clean replacement for multiple inheritance. Scala is also a functional language in the sense that every function is a value [1]. Scala provides a lightweight syntax [6] for defining anonymous functions, it supports higher-order functions [7], it allows functions to be nested [8], and supports currying [9]. Scala's case classes [10] and its built-in support for pattern matching [11] model algebraic types used in many functional programming languages. Furthermore, Scala's notion of pattern matching naturally extends to the processing of XML data [12] with the help of right-ignoring sequence patterns [13]. In this context, sequence comprehensions [14] are useful for formulating queries. These features make Scala ideal for developing applications like web services [15]. Scala is equipped with an expressive type system that enforces statically that abstractions are used in a safe and coherent manner. In particular, the type system supports: A local type inference [26] [29]). In particular, the interaction with the mainstream object-oriented Java programming language is as smooth as possible. Scala has the same compilation model (separate compilation, dynamic class loading) like Java and allows access to thousands of existing high-quality libraries. Support for the .NET Framework (CLR [30]) is also available. Please continue to the next page [21] to read more. In Scala, classes are parameterized with values (the constructor parameters) and with types (if classes are generic [16]). [3] [2] [17] here; otherwise we would not be able to hide the concrete sequence implementation type of the object returned from method newIntSeqBuf. Furthermore, there are cases where it is not possible to replace abstract types with type parameters. Annotations associate meta-information with definitions. A simple annotation clause has the form @C or @C(a1, .., an). Here, C is a constructor of a class C, which must conform to the class scala.Annotation [31]. [51] [45](classOf [52] [53].) Scala supports the notion of case classes. Case classes are regular classes which export their constructor parameters and which provide a recursive decomposition mechanism via pattern matching [11]. [54].. The predefined function classOf[T] returns a runtime representation of the Scala class type T. The following Scala code example prints out the runtime representation of the args parameter: object ClassReprTest { abstract class Bar { type T <: AnyRef def bar(x: T) { println("5: " + x.getClass()) } } def main(args: Array[String]) { println("1: " + args.getClass()) println("2: " + classOf[Array[String]]) new Bar { type T = Array[String] val x: T = args println("3: " + x.getClass()) println("4: " + classOf[T]) }.bar(args) } } Here is the output of the Scala program: 1: class [Ljava.lang.String; 2: class [Ljava.lang.String; 3: class [Ljava.lang.String; 4: class [Ljava.lang.String; 5: class [Ljava.lang.String; Sometimes [21]. Sc" [55] (see section 4) by Emir [56], Odersky [57] and Williams (January 2007). Like in Java 5 (aka. JDK 1.5 [58]), [17] to control the subtyping behavior of generic types. A method with implicit parameters can be applied to arguments just like a normal method. In this case the implicit label has no effect. However, if such a method misses arguments for its implicit parameters, such arguments will be automatically provided. The actual arguments that are eligible to be passed to an implicit parameter fall into two categories: xthat can be accessed at the point of the method call without a prefix and that denote an implicit definition or an implicit parameter. implicit. In the following example we define a method sum which computes the sum of a list of elements using the monoid's add and unit operations. Please note that implicit values can not be top-level, they have to be members of a template. abstract class SemiGroup[A] { def add(x: A, y: A): A } abstract class Monoid[A] extends SemiGroup[A] { def unit: A } object ImplicitTest extends Application { implicit object StringMonoid extends Monoid[String] { def add(x: String, y: String): String = x concat y def unit: String = "" } implicit object IntMonoid extends Monoid[Int] { def add(x: Int, y: Int): Int = x + y def unit: Int = 0 } def sum[A](xs: List[A])(implicit m: Monoid[A]): A = if (xs.isEmpty) m.unit else m.add(xs.head, sum(xs.tail)) println(sum(List(1, 2, 3))) println(sum(List("a", "b", "c"))) } Here is the output of the Scala program: 6 abc. In Scala it is possible to nest function definitions. The following object provides a filter function for extracting values from a list of integers that are below a threshold value: object FilterTest extends Application { def filter(xs: List[Int], threshold: Int) = { def process(ys: List[Int]): List[Int] = if (ys.isEmpty) ys else if (ys.head < threshold) ys.head :: process(ys.tail) else process(ys.tail) process(xs) } println(filter(List(1, 9, 2, 8, 3, 7, 4), 5)) } Note that the nested function process refers to variable threshold defined in the outer scope as a parameter value of filter. The output of this program is: List(1,2,3,4) Sc: Function1[Int, Int] Function2[Int, Int, String] Function0[String]) Sc [27] Any method which takes a single parameter can be used as an infix operator in Scala. Here is the definition of class MyBool which defines three methods and, or, and negate. class MyBool(x: Boolean) { def and(that: MyBool): MyBool = if (x) that else this def or(that: MyBool): MyBool = if (x) this else that def negate: MyBool = new MyBool(!x) } It is now possible to use and and or as infix operators: def not(x: MyBool) = x negate; // semicolon required here def xor(x: MyBool, y: MyBool) = (x or y) and not(x and y) As the first line of this code shows, it is also possible to use nullary methods as postfix operators. The second line defines an xor function using the and and or methods as well as the new not function. In this example the use of infix operators helps to make the definition of xor more readable. Here is the corresponding code in a more traditional object-oriented programming language syntax: def not(x: MyBool) = x.negate; // semicolon required here def xor(x: MyBool, y: MyBool) = x.or(y).and(x.and(y).negate) Sc that methods are automatically coerced to functions if the context requires this. Here is an example: class Decorator(left: String, right: String) { def layout[A](x: A) = left + x.toString() + right } object FunTest extends Application {.: java.lang, scala, scala.Predef. Members of a later import in that order hide members of an earlier import. Scala has a built-in general pattern matching mechanism. It allows to match on any sort of data with a first-match policy. Here is a small example which shows how to match against an integer value: object MatchTest1 extends Application { Application { xto the variable y of type integer. Scala's pattern matching statement is most useful for matching on algebraic types expressed via case classes [10]. Scala also allows the definition of patterns independently of case classes, using unapply methods in extractor objects [59]. Methods. A [60]being raised at run-time. When applied to the selector of a match expression, the @unchecked [47] annotation suppresses any warnings about non-exhaustive pattern matches which would otherwise be emitted. For instance, no warnings would be produced for the method definition below. def f(x: Option[Int]) = (x: @unchecked) match { case Some(y) => y } Without the @unchecked [47] annotation, a Scala compiler could infer that the pattern match is non-exhaustive, and could produce awarning because Option is a sealed class. Similar to interfaces in Java, traits are used to define object types by specifying the signature of the supported methods. Unlike Java, Scala allows traits to be partially implemented; i.e. it is possible to define default implementations for some methods. In contrast to classes [61] (or other traits) with a mixin class composition In Scala, type parameters [16] and abstract types [21] may be constrained by a type bound. Such type bounds limit the concrete values of the type variables and possibly reveal more information about the members of such types. An upper type bound T <: Adeclares that type variable T refers to a subtype of type A. Here is an example which relies on an upper type bound for the implementation of the polymorphic method [25] findSimilar: trait Similar { def isSimilar(x: Any): Boolean } case class MyInt(x: Int) extends Similar { def isSimilar(m: Any): Boolean = m.isInstanceOf[MyInt] && m.asInstanceOf[MyInt].x == x } object UpperBoundTest extends Application { def findSimilar[T <: Similar](e: T, xs: List[T]): Boolean = if (xs.isEmpty) false else if (e.isSimilar(xs.head)) true else findSimilar[T](e, xs.tail) val list: List[MyInt] = List(MyInt(1), MyInt(2), MyInt(3)) println(findSimilar[MyInt](MyInt(4), list)) println(findSimilar[MyInt](MyInt(2), list)) } Without the upper type bound annotation it would not be possible to call method isSimilar in method findSimilar. The usage of lower type bounds is discussed here [19]. While upper type bounds [18] [17]) } [21]: ColorPointinherits all members from its superclass Point; in our case, we inherit the values x, y, as well as method move. ColorPointadds a new method compareWithto the set of (inherited) methods.. ColorPointobjects whenever Pointobjects are required. For cases where we would like to inherit from several other classes, we have to make use of mixin-based class composition [5] as opposed to pure subclassing. [25] are called or generic classes [16]. In contrast to Java, all values in Scala are objects (including numerical values and functions). Since Scala is class-based, all values are instances of a class. The diagram below illustrates the class hierarchy. [62]Scala [24] Scala supports variance annotations of type parameters of generic classes [16]. In contrast to Java 5 (aka. JDK 1.5 [58]), [25], lower type bounds [19], and covariant type parameter annotations in a non-trivial fashion. Furthermore we make use of inner classes [20] = error("no element on stack") def pop: Stack[A] = error("no element on stack") override def toString() = "" } object VariancesTest extends Application { var s: Stack[Any] = new Stack().push("hello"); s = s.push(new Object()) s = s.push(7) Console [25]. Implicit parameters [63] [64]) } } Scala can be used to easily create, parse, and process XML documents. XML data can be represented in Scala either by using a generic data representation, or with a data-specific data representation. The latter approach is supported by the data-binding tool schema2 ]
http://www.scala-lang.org/old/print/book/export/html/104
CC-MAIN-2014-49
refinedweb
1,822
56.05
In this article, we will build an Image Gallery with Next.js using the Pexels API and Chakra UI v1, a modular and accessible component library. We will also use the Next.js Image component to optimize the images fetched from the Pexels API. If you want to jump right into the code, check out the GitHub Repo here. And here's a link to the deployed version:. What concepts & topics will we cover in this article? - How to install and use Chakra UI v1 with Next.js - How to fetch data in Next.js from an API - How to use the Next.js Image Component - How to setup Dynamic Routes in Next.js Table of Contents - Prerequisites - How to Setup and Install Next.js - How to Generate the Pexels API Key - How to Add a Heading to the Gallery - How to Fetch Data from the Pexels API - How to Display Photos on the Page - How to Style Images with Chakra UI - How to Add Search Functionality to the Gallery - How to Add Dynamic Routes to Images - Conclusion Now let's get started. Prerequisites Before we get started, you should have: - Knowledge of HTML, CSS, and JavaScript. - Basic knowledge of React and Next.js. - Node and NPM installed on your local dev machine. - Any code editor of your choice. - React Dev Tools (optional) If you feel like your progress is hindered because you don't know enough about these subjects, check out. The awesome modules there will get you started in no time. How to Setup and Install Next.js We will use Create Next App to initialize a Next.js project quickly. In your project's root directory, run the following commands in the terminal. npx create-next-app next-image-gallery cd next-image-gallery npm run dev The last command, npm run dev, will start the development server on your system's port 3000. Navigate to in the browser. Here is what your app will look like. Run the following command to install Chakra UI: npm i @chakra-ui/react @emotion/react @emotion/styled framer-motion @chakra-ui/icons The next step is to clean the sample code generated by create-next-app and configure the project to use Chakra UI. - Delete the stylesand pages/apifolder. - Update your pages/_app.jslike this: // pages/_app.js import { ChakraProvider } from "@chakra-ui/react"; function MyApp({ Component, pageProps }) { return ( <ChakraProvider> <Component {...pageProps} /> </ChakraProvider> ); } export default MyApp; 3. Modify pages/index.js like this: // pages/index.js import Head from "next/head"; export default function Home() { return ( <div> <Head> <title> NextJS Image Gallery</title> <link rel="icon" href="/favicon.ico" /> </Head> </div> ); } Again head over to. You will see that the app is blank, but the title has changed to NextJS Image Gallery. You can now close the development server. How to Generate the Pexels API Key We will use the Pexels API to fetch images for our Gallery. You will need to create a Pexels API key to authenticate your API requests. The API itself is completely free to use. You can make as many as 200 requests per hour and 20,000 requests per month to the Pexels API. Head over to and create a new account on Pexels. After filling in your details, you will also need to confirm your account before applying for an API key. So check your inbox and confirm your Pexels account. Navigate to and fill in the details for a new API key and click Request API Key Remember to follow the API guidelines. Now copy the API key shown on the next page. In your project's root directory, create a new file named .env.local to store this API key securely. Run the following commands to create the file: touch .env.local Inside this .env.local file, create a new environment variable named PEXELS_API_KEY and paste the API key there. NEXT_PUBLIC_PEXELS_API_KEY = '' Next.js has built-in support for loading environment variables from .env.local into process.env. By default, all environment variables loaded through .env.local are only available in the Node.js environment. This means that they won't be exposed to the browser. Using the NEXT_PUBLIC_ prefix exposes the environment variable to the browser. You can read more about it here. How to Add a Heading to the Gallery In this section, we will add a heading to our Gallery. Import and add the Box component to index.js like this: //pages/index.js import Head from "next/head"; import { Box } from "@chakra-ui/react"; export default function Home() { return ( <div> <Head> <title> NextJS Image Gallery</title> <link rel="icon" href="/favicon.ico" /> </Head> <Box overflow="hidden" bg="purple.100" minH="100vh"></Box> </div> ); } Navigate to. You will see that your app has a background color of light purple. Here's what we are doing: - In Chakra UI, bgis the shorthand prop for property. By passing background bg="purple.100", the background of the app changes to light purple. The number after the color represents the shade of the color where the lightest is 50, and the darkest is 900. Here is an image from the Chakra UI docs to better illustrate this point. - Setting minH="100vh"makes the app at least 100% of the parent's element height. minHis the shorthand prop for the min-heightproperty. - To get rid of extra scroll bars in case the content overflows the parent element, overflow="hidden"is passed. To add a heading, we will use the Text and Container component available in Chakra UI. Modify the Box import in index.js like this: import { Box, Container, Text } from "@chakra-ui/react"; Now, add the Container component inside the Box component. <Box overflow="hidden" bg="purple.100" minH="100vh"> <Container></Container> </Box> You will see no change in your app, but the Container component has added some horizontal padding in your app, which will be more apparent after adding the Text component. Add the following code inside the Container component: <Container> <Text color="pink.800" fontWeight="semibold" mb="1rem" textAlign="center" textDecoration="underline" fontSize={["4xl", "4xl", "5xl", "5xl"]} > NextJS Image Gallery </Text> </Container> Let's break down the above code and discuss it. coloris used to set the color of the text to pink.900. fontWeightis used to set the thickness of the character. mbis a shorthand prop for margin-bottomand 1rem=16px. textAlign="center"aligns the text in the center. textDecoration="underline"adds a line under the text. fontSize, as the name suggests, sets the size of the text. Here is how your app will look: xs: "12px" sm: "14px" md: "16px" lg: "18px" xl: "20px" You might ask why there are four values of fontSize as an array inside curly braces? The {} are used to tell the JSX parser to interpret the expression within {} as JavaScript. Here, {} is used to pass an array for fontSize's value. This array is a shorthand for media queries in Chakra UI. The values are passed in an array to make the text responsive and change the font size according to the devices – that is, the heading will be larger on the desktop. Each index of the array corresponds to a specific breakpoint and the property's value. This means that font-size changes according to the breakpoint. You can read more about it here. const breakpoints = { sm: "30em", md: "48em", lg: "62em", xl: "80em", } It follows the "mobile-first" approach, so the first value is for smaller devices, and the last value is for desktop devices. The above code will generate CSS like this: .css-px6f4t { text-align:center; -webkit-text-decoration:underline; text-decoration:underline; font-size:2.25rem; color:#702459; font-weight:600; margin-bottom:1rem; } @media screen and (min-width:30em) { .css-px6f4t { font-size:2.25rem; } } @media screen and (min-width:48em) { .css-px6f4t { font-size:3rem; } } @media screen and (min-width:62em) { .css-px6f4t { font-size:3rem; } } Here is the side by side difference in heading size as seen in Polypane. How to Fetch Data from the Pexels API You have generated the API key so let's write the code to fetch data from the API. We will create a separate file and define the functions to fetch data inside it. In your project's root directory, create a folder named lib. Inside it, create a file named api.js. Run the following command in the terminal: mkdir lib cd lib touch api.js This is the Pexels API base URL for photos:. The Pexels API has three endpoints: /curatedto receive real-time photos curated by the Pexels team. /searchto search for photos based on a query. /photos/:idto get a single photo from its id. We will use the /curated endpoint to show photos curated by the Pexels team on the app's landing page. Add the following code to api.js: const API_KEY = process.env.NEXT_PUBLIC_PEXELS_API_KEY; export const getCuratedPhotos = async () => { const res = await fetch( ``, { headers: { Authorization: API_KEY, }, } ); const responseJson = await res.json(); return responseJson.photos; }; Let's discuss the above code: - We start by creating a variable named API_KEYthat accesses the NEXT_PUBLIC_PEXELS_API_KEYenvironment variable using process.env. - Then we create an asynchronous function named getCuratedPhotos()that uses the fetch()method to fetch the data from the API. - If you take a closer look at the fetch URL, you will notice that we have added ?page=11&per_page=18after /curatedendpoint. These are the optional parameters that you can pass to the /curatedendpoint as query strings. Here page=11means send the 11th page, and per_page=18means that send 18 photos per page. - You can also remove these optional parameters, in which case the API endpoint will send you 15 pictures from the first page. You can get as many as 80 photos in a single request. - The Pexels API key is passed in the Authorizationfield under the headers. res.json()parses the response in JSON format. responseJsoncontains fields like the page, per_page, and so on, which are not used by our app. So only the photosfield of the response is returned, which looks like this: [ { id: 4905078, width: 7952, height: 5304, url: "", photographer: "Nick Bondarev", photographer_url: "", photographer_id: 2766954, src: { original: "", large2x: "", large: "", medium: "", small: "", portrait: "", landscape: "", tiny: "", }, liked: false, }, ]; In the src field we are given many different image formats to choose from. In this tutorial we will use portrait type images on our landing page. You are free to explore other formats too. As we develop our app, we will write the functions to search for a photo and get a single photo in api.js. For now, we will use this function to display an image on our landing page or homepage. How to Display Photos on the Page Now that we have created the function to fetch data, let's display them on our page. First, import the getCuratedPhotos() function in index.js. import Head from "next/head"; import { Box, Container, Text } from "@chakra-ui/react"; import {getCuratedPhotos} from "../lib/api" We will use the getServerSideProps() function available in Next.js and use the getCuratedPhotos() function inside it to fetch data from Pexels API and inject it in our page. You can read more about getServerSideProps() here. Add the following code at the bottom of your index.js file: export async function getServerSideProps() { const data = await getCuratedPhotos(); return { props: { data, }, }; } The above async function uses getCuratedPhotos() to fetch images from the Pexels API and store it in the data variable. This data variable is made available as a prop in the props property. This data is available as a prop so add it as an argument in the Home component function. export default function Home({data}) { ... } Restart your development server, and inside your Home component, console.log this data: export default function Home({data}) { console.log(data) return ( ... } Head over to and open the console by pressing CTRL + Shift + J in Chrome or CTRL + Shift + K in Firefox. Remove the console.log and add the following code to the top of your index.js file to import the useState() hook from react. import React, { useState } from "react"; We will store the data from the Pexels API inside a state named photos. Add the following code before the return statement: const [photos, setPhotos] = useState(data); To display images, map over the photos array and pass src.original in the src attribute of the img element. Add the following code after the Container component: { photos.map((pic) => ( <img src={pic.src.original} )) } Your app will now look something like this: Aside from the fact that the images are not properly sized, there is another issue with us using <img> to display the images. Head over to and open Developer tools and then the Network tab ( Ctrl+ Shift + E in Firefox and Ctrl + Shift + J in Chrome). It will look something like this: Now reload your page. You will see that the empty Network tab is now filled with data. As you can see in the above image, the requested file is sized over 11 MB, and this is for a single file or image. The sizes can vary anywhere from 10 to 100 MB or more based on the quality of the image. Imagine you have 80 images on your app's landing page. Does it make sense to transfer around 800 MB of files every time someone visits your Gallery or website? It does not. This is why today, most of the images on the web are served in WebP format. This format significantly reduces the size of the image, and you can hardly detect any visual difference. So, we need to change the image format to webp, but the question is, how? Do you need to do it manually? If yes, won't it be time consuming and tiresome? No, you don't need to do it manually. Next.js version 10 comes with built-in support for Image Optimization using the Image component. You can read more about this update here. So, let's replace the img element with the Next.js Image component. First, import this component inside your index.js like this: import Image from "next/image"; But wait, before we use this component in our code, we need to tell Next.js that our images are coming from an external resource, like from Pexels. Stop your development server and create a next.config.js file by running the following command: touch next.config.js Add the following code to next.config.js: module.exports = { images: { domains: ["images.pexels.com"], }, }; And that's it. There are other configurations like path, imageSizes, deviceSizes, and so on that you can add in the images field. But in this tutorial, we will leave them as default. You can read more about the configuration here. Replace img with the Image component and pass the props, as shown below: { photos.map((pic) => ( <Image src={pic.src.portrait} height={600} width={400} alt={pic.url} /> )) } As discussed above, the Pexels API provides different formats or sizes of the same image, like portrait, landscape, tiny, and so on, under the src field. This tutorial uses the portrait images on the landing page, but you are free to explore other sizes. src: { original: "", large2x: "", large: "", medium: "", small: "", portrait: "", landscape: "", tiny: "", } srcfield of the photo object As you can see in the above sample src field, the portrait format of the image has a width of 800 and a height of 1200. But it is too large to show on the webpage, so we will scale it down by dividing it by 2. So 600 and 400 are passed in for the height and width of the Image component. Restart your development server and head over to. You will see that the app itself looks exactly the same. But this time if you open the Network tab and reload the page, you will see something truly magical. Your images are now in webp format, and their sizes have been reduced. The Next.js Image component has also added lazy loading to images. Here is an example to explain how and why you should use lazy loading if you are unfamiliar with it. Even though the images are now in webp format, is it necessary to load all the images whenever someone visits your website? And if the visitor just comes and leaves without scrolling, does it make sense to load the images at the bottom of the page? There is no need to load the images that a user or visitor is not going to see in most situations. And that's where Lazy Loading comes to save the day. It delays the requests to images as to when they are needed or, in this situation, when images come into view. This significantly helps reduce the initial page weight and increases website performance. If you head over to and scroll through all the images, you will see that the images that are not in the viewport are not loaded initially. But as you scroll down, they are transferred and loaded. By default, the layout prop of the Image component has the value of intrinsic, which means the image will scale the dimensions down for smaller viewports but maintain the original dimensions for larger viewports. There are many props that you can pass to the Image component to modify this component further. You can read about them here. How to Style Images with Chakra UI To style the images, we will use Chakra UI's Wrap component. Wrap is a layout component that adds a defined space between its children or images in this scenario. It 'wraps' its children automatically if there is not enough space to fit any child. Import Wrap and WrapItem from Chakra UI. import { Box, Container, Text, Wrap, WrapItem } from "@chakra-ui/react"; WrapItem encloses the individual children while Wrap encloses all the WrapItem components. Modify the expression to display images like this: <Wrap px="1rem" spacing={4} {photos.map((pic) => ( <Image src={pic.src.portrait} height={600} width={400} alt={pic.url} /> ))} </Wrap> Here's what's happening in the above code: px="1rem"is the shorthand prop for padding-leftand padding-right.This adds horizontal padding of 1 rem. spacing={4}applies spacing between each child. This will be seen once each image is wrapped with WrapItem. justify="center"justifies the images in the center. Now wrap each image with WrapItem. Add the following code inside the JavaScript expression: <Wrap px="1rem" spacing={4} {photos.map((pic) => ( <WrapItem key={pic.id} boxShadow="base" rounded="20px" overflow="hidden" bg="white" lineHeight="0" _hover={{ boxShadow: "dark-lg" }} > <Image src={pic.src.portrait} height={600} width={400} alt={pic.url} /> </WrapItem> ))} </Wrap> Let's discuss the props passed to WrapItem one by one: key={pic.id}gives each image a unique key so that React can differentiate between the children or pictures. boxShadow="base"adds shadow to WrapItem. rounded="20px"adds a border-radiusof 20px. overflow="hidden"make sure the image doesn't overflow the WrapItemand is seen rounded. bg="white"adds a white background to the WrapItem. lineHeight="0"sets line-heightproperty to zero. _hover={{ boxShadow: "dark-lg" }}changes the boxShadowwhen you hover over the image. You will see that spacing={4} has also come into effect since we added WrapItem to images. How to Add Search Functionality to the Gallery The next step is to add a feature to allow users to search for images and show those images to them. For this, we will use the /search endpoint in the Pexels API. In lib/api.js create a new function getQueryPhotos() to search for images based on the user's search input. export const getQueryPhotos = async (query) => { const res = await fetch(`{query}`, { headers: { Authorization: API_KEY, }, }); const responseJson = await res.json(); return responseJson.photos; }; The above function getQueryPhotos() is similar to getCuratedPhotos but here we have added a query parameter to the function and modified the API endpoint to include this query. `{query}` Import the getQueryPhotos() function in index.js. import { getCuratedPhotos, getQueryPhotos } from "../lib/api"; getQueryPhotos()in index.js Now, we will create a form to take user input and search for the same. We will import and use Input, IconButton, InputRightElement, and InputGroup from Chakra UI to create this form. Modify the Chakra UI import like this and add an import for SearchIcon: import { Box, Container, Text, Wrap, WrapItem, Input, IconButton, InputRightElement, InputGroup, } from "@chakra-ui/react"; import { SearchIcon } from "@chakra-ui/icons"; Add the following code for the input form inside the Container component in index.js file: <InputGroup pb="1rem"> <Input placeholder="Search for Apple" variant="ghost" /> <InputRightElement children={ <IconButton aria- } /> </InputGroup> Here's what we are doing. InputGroupis used to group the Inputand InputRightElementcomponents. Here pbis shorthand for padding-bottom. Inputis the input field where users will type their queries. It has a placeholder of "Search for Apple". InputRightElementis used to add an element to the right of the Inputcomponent. An icon button with the icon of search is passed to the childrenprop of InputRightElement. IconButtonis a component in Chakra UI which is useful when you want an icon as a button. The icon to render is passed inside the iconprop. Here's how the input field will look. This form doesn't do anything yet. Let's change that. Define a new state named query to store a user's inputs: export default function Home({ data }) { const [photos, setPhotos] = useState(data); const [query, setQuery] = useState(""); ... } querystate Modify the Input component to create a two-way bind between the input field and query state using the value method and onChange event: <Input placeholder="Search for Apple" variant="ghost" value={query} onChange={(e) => setQuery(e.target.value)} /> Now, create a function named handleSubmit() to handle the click event of search icon. For now we will just console.log the input query and clear the field afterwards. export default function Home({ data }) { const [photos, setPhotos] = useState(data); const [query, setQuery] = useState(""); const handleSubmit = async (e) => { await e.preventDefault(); await console.log(query); await setQuery(""); }; ... } Add this function to the onClick event of IconButton: <InputRightElement children={ <IconButton aria- } /> Head over to and type something in the input field and click the search button. But this form is still missing something: if you try to search for something by hitting Enter instead of the search button, it will refresh the page, and the query is not logged. To fix this, enclose the InputGroup with the form element and pass the handleSubmit function to the onSubmit event like this: <form onSubmit={handleSubmit}> <InputGroup pb="1rem"> <Input placeholder="Search for Apple" variant="ghost" value={query} onChange={(e) => setQuery(e.target.value)} /> <InputRightElement children={ <IconButton aria- } /> </InputGroup> </form> You will notice hitting Enter will work now. Now update the handleSubmit function like this to fetch the images based on the user's query: const handleSubmit = async (e) => { await e.preventDefault(); const res = await getQueryPhotos(query); await setPhotos(res); await setQuery(""); } The above function passes the query variable to the getQueryPhotos() function and the data returned from the function overrides the previous value in the photos variable using setPhotos(res). And it's done! You can now search images in your app. There's still something missing. What is it? What if the user tries to search without any query, like with empty strings? The current code will still try to make request using "" and we will run into the following error. To handle this issue, we will use Toast from Chakra UI. Import useToast from Chakra UI: import { Box, Container, Text, Wrap, WrapItem, Input, IconButton, InputRightElement, InputGroup, useToast } from "@chakra-ui/react"; Add the following code jut below where you defined states to intialize Toast. export default function Home({ data }) { const [photos, setPhotos] = useState(data); const [query, setQuery] = useState(""); const toast = useToast(); ... } Modify the handleSubmit() function like this: const handleSubmit = async (e) => { await e.preventDefault(); if (query == "") { toast({ title: "Error.", description: "Empty Search", status: "error", duration: 9000, isClosable: true, position: "top", }); } else { const res = await getQueryPhotos(query); await setPhotos(res); await setQuery(""); } }; In the above code, we check if the query is empty or not with a simple if/else statement. And if it is empty, then we display an error toast with Empty Search text. Try hitting Enter without typing anything in the input field. You will see a toast like this: How to Add Dynamic Routes to Images We will create a dynamic route for each image so users can click on images to get more information on them. Next.js has a very cool feature where you can create a dynamic route by adding brackets to a page ( [param]), where param can be URL slugs, pretty URLs, an ID, and so on. Here the param is id, since to get a specific photo from Pexels API you need to provide its id. Run the following commands in your project's root directory to create [id].js in the photos directory under pages. mkdir pages/photos cd pages/photos touch [id].js Import Link from next/link in index.js. Link helps in client-side transitions between routes. You can read more about Link here. import Link from "next/link" Add this Link to each image like this: <Link href={`/photos/${pic.id}`}> <a> <Image src={pic.src.portrait} height={600} width={400} alt={pic.url} /> </a> </Link> Head over to your app and try clicking any image. It will show an error since we have created photos/[id].js but didn't add any code in it. But if you notice the URL of this page, it will be something like this: We will now create a third function named getPhotoById() in lib/api.js to get a specific photo based on its id. Add the following code to api.js: export const getPhotoById = async (id) => { const res = await fetch(`{id}`, { headers: { Authorization: API_KEY, }, }); const responseJson = await res.json(); return responseJson; }; The above code uses the /photos endpoint to get a single image from Pexels API. You will notice that unlike getCuratedPhotos and getQueryPhotos, getPhotoById returns the responseJson and not responseJson.photos. Add the following code to photos/[id].js: import { getPhotoById } from "../../lib/api"; import { Box, Divider, Center, Text, Flex, Spacer, Button, } from "@chakra-ui/react"; import Image from "next/image"; import Head from "next/head"; import Link from "next/link"; import { InfoIcon, AtSignIcon } from "@chakra-ui/icons"; export default function Photos() { return ( <Box p="2rem" bg="gray.200" minH="100vh"> <Head> <title>Image</title> <link rel="icon" href="/favicon.ico" /> </Head> </Box> ) } We have added a background color of light gray using the bg prop and Box component. To save time, we have imported all the components and icons beforehand. Create a getServerSideProps() function in [id].js to fetch data from the Pexels API. export async function getServerSideProps({ params }) { const pic = await getPhotoById(params.id); return { props: { pic, }, }; } Restart your development server. You might ask how getServerSideProps() is getting the id of the image from the params argument? Since this page uses a dynamic route, params contain the route parameters. Here the page name is [id].js , so params will look like { id: ... }. You can try console.log(params) – it will look something like this. { id: '4956064' } Pass this pic prop to the Photos component function as an argument. export default function Photos({ pic }) { ... } Add the following code to the Box component: <Box p="2rem" bg="gray.200" minH="100vh"> <Head> <title> Image: {pic.id}</title> <link rel="icon" href="/favicon.ico" /> </Head> <Flex px="1rem" justify="center" align="center"> <Text letterSpacing="wide" textDecoration="underline" as="h2" fontWeight="semibold" fontSize="xl" as="a" target="_blank" href={pic.photographer_url} > <AtSignIcon /> {pic.photographer} </Text> <Spacer /> <Box as="a" target="_blank" href={pic.url}> <InfoIcon focusable="true" boxSize="2rem" color="red.500" />{" "} </Box>{" "} <Spacer /> <Link href={`/`} > <Button as="a" borderRadius="full" colorScheme="pink" fontSize="lg" size="lg" cursor="pointer" > 🏠 Home </Button> </Link> </Flex> <Divider my="1rem" /> <Center> <Box as="a" target="_blank" href={pic.url}> <Image src={pic.src.original} width={pic.width / 4} height={pic.height / 4} quality={50} priority </Box> </Center> </Box> Here is how your page will look now: Let's break this code down piece by piece. - We first modify the title of the page, by passing the id of the image after the Imagetext. <Head> <title> Image: {pic.id}</title> <link rel="icon" href="/favicon.ico" /> </Head> - We then create a navbar using the Flexcomponent. <Flex px="1rem" justify="center" align="center"> ... </Flex> Here px is shorthand prop for padding-left and padding-right, and justify and align are for justify-content and align-items, respectively. - We then add a link to the photographer using the Textand AtSignIconicons. You can also use the AtSignIcon. <Text letterSpacing="wide" textDecoration="underline" as="h2" fontWeight="semibold" fontSize="xl" as="a" target="_blank" href={pic.photographer_url} > <AtSignIcon /> {pic.photographer} </Text> The as prop is a feature in Chakra UI that allows you to pass an HTML tag or component to be rendered. Here we are using it with the <a> tag so the Text component will be rendered as <a> tag on the page. The target="_blank" makes sure that the link opens in a new window or tab. - Then we add a Spacercomponent that, when used with Flex, distributes the empty space between Flex's children. You can read more about it here. - Next, we add an information icon that links to the photo on Pexels. <Box as="a" target="_blank" href={pic.url}> <InfoIcon focusable="true" boxSize="2rem" color="red.500" /> </Box> <Spacer /> - Then we add Homebutton in the nav to take the user back to the landing page of the app using the Linkcomponent from next/link. <Link href={`/`}> <Button as="a" borderRadius="full" colorScheme="pink" fontSize="lg" size="lg" cursor="pointer" > 🏠 Home </Button> </Link> - Then we use Dividercomponent to divide the navbar and the image. <Divider my="1rem" /> Here my is shorthand prop for margin-top and margin-bottom. - Finally, we add the image to the page using the Centercomponent, which as the name suggests, centers its children. <Center> <Box as="a" target="_blank" href={pic.url}> <Image src={pic.src.original} width={pic.width / 4} height={pic.height / 4} priority quality={50} </Box> </Center> In the above code, we use the Box component to add a link to the original image on Pexels using the as prop. You will also notice that we have passed a few additional props in the Image component. src: We are passing the originalimage this time. - We scale the image by dividing the original width and height by 4. - By passing priority, the image is considered high priority and is preloaded. - By default, the Imagecomponent reduces the quality of optimized images to 75%, but since the image is still too big, we further decrease its quality to 50%, by passing quality={50}. - By default, loading behavior is lazy in the Imagecomponent, but here we want the image to be displayed immediately, and hence we pass Here is the above code in action. You did it! 🎉 Congrats 👏 on building this Next Image Gallery project. Conclusion In this tutorial, we learned how to build an Image Gallery with Next.js using the Pexels API and Chakra UI. We discussed how to install and use Chakra UI v1 in any Next.js project. We also saw how to fetch data from an API and create dynamic routes in Next.js. Here are some other APIs that you can explore and use in your project: Here are some additional resources that can be helpful: Would you like a second part of this tutorial, where we add animations to images using Framer Motion? Let me know on Twitter. What other projects or tutorials would you like to see? Reach out to me on Twitter, and I'll cover them in my next article! If you're inspired to add features yourself, please do share and tag me – I'd love to hear about them :)
https://www.freecodecamp.org/news/build-an-image-gallery-with-nextjs/
CC-MAIN-2021-21
refinedweb
5,323
67.04
Best practices for customization This page contains best practices for customizing Kentico. The recommendations mostly focus on minimizing problems that can occur when upgrading to newer versions. If you are unfamiliar with the upgrade process, see Upgrading to Kentico 10. Database structure and objects Note: In general, upgrades may change the structure of the default Kentico database tables and overwrite any default database objects. Customizing the default Kentico database tables - NEVER modify Kentico tables manually in the database (adding or removing of columns, changing column data types, etc.). - Adding of custom columns is only possible for tables that store the data of customizable classes: - Open the Modules application in the Kentico administration interface. - Edit the appropriate module. - Edit the customizable class on the Classes tab. - Define any new database columns on the Fields tab. You cannot remove the default fields or change their database definitions (column names, data types, size etc.). Add a unique prefix as a naming convention in the Field name of any custom fields. The prefix prevents conflicts with fields that Kentico may add in the future. When you save the custom class field, the system creates a custom column in the corresponding database table. During upgrades, the system merges the database definitions for customizable classes. The default fields may be updated and overwritten, but the custom fields are preserved. - Customization of database table indexes is supported, but may require additional maintenance during upgrades: - You can drop the default indexes and create custom indexes for tables. You need to perform custom index operations manually in the database (via scripts or SQL Server Management Studio). - Use a unique naming convention for your custom indexes and maintain documentation to keep track of the changes. - The SQL script performed by upgrades may fail if the system attempts to create an index that is not compatible with your custom indexes. For example, if you drop a table's default clustered index and create your own, the SQL upgrade may fail if it attempts to update or recreate the default clustered index. - After applying an upgrade, review each table with custom indexes and make sure the indexes are still relevant and fulfill your requirements. Adding custom database tables If you need to store data in a custom table within the Kentico database, use the administration interface to create one of the following objects: - Custom class (under a Custom module) – the best option for fully integrating the data into Kentico. - Page type – intended for data that you wish to store as pages in the website's content tree. - Form – suitable for data that you wish to collect from the site's visitors. - Custom table – only use if you need to store and edit simple data structures without the need to create a custom module and define an editing interface. Otherwise, custom module classes are recommended instead. See Defining website content structure if you need help deciding which approach is the best for you. Note: If you wish to define custom fields that reference other Kentico objects (i.e. foreign keys), you need to use custom module classes. See Adding references between classes. In all cases, the system automatically creates a database table based on the options that you configure. Any fields (columns) that you define for the table remain unchanged during upgrades. In rare cases, the upgrade may add new general fields required by the system (such additions should not break or affect the table's functionality). Important When creating objects representing custom database tables (such as custom classes, page types, forms, etc.), always use a unique prefix (namespace) in the code name of the object and the matching table name. This convention prevents conflicts with objects and tables that Kentico may add in the future. Never use the cms, com, om or content prefixes for custom objects or database tables. The best option is to use your company name or an abbreviation as the prefix, for example: ACME_MyTable Customizing Kentico database objects (stored procedures, views, functions, etc.) - Do NOT directly modify the default Kentico database objects. Upgrades can overwrite any database object and the customizations will be lost. - You can add custom database objects. Always use a unique prefix or other naming convention for custom database objects. The prefix prevents conflicts with objects that Kentico may add in the future. - If you need to use a modified version of a Kentico database object, create your own custom object and copy the code from the original (use a unique naming convention). Then make any required modifications and ensure that your custom functionality uses the changed version of the database object. If you need to create a custom View or Stored procedure, but do not have direct access to the database, you can use the Database objects application in the Kentico administration interface. This approach is equivalent to creating or scripting the object manually in the database. Note: Do NOT use the Database objects application to edit the default views or procedures. Default data Each installation of Kentico automatically includes a set of default objects. These objects serve as examples of Kentico functionality and in some cases are important components of the system. The following is a list of object types whose default objects are "owned by the system": Default objects that are all overwritten during every upgrade: - Web parts - Web part layouts - Widgets - Reports (for example used by Online marketing, Web analytics and E-commerce) - Time zones Default objects that can be individually overwritten by any upgrade or hotfix: - Form controls - UI elements (managed when editing Modules on the User interface tab) Object types with a specific subset of default objects that are "owned by the system": - Page templates – all default templates in the UI templates category are critical system objects. - Page types – the following page types are integral parts of the system: - Root (CMS.Root) - File (CMS.File) - Page (menu item) (CMS.MenuItem) Chat - Transformations (Chat.Transformations) All default transformations and queries stored under the given page types are also considered system objects. You can however add new queries or transformations under the system page types without problems. To avoid problems during upgrades, handle the default objects listed above according to the following rules: - Do NOT edit or delete any of the listed default objects. Many of the objects are crucial components that are required for the system and administration interface to work correctly. - If you need to modify one of the default objects, create your own copy of the original object instead (in many cases you can use the clone feature). Then make the changes to your custom object and use it for the required purpose. - If you cannot avoid making changes directly to one of the default Kentico objects, you need to assume that any upgrade or hotfix will overwrite your customizations. Maintain detailed documentation of all customizations so you can manually replicate them after an upgrade. - You can create your own objects of the listed types without any problems. Upgrades only overwrite the default objects. For example, upgrades overwrite changes that you make to the default web parts, but any custom web parts that you create will not be affected. - If you need to modify the user interface of the default Kentico applications, do NOT use the Customize option for default UI elements. Such changes can be lost during upgrades. Instead, add your own custom UI elements and then use the resulting interface instead of the original: - Create a custom module in the Modules application. - Add UI elements on the module's User interface tab. - All custom UI elements must be assigned to a custom module. - You can copy the settings of the original UI elements that you want to customize and then make your changes. - Either add the custom UI elements under existing elements or create an entire custom application in the CMS -> Administration -> Custom section of the UI element tree. - See the Creating custom modules documentation for more information. Other default objects In rare cases, specific upgrades or hotfixes may also overwrite, delete or convert other types of objects. To minimize the risk of losing changes made to default objects, we recommend taking the following steps, even for object types that are not listed above (for example Email templates): - Maintain documentation of all changes that you make to default objects - Carefully check the instructions for each upgrade or hotfix version before applying Physical files and code changes Use the following general rules when working with files in the Kentico web project: Avoid modifications of the default Kentico files whenever possible. Adding of new custom files is preferable and easier to maintain through upgrades. Kentico provides a customization model that allows you to implement various scenarios by adding custom classes (for example Event handling or Provider customization). - Do NOT use Kentico API that is marked as obsolete. Such API will most likely be removed in the next version of Kentico, and your code will stop working. - If you need to execute SQL queries from code, avoid hardcoding of the query text. Hardcoded queries can cause errors if the underlying database structure changes. If possible, use the Kentico data engine API to generate your queries (ObjectQuery, DocumentQuery, DataQuery). Maintain documentation to keep track of your custom files and modifications made to the default files. Tip: A good way to keep track of custom files and file modifications is to create a parallel web project next to your Kentico project. Start with an empty web application project and add (as links) any new or customized files from the main project. Recreate the Kentico folder structure as necessary to organize the files. Adding custom files Adding of custom files into the Kentico project is a necessary part of many customization scenarios. For example, you need to add files when: - Defining custom objects or functionality (such as web parts, scheduled tasks, smart search indexes, custom macro method containers, etc.) - Performing initialization code (such as assigning handlers to events) We recommend adding custom files into the project's directories based on the Export folder structure. These locations allow the system to automatically export files along with related database objects. When adding code files (classes), you can choose between two different approaches: - (Preferred) Create the files as part of a custom project (library). Then add the project to the Kentico solution and connect it through references. – OR – Add the files directly into the Kentico project. Use the App_Code folder for web site projects. Advantages of custom code projects Using separate projects (libraries) for custom code has the following advantages: - Cleaner separation of custom code from the default code of the Kentico web project. - Compilation performance – the code of a separate project is compiled into a DLL and does not require runtime compilation that slows down the web project. - Better accessibility of your custom classes from external applications or projects (for example projects running automated tests). - Easier re-usability across multiple projects. Maintaining references between Kentico and custom projects When performing upgrades, references from the Kentico projects (CMS, CMSApp) to your custom projects are preserved. Upgrades merge any new content in the corresponding .csproj files with your custom content (such as references). However, references from custom projects to Kentico libraries (DLLs) need to be added again after performing an upgrade. The change in the versions of the Kentico DLLs breaks the original references. Custom files that you add are not directly affected by upgrades. However, you still need to check each custom file after performing an upgrade: - Make sure the function performed by the file is still relevant for the new Kentico version (read the release notes and upgrade instructions). - Update any Kentico API that you call in code files to be compatible with the latest version. We recommend using the code upgrade tool and/or the list of API changes. Modifying default files in the Kentico project If you cannot avoid customizing one or more of the default files in the CMS web site project or CMSApp web application project: - Add comments and/or regions to clearly identify your custom code within the default Kentico code. This makes it easier to keep track of your changes and allows you to use the code upgrade tool more efficiently. - During an upgrade, the system automatically detects modified files and creates new versions of them with the new extension. You need to manually merge your customizations into the new version of the file (use Visual Studio or another comparison and merging tool). - You need to manually ensure that any Kentico API you call in your custom code sections is up-to-date. We recommend using the code upgrade tool and/or the list of API changes. The following are guidelines for common customization scenarios related to the default files: - Web.config -- you can directly edit your project's web.config file and add any required configuration options. Upgrades attempt to automatically merge your web.config customizations with any changes introduced by the new version. If the automatic merge fails due to incompatible configuration, a separate web.config file with the .new extension is created and you need to combine the file content manually. - Global.asax – do NOT edit or add content to the Global.asax file in the Kentico project. If you wish run code at specific points within the application life cycle, use the customization model to assign handlers of the appropriate Kentico events (ApplicationEvents, RequestEvents). See Reference - Global system events. Administration interface customizations – if you need to customize files that affect the default Kentico administration interface, you can edit them directly within the project: - UniGrid XML definitions used for listing pages - typically stored as ~/App_Data/CMSModules/<module name>/UI/Grids/<object type>/default.xml - Web form pages used for UI elements with manually defined content - typically stored in ~/CMSModules/... Note: Avoid customizations of the default administration interface pages when possible. The recommended approach is to create your own UI elements and then use the resulting interface instead of the original (see the Default data section). Changing the project structure Upgrades must be applied to complete Kentico projects that use the standard folder structure (including the solution file, GlobalAssemblyInfo.cs, the CMS and Lib sub-folders). For example, you cannot directly upgrade web site deployments that only consist of the CMS folder. If you wish to run a Kentico project with an incomplete or modified folder structure, you need to use the following development and upgrade process: - Maintain a development version of the project with the original complete folder structure. - Prepare your modified version of the project and use it to deploy your production website. - Apply upgrades to the development version of the project. After an upgrade is successfully completed, prepare a new version of the modified project and redeploy your website. Using jQuery Do NOT use the default jQuery provided in Kentico projects for your own client scripts. Newer versions of Kentico may contain a different version of jQuery, so your scripts may not work correctly after upgrading. Best practice: Add, link and maintain your own jQuery library within the Kentico project. This gives you full control over the jQuery version and helps protect your custom scripts from breaking when upgrading Kentico. Note: The Kentico jQuery is registered in No-Conflict mode under the $cmsj alias. Was this page helpful?
https://docs.kentico.com/k10/custom-development/best-practices-for-customization
CC-MAIN-2018-39
refinedweb
2,545
53.61
I have CDH 5.1 installed on a 5 node cluster. I am building up a spark program from a series of REPL commands but am experiencing unexpected behaviour the commnads are as follows case class Reading(accountId: String, senderId: String, sensorId: String, metricName: String , readTime: Long , value: Double) var r2 =Reading("sss","fff","FGGF","hjjj", 232L, 22.3) import scala.collection.mutable.ListBuffer var readings = ListBuffer[Reading]() readings.append(r2) The last line thows a mismatch error <console>:18: error: type mismatch; found : Reading required: Reading readings.append(r2) This works as expected from a standalone instance of spark and scala on an Ubuntu box , CDH is installed on Centos where java versions differ , Centos uses oracle jdk, whilst Ubuntu uses OpenJDK . I have tried the code on several instances of CDH that we have here locally and the issue is the same, I would expect the spark-shell repl to have full scala functionality , would this be a valid assumption ? If some else could try the same commands on a CDH instance I would be grateful to know if it worked as expected or not vr Hugh McBride
https://community.cloudera.com/t5/Support-Questions/Simple-Scala-code-not-working-in-Spark-shell-repl/td-p/81082
CC-MAIN-2019-35
refinedweb
190
60.45
, then save it. Example 4-1 defines a class named Book to represent entities of the kind Book. It creates an object of this class by calling the class constructor, then sets several property values. Finally, it calls the put() method to save the new entity to the datastore. The entity does not exist in the datastore until it is put() for the first time. Example 4-1. Python code to create an entity of the kind Book from google.appengine.ext import db import datetime class Book(db.Expando): pass obj = Book() obj.title = 'The Grapes of Wrath' obj.author = 'John Steinbeck' obj.copyright_year = 1939 obj.author_birthdate = datetime.date(1902, 2, 27) obj.put() The Book class inherits from the class Expando in App Engine’s db package. The Expando base class says Book objects can have any of their properties assigned any value. The entity “expands” to accommodate new properties as they are assigned to attributes of the object. Python does not require that an object’s member variables be declared in a class definition, and this example takes advantage of this using an empty class definition—the pass keyword indicates the empty definition—and assigns values to attributes of the object after it is created. The Expando base class knows to use the object’s attributes as the values of the corresponding entity’s properties. The Expando class has a funny name because this isn’t the way the API’s designers expect us to create new classes in most cases. Instead, you’re more likely to use the Model base class with a class definition that ensures each instance conforms to a structure, so a mistake in the code doesn’t accidentally create entities with malformed properties. Here is how we might implement the Book class using Model: class Book(db.Model): title = db.StringProperty() author = db.StringProperty() copyright_year = db.IntegerProperty() author_birthdate = db.DateProperty() The Model version of Book specifies a structure for Book objects that is enforced while the object is being manipulated. It ensures that values assigned to an object’s properties are of appropriate types, such as string values for title and author properties, and raises a runtime error if the app attempts to assign a value of the wrong type to a property. With Model as the base class, the object does not “expand” to accommodate other entities: an attempt to assign a value to a property not mentioned in the class definition raises a runtime error. Model and the various Property definitions also provide other features for managing the structure of your data, such as automatic values, required values, and the ability to add your own validation and serialization logic. It’s important to notice that these validation features are provided by the Model class and your application code, not the datastore. Even if part of your app uses a Model class to ensure a property’s value meets certain conditions, another part of your app can still retrieve the entity without using the class and do whatever it likes to that value. The bad value won’t raise an error until the app tries to load the changed entity into a new instance of the Model class. This is both a feature and a burden: your app can manage entities flexibly and enforce structure where needed, but it must also be careful when those structures need to change. Data modeling and the Model class are discussed in detail in Chapter 7. The Book constructor accepts initial values for the object’s properties as keyword arguments. The constructor code earlier could also be written like this: obj = Book(title='The Grapes of Wrath', author='John Steinbeck', copyright_year=1939, author_birthdate=datetime.date(1902, 2, 27)) As written, this code does not set a key name for the new entity. Without a key name, the datastore generates a unique ID when the object is saved for the first time. If you prefer to use a key name generated by the app, you call the constructor with the key_name parameter: obj = Book(key_name='0143039431', title='The Grapes of Wrath', author='John Steinbeck', copyright_year=1939, author_birthdate=datetime.date(1902, 2, 27)) Because the Python API uses keyword arguments, object attributes, and object methods for purposes besides entity properties, there are several property names that are off-limits. For instance, you cannot use the Python API to set a property named key_name, because this could get confused with the key_name parameter for the object constructor. Names reserved by the Python API are enforced in the API, but not in the datastore itself. Google’s official documentation lists the reserved property names. The datastore reserves all property names beginning and ending with two underscores (such as __internal__). This is true for the Python API and the Java API, and will be true for future APIs as well. The Python API ignores all object attributes whose names begin with a single underscore (such as _counter). You can use such attributes to attach data and functionality to an object that should not be saved as properties for the entity. The complete key of an entity, including the key name and kind, must be unique. (We’ll discuss another part to keys that contributes to a key’s uniqueness, called ancestors, in Chapter 6.) If you build a new object with a key that is already in use, then try to save it, the save will replace the existing object. For when you don’t want to overwrite existing data, the datastore API provides an alternate way to create an object. The get_or_insert() class method takes a key name and either returns an existing entity with that key name, or creates a new entity with that key name and no properties and returns it. Either way, the method is guaranteed to return an object that represents an entity in the datastore: obj = Book.get_or_insert('0143039431') if obj.title: # Book already exists. # ... else: obj.title = 'The Grapes of Wrath' obj.author = 'John Steinbeck' obj.copyright_year = 1939 obj.author_birthdate = datetime.date(1902, 2, 27) obj.put()
https://www.safaribooksonline.com/library/view/programming-google-app/9780596157517/ch04s02.html
CC-MAIN-2016-50
refinedweb
1,014
54.83
Examine MNIST Dataset from PyTorch Torchvision Examine the MNIST dataset from PyTorch Torchvision using Python and PIL, the Python Imaging Library < > Code: Transcript: This video will show how to examine the MNIST dataset from PyTorch torchvision using Python and PIL, the Python Imaging Library. The MNIST dataset is comprised of 70,000 handwritten numerical digit images and their respective labels. There are 60,000 training images and 10,000 test images, all of which are 28 pixels by 28 pixels. First, we import PyTorch. import torch Then we print the PyTorch version we are using. print(torch.__version__) We are using PyTorch 0.3.1.post2. Now that we have PyTorch available, let's load torchvision. import torchvision Torchvision is a package in the PyTorch library containing computer-vision models, datasets, and image transformations. Since we want to get the MNIST dataset from the torchvision package, let's next import the torchvision datasets. import torchvision.datasets as datasets First, let's initialize the MNIST training set. mnist_trainset = datasets.MNIST(root='./data', train=True, download=True, transform=None) We already have the files downloaded, so that was pretty fast. Next, we initialize the MNIST test set. mnist_testset = datasets.MNIST(root='./data', train=False, download=True, transform=None) Now, let's examine what the MNIST train set and the MNIST test set Python variables have. First, let's check the number of items in each Python variable. For the MNIST train set, we use the Python len function to get the number of items. len(mnist_trainset) We see that the variable has 60,000 items which is what we expect as the MNIST training set is comprised of 60,000 images. For the MNIST test set, we again use the Python len function to get the number of items. len(mnist_testset) We see that the variable has 10,000 items which is what we expect as the MNIST test set is comprised of 10,000 images. Next, let's explore what those items actually are. We'll look at the first item in the MNIST train set variable. mnist_trainset[0] We see two things - a PIL image item, then a comma, and a number. Remember that Python is a zero-based index language so it uses zero instead of the number one. This is the zero and this is where the PIL image is. We can check the type of this item to figure out what it is. type(mnist_trainset[0]) It tells us that this is a Python tuple. Python tuples are a sequence of immutable Python objects. In this case, it's a two-element sequence where the first element is a PIL image and the second is an integer. Let's use the Python variable assignment convention to get the image and integer into two separate Python variables. train_image_zero, train_target_zero = mnist_trainset[0] The first element of the tuple goes to the Python variable train_image_zero. The second element of the tuple goes to the Python variable train_target_zero. Because we're using Python 3.6.4 and Anaconda, and Conda as our package manager, we already have PIL available to us. So let's look at the image using PIL show operation. train_image_zero.show() This opens the image viewer on my Mac and shows the train_image_zero image which does indeed look like the handwritten number five. We can then confirm what the label or target is for this image by checking to see what the train_target_zero Python variable contains. print(train_target_zero) We get the number five. Let's do another check, only this time, let's use the test set to see what we get. test_image_eighty, test_target_eighty = mnist_testset[79] We look at the image first. test_image_eighty.show() It looks like a handwritten number seven. Let's check the target now. print(test_target_eighty) And it's the number seven. Brilliant! We were able to examine the MNIST dataset from PyTorch torchvision using Python and PIL, the Python Imaging Library.
https://aiworkbox.com/lessons/examine-mnist-dataset-from-pytorch-torchvision
CC-MAIN-2019-51
refinedweb
657
73.88
Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video. Completing the “Activity” Field Drop Down List4:33 with James Churchill Now that we’ve seen how to work with drop down lists, let’s wrap up work on the “Activity” field. Follow Along To follow along, you’ll need to go back a step, as this video is a continuation of the previous video. Additional Learning If you want to learn more about dynamic types in C# or need a refresher, see this page on MSDN. - 0:00 Now that we've seen some examples of how to create items for - 0:03 the drop down list for method using temporary data, - 0:06 let's work on the actual implementation by updating our action methods. - 0:12 I'll add a property on the ViewBag object ActivitiesSelectListItems - 0:18 and set it to an instance of SelectList. - 0:22 Passing in the Data.Data.Activites, - 0:28 static collection. - 0:31 And the names of the properties for the value, And text fields. - 0:40 This looks odd, but it's correct. - 0:43 The first Data is the namespace for our data static class. - 0:47 Let's also remove this line of code that's setting the ActivityId property. - 0:53 Drop down list items don't automatically repopulate on a post back, so - 0:57 we also need to set this ViewBag property in our post action method. - 1:01 I'll just copy and paste this line of code from here. - 1:11 Down to here. - 1:12 And I'll remove our line of code that is setting the entry.ActivityId property. - 1:18 Now, let's update our view. - 1:20 To start with, we can remove all of this temporary code. - 1:30 Then we just need to update our call to the DropDownListFor - 1:36 method to use our new ViewBag property. - 1:40 ViewBag.ActivitiesSelectListItems. - 1:49 The only thing that's tricky here is that we need to explicitly cast - 1:53 the ViewBag property to its actual type of select list. - 1:57 That's necessary because ViewBag is a dynamic object. - 2:05 Let's run our app and test our changes. - 2:11 And here's our list of available activities. - 2:16 What if we wanted to insert an empty item as the first item so - 2:20 users would need to select a value? - 2:22 Turns out, there's a method overload that makes this easy to do. - 2:27 We can add an empty string, just after the SelectList parameter, and - 2:31 the DropdownListFor method will create a default empty item. - 2:39 We could supply a prompt for our value. - 2:42 Something like Select an Activity, but I prefer to use an empty string. - 2:48 Also it's worth noting that if you pass in null for - 2:51 the value, MVC won't create the default empty item. - 2:55 You need to pass a string value, save the view, and refresh the page. - 3:01 And now the empty item is selected by default, - 3:04 if we right-click on the drop-down list and - 3:06 select the inspect menu item, we can see what our controls markup looks like. - 3:13 The first option is our default empty item. - 3:19 The remaining items are the available activities that we can select from. - 3:23 The value attributes represent the activity ID values, and - 3:27 the option element inner text is populated with the activity name values. - 3:33 When the form is submitted to the server, the selected items value attribute, - 3:37 is used for the activity ID form fields value. - 3:40 It's worth noting, that when we save an entry, - 3:43 we only have the activity ID value on hand, not the activities name. - 3:48 We don't need the activity name, until we display the entry on the list page. - 3:53 This might be surprising the first time you see this approach in use. - 3:56 But it's a very common way of handling related data. - 4:00 Go ahead and stop the app. - 4:03 If you're using GitHub let's commit our changes. - 4:10 Enter a commit message of, - 4:13 Updated the "Activity" field to use a drop - 4:18 down list, and click the Commit All button. - 4:26 In the next video, we'll continue with improving our form - 4:29 by updating the intensity field to use radio buttons.
https://teamtreehouse.com/library/completing-the-activity-field-drop-down-list
CC-MAIN-2019-43
refinedweb
787
72.36
I have a base "fishnet" polygon grid. I attempted to create a model that iterates over each cell in that base fishnet grid and subdivide that cell with the Create Fishnet tool into a new feature class. I expected that I simply would need to set the output from my iterate feature iterator as the 'Template Extent' parameter for the Create Fishnet tool. However, while I can see the name of this iterator output model variable in the drop-down list for the 'Template Extent' parameter; the name does not have the blue Model Variable icon. And more importantly, the template extent does not update at each model iteration. Is there a way that I can make my model recognize aan iteration output as a template extent? ( see screenshot below) [ATTACH=CONFIG]19323[/ATTACH] import arcgisscripting gp = arcgisscripting.create(9.3) #you will need to modify these two parameters for your situation. This is an ex of a pgdb FeatureClass inputLocation = "\\\\C:\Scratch.mdb" inputFC = inputLocation + "\\exGRID" # Open a search cursor on a feature class rows = gp.searchcursor(inputFC) row = rows.Next() i = 1 while row: gp.AddMessage("Attempting to process polgyon " + str(i)) #Get the shape field shape = row.shape #Get the extent object extent = shape.extent outputName = "Fishnet_" + str(i) outFC = inputLocation + "\\" + outputName #Get the origin (lowerLeft) and y-axis (upperLeft) properties of the polygon ll = extent.lowerleft ul = extent.upperleft ur = extent.upperright originXY = str(ll.x) + " " + str(ll.y) yaxisXY = str(ul.x) + " " + str(ul.y) opp_corner = str(ur.x) + " " + str(ur.y) gp.AddMessage("LowerLeft (x,y): %f, %f" % (ll.x, ll.y)) gp.AddMessage("UpperLeft (x,y): %f, %f" % (ul.x, ul.y)) gp.AddMessage("XMin: %f" % (extent.xmin)) gp.AddMessage("YMin: %f" % (extent.ymin)) gp.AddMessage("XMax: %f" % (extent.xmax)) gp.AddMessage("YMax: %f" % (extent.ymax)) #keep the cell width/height set to zero as it will use the opp_corner to figure it out cellWidth = 0 cellHeight = 0 #plug in the #rows/#cols you want the output grids to contain nrows = 10 ncols = 10 gp.CreateFishnet_management(outFC, originXY, yaxisXY, cellWidth, cellHeight, nrows, ncols, opp_corner) gp.AddMessage("Created " + outputName) i = i + 1 row = rows.Next()
https://community.esri.com/t5/geoprocessing-questions/how-to-use-an-iterator-to-set-the-template-extent/td-p/71452?attachment-id=41861
CC-MAIN-2022-40
refinedweb
361
52.56
This action might not be possible to undo. Are you sure you want to continue? 03/21/2013 text original BUS RESERVATION SYSTEM Submitted in partial fulfillment for the Award of degree of Post Graduate Diploma In Information Technology (2008-10) Submitted By: BRIJ MOHAN DAMMANI 200852200 Submitted to: Symbiosis Centre for Distance Learning, Pune 411016, Maharashtra, India ACKNOWLEDGEMENT A project like this takes quite a lot of time to do properly. As is often the case, this project owes its existence and certainly its quality to a number of people, whose name does not appear on the cover. Among them is one of the most extra ordinary programmers it has been my pleasure to work with Mr. Ankur Kaushik, who did more than just check the facts by offering thoughtful logic where needed to improve the project as a whole. We also thank to Mr. Sh. Hardayal Singh (H.O.D. -MCA Deptt. Engineering College Bikaner) who deserves credit for helping me done the project and taking care of all the details that most programmers really don’t think about. Errors and confusions are my responsibility, but the quality of the project is to their credit and we can only thank them. We are highly thankful and feel obliged to Milan Travels staff members for nice CoOperation and valuable suggestions in my project work. We owe my obligation to my friends and other colleagues in the computer field for their co-operation and support. We thank God for being on my side. Contents Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Introduction Development model System Study Project Monitoring System System Analysis Operating Environment System Design System Testing System Implementation Conclusion Scope of the Project Introuction. Development model Software Process Model Our project life cycle uses the waterfall model. Information Engineering encompasses requirements gathering at the strategic business level and at the business area level. 2. System/Information Design Analysis Engineering Code Test The Waterfall Model The waterfall model encompasses the following activities: 1. System/information Engineering and Modeling System Engineering and Analysis encompass requirements gathering at the system level with a small amount of Top-level design and analysis. also known as classic life cycle model or linear sequential model. Software requirements analysis Software requirements analysis involves requirements for both the system and the software to be document and reviewed with the customer. . conducting test to uncover errors and ensure that define input will produce actual results that agree with required results. System Study . and on the functional externals. 6. Testing Once code has been generated. Support Software will undoubtedly undergo change after it is delivered to the customer. because the software must be adapted to accommodate changes in its external environment or because the customer requires functional or performance enhancements. 5. program testing begins. software architecture. Change will occur because errors have been encountered. The testing focuses on the logical internals of the software.3. Design Software design is actually a multi-step process that focuses on for distinct attributes of a program: data structure. The design process translates requirements into a representation of the software that can be accessed for quality before coding begins. Code Generation Code-Generation phase translates the design into a machine-readable form. interfaces representation and procedural detail. 4. that is. ensuring that all statement have been tested. cost. 3.1 Gathering Information Necessary for Scope The most commonly used technique to bridge communication gap between customer and the software developer to get the communication process started is to conduct a preliminary meeting or interview.2 Software Scope The first activity in software project planning is the determination of software scope. and the time that will elapse from start to finish. 3. the resource that will be required. These estimates are made within limited time frame at the beginning of a software project and should be updated regularly as the project progresses. interfaces. there were two other persons out of one was the technical adviser and another one was the cost accountant. In addition. constraints. and reliability. Software scope describes the data and control to be processed. and schedule. performance. Neither of us knows what to ask or say. estimates should attempt to define best case and worst case scenarios so that project outcomes can be bounded. . function. it becomes necessary to estimate the work to be done.Before the project can begin.2.1 Project planning objectives The objective of software project planning is to provide a framework that enables the management to make reasonable estimates of resources. During making such a plan we visited site many more times. we were very much worried that what we say will be misinterpreted. When I visited the site we have been introduced to the Manager of the center. 3. We started to asking context-free questions; that is, a set of questions that will lead to a basic understanding of the problem. The first set of context-free questions was like this: What do you want to be done? Who will use this solution? What is wrong with your existing working systems? Is there another source for the solution? • Can you show us (or describe) the environment in which the solution will be used? After first round of above asked questions. We revisited the site and asked many more questions considering to final set of questions. • Are our questions relevant to the problem that you need to be Are we asking too many questions? Should we be asking you anything else? solved? • • 3.2.2 Feasibility Not everything imaginable is feasible, not even in software. Software feasibility has four dimensions: Technology—is a project technically feasible? Is it within the state of the art? Finance – Is it financially feasible? Time—will the project be completed within specified time? Resources—does the organization have the resources needed to succeed? After taking into consideration of above said dimensions, we found it could be feasible for us to develop this project. 3.3 Software Project Estimation Software cost and effort estimation will never be an exact science. Too may variables—human, technical, environmental, political—can affect the ultimate cost of software and effort applied to develop it. However, software project estimation can be transformed a black art to a series of systematic steps that provide estimates with acceptable risk. To achieve reliable cost and effort estimates, a number of options arise: 1. Delay estimation until late in the project (since, we can achieve 100% accurate estimates after the project is complete!) 2. Base estimates on similar projects that have already been completed. 3. Use relatively simple decomposition techniques to generate project cost and effort estimates. 4. Use one or more empirical models for software cost and effort estimation. the software project estimation. Ideally, the techniques noted for each option be applied in tandem; each used as cross check for the other. Decomposition techniques take a “divide and conquer” approach to software project estimation. By decomposing a project into major functions and related software engineering activities, cost and effort estimation can be performed in the stepwise fashion. Empirical estimation models can be used to complement decomposition techniques and offer a potentially valuable estimation approach in their own right. A model based on experience (historical data) and takes the form D = f (vi) Where d is one of a number of estimated values (e.g., effort, cost, project duration and we are selected independent parameters (e.g., estimated LOC (line of code)). Each of the viable software cost estimation options is only as good as the historical data used to seed the estimate. If no historical data exist, costing rests on a very shaky foundation. Project Monitoring System 4.1 PERT Chart: Program evaluation and review technique (PERT) and critical path method (CPM) are two project scheduling methods that can be applied to software development. These techniques are driven by following information: • Estimates of Effort • A decomposition of the product function • The selection of the appropriate process model and task set • Decomposition of tasks PERT chart for this application software is illustrated in figure 3.1. The critical Path for this Project is Design, Code generation and Integration and testing. Start Requirement Analysis May 17, 2010 Design May 24, 2010 Integration and test July 20, 2010 Coding June 10, 2010 Finish Aug 15, 2010 Documentation and Report Aug 1, 2010 Figure 4.1 PERT charts for “Bus Reservation System”. d2 Wk1. more Milestone: Product statement defined Wk1.d2 Wk1. Work tasks Planned Actual start start Planned complete Actual Complete Notes 1.d5 is time consuming.d3 Wk2.d3 Wk1.1 Identify needs and benefits Meet with customers Identified needs and constraints Established Product Statement Wk1.d1 Wk2.4 Isolation software elements Coding Wk5.2 Gantt Chart: Gantt chart which is also known as Timeline chart contains the information like effort.d3 Analysis and design Wk2. 2010.d3 Wk1.d5 Wk4.d1 Wk5.2 Defined Desiredoutput/control/input (OCI) Scope modes of interacton Documented (OCI) FTR: reviewed OCI with customer Revised OCI as required Milestone: OCI defined 1.d2 Wk2.d3 Wk4.d2 Wk1.d3 Wk1.d3 1.4. start date.d1 Wk3.d1 Wk4.2 we have shown the Gantt chart for the project.d3 Wk1.d5 .d1 Wk1. A timeline chart can be developed for the entire project.d1 Wk1.d1 Wk6.d3 Wk1.3 Defined the function/behavior Milestone: Data Modeling completed Wk5. Start: May 17.d3 Wk3. All project tasks have been listed in the left-hand column.d5 W7.d2 Wk4.d2 Wk1.d2 Wk1. Below in figure 4. completion date for each task.d3 Wk1. duration.d1 Wk5.d2 Wk1.d2 1. 2010 Figure: 4.2 Gant chart for the Bus reservation System. d1—day1. Note: Wk1—week1.d1 Wk7.d6 W11.Reports 1. .d6 W9.d3 Finish: Aug 15.5 Integration and Testing W9.d3 W8. Each analysis method has a unique point of view. 5. By applying these principles. we approach the problem systematically.System Analysis Software requirements analysis is a process of discovery. Partitioning is applied to reduce complexity. Models are used so that the characteristics of function and behavior can be communicated in a compact fashion. Requirement analysis proves the software designer with a representation of information. architectural interface. The 4. Essential and . function. and specification. The models that depict information function and behavior must be partitioned in a manner that uncovers detail in layered (or hierarchical) fashion.1 Analysis Principles Over the past two decades. The behavior of the software (as a consequence of external events) must be represented. 3. modeling. information domain is examined so that function may be understood more completely. To perform the job properly we need to follow as set of underlying concepts and principles of Analysis. 5. However. a large number of analysis modeling methods have been developed. all analysis methods are related by a set of operational principles: 1. The information domain of a problem must be represented and understood. Investigators have identified analysis problems and their caused and have developed a variety of modeling notations and corresponding sets of heuristics to overcome them. and component -level designs. The analysis process should move from essential information toward implementation detail. refinement. 2. The functions that the software is to perform must be defined. and behavior that can be translated to data. 1 The Information Domain All software applications can be collectively called data processing. that is.We have tried to takes above said principles to heart so that we could provide an excellent foundation for design. The information domain contains three different views of the data and control as each is processed by a computer program: (1) information contend and relationships (the data model) (2) information flow. and (3) Information structure. The first operational analysis principle requires an examination of the information domain and the creation of a data model. To fully understand the information domain.implementation vies of the software are necessary to accommodate the logical constraints imposed any processing requirements and the physical constraints imposed by other system elements. to transform data from one form to another. each of these views should be considered. and produce output. 5. ground run. no of hour flying and so forth. Software is built to process data. Similarly. Status declare is a composite of a number of important pieces of data: the aircraft’s name. the content of a control object called System status might be defined by a string of bits. the content of Status declares is defined by the attributes that are needed to create it. Each bit represents a . For example. This fundamental statement of objective is true whether we build batch software for a payroll system or realtime embedded software to control fuel flow to an automobile engine. to accept input. Therefore. the data object. the aircraft’s model.1. Information content represents the individual data and control objects that constitute some larger collection of information transformed by the software. manipulate it in some way. Along this transformation path. For example.1 Information flow and transformation.g. Data and control that move between two transformations define the interface for each function. input objects are transformed to intermediate information (data and / or control).. Figure 5.1.separate item of information that indicates whether or not a particular device is onor off-line. period left for the maintenance of aircraft an others. which is further transformed to output. a disk file or memory buffer). Referring to figure 6. additional information may be introduced from an existing date store ( e. Input Objects Transfor m #1 Intermediate data and control Transfo rm #2 Output Object(s) Data/Contro l Store . Data and control objects can be related to other data and control objects. the date object Status declare has one or more relationships with the objects like total no of flying. The transformations applied to the date are functions or sub functions that a program must perform. Information flow represents the manner in which date and control change as each moves through a system. A computer program always exists in some state.e..2 Modeling The second and third operational analysis principles require that we build models of function and behavior.. until a through delineation of all system functionality is represented.g. Most software responds to events from the outside world. This stimulus/response characteristic forms the basis of the behavioral model. For example.5. Functional models. and in order to accomplish this. in our case the project will remain in the wait state until: • We click OK command button when first window appears • An external event like mouse click cause an interrupt and consequently main window appears by asking the username and password. Software transforms information. printing. it must perform at lease three generic functions: • Input • Processing • And output. Behavioral models. more and more functional detail is gathered. computing. and polling) that is changed only when some even occurs. The functional model begins with a single context level model (i. the name of the software to be built).an externally observable mode of behavior (e. Over a series of iterations. waiting. . • This external system (providing password and username) signals the project to act in desired manner as per need.1. A behavioral model creates a representation of the states of the software and the events that cause software to change state. 5.2 Partitioning (Divide) Problems are often too large and complex to be understood as a whole. Conceptually. partitioning decomposes problem intoits constituent parts. and behavioral domains of software can be partitioned. To issulstate these partitioning approaches let us consider our project “Bus Reservation System”. se tend to partition (divide) such problems into parts that can be easily under stood and establish interfaces between the part so that overall function can be accomplished. functional. Horizontal partitioning: Bus Reservation System . for this reason. In essence.1. Horizontal partitioning and vertical partitioning of Bus Reservation system is shown below. The fourth operational analysis principle suggests that the information. we establish a hierarchical representation of function or information and then partition and uppermost element by (1) (2) exposing increasing detail by moving vertically in the Functionally decomposing the problem my moving hierarchy or horizontally in the hierarchy. Vertical partitioning of Bus Reservation System function: Bus Reservation System Configure system Username and Password Acceptance Rejection Interact with user Fail Retry . administration and maintenance) only. the software (Bus Reservation System) used to program and configure the system.System configuration Password acceptance Interact with user During installation. A master password is programmed for getting in to the software system. After this step only user can work in the environments (right cornor naming operation. NET Framework 3.5MHs and Above • • 512 MB of Random Access Memory and Above 80 GB Hard Disk Software Specification: Environment: .4GHz and Above • 2 GB of Random Access Memory and Above • 160 GB Hard Disk Client Side: • Pentium-IV 1. Notepad ++ OS: Windows server 2003 R2. IE8. such as word processors and accounting packages.5 Technologies: ASP.5 6. Windows XP SP2 Browser: IE7.1 Front-end Environment (. are modeled as stand-alone applications: they offer users the capability to perform tasks using data .NET Framework) The Internet revolution of the late 1990s represented a dramatic shift in the way individuals and organizations communicate with each other. FF 3. C# Database: MS Access Software: Visual Studio 2008.1 Hardware Specification: Server Side: • Core 2 Due 2. Traditional applications.Operating Environment 6.2.NET. Essentially. and individual expression (through Web logs. collaboration (through e-mail and instant messaging). also known as Blogs.NET Framework The . Microsoft . Benefits of the . the .NET Framework is a software component that is a part of several Microsoft Windows operating systems. Most new software. and e-zines — Web based magazines). The .stored on the system the application resides and executes on. The .NET Framework offers a number of benefits to developers: • • • • A consistent programming model Direct support for security Simplified development efforts Easy application deployment and maintenance The . the primary role of most new software is changing into supporting information exchange (through Web servers and browsers). is modeled based on a distributed computing model where applications collaborate to provide services and expose functionality to each other. in contrast. The .NET Framework is the first platform designed from the ground up with the Internet in mind. In fact. object-oriented set of services and libraries that embrace the changing role of new network-centric and networkaware software. the basic role of software is changing from providing discrete functionality to providing services.NET Class Library is a key component of the .NET Class Library contains hundreds of classes you can use for tasks such as the following: .NET Framework represents a unified. It has a large library of pre-coded solutions to common programming problems and manages the execution of programs written specifically for the framework. As a result.NET Framework — it is sometimes referred to as the Base Class Library (BCL).NET Framework is a key Microsoft offering and is intended to be used by most new applications created for the Windows platform. resulting in a consistent object model regardless of the programming language developer’s use.NET Framework consists of three key elements as show in below diagram . Elements of the . and standard Windows applications • Working with application security • Working with directory services The functionality that the .NET Framework The .NET languages.• Processing XML • Working with data from multiple data sources • Debugging your code and working with event logs • Working with data streams and files • Managing the run-time environment • Developing Web services.NET Class Library provides is available to all . components. NET ASP.NET VC#.NET Framework Common Language Runtime .NET VC++.NET Web Server Web Form Window Forms System . Common Language Runtime The Common Language Runtime (CLR) is a layer between an application and the .NET JSCRIPT.NET Class Library Unifying components 1.VB.NET Common Language Runtime Common Type System Operating System Components of the .NET Class Library Data I/O Visual Security Studio. thread management. Instead of producing a binary representation of your code. they all have similar performance characteristics.NET Class Library is called System. it's divided into namespaces. and it contains core classes and data types.NET Class Library easier to work with and understand. Examples of nested namespaces include the following: System. The root namespace of the . because the .NET Class Library containing hundreds of classes that model the system and services it provides. and Console.Diagnostics: System.NET Framework. often referred to as IL.Data: System. When your code executes for the first time. This means that a program written in Visual Basic .NET Class Library The .NET can perform as well as the same program written in Visual C++ .NET languages have the same compiled representation.NET Framework: Microsoft Intermediate Language. Array. To make the . Object.NET Class Library is available on all implementations of the . . 2 . such as Int32. as traditional compilers do. . component lifetime management.NET Class Library include a consistent set of services available to all .NET.NET languages and simplified deployment.NET compilers produce a representation of your code in a language common to the . Because all .operating system it executes on. The CLR is also responsible for compiling code just before it executes. the CLR invokes a special compiler called a Just In Time (JIT) compiler. and default error handling. Secondary namespaces reside within the System namespace. The CLR simplifies an application's design and reduces the amount of code developers need to write because it provides a variety of execution services that include memory management.IO: Contains classes for working with the Event Log Makes it easy to work with data from multiple data sources Contains classes for working with files and data streams The benefits of using the . figuring out how to validate the e-mail address on a form. 1. this chapter has covered the low-level components of the . The unifying components.0 in 1997. for example.NET Windows Visual Forms Studio . you need to be aware of the load that users might place on the server.NET ASP. If you validate the form on the server. You can validate the information on a form by using a client-side script or a server-side script. Unifying components Until this point. Microsoft began researching possibilities for a new web application model that would solve common complaints about ASP. listed next. If you validate the form on the client by using client-side JScript code.NET Framework provides: ASP. Deciding which kind of script to use is complicated by the fact that each approach has its benefits and drawbacks. Web Forms Developers not familiar with Web development can spend a great deal of time. some of which aren't apparent unless you've done substantial design work.NET introduces two major features: Web Forms and Web Services.NET After the release of Internet Information Services 4. ASP. The server has to validate the data and send the result back to the client. are the means by which you can access the services the .3.NET Framework. Web Forms simplify Web development to the point that it becomes as easy as . you need to take into consideration the browser that your users may use to access the form. . Not all browsers expose exactly the same representation of the document to programmatic interfaces. NET Framework.NET runtime. which are created in different . The CLR is the .NET ASP. The CLR allows the objects. ASP.NET. For example. 2. which manages the execution of code. creating ASP. Web Services are designed to be used by other applications and components and are not intended to be useful directly to human end users. the advantages that ASP. is a programming framework that is used to create enterprise-class Web applications. Unlike the ASP runtime. you can write a Web Service that provides weather information for subscribers of your service instead of having subscribers link to a page or parse through a file they download from your site. and a fully integrated debugger. Web Services A Web service is an application that exposes a programmatic interface through standard access methods.NET offers make it more than just the next version of ASP.dragging and dropping controls onto a designer (the surface that you use to edit a page) to design interactive Web applications that span from client to server. Introducing ASP. which provides a GUI designer.NET is integrated with Visual Studio . Web Services make it easy to build applications that integrate features from remote sources. This allows the development of applications in a What You See is What You Get (WYSIWYG) manner. However. ASP.NET. Therefore.NET applications is much simpler. leading to efficient information management. a rich toolbox.NET uses the Common Language Runtime (CLR) provided by the . The enterprise-class Web applications are accessible on a global basis. Clients can simply call a method on your Web Service as if they are calling a method on a component installed on their system — and have the weather information available in an easy-to-use format that they can integrate into their own applications or Web sites with no trouble. the next version of ASP. These features lead to an overall improved performance of ASP. First. This is called Just In Time compilation. the . because ASP. This format makes it easy to apply new settings to applications without the aid of any local administration tools. it is important to note that compilation is a two-stage process in the .NET is language independent. Then. the code is compiled into the Microsoft Intermediate Language (MSIL).NET Framework.languages. Some of these advantages are listed as follows.NET applications. which is easy to read and write. Improved performance: The ASP. The CLR provides just-in-time compilation.NET code is a compiled CLR code instead of an interpreted code. at the execution time. You can use the language that best applies to the type of functionality you want to implement.NET CLR offers many advantages. Flexibility: The entire .NET applications. In addition to simplifying the designing of Web applications. CLR thus makes Web application development more efficient. native optimization. Security: . Here. to interact with each other and hence removes the language barrier. Configuration settings: The application-level configuration settings are stored in an Extensible Markup Language (XML) format. Only the portions of the code that are actually needed will be compiled into native code.NET class library can be accessed by ASP. the MSIL is compiled into native code. and caching. The XML format is a hierarchical text format. ASP. Use the VS. If the IIS server is installed on some other machine on the network.NET Application After you've set up the development environment for ASP. Web forms are contained in files with an ASPX . the application is automatically created on a Web server (IIS server).NET IDE: In this method.NET Web application in one of the following ways: Use a text editor: In this method.NET Web application. to display the output of the Web page in Internet Explorer. known officially as "web forms".NET. replace"localhost" with the name of the server. You can save the ASPX file in the directory C:\inetpub\wwwroot. you can create your first ASP.NET to create a Web page in a WYSIWYG manner. You do not need to create a separate virtual directory on the IIS server.NET applications are secure and use a set of default authorization and authentication schemes. you need to add the file to a virtual directory in the Default WebSite directory on the IIS server. such as Notepad.NET framework makes it easy to migrate from ASP applications. are the main building block for application development. Characteristics Pages ASP. In addition to this list of advantages. you use the IDE of Visual Studio . when you create a Web application.NET pages. You can also create your own virtual directory and add the file to it. However. you can write the code in a text editor. If you save the file in some other directory. you can modify these schemes according to the security needs of an application. Creating an ASP. Then. and save the code as an ASPX file. the ASP.aspx in the Address box. You can create an ASP. you simply need to type<filename>. Also. these files typically contain static (X)HTML markup.Text = DateTime. and ASP. as opposed to code behind.w3. as well as markup defining server-side Web Controls and User Controls where the developers place all the required static and dynamic content for the web page. in programming jargon. EventArgs e) { Label1.extension.org/1999/xhtml"> <head runat="server"> <title>Sample page</title> </head> <body> <form id="form1" runat="server"> <div> The current time is: <asp:Label </div> </form> </body> </html> .dynamic code -.0 Transitional//EN" ". JSP.dtd"> <script runat="server"> protected void Page_Load(object sender.w3. Note that this sample uses code "inline".%> which is similar to other web development technologies such as PHP. } </script> <html xmlns=". <%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.ToLongDateString().Now. dynamic code which runs on the server can be placed in a page within a block <% -. but this practice is generally discouraged except for the purposes of data binding since it requires more calls when rendering the page.org/TR/xhtml1/DTD/xhtml1-transitional. Additionally. cs or MyPage.SampleCodeBehind" AutoEventWireup="true" %> The above tag is placed at the beginning of the ASPX file. the developer writes code to respond to different events.aspx. like the page being loaded.NET's code-behind model marks a departure from Classic ASP in that it encourages developers to build applications with separation of presentation and content in mind.cs acts as the code-behind for this page: using System. to focus on the design markup with less potential for disturbing the programming code that drives it. The CodeFile property of the @ Page directive specifies the file (. Code-behind files typically have names like MyPage. Example <%@ Page Language="C#" CodeFile="SampleCodeBehind. In this example. then SampleCodeBehind.aspx. the @ Page directive is included in SamplePage.vb) acting as the code-behind while the Inherits property specifies the Class the Page derives from.aspx.Code-behind model It is recommended by Microsoft for dealing with dynamic program code to use the code-behind model. or a control being clicked.aspx. rather than a procedural walk through the document. which places this code in a separate file or in a specially designated script tag.vb based on the ASPX file name (this practice is automatic in Microsoft Visual Studio and other IDEs).cs or . ASP.aspx. . for example. When using this style of programming. In theory.cs" Inherits="Website. This is similar to the separation of the controller from the view in modelview-controller frameworks. this would allow a web designer. NET supports creating reusable components through the creation of User Controls.Web. methods. Template engine When first released. except that such controls are derived from the System. An event bubbling mechanism provides the ability to pass an event fired by a user control up to its containing page.UI. ASP. as well as markup defining web control and other User Controls.UserControl class. Because the .NET lacked a template engine.Page { protected override void Page_Load(EventArgs e) { base. many developers would define a new base class that inherits from "System. write methods . a ASCX contains static HTML or XHTML markup. and event handlers. The code-behind model can be used. The programmer can implement event handlers at several stages of the page execution process to perform processing.Web.namespace Website { public partial class SampleCodeBehind : System.Web. and are stored in ASCX files.OnLoad(e). Programmers can add their own properties.UI.Page". the Page_Load () method is called every time the ASPX page is requested. } } } In this case. A User Control follows the same structure as a Web Form.NET framework is object-oriented and allows for inheritance. Like ASPX files.UI. User controls ASP. as well as HTML and JavaScript shared across child pages. called ContentPlaceHolders to denote where the dynamic content goes.here that render HTML. and sends the output to the user. much like a mail merge in a word processor.not while designing it. The master page remains fully accessible to the content page. If the master page exposes public properties or methods (e. Performance ASP. it adds complexity and mixes source code with markup.0 introduced the concept of "master pages". While this allows for common elements to be reused across a site. configure caching etc. All markup and server controls in the content page must be placed within the ContentPlaceHolder control. This means that the content page may still manipulate headers. and then make the pages in their application inherit from this new class. ASP. Other developers have used include files and other tricks to avoid having to implement the same navigation and other elements in every page. Child pages use those ContentPlaceHolder controls. Furthermore.NET merges the output of the content page with the output of the master page. for setting copyright notices) the content page can use these as well. ASP. This compilation happens automatically the first time a .NET aims for performance benefits over other script-based technologies (including Classic ASP) by compiling the server-side code to one or more DLL files on the web server. which must be mapped to the place-holder of the master page that the content page is populating. A web application can have one or more master pages. this method can only be visually tested by running the application . change title. which allow for templatebased page development. The rest of the page is defined by the shared parts of the master page.NET 2. When a request is made for a content page. which can be nested. Master templates have place-holder controls.g. as it has no persistent effects on the data stored in a database. By default ASP. but won't again unless the page requested is updated further. the . The first time a client requests a page. However. If the compilation delay is causing problems. Note that there are some platform-specific variations of SELECT that can persist their effects in a database.NET servers. eliminating the need for just-in-time compilation in a production environment. This feature provides the ease of development offered by scripting languages with the performance benefits of a compiled binary.page is requested (which means the developer need not perform a separate compilation step for pages). or multiple related tables.NET framework parses and compiles the file(s) into a . SQL queries allow the user to specify a description of the desired result set. The ASPX and other resource files are placed in a virtual host on an Internet Information Services server (or other compatible ASP. subsequent requests are served from the DLL files. Database Queries The most common operation in SQL databases is the query. the batch size or the compilation strategy may be tweaked. but it is left to the devices of the database management system (DBMS) to plan. such as the SELECT INTO syntax that exists in some databases.NET will compile the entire site in batches of 1000 files upon first request. below). see Other Implementations. in a database.NET assembly and sends the response. SELECT retrieves data from a specified table. which is performed with the declarative SELECT keyword. the standard SELECT query is considered separate from SQL DML. Developers can also choose to pre-compile their code before deployment. . While often grouped with Data Manipulation Language (DML) statements. the compilation might cause a noticeable but short delay to the web user when the newly-edited page is first requested from the web server. The FROM clause can include optional JOIN clauses to join related tables to one another based on user-specified criteria. aggregate functions can be used in the HAVING clause predicate. which is used to restrict the number of rows returned by the query. The HAVING clause includes a comparison predicate used to eliminate rows after the GROUP BY clause is applied to the result set. and in which order they should be sorted (options are ascending or descending). rows with related values into elements of a smaller set of rows. The WHERE clause eliminates all rows from the result set where the comparison predicate does not evaluate to True. An SQL query includes a list of columns to be included in the final result immediately following the SELECT keyword. An asterisk ("*") can also be used as a "wildcard" indicator to specify that all available columns of a table (or multiple tables) are to be returned. GROUP BY is often used in conjunction with SQL aggregate functions or to eliminate duplicate rows from a result set. The GROUP BY clause is used to combine. with several optional keywords and clauses. including: The FROM clause which indicates the source table or tables from which the data is to be retrieved. The WHERE clause includes a comparison predicate. The ORDER BY clause is used to identify which columns are used to sort the resulting data. and perform the physical operations necessary to produce that result set in as efficient a manner as possible. .optimize. Because it acts on the results of the GROUP BY clause. or group. SELECT is the most complex statement in SQL. The WHERE clause is applied before the GROUP BY clause. The order of rows returned by an SQL query is never guaranteed unless an ORDER BY clause is specified. and aggregation in an SQL query. The query retrieves all rows from the Book table in which the price column contains a value greater than 100. SELECT Book. SELECT * FROM Book WHERE price > 100.The following is an example of a SELECT query that returns a list of expensive books. by returning a list of books and the number of authors associated with each book. count (*) AS Authors FROM Book JOIN Book_author ON Book. The example below demonstrates the use of multiple tables in a join.00. The result is sorted in ascending order by title.isbn GROUP BY Book.title.isbn = Book_author.00 ORDER BY title.title.------SQL Examples and Guide The Joy of SQL 1 3 . grouping. Example output might resemble the following: Title Authors ---------------------. The asterisk (*) in the select list indicates that all columns of the Book table should be included in the result set. or when the data needs to be expressed in a form that is different from how it's stored. many vendors either do not support this approach. a dash "-" would be interpreted as a minus sign. price * 0. SQL allows the use of expressions in the select list to project data. title. count (*) AS Authors FROM Book NATURAL JOIN Book_author GROUP BY title. Thus. or it requires certain column naming conventions. However. Data retrieval is very often combined with data projection when the user is looking for calculated values and not just the verbatim data stored in primitive data types. as in the following example which returns a list of books that cost more than 100. price.06 AS sales_tax . For example. the above query could be rewritten in the following form: SELECT title.) Under the precondition that isbn is the only common column name of the two tables and that a column named title only exists in the Books table. SELECT isbn.00 with an additional sales_tax column containing a sales tax figure calculated at 6% of the price.How to use Wikipedia Pitfalls of SQL 1 2 How SQL Saved my Dog 1 (The underscore character "_" is often used as part of table and column names to separate descriptive words because other punctuation tends to conflict with SQL syntax. it is less common in practice. title.FROM Book WHERE price > 100.00 ORDER BY title. date FROM Book WHERE price > 100. price. They may look like this example: SELECT isbn.00 AND (date = '16042004' OR date = '16042005') ORDER BY title. Some modern day SQL queries may include extra WHERE statements that are conditional to each other. . Chapter 7 System Design . E-R DIAGRAM: BUS RESERVATION SYSTEM Give service s Divide d BUSES Work area DIFFERENT TYPE OF BUSES Full of examin e Care of Wor ks SLEEPER OR WITHOUT SLEEPER DEPARTMENT SEATS . FEEDBACK.The following DFD shows how the working of a reservation system could be smoothly managed: WORK AREAS DEPTT WITH ITS BUSES AGENT BUSES RECORDS DAILY ENTRY REC RESERVED AGENT VISITING AGENT AGENT DETAILS REPORT TABLE DETAIL DESCRIPTION OF DATA FLOW DIAGRAM: We have STARBUS as our database and some of our tables (relation) are such as AGENT_BASIC_INFO. PASSANGER_INFO. STATIS and TIMELIST . AGENT_FNAME AGENT_NAME AGENT_ID agent_shop_city. agent_name. agent_shop_name. agent_fname. agent_name. agent_shop_address. AGENT_SHOP_NAME AGENT_SHOP_ADDRESS AGENT_SHOP_CITY AGENT_BASIC_INFO AGENT_PHON_NUMBER AGENT_MOBIL_NUMBER AGENT_CURRENT_BAL . agent_phon_number etc.STARBUS AGENTBASICINFO FEEDBACK PASSANGERIFNO STATIS TIMELIST In our table AGENT_BASIC_INFO we have following field such as agent_id. In our FEEDBACK table we have fields like name. and User_type. Email. Phon. Subject. . Comment. Ttalseat. c_name. c_phone. c_to. Amount. c_from. Seatnumber. c_time. Agent_id and Status. .Email Name Phone FEEDBACK Comment User_typ e Subject In our table PASSANGER_INFO we have filed like bill_no. . Rate_per_seat.C_name Bill_no C_phon C_to Status PASSANGER _INFO C_from Agent_id C_time Amount Seat_no Total_seat In the table of TIME_LIST we have fields such as Sno. Satation_name. Time. Reach_time and Bus_number. Sno Station_nam e Rate_perSeat TIME_LIST Bus_numbe r Reach_time Time PROCESS LOGIC: . the more they are comfortable with us. the more customers we have visiting our reservation unit .the above tables and modules facilitates many logics like: Number of buses in one unit Number of computers in particular department Number of users in a department Which bus has what tour on which day What are time table for different buses of different department What are the schedule for buses Schedule of a particular bus How many buses are there Each bus has how many seats How many seats are occupied Advance booking for seat How much money is collected in a particular day Bills for different customers Which seat has booked by agent .As the privatization of buses is increasing thus the need of its smooth management is also increasing the more we could facilitate the customers. . Display advantage of the StarBus Links for Agent list and seat status.1. Terms and Conditions. It gives the followings: TollFree number of the other city. Index page This webpage is the starting page of the Website. FAQ. Links for Feedback. 2. Information about the booking which seat is booked and which is empty. As in the above image the Status webpage is displaying: Accessed by anyone. Status. . As in the above image the Agent name webpage is displaying: Accessed by anyone. Agent name.3. . Contains information about name. address and phone number of the agent. Feedback As in the above image Feedback webpage is displaying: This page is access by any user Anyone can give feedback related to the site or services. Links for Terms and Condition’s and Policy and Privacy.4. . Such as how many agent office are there and what is the mode Of the pament. . FAQ As in the above image FAQ webpage is displaying: This page is access by any user Contain information about tour and services of web site.5. age. we required information about customer his/her name.6. . Privacy Policy: As in the above image the Privacy and Policy webpage is displaying: This page is access by any user This page say that when customer using our services. route and email so that we can inform them to there email also. Useful for customer Contain information when to reach the starting point and what should do. As in the above image the Terms and Conditions webpage is displaying: Accessed by anyone. in case when our ticket is lost. .7. Terms and Conditions. Identity Confirmation. Contain link for Forget Password.8. 9. Forget Password Page As in the image Forget Password webpage is displaying: It required user name who forget its password and then click on Next button. 10. And also provide link for administration and other. Login page As in the image Login webpage is displaying: Accessed by the agent. Agent entered its user name and password and click on login. As in the above image Identify Confirmation for user webpage is displaying: . Select the destination. Ticket Booking page. The Question you have select at the time of registration. You need to enter the answer for that question. 11. After click on Next button. As in the above image the ticket booking page is displaying: Only accessed by the agent. . departure date and time. You will get your password on the show password webpage. Red seat indicates booked seat. You can choose rest of the seat.11. It will be converted into green seat. Select Seat page As in the above image the Select Seat page is displaying: Only accessed by the agent. . . Click on Go button for printing the ticket. Agent enters the name and phnumber of the customer.12. Customer Information page As in the above image the Customer Information webpage is displaying: After selecting the seat. These also reduce the agent balance.13. destination. . This contain customer information such as name. Ticket Print page As in the above image the Ticket print webpage is displaying: This page prints the Customer ticket. Number of seat. . Using PNR number. As in the above image the Ticket Search webpage is displaying: Only accessed by the Agent and Administration.14. Agent can search the ticket. Search Ticket. Agent can see the status ticket.15. Ticket Cancellation As in the above image the Ticket cancellation webpage is displaying— Only accessed by the Agent and Administration Using PNR number. . Create Agent: .16. Change Password As in the above image the Change password web page is displaying: Only accessed by the Agent Agent can change password by entering the old and new password Administrator Section: 17. New agents are added by this page Required following information: Username Password Email Security Question. . Security Answer.As in the above image the Change password web page is displaying: Only accessed by the Administrator. After click on Create user button it will send you on Agent Basic Information webpage. 18. Agent List page . Agent Basic Information page As in the above image the agent’s Basic information web page is displaying: Agents Basic Information are added by this page Required following information are : Name Father’s Name Shop Name Shop City Shop phone number Mobile Number Deposit amount 19. Agent Deposit Amount Page .As in the above image the agent’s List web page is displaying: Only accessed by the Administrator. Displaying Agent information such as: Agent ID Name Shop Name Shop City Current Balance Mobile Number 20. As in the above image the agent’s Deposit Amount web page is displaying: Only accessed by the Administrator. Requires agent name and amount he wants to deposit. 21. Search Agent Page . Bus List: Feedback List: . . Chapter 8 System Testing . Because the steps of the test strategy occur at a time when deadline pressure begins to rise. behavior and performance. 8. progress must be measurable and problems must surface as earl as possible. the intent is to find the maximum number of errors with the minimum amount of effort and time. 8. To uncover the errors software techniques are used. and (2) Exercise the input and output domains of the program to uncover errors in program function. software must be tested to uncover (and correct) as many errors as possible before delivery to customer. Our goal is to design a series of test cases that have a high likelihood of finding errors. In both cases. A strategy must provide guidance for the practitioner and a set of milestones for the manager. Software is tested from two different perspectives: (1) Internal program logic is exercised using “White box” test case design techniques.System Testing Once source code has been generated. These techniques provide systematic guidance for designing test that (1) Exercise the internal logic of software components.1 Steps. (2) Software requirements are exercised using “block box” test case design techniques.2 Strategies A strategy for software testing must accommodate low-level tests that are necessary to verify that a small source code segment has been correctly implemented as well as high-level tests that validate major system functions against customer requirements. . The unit test is white-box oriented.3 Validation testing: At the culmination of integration testing. Validation can be defined in many ways.2 Integration testing: Integration testing is a systematic technique for constructing the program structure while at the same time conducting tests to uncover errors associated with interfacing.4 System testing: System testing is actually a series of different tests whose primary purpose is to fully exercise the computer-based system. 8.2. . All independent paths through the control structure are exercised to ensure that all statements in a module haven executed at least once.2. Boundary conditions are tested to ensure that the module operated properly at boundaries established to limit or restrict processing. and a final series of software tests—validation testing-may begin.1 Unit testing: Unit testing focuses verification effort on the smallest unit of software design. software is completely assembled as a package. 8. The objective of this test is to take unit tested components and build a program structure that has been dictated by design. Below we have described the two types of testing which have been taken for this project. 8.2.2. The module interface is tested to ensure that information properly flows into and of the program unit under test the local data structure has been examined to ensure that data stored temporarily maintains its integrity during all steps in an algorithm’s execution. but a simple definition is that validation succeeds when software functions in a manner that can be reasonably expected by the customer.Following testing techniques are well known and the same strategy is adopted during this project testing. 8. interfacing errors have been uncovered and corrected.the software component or module. 2. we cannot be absolutely certain that the software will never fail.2.4. 8. Criteria for Completion of Testing Every time the customer/user executes a compute program. disgruntled employees who attempt to penetrate for revenge. As much time we run our project that is still sort of testing as Musa and Ackerman said.3. Penetration spans a broad range of activities: hackers who attempt to penetrate system for sport. the program is being tested. 8. when anyone who is not authorized user cannot penetrate this system. When programs first load it check for correct username and password.4.1 Security testing Any computer-based system that manages sensitive information causes actions that can improperly harm (or benefit) individuals is a target for improper or illegal penetration. Even at the unit level.995.” . dishonest individuals who attempt to penetrate for illicit personal gain. If any fails to act according will be simply ignored by the system. This sobering fact underlines the importance of other software quality assurance activities. we have done sufficient testing to say with 95 percent confidence that the probability of 1000 CPU hours of failure free operation in a probabilistically defined environment is at least 0. Performance testing occurs throughout all steps in the testing process. the performance of an individual module may be assessed as white-box tests are conducted. For security purposes.8. They have suggested a response that is based on statistical criteria: “No. but relative to a theoretically sound and experimentally validated statistical model.2 Performance Testing Performance testing is designed to test the run-time performance of software within the context of an integrated system. When you try to edit the record for the trainee in Operation division you will find the validation checks. This password is validated to certain string. you won’t get the entry.4 Validation Checks Software testing is one element of broader topic that is often referred to as verification and validation. . Your entry will be automatically abandoned.8. similarly if you data for trainee code in text (string) format it will be simply abandoned. till user won’t supply correct word of string for password he cannot succeed. Boehm state this another way: Verification: “Are we building the product right?” Validation: “Are we building the right product?” Validation checks are useful when we specify the nature of data input. A validation check facilitates us to work in a greater way. In the very beginning of the project when user wishes to enter into the project. he has to supply the password. If you supply the number (digits) for name text box. Validation refers to a different set of activities that ensure that the software that has been built is traceable to customer requirements. When you try to input wrong data. Let us elaborate what I mean. It become necessary for certain Applications like this. In this project while entering the data to many text box you will find the use of validation checks. Verification refers to the set of activities that ensure that software correctly implements a specific function. Chapter 9 System Implementation . .” 7. Requirements are represented in manner that ultimately leads to successful software implementation. 5. This list of basic specification principles provides a basis for representing software requirements. Establish the content and structure of a specification in a way that will enable it to be amenable to change. 4.1 Specification principles A number of specification principles. Establish the context in which software operates by specifying the manner in which other system components interact with software. 9. Recognize that “the specifications must be tolerant of incompleteness and augmentable. 3.Specification. The cognitive model describes a system as perceived by its user community. principles must be translated into realization. adapted from the work of balzer and Goodman can be proposed: 1. Separate functionality from implementation. Define the environment in which the system operates. Develop a model of the desired behavior of a system that encompasses date and the functional responses of a system to various stimuli from the environment. 2. Create a cognitive model rather than a design or implementation model. 6. may be viewed as a representation process. However. regardless of the mode through which we accomplish it. 1. A general outline for the contents of a Software Requirements Specification can be developed.9. Similar guidelines are adhered for my project. However. However. for our automation system we used different symbology. It is sometimes worthwhile to present the same information at different levels of abstraction to aid in understanding. For example.2 Representation As we know software requirement may be specified in a variety of ways. the representation forms contained within the specification are likely to vary with the application area. Paragraph and diagram numbering schemes should indicate the level of detail that is being presented. Representations should reveal layers of information so that a reader can move to the level of detail required. . Information contained within the specification should be nested. diagrams. if requirements are committed to paper a simple set of guidelines is well worth following: Representation format and content should be relevant to the problem. Chapter 10 Conclusion To conclude. Project Grid works like a component which can access all the databases and picks up different functions. It overcomes the many limitations . Among the many features availed by the project.NET Framework. the main among them are: Simple editing Insertion of individual images on each cell Insertion of individual colors on each cell Flicker free scrolling Drop-down grid effect Placing of any type of control anywhere in the grid • • • • • • .incorporated in the . Chapter 11 Scope of the Project Future scope of the project: - . as it is very flexible in terms of expansion. Automatic and error free report generation as per the specified format with ease. With a fully automated solution. accurate and error free manner. Project can be updated in near future as and when requirement for the same arises. addition or deletion of any reseller in any type of modification in future . In case there be any additions or deletion of the services. better space utilization and peaceful work environment. A future application of this system lies in the fact that the proposed system would remain relevant in the future. With the proposed software of Web Space Manager ready and fully functional the client is now able to manage and hence run the entire work in a much better. Automatic calculation and generation of correct and precise Bills thus reducing much of the workload on the accounting staff and the errors arising due to manual calculations. The following are the future scope for the project: The number of levels that the software is handling can be made unlimited in future from the current status of handling up to N levels as currently laid down by the software. Efficiency can be further enhanced and boosted up to a great extent by normalizing and de-normalizing the database tables used in the project as well as taking the kind of the alternative set of data structures and advanced calculation algorithms available.The project has a very vast scope in future. lesser staff. the company is bound to experience high turnover. We can in future generalize the application from its current customized status wherein other vendors developing and working on similar applications can utilize this software and make changes to it according to their business needs. Faster processing of information as compared to the current system with high accuracy and reliability. The project can be implemented on internet in future. hence. All these result in high client-satisfaction.can be implemented easily. The data collected by the system will be useful for some other purposes also. . more and more business for the company that will scale the company business to new heights in the forthcoming future. References . References: • • • • • • • • Complete Reference of C# Programming in C# .wikipedia.NET Object Oriented Programming – Deitel & Deitel .com Software Engineering – Hudson MSDN help provided by Microsoft .Deitel & Deitel The principles of Software Engineering – Roger S. This action might not be possible to undo. Are you sure you want to continue?
https://www.scribd.com/doc/63945583/Star-Bus-Report-v1
CC-MAIN-2015-48
refinedweb
9,744
50.53
Let’s say you’re a data scientist, and you’ve been asked to solve a problem. Of course, what you really want is to build an interactive tool, so your colleagues can solve the problem themselves! In this tutorial, I'll show you how to take a machine-learning model in a Jupyter notebook, and turn it into a web application using the Anvil Uplink. Here's what we'll do: Setting up the Jupyter Notebook We'll start with a pre-existing Jupyter Notebook containing a classification model that distinguishes between cats and dogs. You give it an image and it scores it as ‘cat’ or ‘dog’. (Thanks to Uysim Ty for sharing it on Kaggle.) Connecting to the Uplink We'll use the Anvil Uplink to connect a Jupyter Notebook to Anvil. It’s a library you can pip install on your computer or wherever your Notebook is running. your Jupyter Notebook It works for any Python process - this happens to be a Jupyter Notebook, but it could be an ordinary Python script, a Flask app, even the Python REPL! To connect our notebook, we'll first need to enable the Uplink in the Anvil IDE. This gives us a key that we can then use in our code. We then need to pip install the Uplink library on the machine the Jupyter Notebook is running on: pip install anvil-uplink By adding the following lines to our Jupyter notebook, we can connect it to our Anvil app: import anvil.server anvil.server.connect('<YOUR-UPLINK-KEY>') Now we can do anything in our Jupyter Notebook that we can do in an Anvil Server Module - call Anvil server functions, store data in Data Tables, and define server functions to be called from other parts of the app. We'll load an image into the Jupyter Notebook by making an anvil.server.callable function in the Jupyter Notebook. It will classify the input image as either a cat or a dog. import anvil.media @anvil.server.callable def classify_image(file): with anvil.media.TempFile(file) as filename: img = load_img(filename) We can drag-and-drop components to create a User Interface. It consists of a FileLoader to upload the images, an Image to display them, and a Label to display the classification. Making the UI call the Notebook Now we need to write some Python code that runs in the browser so the app responds when an image is loaded in. We. Your app is already published at a private URL, but we can give it a public URL. You can check out this finished app at. Discussion (1) Hi Meredydd, thank you for the tutorial. I'm just wondering, how is Anvil different from Voila, a popular library for the same purpose?
https://practicaldev-herokuapp-com.global.ssl.fastly.net/meredydd/turn-a-jupyter-notebook-into-a-web-app-lj3
CC-MAIN-2021-25
refinedweb
465
70.13
ReactJS Powered Presentation Framework Spectacle ReactJS based Presentation Library. Getting Started:[email protected]/dist/spectacle.min.js.. One Pageand all the Spectacle exports from ./src/index.js-- Deck, Slide, themes, etc. The presentation must include exactly one script tag with the type text/spectaclethat is a function. Presently, that function is directly inserted inline into a wrapper code boilerplate as a React Component renderfunction.="[email protected]/normalize.css" rel="stylesheet" type="text/css"> </head> <body> <div id="root"></div> <script src="[email protected]/prop-types.js"></script> <script src="[email protected]/umd/react.production.min.js"></script> <script src="[email protected]/umd/react-dom.production.min.js"></script> <script src=""></script> <script src="[email protected]^4/dist/spectacle.js"></script> <script src="[email protected]^4/lib/one-page.js"></script> <script type="text/spectacle"> () => { // Your JS Code goes here return ( <Deck> {/* Throw in some slides here! */} </Deck> ); } </script> </body> </html> Development Build & Deployment. Presenting Spectacle comes with a built in presenter mode. It shows you a slide lookahead, current time and your current slide: Otherwise, it can also show you a stopwatch to count the elapsed time: To present: - Run npm start - Open two browser windows on two different screens - On your screen visit. You will be redirected to a URL containing the slide id. - Add presenter&or presenter&timerimmediately after the questionmark, e.g.: or - On the presentation screen visit - Give an amazingly stylish presentation Note: Any windows/tabs in the same browser that are running Spectacle will sync to one another, even if you don't want to use presentation mode Check it out: You can toggle the presenter or overview mode by pressing respectively alt+p and alt+o. Controls Fullscreen Fullscreen can be toggled via browser options, or by hovering over the bottom right corner of your window until the fullscreen icon appears and clicking it. PDF Export Exporting a totally sweet looking PDF from your totally sweet looking Spectacle presentation is absurdly easy. You can either do this via the browser, or from the command line: CLI - Run npm install spectacle-renderer -g - Run npm starton your project and wait for it to build and be available - Run spectacle-renderer - A totally cool PDF is created in your project directory For more options and configuration of this tool, check out: Browser - Run npm start - Open - Add export&after the ?on the URL of page you are redirected to, e.g.: - Bring up the print dialog (ctrl or cmd + p) - Check "Background Graphics" to on if you are about that life - Change destination to "Save as PDF", as shown below: If you want to print your slides, and want a printer friendly version, simply repeat the above process but instead print from Basic Concepts Main file. Themes object based styles. You will want to edit index.html to include any web fonts or additional CSS that your theme requires. createTheme(colors, fonts).
https://reactjsexample.com/reactjs-powered-presentation-framework/
CC-MAIN-2020-10
refinedweb
486
55.03
What data do you want to send? More info on destination is needed And please limit your question to this thread rather than spamming the board Why would you want to do without the Nextion Library? As per the Nextion Instruction Set all commands are to be data terminated - with three bytes of hexadecimal 0xFF equivalent to a byte of 255 or char ÿ. Changing a string attribute requires the value to be encased in double quotes t0.txt="Hello"ÿÿÿ Changing a numeric attribute does not require the value to be encased in double quotes. t0.font=2ÿÿÿ This you must format as needed and send via the serial port Nextion is on Using the Nextion Library #include "Nextion.h" NexText myt0 = NexText(0,1,"t0"); myt0.setText("Hello"); That is not really a Nextion problem, that is an MCU side programming problem You will have to dig into your documentation a bit - Compiler - Programming Language - Hardware Manuals Happy Coding @Umar It's very simple to send the temperature to your Nextion display without using the library. You can use something like that: #define SerialNxtn Serial1 // <== Change Serial1 to what you are using float tempDs18b20; // ... Some code to read the temperature from DS18B20 // Send temperature to Nextion, text component t0: SerialNxtn.print("t0"); SerialNxtn.print(".txt="); SerialNxtn.write(0x22); // \" SerialNxtn.print(tempDs18b20); SerialNxtn.write(0x22); SerialNxtn.write(0xFF); SerialNxtn.write(0xFF); SerialNxtn.write(0xFF); As you see, you use the same kind of command "Serial.print(xxx)" as with the Serial Monitor. Hi Raphael. Can you tell me: How to show float number from MCU to Nextion Display? I only can show number in interger format. Thank you! Nextion is an integer based device without floating point math. As such as you can only show number in integer format / However, two approaches can be taken - 1) split float into two parts, whole and fractional display each to their respective number components (available as numbers for Nextion side math) - 2) convert to text format display in a Text Component (cov command will not convert a float) In Raphael's example above t0 is a Text Component - parses out to t0.txt="23.5"ÿÿÿ where 23.5 is .print(tempDs18b20); His publically posted code example answers exactly your question. Yes, your help is useful with me. But now I have a case, that is : When I send data from MCU to Display via UART, I want the display check that data. Such as when MCU send "30.5" to t0, How to display auto show that data for t1 same t0? It mean what code for Display. Thanks! Umar farooq 3 people like this idea
http://support.iteadstudio.com/support/discussions/topics/11000010471
CC-MAIN-2018-39
refinedweb
445
62.68
. Images Sizes and Format There are two overarching constraints for images used within notifications: - Images used in notifications must be in one of three formats: .png, .jpg/.jpeg, or .gif, and the format must match the extension. - Images for notifications must be no larger than 200 KB and 1024 x 1024 in dimension.. Image Locations Images used for notifications can be stored in one of three places: - within the app package, using the ms-appx:///prefix to a directory in your deployed application (this is the default). - within local storage, using the ms-appdata:///localprefix to a directory within local storage. Note that images in temporary and roaming application data storage cannot be used. - on the web, using an httpor httpsURI that serves up image content (this requires that the application declare Internet client capability in its manifest).. App Package Images"); Local Storage Images Images in the Cloud. Keep in mind there are some caveats when using cloud or web hosted images: - The most obvious is that if the machine lacks network connectivity, the image won't be available and the notification will not be sent. - Web images are cached, so an update to the image in the cloud may not be immediately reflected on the client. If the cache is full, images will be removed in a policy opaque to the developer. Additionally the system will clear the cache when - The application is uninstalled, or - The user clears personal information from all of her application tiles (via the Settings flyout on the Start screen). The system will comply with caching and expiration headers in the HTTP response. Those headers are not configurable in Windows Azure storage alone, but a web service can be configured and hosted on Windows Azure to support this. - The cloud isn't free! While there are no-cost options (like the 90-day trial and MSDN subscriptions), you ultimately may end up paying for the storage and the transactions (HTTP GET requests) that are made by your application. The complete pricing details are available at the Azure pricing page, but it’s very likely you'll be able to support a popular Windows 8 application for dollars if not pennies a month. Handling Scaling and Contrast Themes. App Package Images. A file named redWide.scale-140.png, if available, would be used in the samples above – in lieu of scaling the default image – whenever there was a request for redWide.pngwould be used when the contrast mode is black and an image scaled to 180% is needed. By the way, redWide.contrast-black_scale-180.pngworks too!. Local Images Unfortunately, none of the conventions supported for app package images are supported when using local images (the ms-appdata:///local namespace), but you could implement similar semantics programmatically using the following Windows APIs: Images in the Cloud). A Recap of the Not-So-Obvious - 80% images are used on tiles for some combinations of screen size and resolution. - Size specifications haven’t been published for images that appear on toast or that do not fill the entire tile, such as the template samples below. In most cases, these will be photographic images which scale fairly well (using the Fant algorithm internally). You could measure the sizes empirically, but if you create images that work for 180% scale they should also scale down well for the other three factors. - Default images (those declared in your app manifest) must be .png or .jpg/.jpeg format, but you can use .gif in your toast and tile notification templates. - If an image is of the wrong format or not available (such as a image hosted on the Web when the client is not connected), the notification will not be sent. - The branding element is taken from the small logo in your manifest. For tiles it appears in the bottom left and for toast in the bottom right. In the tile schema you can use text, logo, or no branding; in the toast schema, the branding attribute is not used and you will always see the logo. - The badge logo must be monochromatic. - if you don’t supply multiple images to accommodate scaling, try to create images with dimensions that are a multiple of 5 as they won’t experience pixel shifting during scaling. - The Visual Studio simulator is an awesome way to test out tile behavior under different resolutions and contrast modes, but be aware, you’ll have to restart your debug session in the simulator if your change in resolution results in loading a different version of the image. - PC Settings > Ease of Access (accessible via the Settings charm) includes a switch to toggle High Contrast mode; however, since there are four high contrast modes, you’ll need to use the desktop Control Panel option to pick one. Once you’ve selected the contrast mode there, PC Settings > Ease of Access will use that High Contrast mode when you toggle the option. - Windows supports four high contrast modes (White, Black, #1, and #2), and these map to four overlapping resource types: standard, high, black, and white as follows:
https://blogs.msdn.microsoft.com/jimoneil/2012/08/06/windows-8-notifications-image-handling/
CC-MAIN-2017-34
refinedweb
848
59.64
c++.stlsoft - Run-time Union List - "christopher diggins" <cdiggins videotron.ca> Jan 03 2005 - "christopher diggins" <cdiggins videotron.ca> Jan 04 2005 - "Matthew" <admin stlsoft.dot.dot.dot.dot.org> Jan 04 2005 I would like to submit the code for a run-time union list to StlSoft, if there is any interest in it. This type behaves like a union, as it can hold one value of an arbitrary list of types. It does not have the property of memory sharing however. It does however have a very small code-base unlike the similar boost::variant. I want to release the code as public domain, would that make it incompatible with the STLSoft licensing requirements? Here is how the code is used: #include "..\utils\union_list.hpp" #include <string> #include <iostream> using namespace std; typedef ul<int, ul<char, ul<bool, ul<double, ul<string, ul_end> > > > > test_type; void output(test_type x) { switch(x.DataIndex()) { case 0 : cout << "int : " << x.get<0>() << endl; break; case 1 : cout << "char : " << x.get<1>() << endl; break; case 2 : cout << "bool : " << x.get<2>() << endl; break; case 3 : cout << "float : " << x.get<3>() << endl; break; case 4 : cout << "string : " << x.get<4>() << endl; break; } } int main() { output('a'); output(3.141); output(42); output(string("Hello world")); output(true); getchar(); return 0; } Is this something that is desirable? -- Christopher Diggins Jan 03 2005 I posted the entire union list code at . Any interest in having it in STLSoft? (still preparing the next release of the YARD parser) -- Christopher Diggins Jan 04 2005 Sorry, Chris Madly snowed under at the mo. Will have to get back to you next week. Cheers Matthew "christopher diggins" <cdiggins videotron.ca> wrote in message news:cren41$2kk9$1 digitaldaemon.com...I posted the entire union list code at . Any interest in having it in STLSoft? (still preparing the next release of the YARD parser) -- Christopher Diggins Jan 04 2005
http://www.digitalmars.com/d/archives/c++/stlsoft/404.html
CC-MAIN-2015-22
refinedweb
319
77.74
Introduction: temperature sensors (I use DS18b20 as they are pretty good and cheap enough) I will divide this Instructable into several little projects as there is quite a bit to do to get it all working. These will be: - Build a temperature sensor using an ESP8266 and DS18b20 - output to serial - Setup MQTT broker on a ubuntu server - Modify the sketch on the ESP8266 to publish temperature to the MQTT broker - Connect LCD screen to another ESP8266 for local monitoring (Instructable) - Install and configure home-assistant on a ubuntu server (for local and remote monitoring) Step 1: Build a Temperature Sensor Using an ESP8266 and DS18b20 - Output to Serial Connecting the DS18b20 to the ESP8266 is very simple. The picture above along with the BreadBoard Fritzing should help. You simply connect the left hand pin to Ground, the centre pin to the GPIO that you want to use (I use D1 which is GPIO5), and the right had ping to 5v. Once this is all connected up you can use the Simple DallasTemperature example to get the temperature from the sensor which is sent to the serial output. I added sensors.setResolution(12) which sets the resolution of the device to 12 bits so that I get a more precise temperature reading. You can see from the values below what you can expect from each of the bit resolutions: Mode Resol Conversion time 9 bits 0.5°C 93.75 ms 10 bits 0.25°C 187.5 ms 11 bits 0.125°C 375 ms 12 bits 0.0625°C 750 ms You can get the library for the DS18b20 from the Arduino Library manager, so no need to download it from github separately. Step 2: Setup MQTT Broker on a Ubuntu Server This part of the Instructable assumes you know how to install and update ubuntu. Once you have got this far you'll need to install mosquitto. root@ubuntu:~# apt-get install mosquitto Reading package lists... Done Building dependency tree Reading state information... Done The following extra packages will be installed: libwebsockets3 The following NEW packages will be installed libwebsockets3 mosquitto 0 to upgrade, 2 to newly install, 0 to remove and 3 not to upgrade. Need to get 0 B/163 kB of archives. After this operation, 490 kB of additional disk space will be used. Do you want to continue? [Y/n] y Selecting previously unselected package libwebsockets3:amd64. (Reading database ... 64521 files and directories currently installed.) Preparing to unpack .../libwebsockets3_1.2.2-1_amd64.deb ... Unpacking libwebsockets3:amd64 (1.2.2-1) ... Selecting previously unselected package mosquitto. Preparing to unpack .../mosquitto_1.4.8-0mosquitto1_amd64.deb ... Unpacking mosquitto (1.4.8-0mosquitto1) ... Processing triggers for ureadahead (0.100.0-16) ... Processing triggers for man-db (2.6.7.1-1ubuntu1) ... Setting up libwebsockets3:amd64 (1.2.2-1) ... Setting up mosquitto (1.4.8-0mosquitto1) ... mosquitto start/running, process 12955 Processing triggers for libc-bin (2.19-0ubuntu6.7) ... Once mosquitto is installed it should be running, check it by running a ps: root@ubuntu:~# ps aux |grep mosquitto mosquit+ 12955 0.1 0.0 37236 2420 ? Ss 16:45 0:01 /usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf root 13307 0.0 0.0 11744 948 pts/0 S+ 16:58 0:00 grep --color=auto mosquitto Now if you run the following command to subscribe to the broker you should see nothing, but mosquitto_sub will sit and wait for something to be published to the broker. root@ubuntu:~# mosquitto_sub -h localhost -v -t "#" This will subscribe to all topics (as you've used the # for the topic) so anything that is sent to the broker will be displayed. Then in another ssh window send a message to the broker as follows : rot@ubuntu:~# mosquitto_pub -h localhost -t "ha/test" -m "Hello" Then back in the other window that is running the mosquitto_sub you should see the following : root@ubuntu:~# mosquitto_sub -h localhost -v -t "#" ha/test Hello This shows that the broker is working and is ready for receiving data from the ESP8266 nodes and sending it onto home-assistant. Step 3: Modify the Sketch on the ESP8266 to Publish Temperature to the MQTT Broker Now that the MQTT broker is running on your ubuntu server you can now update the sketch on your ESP8266 to start sending temperatures to it. The follow sketch will need a little modifying to include your own wifi SSID and the IP address of your ubuntu server that has mosquitto running on it. You will need the following libraries which you can get from github: - - - #include <ESP8266WiFi.h> #include <PubSubClient.h> #include <OneWire.h> #include <DallasTemperature.h> // Data wire is plugged into pin 2 on the Arduino #define ONE_WIRE_BUS 5 // Setup a oneWire instance to communicate with any OneWire devices // (not just Maxim/Dallas temperature ICs) OneWire oneWire(ONE_WIRE_BUS); DallasTemperature sensors(&oneWire); // Update these with values suitable for your network. const char* ssid = ""; const char* password = ""; const char* mqtt_server = ""; WiFiClient espClient; PubSubClient client(espClient); long lastMsg = 0; float temp = 0; int inPin = reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect if (client.connect("arduinoClient_temperature_sensor")) { Serial.println("connected"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } } void setup() { Serial.begin(115200); setup_wifi(); client.setServer(mqtt_server, 1883); pinMode(inPin, INPUT); sensors.begin(); } void loop() { if (!client.connected()) { reconnect(); } client.loop(); long now = millis(); if (now - lastMsg > 60000) { lastMsg = now; sensors.setResolution(12); sensors.requestTemperatures(); // Send the command to get temperatures temp = sensors.getTempCByIndex(0); Serial.println(temp); if((temp > -20) && (temp <60)) { client.publish("ha/_temperature1", String(temp).c_str(),TRUE); } } } . Step 4: Install and Configure Home-assistant on a Ubuntu Server (for Local and Remote Monitoring) For full instructions to install and configure home-assistant you can pop over to. But here are some pointers to get things working. You will need to have python3-pip installed first of all: root@ubuntu:~# apt-get install python3-pip Once pip is installed you can install home-assistant: pip3 install homeassistant You then just run hass as follows: root@ubuntu:~# hass This will run hass and will create a basic configuration file which we will now edit to add the sensor for the temperature. Your home-assistant configuration file should be in your /home/USERID/.homeassistant dir, called configuration.yaml. Open this and you'll need to add a section for the MQTT server and add a new sensor to it as follows: mqtt: broker: 127.0.0.1 port: 1883 keepalive: 1000 protocol: 3.1 client_id: home-assistant-1 sensor: platform: mqtt state_topic: "ha/_temperature1" name: "Back garden" unit_of_measurement: "°C" qos: 1 As you can see the state_topic is the same as what you have set in the sketch on the ESP8266. Once you have saved the config file, restart hass, by just pressing ctrl-c to stop it then run it again by typing hass again. If you then browse to the IP address of your ubuntu server on port 8123 (default port for home-assistant) you should see something like the pic above. If you want to add the temperature to a 'card' on the webpage, which does look much nicer, then you can just add a group for the temperatures (in this case just the one temperature for now) as follows: group: temperatures: name: Temperatures entities: - sensor.back_garden Be the First to Share Recommendations 12 Comments 3 years ago Is there any reason to communicate only the temp within the range of -20 to 60 °, since the ds18b20 can read temperatures up to 125 °? 3 years ago how do i add another temp sensor to the esp8266? and can i send the other sensor on another topic? 5 years ago. Reply 5 years ago Its not well documented, but in the call to client.connect, clientID should be unique. This tripped me up as well. You can use the MAC address as the clientID, it will be unique to the network. char myClientID[18]; WiFi.macAddress( ).toCharArray( myClientID, sizeof( myClientID )); if (client.connect( myClientID )) { Serial.println("connected"); } The Arduino IDE really should be able to generate a unique UUID at compile time. It would save a lot of headaches. 5 years ago Thanks for the super good and inspiring article on Remote Temperature Monitoring Using MQTT and ESP8266. Currently I have a mosquitto Broker running on a Raspberry Pi, and a ESP8266 with your sample code. It works fine, and I can see the temperature in a terminal window on my RPI. Now, I try with another ESP8266 with the same code, but then it goes wrong. On the other ESP8266 I can see in the terminal window that it loses the connection to mosquitto Broker, and constantly trying to reconnect. There are 8 meters between the two ESP8266 so that they should not disturb each other. Via an android WiFi analyzes App, I can see that the two ESP8266 emits a WiFI signal called DoitWiFi, on the same channel as my WiFi Access Point / Router. It is perhaps the reason for the bad connection, but how do I turn this WiFi signal off ?. It is as if ESP8266 acting as an independent Access Point. Can it be changed? The applied ESP8266 is a GreekCreit.NodeMcu-Lua-ESP8266-ESP12E. See link below. Reply 5 years ago It turns out that ESP8266 by default run in Mixed Mode and that this can be changed by inserting the following sentence in the Void Setup_wifi () void setup_wifi () { WiFi.mode (WIFI_STA); // Sets the unit in Station Mode, and not by default Mixed Mode. This disappears this extra WiFi signal. Unfortunately, it has not changed that when two devices connected while you lose the current connection to MQTT broker? ? ? Is it something to be used different user account, or else ii compared to MQTT broker? 5 years ago Is this concept using internet? or local wifi only? 5 years ago Did you try any measurements on the power consumption for ESP8266 configuration? I think about some sensors in my garden and having them on battery sounds not so promising at a first glance. Sending temperature every 15 minutes is ok, but I am not sure how much the batteries will last, 1 month will be ideal :D Reply 5 years ago. Reply 5 years ago Thanks, I'll let you know my findings when I'm done, your project is a good start for what I want to do :) 5 years ago Thanks for this, love the focus om MQTT! 5 years ago Thanks for the follow-up Instructable to your other Instructable. Look forward to trying it out.
https://www.instructables.com/Remote-Temperature-Monitoring-Using-MQTT-and-ESP82/
CC-MAIN-2021-43
refinedweb
1,791
64.61
QtChart window disappears Hello all, I'm trying to use the simple linechart example to work in my code. I'm trying to get the chart window to display from within a button function that does some calculations to get the data points. When the time comes for the chart to display, I can see it pop up and disappear almost instantly. After a lot of reading, I think it has to do with trying to create a new QMainWindow from inside the button? Here is my most recent code that is supposed to set up the chart window: #include "mainwindow.h" #include "ui_mainwindow.h" #include "QtCharts/QChartView" #include "QtCharts/QLineSeries" #include "QtCharts/QLegend" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); // Hide all Buttons // ui->btnHeading->setVisible(false); } QMainWindow *chartWindow = new QMainWindow(0); chartWindow->setCentralWidget(&ChartView); chartWindow->resize(800,600); MainWindow::~MainWindow() { delete ui; } And here is the button that is supposed to display the chart: void MainWindow::on_btnHeading_clicked() { QLineSeries *series = new QLineSeries(); PGNListCount = PGNList.count(); qDebug() << PGNListCount; for (int i=0;i<PGNListCount;i++) { if (PGNList.at(i).contains("127250")) { DB21Data << DB2.at(i) + (DB1.at(i)); //graphTime << timeStamp.at(i); } } int DB21DataCount = DB21Data.count(); for (int i=0; i<DB21DataCount;++i) { DB21hex = (((DB21Data.at(i).toInt(&ok, 16))*0.0001)*57.296); series->append(i, DB21hex); //qDebug() << series << DB21hex; } QChart *chart = new QChart(); chart->legend()->hide(); chart->addSeries(series); chart->createDefaultAxes(); chart->setTitle("Heading"); QChartView *chartView = new QChartView(chart); chartView->setRenderHint(QPainter::Antialiasing); // QMainWindow window; // window.setCentralWidget(chartView); // window.resize(800, 600); chartWindow->show(); } I've tried a few different things - this code errors on the two lines: chartWindow->setCentralWidget(&ChartView); chartWindow->resize(800,600); with "chartWindow does not name a type" Any hints on how I can approach this would be much appreciated! You don't want your chart in a QMainWindow(an app has one of those), you want it in a QDialog. - jsulm Moderators @MScottM As "Main" in QMainWindow suggests a main window is the main window in an application (so many main :-)). That means - a Qt application can only have one QMainWindow. All other windows can be implemented using QWidget or QDialog (as @Chris-Hennes suggested). Okay! Thanks for the suggestions. I am now able to create and show a qwidget window, now I'm working on how to put the QtChart on there... I typically subclass QDialog for everything. So in that case, if you are doing it by hand (rather than using Designer) you are probably looking for something like this (from the QWidget docs): QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(chartView); setLayout(layout); YES! Got it to display a chart with the data I want - now on to fine tuning everything. Thanks again for the hints that got me on the right track! @Chris-Hennes Thanks again - I'm struggling with how to get it into a separate window that can be closed when done, instead of displaying on top of my existing window. Are you subclassing QWidget or QDialog? - jsulm Moderators @MScottM Just call on your dialog instead of exec() Okay, this code: QChartView *chartView = new QChartView(chart); chartView->setRenderHint(QPainter::Antialiasing); QWidget * chartWindow = new QWidget(0); QVBoxLayout *layout = new QVBoxLayout(chartWindow); layout->addWidget(chartView); setLayout(layout); layout->activate(); chartWindow->resize(480,320); chartWindow->show(); opens my chart in a new window like I want, but, I get this error message in the debugger: QWidget::setLayout: Attempting to set QLayout "" on MainWindow "MainWindow", which already has a layout Also, if I close the window then click the button again, I get two charts side by side. I'm thinking there must be some code that properly resets everything when you close the window? Thanks again for all the help! You don't want to just call setLayout()in this case, you want to call chartWindow->setLayout()-- otherwise you are calling the member of your current object (your main window). Aaah! I get it! That solved the error message.
https://forum.qt.io/topic/78415/qtchart-window-disappears
CC-MAIN-2017-34
refinedweb
664
53.71
At HackerLand University, a passing grade is any grade 40 points or higher on a 100 point scale. Sam is a professor at the university and likes to round each student’s grade according to the following rules: - If the difference between the grade and the next higher multiple of 5 is less than 3, round to the next higher multiple of 5 - If the grade is less than 38, don’t bother as it’s still a failing grade Automate the rounding process then round a list of grades and print the results. Input Format First Line - integer - n: number of students - 1<=n<=60 Next Line - integer - grades i: individual grades - 0<=grades i<=100 Output Format Print n lines, each with the rounded value of a student’s grade in input order. Sample Input 0 4 73 67 38 33 Sample Output 0 75 67 40 33 Explanation 0 The first grade, 73 is two below the next higher multiple of 5, so it rounds to 75. 67 is 3 points less than the next higher multiple of 5 so it doesn’t round. 38, like 73, rounds up to next higher multiple of 5, or 40 in this case. 33 is less than 38, so it does not round. solutions of Grading Students Hackerrank problem The difference between the student’s grade and the next multiple of 5 will be less than 3 if grade mode 5 >=3. For example, let’s consider values for the grade in the inclusive interval from 70 through 75: - 70 mod 5 =0 because 5 evenly divides 70, so this would remain unchanged. - 71 mod 5 =1 , so this would remain unchanged. - 72 mod 5 =2 , so this would remain unchanged. - 71 mod 5 =3 , so this would be rounded up to the next multiple of 5. - 71 mod 5 =4 , so this would be rounded up to the next multiple of 5. - 75 mod 5 =0 , so this would remain unchanged. If you perform the same calculations for the grade interval from 75 through 80, you’ll see the same results. this means we have to check wether grade >38 and it’s remainder is >3 or not, or we can say we can check that difference between next highest multiple of 5 and grade is <3 then we will round it else print the same. C++ #include <iostream> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int n,a[60]; cin>>n; for(int i=0;i<n; i++){ cin>>a[i]; if(a[i]>=38){ // grade > 38 int div=(a[i]/5)+1; // 73/5= 14 +1= 15 int next=div*5; // // next higher multiple of 5 if(next-a[i]<3) // diff less than 3 cout<<next<<endl; else cout<<a[i]<<endl; } else cout<<a[i]<<endl; } return 0; } c++ alternate using mod #include <bits/stdc++.h> using namespace std; void solution() { int n, x; cin>>n; for(int i=0; i<n; i++){ cin>>x; if(x>=38 and x%5>=3){ while(x%5!=0){ x++; } } cout<<x<<endl; } } int main () { solution(); return 0; } Python 2 n = int(raw_input().strip()) for a0 in xrange(n): grade = int(raw_input().strip()) if grade>=38 and grade%5>=3: while grade%5!=0: grade = grade + 1 print grade Java import java.util.*; public class Solution { public static int getRoundedGrade(int grade) { if (grade >= 38) { int mod5 = grade % 5; if (mod5 > 2) { grade += 5 - mod5; } } return grade; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); for(int a0 = 0; a0 < n; a0++){ int grade = in.nextInt(); System.out.println(getRoundedGrade(grade)); } in.close(); } }
https://coderinme.com/grading-students-hackerrank-problem-solution-coderinme/
CC-MAIN-2018-39
refinedweb
623
68.1
#include <TagDetector.h> Definition at line 17 of file TagDetector.h. List of all members. Constructor. Definition at line 21 of file TagDetector.h. Gaussian smoothing kernel applied to image (0 == no filter). Used when sampling bits. Filtering is a good idea in cases where A) a cheap camera is introducing artifical sharpening, B) the bayer pattern is creating artifcats, C) the sensor is very noisy and/or has hot/cold pixels. However, filtering makes it harder to decode very small tags. Reasonable values are 0, or [0.8, 1.5]. Used when detecting the outline of the box. It is almost always useful to have some filtering, since the loss of small details won't hurt. Recommended value = 0.8. The case where sigma == segsigma has been optimized to avoid a redundant filter operation. Definition at line 35 of file TagDetector.cc. Definition at line 31 of file TagDetector.cc. Definition at line 23 of file TagDetector.h. Referenced by extractTags().
http://www.tekkotsu.org/dox/classAprilTags_1_1TagDetector.html
CC-MAIN-2022-33
refinedweb
162
61.93
Creating Different Types of Charts in ASP.NET MVC Introduction Creating charts and displaying them in a Web page is a common requirement. As a developer, you might think "What is chart? And, how do I create charts in an ASP.NET application?" One of the popular chart libraries is canvas.js. The canvas.js library is a simple and robust JavaScript API for the HTML5 <canvas> element. This library could be used to generate interactive 2D graphs in a Web browser, by using lines, shapes, paths, images, and text. In this article, we will see how to use canvas.js to create various charts, such as Line, Column, Area, and Pie for ASP.NET MVC applications. Sample Application to Add a Chart to an MVC Page Select Visual C# → Web → ASP.NET Web Application. In the "Name:" field, type the name "ProjectChart", and then click "OK", as shown in Figure 1. Figure 1: New ASP.NET MVC Application On the next screen, select "Empty" on the "Select a template" menu. Then, under "Add folders and core references for:", check the "MVC" checkbox, as you can see in Figure 2. Figure 2: Select ASP.NET MVC Empty Project Template Once the MVC project is created, your empty ASP.NET MVC solution would look like Figure 3. Figure 3: ASP.NET MVC Blank Solution If you execute the project now, you will get a 404 error because there's no "Controller" or "View" to browse to. We have just created a structure of an ASP.NET MVC project. To add a simple Controller and View in the MVC project, right-click the "Controller" folder and select "Add" → "Controller", as depicted in Figure 4. Figure 4: Add a New Controller in the Project On the "Add Controller" screen, type "ChartController" in the "Controller name" text box and select "Empty MVC controller", as shown in Figure 5. Then, click "Add", as shown in Figure 6. Figure 5: Select a Controller Type Figure 6: Enter Name of a Controller Once the controller is added, you will see the "ChartController.cs" class being added to the "Controllers" folder. Double-click the "ChartController.cs" file & right-click the "Index()" method and select "Add View" (see Figure 7). Figure 7: Add a New View Uncheck the "Use a layout or master page" checkbox. Accept the default settings. MVC uses conventions so the view has the same name as the method name in the "ChartController.cs" file, which is "Index()"; then, click "Add", as shown in Figure 8. Figure 8: Enter a View Name In the "Views" folder, you see that the "Chart" folder has been created with the view "Index.cshtml". The .cshtml extension means that the view uses the C# syntax (Razor). Finally, copy and paste the following HTML code on the Index.cshtml page. To create the chart, you need to include CanvasJS Script in the header. That's why I have added the following JavaScript library reference. <script src=""> Once the script is added, I have created a div element inside the body and set its ID as chartContainer. This is where the chart will be rendered. <div id="chartContainer"></div> The JavaScript function will create the chart inside the window's onload event. @{ ViewBag. <title>Chart View</title> <script src=""> </script> <script type="text/javascript"> window.onload = function () { var chart = new CanvasJS.Chart("chartContainer", { theme: "theme2", animationEnabled: true, title: { text: "My Sample Column Chart Created in ASP.NET MVC" }, subtitles: [ { text: "Resize the Browser" } ], data: [ { // change type to bar, line, area, pie, etc. type: "bar", dataPoints: [ { x: 10, y: 71 }, { x: 20, y: 55 }, { x: 30, y: 50 }, { x: 40, y: 65 }, { x: 50, y: 95 }, { x: 60, y: 68 }, { x: 70, y: 28 }, { x: 80, y: 34 }, { x: 90, y: 14 } ] } ] }); chart.render(); }; </script> </head> <body> <div id="chartContainer"> </div> </body> </html> The following controller code returns the Index view. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace ProjectChart.Controllers { public class ChartController : Controller { // GET: Chart public ActionResult Index() { return View(); } } } Now, execute the code. It should display the chart shown in Figure 9 in your browser. Figure 9: The chart produced by your hard work Conclusion In this article, you have learned how to create charts, using canvas.js. I hope you enjoyed the reading this article. Stay tuned. That's all for today. Happy coding!
https://www.codeguru.com/csharp/.net/net_asp/mvc/creating-different-types-of-charts-in-asp.net-mvc.html
CC-MAIN-2019-30
refinedweb
734
76.32
Practical TypeScript. You can download TypeScript 2.0 or get the TypeScript 2.0 compiler through NuGet -- provided, of course, you're working in Visual Studio 2015 with Update 3 or Visual Studio Code. Even if that doesn't describe you, if you're a server-side/datatyping programmer thinking about moving into client-side coding, TypeScript might well be in your future (the TypeScript team claimed 2 million downloads in August of 2016, just through npm). Here's why this release will matter to TypeScript programmers who value type checking and want to avoid errors related to variables set to null or undefined. TypeScript 2.0 also provides a new way to distinguish between related classes. Better Data Typing The most common error with JavaScript code (other than mistaking what the this keyword refers to) is probably errors with variables that are currently set to the null or undefined types. In previous versions of TypeScript a variable declared as some type could always be used with a variable set to null or undefined allowing null/undefined values should be to propagate through your code. In TypeScript 2.0, that's no longer the case. If you want a variable to accept null or undefined then you have to declare that by using a union type. In the following code, the compiler will not allow the variable strictSample to be set to anything but Boolean value (no null or undefined), will allow the variable flexibleSample to be set to a Boolean value or undefined (no null) and will allow veryFlexibleSample should be to be set to a Boolean value or either undefined or null: var strictSample: boolean; var flexibleSample: boolean | undefined; var veryFlexibleSample: boolean | null | undefined; One wrinkle (and then one caveat): Because this is potentially a breaking change in TypeScript (it redefines all previous declarations), you have to turn this option on. You can do that by adding --strictNullChecks to the options in your compiler's command line but it's probably easier just to set the option in your tsconfig.json file like this: { "compilerOptions": { "strictNullChecks": true, Which brings me to the caveat: This is a compiler-time check, not a run-time check. It's probably still possible to insert null and undefined values into these variables at run-time if you're tricky enough. This option does not add a bunch of tests for undefined or null to your generated code. Collateral Enhancements To make these restrictions work at compile time, the compiler relies on enhanced flow analysis capabilities. The 2.0 version of the TypeScript compiler can do a much better job of figuring out what your code will do at runtime. This means that, over and above stricter type checking, you can expect better compile-time reports on errors in your code (the compiler will do a better job on reporting how use you use uninitialized variables, for example). This change also alters how your classes use optional parameters and provide support for optional properties and methods in your classes. With parameters, regardless of how you declare an optional parameter for a method, the undefined type is automatically added to the parameter's declaration. By the time that the compiler is finished with them, these two declarations are identical, for example: function UpdateCustomer(cust?: Customer): boolean {...} function UpdateCustomer(cust?: Customer | undefined): boolean {...} But you can now declare optional properties and methods in a class. You indicate that by adding a question mark to the end of a property or method's name. This class declares both the age property and the calculateAge method as optional, for example: public class Customer { id: string; name: string; age?: number; calculateAge?(): number With this declaration, a valid Customer object can omit the age property and skip providing an implementation for the calculateAge method. When a class does omit those members, clients that access that property or method will find them set to undefined. To ensure that the property or method is present, you can use a type guard (a test for data type or presence) around code that uses optional properties my methods. Using my Customer object, I could write code like this: function UpdateCustomer(cust: Customer) { if (cust.age && cust.calculateAge) { //...use age and calculateAge } The if test on age and calculateAge will only pass if both are not set to undefined and, as a result, the code inside the code block is guaranteed to find a value in age and an implementation in calculateAge. If you think the compiler can't determine your intentions regarding null and undecided from your code, you can signal that your variable won't accept null or undefined by adding an exclamation mark (!) to the end of your variable name. This code asserts that the variable cust may not be null or undefined when accessing the isValid property: if (cust!.isValid) {...} This change also impacts both expressions (a statement that can be evaluated down to a single value -- x + y is an expression, for example) and inferred data types. In TypeScript, the output of an expression is always assigned a data type. With strictNullChecks turned on, that data type does not include null or undefined -- it will always be some strict data type even if values in the expression accept null or undefined...with one exception. That exception is around expressions that include logical ANDs (&&) or logical ORs (||). Logical ANDs will automatically propagate undefined or null types from the right-hand side of an equals sign to the left-hand side. So if one of the inputs of a logical AND includes null or undefined in its datatype then the result of the logical AND will also include null or undefined. Logical OR (||), on the other hand, strips undefined and null out of the type of the result even if the inputs included it. Finally, if you let the compiler infer your data type by simply assigning a value to a newly declared variable, the compiler will not widen the type to include null or undefined. This means that the variable in the following code is especially useless because it can only be assigned a single value: null. Without strictNullChecks, the variable's data type would have been expanded to the any type and the variable could be assigned any value at all: var limited = null; Determining Types by Property Values You can now declare discriminant properties (properties whose value identifies a class) when declaring classes and then use those values in type guards to ensure that your code is only dealing with a specific class. This is equivalent to having a table in a database that holds several different kinds of data and has a column that distinguishes between those types (e.g. a PayType column that distinguished between salaried and hourly employees). For example, assume that you want to write a function that will handle two kinds of objects: Parts and Services. You define your Part class like this: class Part { ProductType: "Part"; Price: number; } And then add a Service class that looks like this: class Service { ProductType: "Service"; HourlyCharge: number; CalloutRate: number; } The ProductType property in both classes is a string property that can only be set to one value ("Part" in the Part class, "Service" in the Service class). That ProductType property acts as a discriminant property for the two classes and doesn't need to be set when instantiating a class. This code, for example, creates a Service class and just sets the two properties on the class (the ProductType property is set automatically): var serv: Service; serv = new Service(); serv.CalloutRate = 50; serv.HourlyCharge = 5; You can now declare a parameter to a function as a union of Part and Service, like this: function CalculatePrice (prod: Part | Service, quantity: number) { var cost: number; Within this class, you can test to see which kind of object you've been passed by looking at the ProductType property and do the right thing with the object. That test acts as a type guard to ensure that, within the test's code block, you have the right object. In addition, with TypeScript 2.0, switch statements can act as type guards. As an example, in this code, my switch statement checks to see whether I have a Part or a Service. Within the code block for "Part," IntelliSense will show me only the properties for Part objects: switch (prod.ProductType) { case "Part": cost = prod.Price * quantity; break; case "Service": cost = prod.HourlyCharge * quantity + prod.CalloutRate; break; } There's more, of course. For example, TypeScript 2.0 now supports the readonly keyword which can be used with fields (variables declared outside of any method or property) to specify a variable that can only have its value set in a class' constructor. Any property declared with a getter and without a setter is assumed to be a readonly property whose value can only be set in the class' constructor. If you like data typing and were thinking of moving to client-side programming, TypeScript has always been an attractive option. TypeScript 2.0 just makes it more attractive.
https://visualstudiomagazine.com/articles/2016/12/05/typescript-2-0-data-typing-class-discriminants.aspx
CC-MAIN-2018-26
refinedweb
1,517
57.71
[Python] Creating Custom Cookies for HTTP Requests 14 May, 2011 Leave a comment One way of adding a custom cookie is to directly specify the "cookie" field in your request header. For example: request.add_header("Cookie", "something=test+1+2+3; source=script") Here, two cookies are set in the request ("something" and "source"). Notice that the cookies are fully specified in the string, instead of using urllib.urlencode. Another way of adding cookies is to create Cookie objects and add them to your CookieJar. Before sending your request, add the cookies by using add_cookie_header. An example for Python 2.7: from cookielib import Cookie from cookielib import CookieJar from urllib2 import Request import urllib2 import urllib ''' Makes a cookie with provided name and value. ''' def makeCookie(name, value): return Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain="kahdev.bur.st", domain_specified=True, domain_initial_dot=False, path="/", path_specified=True, secure=False, expires=None, discard=False, comment=None, comment_url=None, rest=None ) # Create a cookie jar to store our custom cookies. jar = CookieJar() # Generate a request to make use of these cookies. request = Request(url="") # Use makeCookie to generate a cookie and add it to the cookie jar. jar.set_cookie(makeCookie("name", "kahdev")) jar.set_cookie(makeCookie("where", "here")) # Add the cookies from the jar to the request. jar.add_cookie_header(request) # Now, let us try open and read. opener = urllib2.build_opener() f = opener.open(request) print "Server responds with: " print f.read() The above source can also be downloaded from my Github repository. If you run it, you should see the following output: # python cookies.py Server responds with: Cookies: [where] = [here] [name] = [kahdev] Note that the 2.7 documentation for Cookie indicates that you should not need to be doing this often: It is not expected that users of cookielib construct their own Cookie instances. Instead, if necessary, call make_cookies() on a CookieJar instance. However, the method make_cookies is for extracting cookies from HTTP responses.
https://kahdev.wordpress.com/2011/05/14/544/
CC-MAIN-2019-13
refinedweb
327
50.43
The QShortcut class is used to create keyboard shortcuts. More... #include <QShortcut> The QShortcut class is used to create keyboard shortcuts. The QShortcut class provides a way of connecting keyboard shortcuts to Qt's signals and slots mechanism, so that objects can be informed when a shortcut is executed. The shortcut can be set up to contain all the key presses necessary to describe a keyboard shortcut, including the states of modifier keys such as Shift, Ctrl, and Alt. On certain widgets, using '&' in front of a character will automatically create a mnemonic (a shortcut) for that character, e.g. "E&xit" will create the shortcut Alt+X (use '&&' to display an actual ampersand). The widget might consume and perform an action on a given shortcut. On X11 the ampersand will not be shown and the character will be underlined. On Windows, shortcuts are normally not displayed until the user presses the Alt key, but this is a setting the user can change. On Mac, shortcuts are disabled by default. Call qt_set_sequence_auto_mnemonic() to enable them. However, because mnemonic shortcuts do not fit in with Aqua's guidelines, Qt will not show the shortcut character underlined. For applications that use menus, it may be more convenient to use the convenience functions provided in the QMenu class to assign keyboard shortcuts to menu items as they are created. Alternatively, shortcuts may be associated with other types of actions in the QAction class. The simplest way to create a shortcut for a particular widget is to construct the shortcut with a key sequence. For example: shortcut = new QShortcut(QKeySequence(tr("Ctrl+O", "File|Open")), parent); When the user types the key sequence for a given shortcut, the shortcut's activated() signal is emitted. (In the case of ambiguity, the activatedAmbiguously() signal is emitted.) A shortcut is "listened for" by Qt's event loop when the shortcut's parent widget is receiving events. A shortcut's key sequence can be set with setKey() and retrieved with key(). A shortcut can be enabled or disabled with setEnabled(), and can have "What's This?" help text set with setWhatsThis(). See also QShortcutEvent, QKeySequence, and QAction. This property holds whether the shortcut can auto repeat. If true, the shortcut will auto repeat when the keyboard shortcut combination is held down, provided that keyboard auto repeat is enabled on the system. The default value is true. This property was introduced in Qt 4.2. Access functions: This property holds the context in which the shortcut is valid. A shortcut's context decides in which circumstances a shortcut is allowed to be triggered. The normal context is Qt::WindowShortcut, which allows the shortcut to trigger if the parent (the widget containing the shortcut) is a subwidget of the active top-level window. By default, this property is set to Qt::WindowShortcut. Access functions: This property holds whether the shortcut is enabled. An enabled shortcut emits the activated() or activatedAmbiguously() signal when a QShortcutEvent occurs that matches the shortcut's key() sequence. If the application is in WhatsThis mode the shortcut will not emit the signals, but will show the "What's This?" text instead. By default, this property is true. Access functions: This property holds the shortcut's key sequence. This is a key sequence with an optional combination of Shift, Ctrl, and Alt. The key sequence may be supplied in a number of ways: setKey(0); // no signal emitted setKey(QKeySequence()); // no signal emitted setKey(0x3b1); // Greek letter alpha setKey(Qt::Key_D); // 'd', e.g. to delete setKey('q'); // 'q', e.g. to quit setKey(Qt::CTRL + Qt::Key_P); // Ctrl+P, e.g. to print document setKey("Ctrl+P"); // Ctrl+P, e.g. to print document By default, this property contains an empty key sequence. Access functions: This property holds the shortcut's "What's This?" help text. The text will be shown when the application is in "What's This?" mode and the user types the shortcut key() sequence. To set "What's This?" help on a menu item (with or without a shortcut key), set the help on the item's action. By default, this property contains an empty string. Access functions: See also QWhatsThis::inWhatsThisMode() and QAction::setWhatsThis(). Constructs a QShortcut object for the parent widget. Since no shortcut key sequence is specified, the shortcut will not emit any signals. Constructs a QShortcut object for the parent widget. The shortcut operates on its parent, listening for QShortcutEvents that match the key sequence. Depending on the ambiguity of the event, the shortcut will call the member function, or the ambiguousMember function, if the key press was in the shortcut's context. Destroys the shortcut. This signal is emitted when the user types the shortcut's key sequence. See also activatedAmbiguously(). When a key sequence is being typed at the keyboard, it is said to be ambiguous as long as it matches the start of more than one shortcut. When a shortcut's key sequence is completed, activatedAmbiguously() is emitted if the key sequence is still ambiguous (i.e., it is the start of one or more other shortcuts). The activated() signal is not emitted in this case. Returns the shortcut's ID. See also QShortcutEvent::shortcutId(). Returns the shortcut's parent widget.
https://doc.qt.io/archives/qt-4.7/qshortcut.html
CC-MAIN-2021-17
refinedweb
876
66.74
Samrat Som wrote:Hey can you just explain a bit ...what you are trying to achieve with a small example rather than putting such a long jittery of code... It is always better to make a simple code replicating the problem rather than this which couls help to solve it faster and efficiently .... pete stein wrote:Your problem is that you have one Calendar instance, dueDate that is never reconstructed, and so whenever you change the state of dueDate, you change the state of all Calendar objects that refer to this same instance. Solution: reconstruct a new Calendar object each time you need it: public class TabDemo2 { JFrame frame; JPanel panel; JSpinner dateSpinner; //!!Calendar dueDate = Calendar.getInstance(); // get rid of this //..... code deleted class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { Date dS = (Date) dateSpinner.getValue(); String dateLine = String.format("%1$tm/%1$td/%1$tY %1$tl:%1$tM %1$Tp", dS); SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm aa"); Calendar dueDate = Calendar.getInstance(); // add this! //..... code deleted Sebastion Hill wrote:Thanks Pete, even now I was going over the Calendar class but I don't think I wouldn't have spotted that without your help. Thanks so much, works great now :-) pete stein wrote: Sebastion Hill wrote:Thanks Pete, even now I was going over the Calendar class but I don't think I wouldn't have spotted that without your help. Thanks so much, works great now :-) You're entirely welcome. I also agree with the poster above in that if you are going to be adding to your collection only from within Swing's EDT or event dispatch thread, then there's no need to have the overhead of a synchronized collection. Best of luck, Pete
http://www.coderanch.com/t/455713/java/java/completely-lost-terms-understand-Collections
CC-MAIN-2015-22
refinedweb
293
63.29
C# - Menu Strip Duplicating for no Apparent Reason I'm creating a Windows form based multi tap (old phone keypad) type system, using timers and arrays. However, whenever I click a button to append text to a text box, the menu strips duplicates vertically, I have no idea why seem as I have note referenced the menu string in my CS. The code itself isn't finished, I'd just like to stop this duplication from happening, and for the character from the array to actually append to the Rich Text Box. Any help at all would be appreciated, thanks! using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Mini_Keyboard { public partial class MiniKeyboard : Form { public MiniKeyboard() { InitializeComponent(); } string currentMode = "Multi Tap"; // Sets the mode of the app on startup to be "Multi Tap" int intIntervalRequired = 1000; // Time interval in which the user has to switch through the characters string currentKey; string prevKey; int currentIndex = -1; string[] keyPad1 = new string[7] { ".", "~", "\"", "1", "'", ":", ";" }; // Characters for key 1 string[] keyPad2 = new string[7] { "a", "b", "c", "2", "A", "B", "C" }; // Characters for key 2 string[] keyPad3 = new string[7] { "d", "e", "f", "3", "D", "E", "F" }; // Characters for key 3 string[] keyPad4 = new string[7] { "g", "h", "i", "4", "G", "H", "I;" }; // Characters for key 4 string[] keyPad5 = new string[7] { "j", "k", "l", "5", "J", "K", "L" }; // Characters for key 5 string[] keyPad6 = new string[7] { "m", "n", "o", "6", "M", "N", "O" }; // Characters for key 6 string[] keyPad7 = new string[9] { "p", "q", "r", "s", "7", "P", "Q", "R", "S" }; // Characters for key 7 string[] keyPad8 = new string[7] { "t", "u", "v", "8", "T", "U", "V" }; // Characters for key 8 string[] keyPad9 = new string[9] { "w", "x", "y", "z", "9", "W", "X", "Y", "Z" }; // Characters for key 9 string[] keyPad0 = new string[2] { "0", " " }; // Characters for key 0 string[] keyPadStar = new string[3] { "*", "-", "_" }; // Characters for key Star string[] keyPadHash = new string[3] { "#", "-", "_" }; // Characters for key Hash Timer timer = new Timer(); public void runTimer() { InitializeComponent(); timer.Tick += new EventHandler(stopTimer); timer.Interval = intIntervalRequired; timer.Enabled = true; timer.Start(); } public void stopTimer(object sender, EventArgs e) { timer.Stop(); prevKey = currentKey; currentKey = ""; currentIndex = -1; } private void btnChangeMode_Click(object sender, EventArgs e) { if (currentMode == "Multi Tap") // If the current mode is "Multi Tap", change it to "Prediction" { currentMode = "Prediction"; txtCurrentMode.Text = currentMode; } else // If the current mode is "Prediction", change it to "Multi Tap" { currentMode = "Multi Tap"; txtCurrentMode.Text = currentMode; } } private void btnKeyPadNo2_Click(object sender, EventArgs e) { currentKey = "2"; appendChar(ref keyPad2); } public void appendChar(ref string[] key) { runTimer(); if (currentIndex == -1) { currentIndex++; rtbCurrentString.AppendText(key[currentIndex]); } } } } This is a recode of a form I made before which had the same bug, I decided to start from scratch to fix it, but it didn't. Here's a link to a screencap of the problem: UPDATE: Turns out the Mode button is no longer working, and it was fine before this happened. Answers Remove the InitializeComponent(); in runTimer. It should be called once in constructor. Your current flow is: appendChar -> runTimer -> InitializeComponent Need Your Help WP7 Deeplink to Marketplace windows-phone-7 deep-linking marketplaceDoes anyone know what code to use specifically to jump from within a Windows Phone 7 application to the application's listing in the Marketplace?
http://unixresources.net/faq/16352398.shtml
CC-MAIN-2018-43
refinedweb
564
50.46
(a) is ok.. that means my approach is wrong??? and i am unable to understand the point (b).. what is the link tag.. beacuse am new to struts technology also.. please dont mind tell me the things clearly B.Nagarjuna AE-Group +91 9949721747 India (a) Make sure the HTML is rendering the way you expect, and (b) ideally run the home page through an action. Also try setting the namespace explicitly in the link tag; if you're not in an action it might not know where it's mapping from/to. Dave On Tue, Nov 16, 2010 at 11:20 PM, @rju <nagarjunabattula@gmail.com> wrote: -- View this message in context: Sent from the Struts - User mailing list archive at Nabble.com. --------------------------------------------------------------------- To unsubscribe, e-mail: user-unsubscribe@struts.apache.org For additional commands, e-mail: user-help@struts.apache.org
http://mail-archives.us.apache.org/mod_mbox/struts-user/201011.mbox/%3C30235337.post@talk.nabble.com%3E
CC-MAIN-2019-26
refinedweb
143
69.48
1009 Error (Null Object Call) Flash CS4North 60 Nov 30, 2009 6:11 PM Hi All I'm very new to Flash (this is my first attempt) and am trying to figure out how to deal with this error I'm getting. The code is supposed to animate a flyout menu on a mouse hover event. I'm actually surprised I have made it this far before getting stumped. Please help, My brain hurts. Here is my code: import fl.transitions.Tween; import fl.transitions.easing.*; var FishingSub_mc:MovieClip = FishingSub_mc; var Fishing_btn:SimpleButton = Fishing_btn; function FishingFlyout (event:MouseEvent):void { var FishingTween:Tween = new Tween (FishingSub_mc,"y",Regular.easeOut,0,40,20,false); } Fishing_btn.addEventListener(MouseEvent.MOUSE_OVER,FishingFlyout); And here is the error I'm getting: TypeError: Error #1009: Cannot access a property or method of a null object reference. at menu_fla::MainTimeline/frame1()[menu_fla.MainTimeline::frame1:12] Thanks for your help. Dave 1. Re: 1009 Error (Null Object Call) Flash CS4Ned Murphy Nov 30, 2009 7:46 PM (in response to North 60) I am not sure why you have these two lines... var FishingSub_mc:MovieClip = FishingSub_mc; var Fishing_btn:SimpleButton = Fishing_btn; If those two objects are items on your stage, then you should not need those lines of code at all. The important thing is to be sure that you have the instance names assigned to the objects. Whichever object is being targeted on line 12 is out of scope when that code executes. Some of the possible reasons... - the object doesn't have the instance name assigned to it - the object animates into the movie and does not have that instance name assigned at each keyframe - the object is somewhere down a timeline when that code executes 2. Re: 1009 Error (Null Object Call) Flash CS4North 60 Nov 30, 2009 8:19 PM (in response to Ned Murphy) Thanks for the reply. Those two lines of code are there to define two objects. They are on the stage but if I do not define them I recieve the two errors in the attached jpeg. As I said I have only just started programming and it's like learning Japanese to me. . - errors.JPG 23.2 K 3. Re: 1009 Error (Null Object Call) Flash CS4Ned Murphy Dec 1, 2009 4:35 AM (in response to North 60) You do nt need those lines, you need to assign those instance names to the objects on the stage, and those objects need to exist in the frame (not the layer) where that code executes. To give those objects instance names you select each one individually and then enter th name in the properties panel in the input field that says Instance Name 4. Re: 1009 Error (Null Object Call) Flash CS4North 60 Dec 1, 2009 8:28 PM (in response to North 60) You're correct but for some reason Flash was unable to find the objects. I did a little messing around and it now is past that issue and on to the next one. So here is my revised code: 1 import fl.transitions.Tween; 2 import fl.transitions.easing.*; 3 4 function FishingFlyout (event:MouseEvent);void { 5 var FishingFlyout:Tween = new Tween(FishingSub_mc,"y",Regular.easeOut,0,40,20,false); 6 } 7 Fishing_btn.addEventListener(MouseEvent.MOUSE_OVER,FishingFlyout); And my new errors: What do ya think? Tired of my newby questions yet. 5. Re: 1009 Error (Null Object Call) Flash CS4North 60 Dec 3, 2009 6:26 PM (in response to North 60) Ok with a lot of head shaking and lost sleep and a ton of reading I'm getting closer to success. My latest code revision is throwing only one compiler error, but I can't figure out what it actually want's me to do. Probably something simple I'm just not seeing. I'm sure that once I get this last compiler error out of the way, I'll get to deal with run time errors!!!! yay!!! So here's my latest code: 1 import fl.transitions.Tween; 2 import fl.transitions.easing.*; 3 4 //Fishing Button Hover Action 5 6 var startY:Number = fishingSub_mc.y; 7 { 8 function fishingFlyout (event:MouseEvent); void 9 var fishFlyout:Tween = new Tween(FishingSub_mc,y,Regular.easeOut,startY,startY+40,20,false); 10 } 11 Fishing_btn.addEventListener(MouseEvent.MOUSE_OVER,fishingFlyout); And the error is: On line 9 1084: Syntax error: expecting identifier before var. Can't figure out what it want's me to identify. Any ideas O coding guru's?? Thanks Dave 6. Re: 1009 Error (Null Object Call) Flash CS4Ned Murphy Dec 3, 2009 6:40 PM (in response to North 60) I lost touch with your plight, probably due to the delayed response time between our original discussions. It's not the var that's causing the problem. In looking at your code the problem appears to be a semi-colon where a colon is called for... function fishingFlyout (event:MouseEvent); void (only enlarged for clarity, not being a wise-a__) should be... function fishingFlyout (event:MouseEvent): void 7. Re: 1009 Error (Null Object Call) Flash CS4North 60 Dec 3, 2009 6:52 PM (in response to Ned Murphy) I knew it was something simple. Once I got the colon in there and rearranged the brackets plus a couple of other tweaks it does what I wanted it to do!!!!! Thanks for pointing it out. The eye's don't work as well as they used to. Thanks Dave 8. Re: 1009 Error (Null Object Call) Flash CS4Ned Murphy Dec 3, 2009 7:33 PM (in response to North 60) You're welcome, Dave
https://forums.adobe.com/thread/532533
CC-MAIN-2019-04
refinedweb
937
72.76
You can tell that the Visual Studio team recognizes the primary issue C# developers face: finding the matching bracket. That must be true because the most obvious way of finding "the other bracket" is built into the way code is displayed: When you put your cursor beside one bracket (open or close), both it and the matching bracket are highlighted (or, because the default color for the brackets is gray: lowlighted). Unfortunately, that isn't much help if the "matching" bracket is off the screen: you can't see the highlighting if the bracket isn't visible. In those situations my fallback method used to be the plus/minus signs in the left hand margin of the editor window: I collapsed my C# methods to see what code disappeared and what code remained visible. The problem here, of course, is that the collapsed code was often the code in which I was interested. There's a third option that not a lot of developers know about: Place your cursor on the bracket you're trying to match (open or close) and press Ctrl+] (that's the Control key with a closing square bracket). Your cursor moves to the matching bracket. Pressing the key combination again takes you back to the bracket on which you started. There are other benefits: If you're bored and stuck on a problem, I've found repeatedly pressing Ctrl+] and watching the cursor snap back and forth can be soothing. And, if anyone is watching, it looks like you're working. Posted by Peter Vogel on 08/19/2015 at 2:20 PM0 comments Developers frequently want to ensure two strings are identical without having to worry if some characters are in uppercase in one string and the same characters are in lowercase in the other string. Frequently, you see developers using either ToUpper or ToLower to avoid the problem: If Name.ToUpper = OtherName.ToUpper Then... But both ToUpper and ToLower create new strings, which is extra (and unnecessary) work. If you can live with some extra typing, you can avoid generating those new strings by using the Equals method that every variable has, passing the InvariantCultureIgnoreCase choice from the StringComparison enumeration: if (Name.Equals(OtherName, StringComparison.InvariantCultureIgnoreCase)) Now you have much less to worry about. Posted by Peter Vogel on 08/12/2015 at 2:20 PM0 comments The is keyword lets you check if a variable is pointing to an object of a particular class (or a class that inherits from some class). For example, the code in this if block only executes if CustomerVariable is pointing at an object of type Customer (or some class that inherits from Customer): if (CustomerVariable is Customer) { ...code to execute... } It works with interfaces, too: if (CustomerVariable is ICustomer) { ...code to execute ... } You can do your test and get a free cast from a variable by using the as keyword. If the cast fails, no exception is raised, but your destination variable is set to null, telling you that the variable isn't compatible with the object. The following code not only does what the previous code did, but also casts whatever object PremiumCustomerVariable is pointing to into CustomerVariable (if CustomerVariable and the object are compatible, of course): CustomerVariable = PremiumCustomerVariable as Customer; if (CustomerVariable != null) { ...code to execute if PremiumCustomerVariable could be cast as a Customer... } If you want to do the same thing using the variable's class (rather than using some object as the previous examples did) then you want to use IsAssignableFrom: if (typeof(Customer).IsAssignableFrom(typeof(PremiumCustomer))) { CustomerVariable = PremiumCustomerVariable; } This also works with interfaces: if (typeof(ICustomer).IsAssignableFrom(typeof(PremiumCustomer))) { ICustomerVariable = PremiumVariable; } What other ways do you use to check? Share in the comments section. Posted by Peter Vogel on 08/04/2015 at 2:20 PM0 comments I suspect I'm like most developers and keep Visual Studio open and maximized all day (in fact, I've written at least one tip about how to get even more room to edit code). But, I admit, sometimes I switch to other programs. And sometimes, when switching between windows isn't good enough, I need to see that other window beside my Visual Studio window. You could fiddle with your mouse and window borders. Or, you could hold down the Windows key and press the left arrow button (win_left). The current window will be moved to one side of your screen, have its height set to the full height of your screen and its width set to half of the screen's width. If you switch to another window and press win_left the same thing will happen to that window -- but it will be moved to the other side of your screen so that the two windows display side-by-side. If a window was in maximize mode, it will be taken out of it. As you might suspect, other combinations of the Windows key and the arrow keys do interesting things. If you press win_up, the current window will be maximized. Both win_right and win_down take the window back to its prior "non-maximized" state (and that half-window display that win_left put you in doesn't count as your prior "non-maximized" state). And, yes, I realize this isn't really a Visual Studio tip since it works with every window. Posted by Peter Vogel on 07/30/2015 at 2:20 PM0 comments I admit it: I don't use the Watch window much. When I hit a breakpoint and want to know what the current value is in a variable that's near the breakpoint, I'll either type "?variableName" in the Immediate window or hover my mouse over the variable to have Visual Studio pop up a Data Tip with the variable name and value. If you're a "hover your mouse" kind of person you should pay attention to the pushpin at the end of the Data Tip: If you click on the pushpin and switch it to the "upright" position, that Data Tip will stay on the screen. The next time you hit the breakpoint (actually, whenever you have that part of your code on the screen) the Data Tip will be there, displaying the current value of the variable. If you need to drill down into the variable, you can use the plus sign (+) at the beginning of the Data Tip to see the values on the item's properties. You can do more with your Data Tip: When you hover your mouse over the Data Tip, a "mini-menu" of choices will appear just past the end of the Data Tip. The middle icon in this mini-menu will let you unpin the tip which does not, as you might expect, cause the tip to disappear. Instead, the tip just drifts off to the right and now appears whenever you hit a breakpoint in any code window. This can be very helpful when you're trying to check one variable's value against another or want to change the value of the variable in the Data Tip. The bottom option in the mini-menu, which lets you leave a comment to yourself, can also be useful if your memory is as bad as mine. The Debug menu also has some choices for managing Data Tips (including exporting and importing Data Tips if you want to keep some around after your debugging session ends). Data Tips are not an unalloyed blessing, if you have long variable names (names are usually displayed with their complete namespace): If the name disappears off the right side of your screen you won't get a scroll bar that will let you move to the right. Posted by Peter Vogel on 07/23/2015 at 2:20 PM0 comments Within an Action method, you'll sometimes realize that the processing you need is in some other Action method, often in the same controller. ASP.NET MVC provides a couple of ways of transferring control from one Action method to another one, but, sometimes, the simplest solution is just to call the other method. In those cases, it's worthwhile to remember that when you call the View method in ASP.NET MVC, you're not actually processing a View. The View method merely creates a ViewResult object that, when you return it to ASP.NET MVC, causes ASP.NET MVC to find the View and process it. In a recent project, many of my controller methods ended by redisplaying the initial page. I had already created a View that did that: It was the first View that's displayed by the controller (I called the Action method that delivered the View FirstDisplay). That method looked like this: Public Function FirstDisplay (id As Integer?) As ActionResult ...code to load the result object with the data to display... Return View("DisplayItem", result) End Function In my other methods, I could just call FirstDisplay to redisplay the page. FirstDisplay would return the ViewResult object with the correct data, so I just had to return the results of FirstDisplay to get the page I wanted: Public Function Update (id As Integer?) As ActionResult ...code required by the action method... Return FirstDisplay(id) End Function See? Recycling is good. Posted by Peter Vogel on 07/15/2015 at 10:55 PM0 comments In the bad old days of desktop applications, every form object in the world had a Dirty property that let you easily check to see if the user had made any changes to the data on the form. It's almost as easy with client-side code running in the Web browser, provided you use jQuery. This line finds every input tag and ties the tag's change event to a JavaScript function called flagChanges: $("input").change(function () { flagChanges(); }); That will catch your textboxes, checkboxes, and any other input item defined with an input element. If you also want to catch changes in other elements, you can selectively add additional jQuery statements. This statement will catch changes made from dropdown lists (defined with select elements): $("select").change(function () { flagChanges(); }); You can do what you want in your flagChanges function, but here's a version that shoves some bolded text inside another element with an id of ChangeTextDiv (based on the name, probably a div element): function flagChanges() { $("#ChangeLabelDiv").html("<b>unsaved changes in page</b>"); } You'll need to remember to clear that element whenever you let the user save their changes. That's what this line of jQuery does: $("#ChangeLabelDiv").html("<br/>"); Posted by Peter Vogel on 07/07/2015 at 11:19 AM0 comments0 comments While AM0 comments Years and years ago, I talked about how interfaces and inheritance were tools for making different objects look alike. Using interfaces and inheritance this way allows you to process a heterogeneous group of objects using a single variable. In that column, I also pointed out that you sometimes needed to determine what the underlying class was for a group of objects that all looked alike to you. The TypeOf keyword is primary tool you have for determining what class an object "really" is. However, if you were doing a negative test with TypeOf, you had to write some pretty unreadable code. This example tries to determine if the object pointed to by the cust variable is "really" a PremiumCustomer: If Not TypeOf cust Is PremiumCustomer Then Visual Basic 14 now lets you use the IsNot keyword with TypeOf so that you can write this more readable version: If TypeOf sender IsNot Button Then Visual Basic just gets better and better. Posted by Peter Vogel on 06/11/2015 at 10:35 AM0 comments I'm not a big fan of commenting code, which means that when I feel the need to add a comment it's because I feel that the comment is critical to the code's future. As a result, I want any comments I add to have maximum impact/usefulness. In Visual Basic, however, I can only put comments before or after the statements that I want to comment. This is especially limiting in LINQ queries, which I often break up over multiple lines, putting each LINQ clause on a different line. This means that a comment on the line before the LINQ query may be explaining something three or four lines farther down the screen. With Visual Basic 14, I can finally put my comments where I want them: In-line with the part of the LINQ query I want to explain. This example uses a comment to explain a Where clause: Dim PremCusts = From c In db.Customers Where c.Id % 2 = 0 'Premium customers have an even numbered id Select c You can also use in-line comments when you break up a statement over multiple lines using implicit line continuation. Posted by Peter Vogel on 06/09/2015 at 8:31 AM0 comments In Visual Basic 14, can now have read-only auto-implemented properties: Just add the ReadOnly keyword to the Property declaration. Here's an example: Class Customer Public ReadOnly Property Id As String You can set the property by name from within your class' constructors. This example sets my Customer's Id property: Sub New(Id As String) Me.Id = Id End Sub From elsewhere in your class, you can not set the property's value using the property's name. This code won't work anywhere outside of the class' constructor: Me.Id = Id However, you can access the backing field for the property and set the property's value through that. The backing field will have the same name as the property with an underscore prefixed to the property name. This example updates my read-only Id property through its backing field: _Id = "Fred" On a related note: If you have an interface that specifies that a property is read-only, in Visual Basic 14 you don't have to honor that restriction when you implement the interface in a class. The interface that specifies a ReadOnly property will be happy with either a read-only or a read-write implementation in the class that implements the interface. Posted by Peter Vogel on 05/29/2015 at 11:01 AM0 comments > More Webcasts
https://visualstudiomagazine.com/Blogs/Tool-Tracker/List/Blog-List.aspx?m=1'A&platform=372&Page=12
CC-MAIN-2021-43
refinedweb
2,382
57.71
driver ath9k is too slow or not responding Bug Description For several kernel build now the ath9k is not fully fonctionnal with my : #lspci 02:00.0 Network controller: Atheros Communications Inc. AR5008 Wireless Network Adapter (rev 01) The connection is too slow or not responding. Happily I found a solution: I use the last tarball from here: http:// But each time the kernel is updated, I have to compile it and install it again. Are you aware of this problem? Thanks for your help. ProblemType: Bug DistroRelease: Ubuntu 11.04 Package: linux-image- Regression: No Reproducible: Yes ProcVersionSign Uname: Linux 2.6.38-6-generic i686 NonfreeKernelMo AlsaVersion: Advanced Linux Sound Architecture Driver Version 1.0.23. Architecture: i386 AudioDevicesInUse: USER PID ACCESS COMMAND /dev/snd/ /dev/snd/ CRDA: Error: [Errno 2] Aucun fichier ou dossier de ce type Card0.Amixer.info: Card hw:0 'Intel'/'HDA Intel at 0xfdff8000 irq 43' Mixer name : 'Realtek ALC1200' Components : 'HDA:10ec0888, Controls : 37 Simple ctrls : 20 Card1.Amixer.info: Card hw:1 'Q9000'/'Logitech, Inc. QuickCam Pro 9000 at usb-0000:00:1d.7-4, high speed' Mixer name : 'USB Mixer' Components : 'USB046d:0990' Controls : 2 Simple ctrls : 1 Card1.Amixer. Simple mixer control 'Mic',0 Capabilities: cvolume cvolume-joined cswitch cswitch-joined penum Capture channels: Mono Limits: Capture 0 - 3072 Mono: Capture 0 [0%] [18.00dB] [on] Date: Mon Mar 14 23:23:45 2011 HibernationDevice: RESUME= InstallationMedia: Ubuntu 11.04 "Natty Narwhal" - Alpha i386 (20110302) MachineType: HP-Pavilion GX598AA-ABF a6221.fr ProcEnviron: LANGUAGE=fr:en LANG=fr_FR.UTF-8 SHELL=/bin/bash ProcKernelCmdLine: BOOT_IMAGE= RelatedPackageV linux- linux- linux-firmware 1.48 RfKill: 0: phy0: Wireless LAN Soft blocked: no Hard blocked: no SourcePackage: linux UpgradeStatus: No upgrade log present (probably fresh install) dmi.bios.date: 07/27/2007 dmi.bios.vendor: Phoenix Technologies, LTD dmi.bios.version: 5.21 dmi.board.name: Leonite2 dmi.board.vendor: ASUSTek Computer INC. dmi.board.version: 6.00 dmi.chassis.type: 3 dmi.chassis.vendor: Hewlett-Packard dmi.chassis. dmi.modalias: dmi:bvnPhoenixT dmi.product.name: GX598AA-ABF a6221.fr dmi.sys.vendor: HP-Pavilion Related branches same bug with the last ubuntu natty kernel version, 2.6.38-7: connection too slow with the ath9k driver, , web site does not load completely... I compiled the last version of compat-wireless and my connection is at the top! Tips: to compile the last compat-wireless on Ubuntu Natty, you have to add this line: #include <linux/sched.h> in the file compat/ --> see this thread: http:// Hope this help. LGDN I'm seeing this bug on Arch Linux with 2.6.38-1 from testing, too. I think it's an obvious kernel regression. I'm about to try compiling the latest version of compat-wireless and see what I get from that. Like I said in my previous mail, I have this bug with all 2.6.38 ubuntu natty kernel series, but I didn't try with another kernel (vanilla). Do the kernel devs read this report on launchpad or do we report a bug on the kernel dev site? LGDN This is also affecting ath5k for me. Using the compat-wireless tarball from 3/18/2011 didn't fix anything; reverting to 2.6.37 has fixed the problem for me. I will try a compat-wireless from a different date soon. This seems only to occur when the card is in certain modes, like wireless n or ad-hoc. I will be filing a bug report with the kernel later tonight. I noticed the same problem with ath9k on an AR9280 rev.2 chipset. I tried compat-wireless for 2.6.38 but that didn't helped much (fixed dma errors and chip lockup issues, but speeds were still bad). Using today's compat-wireless snapshot (compat- I have the exact same behavior on Arch Linux. With stock kernel testing my bandwith is around 60-90kb, with the compat-wireless I'm back around 6Mb, which makes a HUGE difference. Also connecting to my network seems faster. Thanks! Ubuntu kernel 2.6.38-7 updated but bug still present: download speed without compat-wireless driver: 60 ko/s with compat-wireless driver: 390 ko/s Why is this bug status is incomplete? I also have a very slow network connection (1-2kB/s instead of > 1MB). I found out that I had to install the firmware for carl9170, which is supposed to be the successor of the (now deprecated) ar9170usb driver. With the carl9710 driver compiled from linuxwireless.org, everything works fine. Seems to be related to #713987. Hello, I'm quite glad I found this bug report. Compiling compat-wireless is very easy (nice scriptwork there!), and made a major improvement: Running an scp from a different (also wireless) machine on my network used to work at 15kB/s. Now it's around 300kB/s, which makes much more sense. Also, browsing websites (especially image-heavy ones) has become much smoother; it used to be quite choppy. This seems to happen again upon resuming from suspend (checked using scp from my other machine again), until the ath9k module is reloaded. Here's a workaround: Create a file /etc/pm/ SUSPEND_ Status update: The upgrade to 2.6.38-8-generic did not resolve the issue, and also shows that just having the carl9710-firmware does NOT suffice, I had to again compile the compat-wireless modules for the new kernel. ubuntu kernel updated to 2.6.38-8, bug still present for Atheros AR5008 with ath9k driver. I compiled again linux-wireless driver and my WIFI card is working now at normal speed. Does the Ubuntu team plan to correct with bug? It is very annoying for people who are using a lot the WIFI network and today it is not a minority... I've reverted to the ubuntu-included ath9k module, and it works just as well - providing that you reload it on suspend, as I've explained earlier. However, this sometimes causes suspend to take a long time, as the module is perceived as "in use" for several more seconds (~10 seconds) Hi, I have the same problem with my Atheros card AR9280 on a eeepc 1000HE the committed fix will be include in a next update ? This problem has been around for years without a fix - can this be set as an Important priority? Many users like myself have netbooks that cannot get online wirelessly because of this bug with atheros chipset. I'm no pro with Ubuntu - does any one have their own patched Ubuntu distro with this working that I could download in the meantime? Same problem on hp pavilion dv6 with an atheros ar9285 with ubuntu 11.04, recompiling compat-wireless didn't fix anything :( hoping for the fix to be up soon! I see an encouraging status: In Progress → Fix Committed : ) Accepted linux into natty-proposed, the package will build now and be available in a few hours. Please test and give feedback here. See https:/ Something really strange just happened: on a natty fresh install, no upgrade - no proposed repo enabled, my ar9285 was NOT working. I inserted a rt73 usb dongle, used it for a while, disconnected, re-enabled the ar9285...now it works like a charm, but don't ask me why O_o" system has crashed a few minute later with a complete freeze, though. Now I just rebooted and the ar9285 is working out of the box without any crash nor speed or connection troubles - for now xD This commit is an early application of a commit that will be coming in via upstream stable. As such it is not subject to the standard bug verification process. I upgraded from linux-image- (through natty/proposed), and wireless appears to work fine now. Thanks for committing the fix! I upgraded as well but i have to turn wlan0 down and then up using ifconfig.. otherwise it only shows that the network is connected but there is no activity... speeds are good.. same as my Ubuntu 10.10 ... so thanks for the fix.. Still not working for me on a Acer Aspire One ZG5 and clean install. I do see the adapter and it does show networks but its never able to connect whether wpa, wep, unsecured, etc. Installed the new Kernel from proposed, but it still drops to 0 B/s after a while and can only get it back by turning wireless off and then on. Acer Aspire One D250. Marking as verification- I still have the problem with the kernels from natty-proposed: Wireless connection is extremely slow (<5kB/s) and frequently breaks completely. Installing compat- I googled the problem, and came up with this command; sudo -s echo "options ath9k nohwcrypt=1" > /etc/modprobe. taken from here; http:// I have the same problem. ath9k wireless on my Samsung N145 netbook is slow to unusable. Installed the 2.6.38-9.43 kernel from natty-proposed and the connection rate went up to 100-200kB/s for some minutes, now it's settled at about 50-100 kB/s. Much better than before, but less than perfect. I think I'll try the compat-wireless drivers next. I'd like to avoid turning off hardware decryption on a low-performance netbook. I have this problem, too. Used ubuntu and mint for years dual booting with xp or without and many many installs trying things out. Last fall bought a hp dm3 1030us with win7. Everything cool until my hard drive failed. Got new hard drive but the backup I had made was not good. Wiped the drive - now my xp won't install. No version of Ubuntu or min't can log onto a linksys WRT54G2 with WPA2 Personal (w/AES), even though I got on this same system back when I had both win7 and mint installed, just put the encryption key in and it worked with both OS's.. I am baffled. It worked fine for me too until this kernel... Wireless now drops and becomes unusable... Atheros AR5008 Kernel 2.6.38-8 When I restart using kernel 2.6.35, works fine... another noobie here I have a similar problem with a wired lan, i have seen the link on this page, is this a bigger issue than the wireless cards, is it the kernel issue as mentioned on the link below, has anyone tried it or having this problem with wired networks https:/ Running Natty on a Sony Vayo Post #29 from Dante fixed the problem for me add nohwcrypt=1 to module options of ath9k module Thanks Dante :) From Seth: The patch in question is already released in 2.6.38.5, and the feedback on testing the kernel in proposed is split (two say their wireless worked better, two say it didn't). There's probably another issue producing similar symptoms. So I think we ought to keep the patch. Seth Marking as verification complete and we'll keep this fix Asus UL30A-X5 here - Everything worked great with Ubuntu 10.04, and 10.10. Went to 11.04, and on N networks, I'll get full speed (>5MB/sec briefly, then it drops to ~1MB/sec, and sometimes stalls. $ uname -a Linux lap 2.6.38-8-generic #42-Ubuntu SMP Mon Apr 11 03:31:24 UTC 2011 x86_64 x86_64 x86_64 GNU/Linux $ lsb_release -a No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 11.04 Release: 11.04 Codename: natty lspci -v -s 02:00.0 |egrep -v 'Serial Number' 02:00.0 Network controller: Atheros Communications Inc. AR9285 Wireless Network Adapter (PCI-Express) (rev 01) Subsystem: AzureWave Device 1089 Flags: bus master, fast devsel, latency 0, IRQ 17 Memory at feaf0000 761176 has more people still affected by this. I followed the idea in that bug to try the ppa kernel - Looks like the fix is in there.. I'm back to >5 MB/sec on 802.11n links with it. $ uname -a apt history for the upgrade Start-Date: 2011-05-27 20:01:03 Commandline: apt-get dist-upgrade Install: linux-image- Upgrade: linux-generic:amd64 (2.6.38.8.22, 2.6.39. End-Date: 2011-05-27 20:03:30 apt-cache policy linux-image linux-image: Installed: (none) Candidate: 2.6.39.0.1~20110419 Version table: 2. 500 http:// 2.6.38.8.22 0 500 http:// Ryan: The natty kernel you have installed doesn't contain the fix. If you want to test the fix you need to install the kernel currently in proposed. The only way I could get wireless to work again is to compile the driver from source as explained above. The new kernel in proposed didn't help. I enabled proposed repository and installed the new kernel: $ uname -a Linux maggie 2.6.38-9-generic #43-Ubuntu SMP Thu Apr 28 15:23:06 UTC 2011 x86_64 x86_64 x86_64 GNU/Linux The problem is not solved, although the situation has significantly improved in both speed and stability. The issue, however, remains: # Internet download speed is limited if compared to a wired connection. Response time is visually slower and downloads won't go faster than 600KB/s without hanging. # the driver is not completely stable yet. Downloading big files, for instance a Ubuntu ISO using torrent, will hang the connection. In that case I have to disconnect and reconnect. # the computer runs much hotter. A video call on Skype will make the internal temperature increase by 4-5 degrees if compared to the same call using a wire. My hardware encryption is ON. Network controller: Atheros Communications Inc. AR928X Wireless Network Adapter (PCI-Express) (rev 01) Kernel update in -proposed (2.6.38- Hmph. Actually, it died as well with 2.6.38-10. It just lasted for a surprisingly long time. (Something like 24 hours). This time around it actually disconnected and wouldn't reconnect, though. I have seen that before recently, but it's a little different from what I usually get here (and what the reporter describes) where Network Manager says there is a connection but nothing actually gets through. It seems that running a torrent client is a sure way to trigger this collapse._... 2.6.38-10.46 came through the Update Manager today and I can confirm it fixes the problem. On one speedtest.net run I got 45Mbps download speed though the average is around 32Mbps. Plus I can ping my router without losing packets. So I offer big thank you to the people who fixed these bugs. But to whoever labeled these changes "urgency=low" I say, please make a better judgement next time. These bug(s) all but crippled my HTPC. I had to connect a wired network to get it to function. I updated my Ubuntu Natty today with the 2.6.38-10-generic #46-Ubuntu SMP kernel update and my Atheros AR5008 wifi card (ath9k driver) works again like a rocket!! Thank you very much for all developpers behind this patch! Upgraded to the latest kernel 2.6.38-10 and I'm still seeing my connection speed drop to nothing whilst using rsync. Stumbled across this bug while searching for information on why I can only get a very slow and unstable connection with my 802.11n wireless card, which used to work just fine under 10.04. I now have to use a shared Internet connection through a LAN cable connected to my laptop, which is much less than ideal for me. Running a fully up-to-date install of 11.04 64-bit. $ lspci | grep Network 01:07.0 Network controller: Atheros Communications Inc. AR5008 Wireless Network Adapter (rev 01) $ uname -a Linux Xyz 2.6.38-10-generic #46-Ubuntu SMP Tue Jun 28 15:07:17 UTC 2011 x86_64 x86_64 x86_64 GNU/Linux seems not really fixed yet I am still getting pretty poor performance True. Also in 12.04 the connection randomly drops (https:/ Oneiric also once in a while (minutes/hours, depending on how much traffic I make) disconnects the Wifi (WPA2) connection and cannot connect back to it. Usually a restart either of the router, or of the ubuntu system makes it work again (until it disconnects again). I use the latest official launched kernel on Oneiric (3.0.0-16-generic) and all updates up-to-date. Should I open a new bug report? These issues with ath9k last since forever :( sudo lspci -v -s 02:00.0 |egrep -v 'Serial Number' 02:00.0 Network controller: Atheros Communications Inc. AR9285 Wireless Network Adapter (PCI-Express) (rev 01) Subsystem: Lite-On Communications Inc Device 6611 Flags: bus master, fast devsel, latency 0, IRQ 17 Memory at d4400000 uname -a Linux florin- Florin, please subscribe to that bug that has been repported upstream too: https:/ I also posted on kernel bugzilla (https:/ We should have a look there from time to time. I'm also seeing this problem with the ath9k driver. Using what comes with Ubuntu, scp over my wireless LAN is less than 1/8th the speed I can get with the driver compiled from that tarball. This is using Ubuntu Natty on an x86_64 computer.
https://bugs.launchpad.net/ubuntu/+source/linux/+bug/735171
CC-MAIN-2017-43
refinedweb
2,887
66.74
You! At this point you can continue developing your app as usual. Refer to our debugging and deployment docs to learn more about working with React Native. The keys to integrating React Native components into your iOS application are to: RCTRootView Follow the React Native CLI Quickstart in the environment setup guide to configure your development environment for building React Native apps for iOS. To ensure a smooth experience, create a new folder for your integrated React Native project, then copy your existing iOS project to a /ios subfolder. /ios Go to the root directory for your project and create a new package.json file with the following contents: package.json { : react react-native $. /node_modules Add node_modules/ to your .gitignore file. node_modules/ .gitignore. Assume the app for integration is a 2048 game. Here is what the main menu of the native application looks like without React Native. Install the Command Line Tools. Choose "Preferences..." in the Xcode menu. Go to the Locations panel and install the tools by selecting the most recent version in the Command Line Tools dropdown. We will now add an event handler from the menu link. A method will be added to the main ViewController of your application. This is where RCTRootView comes into play. ViewController. index.bundle RNHighScore NSURL. RNHighScores moduleName First import the RCTRootView header. import #import <React/RCTRootView.h> The initialProperties are here for illustration purposes so we have some data for our high score screen. In our React Native component, we will use this.props to get access to that data. initialProperties this.props - to create a bridge and then use RCTRootView initWithBridge. RCTRootView initWithURL [RCTRootView alloc] initWithURL RCTBridge initWithBundleURL RCTRootView initWithBridge When moving your app to production, the NSURL can point to a pre-bundled file on disk via something like [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];. You can use the react-native-xcode.sh script in node_modules/react-native/scripts/ to generate that pre-bundled file. [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"]; react-native-xcode.sh node_modules/react-native/scripts/ Wire up the new link in the main menu to the newly added event handler method. Here is the React Native high score screen: If you are getting module resolution issues when running your application please see this GitHub issue for information and possible resolution. This comment seemed to be the latest possible resolution. You can examine the code that added the React Native screen to our sample app on GitHub. First import the React library. React import React @IBAction to create a bridge and then use RCTRootView initWithBridge. RCTRootView bundleURL When moving your app to production, the NSURL can point to a pre-bundled file on disk via something like let mainBundle = NSBundle(URLForResource: "main" withExtension:"jsbundle"). You can use the react-native-xcode.sh script in node_modules/react-native/scripts/ to generate that pre-bundled file. let mainBundle = NSBundle(URLForResource: "main" withExtension:"jsbundle")
http://reactnative.dev/docs/0.63/integration-with-existing-apps
CC-MAIN-2022-27
refinedweb
485
50.73
. Jitendra Bahadur Chand says I subscribed but can’t see the ebook in my email box Tuğberk says good job, very informative, deep knowledge, thanks. chetan sharma says TreeMap doesnot implement Random Access Fantine says I subscribed but can’t see the ebook in my email box Subhash says LinkedHashMap is missing the collection table hooni says thank you very much. this helped me a lot (learning java now). Thank you!! :)) ilhom says hi, I found a mistake on your DEsign Pattern book in example in Chain of Responsibility Pattern, can u please check that program there s smth wrong with it, it is printing Null Pointer Exception, thanks. sakshi says Treemap contain null values.you have written wrong i think. zabir says RendomAccess Interface implemented class is ArrayList, AttributeList, CopyOnWriteArrayList, RoleList, RoleUnresolvedList, Stack, Vector Source:: amol says Hi Pankaj ! This is an amazing tutorial. I am a fan or your work. I have read this article in text mode. Just like any text read without fancy css and ads. Can you please give me that link. Pankaj says I didn’t get what you meant. Rahul S Kumar says Amol….. Reading mode is a feature of your browser. Firefox is having that feature. I don’t know if other browsers having that feature or not (Might be having). Anurag Singh says Hello sir this is very well explained about java collection framework. keep posting like that thank you so much this useful post Chandra Babu says Why CopyOnWriteArraylist is not random access? From the source code public class CopyOnWriteArrayList implements List, RandomAccess, Cloneable, java.io.Serializable { Chandra Babu says Sorry Overlooked CopyonWriteArraySet Dev says Hi Admin, I need little more information regarding object equals() and hashcode() method. In java equals() and hashcode() method are very important. I want to know the cases where these two method are call internally in java. For example : 1. get() method in HashMap. 2.Set 3.contains() method in ArrayList calls equals method internally. Can anyone please tell me what is the other cases where equals() method (or hashcode()) calls internally to perform any operation (like above mention 3 cases). Pankaj says I think they are used in String too. Keval Solanki says It would be nice if you add here some programmes too….theory only is not at all sufficient.. ch sreelekha says can u please provide more programs that users can easily understand pratically also……. Arjun Sridhar says Corrections: HashSet Internally uses HashMap not HashTable. Author can you please rectify we are all observing your site keenly.. Pankaj says Sorry for typo error and Thanks a lot for pointing it out. I have corrected the post. sivaaprasad says But it is given in java docs that hashset uses hashtable to store elements. could u pls justify ur answer Satya Chandu says Pretty good coverage. Good Job !!! kamlesh says nice……………tutorials for helpful all Student aparna says hi pankaj, can u please put all the data topic wise on this website in downlodable PDF format. Rajan Chauhan says theoretically its very understandable………..but could it be presented with examples of each ?……classes implementing these interfaces.. that will be more understandable. Contra says Wonderful post!, it was worth spending every sec reading your blog. Sekhar says Hi, I faced one question in interview that is “Which collection frame work object is used in your project, I replied that I was using HashMap because of synchronisation” He asked is this only the main advantage of hashmap?. But i was in silent for that question. Please provide the proper solution for these type of questions> Thanks in Advance, Sekhar Pankaj says You can’t read everything, some things come from experience. There are no limits on interview questions, that being said there is no way anyone can address all of them. manjunath says I’m following your blog from past 5 months it’s was too much good , I have a doubt why all methods in Collections class are static methods , please provide your powerful answer. Thanks in advance Pankaj says Collectionsis a utility class that provides useful methods, that’s why all the methods are made static. There is no point in making those methods non-static, that will result in create an object of it and then calling the method. manjunath says Thank you very much sir,According to my analogy ” this “(operator) is a static reffereence which is created by JVM and supplies to each and every java program at run time and also internally “this” operator is following dynamic bynding(runtime polymorphism) static x this; ——this stmt is created by jvm inside the class x obj=new x(); —-programmer statement next duty of jvm: this=obj1; ,,,,,,,and so on in a class bhaskar says Interviewer tricked you, as HashMap is not synchronized. If you are using HashMap and you want it to be thread safe, then you have to provide synchronization mechanism. Siva Narayana Reddy M says Hi Sekhar, Whether you already know it or not, I just want to put forth some piece of information which I know. HashMap is a concrete implementation of Map interface. HashMap is NOT synchronized. HashTable is another concrete implementation of Map interface. HashTable is SYNCHRONIZED. Thanks Siva Narayana Reddy M Vaibhav says hi pankaj, you explained it very impressively.. Start with list if topic then explanation of it.. its very easy to read n your explanations are easy to understand too..:-) just a request..plz give simple..small example for it.. thanks..:-) Urmila says Very Good Explanation but can u give small practical example on Collections Framework JJ_Jacob says good article Partha says Hi Pankaj, As you said Random access NO for LinkedList and YES for ArrayList. Could you elaborate more on this, what random access mean? Does it mean retrieving the object from a list/map? I can see there is a get() in both the ArrayList and LinkedList class. Using this method we can retrieve the object. Does it mean random access? Thanks Partha Pankaj says LinkedList supports get(int index) operation but internally it traverses the list from start or end which ever is closer depending on the length. So it’s not efficient and not random. Random access means that whether you get the element at index 1 or at index 10000 of 50000 elements, it should take same time but for LinkedList it will take more time because it will have to skip first 9999 elements to get the desired element. ArrayList supports random access, means whether you are accessing index 1 or 10000 of 50000 elements, time to get the element will be same. If you look at the implementation of ArrayList and LinkedList, you will see that ArrayList implements RandomAccess interface whereas LinkedList does not. Partha says As per my understanding, In ArrayList if an element is removed then the arrayList is resized. But Linked list works on the principle of Node. So if any element is removed in LinkedList it is not resized. Lets say in element 10 is removed so element 11 will take the place of 10 in ArrayList. But in Linked list element 10 place is blank. So we can’t access element 10 if we are using LinkedList. Is that the reason LinkedList doesn’t allow Random Access? jagjeet singh says great Work…easily understand all things in collection framework.and how it work in java. shirisha says Thanq Pankaj ,Perfectly explained . Nihar says Amazing …. love to read ur blog. Abhay Singh says Hi Pankaj.. I think ConcurrentHashMap does not allow null values.. but you have mention YES in the table... Pankaj says Hi Abhay, Thanks for pointing out the mistake and providing the explanation. I have corrected it. dg says Hey! I’m at work browsing your blog from my new apple iphone! Just wanted to say I love reading your blog and look forward to all your posts! Keep up the excellent work! Snehal Masne says I think this is among the most significant articles I have seen. And I’m glad reading your article. Good job, cheers! 🙂 Madiraju Krishna Chaitanya says Hi Pankaj Sir, Wonderful Post.We got a Good Understanding of the Collections Framework from this writeup.Please keep up the Good Work and keep posting wonderful articles like this.May GOD Bless You. satish says thks i learn some thing from here выкройки одежды для собaк журнaл says Very good write-up. I definitely appreciate this site. Keep it up! anonymous says It’s hard to find well-informed people about this topic, however, you sound like you know what you’re talking about! Thanks homepage says Hello my friend! I want to say that this article is amazing, great written and include approximately all important infos. I would like to peer extra posts like this . kenneth copeland ministry says Howdy fantastic website! Does running a blog similar to this require a lot of work? I’ve no understanding of programming but I was hoping to start my own blog soon. Anyways, should you have any suggestions or techniques for new blog owners please share. I know this is off topic but I simply needed to ask. Appreciate it! Emilio says I think this is among the most significant information for me. And i’m glad reading your article. But wanna remark on some general things, The website style is great, the articles is really great : D. Good job, cheers Zella says It’s very effortless to find out any matter on web as compared to books, as I found this post at this site. Sreenivas Reddy says Great tutorial about Collections. We can easily understand about java collections by this tutorial. Keep post good posts like this .Thanks very much for this valuble info.. says I always spent my half an hour to read this web site’s articles all the time along with a cup of coffee. Prashant Kumar says Perfectly explained Pankaj. Thanks a lot.. Bhimaraya says Thank you very much sir. you explained very nicely. Santosh says Q>>why would you want to catch Exception, when you can catch Throwable? Pradeep says You are absolutely right. you can catch Throwable object instead of Exception object BUT if you look at the hierarchy of exceptions then you will notice Throwable is the top class of ERROR & EXCEPTION classes…..& if you catch Throwable object then there is assumption from developer that your program may throw Error object which is not possible. Please read in below article:- So whichever exception(Runtime or CompileTime) is occuring in the program, will be able to Upcast to Exception object….so it is good practice to catch Exception object rather than Throwable object.
https://www.journaldev.com/1260/collections-in-java-tutorial
CC-MAIN-2019-30
refinedweb
1,782
75.2
Role Management Role Entity Role entity represents a role for the application. It should be derived from AbpRole class as shown below: public class Role : AbpRole<Tenant, User> { //add your own role properties here } This class is created when you install module-zero. Roles are stored in AbpRoles table in the database. You can add your custom properties to Role class (and create database migrations for the changes). AbpRole defines some properties. Most importants are: - Name: Unique name of the role in the tenant. - DisplayName: Shown name of the role. - IsDefault: Is this role assigned to new users by default? - IsStatic: Is this role static (pre-build and can not be deleted). Roles are used to group permissions. When a user has a role, then he/she will have all permissions of that role. A user can have multiple roles. Permissions of this user will be a merge of all permissions of all assigned roles. Dynamic vs Static Roles In module-zero, roles can be dynamic or static: - Static role: A static role has a known name (like 'admin') and can not change this name (we can change display name). It exists on the system startup and can not be deleted. Thus, we can write codes based on a static role name. - Dynamic (non static) role: We can create a dynamic role after deployment. Then we can grant permissions for that role, we can assign the role to some users and we can delete it. We can not know names of dynamic roles in development time. Use IsStatic property to set it for a role. Also, we should register static roles on PreInitialize of our module. Assume that we have an "Admin" static role for tenants: Configuration.Modules.Zero().RoleManagement.StaticRoles.Add(new StaticRoleDefinition("Admin", MultiTenancySides.Tenant)); Thus, module-zero will be aware of static roles. Default Roles One or more roles can be set as default. Default roles are assigned to new added/registered users as default. This is not a development time property and can be set or changed after deployment. Use IsDefault property to set it. Role Manager RoleManager is a service to perform domain logic for roles: public class RoleManager : AbpRoleManager<Tenant, Role, User> { //... } You can inject and use RoleManager to create, delete, update roles, grant permissions for roles and much more. You can add your own methods here. Also, you can override any method of AbpRoleManager base class for your own needs. Like UserManager, Some methods of RoleManager also return IdentityResult as a result instead of throwing exceptions for some cases. See user management document for more information. Multi Tenancy Similar to user management, role management also works for single tenant in one time in a multi-tenant application. See user management document for more information.
http://aspnetboilerplate.com/Pages/Documents/Zero/Role-Management
CC-MAIN-2017-09
refinedweb
461
58.99
Writing Parquet Files with Dask using to_parquet • April 4, 2022 This blog post explains how to write Parquet files with Dask using the to_parquet method. The Parquet file format allows users to enjoy several performance optimizations when reading data, benefiting downstream users of the data. This blog post will teach you the basics of writing Parquet files and advanced options like customizing the filenames and controlling if the metadata file gets written. You need to be careful to avoid writing the metadata file when it can become a performance bottleneck. Let’s dive in with a simple example. Dask write Parquet: Small example Let’s create a small Dask DataFrame and then write it out to disk with to_parquet. import dask.dataframe as dd import pandas as pd df = pd.DataFrame( {"nums": [1, 2, 3, 4, 5, 6], "letters": ["a", "b", "c", "d", "e", "f"]} ) ddf = dd.from_pandas(df, npartitions=2) ddf.to_parquet("data/something", engine="pyarrow") Here are the files that are output to disk. data/something/ _common_metadata _metadata part.0.parquet part.1.parquet Dask DataFrame’s file I/O writer methods output one file per partition. This DataFrame has two partitions, so two Parquet files are written. The Parquet writer also outputs _common_metadata and _metadata files by default. Parquet files contain metadata about the file contents including the schema of the data, the column names, the data types, and min/max values for every column in each row group. This metadata is part of what allows for Parquet files to be read in a more performant manner compared to file formats like CSV. Dask writes out the metadata in the Parquet file footers to a single file to bypass the need to fetch the metadata from each Parquet file that’s being read. Footers are a section of Parquet files where metadata is stored. It can just look at the metadata file to get the metadata for each file in the directory. Creating the metadata file is great for small datasets, but can become a performance bottleneck when lots of files are written. Dask to_parquet: write_metadata_file The write_metadata_file argument is set to True by default. For large writes, it’s good to set write_metadata_file to False, so collecting all the Parquet metadata in a single file is not a performance bottleneck. Here’s how to write out the same data as before, but without a _metadata file. ddf.to_parquet( "data/something2", engine="pyarrow", write_metadata_file=False, ) Here are the files that are output to disk. data/something2/ part.0.parquet part.1.parquet When Dask reads a folder with Parquet files that do not have a _metadata file, then Dask needs to read the file footers of all the individual Parquet files to gather the statistics. This is slower than reading the data directly from a _metadata file. But, as mentioned previously, trying to write too much data to a single _metadata file can be prohibitively slow when lots of files are written. In short, set write_metadata_file to False when doing large Parquet writes. Dask to_parquet: name_function The Parquet writes will output files with names like part.0.parquet and part.1.parquet by default. You can set the name_function parameter to customize the filenames that are written with to_parquet. Let’s output a universally unique identifier (UUID) in the filename that’s output so we can see what files are written per each batch. import uuid id = uuid.uuid4() def batch_id(n): return f"part-{n}-{id}.parquet" ddf.to_parquet( "data/something3", engine="pyarrow", write_metadata_file=False, name_function=batch_id, ) Here are the files that are output to disk. data/something3/ part-0-09a19442-309e-485f-b006-fd9cb10f9cc7.parquet part-1-09a19442-309e-485f-b006-fd9cb10f9cc7.parquet It’s really nice to write files like this in your production applications. This lets you easily identify the files that are written, per batch. You can also use the name_function to write out files with a timestamp, so they’re ordered chronologically. Dask to_parquet: compression Dask writes out Parquet files with Snappy compression by default. Snappy compression is typically the best for files used in distributed compute contexts. Snappy doesn’t usually compress files as much as other compression algorithms like gzip, but it’s faster when decompressing files (aka inflating files). You’ll often read compressed files from disk in big data systems, so fast inflation is important. You can specify the Snappy compression algorithm, but this doesn’t change anything because Snappy is used by default. ddf.to_parquet( "data/something4", engine="pyarrow", write_metadata_file=False, compression="snappy", ) You can write out the files with the compression algorithm in the filename, which can be convenient. def with_snappy(n): return f"part-{n}.snappy.parquet" ddf.to_parquet( "data/something5", engine="pyarrow", write_metadata_file=False, compression="snappy", name_function=with_snappy, ) Here are the files that are output to disk. data/something5/ part-0.snappy.parquet part-1.snappy.parquet This is a nice way to make it clear to other humans what compression algorithm is being used by the file. Note that you will need to manually update the name_function parameter to reflect any changes made to the compression parameter. Different columns of a Parquet file can actually be compressed with different compression algorithms. Here’s how to compress the nums column with Snappy and the letters column with gzip. ddf.to_parquet( "data/something6", engine="pyarrow", write_metadata_file=False, compression={"nums": "snappy", "letters": "gzip"}, ) You don’t normally see different compression algorithms for different columns in a Parquet file, but it’s a cool feature that’s incredibly handy for niche use cases. Dask write parquet: FastParquet vs PyArrow Engines You can write Parquet files with both the FastParquet and PyArrow engines. For most use cases, either selection is fine. There are some subtle differences between the two engines, but they don’t matter for most users. PyArrow’s popularity has taken off and it’s well supported in Dask, so PyArrow is a good option if you’re not sure which engine to use. Dask write parquet: partition_on You can write Parquet files in a Hive-compliant directory structure that allows for readers to leverage disk partition filtering by setting the partition_on argument. Disk partition filtering can be a significant performance optimization for certain types of queries, but it will make other types of queries run slower. For example, queries that filter or group-by on the partition key will run a lot faster than queries operating on different keys. Queries that don’t operate on the partition key will face the drag of extra files and globbing nested directories. Globbing is particularly expensive in cloud based object stores like AWS S3. See the post on Creating Dask Partitioned Lakes with Dask using partition_on for more information. Disk partitioning allows for huge performance gains for some query patterns, so you should know how it works. Dask to_parquet Conclusion Dask makes it easy to write Parquet files and provides several options allowing you to customize the operation. You can specify the compression algorithm, choose if the metadata file should be written, customize the filename, and write the files in a nested directory structure for disk partition filtering. Consider omitting the metadata file when you must write a lot of partitions because it can be a performance bottleneck. Including a UUID and the compression algorithm in the filename is nice when you’re building production pipelines that repeatedly write to the same directory. You can always repartition before writing to change the number of files that are written. See this blog post for more information about the repartition method. See this blog post to learn more about the performance benefits you can get from column pruning and predicate pushdown filtering, two optimization techniques that are afforded by Parquet files but not available in other file formats like CSV or JSON.
https://coiled.io/blog/writing-parquet-files-with-dask-using-to_parquet/
CC-MAIN-2022-21
refinedweb
1,303
54.12
In ASP.NET MVC you don't browse to your view files directly. You have to use the routes that are setup in your site's Application_Start() event. For example, a new ASP.NET MVC project adds this route by default in global.asax: routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" } ); It also adds a default controller and action: public class HomeController : Controller { public ActionResult Index() { ViewData["Message"] = "Welcome to ASP.NET MVC!"; return View(); } } And a View under Views/Home named Index.aspx. Instead of using the address you would use You can learn more about routing here: I want to add something: I am pretty sure that what you actually need is to add the .ASPX reditection on your IIS server. If you are using IIS6, this can be done with the following steps: Without the steps above, your ASP.NET MVC will not work properly. I have had this experience before and my current host, ASPHostCentral, advised me those steps above :) Good luck! You can see those files if you really must - for example if they're plain .html files - with an Ignore route: routes.IgnoreRoute("Views/{name}.html"); That would allow you to browse directly to any .html file living in the Views folder, without defining routes, controllers, etc. It's pretty nice how easily the Routes system gets in and out of the way depending on what you want out of it. You can learn Routes in 4 steps here: I have found a new reason for this error: If you are using Resharper it is suggesting to change eventhandler name but if you click to yes it is not changing the event name of the object under the Global.asax file. I havent seem the object in the framework but it is percept16 times active 10 months ago
http://serverfault.com/questions/44389/asp-net-mvc-error/56584#56584
crawl-003
refinedweb
309
72.05
#include <MilkyWay.hpp> Inherits StelModule. Initialize the class. Here we load the texture for the Milky Way and get the display settings from application settings, namely the flag which determines if the Milky Way is displayed or not, and the intensity setting. Implements StelModule. Draw the Milky Way. Reimplemented from StelModule. Update and time-dependent state. Updates the fade level while the Milky way rendering is being changed from on to off or off to on. Implements StelModule. Does nothing in the MilkyWay module. Reimplemented from StelModule. Does nothing in the MilkyWay module. Reimplemented from StelModule. Used to determine the order in which the various modules are drawn. Reimplemented from StelModule. Get Milky Way intensity. Set Milky Way intensity. Get the color used for rendering the milky way. Sets the color to use for rendering the milky way. Sets whether to show the Milky Way. Gets whether the Milky Way is displayed.
http://stellarium.org/doc/0.10.4/classMilkyWay.html
CC-MAIN-2014-42
refinedweb
152
71.92
Make a struct, stuff all the common arguments in there and pass it around. Unless there's a real need for global variables, I'd avoid it. There are things that need global variables, but this isn't it. Just bear in mind that if you are actually interested in performance within your ray-tracer, using local variables or parameters is likely to produce better code, since the compiler must assume that global variables may be affected by any function call you make (except for functions that the compiler decides to inline and thus can decide that this portion of code doesn't modify certain variables). It does sound like those definitions are suitable for storing in a struct that is passed as one const pointer to all functions (that need them). -- Mats Compilers can produce warnings - make the compiler programmers happy: Use them! Please don't PM me for help - and no, I don't do help over instant messengers. If you absolutely must use globals, then a few rules will help matters. 1. Use a decent namespace, like prefixing all globals with "g_". If you use something terse like 'obj', then you're going to have surprises. One unfortunate project from my past managed to make a global variable called 'i'. Talk about chaos. 2. Put them all in one place, so that you can instantly see the scope of the problem should you ever want to port the code somewhere else. 3. Use gcc and compile with the -Wshadow option, to tell you about the case you highlighted in this thread, namely having a global and a parameter with the same name. But naming rules will also help. 4. Keep the numbers down. Less than 10 is a lot easier to manage than say more than 100. If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut. If at first you don't succeed, try writing your phone number on the exam paper.
http://cboard.cprogramming.com/c-programming/101642-need-help-extern-pointers-2.html
CC-MAIN-2016-44
refinedweb
335
71.04
Red Hat Bugzilla – Bug 125979 /usr/include/X11/extensions/dpms.h cannot be used in C++ code Last modified: 2007-11-30 17:10:44 EST From Bugzilla Helper: User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.6) Gecko/20040612 Firefox/0.8 Description of problem: When using dpms.h in a C++ program. The code is compiled and linked correctly, but when the program is ran the DPMS symbols have been mangled by C++ and the DPMS* functions can't be located and the program crashes. Suggest putting and #ifdef __cplusplus extern "C" in the dpms.h header to correct this problem. Example from xpm.h, which works correctly with C++ #ifdef __cplusplus extern "C" { #endif Version-Release number of selected component (if applicable): xorg-x11-devel-6.7.0-2 How reproducible: Always Steps to Reproduce: 1. create a c++ program that uses DPMSQueryExtension 2. compile and link program 3. execute program Actual Results: relocation error: undefined symbol: _Z18DPMSQueryExtensionP9_XDisplayPiS1_ Expected Results: Program should execute correctly. Additional info: When compiling against C code the program works correctly. In my program I did this and it solved the problem #ifdef DPMSExtension #include <X11/Xlib.h> #ifndef DPMS_SERVER #include <X11/X.h> #include <X11/Xmd.h> extern "C" Bool DPMSQueryExtension(Display *, int *, int *); extern "C" Bool DPMSCapable(Display *); extern "C" Status DPMSInfo(Display *, CARD16 *, BOOL *); extern "C" Status DPMSEnable(Display *); #endif #endif I don't want to make such a change to our X header files unless it's been approved by upstream first, as there are risks involved within a stable release cycle, however if you file a bug report in the X.Org bugzilla at and carbon copy me on the bug report, I'll track the issue in their bugzilla instead, and will consider backporting any changes they make in CVS. Thanks for the report! Opened bug #830 at freedesktop Above link points to 830 in Red Hat bugzilla. Upstream URL link is: Setting bug status to "UPSTREAM" and tracking in fd.o bugzilla. Thanks. Status update: The upstream bug report has not yet received any comments from developers. You may wish to discuss the issue with them on xorg mailing lists, or update the upstream report with additional comments. I have submitted at patch into the bugzilla report. Hopefully it will be accepted. Was committed to upstream CVS for a while now. Resolving as rawhide...
https://bugzilla.redhat.com/show_bug.cgi?id=125979
CC-MAIN-2017-04
refinedweb
403
59.3
Well readers another week has come and gone. As you know last week I learned quite a few new things. This week was not as fruitful as last week but regardless I did learn a few new things and I hope you did as well. RazorEngine In the past I read a few posts how you can use Razor outside of asp.net but until this week I never had a practical purpose for using it. We are developing an email based alert system that requires tokens for user data. This sounds like perfect usage of razor as a templating engine for emails. After installing the Nuget package and a bit of working I was up and running quickly and generating <html/> emails from .cshtml files. On this subject if you want to have intellisense work follow this guide. The only change I made was just using TemplateBase<T> instead of the custom type. note, if resharper says you are safe to remove redundant namespaces, just let them there, Models caused an error until I did MyProject.Models Convention over Configuration With the Alert system we are building we decided to go with convention over configuration. Our simple convention is our email templates are named the same as the alert type, simple but effective. Configuration is fun until you have to make those configuration changes. Relearn Old Things This week a follow coworker shared how Parallel.ForEach() helped improve performance of the application he was developing. This is one of the topics I used in the past but simply forgot. I took this opportunity to engage in conversation and learn more about how he used this technique. This dialogue allowed me to learn from him and share ideas when we might be able to use this in the future. Finding Passion As you may know I have passion for software development and solving problems. Everyone is passionate about something and it is your job to find out what you are passionate about. When you find that passion you enjoy going to work and will excel in your career. On to Next Week Well I hope everyone has had a wonderful labor day and always, learn something new. UP UP. The author has a clear learning goal. Thanks for sharing Mark. Always interested in learning what other's are up to.
http://tech.pro/blog/1553/what-i-learned-this-week-826-830
CC-MAIN-2014-35
refinedweb
390
73.37
In a recent press, BEA claimed that more than 210 customers in the Americas, Asia/Pacific and Europe selected BEA over IBM in head-to-head sales situations during the past quarter. 125 of these customers selected BEA despite the fact that IBM WebSphere was the incumbent platform. 93 of these customers chose BEA for new projects, and in 32 cases Websphere was replaced with Weblogic. Read BEA's Press Release "BEA Wins Hands Down in Real-World Competition Against IBM as Customers Prefer BEA" ****************************** Editor's Note * ****************************** ?" -Billy Newport I would like to apologize for this lapse in editorial integrity. This news item was posted hastily and was not given a proper editorial narrative. TheServerSide's goal is to bring you objective and essential J2EE news and we will work harder to realize it. This issued press release is a claim made by BEA, not an independently reported article. What do people think about these claims? BEA Claims Big Wins Against IBM (28 messages) Threaded Messages (28) - Customers Prefer BEA Over IBM in 'Real World' Competition by Lu Huang on August 15 2002 17:25 EDT - Customers Prefer BEA Over IBM in 'Real World' Competition by Corby Page on August 15 2002 19:01 EDT - funny numbers by John Hess on August 15 2002 19:50 EDT - funny numbers by Ken Larson on August 16 2002 11:33 EDT - Customers Prefer BEA Over IBM in 'Real World' Competition by Billy Newport on August 15 2002 23:18 EDT - Customers Prefer BEA Over IBM in 'Real World' Competition by Markus Neifer on August 16 2002 02:25 EDT - Customers Prefer BEA Over IBM in 'Real World' Competition by Andreas Mueller on August 16 2002 06:44 EDT - Customers Prefer BEA Over IBM in 'Real World' Competition by Debjani Roy on August 16 2002 08:16 EDT - Customers Prefer BEA Over IBM in 'Real World' Competition by Dheeraj Jain on August 16 2002 03:53 EDT - Customers Prefer BEA Over IBM in 'Real World' Competition by Billy Newport on August 16 2002 06:06 EDT - Customers Prefer BEA Over IBM in 'Real World' Competition by zohar melamed on August 16 2002 12:44 EDT - Customers Prefer BEA Over IBM in 'Real World' Competition by Billy Newport on August 16 2002 02:12 EDT - Customers Prefer BEA Over IBM in 'Real World' Competition by Nick Minutello on August 18 2002 08:31 EDT - Customers Prefer BEA Over IBM in 'Real World' Competition by Billy Newport on August 19 2002 07:18 EDT - Customers Prefer BEA Over IBM in 'Real World' Competition by Nick Minutello on August 19 2002 07:32 EDT - Customers Prefer BEA Over IBM in 'Real World' Competition by Randy Schnier on August 19 2002 11:55 EDT - Customers Prefer BEA Over IBM in 'Real World' Competition by Web Master on August 19 2002 04:44 EDT - Customers Prefer BEA Over IBM in 'Real World' Competition by Nick Minutello on August 19 2002 07:42 EDT - Customers Prefer BEA Over IBM in 'Real World' Competition - by Java Enterprise Developer Incognito on August 18 2002 17:00 EDT - Customers Prefer BEA Over IBM in 'Real World' Competition by Dheeraj Jain on August 20 2002 06:49 EDT - Customers Prefer BEA Over IBM in 'Real World' Competition by Billy Newport on August 20 2002 01:55 EDT - Real world Websphere 5 : IBM is not an option (AFAIK) by Richard De Falco on April 14 2003 11:59 EDT - BEA Claims Big Wins Against IBM by Jamie Schiner on August 17 2002 13:20 EDT - BEA Claims Big Wins Against IBM by Yin tse on August 18 2002 12:56 EDT - BEA Claims Big Wins Against IBM by Cameron Purdy on August 19 2002 10:29 EDT - article: IBM Disputes BEA Application Server Claims by Sean Sullivan on August 19 2002 18:37 EDT - BEA Claims Big Wins Against IBM by neunet n on August 19 2002 22:30 EDT - IBM Disputes BEA Application Server Claims by bco ley on August 20 2002 13:42 EDT Customers Prefer BEA Over IBM in 'Real World' Competition[ Go to top ] <quote> - Posted by: Lu Huang - Posted on: August 15 2002 17:25 EDT - in response to Nate Borg One customer that replaced IBM with BEA is Chicago-based Abt Electronics. "We needed to redesign the Abt Electronics Web site to provide better security, more automation, and more real-time information, but most importantly, an enhanced and more satisfying buying experience for our customers," said Bill Wolfe, chief information officer at Abt Electronics. "We evaluated BEA, IBM, and others. We chose BEA for its flexibility and scalability, and we expect it to dramatically reduce the effort, time and cost necessary to enhance and maintain our Web site moving forward." </quote> It sounded like a new purchase, instead of replacement, according the CIO's quote. I really want to hear some WebLogic replacements of WebSphere: why, how, cost, roi, etc. Customers Prefer BEA Over IBM in 'Real World' Competition[ Go to top ] SAN JOSE, Calif., Aug. 14 /Flack Machine/ - BEA subsequently sent TheServerSide.com it's sincere thanks for reprinting its unabridged marketing drivel with a complete lack of editorial context. - Posted by: Corby Page - Posted on: August 15 2002 19:01 EDT - in response to Nate Borg "I remember when we used to pay for advertising," commented Dave Swickers, Weblogic Marketing Director. "Now remember, kids, free advertising: good, free appservers: bad." funny numbers[ Go to top ] According to this release, in the 210 head-to-head sales that BEA says they won, Websphere was the incumbent in 125. That leaves a maximum of 85 customers where Weblogic was the incumbent. Per that sampling, Websphere must have started the quarter with 50 percent more market share than BEA. - Posted by: John Hess - Posted on: August 15 2002 19:50 EDT - in response to Nate Borg funny numbers[ Go to top ] This figure doesn't include the others deals that were not head to head. Just as IBM has a number of deals w/ no competition so does BEA. - Posted by: Ken Larson - Posted on: August 16 2002 11:33 EDT - in response to John Hess Customers Prefer BEA Over IBM in 'Real World' Competition[ Go to top ]? - Posted by: Billy Newport - Posted on: August 15 2002 23:18 EDT - in response to Nate Borg If it even had some kind of journalistic narrative besides the comments from your readers then I would see some justification for sticking it as the lead story but frankly I expected better than this. Given BEA started off with almost all of the market in hand about 3 years ago and are now struggling to keep their #1 slot, that has to be scaring them silly. Here are a couple of things to ponder on when observing the coming 'battles' and to put 210 customers in perspective. Given we have no narrative on this thread, here is my 'spin' on a possible narrative, right or wrong. Given the current drive towards lowering costs and as application servers mature and commoditize, vendors such as IBM, Oracle and Microsoft will have a serious advantage over BEA in any contest because they sell application servers, development tools, databases, enterprise messaging, integration platforms and services, operating systems, hosting facilities, management software and hardware. As this stack gets further integrated across these products, license costs and operating costs for these bundles will come down. As application servers become more commoditized this will become more and more important as a deciding factor for customers when choosing a platform provider (notice, not an application server, I said 'a platform'). The next point is easy to forget for us developers, so I'll state it although it should be obvious. "The only companies that care about technology for it's own sake are technology companies". For everyone else, technology is a necessary 'evil' to do business efficiently and make no mistake, they are looking to get the best return on every dollar spent on IT. Many corporations are starting to consolidate multiple J2EE applications and things like databases around the firm on to 'standardized' server farms in order to lower costs and reduce the number of licenses required. Work out how much a HA setup for a typical application costs (2 app server boxes, 2 boxes with shared DASD for a database, HA veritas etc software, now add in software licenses, SAs, backup costs, operating costs) and you can see why it's a question of when not if this will happen. Once they do this, then a good chunk will figure out that it's cheaper again to outsource this to a third party hosting company, further reducing license revenue as license are shared among a larger pool of applications. As the platform matures, they'll upgrade less, which will suit the hosting companies as it's less work for them and it suits the customers as it's less work for them too. Again, license revenue drops. Even smaller companies will do this once the big guys create the market and lower the cost of entry for this service. More consolidation of license revenue occurs and it drops again.). IBM calls it the fifth utility or eHosting. Once this starts to happen widely and it's gonna, a company whose bottom line depends on license revenue from commodity software which is only a small piece of the puzzle is going to be in jeopardy and it's going to get squeezed, and squeezed hard. Microsoft is the only company that have survived this commodization in the past and they had a defacto monopoly to alleviate pricing pressure thus avoiding the trap. BEA does not have a monopoly today and isn't likely to have it moving forward either. Look at what Oracle, SAP, Intel, IBM, GE etc are investing in. It's costing billions to make the investments needed to carry on as a player in the market environment which is coming. What are they doing? They are investing in ehosting type infrastructure and it's only for the very deep pocketed. This is where enterprise software is moving, not J2EE v10 or JMS v4, it's becoming a service for customers to use just like they use water or electricity today. Now look at BEA and what they are investing in and tell me how important is it that they have 34% versus 32% for IBM right now when looking ahead over several years. But wait, it's troubling isn't it, maybe BEA knows something which GE, IBM, Oracle, Intel and Microsoft et al have missed, are all the other companies stupid and throwing billions away? are Andy Grove, Ballmer, Ellison or Sam P clueless? Read between the lines here and see whats going to happen next. Someone is going to buy them and BEA can spin this anyway they want but I think this is inescapable, it's that or fade away. Billy (Opinions are my own and don't represent IBM) Customers Prefer BEA Over IBM in 'Real World' Competition[ Go to top ] "The only companies that care about technology for it's own sake are technology companies". - Posted by: Markus Neifer - Posted on: August 16 2002 02:25 EDT - in response to Billy Newport Billy, i'll save your message in my archives. Sometimes geeks forget what this game is all about. Thank you for the reminder. Markus Customers Prefer BEA Over IBM in 'Real World' Competition[ Go to top ] Billy, i'll save your message in my archives. - Posted by: Andreas Mueller - Posted on: August 16 2002 06:44 EDT - in response to Markus Neifer > Sometimes geeks forget what this game is all > about. Thank you for the reminder. Yeah, me too.. as always - it's a pleasure to read his comments! -- Andreas Customers Prefer BEA Over IBM in 'Real World' Competition[ Go to top ] - Posted by: Debjani Roy - Posted on: August 16 2002 08:16 EDT - in response to Andreas Mueller a message for posterity. remember how engineers disliked working for those giant power utilities ... all the chaotic fun we have will be over soon Customers Prefer BEA Over IBM in 'Real World' Competition[ Go to top ] "). " - Posted by: Dheeraj Jain - Posted on: August 16 2002 03:53 EDT - in response to Billy Newport Did you mean the ASP model will again enter into the IT shops of the big enterprise ? Customers Prefer BEA Over IBM in 'Real World' Competition[ Go to top ] Dherraj, - Posted by: Billy Newport - Posted on: August 16 2002 06:06 EDT - in response to Dheeraj Jain Yes, big first, and once cost barriers come down then middle sized and then smaller ones. Billy Customers Prefer BEA Over IBM in 'Real World' Competition[ Go to top ] Billy Newport writes : - Posted by: zohar melamed - Posted on: August 16 2002 12:44 EDT - in response to Billy Newport >>Given BEA started off with almost all of the market in >>hand about 3 years ago and are now struggling to keep >>their #1 slot, that has to be scaring them silly. This has a lot to do with the fact J2EE is an open standard implemented by multiple vendors and is to be expected. What's odd is that IBM,HP,SUN,Oracle, et al failed to dislodge them from the nunber 1 slot so far. Oracle and SUN will gradually take market share away from BEA and IBM, that is also to be expected. Looking at how companies spend their cash, IBM might like to consider investing in the WebSphere app server, not eHosting. Will they be the last major vendor with a 1.3 solution ? Think of the billions spent by companies paying for IBM's profesionl services to come in and salvage various WebSphere projects. This is the first area for saving, and is simpler to tackle then eHosting. Oracle's mainstay is their RDBMS offering, It's a good easy to use product, are they a weak, one product company ? How about SAP ? Do you consider having a product that is easy to develop with, requires minimal external consultancy, and supports the latest standards "Technology for it's own sake" ? Customers Prefer BEA Over IBM in 'Real World' Competition[ Go to top ] What's odd is that IBM,HP,SUN,Oracle, et al failed to dislodge them from the nunber 1 slot so far. - Posted by: Billy Newport - Posted on: August 16 2002 14:12 EDT - in response to zohar melamed <bn> Very high by the end of the year. </bn> Will they be the last major vendor with a 1.3 solution ? <bn> It's possible and thats not the most important thing on the radar. I've personally heard customers 'complain' that the products are rolling out faster than they can keep up. </bn> Think of the billions spent by companies paying for IBM's profesionl services to come in and salvage various WebSphere projects. This is the first area for saving, and is simpler to tackle then eHosting. <bn> Right, IBM has and is spending a fortune on tools which allow J2EE enterprise applications to be developed more easily than before. Look at eclipse and WSAD. There are also two costs here, one is development, one is deployment. Tools needs to step up to make development cheaper, deployment will probably get cheaper through hosting. </bn> Oracle's mainstay is their RDBMS offering, It's a good easy to use product, are they a weak, one product company ? <bn> Oracle hosting, Oracle Applications suite, ... hardly a one product company. They have bet huge on oracle applications as well hosting facilities so customers can outsource their applications as well as databases etc. They are heavy investors in network computing as well as Larry investing in that Oracle Accountancy eapplication which is available now. </bn> How about SAP ? <bn> Building mySAP.com </bn> Do you consider having a product that is easy to develop with, requires minimal external consultancy, and supports the latest standards "Technology for it's own sake" ? <bn> Ease of development will soon have little to do with the production application server. Standards will let tools vendors ship lightweight, RAD friendly J2EE servers which are used for development. Deployment can use different servers with different characteristics. Although, the J2EE standard is a ways away from making applications this portable as this point. I think to compete with Visual Studio, we'll see builtin application servers very tightly integrated with tools. So, if you're in the application server business then you need your own tooling or you better be in bed with a tools vendor and working very closely with them. </bn> Customers Prefer BEA Over IBM in 'Real World' Competition[ Go to top ] - Posted by: Nick Minutello - Posted on: August 18 2002 20:31 EDT - in response to Billy Newport Billy, You often state that your views are your own and not IBM's, however some of what you say here sounds like it comes directly from an IBM marketing handbook. I say this becasue I have heard it before - from other IBM employees (and, more recently, from Sun). I am not doubting your technical ability, and a lot of what you write is quite interesting, however, your one-eyed support for your employer, IBM, and taking potshots at competitors - BEA in particular - is not really very professional. It would perhaps be more acceptable if you were "independant analyst", but you are not - and the bias is evident (in this post and others). Why do none of the guys that post here from BEA, Oracle, HP, Borland, Macromedia etc feel it is necessary to lower the level of debate to "we are going to put them out of business" - "they must be scared silly"? I know that you were reacting to the bias of the orignal post (now corrected) but it wasnt posted by any of the BEA guys, was it? And moreover, you didnt actually deal with any of the points in the article... Before I continue, for the record let me point out I dont work for any of the vendors - never have. Moreover, I dont hold any shares or any interests in any either. I work for what is known as a "customer" - something that a lot of the larger vendors seem to forget now and again. The company I work for is a customer of IBM, BEA, Oracle, Tibco, Microsoft, Sybase and many other vendors, so there is no hidden agenda - no cosy relationship. Currently, on the appserver front, BEA happen to give us what we ask for. As soon as they stop delivering, they will likely be replaced by a vendor who does deliver. If that happens to be Websphere, then great. That is what competition is all about - its what J2EE allows us to do. While I dont think the original article that prompted this thread had a great deal of value, I certainly dont think that the resultant debate adds any. The original article claimed that some existing Websphere customers preferred Weblogic. I dont plan to argue for that case or refute it - but I will acount our experience as I guess we make up 1 of the 125 customers where Websphere was the encumbent platform (if you believe those numbers that is). (However, I will point out that we are still Websphere customers and will likely continue to use both). In the last 12 months or so, I have met a few employees of large organisations, banks etc. It was interesting - a number of them were at various stages of going through a full-pitch internal battle with their "standards" people in order to use (usually Weblogic) over Websphere. It was interesting because at that time, we were also going through our own exercise of getting Weblogic "approved" as an alternative standard to Websphere. Interestingly, there were no cases of Websphere replacing any appserver. Many of the complaints of Websphere that I heard during these discussions were the same - and strikingly similar to our own. It is a pain to use: To be fair, a lot of them were using WAS3.5. Also, to be fair, most were using VAJ, which they hated. (it just goes to show that integrated tooling is not as important as good tooling). It is way behind in standards: While the december 2001 alpha release of WAS5 generated some optimism that IBM had turned the corner on its stance on standards support, 9 months later we are still waiting for a shipping product. (I hear its coming soon?). (More on why I think standards support is important later) Integration with non-ibm products is average: While potentially contentious, this assertion has some basis: On wintel, only the IBM JVM is supported (what about Sun, Jrockit?). Full XA integration with messaging was only via MQ. Support for BLOB's worked with DB2, but not with Oracle. It was expensive to maintain: Most of the people had full-time IBM consultants on site that were required to keep things running (in addition to their own support staff). Not because it was utterly unreliable - but mainly because when problems did occur, it was difficult to find out how fix/avoid them. Also, just getting up and running for someone new to WAS too often required assistance. The support from IBM was poor: Also a contentious point, there is a general feeling that the level of attention they got from IBM was less than that of most other software vendors. I can give examples of our own current ridiculous situation regarding IBM support, however, to be fair, its not all IBM's fault, so I wont. Now, I grant that this experience with Websphere comes from a limited group of poeple - I am sure there are people that are perfectly happy with Websphere. I am sure that there are also those that disagree violently with the points above. Please note that I am not arguing that the above is a generalisation, nor am I trying to extrapolate from that - its just an account of our experience/opinions and those of people I spoke to - readers can take it with a grain of salt. With particular reference to the points you raised in your response: Integrated Product Stack: The arguments that seem to be coming from the big vendors seem to be the same: that it is vital to have a completely integrated stack - and also that this is also what customers want. Any vendor that doesnt have the "full-stack" is going to get squeezed out of business. To some extent, this goes against the best-of-breed ethos of J2EE. It also goes against past experience, Databases are a commodotized market, yet Oracle have enjoyed a healthy market share - why? Not because they have sold an integrated stack, but because its a good product. There will always be a market for a good product. Customers want choice. Customers dont necessarily want the whole stack - they want to be able to integrate the products they choose without having to pay a penalty. Those that dont want to integrate with anything else would probably be happy going with Microsoft. Also, the pricing advantages touted of the bundled-stack are quickly evaporated if extra development is required because there are missing features in any one of the products or if it is considerably more difficult to integrate with *existing* third-party products. E.g. If I am using Websphere on Wintel, and I hit a bug in the IBM JVM (which we have done), I want to be able to swap it out (without losing my support) until the bug is fixed. If my application is down or delayed in going to production, the total cost of this will dwarf the *total* license cost - let alone the delta saving in bundled licensing. We had a situation where a project was delayed 6 months from going into production because of an AIX/JVM bug. There was not much we could do but wait for the patch (there is only one JVM for AIX). We, and I am sure others, want to avoid these situations where we are left with no choice. Thats why, for instance, we choose J2EE over .Net. Standards and Application Servers: In response to criticisms regarding Webshere's slow uptake of standards, I have heard the following from IBM employees: "If you want the latest bit-twiddling API's, then Websphere is not the right choice. Websphere only supports mature standards". I have also seen: "its not the most important thing on the radar" and "The only companies that care about technology for it's own sake are technology companies". I continually assert that, for most projects, the cost of development is far greater than the license costs of appservers. While the investment in tooling from IBM and other vendors helps, its not going to solve development problems that arise when the target appserver doesnt support the required features (read standards). Supporting the current standards means that we can leverage more of the appserver features (while avoiding vendor-lock) to reduce the amount of development we have to do. The less development we have to do, the cheaper all around it is for us. If we develop something an appserver should give us, it can be *very* expensive. We take an initial hit in development and testing. We take a secondary hit when, inevitably, the first implementation is poor, and will require more work. We take a further hit in documenting how to support it. And then we take a continuous hit in maintaining it and supporting it for the life of the application. And all these costs are diverting resources from the efforts of writing and supporting software that actually *makes* us money. Having a product that is easy to develop with, requires minimal external consultancy, and supports the latest standards is not "Technology for it's own sake". It gives us (and, I am sure, others) the potential to save a lot of money. More money than bundled licensing and eHosting will. On the Topic of eHosting; I have some doubts about the significance of this. I am not denying there is a market, but I am not convinced that it is so significant that it is going to drive all but giants: IBM, Oracle and Microsoft out of business. For many organisations, there will be reasons why outsourcing hosting wont happen: + Some will be technical reasons: Legacy constraints will prevent it from being possible. + Some will be legal reasons: Some organisations have regulatory/legal requirements that would prohibit them from hosting off-site (banks, for example). + Some will be strategic reasons: Will the organisation place that level of trust in the hosting company - will they take that level of risk? I am not sure our organisation would. If you think, after reading this, that I am rabid supporter of BEA or have any dislike for IBM or any of its employees, then you would be wrong. I give out credit and criticism in equal measure where its due. So why do I post this? Its certainly not for fun - I have had my fill of Weblogic/Websphere debates from our own internal discussions over the past 9 months. The reason is because TSS has a large readership and is influential. (I have no doubt that this is why Billy posted his reply). If left unchallenged, then the arguments such as posted above start to appear in peoples decision making rationale. It wouldnt be the first time I have heard some material posted on TSS appear in a discussion. Anyway, we can see the gloves are coming off in the J2EE marketplace... Regards, Nick Customers Prefer BEA Over IBM in 'Real World' Competition[ Go to top ] Nick, - Posted by: Billy Newport - Posted on: August 19 2002 07:18 EDT - in response to Nick Minutello From my posting: "Given we have no narrative on this thread, here is my 'spin' on a possible narrative, right or wrong." A possible narrative. I made no shots on WebLogic the product. I didn't say WebSphere is better than WebLogic or vice versa. I didn't recycle old issues with WebLogic 4.x, 5.x or 6.x or the current 7.0. I wasn't saying product X is better than product Y. It was purely 'a possible narrative' on a possible market direction (right or wrong) rather than whose application server is better. Latest product standards. Yep, WAS 5.0 will be out in Nov 02. It'll support J2EE 1.3 plus the enterprise version has all the web service composition/process choreography stuff, asynchronous beans, business rules, and the rest. You spoke of the issues with customers needing to develop their own plumbing. I agree and this is what we're doing to help. I agree that supporting the latest standards is important but I also think supporting new types of application, plumbing and expanding the reach of J2EE based technology is important also. So, it's a balance. There is a bunch of stuff present in the full product which is very useful to customers and isn't part of the J2EE specification at this point. All of the extension stuff is or will be a JSR very soon now so the extension work helps us gain experience with new features and helps improve the J2EE spec through improved JSRs. The integrated product stack. Integrated does not mean unintegratable or not competitive on it's own. Each product in the stack should be usable on it's own and be competitive on it's own. How-ever, using multiple products together should result in efficiencies and enhance the competitiveness of the overall suite. Thats the point. eHosting. This is happening even in markets you think it unlikely. This will become more important in larger customers. Billy Customers Prefer BEA Over IBM in 'Real World' Competition[ Go to top ] - Posted by: Nick Minutello - Posted on: August 19 2002 19:32 EDT - in response to Billy Newport >> I made no shots on WebLogic the product <grin> No, thats true, but instead you took the opportunity to take plenty at BEA. (its not the first time either). I just think that plenty of people take interest in what you write, however I think that even you would admit that you dont hold an impartial position. It would be sad if TSS was hijacked by vendors to be used as a platform for launching their marketing wars... >>Yep, WAS 5.0 will be out in Nov 02 Oh no. I was told August - I jokingly interpreted that as September... ...very well. Like I said, it makes it difficult for us to use WAS, when its so far behind. >>using multiple products together should result in >>efficiencies Agreed. I think people object about vendor-lockin when its unreasonably difficult (or impossible) to integrate other products (or they are "not supported"). In general, I am wary of companies that sell a "full stack". Its usually in their interest to make it more difficult to integrate products other than their own. On the other hand, vendors that specialise tend to make damn sure that they are integrated with as much as they can - its in their interest to. >>This will become more important in larger customers Given how conservative larger organisations tend to be, I would have thought these would have been the last to take up out-hosting (for the last reason I outlined). Do you mean larger *existing* customers - ie full-on IBM/Microsoft/Oracle shops? Cheers, -Nick Customers Prefer BEA Over IBM in 'Real World' Competition[ Go to top ] Nick, - Posted by: Randy Schnier - Posted on: August 19 2002 11:55 EDT - in response to Nick Minutello In addition to Billy's comments, I also wanted to thank you for taking the time to write such a thoughtful post. In general, I hardly think the contents of a BEA-written press release saying "we're better than IBM" qualifies as NEWS. I was surprised to see it posted here in the first place. Randy Schnier WebSphere Development (colleague of Billy) Customers Prefer BEA Over IBM in 'Real World' Competition[ Go to top ] I think the BEA sales pitch was worth posting for the quality of response it got from such a talented bunch of individuals. - Posted by: Web Master - Posted on: August 19 2002 16:44 EDT - in response to Randy Schnier Customers Prefer BEA Over IBM in 'Real World' Competition[ Go to top ] - Posted by: Nick Minutello - Posted on: August 19 2002 19:42 EDT - in response to Randy Schnier >>In general, I hardly think the contents of a BEA-written >>press release saying "we're better than IBM" qualifies as >>NEWS. I was surprised to see it posted here in the first >>place. Agreed. This site is valued for its content and the quality of contribution from readers. As I mentioned above, it would be rather unfortunate if we have to start running everything through the marketing-bullshit-filter. -Nick Customers Prefer BEA Over IBM in 'Real World' Competition -[ Go to top ] << Disappointing that TSS publishes this kind of one sided press release. Publishing stories by 'independant' analysts is one thing, at least they are supposed to have no bias - Posted by: Java Enterprise Developer Incognito - Posted on: August 18 2002 17:00 EDT - in response to Billy Newport >> Agreed. However, the only independent analyst I knew personally is working for food. Every one else is getting paid to deliver white papers. < "The only companies that care about technology for it's own sake are technology companies". >> Or developers who have to make it work. 100% agreement there. Chief Fingering Officer to Chief Incompetent Officer: "What is the problem with your developers? Didn't we got a great deal on these licenses from Incumbent Baggage Machines®? Now you are telling me that we have pay these consultants from Imperial Globetrotting Consulting Group® for another year? Plane tickets, meals and all? Chief Incompetent Officer, "Yes Sir, it's all the developers' fault. For months, I have heard nothing but whining about lack of features like hot deployment, many-to-many CMR, local ejb and workstations only fit for word-processing. Why, when I was managing that mother of all RPG projects at the Post Office, all we need are flags and dumb terminals. Chief Fingering Officer: "Fire the smart-asses and outsource the whole project!" Chief Incompetent Officer: "Yes Sir! Consider it done! By the way, we did get a ton of free DataBug2 licenses. Eat your heart out, Larry" <>>“No high-powered executive ever gets fired for buying Incumbent Baggage Machines”® Even the guys from Pee-Wee Consulting(PwC), under new management, can tell you that. <>>Carly, it's going to be cheaper than Bluestone(RIP). Get your checkbook ready. How true. BEA is losing the big marketing/financial war even while winning many small technical battles. For large enterprises with legacy systems and looking for complete solutions, BEA comes up empty. Java Enterprise Developer Incognito Disclaimer : I have never been a high-priced consultant, high-powered financial executive nor an ignorant IT executive bent on covering my own ass at a Fortune 500 corporation. As such, I make no representation as to having any qualifications to make sound, informed opinions on Enterprise Computing Solutions and the budgeting thereof. In fact, I have none at all. My only qualification is that I get paid to deliver J2EE software that works. It is also the reason I am still making a living. Opinions are my strictly my own and don't represent Incumbent Baggage Machines® or Being Executive-decisioned Alive®. I have never been an independent analyst, dependent analyst, employee, H1B-consultant, shareholder, stock-option holder, bean counter of either entities, real or imagined) Customers Prefer BEA Over IBM in 'Real World' Competition[ Go to top ] "Once they do this, then a good chunk will figure out that it's cheaper again to outsource this to a third party hosting company, further reducing license revenue as license are shared among a larger pool of applications" - Posted by: Dheeraj Jain - Posted on: August 20 2002 06:49 EDT - in response to Billy Newport Just tyring to understand the feasibilty of above made statement.Could you exlpain how a JVM could be shared with other xyz org's apps.How can you consolidate apps even with your own/other enterprise.I think you end up spending more in designing,paying to consultants,modifying the apps to reduce license spending. How clustering,security,load balancing would work if you mix up things.I see this more a academic approach or lacking some knowledge in this. P.S We can also take this offline. Customers Prefer BEA Over IBM in 'Real World' Competition[ Go to top ] Send me an email at bnewport at yahoo dot com and we can discuss it if you'd like. - Posted by: Billy Newport - Posted on: August 20 2002 13:55 EDT - in response to Dheeraj Jain Billy Real world Websphere 5 : IBM is not an option (AFAIK)[ Go to top ] Hello, - Posted by: Richard De Falco - Posted on: April 14 2003 11:59 EDT - in response to Billy Newport I don't understand how it is possible for IBM to claim such an important market share. How all these people are doing for developping on a App Server like websphere 5 (I do not know about earlier versions) ? That's for now, a mystery for me. If someone can bring up the light for me.... Let me explain a little further. I'm working for an independant software vendor and developping the same product on Jboss 3, Weblogic 7, Websphere 5. My application is made of : 1 ear containing 3 ejb-jar + java utils classes : ejb-jar 1 : 1 session, 1 entity bean (cmp) ejb-jar 2 : 1 session, 6 entity bean (cmp) ejb-jar 3 : 2 entity bean (cmp with cmr) war : 1 servlet + ejb-client-jars Total size of the ear : about 1MB. My developpement server is Jboss which is perfect (light, fast, easy to use, reliable). Then, when I reach a "stable version", I port it to weblogic and websphere. Weblogic porting and debugging is usually a matter of hours (about half a day), weblogic enforces usually specs compliance a little bit than JBoss. Though it is not perfect (bugs, cmp-jdbc mapping confusing etc...) it is USABLE. Now we come to websphere, I'll list below what I was needed to do (maybe I'm missing some things here, but if there are any WAS experienced developpers that point something wrong, I will be happy to know what... because I do not found answers anywhere!!). 1. Build it 1.1 Build your ear the "classic" way, (deployable as it is on other servers) (15 secs). 1.2 Make ant tasks working (WEBSPHERE SPECIFIC): - the trick here is that websphere comes with his own "customized" jre (see .properties and dll and so on... under WAS_HOME/java). You must use this jre even for building, if not... you're in big trouble. There is even a .bat to run ant tasks in bin directory !!! The good news is that if ther is no such script, I would not have been able to make it run because there is no documentation (AFAIK) on this !!! - the ant tasks documentation is extraordinary incomplete and inconsistent (there are typos, that prove that IBML people don't even reread the doc). Am I the only one on earth that build and deploy without using WSAD and/or console ? I'm asking myself. - For now, it works but on the same machine : if i build on one box and the deploy on the other from my dev box : the deploy task (wsInstallApp) is not working saying that it cannot find a file : com.ibm.websphere.management.exception.AdminException: ADMA0043E: C:\app26673.ear (which is not my original ear) not found. Of course, don't expect to find any infos on this... 1.3. Lauch the build process (WEBSPHERE SPECIFIC): Run ant task (wsejbdeploy) with your ear. On my 512MB machine it takes 450 (7-8 mn) seconds to complete. It makes me a websphereonly.ear, about 1.5 size of my original one. At this point I do not know how people that have dozens of ejb do, but i like to know if there is any. For me, it gives me the time to write this article !!!! Other server : one file copy is enough (1 sec to copy, 10 secs to deploy) 1.4 Stop your application previous version (20s) (WEBSPHERE SPECIFIC) 1.5 Desinstall it (20s) (WEBSPHERE SPECIFIC) 1.6 Uncompress the generated ear, get the generated table.ddl that lies within and manage to run it against your database (destroy schema - drop tables, create a new one and so on..). About 3-4 minutes. (WEBSPHERE SPECIFIC) Any way of deploying database schema automatically, at least on cloudscape, which is shipped along ? didn't found it (this is the default on other appserver). Any way to build your ear independant of database back end ? didn't found it. For now I must ejbdeploy again (and again, and again...) - see step 1.3. What if my DB isn't in the IBM list ? Didn't found it. 1.7 Install It (30 s) (WEBSPHERE SPECIFIC) 1.8 Start It (20 s) (WEBSPHERE SPECIFIC) 1.9 Stop and start your server (3-5 mns). This is because (i suppose) you don't know when you have to do it and when not. The console is saying : maybe you should restart your server : may be or may be not. To be sure, I restart. This is getting worse and worse if you plan to debug or turn on some logs or profiling. (WEBSPHERE SPECIFIC) TOTAL TIME : 15-20 MINUTES. 2. Run It 2.0 Buy a BIG BIG Box, even if you're the only client on your app, debugging. (WEBSPHERE SPECIFIC) 2.1 It does not work. The SAME application is working UNMODIFIED on JBoss and weblogic, but not on websphere. For example have you tried to run local ejb calls in websphere ? If you want do it, you have to discover that there is a local namespace and use IN YOUR CODE. Since this, i have in my code (write once run anywhere BUT on websphere): (WEBSPHERE SPECIFIC) static final String WASLOCALJNDISTRING = "local:ejb/"; public static String getSequenceLocalHome() { if (SystemProperties.isWebsphere()) return WASLOCALJNDISTRING + SEQUENCE_HOME; return SEQUENCE_LOCAL_HOME; } Try to find where it is clealrly stated in documentation... You will have fun. And one bad try is expensive : see points 1.x !!! 2.2 It does not work and there is mysterious errors happenings : - subtransactions not supported ??!? or some mysterious exceptions like: com.ibm.ejs.container.CreateFailureException: javax.ejb.TransactionRolledbackLocalException: javax.transaction.TransactionRolledbackException: com.ibm.websphere.csi.CSITransactionRolledbackException: null; nested exception is: javax.ejb.TransactionRolledbackLocalException: javax.transaction.TransactionRolledbackException: com.ibm.websphere.csi.CSITransactionRolledbackException: null; nested exception is: com.ibm.ejs.container.HomeDisabledException: OpenServer#sequencegenerator-ejb.jar#Sequence com.ibm.ejs.container.HomeDisabledException: OpenServer#sequencegenerator-ejb.jar#Sequence at com.icominfo.openserver.accesscontrol.provider.ejb.entity.EJSLocalCMPPrincipalHome_300c336f.create(Unknown Source) at test.com.icominfo.PropertyTestEJB.setUp(PropertyTestEJB.java:55) helpful, no ? Generally speaking, when it does not work you're in big big trouble because you WILL not find the cause of your error : neither in docs, neither on ibm website, neither on news (newsgroups on ibm app server are incredibly poor vs BEA ones - for example) --> (WEBSPHERE SPECIFIC) 3. Try to debug If you put trace on, you should carrefully select whch one because you will have no longer a usable machine (it slows down so much that it is unusable). 4. Call IBM support After five detailed mails to evaluation support, I do not have any response but "we're looking your problem". There is definitively NO evalutaion support. You will have to pay to see. For me, I would not ask my company to do it after this demonstration. 5. Use WSAD... and stay on it. (WEBSPHERE SPECIFIC) It seems that a big point on IBM strategy is hiding proprietary details behind WSAD such making you completely dependant on it. IBM technical papers are WSAD screen shots compil. My understanding is that: if you're using WSAD things get a little less complicated but you're catch, exactly what IBM is wanting to keep his market share !!! So, at this point, even an IBM Global Services engineer should have switched to bea or jboss or whatever you like: I think it could not be worst. For now, I'm about to definitiveley remove this from my Hard Disk, despite the "market share" that IBM is claiming, unless some WAS fluent guy is pointing me where I'm completeley missing something !!! Have fun, Richard PS: if you would like any details to make the discussion go forward, don't hesitate. BEA Claims Big Wins Against IBM[ Go to top ] I think BEA & Websphere are both good app server. But the release of Websphere 4.03 has taken a good lead over WL 7.0. I have deployed application in WL 7.0 in production which is really very unstable and flacky on high load, The WAS 4.03 runs fine in high load and seems to be 30% or more faster than WLS 7.0 . I hate to say this but WLS 7.0 is still not ready for production. It has too many many issue on the console, node manager, clustering and run time issues I would recommended to stay away from WLS 7.0. I hope BEA will resolve the issues soon on the other hand Websphere console and ease of creating nodes and clustering beats far than WLS 7.0. The load balancing, scalability and hot deployment of WAS 4.03 clearly makes it a winner. I have been working on java for more 6 years and have tried both appserver. Websphere 5.0 will be another clear winner for IBM from what I have seen so far. I am also trying out the Oracle 9iAS and JDEV 9i and looks good but not mature yet. I am really glad that we have options to choose app server in the market - Posted by: Jamie Schiner - Posted on: August 17 2002 13:20 EDT - in response to Nate Borg BEA Claims Big Wins Against IBM[ Go to top ] hmm, just wondering. How does jboss stack up against those big guys ? Have you had any experience or heard anything about this *free* app server ? Thanks for the feedback. - Posted by: Yin tse - Posted on: August 18 2002 12:56 EDT - in response to Jamie Schiner BEA Claims Big Wins Against IBM[ Go to top ] Yin: "How does jboss stack up against those big guys?" - Posted by: Cameron Purdy - Posted on: August 19 2002 10:29 EDT - in response to Yin tse IMHO - JBoss is the easiest EJB platform for development and the most cost-effective (duh!) for bundling. My guess is you'll see most ISV apps developed for JBoss (low cost turn-key, default server), WebLogic and WebSphere (perceived commercial market leaders). Most large companies do internal "enterprise app" development solely on WebLogic, WebSphere, or another proprietary (in the objective sense) application server. Regarding performance, it really depends what you are doing. JBoss is easily "good enough" for the majority of applications, and in a few situations it meets/beats the "market leaders". However, in general, JBoss is not selected for performance reasons, but rather (a) ease of use, (b) availability of source, (c) ability to customize and (most obviously) (d) cost. In that sense, you could compare it to Apache Jakarta Tomcat, which you rarely select for speed reasons, but the performance is usually good enough, it usually is very quick to support the latest standards, it is ubiquitous in its development use and deployments, and the price is right. Peace, Cameron Purdy Tangosol, Inc. article: IBM Disputes BEA Application Server Claims[ Go to top ] - Posted by: Sean Sullivan - Posted on: August 19 2002 18:37 EDT - in response to Nate Borg IBM Disputes BEA Application Server Claims August 19, 2002 BEA Claims Big Wins Against IBM[ Go to top ] I have a question for the BEA employees.. - Posted by: neunet n - Posted on: August 19 2002 22:30 EDT - in response to Nate Borg How are the boys from Redmond (x-microserfs), whom you have employed doing? I see they have been busy beavers propelling BEA to non-standards J2EE. IBM Disputes BEA Application Server Claims[ Go to top ] - Posted by: bco ley - Posted on: August 20 2002 13:42 EDT - in response to Nate Borg
http://www.theserverside.com/discussions/thread.tss?thread_id=14998
CC-MAIN-2016-26
refinedweb
8,135
60.24
ggiGetGamma, ggiSetGamma, ggiGetGammaMap, ggiSetGammaMap, ggiGammaMax - Manipulate the gamma maps and the gamma correction of a visual #include <ggi/ggi.h> int ggiGetGamma(ggi_visual_t vis, ggi_float *r, ggi_float *g, ggi_float *b); int ggiSetGamma(ggi_visual_t vis, ggi_float r, ggi_float g, ggi_float b); int ggiGetGammaMap(ggi_visual_t vis, int s, int len, ggi_color *gammamap); int ggiSetGammaMap(ggi_visual_t vis, int s, int len, const ggi_color *gammamap); int ggiGammaMax(ggi_visual_t vis, uint32_t bitmeaning, int *max_r, int *max_w); Some modes on some hardware can use a per-channel palette to lookup the values before sending to the monitor. Generally this is used for gamma correction by filling the lookup table with a curve, hence the name "gamma map", but it could be used for other things e.g. special effects in games. Truecolor modes with gamma maps are sometimes referred to as "directcolor". ggiSetGammaMap and ggiGetGammaMap set or get the gamma map, for len colors starting at s. In the event that there are more map entries for some channels than others, values for the upper indices of the map in the shallow channels are ignored on write, and undefined on read. The ggiGammaMax function is used in order to find out how many readable and writeable entries are in the map (returned in the integers referenced by max_w and max_r). This must be done once for each channel. The parameter bitmeaning should be set to the bit meaning (e.g. GGI_BM_TYPE_COLOR | GGI_BM_SUB_BLUE) of the channel of which you are inquiring. If ggiGammaMax returns an ggi-error(3), you cannot set the gamma map on this visual. If ggiGammaMax succeeds, but max_w is -1 on return, this means that ggiSetGamma will work, but that ggiSetGammaMap will not. ggiSetGamma and ggiGetGamma sets or gets the gamma correction for the visual according to the usual curve associated with the given values for each channel, which should be positive. All five functions 0 for OK, otherwise a ggi-error(3) code.
http://huge-man-linux.net/man3/ggiGammaMax.html
CC-MAIN-2017-13
refinedweb
321
59.13
🦅 SwiftGraphQL A GraphQL client that lets you forget about GraphQL. Features - ✨ Intuitive: You'll forget about the GraphQL layer altogether. - 🦅 Swift-First: It lets you use Swift constructs in favour of GraphQL language. - 🏖 Time Saving: I've built it so you don't have to waste your precous time. - 🏔 High Level: You don't have to worry about naming collisions, variables, anything. Just Swift. Overview SwiftGraphQL is a Swift code generator. let name: String let homePlanet: String? } // Create a selection. let human = Selection<Human, Objects.Human> { Human( id: try $0.id(), name: try $0.name(), homePlanet: try $0.homePlanet() ) } // Construct a query. let query = Selection<[Human], Operations.Query> { try $0.humans(human.list) } // Perform the query. SG.send(query, to: "") { result in if let data = try? result.get() { print(data) // [Human] } } Installation To install it using Swift Package Manager, open the following menu item in Xcode: File > Swift Packages > Add Package Dependency... In the Choose Package Repository prompt add this url: Then press Next and complete the remaining steps. To learn more about Swift Package Manager, check out the official documentation. Why? Why bother? Simply put, it's going to save you and your team lots of time. There's a high chance that you are currently writing most of your GraphQL queries by hand. If not, there's probably some part of the link between backend and your frontend that you have to do manually. And as you well know, manual work is error-prone. This library is an end to end type-safe. This way, once your app compiles, you know it's going to work. Why another GraphQL library? There was no other library that would let me fetch my schema, generate the Swift code, build queries in Swift, and easily adapt query results to my model. I was considering using Apollo iOS for my projects, but I couldn't get to the same level of type-safety as with SwiftGraphQL. This library has been heavily inspired by Dillon Kearns elm-graphql. How it works? It seems like the best way to learn how to use SwiftGraphQL is by understanding how it works behind the scenes. The first concept that you should know about is Selection. Selection lets you select which fields you want to query from a certain GraphQL object. The interesting part about Selection is that there's actually only one Selection type, but it has generic extensions. Those generic extensions are using phantom types to differentiate which fields you may select in particular object. TLDR; Phantom types let you use Generics to constrain methods to specific types. You can see them at work in the funny looking Selection<Type, Scope> parts of the code that let you select what you want to query. You can read more about phantom types here, but for now it suffice to understand that we use Scope to limit what you may or may not select in a query. Take a breath, pause, think about Selection. Now that you know about selection, let's say that we want to query some fields on our Human GraphQL type. The first parameter in Selection - Type - lets us say what the end "product" of this selection is going to be. This could be a String, a Bool, a Human, a Droid - anything. You decide!. The second parameter - Scope (or TypeLock) - then tells Selection which object you want to query. You can think of these two as: Type: what your app will receive Scopewhat SwiftGraphQL should query. Take a breath, pause, think about Scopeand Type. But how do we select the fields? That's what the Selection initializer is for. Selection initializer is a class with methods matching the names of GraphQL fields in your type. When you call a method two things happen. First, the method tells selection that you want to query that field. Secondly, it tries to process the data from the response and returns the data that was supposed to get from that particular field. For example: let human = Selection<Human, Objects.Human> { select in Human( id: try select.id(), // String name: try select.name(), // String homePlanet: try select.homePlanet() // String? ) } As you may have noticed, id returns just a string - not an optional. But how's that possible if the first time we call that function we don't even have the data yet? SwiftGraphQL intuitively mocks the data the first time around to make sure Swift is happy. That value, however, is left unnoticed - you'll never see it. Take a breath, pause, think about Selection. Again. Alright! Now that we truly understand Selection, let's fetch some data. We use GraphQLClient's send method to send queries to the backend. To make sure you are sending the right data, send methods only accept selections of Operations.Query and Operations.Mutation. This way, compiler will tell you if you messed something up. We construct a query in a very similar fashion to making a human selection. let query = Selection<[Human], Operations.Query> { try $0.humans(human.list) } The different part now is that humans accept another selection - a human selection. Furthermore, each selection let's you make it nullable using .nullable or convert it into a list using .list. This way, you can query a list of humans or an optional human. NOTE: We could also simply count the number of humans in the database. We would do that by changing the Type to Int - we are counting - and use Swift's count property on a list. let query = Selection<Int, Operations.Query> { try $0.humans(human.list).count } Take a breath. This is it. Pretty neat, huh?! 😄 Getting started In the following few sections I want to show you how to set up SwiftGraphQL and create your first query. You can try connecting to your API right away or use a playground. We'll create a code generation build step using SwiftPackage executable and explore the API using XCode autocompletion. Generating Swift code First, we need to somehow generate the code specific to your GraphQL schema. We can do that by creating SwiftPackage executable. - Open your terminal and navigate to your project root. - Create a folder named Codegennext to your application folder and cdinside. - Run swift package init --type executableto initialize your executable. - Run open Package.swiftto open XCode editor and add SwiftGraphQL to your dependencies. (I also recommend using Files by John Sundell as a file navigator, but you can use a library of your choice.) // swift-tools-version:5.3 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( // ... dependencies: [ /* Depdendencies*/ .package(name: "SwiftGraphQL", url: "", Package.Dependency.Requirement.branch("main")), .package(url: "", from: "4.0.0"), ], targets: [ .target( name: "Codegen", dependencies: ["SwiftGraphQL", "Files"]), ] // ... ) Don't forget to add both libraries to target depdencies! - Now, open up main.swiftinside your Sources. You want to make it look something like this: import Files import Foundation import SwiftGraphQLCodegen let endpoint = URL(string: "")! do { let target = try Folder.current.parent! .subfolder(at: "<APP>") .createFile(at: "API.swift").url /* Create Generator */ let scalars: [String: String] = [ // Here you can map your scalars GraphQL: Swift. ] let options = GraphQLCodegen.Options(scalarMappings: scalars) let generator = GraphQLCodegen(options: options) /* Generate the API */ try generator.generate(target, from: endpoint) print("Generated API to \(target.absoluteString)") } catch let error { print("ERROR: \(error.localizedDescription)") exit(1) } You can checkout more customization options below in documentation. - Lastly, you want to add a build step to your project. Click on your project file in XCode and navigate to Build Phasesafter you've selected a target. Click on a plus and name the build step "Generate GraphQL". Drag it below the dependencies at the top to make sure it occurs soon enough and paste in the shell below. cd "${SRCROOT}"/Codegen xcrun -sdk macosx swift run - 🎉 That's it! You can verify that it's working by building the project and seeing the generated code. NOTE: You might need to drag the file into the project/workspace. Documentation SwiftGraphQL SwiftGraphQL SwiftGraphQL exposes only one method - send - that lets you send your query to your server. It uses URLRequest internally and shared URLSession to perform the request, and returns Swift's Request type with the data. You can pass in the dictionary of headers to implement authorization mechanism. SG.send(query, to: "") { result in if let data = try? result.get() { print(data) } } SwiftGraphQL intentionally doesn't implement any caching mechanism. This is only a query library and it does that very well. You should implement caching functionality yourself, but you probably don't need it in most cases. Selection<Type, Scope> SwiftGraphQL Selection lets you select fields that you want to fetch from the query on a particular type. SwiftGraphQL has generated phantom types for your operations, objects, interfaces and unions. You can find them by typing Unions./ Interfaces./ Objects./ Operations. followed by a name from your GraphQL schema. You plug those into the Scope parameter. The other parameter Type is what your constructor should return. nullable, list, non-nullable fields Selection packs a collection of utility functions that let you select nullable and list fields using your existing selecitons. Each selection comes with three calculated properties that let you do that: list- to query lists nullable- to query nullable fields nonNullOrFail- to query nullable fields that should be there // Create a non-nullable selection. let human = Selection<Human, Objects.Human> { Human( id: try $0.id(), name: try $0.name() ) } // Use it with nullable and list fields. let query = Selection<Void, Operations.Query> { let list = try $0.humans(human.list) let nullable = try $0.human(id: "100", human.nullable) } You can achieve the same effect using Selection static functions .list, .nullable, and .nonNullOrFail. // Use it with nullable and list fields. let query = Selection<Void, Operations.Query> { let list = try $0.humans(Selection.list(human)) } ⚠️ Don't make any nested calls to the API. Use the first half of the initializer to fetch all the data and return the calculated result. Just don't make nested requests. // WRONG! let human = Selection<String, Objects.Human> { select in let message: String if try select.likesStrawberries() { message = try select.name() } else { message = try select.homePlanet() } return message } // Correct. let human = Selection<String, Objects.Human> { select in /* Data */ let likesStrawberries = try select.likesStrawberries() let name = try select.name() let homePlanet = try select.homePlanet() /* Return */ let message: String if likesStrawberries { message = name } else { message = homePlanet } return message } Union SwiftGraphQL When fetching a union you should provide selections for each of the union sub-types. Additionally, all of those selections should resolve to the same type. let characterUnion = Selection<String, Unions.CharacterUnion> { try $0.on( human: .init { try $0.funFact() /* String */ }, droid: .init { try $0.primaryFunction() /* String */ } ) } You'd usually want to create a Swift enumerator and have different selecitons return different cases. Mapping Selection You might want to map the result of your selection to a new type and get a selection for that new type. You can do that by calling a map function on selection and provide a mapping. struct Human { let id: String let name: String } // Create a selection. let human = Selection<Human, Objects.Human> { Human( id: try $0.id(), name: try $0.name(), ) } // Map the original selection on Human to return String. let humanName: Selection<String, Objects.Human> = human.map { $0.name } Interfaces SwiftGraphQL Interfaces are very similar to unions. The only difference is that you may query for a common field from the intersection. let characterInteface = Selection<String, Interfaces.Character> { /* Common */ let name = try $0.name() /* Fragments */ let about = try $0.on( droid: Selection<String, Objects.Droid> { droid in try droid.primaryFunction() /* String */ }, human: Selection<String, Objects.Human> { human in try human.homePlanet() /* String */ } ) return "\(name). \(about)" } You'd usually want to create a Swift enumerator and have different selecitons return different cases. OptionalArgument SwiftGraphQL GraphQL's null value in an input type may be entirely omitted to represent the absence of a value or supplied as null to provide null value. This comes in especially handy in mutations. Because of that, every input object that has an optional property accepts an optional argument that may either be .present(value), .absent or .null. NOTE: Every nullable argument is by default absent so you don't have to write boilerplate. Codecs - Custom Scalars SwiftGraphQL SwiftGraphQL lets you implement custom scalars that your schema uses. You can do that by conforming to the Codec protocol. It doesn't matter where you implement the codec, it should only be visible to the API so that your app compiles. public protocol Codec: Codable & Hashable { associatedtype WrappedType static var mockValue: WrappedType { get } } You should provide a codec for every scalar that is not natively supported by GraphQL, or map it to an existing Swift type. You can read more about scalar mappings below, in the generator section of the documentation. // DateTime Example struct DateTime: Codec { private var data: Date init(from date: Date) { self.data = date } // MARK: - Public interface var value: String { let formatter = DateFormatter() formatter.locale = Locale(identifier: "fr") formatter.setLocalizedDateFormatFromTemplate("dd-MM-yyyy") return formatter.string(from: self.data) } // MARK: - Codec conformance // MARK: - Decoder init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let value = try container.decode(Int.self) self.data = Date(timeIntervalSince1970: TimeInterval(value)) } // MARK: - Encoder func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(Int(data.timeIntervalSince1970)) } // MARK: - Mock value static var mockValue = DateTime(from: Date()) } Don't forget to add your scalar mapping to code generator options. Otherwise, generator will fail with unknown scalar error. GraphQLCodegen SwiftGraphQLCodegen Lets you generate the code based on a remote schema. It accepts an optional argument options. Use .generate method to generate the code into a specified target. SwiftGraphQL assumes that the target file already exists. I suggest using John Sundell's Files library for navigation between folders and file creation. Check the example above to see how I use it. GraphQLCodegen.Options SwiftGraphQLCodegen Lets you customize code generation. Accepts one property - scalarMappings which should be a dictionary of strings that map keys of GraphQL scalars into Swift scalars. let scalars: [String: String] = ["Date": "DateTime"] let options = GraphQLCodegen.Options(scalarMappings: scalars) How do I create a fragment? Just create a new variable with a selection. In a way, every selection is a fragment! How do I create an alias? You can't. SwiftGraphQL aims to use Swift's high level language features in favour of GraphQL. The primary goal of GraphQL alias is to support fetching same fields with different parameters. SwiftGraphQL automatically manages alias based on the values you provide to a particular field. Because of this, you can select the same field as many times as you'd like. My queries include strange alias. What is that about? SwiftGraphQL uses hashes to construct your queries. There are two parts of the query builder that contribute to the hashes; - the first one - query parameters - uses hashes to differentiate between same fields with different parameters. Because of this, you don't have to manually check that your field names don't collide. - the second one - query variables - uses hashes to link your input values to the part of the query they belong to. SwiftGraphQL laverages Swift's native JSON serialization as I've found it incredibly difficult to represent enumerator values in GraphQL SDL. This way it's also more performant. query($__rsdpxy7uqurl: Greeting!, $__l9q38fwdev22: Greeting!, $_b2ryvzutf9x2: ID!) { greeting__m9oi5wy5dzot: greeting(input: $__rsdpxy7uqurl) character__16agce2xby25o: character(id: $_b2ryvzutf9x2) { __typename ...on Human { homePlanet___5osgbeo0g455: homePlanet } ...on Droid { primaryFunction___5osgbeo0g455: primaryFunction } } } Why do I have to include try whenever I select something? Swift handles errors in a very upfront way. Since we are trying to decode nested values, the decoder might fail at various different depths. Because of that, we have to write try. What are the pitfalls in Apollo iOS that you were referring to at the top? Apollo iOS code generator lets you write your queries upfront and generates the type annotations for them. Let's say that there's a Human object type that has a property friends (who are also humans). Because you could select different fields in Human than in friends (sub- Human), Apollo generates two different nested structs for "each" of the humans. In TypeScript and JavaScript this is not a problem, since objects are not "locked" into definition. In Swift, however, this becomes problematic as you probably want to represent all your humans in your model with only one human type. I ended up writing lots of boilerplate just to get it working, and would have to rewrite it in multiple places everytime backend team changed something. Roadmap and Contributing This library is feature complete for our use case. We are actively using it in our production applications and plan to expand it as our needs change. We'll also publish performance updates and bug fixes that we find. I plan to actively maintain it for many upcoming years. Swift seems like a fantastic language and I've only started learning it. Feel free to create a pull request with future improvements. Please, document your contributions well, and clearly outline the benefits of the change. It's also very helpful to include the ideas behind changes. Here's a rough collection of ideas we might tackle next: - Networking Layer - Subscriptions - Caching PS.: PRs for the above features will be reviewed a lot more quickly! Thank you I want to dedicate this last secion to everyone who helped me along the way. - First, I would like to thank Dillon Kearns, the author of elm-graphql, who inspired me to write the library, and helped me understand the core principles behind his Elm version. - I would like to thank Peter Albert for giving me a chance to build this library, having faith that it's possible, and all the conversations that helped me push through the difficult parts of it. - Lastly, I'd like to thank Martijn Walraven and Apollo iOS team, who helped me understand how Apollo GraphQL works, and for the inspiration about the parts of the code I wasn't sure about. Thank you! 🙌 Licence MIT @ Matic Zavadlal Github You may find interesting Dependencies Used By Total: 0 Releases SwiftGraphQL 2.0.0-beta.1 - This version includes utility functions for mapping a Selection and numerous improvements to internal data handling. I've streamlined GraphQLResult structure so that it more accurately represents the return value. Field accessors may now fail to reflect the possibility of a bad payload. This is a huge improvement over the previous approach since we no longer trigger a fatal error whenever the data is corrupt, but instead throw a bad payload error. Additionally, we require that query selection is optional since it might fail. To prevent endless nullability wrappings, I've created a utility send function that wraps selection in nonNullOrFail selection. This is a breaking release. To prevent version pollution, I'll keep some of the upcoming changes in the prerelease tag until we fix all the small changes internally. SwiftGraphQL 1.1.2 - This release fixes the bug where nonNullOrFail selection would use mock data instead of throwing when data isn't there. SwiftGraphQL 1.1.1 - Fixes the bug where errors wasn't a public property of a result. SwiftGraphQL 1.1.0 - Ships utility functions for selecting nullable and list fields. Check the documentation for more information. SwiftGraphQL 1.0.0 - This is the first stable release of SwiftGraphQL library. I'll continue to publish fixes as we discover them in our projects, but feel free to use the library. I'll use semantic versioning from now on. Networking - This release contains methods that you can use to send network requests besides other improvements. RC2 - Includes bugfixes and improvements. RC1 - Possibly the first stable release of this library. Contains features like: - Object, Union, Interface selection; - Custom Scalars; - Automatic aliasing. 🎉
https://swiftpack.co/package/maticzav/swift-graphql
CC-MAIN-2020-50
refinedweb
3,311
60.01
IronRuby is an open-source implementation of the Ruby programming language which is tightly integrated with the .NET Framework. IronRuby can use the .NET Framework and Ruby libraries, and other .NET languages can use Ruby code just as easily. Download Ruby 1.1 1.1.3 released on 2011-3-13 release notes | source Try Ruby in the browser Quickly run Ruby code in your browser, without installing IronRuby. # namespaces are modules include System::Collections::Generic # indexers constrains type d = Dictionary[String, Fixnum].new # Ruby idioms just work d['Hello'] = 1 d['Hi'] = 2 # this gives a TypeError d[3] = 3 # Enumerable methods work d.each{|kvp| puts kvp} Experience a more interactive .NET and Ruby development experience with Ruby Tools for Visual Studio. - Why IronRuby? IronRuby is an excellent addition to the .NET Framework, providing Ruby developers with the power of the .NET framework. Existing .NET developers can also use IronRuby as a fast and expressive scripting language for embedding, testing, or writing a new application from scratch. The CLR is a great platform for creating programming languages, and the DLR makes it all the better for dynamic languages. Also, the .NET framework (base class library, presentation foundation, Silverlight, etc.) gives developers an amazing amount of functionality and power. Announcements March 13, 2011 IronRuby 1.1.3 is released. February 7, 2011 IronRuby 1.1.2 is released. October 21, 2010 IronRuby 1.1.1 is released. July 16, 2010 IronRuby 1.1 is released. April 12, 2010 IronRuby 1.0 is the first stable release of the Ruby programming language implementation for the .NET framework.
https://ironruby.net/
CC-MAIN-2019-18
refinedweb
267
53.47
import re str="x8f8dL:s://" str2=re.match("[a-zA-Z]*//([a-zA-Z]*)",str) print str2.group() current result=> error expected => wwwqqqzzz I want to extract the string "wwwqqqzzz" ,how i do that? May be there is a lot dots Such as "whatever..s#$@.d.:af//w" so basically i want the stuff bounded by // and / How do I acheive that. Additional question, import re str="xxx.yyy.xxx:80" m = re.search(r"([^:]*)", str) str2=m.group(0) print str2 str2=m.group(1) print str2 seems they are the same, group(0) group(1) match tries to match the entire string. Use search instead. The following pattern would then match your requirements: m = re.search(r"//([^/]*)", str) print m.group(1) Basically, we are looking for /, then consume as many non-slash characters as possible. And those non-slash characters will be captured in group number 1. In fact, there is a slightly more advanced technique that does the same, but does not require capturing (which is generally time-consuming). It uses a so-called lookbehind: m = re.search(r"(?<=//)[^/]*", str) print m.group() Lookarounds are not included in the actual match, hence the desired result. This (or any other reasonable regex solution) will not remove the .s immediately. But this can easily be done in a second step: m = re.search(r"(?<=//)[^/]*", str) host = m.group() cleanedHost = host.replace(".", "") That does not even require regular expressions. Of course, if you want to remove everything except for letters and digits (e.g. to turn into wwwregularexpressionsinfo) then you are better off using the regex version of replace: cleanedHost = re.sub(r"[^a-zA-Z0-9]+", "", host) output=re.findall("(?<=//)\w+.*(?=/)",str) final=re.sub(r"[^a-zA-Z0-9]+", "", output [0]) print final Similar Questions
http://ebanshi.cc/questions/2023087/python-regular-expression-match
CC-MAIN-2017-22
refinedweb
298
62.95