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 |
|---|---|---|---|---|---|
J
database table!");
Connection con = null;
String url = "jdbc:mysql... implementing class. Hi friend,
Example of JDBC Connection with Statement interface :
import java.sql.*;
public class InsertValues{
public static
JDBC - JDBC
JDBC i am goint to work on JDBC and i knew oracle but very poor... ILLUSTRATIONS to understand the way to do work in JDBC with syntaxes Hi... Connect Example.");
Connection conn = null;
String url = "jdbc:mysql
JDBC doesn't provide an EOF method.
JDBC doesn't provide an EOF method. How can I know when I reach the last record in a table, since JDBC doesn't provide an EOF method
jdbc - JDBC
Deletion Example");
Connection con = null;
String url = "jdbc:mysql://localhost...jdbc jdbc
Expert:Ramakrishna
Statement st1=con.createStatement... values from table;))
At a time you can do one work.
first time you can
install mysql - JDBC
install mysql i want to connect with mysql database.can i install mysql on local system
please send me link how download mysql Hi friend,
MySQL is open source database and you can download and install it on your
level can be set in JDBC. the method can accept any of the arguments listed below... work done after the savepoint. A save point is created using the method
main(String[]args){
try{
Connection con = null;
String url = "jdbc:mysql...();
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306
= DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "root...:
Retrieve Image using Java
jdbc - JDBC
= null;
String url = "jdbc:mysql://localhost:3306/";
String dbName....
Thanks
error - JDBC
();
}
}
}
i wrote any jdbc program .it won't work in my system. but it is complied
i... conn = null;
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String...; Hi friend,
Please add mysql connector jar file.
Read for
mysql jdbc connectivity
mysql jdbc connectivity i want to connect retrieve data from mysql using jdbc
Prepared statement JDBC MYSQL
Prepared statement JDBC MYSQL How to create a prepared statement in JDBC using MYSQL? Actually, I am looking for an example of prepared statement.
Selecting records using prepared statement in problem - JDBC
= "jdbc:mysql://localhost:3306/test";
Connection con=null;
try...mysql problem hai friends
please tell me how to store the videos in mysql
plese help me as soon as possible
thanks in advance
regarding jdbc - JDBC
").newInstance();
con = DriverManager.getConnection("jdbc:mysql:///test... on JDBC visit to :...("Successfully connected to MySQL server...");
} catch(Exception e
Introduction to the JDBC
MySQL JDBC DRIVERS - 100% pure java driver for MySQL...
Introduction to the JDBC
Introduction
This
article introduce you with JDBC and shows you how to our search
Features of JDBC 4.0
productivity. JDBC 4's key priority is to make
it easier for developers to work... doesn't
mean that a connection is closed. Now in JDBC 4 Connection class we... problem - JDBC
mysql problem
hai friends
i have some problem with image storing in mysql. i.e while i am using
image(blob) for insert the image it says... of creation of table in mysql. it will take any image and store in database.swing.
batch in jdbc
JDBC BATCH PROCESSING
In Batch processing, many queries work together as batch.
The following program include collective set of SQL queries...;url = "jdbc:mysql://192.168.10.13:3306/";
... for more information.
jdbc
jdbc Hai ,
Give a steps for jdbc connectivity
jdbc
jdbc display the records using index in jdbc
JDBC
JDBC why we use batch in jdbc
Jdbc Question
Jdbc Question Hi.
In Jdbc, if i am pointing to the database of some other machine, i mean instead of local-host i give the ip of that machine and that machine is shut down, Will my connection still work
timestamp - JDBC
timestamp Is there any timestamp for INSERT, UPDATE commands? If is there, when it will get effected? Hi friend,
Thanks
JDBC
JDBC How to add set of queries in a single query in JDBC
Working with Database through JDBC
Working with Database through JDBC
You can use JDBC to work with database. For this you
can write JDBC code in the action method
java - JDBC
java how to get connectoin to database server from mysql through java programme Hi Friend,
Please visit the following link for more detailed information
JDBC connection
JDBC connection ![alt text][1]I got exception in Connecting to a MySQL Database in Java.
The exception is ClassNotFoundException:com.mysql.jdbc.Driver
wat is the problem
Connecting to remote mysql server using jdbc.
Connecting to remote mysql server using jdbc. How to Connect to remote mysql server using jdbc
java - JDBC
for database connectivity:... have to use JDBC and oracle. plz send the details for connecting "java... sending data inserting code into database using JDBC with jsp define batch updates define batch updates?exp
JDBC... links:
Server DB connection - JDBC
also tried passing the 4th argument to the mysql_connect function but I can't get it to work.
If you have any sample code for getting connection please
JDBC, JAVA
JDBC, JAVA I want to develop a s/w that will work on a LAN, so is there any need for a server, bcoz I am using database to store information, and these information will be on LAN... JDBC Connectivity Code
in Java.
JDBC
Drive For Mysql... JDBC Drive for Mysql.
JDBC
Execute
Query
jdbc I can't run my jdbc program because it has error in this line:
public static void main(String[] args)
the error is:illegal static declaration in inner class
would you please let me whats the problem?
regards | http://www.roseindia.net/tutorialhelp/comment/22302 | CC-MAIN-2014-23 | refinedweb | 922 | 57.57 |
Two dimensional arrays and slices are useful for many situations. When creating an array in the Go programming language it is automatically initialized to the empty state, which is usually a 0. Arrays cannot be expanded. Arrays live in the stack and take up space in the compiled executable. Arrays are also passed by copy whereas slices pass pointers. Slices require a little more initialization at first but are more versatile. You can grab subsets of the arrays if needed, access elements directly, or expand the slices. Slices are thin wrappers around arrays and hold pointers to the array. They are initialized during run time and live in the heap.
Arrays
Try it in the Go Playground.
package main
import "fmt"
func main() {
// Initialize a 2D array
var grid [10][4]int
fmt.Println(grid)
// Another way to initialize 2D array
gridB := [6][3]int{}
fmt.Println(gridB)
}
Slices
Try it in the Go Playground.
package main
import "fmt"
func main() {
numRows := 10
// Initialize a ten length slice of empty slices
grid := make([][]int, numRows)
// Verify it is a slice of ten empty slices
fmt.Println(grid)
// Initialize those 10 empty slices
for i := 0; i < numRows; i++ {
grid[i] = make([]int, 4)
}
// grid is a 2d slice of ints with dimensions 10x4
fmt.Println(grid)
} | https://www.devdungeon.com/content/2d-arrays-and-slices-go | CC-MAIN-2021-04 | refinedweb | 216 | 66.33 |
This is post 2 of 3 in a blog series previewing the upcoming presentation, HTML5: The Parts You Care About by David Wesst at Prairie Dev Con in Saskatoon, SK (November 4-5). Read Part 1 here.
As discussed in my previous post, HTML5 has come a long way since its inception and release in the early 90’s. With eight different categories of functionality that are continuing to develop, expand, and evolve there are a lot of areas to cover.
But what can it really do? Given there are so many features to cover, there is no way to cover them all in a single post. What is doable, is to cover my favourite features in each of the core technologies: HTML Markup, CSS, and JavaScript.
HTML Markup
Since the beginning, the purpose of HTML has been to define the structure of the documents we intend to share with the web. That purpose continues with HTML5, but with some notable new and improved tags to better describe how we write documents today.
Being that I’m a sucker for a rich user interfaces and a big fan of video games, my favourite feature is the new HTML Canvas, with a close runner up on the (a.k.a Multimedia) tags.
Canvas
The HTML Canvas is just that, a blank canvas. With this element, the developer is in direct control over every pixel inside of the canvas, which means that the developer is responsible for handling everything from the graphics right through to the handling of clicks on the pixels.
For many this might sound like a bit of a nightmare considering that we are used to having things like controls (e.g. input elements) and event handlers to build our apps. But those controls, although limit us to what they provide. Having a clean slate, or in this case, a blank canvas, gives us the ability to make our apps and games look and act however we want them to.
Beyond the creativity aspects, there are performance aspects as well. When we use the Document Object Model (DOM) to deliver rich and engaging experiences, we need to write code the traverses the tree of elements and manipulates them. With the canvas, we don’t have to worry about the DOM because we are controlling everything on the canvas ourselves improving the performance (assuming we don’t write garbage code).
Here is an example of a simple canvas of a red box that the user can control and jump around with on the screen. You’ll notice that if you use your F12 Developer Tools that there are no elements inside of the canvas as our code is handling the creation and interaction of the red box.
Here is a link to the code.
Getting Started
Although drawing and managing every pixel on a screen can sound intimidating, there are plenty of tools out there to help you get started and to make your life a little bit easier. Here are a few resources to get you looking in the right places:
Notable HTML Mentions
As I mentioned earlier, there are too many features for me to go over in a single post, but here are a few more notable HTML-based features that I consider pretty amazing.
CSS Styling
Even though HTML is great on its own, when you give it some style, that is when it really pops. Cascading Style Sheets (CSS) give us more than just styling, but a great way of applying styling rules to our DOM. It even provided us with selector syntax which is easily one of the most useful features inside of the HTML space.
There are a ton of features inside of CSS that I could mention, but one really stands out as my favourite: Media Queries.
Media Queries
A Media Query is CSS code that allows a developer to write CSS code that is specific for media types and features. For example, if someone is viewing your app on a mobile device with a small screen, you can write styling rules that will only apply to mobile devices with a specific screen width.
This is a feature that has was around before HTML5, but has been enhanced with CSS3 (which is considered part of HTML5).
I would write my own example, but there are too many great ones already out there. Plus, I tend to use CSS and HTML frameworks that apply media queries, like Twitter Bootstrap. If you take a look below, you’ll see how the page looks different with different screen sizes.
As you can see, as the screen width gets smaller, the elements on screen change. Namely the placement and spacing around the KendoUI add, and the header navigation. This is the power that are Media Queries, a single code base, multi-device support.
Getting Started
The easiest way to get yourself started with Media Queries is to use a framework that supports them (such as Twitter Bootstrap). If you want to write your own, then here are a few other resources that can get you moving in the right direction.
Notable CSS Features
Media Queries are my favourite, but there are a number of CSS features that have been included in HTML5 that have made my web development life that much easier.
- Rounded Corners (a.k.a. Border Radius)
- Gradients
- Box Shadow
JavaScript
JavaScript has been the source of the real power in HTML apps since Netscape introduced it. With JavaScript being one of the core technologies that are considered in the HTML5 movement, there are a lot of great new features that make HTML a platform that can stand on its own.
Of all the HTML features that are included as enhancements to JavaScript, I think the best are related to providing data storage in one way or another. The one I believe to be the best is probably considered the simplest of the group: Web Storage.
Web Storage
Web Storage is pretty self-explanatory, as it is storage for the web. It works by adding two objects to the global namespace in JavaScript sessionStorage and localStorage that the developer can use key value pairs to store variables. The sessionStorage object provide storage for the user’s current session, while the localStorage object provides data storage that persists across sessions.
Here is an example (view the Github Gist):
The example is simple, but demonstrates methods in which you can use web storage. Instead of a simple text string from a textbox, you can store RGBA values for backgrounds, or base 64 encoded strings for data. You should note that the data is unsecured considering that this is stored on the client, so I would recommend against storing things like passwords and the like. Still, it is quite powerful and is definitely something that any HTML developer can leverage.
Getting Started
If the Gist isn’t enough, here are a few links to dive a bit deeper into Web Storage.
- Web Storage Tutorial at WebPlatform.org
- Overview of Client-Side Storage at WebPlatform.org
- W3C Web Storage Specification
Notable JavaScript Features
I think that the features added to JavaScript with the HTML5 movement is really what has brought HTML into the forefront and out of the browser in the past few years. Here are a couple (but definitely not all) of the coolest new JavaScript features that have come with HTML5.
Thanks for playing.
~ DW | https://blogs.msdn.microsoft.com/cdndevs/2013/10/24/html5-the-parts-you-care-about-part-2/ | CC-MAIN-2016-44 | refinedweb | 1,239 | 67.38 |
1
Hi everyone,
I have a modal dialog box which is called by the main thread. This dialog has no parent (appears at center screen, overlapped, and shown in taskbar). When the user clicks "Save" in the dialog, the dialog procedure receives the command and displays a save file dialog (GetSaveFileName).
The problem is that the second dialog (Save Dialog) doesn't work at all. It can't be activated, and seems kind of frozen (can't be closed, buttons and scroll bars are frozen). Here's my code:
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { DialogBox(hInstance, MAKEINTRESOURCE(101), NULL, DialogProc); MSG msg; while (GetMessage(&msg, NULL, 0, 0) != 0) { TranslateMessage(&msg); DispatchMessage(&msg); } return (int)msg.wParam; } INT_PTR CALLBACK DialogProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { HDC hdc; PAINTSTRUCT ps; switch (message) { case WM_COMMAND: switch(LOWORD(wParam)) { case IDSAVE: OPENFILENAME OFN; OFN.hwndOwner = hWnd; [...] //PROBLEM IS HERE. The save file dialog is half-frozen and never returns. if (GetSaveFileName(&OFN)) {[...]} break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return true; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); EndPaint(hWnd, &ps); break; case WM_INITDIALOG: [...] return true; case WM_CLOSE: [...] return true; case WM_DESTROY: [...] return true; default: return DefWindowProc(hWnd, message, wParam, lParam); } return false; }
Whatever dialog type I put at this line (print dialog, modal dialog, modeless dialog), it doesn't behave properly. What am I missing?
I tried with OFN.hwndOwner = NULL, but doesn't work.
Thanks in advance! | https://www.daniweb.com/programming/software-development/threads/221036/modal-dialogs-help | CC-MAIN-2018-13 | refinedweb | 245 | 59.09 |
On my to do list for many years has been getting my head round how Skulpt works. In case you haven’t come across it before, Skulpt is a small, client-side Javascript package that implements elements of Python in the browser. (Originally it only supported Python 2.7 syntax, but the master branch has now moved to supporting Python 3.7 syntax.)
My proximal reason for playing with it is that it is used in a Ev3devSim, a simple browser based robot simulator that I’m pretty sure we’re going to use in a course update. I’m itching to get back to tinkering with it, but as we’re on strike, I’m not going to until the strike action is over. This will make it hard to get it into the state I want it, and to develop the activities I’d like to create around it, by the time that they’re required to meet handover deadlines, but the strike action seems designed to cause stress and disruption to the strikers rather than the organisation we work for. Such is life. The collective decided and we’re out.
Although this is related to that, this blog has been languishing somewhat, lately, so before I forget for myself the small progress I made with tinkering with Skulpt, here’s a quick write-up.
The challenge I set myself was to create a simple text-to-speech function callable from an in-browser Skulpt Python environment that would convert a provided text string to speech using the SpeechSynthesis part of modern web browsers’ Web Speech API (this also defines a speech recognition API, which could offer some interesting accessibility directed possibilities…).
Calling the API from Javascript is straightforward enough: the
speechSynthesis.speak(new SpeechSynthesisUtterance(txt)) javascript call run in a browser will speak the provided text string aloud. To ensure that the text object is a string and not some other object type, we force it to a string type in a Skulpt context by calling it as
txt.$jsstr().
If we wrap this API call in a Javascript function, we can make it available by saving into a module file (such as
src/lib/playsound.js) with some boilerplate that identifies the file as a loadable module and defines the function(s) available within it.
// src/lib/playsound.js // // Define a Javascript function to do // whatever we want the Skulpt Python function to do... function say (obj) { speechSynthesis.speak(new SpeechSynthesisUtterance(obj.$jsstr())) } // Define the file as a Skulpt Python module var $builtinmodule = function(name) { var mod = {}; // Add the say function to the module mod.say = new Sk.builtin.func(function(obj){ say(obj); return new Sk.builtin.none; }) return mod; }
With node.js installed, run
npm run dist in the top level repo directory. A series of tests will be executed and copies of
skulpt.min.js and
skulpt-stdlib.js built into the Skulpt
dist folder. These files can then be loaded into a web page and used to power in-browser Python code execution.
The module can them be loaded into a Skulpt Python context and the text to speech function called as follows:
import playsound playsound.say('hello world')
In passing, I note that the forked version of Skulpt used in BlockPy supports other handy packages not in the base Skulpt distribution, including
matplotlib (
src/lib/matplotlib). I’m not sure how tightly this is bound into the BlockPy UI, or how straightforward a task it would be to be able to make use of it in an Ev3Dev context?
I also note that the
sqlite3 module seems to be unimplemented. Would it make sense to try to wrap
kripken/sql.js in a Skulpt
src/lib module, I wonder?
2 thoughts on “Simple Text to Speech With Skulpt”
Have you tried the Processing lib in Skulpt? I wrote the initial version many moons ago, and found quite enjoyable. I never had an opportunity to use it …. maybe now though, in the “real world”!
No, not tried that. I was really just looking for a simple, useful thing that I could do to prove to myself I could extend Skulpt if I have to. For Pyhton in the browser, I really should be looking Pyodide, I think… | https://blog.ouseful.info/2020/02/26/simple-text-to-speech-with-skulpt/ | CC-MAIN-2020-50 | refinedweb | 715 | 71.65 |
Opened 11 years ago
Closed 11 years ago
Last modified 10 years ago
#1399 closed enhancement (fixed)
[patch] [magic removal branch] Add 'template_model_name' to generic view list_detail.py
Description
the generic views currently in the Magic-removal branch reference the the object or objects with the keyword 'object' or 'object_list' represetivly. This makes the templates rendering the page more obscure.
Example:
{% if survey_list %} ... {% for survey in survey_list %} .... {% endfor %} .... {% endif %}
vs
{% if object_list %} ... {% for survey in object_list %} .... {% endfor %} .... {% endif %}
I propose adding a new parameter called 'template_model_name' to the generic view. This will enable templates to be far more elegant and intutive. I also feel this would make generic templates more 'Djangoified' ie I think it fits with Django philsophies on creating a amzingly simple to use and clean web development framework.
An Example of how this can be called in the URLConf is as follows:
!#python urlpatterns = patterns('', (r'^survey/(?P<object_id>\d+)/$', 'django.views.generic.list_detail.object_detail', {'queryset': Survey.objects.all(), 'template_model_name': 'survey'}), (r'^list/$', 'django.views.generic.list_detail.object_list', {'queryset': Survey.objects.all(), 'template_model_name': 'survey', 'template_name': 'survey/index'}) )
Please see the attach patch.
Notice that I have included the a default on the argument 'template_model_name' and set it to 'object'. This means this patch can go in and never effect any code which doesnt want to use it. It will only come into effect if you add the extra argument into the URLConf setup, else everything works as before.
A Patch to add 'template_model_name' to generic views | https://code.djangoproject.com/ticket/1399 | CC-MAIN-2016-50 | refinedweb | 249 | 51.34 |
To understand python closure, you should have the idea of nested function and python class. Actually python closure is also a function that provides the opportunity to encapsulate some data with code.
Table of Contents
- 1 Idea of Python Closure
Python nested function
def funcOut(): print("Now we are in funcOut.") def funcIn(): print("This function is defined inside the funcOut.\nThis one is called a nested Function.") print("Here we will call the funcIn that is defined.") funcIn() print("We are in _main_.\nCalling the funcOut.") funcOut()
In the above code
funcIn is nested function inside the
funcOut. If you look at the output of the above code then you will understand the calling sequence of the functions. The output will be:
We are in _main_. Calling the funcOut. Now we are in funcOut. Here we will call the funcIn that is defined. This function is defined inside the funcOut. This one is called a nested Function.
Turning the funcOut into a python closure
Say, you want to have all the functionalities that is done by the
funcIn from
funcOut.
How can you do this? What comes in your mind?
return right!!!
Normally we return a value or reference form a function. But here, we need to return the whole functionalities of
funcIn. If we just overwrite the function calling
funcIn() in line 6 by
return funcIn, then we have achieved what we want.
The thing that we have just done is known as closure in python. You will understand python closure more clearly as you go through the whole tutorial.
Idea of Python Closure
So, from the above we have learned that when a function returns another function defined in ( ie. nested function) it, it’s called a closure. Let’s now have a look on sample structure of a closure.
Python Closure Structure
def closureFunc(): def nestedFunc(): # ... statements ... print(" Welcome To Closure ") return nestedFunc get = closureFunc() get()
This will output:
Welcome To Closure
In the above code, as per the name of the function I hope you understand the outer function is the closure function, in which there is a nested function which is being returned by the closure function.
Python closure embeds data with code
When we create a object of a class, this object contain some information with it. Just like that closure embeds data with the code.
Let’s explore with an example code
def closureFunc(n): def nestedFunc(): # ... statements .. print("Welcome To Closure ") print("You have sent argument %d + 10 = %d" % (n, n+10)) return nestedFunc getting = closureFunc(12) getting()
This will output:
Welcome To Closure You have sent argument 12 + 10 = 22
Notice line 7 and 8 –
getting variable is now working as a function. All the functionalities of the inner function of nested function is now being done by it.
Python Closure remembers its context
Look at the following code, we have deleted the
closureFunc.
def closureFunc(sum): def nestedFunc(): # ... statements .. print("Welcome To Closure ") print("You have sent argument %s" % sum) return nestedFunc getting = closureFunc(12) del closureFunc getting()
This will output:
Welcome To Closure You have sent argument 12
This is the power of closure. Even if you delete the closure function the
getting remember its context where it was and what it does. That’s why we got the output of
getting even after deleting the actual function.
Use of nonlocal variable in closures
Let’s have a look to another example. The following closure adds up all the number upto a certain range which is given as argument to the closure function.
def closureFunc(up): val = 0 def nestedFunc(): nonlocal val print("Welcome To Closure ") for i in range(up+1): val += i print("Total is = %d" % val) return nestedFunc getting = closureFunc(5) getting()
This will output:
Welcome To Closure Total is = 15
Notice that we have taken a variable val in the closureFunc and reuse it in the
nestedFunc declaring as a nonlocal to this function using the keyword
nonlocal.
If you do not declare as nonlocal then you will get error that local variable ‘val‘ referenced before assignment, that means it will be considered as a local variable to the
nestedFunc function .
Closure with argument
Let’s have a look at the last example of this tutorial. In this code we want to provide argument to the nestedFunc. And observe the output for different value.
def closureFunc(up): val = 0 def nestedFunc(arg): nonlocal val print("Welcome To Closure ") for i in range(up+1): val += i val *= arg print("Total is = %d" % val) return nestedFunc retFunc = closureFunc(5) retFunc(10) retFunc(4)
Below image shows the output of above python closure program.
If you can understand why the second output is 660 then I must say you have gained knowledge from this tutorial.
The output is 660 because, when line 11 executes, variable up=5 is set.
Then when line 12 executes,
nestedFunc executes and variable val=150 is set.
After that when we again call the function with different argument 4 in line 13, then the closureFunc is having up=5, val=150. So in the for loop val is updated by 150 plus summation of 1 to 5 that equals 150+15 = 165. Then multiply it with 4 which equals 660. That’s it. This is what python closure is. Hope this tutorial is helpful for you. Best of luck coding with closure.
__closure__
All function objects have a
__closure__ tuple attribute that returns cell objects if it is a closure function.
def closureFunc(up): val = 0 def nestedFunc(arg): nonlocal val print("Welcome To Closure ") for i in range(up + 1): val += i val *= arg print("Total is = %d" % val) return nestedFunc retFunc = closureFunc(5) print(retFunc.__closure__) print(retFunc.__closure__[0].cell_contents) print(retFunc.__closure__[1].cell_contents) retFunc(10) print(retFunc.__closure__) print(retFunc.__closure__[0].cell_contents) print(retFunc.__closure__[1].cell_contents) retFunc(4) print(retFunc.__closure__) print(retFunc.__closure__[0].cell_contents) print(retFunc.__closure__[1].cell_contents)
It will produce following output now and closure context values up and val are also getting printed.
(<cell at 0x10079f288: int object at 0x10028ba80>, <cell at 0x101033618: int object at 0x10028b9e0>) 5 0 Welcome To Closure Total is = 150 (<cell at 0x10079f288: int object at 0x10028ba80>, <cell at 0x101033618: int object at 0x10028cca0>) 5 150 Welcome To Closure Total is = 660 (<cell at 0x10079f288: int object at 0x10028ba80>, <cell at 0x101033618: int object at 0x1007eae70>) 5 660
Python closure is a good to know feature but it gets complicated if we have more inner functions and arguments. You can achieve the same thing with classes and normal functions. So use python closure with caution.
Reference: StackOverflow question | https://www.journaldev.com/14961/python-closure | CC-MAIN-2019-39 | refinedweb | 1,114 | 63.8 |
//#define DEBUG#define FILTER_AMOUNT 7// Timeout is in microseconds#define ANALOGUE_INPUT_CHANGE_TIMEOUT 250000// Contains the current value of the analogue inputs.int analogueInputs[6];// Variable to hold temporary analogue values, used for analogue filtering logic.int tempAnalogueInput;// for loopint i = 0;// Variable to hold difference between current and new analogue input values.int analogueDiff = 0;// This is used as a flag to indicate that an analogue input is changing.boolean analogueInputChanging[6];// Time the analogue input was last movedunsigned long analogueInputTimer[6];void setup(){ Serial.begin(31250); // Initialise each analogue input channel. for (i = 0; i < 1; i++) { // Set the pin direction to input. pinMode(i, INPUT); // Initialise the analogue value with a read to the input pin. analogueInputs[i] = analogRead(i); #ifdef DEBUG Serial.print("read in setup: "); Serial.println(analogueInputs[i]); #endif // Assume no analogue inputs are active analogueInputChanging[i] = false; analogueInputTimer[i] = 0; } }void loop(){ /* * Analogue input logic: * The Arduino uses a 10-bit (0-1023) analogue to digital converter (ADC) on each of its analogue inputs. * The ADC isn't very high resolution, so if a pot is in a position such that the output voltage is 'between' * what it can detect (say 2.505V or about 512.5 on a scale of 0-1023) then the value read will constantly * fluctuate between two integers (in this case 512 and 513). * * If we're simply looking for a change in the analogue input value like in the digital case above, then * there will be cases where the value is always changing, even though the physical input isn't being moved. * This will in turn send out a constant stream of MIDI messages to the connected software which may be problematic. * * To combat this, we require that the analogue input value must change by a certain threshold amount before * we register that it is actually changing. This is good in avoiding a constantly fluctuating value, but has * the negative effect of a reduced input resolution. For example if the threshold amount was 2 and we slowly moved * a slider through it's full range, we would only detect every second value as a change, in effect reducing the * already small 7-bit MIDI value to a 6-bit MIDI value. * * To get around this problem but still use the threshold logic, a timer is used. Initially the analogue input * must exceed the threshold to be detected as an input. Once this occurs, we then read every value coming from the * analogue input (not just those exceeding a threshold) giving us full 7-bit resolution. At the same time the * timer is started. This timer is used to keep track of whether an input hasn't been moved for a certain time * period. If it has been moved, the timer is restarted. If no movement occurs the timer is just left to run. When * the timer expires the analogue input is assumed to be no longer moving. Subsequent movements must exceed the * threshold amount. */ for (i = 0; i < 1; i++) { // Read the analogue input pin, dividing it by 8 so the 10-bit ADC value (0-1023) is converted to a 7-bit MIDI value (0-127). tempAnalogueInput = analogRead(i); #ifdef DEBUG Serial.print("read in loop: "); Serial.println(tempAnalogueInput); #endif // Take the absolute value of the difference between the curent and new values analogueDiff = abs(tempAnalogueInput - analogueInputs[i]); #ifdef DEBUG Serial.print("difference: "); Serial.println(analogueDiff); Serial.print("\n"); delay(2000); #endif // Only continue if the threshold was exceeded, or the input was already changing if ((analogueDiff > 0 && analogueInputChanging[i] == true) || analogueDiff >= FILTER_AMOUNT) { // Only restart the timer if we're sure the input isn't 'between' a value // ie. It's moved more than FILTER_AMOUNT if (analogueInputChanging[i] == false || analogueDiff >= FILTER_AMOUNT) { // Reset the last time the input was moved analogueInputTimer[i] = micros(); // The analogue input is moving analogueInputChanging[i] = true; } else if (micros() - analogueInputTimer[i] > ANALOGUE_INPUT_CHANGE_TIMEOUT) { analogueInputChanging[i] = false; } // Only send data if we know the analogue input is moving if (analogueInputChanging[i] == true) { // Record the new analogue value analogueInputs[i] = tempAnalogueInput; #ifdef DEBUG Serial.print("Value to send: "); Serial.println(analogueInputs[i]/8); #endif // Send the analogue value out on the general MIDI CC (see definitions at beginning of this file) controlChange(177, 21+i, analogueInputs[i]/8); } } } }// Send a MIDI control change messagevoid controlChange(int channel, int control, int value){ Serial.print(channel, BYTE); Serial.print(control, BYTE); Serial.print(value, BYTE);}
//current reading from potint sendval[2] = {0, 0};//previous reading from potint last[2] = {0, 0};//difference between current and previous readingint diff[2] = {0, 0};//for loop variableint i = 0;void setup() { Serial.begin(31250); }void loop() { for (i=0; i<1; i++) { sendval[i]=analogRead(i); diff[i]=abs(sendval[i]-last[i]); if ( (sendval[i]/8 != last[i]/8 ) && (diff[i]>7) ) { //Serial.println(sendval[i]/8, DEC); midiCC(177, 21, sendval[i]/8); // update last variable last[i] = sendval[i]; } } }// this function sends a Midi CC. void midiCC(char CC_data, char c_num, char c_val){ Serial.print(CC_data, BYTE); Serial.print(c_num, BYTE); Serial.print(c_val, BYTE);}
it reads different values like
we are talking about ONE pot whole time by the way
removed the MIDI cables from it and connected it to TX pin on the board)
Quoteremoved the MIDI cables from it and connected it to TX pin on the board)You can't do this it will not work. MIDI is a current loop interface and the TX pin is a TTL voltage interface. You need some hardware to convert the two, something like his:-
Please enter a valid email to subscribe
We need to confirm your email address.
To complete the subscription, please click the link in the
Thank you for subscribing!
Arduino
via Egeo 16
Torino, 10131
Italy | http://forum.arduino.cc/index.php?topic=64766.msg472678 | CC-MAIN-2015-18 | refinedweb | 962 | 54.52 |
IRC log of ws-ra on 2009-09-22
Timestamps are in UTC.
19:22:09 [RRSAgent]
RRSAgent has joined #ws-ra
19:22:09 [RRSAgent]
logging to
19:22:11 [trackbot]
RRSAgent, make logs public
19:22:11 [Zakim]
Zakim has joined #ws-ra
19:22:13 [trackbot]
Zakim, this will be WSRA
19:22:13 [Zakim]
ok, trackbot; I see WS_WSRA()3:30PM scheduled to start in 8 minutes
19:22:14 [trackbot]
Meeting: Web Services Resource Access Working Group Teleconference
19:22:14 [trackbot]
Date: 22 September 2009
19:22:31 [Yves]
Agenda:
19:24:53 [li]
li has joined #ws-ra
19:25:46 [Zakim]
WS_WSRA()3:30PM has now started
19:25:53 [Zakim]
+li
19:26:01 [Zakim]
+[Microsoft]
19:26:49 [Bob]
Bob has joined #ws-ra
19:27:01 [Zakim]
+ +039331574aaaa
19:27:08 [Bob]
trackbot, start telecon
19:27:10 [trackbot]
RRSAgent, make logs public
19:27:12 [trackbot]
Zakim, this will be WSRA
19:27:12 [Zakim]
ok, trackbot, I see WS_WSRA()3:30PM already started
19:27:13 [trackbot]
Meeting: Web Services Resource Access Working Group Teleconference
19:27:13 [trackbot]
Date: 22 September 2009
19:27:40 [Zakim]
+Bob_Freund
19:29:02 [dug]
dug has joined #ws-ra
19:29:10 [Zakim]
+Doug_Davis
19:29:17 [Zakim]
+gpilz
19:29:39 [asoldano]
Hi there
19:30:17 [Tom_Rutt]
Tom_Rutt has joined #ws-ra
19:30:33 [Bob]
chair: Bob Freund
19:30:45 [Zakim]
+Tom_Rutt
19:31:09 [Zakim]
+[Microsoft.a]
19:31:34 [Zakim]
+ +1.571.262.aabb
19:32:00 [fmaciel]
fmaciel has joined #ws-ra
19:32:02 [Ram]
Ram has joined #ws-ra
19:32:03 [Zakim]
+ +0208234aacc
19:32:12 [Vikas]
Vikas has joined #ws-ra
19:32:37 [Zakim]
+ +1.408.970.aadd
19:32:44 [dug]
zakim who is making noise?
19:32:57 [Katy]
Katy has joined #ws-ra
19:33:03 [Zakim]
+Yves
19:33:15 [Bob]
zakim ses nobody making noise now that they have muted
19:33:55 [dug]
zakim, who is making noise?
19:34:07 [Zakim]
dug, listening for 11 seconds I heard sound from the following: Bob_Freund (59%), +1.571.262.aabb (46%)
19:34:26 [dug]
tons of static Vikas
19:34:45 [Zakim]
+??P11
19:34:47 [Vikas]
Muted
19:36:01 [Bob]
agenda:
19:37:00 [DaveS]
DaveS has joined #ws-ra
19:37:19 [Bob]
scribe: Li Li
19:37:29 [Bob]
scribenick: LI
19:37:50 [asoldano]
yes, I'm here
19:38:17 [asoldano]
Bob, I'm on the phone
19:38:27 [dug]
Alessio, are you muted?
19:38:32 [asoldano]
perhaps I'm muted, let me check
19:38:45 [dug]
mary had a little lamb...
19:39:31 [Bob]
Alessio, there is an audio issue, we can't hear you
19:39:35 [asoldano]
I tried 60#
19:39:40 [asoldano]
but I think I'm still muted
19:39:48 [asoldano]
039 is Italy, yes
19:39:49 [asoldano]
sure
19:39:52 [asoldano]
I can here you
19:40:24 [dug]
zakim, umute asoldano
19:40:24 [Zakim]
I don't understand 'umute asoldano', dug
19:40:29 [asir]
asir has joined #ws-ra
19:40:33 [dug]
zakim, unmute asoldano
19:40:33 [Zakim]
sorry, dug, I do not know which phone connection belongs to asoldano
19:41:03 [asoldano]
OK, let me try to redial
19:41:08 [Zakim]
- +039331574aaaa
19:41:25 [gpilz]
that's ok, most of us only communicate unidirectionally in any case
19:41:27 [li]
TOPIC: agenda
19:41:30 [dug]
LOL
19:41:38 [li]
agenda agreed
19:41:40 [Zakim]
+ +039331574aaee
19:41:52 [li]
TOPIC: approval of minutes
19:42:18 [li]
bob: minutes approved
19:42:27 [li]
TOPIC: f2f next week
19:42:31 [Zakim]
- +039331574aaee
19:42:47 [Bob]
19:43:19 [li]
bob: complete it by tomorrow
19:43:41 [Ram]
q+
19:43:56 [li]
bob: discuss next f2f in santa clara
19:44:06 [Bob]
ack ram
19:44:29 [asoldano]
sorry, I've phone issues, joining again in few sec
19:44:46 [li]
ram: publishe fpwd by friday?
19:44:55 [li]
yves: will try
19:45:42 [li]
TOPIC: schedule
19:45:43 [Zakim]
+ +039331574aaff
19:46:44 [dug]
q+
19:46:49 [li]
TOPIC: AI reviews
19:46:57 [Bob]
ack dug
19:47:07 [li]
bob: anything can't be done by next f2f?
19:47:45 [asir]
q+
19:48:01 [Katy]
q+
19:48:04 [Bob]
ack asir
19:48:38 [li]
asir: ask dug if it's possible to send out proposal this week
19:48:42 [li]
dug: i think so
19:49:16 [Zakim]
+ +0759029aagg
19:49:21 [Zakim]
-??P11
19:49:32 [li]
asir: ai 94 is being worked on by me, we'll take over ai from geoff
19:49:36 [Bob]
ack katy
19:50:12 [li]
katy: 61
19:50:22 [li]
TOPIC: ws-frag
19:50:51 [Yves]
dug, mail sent (re AI on x-links)
19:50:57 [dug]
thanks
19:51:18 [li]
ram: details not ready for f2f
19:51:48 [li]
ram: by the end of this week
19:52:07 [li]
TOPIC:
19:53:07 [li]
issue opened
19:53:37 [li]
bob: any objection to the proposal in the issue?
19:54:07 [li]
ram: looks fine
19:54:13 [asoldano]
fine to me
19:54:34 [li]
bob: no objection and resolved as proposed
19:54:56 [li]
TOPIC:
19:56:33 [li]
yves: iri is not used in xml namespace, as pointed out by asir
19:56:37 [dug]
q+
19:56:53 [Bob]
proposal is to use IRI for everything but namespaces
19:56:54 [li]
bob: use iri in everything except namespace?
19:57:03 [Bob]
ack dug
19:57:37 [li]
dug: ws-a bounced between IRI and URI
19:57:58 [li]
...concrete strings are URI but generic ones are IRI
19:58:09 [li]
...what is the pattern for us?
19:58:43 [li]
bob: use IRI for everything but namespace and literal strings
19:58:46 [asir]
q+
19:58:59 [Bob]
ack asir
19:59:24 [li]
asir: URI is also IRI, we can do a global replacement
19:59:33 [li]
dug: i'm still confused
19:59:57 [li]
dug: why the exception?
20:00:36 [dug]
The working group intends to update the value of the Web Services Eventing namespace URI each...
20:00:51 [li]
bob: use IRI to permit localization
20:01:14 [li]
...otherwise we stick to URI
20:02:03 [li]
dug: namespace URI -> URI, so it's not global change
20:02:48 [li]
asir: someone needs to make a line-by-line change
20:04:00 [li]
bob: we have to give either detail changes or instructions to editors
20:04:04 [gpilz]
q+
20:04:15 [li]
dug: i like line-by-line changes
20:04:16 [Yves]
I can do this on friday
20:04:20 [Bob]
ack gpil
20:05:16 [li]
bob: prefer line-by-line changes
20:05:41 [Yves]
ACTION: Yves to produce a line-by-line diff for issue 7426
20:05:41 [trackbot]
Created ACTION-105 - Produce a line-by-line diff for issue 7426 [on Yves Lafon - due 2009-09-29].
20:05:51 [li]
thanks
20:06:29 [li]
TOPIC:
20:06:39 [Bob]
proposal at
20:06:52 [dug]
zakim, who is making noise?
20:07:08 [dug]
ah, sorry, didn't know it was you gil :-)
20:07:12 [Zakim]
dug, listening for 17 seconds I heard sound from the following: Bob_Freund (2%), gpilz (97%)
20:07:20 [li]
gil: explain the proposal
20:09:34 [li]
...it is about negotiating durations
20:09:41 [DaveS]
q+
20:09:50 [li]
...it's simple and efficient
20:10:06 [Bob]
ack dave
20:10:37 [li]
daves: subcription is cut down to yes/no
20:11:02 [li]
...more intelligent source can put hint in the response
20:11:27 [li]
...how to make response clear
20:11:31 [Ram]
q+
20:11:42 [Bob]
ack ram
20:12:18 [li]
ram: proposal is technical correct, but compatibility is an issue
20:12:48 [gpilz]
q+
20:13:03 [li]
...developers should code against failures
20:13:59 [li]
...subscriber should be able to negotiate in different situations
20:14:59 [DaveS]
q+
20:15:00 [dug]
q+
20:15:32 [li]
...we need to provide right guidance to developers
20:15:50 [Bob]
ack gpi
20:15:55 [li]
...this proposal doesn't help with practical issues
20:16:11 [asir]
[Gil's voice is not clear on the phone
20:16:20 [Ram]
Gil: Your voice quality is not audible.
20:17:18 [asoldano]
the same here unfortunately
20:17:28 [li]
gil: in system integration, event sink needs to count on event source
20:18:11 [dug]
q-
20:18:26 [Bob]
ack dave
20:18:29 [li]
...[not audible]
20:19:09 [li]
daves: incompatibilty 1: failure to provde feedback
20:19:21 [dug]
q+
20:19:47 [li]
incompatibilty 2: provide feedback in failure
20:20:14 [li]
...3: complicated protocol and policy
20:20:37 [li]
...gil's is in the middle ground
20:20:55 [Ram]
q+
20:21:07 [li]
...optional framework for policy later on?
20:21:15 [Bob]
ack ram
20:21:28 [gpilz]
q+
20:21:40 [li]
ram: need to deal with device comp. issue
20:22:31 [li]
...feedback from users on back comp. issues
20:23:32 [li]
ram: is not back comp. issue, rather to avoid mistakes by developers
20:23:43 [li]
bob: specific changes?
20:24:18 [li]
ram: i sent some response today, event source should decide duration,
20:24:21 [DaveS]
q+
20:24:59 [Bob]
ack dug
20:25:01 [li]
...i can live with subscriber having an option to indicate hint
20:25:16 [Ram]
q+
20:25:34 [li]
dug: there are cases subscriber can indicate a hint or not a hint
20:26:10 [li]
...can we have both, instead of just one?
20:26:44 [dug]
bob I'd like to respond to what he just said
20:26:51 [gpilz]
go ahead
20:26:57 [li]
ram: you are optimizing protocol to avoid unsubscribe
20:27:05 [DaveS]
q-
20:27:17 [Bob]
ack ram
20:27:20 [li]
...what is broken?
20:27:33 [li]
gil: yield to dug
20:28:19 [li]
dug: lightweight situation can create/delete subscription at will,
20:28:32 [li]
but other situation this is expensive
20:29:01 [li]
...so we need to indicate "i really want"
20:29:01 [Bob]
ack gp
20:29:27 [li]
gil: device and enterprise people are talking across..
20:29:40 [DaveS]
q+
20:30:12 [li]
...we need to support both cases
20:30:14 [Bob]
ack dave
20:30:23 [Ram]
q+
20:31:43 [li]
daves: gil's proposal covers ram's concern by not puting duration in request
20:31:59 [Bob]
ack ram
20:32:11 [gpilz]
A Subscriber MAY indicate that it is willing to accept a Subscription with any expiration time by omitting this element from the Subscribe request.
20:32:20 [li]
ram: we're making leap of faith...
20:32:42 [gpilz]
(the above is a part of the description of the optional /wse:Expirese element)
20:32:47 [gpilz]
q+
20:33:08 [DaveS]
Ohh!?
20:33:31 [DaveS]
Ooops I sat on the keyboard.
20:33:34 [dug]
LOL
20:33:39 [li]
...flexiblity is needed to interop
20:33:52 [li]
...let's talk more usecases in the f2f
20:34:12 [dug]
q+
20:34:22 [li]
...i'd like to know what is your use cases...
20:34:57 [li]
..we shouldn't loose interop between device and enterprise worlds
20:35:22 [li]
...what's wrong with current spec?
20:35:44 [Bob]
ack gpi
20:35:53 [Bob]
Asir, I hear hin well
20:36:28 [dug]
there's also no guarantee that Renew will be accepted later on
20:36:29 [li]
gil: hint doesn't provide value to sink, if the time is cut off
20:36:33 [asir]
we have difficulty hearing there is a lot of background noise
20:37:03 [DaveS]
Dave agrees with Gil. A hint is the same as providing no duration at all.
20:37:29 [Bob]
ack gpi
20:37:29 [li]
...[in audible mostly]
20:37:39 [Bob]
ack dug
20:38:08 [li]
dug: 2 issue with current spec: 1 cost of unsubscribe, 2 no guarantee on renew
20:38:40 [Ram]
q+
20:38:46 [gpilz]
katy what number do you use to dial into W3C?
20:38:56 [li]
...why isn't your requirement not supported by proposal
20:39:11 [li]
ram: i have the same question to dug
20:39:28 [dug]
q+
20:40:17 [li]
...current spec is not burdening event source.
20:40:30 [Katy]
Gil - number is +441173706152
20:40:40 [li]
...current spec works in many different environments
20:40:46 [Bob]
ack dug
20:40:48 [Bob]
ack ram
20:41:02 [li]
dug: which use cases are not supported?
20:41:19 [li]
ram: i'm lost at what you try to solve
20:41:48 [li]
dug: what use case not supported
20:42:20 [li]
ram: not about technical content of proposal
20:42:38 [li]
...but on what's goal of the proposal
20:42:54 [li]
bob: how would you modify it?
20:43:23 [li]
ram: i'll take another stab at it
20:43:43 [li]
bob: it's about deployment, correct?
20:43:47 [DaveS]
q+
20:43:59 [li]
bob: which line should be modified?
20:44:40 [li]
ram: though technically sound, but it doesn't help me
20:44:59 [li]
bob: what part cause you problem?
20:45:46 [li]
ram: client having two options is a problem
20:46:44 [dug]
q+
20:46:51 [li]
ram: having two parties making decision is difficult to code
20:47:12 [Bob]
ack dave
20:47:16 [li]
ram: i'm having problem with duality
20:47:53 [Zakim]
+ +01831332aahh
20:48:11 [Ram]
q+
20:48:12 [li]
daves: proposal puts both subscriber and source in the driver seats
20:48:23 [dug]
bob - ram can go first to answer dave
20:48:34 [dug]
it might make my question moot
20:48:41 [Bob]
ack ram
20:49:43 [li]
ram: giving dualities is a problem for developers
20:50:30 [gpilz]
q+
20:51:12 [li]
ram: cause developers to misuse API instead of coding with interactions
20:51:42 [li]
dug: all elements in subscribe are optional
20:52:09 [li]
...why this one expiry is different from the others?
20:52:26 [li]
...while all others can fault when not satisfied
20:52:36 [Bob]
ack dug
20:53:00 [li]
ram: but there is negotiation between subscriber and source
20:53:23 [Ram]
Ram has joined #ws-ra
20:53:40 [li]
bob: why is it different from unsupported filter
20:53:45 [dug]
q+
20:53:56 [li]
ram: others are black and white, this one is not
20:54:39 [li]
dug: please explain why they are different
20:55:23 [li]
ram: something negotiable whereas other are not
20:55:36 [DaveS]
q+
20:55:50 [DaveS]
q-
20:56:06 [Bob]
ack gp
20:56:12 [li]
...current spec is flexible and interop
20:56:15 [Zakim]
- +039331574aaff
20:56:44 [li]
gil: where can we go, if nothing can be modified?
20:57:24 [li]
bob: strong objection?
20:57:29 [Zakim]
-gpilz
20:57:32 [li]
ram: need more time
20:57:46 [li]
bob: it's long enough
20:58:12 [li]
asir: we should not close it now
20:58:54 [li]
bob: i asked many different ways
20:59:08 [li]
asir: we need to work with oracle
20:59:24 [li]
bob: what's wrong?
20:59:40 [li]
bob: we're not progressing
20:59:46 [DaveS]
I really would like specfics before allowing more time.
20:59:59 [dug]
I agree with Bob - I'm still confused as to what's wrong with the proposal
21:00:01 [li]
ram: let's spend time in f2f
21:00:19 [DaveS]
What is broken and I am happy to see more time.
21:00:45 [li]
bob: let's focuses on specifics
21:00:57 [li]
s/focuses/focus/
21:01:21 [li]
bob: objection or acceptance
21:01:31 [li]
ram: will work on it
21:02:04 [li]
bob: action to ram to work on the proposals
21:02:42 [li]
ACTION: ram to work on proposal for the issue
21:02:42 [trackbot]
Created ACTION-106 - Work on proposal for the issue [on Ram Jeyaraman - due 2009-09-29].
21:03:04 [Zakim]
- +0759029aagg
21:03:14 [Zakim]
- +1.408.970.aadd
21:03:15 [Zakim]
-[Microsoft]
21:03:15 [Zakim]
- +1.571.262.aabb
21:03:16 [Zakim]
-Yves
21:03:16 [Zakim]
-[Microsoft.a]
21:03:16 [Zakim]
-Bob_Freund
21:03:17 [Zakim]
-Doug_Davis
21:03:20 [Zakim]
-li
21:03:25 [Zakim]
-Tom_Rutt
21:03:30 [RRSAgent]
I have made the request to generate
Yves
21:07:32 [gpilz]
gpilz has left #ws-ra
21:07:41 [Zakim]
- +01831332aahh
21:08:07 [Zakim]
- +0208234aacc
21:08:09 [Zakim]
WS_WSRA()3:30PM has ended
21:08:10 [Zakim]
Attendees were li, [Microsoft], +039331574aaaa, Bob_Freund, Doug_Davis, gpilz, Tom_Rutt, +1.571.262.aabb, +0208234aacc, +1.408.970.aadd, Yves, +039331574aaee, +039331574aaff,
21:08:13 [Zakim]
... +0759029aagg, +01831332aahh
21:37:54 [dug]
dug has joined #ws-ra
21:37:58 [dug]
yves?
23:26:12 [Zakim]
Zakim has left #ws-ra | http://www.w3.org/2009/09/22-ws-ra-irc | CC-MAIN-2015-40 | refinedweb | 3,032 | 71.28 |
howdy,
this code is an atempt to get user input and check to make sure it is the correct type.
#include <iostream.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <typeinfo>
float ftoi();
int main()
{
float ts;
// ftoi();
ts = ftoi();
cout <<"ts = " <<ts<<"\n";
cout <<"ts doubled = "<<ts*2<<"\n";
}
float ftoi()
{
//the first thing is to convert from feet to inches
system ("clear");
int feet = 0; //set feet to zero
double inches = 0; //set inches to zero
double total_span = 0;
char t;
cout <<"Enter FEET of bridge span: "; //whole feet of bridge span
cin >> feet;
t = feet;
if (typeid(t).name() != "int"){
//cout<<"You must enter feet as a digit\n";
cin>>feet;
}
cout <<"\nEnter INCHES with fraction(ie 6.38)of bridge span: "; //inches span
cin >> inches;
feet = feet*12; //convert feet to inches
total_span = feet + inches; //add feet & inches
cout <<"\nThe Total span is "<<total_span<<" inches\n";
return total_span;
}
the "typeid(t).name()" thing seems to catch the char types however it just falls through and exits.
what is a better way of checking user input for correct type.
Thanks
M.R. | http://cboard.cprogramming.com/cplusplus-programming/7639-checking-user-input-type.html | CC-MAIN-2014-10 | refinedweb | 188 | 69.41 |
Exam 190805 study material Made available by CertsKing.com
Free 190805 Exam Preparation Questions Exam 190805 : Using Web Services in IBM Lotus Domino 8 Applications
For Latest 190805 Exam Questions and study guides visit
Question: 1 Sofie has created a LotusScript Domino Web service. She can compile successfully, and she can generate WSDL that appears to be correct. But the Web service is not returning the expected values. Sofie is considering adding messagebox statements within the Web service code in an attempt to help debug. Will messagebox statements return any output that she can examine? A. No. Messagebox statements are front end calls. A messagebox statement in a back end routine will result in an abend. B. Yes. Messagebox statements within a LotusScript Web service are returned to the Web service consumer as WS_FAULT String values. C. Yes. Messagebox statements within a LotusScript Web service will write output to the server log. Sofie can browse the log to see these messages. D. No. Messagebox statements only display to UI. Since a Web service executes in the back end, the messagebox statements are ignored and produce no output. Answer: C Question: 2 Donnie wants to write a LotusScript Web service method what returns an array of Strings. Which one of the following Function definitions will do this? A. Function getArray() As String() B. Function getArray() List As String C. Function getArray() As XSD_STRINGARRAY D. Function getArray() As STRINGARRAY_HOLDER Answer: D Question: 3 Question: 4 Liz wrote a LotusScript Web service method with the following structure: Public Function lookupPersonInfo (personName As String) As PersonInfo '** do the lookup, return the information in our custom PersonInfo data typeEnd Function PersonInfo is a complex data type that is used to return various pieces of information in a single object. How does Liz need to define this complex data type in her LotusScript Web service code? A. As a separate Public class B. As a separate Private class C. As a custom LotusScript Type D. As a Private Function called PersonInfo_Type within the class that defines the Web service Answer: A Question: 5 Chuck has the following class defined as a complex data type in his LotusScript Web service: Public Class PersonInfo Public FirstName As String Public LastName As String PhoneNumber As String Private Email As String Public Function FullName () As String FullName = FirstName + " " + LastName End Function End Class What properties of that complex data type will be visible to a consumer of this Web service? A. FirstName and LastName B. FirstName, LastName, and FullName C. FirstName, LastName, and PhoneNumber D. FirstName, LastName, PhoneNumber, and Email Answer: C Question: 6 Nils is developing a Domino Web service to return employee data. The Web service will accept an employee name, and return the ID, phone number, and salary of the employee. Nils had started to code a separate public function to return each of these data items, but is wondering if he can create a Web service that will accept the employee name and return all 3 desired fields at once. Can he do this in Domino? Why or why not? For Latest 190805 Exam Questions and study guides visit
A. Yes. Nils can code a public sub with 4 parameters: one input parameter and three inout parameters. B. Yes. Nils can code a public function with 4 parameters: one input parameter and three output parameters. C. No. Domino Web services must include a public class. That class may include functions and subs, but subs cannot return values, so Nils must use functions. D. No. Domino Web services must include a public class, and that public class must expose a public function for each defined operation. Each function returns a Answer: A Question: 7 Collin is writing a Domino Web service to provide product inventory information. What signature of the getQuantity function in his Web service would result in this WSDLbeing part of the associated WSDL document? <wsdl:message <wsdl:part </wsdl:message>: <wsdl:operation <wsdl:input<wsdl:output</wsdl:operation> A. Private Function GETQUANTITY( PRODID As String ) As Long B. Public Function getQuantity( ProdID As String ) As Double C. Public Function getQuantity( ProdID As String ) As Integer D. Private Function GETQUANTITY( PRODID As String ) As Single Answer: C Question: 8 Gloria has coded the GetAccountBalance class in the Declaration section of her Web service. What WSDL element will map to this class name? A. wsdl:binding B. wsdl:service C. wsdl:portType D. wsdl:operation Answer: C Question: 9 Jerry has coded a function called ConnectToProvider in the GetAccountBalance class in the Declaration section of his Web service. What WSDL element will be used to control the request to and response of the function? A. wsdl:part B. wsdl:method C. wsdl:binding D. wsdl:message Answer: D Question: 10 Jose wrote the following LotusScript Web service class: Class NumberTest Function GetOne () As IntegerGet? A. GetTwo only B. GetOne and GetTwo C. GetOne, GetTwo, and GetThree D. None of the methods will be available, because the Class was not declared to be Public Answer: B
For Latest 190805 Exam Questions and study guides visit
For complete Exam 190-805 Training kits and Self-Paced Study Material Visit:
For Latest 190805 Exam Questions and study guides visit
Published on Oct 7, 2009
Published on Oct 7, 2009
Certsking the leading source in certification preparation services, all certification guaranteed study material, question and answers, pract... | https://issuu.com/clarkemichael/docs/190-805 | CC-MAIN-2018-09 | refinedweb | 897 | 54.73 |
Thomas Heller wrote: > Thinking about this, I now believe (again) that this isn't what people should do. Instead, they should avoid these type names altogether, and should avoid casting function pointers. The reason they currently do that is because of the self pointer: the self pointer should have the specific type, instead of being PyObject*, so that you can access the fields of the object. The reason they should avoid this is that this casting is error-prone: If they make a mistake in the signature (e.g. forget to replace int with Py_ssize_t), the compiler will not tell them. This happened to me a few times while converting modules to Py_ssize_t; you need to be very careful when using these casts. OTOH, the solution to avoid them is pretty mechanic, and straight-forward. Just drop the casts, and replace Py_ssize_t foo_len(Foo* self) { ... } with Py_ssize_t foo_len(PyObject* _self) { Foo* self = (Foo*)_self; ... } Then, foo_len will already have the type lenfunc, and no cast is required. If you have also #if (PY_VERSION_HEX < 0x02050000) typedef int Py_ssize_t; #endif then this code will work unmodified in earlier versions: foo_len will be of type int (*)(PyObject*), which is precisely the type inquiry that it should have in the earlier versions. See for an example of applying this approach to ctypes. Regards, Martin | http://mail.python.org/pipermail/python-dev/2006-March/062561.html | crawl-002 | refinedweb | 220 | 70.33 |
Generating Postscript graphs using PyX
Postscript is an interpreted language which is highly oriented toward graphics and typography. It is a device-independent, stack-based page description language used in the desktop publishing area.
As Don Lancaster of TV
typewriter fame comments, "Postscript is an underappreciated
yet superb general purpose computing language. In its spare time, PostScript
also excels at dirtying up otherwise clean sheets of paper."
PyX is a Python package which can be used to generate publication-ready, high-quality PostScript files. It combines an abstraction of the PostScript drawing model with a TeX/LaTeX interface.
A prelude to PostScript
PostScript is an object-oriented, interpreted, dynamically-typed,
stack-based language which follows the
Reverse Polish
Notation syntax. PostScript treats images and fonts as a
collection of geometrical objects rather than as bitmaps. As it is an
interpreted language, it needs an interpreter that executes PostScript
instructions. Ghostscript is the most famous PostScript interpreter
which runs on Linux, Windows, and Mac Operating Systems. Since PostScript
is dynamically typed, its variables do not have a declared
type and can contain any kind of value.
As any other programming language, it works with various types of data such as numbers, characters, strings and arrays. These are referred to as PostScript 'objects'. It manipulates data using variables and also using a special entity called a 'stack'. The stack is a piece of memory set aside for data to be used by PostScript. Like any ordinary stack, it is a 'last in, first out' type data structure. The operator and operand handling of a PostScript interpreter can be demonstrated using this small example:
1 2 addThe operands 1 and 2 are pushed on to the stack and then the add operator replaces them with their sum. That is, the 'add' operator removes the top two numbers from the stack, adds them, and pushes the sum back onto the stack. The same is true for the 'sub', 'div', 'mod', and 'mul' operators.
Let's get our hands dirty with some PostScript snippets
If I say that PostScript is the world's best programming language to "Just let it out what is in your heart", it won't be an exaggerated statement. Imagine the situation where you have a crush on the human being sitting next to you. You can't use any other language as those languages can either provide only console based black and white things (totally unromantic) - or if you managed to get a romantic output, the code will take several pages. But just think of PostScript - and in 6 lines, you can express your feelings to the person you care for. See the code in heart.ps for example. The recipient will have to invoke a PostScript interpreter to see the what's in your geek heart, though.
gv heart.ps
%!ps % Every PostScript program should start with this line. 1 0 0 setrgbcolor %sets the color as red (rgb) 250 210 moveto %sets the initial position 270 170 100 100 200 275 curveto %draws the two curves 400 170 100 100 200 275 curveto fill showpage
A "Hello, world!" program in PostScript is available here [see helloworld.ps]. It's simple: just issue the string to be displayed, in parentheses, after setting the font and position of the text:
/Helvetica findfont % Get the basic font 30 scalefont % Scale the font to 30 points setfont % Make Helvitica the current font 250 450 moveto % Text positioned at (250,450) (Hello World !) show showpageThis will show "Hello World !" in the specified position. Another string manipulating program which contains a 'for' loop is given here [LG.ps]. Another simple program to understand the graphical nature of PostScript is the drawing of a square using lineto [square.ps].
A Simple PostScript program using PyX
Generally the PostScript programs are generated by other applications.
So from now on, instead of writing by hand, we are giving the
resposibility of generating PostScript programs to a great graphical package
available in Python programming language - PyX.
PyX is available for download at the SourceForge Download Page. It can be installed just like any other Python module.
tar zxvf PyX-0.10.tar.gz cd PyX-0.10 python setup.py installA complete installation of Tex should be present in your system as PyX depends on it. As Tex is usually distributed with almost all the standard distributions as part of authoring and publishing, it can be easily installed using the "Add/Remove Software" option in your distribution. If it is not present, another way to install TeX support in your system is:
yum install tetex # on Redhat/Fedora distributions apt-get install tetex-latex # on Debian/Ubuntu distributionsNow let's try a small Python program to dive into the PostScript world using PyX [see listing5].
from pyx import * c = canvas.canvas() c.text(10, 10, "Hello, world!") c.writePSfile("hello")Run this program as python hello.py
This will create a file "hello.ps" in the present working directory. To see the output, you can use Ghostview (gv), Gimp, or 'evince' as these programs can also display the PostScript output.
Some more PostScript graphs
A graph is generally used to depict the relationship between two or more variables with a discrete or continuous value range. It is very useful in visualizing collected data. One of such data sets that I collect daily is the blood sugar count of my mother who is a diabetes patient. This helps us to regulate her insulin injection volume as well as managing her diet. Last week's data is [diabetes.dat]:
Sunday 260 Monday 242 Tuesday 245 Wednesday 228 Thursday 282 Friday 232 Saturday 254
The Python program to visualize this data is [diabetes.py]:
from pyx import * g = graph.graphxy(width=8, x=graph.axis.bar()) # creates a graphxy instance g.plot(graph.data.file("diabetes.dat", xname=0, y=2), [graph.style.changebar()]) # reads data from diabetes.dat g.writePSfile("diabetes") # generates the PostScript file
The output of this program is [diabetes.ps]. PyX can generate graphs based on the functions also.
from pyx import * g = graph.graphxy(width=8) g.plot(graph.data.function("y(x)=sin(x)", min=0, max=10)) g.writePSfile("sine")The output of this program is [sine.ps]. The PyX package supports the generation of 3D graphs with the help of the 'graphxyz' instance. Exploring the features of PyX will be a truly rewarding experience if you want to 'visualize' the particular data that you are interested in.
Conclusion
Apart from being the worldwide leader in printing and imaging standard,
PostScript is the champion of platform-independent documentation
standards as well as excellent output quality.
PyX provides a very sophisticated PostScript graph generation mechanism using the Python language. It provides full access to the PostScript features and helps the programmer to generate high quality graphs without much effort.
ReferencesThe PostScript Language Reference, the Blue Book, and the Green Book are the "classic" books to go for, if you have a crush on PostScript.
Tinaja.com provides information regarding some interesting capabilities of PostScript.
The best documentation for the PyX package is available at the PyX SourceForge page..
. | http://ldp.indosite.co.id/LDP/LGNET/145/john2.html | crawl-003 | refinedweb | 1,193 | 56.05 |
Building Database-free Websites with Statamic CMS
Free JavaScript Book!
Write powerful, clean and maintainable JavaScript.
RRP $11.95
A content management system (CMS) is a package of code around which you build a dynamic website—with components that change, adapt and update automatically, in contrast to a hard-coded, static site.
In this article, Gareth Redfern presents a relatively new type of CMS that’s challenging the more established database-driven model.
Statamic is a flat-file CMS that has been in the wild since 2012.
It's built in PHP, and cleverly combines static and dynamic functionality. While some coding skills (HTML and CSS) are required to create a Statamic site, it's very simple to work with—having its own, intuitive templating language, and not requiring any knowledge of PHP.
All you need to get going is a code editor and an FTP program to connect with your server, and you can have your own site up and running quickly.
There's a handy 38 second video on the Statamic site that shows the CMS in action.
Statamic is a commercial product—$29 for a personal license and $99 for a pro license. That may be off-putting people used to free options like WordPress, but benefits come with this modest price—not least prompt and direct support from the development team.
Version 1 of Statamic doesn’t have a free demo, but version 2—due for beta release and built on top of Laravel—will offer this option.
Terminology
A flat-file CMS stores all your content in text files, rather than in a database—allowing you the freedom to write content directly in files using Markdown. (This is where the “static” part of the Statamic name comes from.)
Statamic is sometimes compared with static site generators such as Jekyll, which run your site through a converter that then produces HTML files for you to upload to your server. Although Statamic does have a static site generator, it requires PHP to run on your server, and is much more dynamic than the likes of Jekyll.
The Control Panel
Because Statamic is dynamic, it offers a control panel for adding and editing your content—which means it's a viable CMS to hand off to clients, unlike Jekyll.
The control panel is fully responsive, and offers a very clean, easy-to-use interface which both clients and fellow developers love.
The Statamic Control Panel
Although the control panel is available, you don't have to use it, as you can also work directly with text files and upload them as needed.
Version Control Your Complete Site
Having your whole site based on simple text files—including the content—carries the great advantage that everything can be version controlled, and even stored and edited in your favorite Git hosting service.
This removes a lot of the headaches that traditional database-driven websites can give you when it comes to keeping content in sync from staging to production.
Types of Sites That Suit Statamic
Statamic lends itself well to the majority of website builds, with some popular blogs and company sites running it as their preferred CMS.
Of course, if you have a very large, content-heavy site with complex relationships, then a database-driven site may be more appropriate—though personally, I haven’t come across a site that Statamic can’t handle yet.
Getting Started
Installing Statamic is very simple.
You can run it locally on a server environment like MAMP or WampServer. You can then transfer everything to your server as needed.
First you should run a quick server check to make sure your host meets the minimum requirements.
After running the checks, just drop your files into the root of your site and enter some basic config settings in the
settings.yaml file, enable the
sample.htaccess by renaming it to
.htaccess, and you're all set.
Updating is even easier: you just need to swap out two folders,
_app and
admin.
The Folder Structure
The standard install comes with two example themes, and content which can be used as a starting point for creating your own theme.
All your written content is stored in the
_content folder. In that folder, you have two “types”: pages and entries.
Pages are for your more static content, which can still be edited via the control panel, but which tend to be single pages like an “about” page. Entries are more dynamic, being added or updated on a regular basis. Blog or news articles are a good example of this type of content.
Each content page will have a YAML header—which is basically your template variables and content stored between 3 dashes.
If you haven’t heard of YAML before, it's a very human readable language used for storing data. One important point to remember when you're first starting is that YAML is very specific about indentation (use 2 spaces). Here's an example of a YAML file:
Theming
The
_themes folder is where you can drop your theme. Statamic is very flexible in how you build it, but by following some conventions you can create themes that are easy to swap out on a site-by-site basis.
I've created a simple theme on GitHub for you to refer to as an example following this convention.
Basic Anatomy of a Theme
The folder structure example can be explained as follows:
- Layouts are the main structure of your page. Here you'll include partials and templates.
- Partials are small reusable chunks of reusable code.
- Templates are content-specific, and usually house the logic for displaying your page content.
Statamic comes with its own templating language that's very straightforward to learn. As an example, I'll run through how you would list your blog entries on a page, linking through to the detailed post.
Open up the
_content folder and navigate to the
blog folder. You should see the following structure:
Blog Folder Contents
The articles, which all start with the date
2015-01-01 etc., will be what we're going to list using the
entries tag.
Listing Entries
Go to the
default.html template in the theme’s template folder and have a look at the
{{ entries:listing }} tag pair, which is wrapping the article HTML tags.
Here we've told the
entries tag to fetch the listings from the
blog folder by using the
folder="blog" parameter. We've also set a limit of 2 articles to be listed by using the
limit="2" parameter. The
entries tag is a tag pair, so you'll see that there has to be a closing tag
{{ /entries:listing }} which closes the loop.
The complete listing code looks like below, and inside there are two variables used—
{{ url }} and
{{ title }}:
{{ entries:listing{{ title }}</a></h3> </article> {{ /entries:listing }}
The first tag will render the URL to the single article, and the second tag will render the title of the article. This is the simple listings page all set up: we have two articles listed, which link through to their post pages.
Pagination
The pagination tag is used in conjunction with the
{{ entries:listing }} tag to render pagination when there are more articles than you have set within the limit parameter. There are two important points when using the pagination tag.
1. Matching parameters
The folder and limit parameters must match what you've set on the
{{ entries:listing }} tag. So, for example, the folder is set to
blog on both tags, and the limit is set to
2 on both tags.
2. Setting variables
Next, we need to set the variables inside the pagination tag pair, which will render the required links depending on what page you're on. You'll see in the
default.html template there's a couple of conditional statements used to set the page links. If you're unfamiliar with conditional statements, don't worry too much about what this code is doing. Just know that it'll render the correct links for your pagination to work.
{{ entries:pagination {{ if previous_page }} <a href="{{ previous_page }}">« Previous</a> {{ endif }} {{ if next_page }} <a href="{{ next_page }}">Next »</a> {{ endif }} </div><!-- END .pagination --> {{ /entries:pagination }}
The Post Template
We now have our main listing page rendering all our blog articles. When you click on a article listing link, you're taken through to a post page, and by default this will use the
post.html template to render the content.
Open up the
post.html template in your code editor, and you'll see that this page only has two template tags title and content. The
{{ title }} tag displays the title for the post and the
{{ content }} tag will render all the text in your entry file below the YAML header (three dashes at the top of your file).
How does Statamic know what content to render and which template to use? The secret is in the
{{ entries:listing }} tag used in the previous template. With the URL variable set on the link in the
default.html template, it dynamically links to the correct page and will always use the following required templates:
- if present:
post.html
- otherwise, if present:
default.html
- otherwise:
404.html.
You can override this by setting a
_template: my_template variable in your YAML header, but as we haven’t, the
post.html template is chosen to render the content. For more information on this, have a look at the documentation.
Community and Resources
One of the great things about Statamic is the amazing community that surrounds it. Asking a question on Twitter using the
#statamic hash tag, or on the recent Slack channel, usually gets you an answer straight away.
The main support area—called the Lodge—has a wealth of searchable questions and answers. It’s also a great place to ask questions—and again, either a member of the community or one of the Statamic Gentlemen is always on hand to help you.
There are lots of other resources for learning more about building Statamic sites. There's the add-on stash, featuring a range of add-ons for extending Statamic in all sorts of ways, and builtwithstatamic.com, a showcase of sites built on Statamic. There are also some great videos on Vimeo that show Statamic in action and explain how to do certain things with it. If you're looking for a starter theme, check out my Statarkers Theme. And finally, you can keep up with the latest news on the Statamic blog, and keep tabs on the next version on the version 2 blog.
Wrap-up
Statamic provides a great platform for building a range of websites. Once you pick up the basics of how to put a theme together, you’ll soon fall in love with its flexibility. The control panel is simple and a joy to use for content editing, but the flexibility is such that you can keep content up to date in simple Markdown files. There's a great flow when developing Statamic sites, as you quickly move from content modeling to content editing easily.
I hope you've enjoyed this introduction to Statamic. There are lots of CMSs available these days, but this one has emerged as one of the leaders in recent years, and is definitely worth considering on your next project. For many, its flat-file focus is a real winner in terms of version control, updating and ease of use.
If you have any questions, let me know in the comments. I'm keen to know if you've tried Statamic and how you found it.
Get practical advice to start your career in programming!
Master complex transitions, transformations and animations in CSS! | https://www.sitepoint.com/building-database-free-websites-with-statamic-cms/ | CC-MAIN-2021-04 | refinedweb | 1,957 | 70.63 |
A first glimpse into .NET Core 2.0 Preview 1 and ASP.NET Core 2.0.0 Preview 1
Jürgen Gutsch - 30 May, 2017
At the Build 2017 conference Microsoft announced the preview 1 versions of .NET Core 2.0, of the .NET Standard 2.0 and ASP.NET Core 2.0. I recently had a quick look into it and want to show you a little bit about it with this post.
.NET Core 2.0 Preview 1
Rich Lander (Program Manager at Microsoft) wrote about the release of the preview 1, .NET Standard 2.0, tools support in this post: Announcing .NET Core 2.0 Preview 1. It is important to read the first part about the requirements carefully. Especially the requirement of Visual Studio 2017 15.3 Preview. At the first quick look I was wondering about the requirement of installing a preview version of Visual Studio 2017, because I have already installed the final version since a few months. But the details is in the numbers. The final version of Visual Studio 2017 is the 15.2. The new tooling for .NET Core 2.0 preview is in the 15.3 which is in preview currently.
So if you want to use .NET Core 2. preview 1 with Visual Studio 2017 you need to install the preview of 15.3
The good thing is, the preview can be installed side by side with the current final of Visual Studio 2017. It doesn't double the usage of disk space, because both versions are able share some SDKs, e.g. the Windows SDK. But you need to install the add-ins you want to use for this version separately.
After the Visual Studio you need to install the new .NET Core SDK which also installs NET Core 2.0 Preview 1 and the .NET CLI.
The .NET CLI
After the new version of .NET Core is installed type
dotnet --version in a command prompt. It will show you the version of the currently used .NET SDK:
Wait. I installed a preview 1 version and this is now the default on the entire machine? Yes.
The CLI uses the latest installed SDK on the machine by default. But anyway you are able to run different .NET Core SDKs side by side. To see what versions are installed on our machine type
dotnet --info in a command prompt and copy the first part of the base path and past it to a new explorer window:
You are able to use all of them if you want to.
This is possible by adding a "global.json" to your solution folder. This is a pretty small file which defines the SDK version you want to use:
{ "projects": [ "src", "test" ], "sdk": { "version": "1.0.4" } }
Inside the folder "C:\git\dotnetcore", I added two different folders: the "v104" should use the current final version 1.0.4 and the "v200" should use the preview 1 of 2.0.0. to get it working I just need to put the "global.json" into the "v104" folder:
The SDK
Now I want to have a look into the new SDK. The first thing I do after installing a new version is to type
dotnet --help in a command prompt. The first level help doesn't contain any surprises, just the version number differs. The most interesting difference is visible by typing
dotnet new --help. We get a new template to add an ASP.NET Core Web App based on Razor pages. We also get the possibility to just add single files, like a razor page, "NuGet.config" or a "Web.Config". This is pretty nice.
I also played around with the SDK by creating a new console app. I typed
dotnet new console -n consoleapp:
As you can see in the screenshot dotnet new will directly download the NuGet packages from the package source. It runs dotnet restore for you. It is not a super cool feature but good to know if you get some NuGet restore errors while creating a new app.
When I opened the "consoleapp.csproj", I saw the expected TargetFramework "netcoreapp2.0"
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp2.0</TargetFramework> </PropertyGroup> </Project>
This is the only difference between the 2.0.0 preview 1 and the 1.0.4
In ASP.NET Core are a lot more changes done. Let's have a quick look here too:
ASP.NET Core 2.0 Preview 1
Also for the ASP.NET 2.0 Preview 1, Jeffrey T. Fritz (Program Manager for ASP.NET) wrote a pretty detailed announcement post in the webdev blog: Announcing ASP.NET Core 2.0.0-Preview1 and Updates for .NET Web Developers.
To create a new ASP.NET Web App, I need to type
dotnet new mvc -n webapp in a command prompt window. This command immediately creates the web app and starts to download the needed packages:
Let's see what changed, starting with the "Program.cs":
public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); }
The first thing I mentioned is the encapsulation of the code that creates and configures the
WebHostBuilder. In the previous versions it was all in the static void main. But there's no instantiation of the
WebHostBuilder anymore. This is hidden in the
.CreateDefaultBuilder() method. This look a little cleaner now, but also hides the configuration from the developer. It is anyway possible to use the old way to configure the
WebHostBuilder, but this wrapper does a little more than the old configuration. This Method also wraps the configuration of the
ConfigurationBuilder and the
LoggerFactory. The default configurations were moved from the "Startup.cs" to the
.CreateDefaultBuilder(). Let's have a look into the "Startup.cs":?}"); }); } }
Even this file is much cleaner now.
But if you now want to customize the Configuration, the Logging and the other stuff, you need to replace the
.CreateDefaultBuilder() with the previous style of bootstrapping the application or you need to extend the
WebHostBuilder returned by this method. You could have a look into the sources of the WebHost class in the ASP.NET repository on GitHub (around line 150) to see how this is done inside the
.CreateDefaultBuilder(). The code of that method looks pretty familiar for someone who already used the previous version.
BTW: BrowserLink was removed from the templates of this preview version. Which is good from my perspective, because it causes an error while starting up the applications.
Result
This is just a first short glimpse into the .NET Core 2.0 Preview 1. I need some more time to play around with it and learn a little more about the upcoming changes. For sure I need to rewrite my post about the custom logging a little bit :)
BTW: Last week, I created a 45 min video about it in German. This is not a video with a good quality. It is quite bad. I just wanted to test a new microphone and Camtasia Studio and I chose ".NET Core 2.0 Preview 1" as the topic to present. Even if it has a awful quality, maybe it is anyway useful to some of my German speaking readers. :)
I'll come with some more .NET 2.0 topics within the next months. | http://asp.net-hacker.rocks/2017/05/30/first-glimpse-into-netcore2-preview.html | CC-MAIN-2018-09 | refinedweb | 1,231 | 78.35 |
".
- Setup for a three-player game.
- A player board after a few rounds..
49 Reader Comments!
Good call.
I haven't actually played Diplomacy, but my understanding is that it's less "bluff and laugh with friends" and more "burn all your friendships to the ground and gleefully dance on the ashes."
Yeah, Secret Hitler looks promising. Great art and design, too.
Good call.
I haven't actually played Diplomacy, but my understanding is that it's less "bluff and laugh with friends" and more "burn all your friendships to the ground and gleefully dance on the ashes."
I've heard this a lot, but I have to respectfully disagree. If you're playing Diplomacy and it's ruining your friendships, I dare say that you were playing Diplomacy with people who couldn't mentally separate "my friend lied to me" from "my friend lied to me during a game in which lying is an accepted game mechanic".
I will agree that it's not for everyone, not everyone can handle how intense it can get, but I've made some good friends playing Diplomacy and I know other people who have made even closer friendships through Diplomacy. Sure, once in a while I might tank emotionally over what's just happened to me, but I've almost always gone and had dinner or at least a drink with the person I was upset with at the end of the game.
And I play tournament Diplomacy, where trophies and other shiny objects (and some intra-hobby cachet for doing well at a tournament) are on the line, not just house games. In fact, the only times I've really tanked emotionally over Diplomacy are at tournaments--"you've reduced my end of this to pushing pieces, and why did I fly all this way to do that? I can play pushing pieces at home on my own board!"
Now this last bit is my personal take on it, but if you backstab me and I can see why you did it, I don't really take it that hard. I might not agree that it was your best/only course of action, but if I can see how it advances your own goals, then whatever, that's the game. The only times I've started yelling at people during Diplomacy is when I can't understand why they're doing what they're doing and am convinced that they're just doing something that's going to ultimately take BOTH of us down; but I only really care enough to do this if it's at a tournament. I discussed this once with a fellow tournament player and he put it exactly right: "I can lose this game for myself, thank you very much."
Last edited by Eurynom0s on Sat Dec 26, 2015 11:39 am
Munchkin is pretty complicated in my experience but fun, and Machiavelli has pretty simple rules and is really fun too. In Machiavelli, the bluffing part consists of that every round each player has one of eight characters (or two in case of a 2-player game) but no one knows which character you are. You can be the thief for example and steal someone's gold, but you have to figure out which character that player has to steal it from.
Coup on the other hand is quite enjoyable since there are few enough copies of each role for it to be possible to make educated guesses with very little information, especially as odds are improved as more cards are revealed. Even a mistaken accusation can glean you a little more information, at the cost of one of your own cards.
Same thing with Bang! The dice game. Players can try to deduce who plays what role based on their actions, i.e. what dice they choose to keep, but the random nature of the dice is enough to create plausible doubt and allowing for the accusations fly..
The only real downside to it is the iOS/Android app that reads the script. As a group mostly made up of music producers, some of whom regularly compose music for video games, the bad loop in the app's background music drives us INSANE. ... ret-hitler
Correct. for UK users. ... e&t=34m23s for other users.
Cheap too. All you need is a carrot and two boxes. ... ret-hitler
Wish I'd seen this one while it was still in the pre-funding phase!
Separately, a bunch of Arsians have been playing werewolf online for over five years now. Periodically posting about it in the GESC. Come on over and take a look if you're interested in refining your skills...
here.
i've played fun games with people who weren't into them or perhaps forced to play by others. it ruins the game.
best to move on to other activities.
My personal favorite thing, though, was teaching them to play Werewolf on the dock of the lake. Getting 'killed' meant you had to jump in. It was fun watching the kids reaction as they hear a splash in the 'night', signifying that someone met a grisly fate.
The one our family plays all the time is the Dutch card game Toepen. Uses regular cards, but has a great betting/knocking system to bluff through. Rules:
And an oldie but goodie that we played as kids was Contraband - simple card game about smuggling goods and paying duty on what you 'declare'.
Are there any, ACTUAL simple games involving lying, instead of these complicated ones?!
The first time i played this on Christmas day, I did exactly that. I would pretend others' cards were mine, so they wouldn't choose them. This would work as some people wouldn't award people with the most black cards, so it's a good extra level to add to the game. Just make a rule that says you can't say that any card is, or is not, your card, but you can act any way you like (sheepish, smug, etc) in order to hint one way or another.
Are there any, ACTUAL simple games involving lying, instead of these complicated ones?
The big game-changer for me for resistance (as far as making it more than just a fun game to play while drunk) was:
1) Realizing that "just vote yes for the first-round team" is a _terrible_ strategy.
2) Getting the expansions that add just enough complexity to make it a bit more strategic.
3) Giving everyone one of the special-power cards to start the game.
(1) is huge: For the first couple dozen rounds, people just assume: "well I have no information, so I have no reason to vote this team down", but the key is that you _do_ have information: If you're not a spy and you're not on the mission, there's a much greater-than-average chance a spy is on the mission. Once people start voting down missions they're not on, it becomes much more challenging for the spies to conceal themselves.
(2) helps just by adding some extra goals and abilities.
(3) also helps in larger groups. If at the start of the game, someone has the "look at Y's identity card", then it adds a bit more deduction since you learn facts like "X looked at the card and accused Y of being a spy, so they're likely on different teams". It's also more fun to just have the special power.
One game I like that is kinda up this alley is Shadow Hunters. It's a mix of bluffing and deduction because you get to find out info about others and watch what they do to try and guess who they are. Along the lines of a more complicated Coup mixed with ONUW. You have three teams. The good guys. The bad guys and neutrals. The good guys are trying to kill the bad guys and the bad guys are trying to kill the good guys. The neutrals have unique ways to win. One neutral might win by dying first. Another might win if the player to his left wins. You get info by getting a specific type of card and giving it to someone else. It might say if you are a Good guy or a neutral take 1 damage. Everyone gets to see the result but only the person who gave them the card knows what it said. The bluffing comes in because you can tell anyone anything you want about the game but you don't know if they are bluffing or not. You can't "lie" when given the a card but other than that it's fair game when trying to convince the other players who you are or who you think/know someone else is. Your role also has a special ability that you can use one or more times depending on the ability but they all come with a big cost. You have to reveal who you are. You're are a good guy and are sure who the last bad guy is? You can reveal yourself to make your argument more convincing. About to die? You might be able to reveal yourself to save yourself but your time is now limited unless the other team is too scared to attach you.
YES. I learnt something that day. Do not play Sean Lock at social interactive games were bluffing and intrigue are the main mechanics of the game.
Though I found my self considering he was being too obvious at the end. I found my self hoping it was a ruse.
Edit: spelling
It is great fun, involves lots of lying, and just requires a pile of dice, nothing fancy.
It reached truly epic proportions when he drew suspicion aggro in a Battlestar Galactica game by suggesting that we complete a task, then sabotaging it partway through because he apparently decided A) it wasn't worth doing, B) this would be obvious ('logical') to everyone that he just convinced to do it, and C) there would / should be no downside to making this decision unilaterally after a couple comments along the lines of 'I dunno, this is a lot of my resources.'
The ACTUAL Cylons had just lucked out on a Baltar False Negative, and the second half of the game had just started, so things went about the way you'd expect. I got a feeling that something was horribly wrong when my other non-Cylon friend looked him right in the eye and said, "You're either the Cylon, or a complete idiot", and I saw the expression he got in return (in context, the tone and delivery were quite insulting and somewhat out of bounds). Before I could work out whether we had one or two and try to do something about it, the Cylons were President and Admiral and throwing everyone in the brig. To this day, the non-Cylon refuses to play these sorts of games and insists that his actions made total sense.
Good times.
It is essentially the older board game Balderdash, but played with each person's cell phone or tablet for input.
For best experience, have something you can use to display the game on your TV - I use a Chromecast - and then everyone simply joins with their cell phone. There is nothing to download, you simply visit their website and enter the room code displayed in-game to join.
It's super easy and I really see a lot of potential with this "platform".
Not only does the name work amazingly well, but you can form alliances and plan on the future when to backstab your friends!
Diplomacy might be the easiest way I know to really get angry with people I generally like very much. Only drawback is that it isn't exactly spontaneous, being seven players is basically required, and everyone needs to be available for basically the whole day (though I guess that depends on how strict you are with timers).?
Were you playing full Werewolf or One Night? What did your friend do that ruined the game for you?
Avalon feels much more like Werewolf than Sheriff of Nottingham; Sheriff is much friendlier and less intense than many of the hidden role games. If you want a low-stress game with hidden roles, Coup might work for you.
Yeah, I was going to mention G54's existence but decided to keep it simple for this list. I haven't tried it yet, but it looks like it could be a cool step up from base Coup for some groups.
One Night Resistance is also on my list to try. Hard to keep up with all of IB&C's Kickstarters.
Honestly, if you can't lie and backstab each other, we're probably not playing it. Way more fun than playing a game that's decided entirely by luck.
You must login or create an account to comment. | https://arstechnica.com/gaming/2015/12/lying-to-your-friends-a-bluffing-games-primer/?comments=1 | CC-MAIN-2017-47 | refinedweb | 2,179 | 77.37 |
I've got a Reservation model that can take a scheduled appointment attribute as
date and it has an online attribute
duration that signifies how lengthy the appointment will require. The actual attribute,
booking_end requires a Time that's recommended throughout my application. However, for easy input, we use duration rather than selecting another
Time. The fields are below:
def duration ( (booking_end - date) / 1.hour ).round( 2 ) rescue nil end def duration=(temp) if ( true if Float(temp) rescue false ) self.booking_end = time_round(date + temp.to_f.hours, 15.minutes) else errors.add(:duration, "must be a number, stated in hours.") self.booking_end = nil end end
The entire factor fails after i reference the
date area while developing a new record. I recieve a 'nil' error because date has not been initialized. How do i fix this issue? The relaxation of the works when upgrading existing records.
Whenever you call Reservation.new(:date => date, :duration => duration) ActiveRecord::Base assigns characteristics values by doing this (see assign_characteristics method):
attributes.each do |k, v| ... respond_to?("#{k}=") ? send("#{k}="", v) ...
Hash#each method iterates with the values the way in which :duration secret is utilized before :date one, so date is nil within the duration= method:
ruby-1.8.7-p302 > {:date => Date.today, :duration => 5}.each do |key,value| ruby-1.8.7-p302 > puts "#{key} = #{value}" ruby-1.8.7-p302 ?> end duration = 5 date = 2010-11-17
So you will need to call duration= after initialization.
Or redefine Reservation#initialize to call super with :date after which update_characteristics using the relaxation of parameters.
I attempted to initialize the model with
Reservation.new(params[:reservation][:date])
after which call
update_attributes onto it. This works in console, although not otherwise. The only real workaround that appears to consider hold is draining duration from the params hash after which passing it back before save. This appears really stupid, though, and most likely not the best or Rails method of doing things. Using 4 lines where you ought to suffice.
duration = params[:reservation][:duration] params[:reservation].delete('duration') @reservation = Reservation.new(params[:reservation]) @reservation.duration = duration # Then go to save, etc.
Can there be an additional way to initialize the model or possibly access the characteristics hash from the model? | http://codeblow.com/questions/how-do-i-reference-characteristics-before-a-save/ | CC-MAIN-2019-30 | refinedweb | 375 | 52.76 |
Re: Topic: .NET/COM Interop in VB6 MSProject Addin
DapperDanH_at_nospam.nospam
Date: 06/29/04
- ]
Date: Tue, 29 Jun 2004 12:23:01 -0700
Martin,
Thanks for your reply. This has been tremendous help!!!
Sincerely,
Dan
"Martin Boehm" wrote:
>
> Hi Dan,
>
> Seems like you have the same problem I had when I wrote my MS Project Addin
> (completely c#).
>
> Let's see what I can do for you....
>
> 1) The setup worked only on machines where VS.Net was istalled and where the
> code has been compiled before. It was a little bit frustrating, but in some
> news entry I found the solution:
> Try to declare your classes and methods as internal or private. Use
> public classes and methods only if necessary.
>
> This one's very important:
> Don't use your custom .Net classes in public methods!!!! (Sounds weird,
> but I have tested it, the problem is the sequence methods and objects are
> registered for COM interop)
>
> 2) Since we have a pure c# Addin we decided to strongly name our addin and
> add it to the GAC. So it doesn't matter where the dll is. It can be in any
> directory specified by the user during the setup.
>
> 3) Debugging .Net Addins:
> you can debug your dll quite easily: Click on the project in the project
> explorer and select properties. Select Debug from configuration settings
> and as start options select start program and an application which you would
> like to start. Then if you're in debug mode you should be able to debug your
> project ;-)
>
> 4) Storing application settings:
> Application settings for dlls are always stored in the config file of the
> calling application. In this case it's winproj.exe.config. But I recommend
> that you store your settings somewhere else, e.g. registry. It's much easier
> to maintain, especially because there might be problems when distributing it
> to the end users. In this case the whole config file would have to be
> exchanged.
>
>
> HTH.
>
> Best Regards
> Martin
> Martin DOT Boehm AT OPUS HYPHEN GmbH DOT Net
>
> <DapperDanH@nospam.nospam> schrieb im Newsbeitrag
> news:0B757729-545D-4ACC-8357-35FEF50A1914@microsoft, I
> > wrote a simple wrapper class that exposes a single method
> > and several events for use in COM. In all there are about
> > seven supproting .NET dlls that are directly or indirectly
> > referenced by this wrapper I've created.
> >
> > I am looking for some sound advice regarding the best way
> > to structure and deploy this kind of solution. I have read
> > everything that I could find in the VS.NET 2003 help files,
> > MSDN-online, and a bunch of Google search hits. While I have
> > found a solution that gets the job done, I don't feel very
> > confident that I am doing it the 'right' or 'best' way.
> >
> > Some of the ideas I have encountered and/or tried are:
> > 1 Register the .NET assemblies using the 'regasm -codebase'.
> > Works great on my local machine, but didn't work when I
> > tried to deploy on several test machines.
> >
> > 2 Install the .NET assemblies in the GAC.
> > Works great, even when deployed on test machines, but
> > all the 'official' Microsoft references seemed to
> > discourage the use of the GAC, except when its use is
> > absolutely required. (The MS help pages did not specify
> > what they meant by 'absolutely required', but the did
> > specifically mention COM interop did not require that
> > the .NET assemblies be installed in the GAC.
> >
> > 3 Just install the .NET dlls in the application directory.
> > This works fine, as long as I can guarantee that the
> > 'current directory' is known when I install the dlls.
> > Using this approach, you can't even debug a VB app
> > that references .NET assemblies. You have to build an
> > executable and then explicitly place it in the same
> > directory as the .NET dlls it references.
> >
> > An additional problem is that I don't know what current
> > directory is used by MS Project when it loads/runs add-
> > ins. I don't even know if it's guaranteed to be the
> > same directory, or if it might change, depending on
> > variables outside my control.
> >
> > Attached is a simple application that roughly exhibits
> > the situation I've got. Rather than using a VB add-in
> > project, I just made a stand-alone VB 6.0 executable
> > that references one of my .NET dlls. I generated a tlb
> > using regasm.exe, so that I could reference it in my VB
> > project. To test that it will run fine, regardless of
> > the current working directory, I just copy the VB exe
> > to a different location and test that it runs the same.
> > Although the events that I fire in this sample are some-
> > what contrived, use of events is required in my real-
> > world application and that is why they are in the sample.
> >
> > To set up the attached sample, please extract the
> > archive to a folder. Everything is pre-built, so there
> > should be no need to rebuild it. However, if you wish
> > to do so, simply load 'VBCOMInterop.sln' in VS.NET
> > and 'IntCalcWrapperVBClient.vbp' in VB 6.0 and build
> > the projects. (You may need to run 'regasm -tlb' on the
> > 'IntCalcWrapper.dll' before you make the VB exe, so that
> > you can set up the project reference.)
> >
> > At this point, the VB app should run correctly when run
> > from a pre-built exe that lives in the same directory
> > as the .NET dlls.
> >
> > I would appreciate your thoughts as
> > to the most appropriate way to make it run properly even
> > if the executable doesn't reside in the same location as
> > the .NET dlls. (Such as if the VB app were really an
> > office add-in) The 'calcsetup.bat' file in the archive
> > contains the steps I took to get it to work.
> > (I copy the binaries to the 'VBCOMInterop/deploy' folder
> > in a post-build event. So all that you need to do to
> > execute my deployment solution is run 'calcsetup.bat',
> > which is also in the 'VBCOMInterop/deploy' directory.)
> >
> > Thank you for you help.
> >
> > -Dan
> >
> >
>
>
>
- ] | http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.interop/2004-06/0461.html | crawl-002 | refinedweb | 1,010 | 74.39 |
I want to make my plugin transparent to end user like this:
def on_modified(self, view):
command = view.command_history(0)
if command[0] == 'my_command':
if _IT_IS_UNDO_:
view.run_command('undo')
elif _IT_IS_REDO_:
view.run_command('redo')
But the Undo and Redo commands don't appear in command_history(), so how can I know is it a undo or redo command in on_modified?
Thanks for helping.
In my Elastic Tabstops plugin (github.com/SublimeText/ElasticTabstops) I actually overrode undo and redo because I couldn't figure out how else to do it. This was before view.command_history existed, though, so there may be a better way now. Let us know if you get something workable! | https://forum.sublimetext.com/t/detect-its-whether-a-undo-or-a-redo-command-in-on-modified/6235/2 | CC-MAIN-2017-09 | refinedweb | 111 | 53.17 |
lazr/__init__.py should not do a version test
Bug Description
lazr/__init__.py registers pre-PEP 420 namespace packages but does only for Python versions < 3.3. Python 3.3 is where PEP 420 was introduced so the version test attempts to avoid the old-style registration for Pythons that support PEP 420. This is broken however because the mere presence of lazr/__init__.py disables PEP 420 namespace packages. While Debian packaging tools will remove the lazr/__init__.py from all namespace portions when they build the >= Python 3.3 binary packages, if you are using something like `python3.4 setup.py install` on a project that is dependent on lazr.* packages, the lazr/__init__.py file will not get deleted, and thus neither PEP 420 nor old-style registration will happen. This makes lazr packages unimportable.
Since the upstream Python packaging tools have no inherent way of removing the lazr/__init__.py file, the solution is just to remove the version test and always use the old-style registration code.
This bug may affect other lazr.* packages too. I'll try to take a look but right now lazr.{smtptest,
config, delegates} is my highest priority for releasing a fix. | https://bugs.launchpad.net/lazr.config/+bug/1407816 | CC-MAIN-2019-51 | refinedweb | 203 | 77.64 |
View Complete Post
We have number of asmx services. I want to give an user a page with a textbox to input service url like. When user hit "Load" button, dynamically I add all the web methods to the dropdown.
I was able to find a way to generate the proxy and the list of all the methods using this helpful link:
But, I found that I have to know the serviceName and the namespace beforehand to make this work. In real scenario, user will just enter any asmx, how will I know the namespace and the service name of the selected service upfront? Can I extract that too dynamically
so that I don't need to change the code or build a list of all the namespaces and servicenames?
Hall of Fame Twitter Terms of Service Privacy Policy Contact Us Archives Tell A Friend | http://www.dotnetspark.com/links/9817-webreference-vs-servicereference.aspx | CC-MAIN-2017-13 | refinedweb | 145 | 67.49 |
In a Xamarin Forms iOS/Android app I've been using a single .resx file for some time. Now, I'm getting 'MissingManifestResourceException', 'Could not find any resources appropriate for the specified culture or the neutral culture'. This seemed to coincide with installing XS 5.91 but can't be sure on that.
Reverting to XS 5.9 and retrieving a backup copy of my app from before the problem started, I found curiously that the app would run but as soon as I made any edit however trivial to my .resx file, the error would return. Experimenting further, I built a minimal app having a .resx file, and it had the same problem. Next, I downloaded the .resx sample app at . It too ran correctly first up. Interestingly, it includes reflection code to check that the resource file is indeed embedded, and output a message showing that it was. However, as soon as I made a trivial edit to its default .resx file, it got the same error when next run.
Getting somewhat desperate now, I (completely) uninstalled Xamarin iOS, Xamarin Android and XS, following the guide at . Then I went back a couple of versions and installed iOS8.9.1, Android 4.20.2 and XS 5.8.3. I re-downloaded the sample .resx app just to be sure, and tried it out. Same result -- it runs first time but gets the error after any trivial edit is made to the default .resx file.
I believe I've checked all the usual things like build action of the .resx being Embedded Resource. Xcode is V6.3. My tests were with the iOS side.
Running out of ideas here, and of course can't progress with my app. Would be so grateful for any suggestions.
To be clear, the .resx is in the PCL and the startup project is iOS.
My Bugzilla bug report posted here:
(Very) temporary workaround:
I think you are seeing bug 30044 in Xamarin Studio 5.9. In Xamarin Studio 5.8 you should be able to fix the problem by configuring the .NET naming policy, more on this below.
The problem in Xamarin Studio 5.9 is that it is generating a different resource name in the AppResources.Designer.cs file. The unmodified code on GitHub is:
The
"UsingResxLocalization.Resx.AppResources"string being passed to the resource manager is the important part.
I suspect when you edit the .resx file and save it the string is being changed to
"UsingResxLocalization.AppResources"which is the problem reported in bug 30044.
In Xamarin Studio 5.9 you should be able to workaround this by changing the Resource Id in the properties for each .resx file so it is the correct string. Another slightly hacky way is to change the default namespace of the project to be
"UsingResxLocalization.Resx". Another workaround would be to move the resource files into the root directory of the project.
In Xamarin Studio 5.8 I believe you will need to configure the .NET Naming policy in the project options so the correct resource name string is generated. If you check both Associate namespaces with directory names and Use default namespace as root then re-save the .resx file it should generate the correct string in the designer file. By default it generates the resource name without the directory name.
Thanks @mattward. Excising ".resx" from the .resx file's ResourceId property fixed my problem.
I have the same problem...
I had the same desperate problem @BillFulton, then i hit this page at 4 AM
I am getting the error just launching an unmodified copy of UseResxLocalization demo on android on the latest version of Xamarin & Xamarin Studio.
Any suggestions?
My issue was, that I had previously been changing the namespace for my entire solution by first changing the Default Namespace in the project properties and thereafter using ReSharper to adjust the namespaces automatically.
I personally solved the issue I had by opening
./Resources/AppResources.rex/AppResources.Designer.cswhere I found that the namespace hadn't been changed for the
ResourceManagerautomatically.
I simply changed the ´OLD.NAMESPACE` (see code below) to my new namespace which fixed the issue:
Hmm. This problem re-emerged, seemingly coincident with installing Xamarin 4.
In my case I solved it by restoring the ".resx" that I had previously excised to get things working in an earlier version - see my comment above dated May 21, 2015. Sounds like the bug has been fully addressed now ...
I'm getting a similar error and I've tried all of the above steps
{System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Resources.MissingManifestResourceException: Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "MobileGateApp.AppResources.resources" was correctly embedded or linked into assembly "PatrolLiveApp" at compile time, or that all the satellite assemblies required are loadable and fully signed.
I did rename namespaces all over my solution using resharper , from MobileGateApp to PatrolLiveApp
The above error would indicate it is still looking for a resource file named MobileGateApp:
Make sure "MobileGateApp.AppResources.resources" was correctly embedded
Where is this MobileGateApp.AppResources.resources ?
Same here, tried all above fixes, still the problem persists.
Same here by error. Changed Resource to public and forgeted to change the custom tool to PublicResXFileCodeGenerator
Had same problem, was hard to fix, after getting the code from the xamarin forms resx localization article and sample code.. The point was the mismatch between namespaces. I hope that was your case, so we could fix it. When you make all namespaces dependencies match in different places everything will suddenly work
When you create a ResX resource table you gave it a name like YourResXTablename (mine was name just "Res").
ResX custom tools auto-generate namespace for your brand new resource tables as Yourappnamespace.ResX. It will reside inside YourResXTablename.Designer.cs and must not be changed as the compiler will overwrite it.
In the Shared project:
ILocalizeinterface has to have same namespace as the auto-generated for resources (Yourappnamespace.ResX).
class TranslateExtensionsame, set namespace to Yourappnamespace.ResX.
const string ResourceId = "Yourappnamespace.ResX.YourResXTablename";
In Android project:
public class Localize : ILocalizeSet namespace same as your main android project namespace (Yourappnamespace.Droid or Yourappnamespace.Android)
[assembly: Xamarin.Forms.Dependency(typeof(Yourappnamespace.Droid.Localize))]to match your Android project namespace.
In iOS etc - proceed like for Android.
The usage in XAML can be cleaner than proposed in xamarin article:
Every page include
xmlns:resX="clr-namespace:Yourappnamespace.ResX;assembly=Yourappnamespace"and the string goes as
Text="{resX:Translate StringName}".
Or.. dunno how but
Text="{x:Static resX:Res.StringName}"translates fine too..
@NickKovalsky thanks a lot, your post helped me out of my problems!
In my Xamarin version the autogenerated namespace of YourResXTablename.Designer.cs was no longer Yourappnamespace.ResX. My version generated only Yourappnamespace.
So had to leave out the ".ResX".
At the end my problem was that I also got the code from the xamarin forms resx localization article - and I had to change the line you mentioned above to:
const string ResourceId = "Yourappnamespace.YourResXTablename";**
Try also looking in your Pro file. I've had same problem and in my Proj file remain old name | https://forums.xamarin.com/discussion/comment/134473/ | CC-MAIN-2021-10 | refinedweb | 1,207 | 60.31 |
Selection Operations¶
See also
Reading Assignment
Chapters 4.1 - 4.7
Today, we will focus more attention on the Selection Structure, usually seen in the form of an if-then-else statement:
We have seen how this statement works, it follows the logical structure we saw in our flowcharts:
Finding ways to use this structure is a fairly simple process - any time you need to ask a question, you will end up using this structure. The big problem is How do we ask questions?
All questions in programming take the form of Logical Expressions that end up delivering a true or false answer. The question (logical expression) is evaluated as part of a decision block and control of the program follows the path indicated by the answer. We cannot go through both paths!
So how do we form Logical Expressions?
Logical Operators¶
There are a number of obvious and a few not-so-obvious operators used to form our questions. Here they are:
- < less than
- <= Less than or equal
- > greater than
- >= greater than or equal
- == equal to
- != Not equal to
Here are the diagrams we need to finish off our if-then-else statement rules:
We call these operators Relational Operators because they evaluate two things to see what relationship they have to each other.
These operators are used between two operands which is just a fancy name for some value or variable on either side of the operator. What causes confusion when you first start learning about these logical expressions is that those operands on both sides of the operator can be the familiar numerical expressions we have used earlier. Phew!! Let’s work on that part later. For now, we will keep the operands simple.
Typical Questions¶
if (counter == 3){ cout << "We hit 3!" << endl; }
The logical expression compares the two values on either side of the operator, then - based on the operator – decides if the answer is true or false. In the case of the selection statement above, the current value stored in the variable counter is compared to the value 3 and if they are equal at that moment, the expression evaluates to true, otherwise it evaluates to false.
Using Variables in expressions¶
We have shown how to set up variables in previous examples. You must declare them, and tell the system what kind of data you plan to place in them. When the system sees a variable in an expression, it simply looks up the value stored in that variable at that moment and uses that value in the calculations it is doing. In our simple numerical expressions, the system was performing math, in our logical expressions it is performing comparisons.
More Complex Logical Expressions¶
Suppose you want to know if a value falls between two other values.
For instance, suppose I want to assign a letter grade based on a test score. How would I go about doing that?
Nested If Statements¶
Well, based on what we know at the moment, we could use nested if-then-else statements:
int score = 92; if (score >= 90) { cout << "Your grade was 'A'" << endl; } else { if(score >= 80) { cout << "Your grade was 'B'" << endl; } }
You can see how to complete this. When you set up complicated questions like this, you need to think through all the possible cases to make sure your questions will work the way you expect. In ordering the questions as we have above, we start by looking for grades greater than or equal to 90. Then (if the grade is below 90), we look for those above or equal to 80. This will catch all grades between 80 and 89 (see why?). We know the value is not 90 or above because that value would have already been caught by the first part of this question.
If we want to ask more complex questions, we need to introduce two more logical operators:
- && AND
- || OR
These operators allow us to combine smaller logical expressions into a more complicated question. The operands on either side of these operators must evaluate to true or false values. The result of combining the se values with the AND or OR operators can be seen in a simple Truth Table form:
Here is the table for the AND operator (A && B):
We can see that we get a true result only if both A AND B are both true - so it kind of makes sense!
Here is the table for the OR operator (A OR B)
Here we get a true value if Either A or B is true - again it kind of makes sense!
Combining Questions¶
We can use these operators to ask more complex questions.
Is this value between one value and another value?
- if (value >= low && value <= high) …
Notice that we do NOT just write something like this:
- WRONG: if (value >= low && <= high) …
That would generate a syntax error. Do you see why - we have two operators in a row, and that is not allowed. So, we need to combine two simple logical expressions with the AND operator to get the result we are after.
More on nesting selections¶
Selection statements can get quite involved. You can use selections inside other selections to ask complex questions. The use of nested if statements is not a problem, except that if you use correct style, you end up indenting your code way over to the right, and that does not really help with the readability. Lets look at the nesting concept a bit, and see what is really happening:
Here are two simple if statements in a sequence:
if(grade >= 90 && grade <= 100) { cout << "Grade is 'A'" << endl; } if(grade >= 80 && grade < 90) { cout << Grade is 'B'" << endl; }
Is there anything wrong with this?
Not really, the code will work as expected. However, the entire second logical expression will be evaluated by the system even if the first logical expression evaluates to true! We are wasting time, and could mess things up if we get our logical expressions confused.
The solution to these problems is to nest the statements:
if(grade >= 90 && grade <= 100) { cout << "Grade is 'A'" << endl; } else { if(grade >= 80) { cout << Grade is 'B'" << endl; } }
Now you see the inner if statement indenting a bit. In this example, the second logical expression will not even be evaluated if the first expression results in a true - so we are making the program more efficient. Notice that I do not even need to check if the grade is less than 90 since all grades of 90 or better were captured by the first expression.
We can solve the style problem by making use on a new fact about this expression.
So far, every time we have written an if statement, we have used curly braces around the entire true statement set and false statement set. However, the rules for the language let us omit those braces if we only want one statement in that part! So, we can rewrite the above example this way:
if(grade >= 90 && grade <= 100) cout << "Grade is 'A'" << endl; else if(grade >= 80) cout << Grade is 'B'" << endl;
We are still indenting, but we have gotten rid of a bunch of braces. Now, change the style a bit and we have a better solution:
if(grade >= 90 && grade <= 100) cout << "Grade is 'A'" << endl; else if(grade >= 80) cout << Grade is 'B'" << endl;
Now, we have eliminated the indenting, and we can add as many sections as we like. We are still free to have more than one thing happen in each section, but we need to add in the braces if we do:
if(grade >= 90 && grade <= 100) cout << "Grade is 'A'" << endl; else if(grade >= 80) { cout << " Score was " << grade << endl; cout << Grade is 'B'" << endl; }
Careful use of this kind of style will make the code easier to read (and write!)
Building a useful program¶
Take a deep breath, we are going to dive into C++ programming pretty deeply in what follows. Read through this material first. I will talk you through a complete program in pieces. We will build some code, then test it out to see what happens. I will try to explain the thinking going on during this process. You should fire up Dev-C++ and try the code yourself. Nothing beats experimenting with this new thing called programming. As you gain confidence in what you are doing, feel free to cut and paste code fragments and build your own version of the examples.
Let’s try to build a useful program. We want to see if we really are getting a good deal when we buy a car and get “Money Back”, or a good loan rate. (I want both!)
Here is the problem we will explore here:
Car Loan Decisions¶
Suppose you have picked out a car and arrived at a selling price. The salesman offers you “Cash Back” if you buy the car at one loan rate, or no cash but a better loan rate. Which way should you go.
We want to play with the numbers a bit, so we want to allow the user to enter several sets of data to compare the various situations.
Breaking it down¶
Where do we start?
First, let’s identify the information we need:
- Car selling price
- Amount of cash back offered
- Loan interest rate and months
- No cash loan interest rate and months.
- We also need a formula to see how much the car will cost us per month.
I Googled this problem and came up with this link:
And, here is the formula - it is a bit complicated and involves a magic operation we will learn about soon - the Power Function:
Let: P be the amount borrowed N = the number of years for the loan I = the interest rate (as a fraction - 11% = 0.11) M is the monthly payment M = P * I / ( 12 * (1 - pow(1 + (I/12),(-N * 12))))
As an example, suppose we borrow $12000 for 4 years at 11%. The monthly payment would be:
- 12000 * 0.11 /(12 * (1 - pow(1 + (0.11/12),(-4*12))))
Here, the pow(a,b) function gives the result of raising a to the b power. In our sample problem, both a and b are expressions. We will make this clearer once we talk about functions in the course - for now, trust me, it will work as we need it to.
All of this messy formula is something you should have worked through in your math class. And financial formulas are as messy as any! We just have to trust the formula, and let the computer do it’s thing. It sure beats running the formula through your calculator!
If we do it right, the sample loan gives a result of $310.15. Let’s code this part up and see if we can get it to work.
Floating point data¶
For this problem, we need to use floating point data. Remember that this kind of data is just a number encoded in such a way that it can have a fractional part. For our calculations here, we will use a high precision floating point number called double. This is another of the built-in data types that C++ knows about - the more bits used to encode the numbers, the better the accuracy of the calculations. Here is a code fragment to calculate the monthly payment:
#include <cmath> ... double P = 12000.00; double I = 0.11; double N = 4.0; double M; M = P * I / (12 * (1 - pow(1 + (I/12),(-N * 12)))); cout << "Monthly payment = " << M << endl;
That #include line makes it possible for us to use those magic math functions we need for this problem. We have seen this before!
Note
All C++ programs start off with a basic structure you have already seen - the empty code produced by Dev-C++ when you start a new project. To make this fragment work, you start a new project and add this fragment to the code. The #include part goes after the existing #include <iostream> line, and the rest of the fragment goes inside the curly brackets that make up the main part of the code. The compiler will tell you when you get it right! (Do not include the “…” line.)
Does it work? Let’s see:
Monthly payment = 310.146 Press any key to continue . . .
For now, we will not worry about the actual number being a weird fraction.
It works!
What we just did was a research project to make sure we had all the information we needed to solve this problem, and we knew what to do with that information. The website showed us a complex formula, that we needed to test to see if we could get good results. So, we coded up a little test program and tried it out - working with it until we got the right answer to a test problem found on the website. With that done, we feel confident that we can proceed!
Getting started - setting up the loop¶
Since we want the user to be able to try a bunch of options, we will need to set up a loop for the program. We will ask the user for some information, and use something called a sentinel value to control bailing out of the loop:
Here is what it looks like as a flow chart:
Do you see how we use a special value to bail out of the loop. You cannot borrow negative money, so we let the user enter a negative loan amount to get out of the loop.
We can translate this diagram into C++ as follows:
double P = 1.0; while(p > 0) { cout << "Enter the loan amount:"; cin >> P; cout << "process the loan for " << P << endl; }
Do you see a problem with this translation? The code is not exactly like the diagram. I cheated and started off by initializing the value of the variable P in the declaration and used this starting value to make sure I start the loop. We get the real first value from the user once we get things going. This is one way to start the loop, but maybe not the best. In any case, once we get into the actual loop, it works like we want.
This fragment shows how to get information from the user. We have been using a similar statement to display things on the screen using that cout name and the double ** << ** brackets. Here, we use the cin name and the double ** >> ** brackets to get user data from the keyboard into the variable named P in this example. (You might ask if the name P is a good one - not really, but the name does match that formula we found earlier!) Assuming the user does what we ask on the prompt we write out before the input line, whatever the user types will be loaded into our variable for the program to use from that point.
This tiny fragment is enough to test our program logic and see if it works:
Enter a loan amount:10000 Processing loan for 10000 Enter a loan amount:20000 Processing loan for 20000 Enter a loan amount:30000 Processing loan for 30000 Enter a loan amount:-1 Processing loan for -1 Press any key to continue . . .
Well, it works, but I probably do not want to process the loan for the negative amount. Could I rework this code to make it better? Let’s try:
First, notice that we want the user to enter a loan amount even to stop the program. Why don’t we get the first value outside the loop, then again inside the loop? Like this:
cout << "Enter a loan amount:"; cin >> P; while (P > 0) { cout << "Processing loan for " << P <<endl; cout << "Enter a loan amount:"; cin >> P; }
I had to code up the prompt twice, but the program works better!
Which gives this:
Enter a loan amount:100 Processing loan for 100 Enter a loan amount:200 Processing loan for 200 Enter a loan amount:-1 Press any key to continue . . .
Wait a minute, look back at the flowchart I constructed earlier. In fact, that chart matches the code we just created better than the first try. Hmmm, maybe I was smarter than I thought - or I just was not careful when I translated my diagram into code!
Adding in the Monthly Payment calculation¶
In order to move forward, we now need more data from the user. Specifically, we need the number of years (N) and the interest rate (I). Let’s add that in:
cout << "Enter a loan amount:"; cin >> P; while (P > 0) { cout << "Enter the number of years for this loan:"; cin >> N; cout << "Enter the interest rate as a fraction":; cin >> I; cout << "Processing loan for " << P <<endl; M = P * I / (12 * (1 - pow(1 + (I/12),(-N * 12)))); cout << "Monthly payment = " << M << endl; cout << "Enter a loan amount:"; cin >> P; }
Now, that pow function is a bit messy. Look back at how it was defined - pow(a,b). Where we see the names a and b, we are actually putting in expressions from our formula to figure out the right values to send into the function. Don’t worry about what is happening here, we are doing the same things you could do with your calculator, figuring out values and pushing function keys to figure out things!
Running our test case shows that this works:
Enter a loan amount:12000 Enter the number of years for this loan:4 Enter the interest rate as a fraction:0.11 Processing loan for 12000 Monthly payment = 310.146 Enter a loan amount:
Computing total cost of the loan¶
Next, let’s see how much all the payments add up to. This is an easy step, since all we need to do is a simple multiplication:
double total_cost; ... total_cost = N * 12 * M; cout << "This loan will cost you " << total_cost << endl; cout << " (" << total_cost - P << " in interest!)" << endl;
Please be careful here, I have had students type in the … stuff above and get confused when the compiler choked! That line means other stuff goes here, and you should be able to look back and figure what that stuff is.
If not, send me an email and I will help clear it up for you.
Enter a loan amount:12000 Enter the number of years for this loan:4 Enter the interest rate as a fraction:0.11 Processing loan for 12000 Monthly payment = 310.146 This loan will cost you 14887 (2887.02 in interest!) Enter a loan amount:
Well, the numbers do not look like money, but the answers are usable at this point.
Adding in cash back¶
At this point, we need to think about where we are trying to go, and modify our code to suit. Let’s add some comments into our code as to help keep track of what we want to do. A comment begins with the two characters // and extends to the end of that line:
// get the price of the car we are considering cout << "Enter a loan amount:"; cin >> P; while(P > 0) { // see how long we are going to pay for this car cout << "Enter the number of years for this loan:"; cin >> N; // get the no cash data cout << "Enter the interest rate as a fraction:"; cin >> I; // process the payment and total cost for this option cout << "Processing loan for " << P <<endl; M = P * I / (12 * (1 - pow(1 + (I/12),(-N * 12)))); cout << "Monthly payment = " << M << endl; total_cost = N * 12 * M; cout << "This loan will cost you " << total_cost << endl; cout << " (" << total_cost - P << " in interest!)" << endl; // get the cash back option // read the amount of cash back ( we will apply it to the loan) // get the new interest rate // process the cash back option cout << "Enter a loan amount:"; cin >> P; }
So far, we have developed the program to the point where we can figure out how much the car will cost for a basic loan. What remains is to add in the cash back option. In this exercise, we will use the cash back to buy down the loan. That means that instead of a new big-screen TV, we will apply the cash back to the car price and finance less money (that is what you would do - right?)
So, how do we proceed?
First, we need to get the data from the sales-droid. How much cash are we going to get back, and what will the interest be on the loan?
Here is some sample data for you to work with:
- Price for car: 20000
- Loan time: 5 years
- Cash back interest rate: 5%
- Cash back: 1500
- No cash interest rate: 1%
- Cash back payments: $349
- No cash back payment: $342
- Total price with cash back: $20947
- Total price no cash: $ 20512
Our work involves replacing the comments with actual code.
Here is code to get the additional data from the user:
double cash_back, cash_back_interest; ... cout << "How much cash back will you get?:"; cin >> cash_back; cout << "What is the normal interest rate?:"; cin >> cash_back_interest;
Now, we can finish off by calculating the new payment and total cost:
double M2; ... P = P - cash_back; I = cash_back_interest; M = P * I / (12 * (1 - pow(1 + (I/12),(-N * 12)))); total_cost2 = M * 12 * N; cout << "Your cash back payment will be: " << M << endl; cout << "This loan will cost you " << total_cost2 << endl; cout << " (" << total_cost2 - P << " in interest!)" << endl;
Notice that we lowered the amount we need to finance by the amount of the cash back. In order to reuse a complicated line of code, I also copied the cash back interest rate into the I variable so the original formula would still work.
All that remains is to see which way is smarter - cash or no cash!
if (total_cost > total_cost2) { cout << "Skip the cash!" << endl; } else { cout << "Take the cash!" << endl; }
And we have a useful tool!
But it is ugly!
As programs go, this one is OK, but could use some cleaning up. Here is the total program as we now have it:
#include <cstdlib> #include <iostream> #include <cmath> using namespace std; int main(int argc, char *argv[]) { double P; double I; double N; double M; double total_cost, total_cost2; double cash_back, cash_back_interest; // get the loop started cout << "Enter a loan amount:"; cin >> P; while(P > 0) { // get the length of the loan in years cout << "Enter the number of years for this loan:"; cin >> N; // now, get the interest rate as a fraction (11% is 0.11) cout << "Enter the interest rate as a fraction:"; cin >> I; // process the basic loan to get the payments cout << "Processing loan for " << P <<endl; M = P * I / (12 * (1 - pow(1 + (I/12),(-N * 12)))); cout << "Monthly payment = " << M << endl; // now compute the total cose total_cost = N * 12 * M; cout << "This loan will cost you " << total_cost << endl; // see how much cash back we are being offered cout << " (" << total_cost - P << " in interest!)" << endl; cout << "How much cash back will you get?:"; cin >> cash_back; // see what the cash back interest rate is cout << "What is the new cash back interest rate?:"; cin >> cash_back_interest; P = P - cash_back; I = cash_back_interest; // figure out the new payment and total cost M = P * I / (12 * (1 - pow(1 + (I/12),(-N * 12)))); total_cost2 = M * 12 * N; cout << "Your cash back payment will be: " << M << endl; cout << "This loan will cost you " << total_cost2 << endl; cout << " (" << total_cost2 - P << " in interest!)" << endl; // now figure out the best deal if (total_cost2 > total_cost) { cout << "Skip the cash!" << endl; } else { cout << "Take the cash!" << endl; } cout << "Enter a loan amount:"; cin >> P; } //cout << "Monthly payment = " << M << endl; system("PAUSE"); return EXIT_SUCCESS; }
Now, we talked our way through this code as we wrote it all down. Actually, if you look at the comments, you see that we are capturing our thinking (talking) as comments in the code to make it clearer what is going on.
Are we done yet? Not quite. One problem remains. The quick and dirty names I chose for the variables are not that clear. While short names are nice when typing stuff in, they can be a pain over the life of the program since they may not be that clear. Let’s rename a few things so the names we are using more properly indicate what is going on, and modify the output to make it neater:
#include <cstdlib> #include <iostream> #include <cmath> using namespace std; int main(int argc, char *argv[]) { // Define the variables we need here double car_price; double loan_years; double no_cash_interest, cash_back_interest; double cash_back; double monthly_payment; double no_cash_cost, cash_back_cost; // Get the first loan amount to start the loop cout << "Enter a loan amount (negative to quit):"; cin >> car_price; // repeat the analysis for each loan the user is considering while(car_price > 0) { cout << "Processing loan for " << car_price <<endl; // how long will the loan be for? cout << "Enter the number of years for this loan:"; cin >> loan_years; // Part 1 - no cash back option (need an interest rate) cout << "Enter the interest rate as a fraction:"; cin >> no_cash_interest; // do the no cash back calculations monthly_payment = car_price * no_cash_interest / (12 * (1 - pow(1 + (no_cash_interest/12),(-loan_years * 12)))); no_cash_cost = loan_years * 12 * monthly_payment; // show the results cout << "No cash back option results:" << endl; cout << " Monthly payment = " << monthly_payment << endl; cout << " This loan will cost you " << no_cash_cost; cout << " (" << no_cash_cost - car_price << " in interest!)" << endl; // Part 2 - Cash back option (Need interest and cash amount) cout << endl << "How much cash back will you get?:"; cin >> cash_back; cout << "What is the cash back interest rate?:"; cin >> cash_back_interest; // do the cash back calculations car_price = car_price - cash_back; monthly_payment = car_price * cash_back_interest / (12 * (1 - pow(1 + (cash_back_interest/12),(-loan_years * 12)))); cash_back_cost = monthly_payment * 12 * loan_years; // Show the cash back results cout << "Cash back option results:" << endl; cout << " Your cash back payment will be: " << monthly_payment << endl; cout << " This loan will cost you " << cash_back_cost; cout << " (" << cash_back_cost - car_price << " in interest!)" << endl; // show which option is best cout << "My recommendation: " if (cash_back_cost > no_cash_cost) { cout << "Skip the cash!" << endl; } else { cout << "Take the cash!" << endl; } cout << "Enter a loan amount (negative to quit):"; cin >> car_price; } // pause the program on exit system("PAUSE"); return EXIT_SUCCESS; }
Notice that I have sprinkled a few extra endl items into my output to space things out a bit, and I have indented some of the output - all to make the program more usable.
Here is the final output - neater now!
Enter a loan amount (negative to quit):20000 Processing loan for 20000 Enter the number of years for this loan:5 Enter the interest rate as a fraction:0.01 No cash back option results: Monthly payment = 341.875 This loan will cost you 20512.5 (512.497 in interest!) How much cash back will you get?:1500 What is the cash back interest rate?:0.05 Cash back option results: Your cash back payment will be: 349.118 This loan will cost you 20947.1 (2447.07 in interest!) My recommendation: Skip the cash! Enter a loan amount (negative to quit):
That should do it! | http://www.co-pylit.org/courses/cosc1315/statements/01-selection-operations.html | CC-MAIN-2018-17 | refinedweb | 4,505 | 75.64 |
Important: Please read the Qt Code of Conduct -
Database class
Hi I am trying to use QSqlDatabase, but I am getting build errors and QTCreator doesn't seem to know that QSqlDatabase exists? The IDE is not even auto-completing my typing, etc.
Running build steps for project app13_sqlite3...
Configuration unchanged, skipping qmake step.
Starting: "/usr/bin/make" -w
make: Entering directory `/home/yadav/dev/cpp/QT_Samples/app13_sqlite3-build-desktop'
g++ -c -pipe -g -Wall -W -D_REENTRANT -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/usr/share/qt4/mkspecs/linux-g++ -I../app13_sqlite3 -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtGui -I/usr/include/qt4 -I. -I. -I../app13_sqlite3 -I. -o dialog.o ../app13_sqlite3/dialog.cpp
../app13_sqlite3/dialog.cpp:4: fatal error: QSqlDatabase: No such file or directory
compilation terminated.
- DenisKormalev last edited by
Try to add
@
QT += sql
@
to your project file
still getting the same error, btw where do i add that? to the project setting -> build steps -> additional arguments ??
also I can't even navigate to QSqlDatabase.h ? using follow symbol under cursor from the IDE, is there something wrong. should this not work with a default SDK install
ok i figured it out, I needed to
#include <QtSql/QSqlDatabase>
rather than
#include <QSqlDatabase>
- DenisKormalev last edited by
You have .pro file in your project tree. Just add stuff I've said you there and all will be ok.
thanks again, that helped me figure out where to also add the linker stuff so my exe would run without an error
LIBS += -lsqlite3
You don't need to add that lib. It is already linked against the Qt SQLite plugin.
Andre thanks, didn't know that, removed the explicit linkage. | https://forum.qt.io/topic/3530/database-class | CC-MAIN-2020-34 | refinedweb | 281 | 57.16 |
My teacher wants me to write a function called can use the function pos_power() in your exponent.c from Lab 6 and Hw 4,.
So I wrote my driver1.c file:
#include<stdio.h> #include"util.c" #include "exponent.c" main() { int fact; int answer; printf("Enter a degree:\n"); scanf("%d", &fact); answer=factorial(fact); printf(" cos of %d degree is:%d\n", fact, answer); }
My util.c file:
#include<stdio.h> int factorial(float fact); int close_enough(float num1, float num2); int factorial(float fact) { float total; total=fact*(fact-1); while(fact>2) { fact=fact-1; total=total*(fact-1); } return(total); } int close_enough(float num1, float num2) { if(num1-num2 >=0.00005) {return 0;} else {return 1;} }
My trig.c file:
#include<stdio.h> #define PI 3.14 int cos(float x); { float answer; printf("Enter an angle to compute:"); while(scanf("%d, &x)==1) { answer=(x*PI)/180; } printf("The cosine of %d is %d.\n", x, answer); }
And lastly my exponent.c file:
#include<stdio.h> #include"exponent.h" /* #define DEBUG */ /* Declaration */ float pos_power(float base, int exponent) { float num; float e; num=base; e=exponent; float value; value=1; int power; power=1; if(e<0) /* Math rules */ {return 0;} if(e == 0) {return 1;} #ifdef DEBUF /* Function */ printf("debuf: Enter pos_power: base = %f exponent= %d\n", base, exponent); #endif while (power<=e) /* Condition */ { power=power+1; /* Controls how many times the function loops */ value=value*base; } #ifdef DEBUG /* If the first function is executed */ printf("debug:Exit pos_power: result = %4.9f\n", value); #endif return value; }
The thing is I know I need to put the function double cos(float) in the trig.c file, but I don't know what to do with it when the function cos() is in there too. Plus, the angle needs to be calculated by the Taylor series which is cos(x)= 1 - x^2/2! + x^4/4! - x^6/6! ... My factorial (util.c) works, so is my exponent.c but how can I make it to be only even and just like in the Taylor series? And should I put the Taylor series in driver.c?
Please help me. | https://www.daniweb.com/programming/software-development/threads/439942/taylor-series-cosine-function-help-please | CC-MAIN-2018-13 | refinedweb | 366 | 59.09 |
.event;31 32 import java.util.EventObject ;33 34 import nextapp.echo2.app.table.TableColumnModel;35 36 /**37 * An event which describes an update to a <code>TableColumnModel</code>38 */39 public class TableColumnModelEvent extends EventObject {40 41 private int fromIndex;42 private int toIndex;43 44 /**45 * Creates a new <code>TableColumnModelEvent</code>.46 *47 * @param source the updated <code>TableColumnModel</code>.48 * @param fromIndex the index from which the column was moved or removed49 * (relevant to remove and move operations)50 * @param toIndex the index to which the column was moved or added 51 * (relevant to move and add operations)52 */53 public TableColumnModelEvent(TableColumnModel source, int fromIndex, int toIndex) {54 super(source);55 this.fromIndex = fromIndex;56 this.toIndex = toIndex;57 }58 59 /**60 * Returns the index from which the column was moved or removed.61 * This method is only relevant to remove and move operations.62 *63 * @return the index from which the column was moved or removed64 */65 public int getFromIndex() {66 return fromIndex;67 }68 69 /**70 * Returns the index to which the column was moved or added.71 * This method is only relevant to move and add operations.72 *73 * @return the index to which the column was moved or added74 */75 public int getToIndex() {76 return toIndex;77 }78 }
Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ | | http://kickjava.com/src/nextapp/echo2/app/event/TableColumnModelEvent.java.htm | CC-MAIN-2016-44 | refinedweb | 232 | 54.73 |
Top 10 Funniest South Park Episodes
What exactly are the TOP 10 South Park episodes? Many have been on a long and epic search to find this information. But good news, my friends. If you are on of these people, then your search is finally over. For I have created a list for you.
The top 10 funniest episodes are:
1. The imagination land series. This is actually 3 episodes, but the whole thing is definitely the funniest one out there. It makes fun of almost every cartoon you can imagine.
2. Night of the Living Homeless. In this episode, homeless people overtake southpark. It is up to the survivors to put a stop to it.
3. About Last Night. The Funniest political episode ever! I won't ruin it, but lets just say that Obama, McCain, and Sarah Palin are all in on a secret plan together...
4. Make Love, Not Warcraft. This episode is a must-see for world of warcraft fans. The boys become addicted Warcraft, and decide to defeat the top player for good.
5.Mystery of the Urinal Deuce. Someone takes a crap in a urinal, and Mr. Mackey hires the Hardy Boys to find out who did it...
6. Major Boobage. A new drug is sweeping southpark, which is sniffing cat urine. Kenny bcomes addicted to the drug, along with another certain dad...
7. Overlogging. The internet goes down all over the United States, and Stan's dad goes on a quest to use the internet to look at porn.
8. The Return of Chef. Chef leaves for the adventure club, and comes back as a new man. The boys have to go and discover what happened while he was gone.
9. Something Wall-Mart comes this way. Wall Mart comes to southpark, and it buys out all the other businesses. Not only does it take over South Park, but also people's souls.
10. Cartmans incredible gift. Cartman tries to jump off a roof with cardboard wings, and ends up in the hospital. But when he gets out, he discovers that he has psychic powers.
While all these episodes are very funny, you may have noticed that most of them are newer. The classics such as Starvin Marvin, Cat Orgy, and Timmy 2000 will be remembered forever by South Park fans.
Now that you have read this list, head over to this site and watch the full episodes for free!
- South Park Studios
Watch every episode of South Park for free and get news straight from the studio at the official site for television series. South Park is an Emmy and Peabody award winning animated television series created by Trey Parker and Matt Stone
Obliviously you haven't been watching South Park long because the new episodes aren't really that funny. Ones like Cartman Joins Nambla, Butter's Very Own Episode, Goobacks and Timmy 2000 are way better and didn't even make your list.
I believe the general audience agrees with Ryan. There are only a few new episodes that can compete with the old ones.
not without my anus. terrence and phillip special is hilarious
butters bottom bitch is a must see
What about Scott Tenorman must die??? Hahahahhahs I made u eat ur parents lol
Ya well you havn't really been watching South Park very long. I think Ginger Kids, Casa Bonita, Awesome-O, Jennifer Lopez, Nambla and the LOTR episodes were brilliant.
def the old ones are the funniest, starvin marvin, the mongolian episodes, cat orgy episode, hilarious
Those are pretty good, but what about "Cartman sucks" and "The biggest douche in the universe"? And I totally love "Chef goes nanners". Well, I guess we're all different with different opinions (but still, my opinion is the right one) :D
PS. To all retarded people out there: I was NOT being serious. Everyone's opinion is worth listen to, peace on earth, little puppies yada yada yada :D DS
Ginger Kids is at least top 5
I love Butters Bottom Bitch, When Cartman was the robot, Ginger kids and the Jennifer lopez episode the most.
I gotta say, I'm not a die-hard fan but I haven't seen most of the ones on this list.
-
Love: Goobacks, Butter's Own Episode, How to Eat With Your Butt, Proper Condom Use, Summer Sucks, The Terrance and Phillip's Movie Trailer, Red Hot Catholic Love, Guitar Queer-O, Asspen... I could really keep going.
This is just my opinion but I feel Scott Tenorman Must Die is overrated. Great first couple of times through but gets too much credit. I also feel A Million Little Fibers gets a bad rep. Stupid? yes. But I find it hilarious.
awesome-o
butters very own episode
what about miss teacher bangs a boy? that is the fuinniest shit of all time...NICE!
this list is actually pretty good, i meen with the exeptional absence of 'Nambla' and 'utters own episode,'
but seriously where is 'Medicinal Fried chicken' its fucking halarious. xxx
i just watched the night of the living homeless and i must say that gingers and medicinal fried chicken was a lot funnier. in other words, i don't think that it should be on a top 10 list. [my opinion, of course. ;)]
Imaginationland and Make Love Not War Craft are a couple of my favorites, but I have to say I like more of the old episodes better
I find marjorine incredibly funny, probably because of the pet cemetery reference
Also, pandemic is good
What about Casa Bonita? It's my fave. There r a few good new ones like "W.T.F" and "Make Love Not Warcraft". The best old one is the one with the creatures who want their antichrist. i think its in season 2 not sure.
this is a really really shitty list and you got the name wrong on the walmart episode
Guys, one of the best is the first towlie episodes. When he plays funkytown I cried laughing so hard. Another is the super just friends episode...how do u kill a giant stone abe lincoln, ahh, hmm, a giant stone john wilks booth hahahahaha classic
Goobacks is probably my favorite. The one about Wal-Mart is very underrated. If you want to go back to the very early ones, check out Ike's briss. Mr. Mackey goes on a drug binge, absolutely hilarious.
Good times with weapons! LOL
-
this list is terrible
This list just means this guy has never watched any of the older episodes otherwise he would be dumb enough to make a list with all mediocre (except four and five which would make top fifteen) and I've read some great episodes but what about korns groovy pirate ghost mystery?
"I spy with my little eye something that starts with the letter r" "ra-r-road?" "that's right!"
"now I spy with my little eye something that starts with the letter p" "I don't know johnathon, what?" "PA-PA-PA-PIRATE GHOST!!!"
Pick any episode from Season 8 and you're gold. Mr Jefferson, Passion of the Jew, Goobacks, Walmart, AWESOME-O, Evil Woodland Critter Christmas, Cartman's Incredible Gift, and my personal favorite: Good Times with Weapons.
my favories is the death of eric cartman
Season 14 is the best.
I like the most "Make war, not Warcraft" episode, watched it like 3 times already.
ummm Tsst! is hilarious!!! i was literally laughing out loud. and Proper Condom Use was just brilliant
In my opinion I think the new episodes are hilarious they are on Netflix and wow freaking funny like shit!!!! Especially the "its a jersey thing" one is hilarious
the funniest episodes are 1. mrs teacher bangs a boy 2. pandmic 1 & 2 3. tsst 4. T.M.I. 5. Make love not war craft 6. crack baby athletic association 7. scott tenromen must die 8. its a jersey thing 9. death of eric cartman 10. W.T.F, THE LIST IS NOT IN ORDER THESE ARE MY FAV EPISODES
My favorite is Le petite terett or what ever. That one had me tripin' balls!! Haha
Who can forget the Chicken F*****r episode!!! That's a classic! Best episode may have to be "Fightin' round the world", cant believe no one mentioned that one.
Mystery of the Urinal Deuce hands down funniest of all... Just listening to the principal repeat the question of why would anyone do such a thing is some funny sh*t
Cartmanland is clearly the best
Classics: Awesome-o, Asspen, Medical FC, Lord of the rings, casa bonita, fatbutt pancake hand(Lopez), Towlie, north american marlon brando look alikes, scott tenorman is overrated but genius writing, mr jefferson, buter very own epsiode, cartmans gift, over logging, butters bottom bitch
Personal Gems: The red badge of gayness, two days before the day after tomorrow, million little fibers, royal pudding, trapped in the closet, 200, 201, miss teacher bangs boy, eek a penis, proper condom use, going native, lil crime stoppers, die hippie die, losing edge, pinewood derby, mc booger balls and thats only scratching the surface!
Imagination land and Coon episodes are great as well favorite seasons14 and 8
38 | https://hubpages.com/entertainment/Top-10-Funniest-South-Park-Episodes | CC-MAIN-2017-22 | refinedweb | 1,541 | 82.04 |
My understanding is that matrix dot product between two 2x2 matrices will result in another 2x2 matrix.
However, the DotProduct example in Lesson 5 results in 2 element vector.
a = T([[1.,2],[3,4]])
b = T([[2.,2],[10,10]])
(a*b).sum(1)
Result:
6
70
[torch.FloatTensor of size 2]
The code example uses (a*b).len(1) to compute Dot Product:
class DotProduct(nn.Module):
def forward(self, u, m): return (u*m).sum(1)
Shouldn’t it be
[a b]. [w x] = [aw+by ax+bz]
[c d] [y z] [cw+dy cx+dz]
or in numpy: np.dot(a, b) resulting in:
array([[ 2., 4.],
[30., 40.]]) | https://forums.fast.ai/t/lesson-5-dotproduct/9772 | CC-MAIN-2018-51 | refinedweb | 113 | 62.85 |
Linux
The "Linux" sub-platform of the Island target lets you build CPU-native libraries and executables for Linux using the low-level Posix API and compiles as CPU-native x64 code.
Available APIs:
- Linux/Posix C-Level API (glibc) in the
rtlnamespace. This includes everything from
fopen()to
printf()to let you create native Linux apps
- Island RTL
- Elements RTL
- Delphi RTL
- Swift Base Library (mainly for use with Swift)
- Gtk
- SQLite
Of course any other custom, third party or open source C APIs can be imported using FXGen.
Development, Deployment and Debugging
Development of Island apps for Linux is supported in both Visual Studio and in Fire on the Mac. They can be deployed to any 32-bit or 64-bit Windows version.
Native debugging is supported in Visual Studio and Fire. To remote-debug Linux apps, you will need CrossBox 2 and an open SSH connection to your Linux PC or VM. | https://docs.elementscompiler.com/Platforms/Island/Linux/ | CC-MAIN-2018-51 | refinedweb | 155 | 59.03 |
IRC log of sml on 2008-11-06
Timestamps are in UTC.
19:02:03 [RRSAgent]
RRSAgent has joined #sml
19:02:03 [RRSAgent]
logging to
19:02:06 [Kirk]
invite rrsagent
19:02:12 [MSM]
Kirk, you need a leading slash
19:02:24 [MSM]
so: /invite ... (but someone already invited RRSAgent)
19:02:33 [Kumar]
Kumar has joined #sml
19:03:03 [Zakim]
+ +1.425.836.aabb
19:03:06 [Kirk]
meeting: W3C SML Teleconference Call
19:03:13 [Kumar]
zakim, aabb is me
19:03:13 [Zakim]
+Kumar; got it
19:03:23 [Kirk]
chair: John Arwe
19:03:31 [Kirk]
scribe: Kirk Wilson
19:03:38 [Kirk]
scribenick: Kirk
19:04:50 [Kirk]
regrets: Ginny (first hour)
19:05:08 [johnarwe_]
Agenda:
19:05:34 [Kirk]
rrsagent, make log public
19:06:10 [Kirk]
TOPIC: Approval of minutes from F2F
19:06:16 [johnarwe_]
19:06:43 [johnarwe_]
19:06:54 [Kirk]
RESOLUTION: Minutes of 10/27 accepted as record of meeting
19:07:06 [johnarwe_]
19:07:10 [Kirk]
RESOLUTION: Minutes of 10/28 accepted as record of meeting
19:07:24 [Kirk]
RESOLUTION: Minutes of 10/29 accept as record of meeting.
19:07:52 [Kirk]
TOPIC: Communications from CG
19:08:17 [Kirk]
John: CG tentatively approved week of 02/23/2009 for next set of F2F.
19:08:54 [Kirk]
Jonh: The WG will decide if we need to meet at this time.
19:09:04 [Kirk]
TOPIC: Action Items
19:09:32 [Kirk]
Test case for lax fallback
19:10:06 [Kirk]
MSM: Working on it, but status as not changed.
19:10:20 [Kirk]
Draft namespace policy document
19:10:43 [Kirk]
John: We need to put a realistic date on this.
19:11:17 [Kirk]
MSM: Not clear that there is a clear deadline for this. CR publication date will be a good target.
19:12:52 [johnarwe_]
19:13:53 [Kirk]
John: Kumar should enter the URL in the action. Target date should be last Thursday that Kumar will be here.
19:14:44 [Kirk]
...We will assign Action to someone else if Kumar does not complete it at that time.
19:15:50 [lencharest]
lencharest has joined #sml
19:16:01 [Kirk]
John: Also open: Action 184 on Pratul to draft the XLink Note. John will close this action item
19:16:43 [Kirk]
TOPIC: CR Request
19:17:28 [Kirk]
John: Request need to be sent one week before meeting. Request was posted this morning.
19:17:55 [Kirk]
19:18:28 [Kirk]
Jonh: Date in the request is an estimate, no need to have team vote on this.
19:18:40 [Kirk]
TOPIC: Open Issues
19:19:18 [Kirk]
Issue 6011
19:19:22 [Kirk]
Schema 1.1 [baseURI] comments
19:20:03 [Kirk]
John: XML Schema group agreed to add [baseUR] to list of dependent properties.
19:20:31 [Kirk]
No objections from SML group to resolution proposed by XML Schema group.
19:20:53 [Kirk]
John updates the issue with SML WGs endorsement of this proposal.
19:21:03 [Kirk]
Issue 6056
19:21:37 [Kirk]
Propogation of identity constraints on substitution groups
19:22:29 [Kirk]
John: XML Schema WG does not plan to make SML proposal as part of 1.1 Proposes a resolution of LATER.
19:22:54 [Kirk]
No objections from SML group to resolution proposed by XML Schema group.
19:23:04 [Kirk]
....Kumar does not object.
19:23:33 [Kirk]
John updates the issue with SML WG's endorsement of this proposal.
19:24:01 [Kirk]
John: Acknowledge that Julia has left the group. (Kirk to update scribe list.)
19:24:22 [Kirk]
TOPIC: Open issue with no Keyword
19:24:25 [johnarwe_]
19:25:55 [Kirk]
John: Unclarity in the spec regarding a COSMOS test case. Does MS implementation read the text a different way?
19:29:40 [Kirk]
John: Issue is whether documentAliases are allowed to contain relative URIs.
19:30:51 [Kirk]
...Meaning of "URI prefix" in the spec--does it allow relative URIs
19:34:23 [johnarwe_]
smlif 5.4.2 defines rule binding, on rulealias defers to uri prefix matching (defined by smlif not by rfc3986)
19:34:43 .
19:35:18 [johnarwe_]
If we interpret URIs in that passage to mean "the URI production of RFC 3986" then it implicitly says the URIs are absolute
19:35:58 [johnarwe_]
(based on 3986 sections 3 and 4.1) in 3, URI production, scheme is required. in 4.1, a URI ref is defined as a URI or a relative ref
19:38:06
19:39:00 [lencharest]
lencharest has joined #sml
19:40:41 [Kirk]
Kumar: Actual conherent could be relative URI, absolutized via [baseURi]: therefore logical value is always an absolute URI.
19:41:00 [johnarwe_]
s/conherent/content/
19:41:36 [Kirk]
...Kumar: actual content of documentAlias / ruleAlias
19:41:42 [johnarwe_]
"actual content" refers to value of markup. comparison would be done after transformation to absolute URI.
19:47:27 [Kirk]
Kumar: Add in 5.4.2 a non-normative:
19:49:31 ].
19:51:43 ].
19:52:33 [johnarwe_]
(might also append to that draft): For example, if they are relative references then they would be transformed to absolute URIs before comparison.
19:52:58 .
19:55:06 [Kirk]
RESOLUTION: No objections to this proposal.
19:55:42 [Kirk]
John: Will paste text into the issue and change Keyword to "Editorial".
19:55:49 [Kirk]
...No review is required.
19:57:03 [Kirk]
Issue 6205:
19:57:10 [lencharest]
lencharest has joined #sml
19:57:36 [Kirk]
John: This was fixed by Ginny. No need to change SML-IF.
19:57:58 [Kirk]
RESOLUTION: No Objections to closing this as a duplicate of 6188.
19:59:00 [Kirk]
TOPIC: Issues: Non-editorial targetted for next draft
20:00:44 [Kirk]
Issue 5680:
20:02:04 [Kirk]
RESOLUTION: No objections to not taking any action on this.
20:02:25 [Kirk]
John: Wants to break out Comment #5 as a separate issue.
20:03:54 [Kirk]
...Issue from Yves's email.
20:04:35 [Kirk]
RESOLUTION: No objection to breaking Comment #5 into a separate issue.
20:05:00 [Kirk]
ACTION: John toopen issue based on Comment #5 in issue 5680.
20:05:00 [trackbot]
Created ACTION-204 - Toopen issue based on Comment #5 in issue 5680. [on John Arwe - due 2008-11-13].
20:05:36 [Kirk]
TOPIC: Assignment of person to take over XLink Technical Note.
20:06:16 [Kirk]
John: This means acting as an editor for this note.
20:06:45 [Kirk]
...Person needs to contact Henry on this note.
20:07:00 [lencharest]
lencharest has joined #sml
20:08:15 [Kirk]
Len: Will volunteer to do this. Kumar to show Len how to get CVS up and running.
20:08:44 [lencharest]
lencharest has joined #sml
20:09:00 [Kirk]
ACTION: Michael to set up Len for access to CVS.
20:09:00 [trackbot]
Created ACTION-205 - Set up Len for access to CVS. [on Michael Sperberg-McQueen - due 2008-11-13].
20:10:02 [Kirk]
TOPIC: Test Case Discussion Continued
20:11:02 [Kirk]
Features list (distributed by Kumar)
20:13:51 [Kirk]
Kumar: Will need to send out list of mapping of features to COSMOS test.
20:17:41 [Kirk]
Kirk and MSM are satisfied to have the team proceed without our exhaustive review of the test case. Kirk and MSM will bring up comments as they find appropriate in the future.
20:18:51 [Kirk]
TOPIC: Other items
20:19:31 [johnarwe_]
This document is also available in these non-normative formats: XML.
20:19:41 [johnarwe_]
links to
20:20:13 [Kirk]
Len: SML 1.1 reference to non-normative format. Only format is XML, but you don't get an XML document.
20:21:24 [Kirk]
Kumar: This is not an SML bugzilla issue.
20:21:32 [johnarwe_]
is MSM still listening?
20:22:13 [Zakim]
+MSM.a
20:22:15 [Kirk]
Kumar: Will send email to Web Admin to help us with this.
20:22:55 [Kirk]
Len: List of editorial minor editorial corrections.
20:23:44 [Kirk]
John: Easier in this case to open one bug to handle editorial issues.
20:24:02 [Kirk]
Len will open bug for these corrections.
20:24:09 [johnarwe_]
20:25:16 [Kirk]
Len: Issue re: sml:locid.
20:35:19 [Kirk]
MSM: We should not/cannot standardize on these issues. A human may be required to set up a model in another environment.
20:38:18 [Kirk]
rrsagent, generate minutes
20:38:18 [RRSAgent]
I have made the request to generate
Kirk
20:44:54 [MSM]
MSM has joined #sml
20:45:02 [Kirk]
MSM: Yes, it is a problem for interoperability. But we are not sure of the extent to which it is resolvable.
20:45:21 [Kirk]
...Len will not push the issue.
20:45:54 [Kirk]
John: Transition meeting schedule for one week from today in the morning.
20:46:42 [Kirk]
Adjournment: 3:47 pm ET.
20:46:44 [Zakim]
-Sandy
20:46:45 [Zakim]
-Kumar
20:46:48 [Zakim]
-MSM.a
20:46:49 [Zakim]
-[Microsoft]
20:46:49 [Zakim]
- +1.603.823.aaaa
20:46:50 [Zakim]
-JohnArwe
20:47:04 [Kirk]
rrsagent, generate minutes
20:47:04 [RRSAgent]
I have made the request to generate
Kirk
20:47:36 [Kirk]
rrsagent, make log public
20:50:43 [johnarwe_]
zakim, who was here?
20:50:43 [Zakim]
I don't understand your question, johnarwe_.
21:05:01 [Zakim]
disconnecting the lone participant, MSM, in XML_SMLWG()2:00PM
21:05:04 [Zakim]
XML_SMLWG()2:00PM has ended
21:05:05 [Zakim]
Attendees were [Microsoft], +1.603.823.aaaa, MSM, Sandy, JohnArwe, +1.425.836.aabb, Kumar
21:05:25 [Sandy]
rrsagent, generate minutes
21:05:25 [RRSAgent]
I have made the request to generate
Sandy
21:05:28 [johnarwe_]
aaaa was Kirk, aabb was Len
21:05:36 [johnarwe_]
johnarwe_ has left #sml | http://www.w3.org/2008/11/06-sml-irc | CC-MAIN-2017-17 | refinedweb | 1,678 | 73.58 |
Python: Converting a date string to timestamp
I've been playing around with Python over the last few days while cleaning up a data set and one thing I wanted to do was translate date strings into a timestamp.
I started with a date in this format:
date_text = "13SEP2014"
So the first step is to translate that into a Python date - the strftime section of the documentation is useful for figuring out which format code is needed:
import datetime date_text = "13SEP2014" date = datetime.datetime.strptime(date_text, "%d%b%Y") print(date)
$ python dates.py 2014-09-13 00:00:00
The next step was to translate that to a UNIX timestamp. I thought there might be a method or property on the Date object that I could access but I couldn't find one and so ended up using calendar to do the transformation:
import datetime import calendar date_text = "13SEP2014" date = datetime.datetime.strptime(date_text, "%d%b%Y") print(date) print(calendar.timegm(date.utctimetuple()))
$ python dates.py 2014-09-13 00:00:00 1410566400
It's not too tricky so hopefully I shall remember next time.
About the author
Mark Needham is a Developer Relations Engineer for Neo4j, the world's leading graph database. | https://markhneedham.com/blog/2014/10/20/python-converting-a-date-string-to-timestamp/ | CC-MAIN-2019-13 | refinedweb | 205 | 60.24 |
Hi!
My code is really different from the one on the walkthrough video.
It works this way. But the way Matt explained cheapest method got me confused, especially with $%.2f and % (cost, method). It was never explained in the course.
Hi!
Hello @faridsaryev421170057, welcome to the forums! The
% operator in this case is a type of string formatting operator (not to be confused with the modulo operator-which looks the same (
%), but is used for a different purpose). I would recommend reading this article on how it is used.
Your code for cheapest shipping method is wrong by the way.
If drone and ground has the same price you’ll end up saying premium is cheapest.
def cheapest_option(): ground = 3 premium = 1000 drone = 3 if ground < drone and ground < premium: print("Ground shipping is the better option for you! Your total cost is " + str(ground)) elif drone < ground and drone < premium: print("Drone shipping is the better option for you! Your total cost is " + str(drone)) else: print("Premuim ground shipping is the better option for you! Your total cost is " + str(premium)) cheapest_option()
This does happen at weight 3 + 1 / 3 (blue and orange lines crossing)
import matplotlib.pyplot as plot xs = [n / 10 for n in range(350)] plot.plot(xs, [drone_shipping_price(x) for x in xs], label="drone") plot.plot(xs, [ground_shipping_price(x) for x in xs], label="ground") plot.plot(xs, [125 for x in xs], label="premium") plot.legend() plot.show()
weight = 3 + 1 / 3 print('drone price:', drone_shipping_price(weight)) # 30.0 print('ground price:', ground_shipping_price(weight)) # 30.0 cheapest_option(weight) # 125.0 ... oops.
Thank you for your response!
Your link is really useful.
Thank you for your response!
But in this exercise is always given exact weight. Who would give 3+1/3 weight and for what?
And in that case what the difference between my “cheapest function” vs Matt’s “cheapest function”?
I didn’t understand anything from the last code you send.
P.S I have zero IT background.
This topic was automatically closed 41 days after the last reply. New replies are no longer allowed. | https://discuss.codecademy.com/t/sals-shipping/500050 | CC-MAIN-2020-40 | refinedweb | 354 | 77.94 |
Recovering FAT Directory Stubs with SleuthKit
By Silas Brown
When I accidentally dropped an old Windows Mobile PocketPC onto the floor at the exact moment it was writing to a memory card, the memory card's master FAT was corrupted and several directories disappeared from the root directory. Since it had not been backed up for some time, I connected the memory card to a Linux system for investigation. (At this point it is important not to actually mount the card. If you have an automounter, turn it off before connecting. You have to access it as a device, for example /dev/sdb1. To see which device it is, you can do ls /dev/sd* both before and after connecting it and see what appears. The following tools read from the device directly, or from an image of it copied using the dd command.)
fsck.vfat -r offered to return over 1 GB of data to the free space. This meant there was over 1 GB of data that was neither indexed in the FAT nor listed as free space, i.e. that was the lost directories. It was important not to let fsck.vfat mark it as free yet, as this would impair data recovery. fsck.vfat can also search this data for contiguous blocks and reclaim them as files, but that would not have been ideal either because the directory structure and all the filenames would have been lost, leaving thousands of meaninglessly-named files to be sorted out by hand (some of which may end up being split into more than one file).
The directory structure was in fact still there; only the entries for the top-level directories had been lost. The listings of their subdirectories (including all filenames etc) were still present somewhere on the disk, but the root directory was no longer saying where to find them. A few Google searches seemed to suggest that the orphaned directory listings are commonly known as "directory stubs" and I needed a program that could search the disk for lost directory stubs and restore them. Unfortunately such programs were not very common. The only one I found was a commercial one called CnW Recovery, but that requires administrator access to a Windows PC (which I do not have).
SleuthKit to the rescue
A useful utility is SleuthKit, available as a package on most distributions (apt-get install sleuthkit) or from sleuthkit.org. SleuthKit consists of several commands, the most useful of which are fls and icat. The fls command takes an image file (or device) and an inode number, and attempts to display the directory listing that is stored at that inode number (if there is one). This directory listing will show files and other directories, and the inode numbers where they are stored. The icat command also takes an image file and an inode number, and prints out the contents of the file stored at that inode number if there is one. Hence, if you know the inode number of the root directory, you can chase through a normal filesystem with fls commands (following the inode numbers of subdirectories etc) and use icat to access the files within them. fls also lists deleted entries (marked with a *) as long as those entries are still present in the FAT. (Incidentally, these tools also work on several other filesystems besides FAT, and they make them all look the same.)
The range of valid inode numbers can be obtained using SleuthKit's fsstat command. This tells you the root inode number (for example 2) and the maximum possible inode number (for example 60000000). fsstat will also give quite a lot of other information, so you may want to pipe its output through a pager such as more or less (i.e. type fsstat|more or fsstat|less) in order to catch the inode range near the beginning of the output.
Scanning for directory stubs
Because the root FAT had been corrupted, using fls on it did not reveal the inode locations of the lost directories. Therefore it was necessary to scan through all possible inode numbers in order to find them. This is a lot of work to do manually, so I wrote a Python script to call the necessary fls commands automatically. First it checks the root directory and all subdirectories for the locations of "known" files and directories, and then it scans all the other inodes to see if any of them contain directory listings that are not already known about. If it finds a lost directory listing, it will try to recover all the files and subdirectories in it with their correct names, although it cannot recover the name of the top-level directory it finds.
Sometimes it finds data that just happens to pass the validity check for a directory listing, but isn't. This results in it creating a "recovered" directory full of junk. But often it correctly recovers a lost directory.
image = "/dev/sdb1" recover_to = "/tmp/recovered" import os, commands, sys def is_valid_directory(inode): exitstatus,outtext = commands.getstatusoutput("fls -f fat "+image+" "+str(inode)+" 2>/dev/null") return (not exitstatus) and outtext def get_ls(inode): return commands.getoutput("fls -f fat "+image+" "+str(inode)) def scanFilesystem(inode, inode2path_dic, pathSoFar=""): if pathSoFar: print " Scanning",pathSoFar for line in get_ls(inode).split('\n'): if not line: continue try: theType,theInode,theName = line.split(None,2) except: continue # perhaps no name (false positive inode?) - skip if theInode=='*': continue # deleted entry (theName starts with inode) - ignore assert theInode.endswith(":") ; theInode = theInode[:-1] if theType=="d/d": # a directory if theInode in inode2path_dic: continue # duplicate ?? inode2path_dic[theInode] = pathSoFar+theName+"/" scanFilesystem(theInode, inode2path_dic, pathSoFar+theName+"/") elif theType=="r/r": inode2path_dic[theInode] = pathSoFar+theName print "Finding the root directory" i=0 while not is_valid_directory(i): i += 1 print "Scanning the root directory" root_inode2path = {} scanFilesystem(i,root_inode2path) print "Looking for lost directory stubs" recovered_directories = {} while i < 60000000: i += 1 if i in root_inode2path or i in recovered_directories: continue # already known sys.stdout.write("Checking "+str(i)+" \r") ; sys.stdout.flush() if not is_valid_directory(i): continue inode2path = root_inode2path.copy() scanFilesystem(i,inode2path) for n in inode2path.keys(): if n in root_inode2path: continue # already known p = recover_to+"/lostdir-"+str(i)+"/"+inode2path[n] if p[-1]=="/": # a directory recovered_directories[n] = True continue print "Recovering",p os.system('mkdir -p "'+p[:p.rindex("/")]+'"') os.system("icat -f fat "+image+" "+str(n)+' > "'+p+'"')
Note that the script might find a subdirectory before it finds its parent directory. For example if you have a lost directory A which has a subdirectory B, it is possible that the script will find B first and recover it, then later when it finds A it will recover A, re-recover B, and place the new copy of B inside the recovered A, so you will end up with both A, B and A/B. You have to manually decide which of the recovered directories are actually the top-level ones. The script does not bother to check for .. entries pointing to a directory's parent, because these were not accurate on the FAT storage card I had (they may be more useful on other filesystems). If you want you can modify the script to first run the inode scan to completion without recovering anything, then analyze them, discarding any top-level ones that are also contained within others. However, running the scan to completion is likely to take far longer than looking at the directories by hand.
As it is, you can interrupt the script once it has recovered what you want. If Control-C does not work, use Control-Z to suspend it and do kill %1 or whatever number bash gave you when you suspended the script.
This script can take several days to run through a large storage card. You can speed it up by using dd to take an image of the card to the hard disk (which likely has faster access times than a card reader); you can also narrow the range of inodes that are scanned if you have some idea of the approximate inode numbers of the lost directories (you can get such an idea by using fls to check on directories that are still there and that were created in about the same period of time as the lost ones).
After all the directories have been recovered, you can run fsck.vfat -r and let it return the orphaned space back to the free space, and then mount the card and copy the recovered directory structures back onto it.
Some GNU/Linux live CDs have a forensic mode that doesn't touch local storage media. For example if you boot the GRML live CD you can select "forensic mode" and can safely inspect attached harddisks or other media. AFAIK Knoppix has a similar option. -- René
Talkback: Discuss this article with The Answer Gang
Silas Brown is a legally blind computer scientist based in Cambridge UK. He has been using heavily-customised versions of Debian Linux since 1999. | http://ldp.indosite.co.id/LDP/LGNET/172/brownss.html | crawl-003 | refinedweb | 1,505 | 50.67 |
Chinese on the Mac. It's funny you mention that, because a friend of mine who is the PM in charge of MacWord is not only Chinese originally, but he is absolutely passionate (and I mean crazy-passionate) about supporting Unicode and Asian languages on the Mac, and is more or less single-handedly responsible for getting that into the 2004 product by browbeating those around him in MacBU. My understanding is that 2004 does support Chinese, BTW. If you find it surprising that it took awhile to support Chinese in MacWord given the huge population of Chinese speakers, you need to factor in the tiny percentage of those people who have Macs (then multiply that by the percent that don’t pirate software, and you get real market for Chinese in MacWord). Fundamentally without a business case, things only get done out of passion (like my friend's).
Reveal codes in Word. Well, we get that request a lot of course. The internal architectures of WordPerfect and Word are essentially totally different. WordPerfect has a tagged format system, which most of us are familiar with now from HTML, although it predated HTML by a long shot (I don't know if it was influenced by SGML or not - maybe a WP person could tell us? My guess is not). So to "reveal codes", WP just shows its internal format. Word however, is designed as a set of "objects" with properties. To make something Bold in WP, you (effectively) put Bold tags around the ends of it. In Word, that "run" of text is assigned the property "Bold". Actually, there is some indirection involved. Any run of text in Word with unique properties has a unique "property bag" assigned to it. The property bag is defined elsewhere in the document. If more runs of text are created that use the same format, the property bag is reused by reference - that is, the text is assigned the properties from bag #427, and somewhere else #427 is defined as bold, green, italic, etc. many different runs of text can refer to bag #427. Same for paragraphs, sections, and so on. That's a lot of gobbledygook to say that there are no "codes" to reveal. If you use the "Format/Reveal Formatting" feature in Word2002 or 2003, what you see is the contents of the property bag for the text you had your insertion point in, and you can then change them. So, asking for reveal codes is sort of like asking a Mazda rotary engine owner if you can see the pistons in his engine. They don’t exist. Generating a tagged format like HTML or XML from Word is therefore an export/conversion process, where these object-property sets have to be converted into a serial form that the markup languages use. Likewise import means converting these sets of tags into properties assigned to runs of text. I believe you can read more about the architecture of Word if you do a Google on Charles Simonyi. He was the architect for the original WinWord - it was his second go-round (at least) since he came from Xerox where he had worked on word processing tools of similar design (so I am told).
Some people pointed out that Open Office is not an *exact* clone of Office. That wasn't my point - all I was saying was that as a designer, I am interested in innovative, clever, usable designs to solve problems. When I looked at Open Office 1.1.1 the other day, nothing jumped out at me. If there are some neat designs in there, please share the details.
Creating and modifying Word binary docs outside of Word. Well, I think from a technical perspective that's a risky proposition. We wouldn't try it, that's for sure. It's the kind of thing you can get sort of working but it never leaves that stage due to the complexity involved. That's why our binary save converter for Word95 format was actually a version of Word95 hooked up to read RTF and spit out 95 *.doc. Creating a Word binary from scratch is tough. RTF is used for this purpose instead since it is easier to deal with than Word binary for apps other than Word (remember that is why we created it - it stands for Rich Text interchange Format). The new XML format is designed for exactly that purpose - and it is easier to work with than RTF. You can create the WordML doc (or even a minimal subset) on a server using XML tools, then send the XML to Word on the client and Word will load it up. If you're missing a lot of the Word specific stuff, that's OK - Word will fill in the missing bits with defaults. In fact, you can skip generating the doc on the server if you want - just generate an XML data file in your own schema and provide an XSLT for Word to use when opening the file. That pushes a lot of the processing onto the client.
BTW, a lot of the confusion around XML in Word2003 was that people thought it was just a file format - probably because Open Office uses it that way, and the long tradition of SGML which was so document focused. To us, WordML is handy, but what is really cool is the support for schemas that customers or other developers define. WordML in this sense acts as the "envelope" for the "letter" that is the real customer data. The Pro version of Office allows you to tag up a document in Word (although we think that's a pretty unfriendly thing to ask a normal user to do, it is the first step for developers). More interestingly, as a developer, you can build structured templates using your own schema, and have users create docs using them that are pre-structured. You can hook the save event to get the document out as XML, and then you're off and running. There's a thing on the client called the "schema-library" that associates XML namespaces of your choice with XSL files, solutions, etc. This means once you're set up in the schema-library, you can dump blobs of XML to Word (via e-mail attachments, or code), and Word will check the XML you provide - find the associated files to deal with it locally, and transform that XML using a presentation that can also retain the XML markup you supplied. Note this important difference - this is not converting one schema into another like a file converter (although it can be used that way) - it is generating presentation to wrap around the actual customer data, which is retained in the resulting file.
To be clear, if you’re thinking only in terms of file format, then the XML you're imagining has things like "bold", "italic", indent", etc. And then the conversions you imagine are sort of like converting "<b>" into "<bold>" or whatever. This is necessary stuff but not all that exciting. What I'm talking about are schemas of the form "customer ID", "quantity", price", etc. These are database schemas with semantic markup of the data. Without support for this sort of thing in the application, then XML really is just another file format. A handy one to parse outside the creating app - no question there - but the exciting bit is when you can hook business data into your documents, modify it in the content of the tools you are familiar with, and print or save or update database - whatever. This can cut out a lot of steps in today's workflow, and not only be faster but also reduce error.
Working on XML in Word2003 was a blast - it seemed like every week we'd come up with a new amazing thing you could do with it. The last two or three years have been some of the most fun I've ever had at work - OneNote was of course a thrill ride, and the XML stuff in Word2003 really was breaking exciting new ground. | http://blogs.msdn.com/b/chris_pratley/archive/2004/04/28/122374.aspx | CC-MAIN-2015-40 | refinedweb | 1,360 | 67.38 |
Prepared by: Richard A. Sevenich, rsevenic@netscape.net
Chapter 6: Using a Character Driver to Look at the PCI Bus
References:
• Neil Matthew and Richard Stones, Beginning Linux Programming, 2nd Edition, Chapter 21, Wrox Press Ltd.
(1999).
• Neil Matthew, Richard Stones, et alii, Professional Linux Programming, Chapter 26, Wrox Press Ltd. (1999).
• Don Anderson and Tom Shanley, PCI System Architecture, 4th edition, Chapter 19, Addison Wesley (2000).
• /usr/src/linux/Documentation/pci.txt
• /usr/src/linux/include/linux/pci.h
• /usr/src/linux/drivers/pci/pci.c
• man pages for lspci and setpci (the pciutils)
• - the web site of the PCI SIG (Special Interest Group) which performs various PCI
related activities, including maintaining the PCI specification
Note 1: Our study in this chapter includes an update and revision of GPL'd code drawn from our first reference - the
Wrox book by Matthew and Stones. This is a well done book with great examples.
Note 2: The fourth through sixth references above illustrate a common situation - you may need to go to the source
code hierarchy for documentation. Further, of those possibilities, items found in /usr/src/linux/Documentation are
not necessarily up to date. However, in our case pci.txt is reasonably current - and pci.h and pci.c are well
commented and (as source code) necessarily current for the associated kernel.
6.0 Introductory Comments
The character driver that evolved in the prior chapters gave us a look at most of the API and infrastructure of the
character driver. The pp_probe function was interesting in that it had to deal with hardware ill-designed to let the
system learn its whereabouts in I/O space and its specified irq.
In this chapter we exercise another character driver. This one will investigate the PCI bus and manipulate the PCI
based graphics card. The two new areas of interest are
• the Linux PCI layer which provides data structures and functions for interfacing with PCI devices
• learning how to access memory on an IO device such as the PCI based graphics card
When the PCI bus is implemented in accordance with the fullest expression of the PCI specification, probing for the
hardware is reduced to inspecting a PCI database set up during system boot. Linux provides a PCI layer with
functions intended to work with this database and the associated PCI bus/cards. This layer has evolved as the kernel
versions have moved from 2.0 to 2.2 to 2.4. Our new driver will use some of the functions available in the Linux
PCI layer. It is not itself a PCI driver, but looks at an already supported PCI hardware card in your system.
Nevertheless, before we build our investigative driver, we will provide an introduction to PCI device drivers.
6.1 PCI Device Drivers
What Linux has determined about a particular PCI device is stored in a corresponding pci_dev struct. The early part
of this struct has links to the global list of PCI devices, identifies this struct as a node in the per bus list, identifies
which PCI bus this device is on and so on - essentially providing linkage to the entire PCI bus system. It also
identifies device specific information such as the vendor, the device, and the device driver. Further, it identifies the
resources needed by the device driver, such as irq, I/O ports, and memory. This is clearly a different world than that
we encountered with our earlier driver (in previous chapters). Instead of probing blindly for the device resources
needed, it is now available in this (and other) data structures. We'll see more of the pci_dev struct once we construct
our own driver.
R.A. Sevenich © 2004 Introduction to Linux Device Driver Development 6 - 1
How does a PCI device driver access the information stored in the linked list of pci_dev structs? In the 2.4 series
kernel, the driver's probe function examines that linked list looking for the desired device. In particular, the
preferred approach is that the driver fill out the pci_driver struct and register that with the PCI layer. As expected
this registartion is done within the driver's init_module code. When init_module is executed (e.g. by insmod), the
kernel will use the probe function identified in the pci_driver struct to find the device by appropriately traversing the
list of pci_dev structs. Here is the pci_driver struct:
struct pci_driver
{
struct list_head node;
char *name;
const struct pci_device_id *id_table;
/* NULL if wants all devices */
int (*probe)(struct pci_dev *dev, const struct pci_device_id *id);
/* New device inserted */
void (*remove)(struct pci_dev *dev);
/* Device removed (NULL if not a hot-plug capable driver) */
int (*save_state)(struct pci_dev *dev, u32 state); /*Save Dev Context */
int (*suspend)(struct pci_dev *dev); /* Device suspended */
int (*resume)(struct pci_dev *dev); /* Device woken up */
int (*enable_wake)(struct pci_dev *dev, u32 state, int enable);
/* Enable wake event */
};
Let's describe some of these fields:
• name - the name chosen for the driver
• id_table - references a table of device id's with which this driver is concerned
• probe - this function searches for the hardware resources. It returns 0 if no device matching an id in the prior
table is found; otherwise > 0.
• remove - references the function to be called when a device belonging to this driver is removed by being
unregistered or removed physically in the case of a hot-pluggable device
• suspend - references a power management function when the device goes to sleep
• resume - references a power management function when the device is awakened from a sleep
The pci driver passes reference to the pci_driver struct to the kernel as an argument to pci_register_driver. Then the
probe is called within the scope of pci_register_driver. If the probe returns 0, pci_register_driver will return 0 to the
initialization routine.
In the 2.2 series kernel, init_module did much of the work of searching the pci_dev list, work which in the 2.4 series
is now done by the static kernel. The search routines used by the older style init_module are still available. In this
chapter, we write a driver which investigates the PCI bus, looking for a graphics card with prefetchable memory.
Note that our driver will not be a PCI driver itself - the drivers for the PCI devices are already available on our
machine and we aren't planning to supplant any. However, the search functions used directly in the older
init_module code in the 2.2 series will be useful in our investigative driver.
As indicated above pci_register_driver function is used by init_module to register the pci_driver struct with the
kernel, but that's not the whole story. You may have noticed that the pci_driver struct contained only a few entry
points and those didn't really deal with the productive work to be accomplished with the driver - they have more to
do with finding, suspending, awakening, and removing the device. The PCI device could be a character device, a
network device etc. and how it registers its other entry points varies from case to case. For example, if you inspect
the device driver for the PCI watchdog timer WDT500/501, /usr/src/linux/drivers/char/wdt_pci.c you find that
• it uses the file_operations struct
• which it encloses in a miscdevice struct
• and registers that miscdevice struct via the misc_register function
You might use the Linux cross reference () to investigate the internals of various PCI device
drivers, employing pci_register_driver as your initial search identifier.
R.A. Sevenich © 2004 Introduction to Linux Device Driver Development 6 - 2
6.2 Our Investigative Module
This example assumes that your graphics card is of the PCI/AGP variety. The PCI bus features high data transfer
rates and Plug and Play (PNP) features. The PCI specification indicates that each PCI device has 256 bytes of
configuration address space of which the first 64 bytes, called the Configuration Header Region, have predefined
purposes. Some of the registers in this predefined area are then written during the PNP configuration process. If a
particular card is not completely PNP compliant the system will have an extra burden. The 64 bytes of predefined
registers include fields which are useful to the operating system in deciding which device driver is appropriate.
There are nine mandatory fields of which those particularly useful for device determination are:
• Vendor ID
• Device ID
• Revision
• Class Code
• Subsystem Vendor ID
• Subsystem ID
The PCI SIG assigns PCI vendor id's, while the vendor chooses device id's.
As Linux evolves, it becomes less necessary for the PCI device driver writer to directly query the raw PCI data base
described in the prior paragraph. The Linux PCI layer now includes, not only carefully designed data structures
holding the information in a conveniently accessible form, but also has functions for interacting with that database.
We can use these functions to do such things as:
• find a device
• enable the device
• access device configuration space to discover specific resources
• allocate those resources
• use the device
• deallocate the resources
• disable the device
For example, if we focus on finding a device, we have various functions, including:
• pci_find_dev()
• pci_find_class()
Let's say we want to determine if we have a vga capable graphics card and, if so, we want the base address for the
prefetchable video memory and also its size. There are a number of useful functions and fields we can use to glean
this information. These functions were found by examining Linux source files and also by using the references given
at the beginning of this chapter. We'll proceed by showing actual code and then going back and examining the
salient program lines.
R.A. Sevenich © 2004 Introduction to Linux Device Driver Development 6 - 3
Let's start with this nearly empty module containing an init_module and a cleanup_module:
#define __KERNEL__
#define MODULE
#include <linux/module.h>
#include <linux/version.h>
#include <linux/wrapper.h>
#include <linux/fs.h>
#include <linux/sched.h>
#include <linux/ioport.h>
#include <linux/pci.h>
#include <asm/uaccess.h>
#include <asm/io.h>
MODULE_LICENSE("GPL");
#define DEV_NAME "pci_inv"
#define true 1
#define false 0
#define SUCCESS 0
#define FAILURE -1
int init_module(void)
{
int i, dev_flags, real_base, size;
u32 base[6];
struct pci_dev *pdev = NULL;
printk(KERN_ALERT"\nTrying to install %s.\n", DEV_NAME);
printk("Search for PCI_CLASS.\n");
if (pdev = pci_find_class(PCI_CLASS_DISPLAY_VGA << 8, NULL))
{
printk("Found graphics card.\n");
printk("Vendor, Device: 0x%x, 0x%x\n", pdev->vendor, pdev->device);
for (i=0; i<6; i++)
{
base[i] = pdev->resource[i].start;
dev_flags = pdev->resource[i].flags;
if(dev_flags & PCI_BASE_ADDRESS_MEM_PREFETCH)
{
real_base = base[i] & PCI_BASE_ADDRESS_MEM_MASK;
printk("Found prefetchable memory at 0x%x,\n", real_base);
printk(" lurking in base_register[%d]\n", i);
size = pdev->resource[i].end + 1 - real_base;
printk(" and with a size of %d MB.\n", size/1024/1024);
return SUCCESS;
}
}
printk("but not prefetchable memory.\n\n");
return FAILURE;
}
printk( KERN_ALERT "Did not find graphics card.\n");
return FAILURE;
}
void cleanup_module(void)
{
printk( KERN_ALERT "Removing %s.\n", DEV_NAME);
}
R.A. Sevenich © 2004 Introduction to Linux Device Driver Development 6 - 4
Here is the pci information harvested as shown in output from insmod:
Apr 17 10:25:28 aurach kernel: Trying to install pci_inv.
Apr 17 10:25:28 aurach kernel: Search for PCI bus.
Apr 17 10:25:28 aurach kernel: Search for PCI_CLASS.
Apr 17 10:25:28 aurach kernel: Found graphics card.
Apr 17 10:25:28 aurach kernel: Vendor is 0x1013.
Apr 17 10:25:28 aurach kernel: Device is 0xbc.
Apr 17 10:25:28 aurach kernel: Found prefetchable memory at 0xf6000000,
Apr 17 10:25:28 aurach kernel: lurking in base_register[0]
Apr 17 10:25:28 aurach kernel: with a size of 32 MB.
and from rmmod:
Apr 17 10:25:46 aurach kernel: Removing pci_inv.
Let's discuss some of the program statements in the init_module:
• pdev = pci_find_class(PCI_CLASS_DISPLAY_VGA << 8, NULL) - this searches though the
linked list of pci_dev structs looking for a graphics card. As used in the if statement, it quits when it finds the
first acceptable card and returns that pci_dev struct. If it finds nothing, it returns NULL.
• printk("Vendor is 0x%x.\n", pdev->vendor); - the vendor field of the struct contains the
vendor id
• printk("Device is 0x%x.\n", pdev->device); - the device field contains the device id for that
vendor
• base = pdev->resource[i].start; - there are as many as six IO or memory regions and this
references the start of one of those (as designated by i)
• dev_flags = pdev->resource[i].flags; - the flags give us crucial information as shown next
• if(dev_flags & PCI_BASE_ADDRESS_MEM_PREFETCH) - we can use the flags field of the resource to
determine if we've found prefetchable IO memory as desired
• base = base & PCI_BASE_ADDRESS_MEM_MASK; - we just want the bits that constitute the actual
address
Note: Video memory on PCI cards is often 'prefetchable' and marked as such, indicating that it can be cached by the
CPU and manipulated as desired. Many devices also implement their IO registers in memory regions. These would
be marked as not prefetchable to avoid being cached. IO registers, of course, need to be read and written without
being cached - otherwise we are reading or writing the cache and not the IO device in its current state.
6.3 Mapping IO Memory
Cards in IO space can have their own memory. For example, a PCI based video card will have sufficient memory for
the screen display, often called the frame buffer. In general, this memory in IO space is called IO memory. How can
a driver gain convenient access to this memory? If we focus on the CPU (IA32 variety), we note that the CPU is
aware of three kinds of memory:
• logical addresses
• linear addresses
• physical addresses
The IA32 translates logical addresses to linear addresses using the segmentation system, and then translates linear
addresses to physical addresses using the paging system. The physical addresses are driven onto the data bus to
access system RAM and ROM. Most other CPU architectures do not employ segmentation, only paging - so those
CPU's will be aware of just
• linear addresses
• physical addresses
IA32 segmentation has some virtues, but it is usually treated as a necessary and inescapable nuisance. Operating
systems often set its parameters up to provide the simplest segmentation system, minimizing its impact.
IO memory is yet another kind of address space, sometimes called a bus address space. In the IA32 the bus address
is the physical address, not necessarily true in other architectures. We will focus on the IA32. For the PCI bus, the
video card frame buffer is mapped to physical addresses beyond the end of the physical main memory. Further,
programs (such as our driver) do not access physical memory directly. What is done is to map the IO memory to the
virtual memory (logical memory for the IA32, linear for non segmented architectures) accessible to the driver. This
is done with the Linux function ioremap which hides architectural differences so the driver writer can expect to
achieve portability.
R.A. Sevenich © 2004 Introduction to Linux Device Driver Development 6 - 5
As a quick example, let's suppose that we investigate the PCI subsystem of our computer with the command
lspci -v (cat /proc/pci is deprecated)
and find somewhere in the output that our video card has 32 MB of prefetchable 32-bit memory starting at address
0xF6000000. To make that accessible to our driver we could do this:
char * vid_mem_ptr = ioremap(0xF6000000, 32*1024*1024);
and then access it in various ways e.g.
writeb('Y', vid_mem_ptr + 43);
Of course, the driver would need to release this mapping when done with it. In our example, this would be done with
iounmap(vid_mem_ptr);
6.3.1 The iomap.c driver and related files
In this section we look at the driver and support files from the first of the references as given at the start of this
chapter. We've updated it in only a limited fashion; enough to get it up and running for the 2.4 kernel. We'll explain
how it works and then use it as suggested in the reference. In this version it does not use the sorts of functions as
discussed in section 6.2. In fact, the user must learn which card he has etc., by manually entering
lspci -v
Subsequently, in Section 6.4, we'll look at interesting features of this program. As indicated, the program is based on
an earlier version of the Linuc PCI layer, so in Section 6.5 we'll make further changes to the driver ... somewhat in
the spirit of Section 6.2. This scenario is typical of open source - we can go to GPL'ed source code and learn a great
deal, while it continues to evolve under our feet.
We'll show listings for three files, modified from their kernel 2.2 origins so we can compile and run them for a 2.4
kernel:
• iomap.h
• iomap.c
• setup.c
Then in subsequent sections we'll focus on various areas of the example.
Note: The following listings may omit some lines extraneous to this discussion. However, your instructor will
provide a tarball of the whole works anyway.
First, here is the header file iomap.h:
#define IOMAP_MAJOR 42
#define IOMAP_MAX_DEVS 16
/* define to use readb and writeb to read/write data */
#define IOMAP_BYTE_WISE
/* the device structure */
typedef struct Iomap
{
unsigned long base;
unsigned long size;
char *ptr;
} Iomap;
#define IOMAP_GET _IOR(0xbb, 0, Iomap)
#define IOMAP_SET _IOW(0xbb, 1, Iomap)
#define IOMAP_CLEAR _IOW(0xbb, 2, long)
#define MSG(string, args...) printk(KERN_ALERT "iomap: " string, ##args)
R.A. Sevenich © 2004 Introduction to Linux Device Driver Development 6 - 6
Second, here are the salient parts of iomap.c.
/*
* Example of memory mapping i/o memory
*/
#include <linux/module.h>
#include <linux/version.h>
#include <linux/wrapper.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/types.h>
#include <linux/config.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/wrapper.h>
#include <linux/pci.h>
#include <linux/pci_ids.h>
#include <asm/uaccess.h>
#include <asm/page.h>
#include <asm/io.h>
#include "iomap.h"
Iomap *iomap_dev[IOMAP_MAX_DEVS];
MODULE_DESCRIPTION("iomap, mapping i/o memory");
MODULE_AUTHOR("Jens Axboe");
MODULE_LICENSE("GPL");
int iomap_remove(Iomap *idev)
{
iounmap(idev->ptr);
MSG("buffer at 0x%lx removed\n", idev->base);
return 0;
}
int iomap_setup(Iomap *idev)
{
/* remap the i/o region */
idev->ptr = ioremap(idev->base, idev->size);
MSG("setup: 0x%lx extending 0x%lx bytes\n", idev->base, idev->size);
return 0;
}
/* Beware: A RedHatism was encountered around the 2.4.20 Linux kernel where
RedHat changed a prototype. In Particular, RedHat took the original
prototype:
extern int remap_page_range(unsigned long from, unsigned long to,
unsigned long size, pgprot_t prot);
and inserted yet another argument at the start of the argument list:
struct vm_area_struct *vma
The prototype stock kernel was unchanged. See <linux/mm.h> for your
system.
*/
R.A. Sevenich © 2004 Introduction to Linux Device Driver Development 6 - 7
static int iomap_mmap(struct file *file, struct vm_area_struct *vma)
{
Iomap *idev = iomap_dev[MINOR(file->f_dentry->d_inode->i_rdev)];
unsigned long size;
/* no such device */
if (!idev->base) return -ENXIO;
/* size must be a multiple of PAGE_SIZE */
size = vma->vm_end - vma->vm_start;
if (size % PAGE_SIZE) return -EINVAL;
if (remap_page_range(vma->vm_start, idev->base, size, vma->vm_page_prot))
{
return -EAGAIN;
MSG("region mmapped\n");
return 0;
}
R.A. Sevenich © 2004 Introduction to Linux Device Driver Development 6 - 8
static int iomap_ioctl(struct inode *inode, struct file *file,
unsigned int cmd, unsigned long arg)
{
Iomap *idev = iomap_dev[MINOR(inode->i_rdev)];
switch (cmd) {
/* create the wanted device */
case IOMAP_SET:
{
/* if base is set, device is in use */
if (idev->base) return -EBUSY;
if (copy_from_user(idev, (Iomap *)arg, sizeof(Iomap))) return -EFAULT;
/* base and size must be page aligned */
if (idev->base % PAGE_SIZE || idev->size % PAGE_SIZE)
{
idev->base = 0;
return -EINVAL;
}
MSG("setting up minor %d\n", MINOR(inode->i_rdev));
iomap_setup(idev);
return 0;
}
case IOMAP_GET:
{
/* maybe device is not set up */
if (!idev->base) return -ENXIO;
if (copy_to_user((Iomap *)arg, idev, sizeof(Iomap))) return -EFAULT;
return 0;
}
case IOMAP_CLEAR:
{
long tmp;
/* if base is set, device is in use */
if (!idev->base) return -EBUSY;
if (get_user(tmp, (long *)arg)) return -EFAULT;
memset_io(idev->ptr, tmp, idev->size);
return 0;
}
default:
return -1;
}
}
int iomap_open(struct inode *inode, struct file *file)
{
int minor = MINOR(inode->i_rdev);
/* no such device */
if (minor >= IOMAP_MAX_DEVS) return -ENXIO;
return 0;
}
R.A. Sevenich © 2004 Introduction to Linux Device Driver Development 6 - 9
int iomap_release(struct inode *inode, struct file *file)
{
return 0;
};
}
R.A. Sevenich © 2004 Introduction to Linux Device Driver Development 6 - 10
static ssize_t iomap_write(struct file *file, const char *buf,
size_t count, loff_t *offset)
{
Iomap *idev = iomap_dev[MINOR(file->f_dentry->d_inode->i_rdev)];
char *tmp;
/* device not set up */
if (!idev->base) return -ENXIO;
/* end of mapping? */
if (file->f_pos >= idev->size) return 0;
tmp = (char *) kmalloc(count, GFP_KERNEL);
if (!tmp) return -ENOMEM;
/* adjust access beyond end */
if (file->f_pos + count > idev->size) count = idev->size – file->f_pos;
/* get user data */
if (copy_from_user(tmp, buf, count))
{
kfree(tmp);
return -EFAULT;
}
/* write data to i/o region */
#ifdef IOMAP_BYTE_WISE
{ int i;
for (i = 0; i < count; i++)
writeb(tmp[i], idev->ptr + file->f_pos + i);
}
#else
memcpy_toio(idev->ptr+file->f_pos, tmp, count);
#endif
file->f_pos += count;
kfree(tmp);
return count;
}
struct file_operations iomap_fops = {
owner: THIS_MODULE,
read: iomap_read,
write: iomap_write,
ioctl: iomap_ioctl,
mmap: iomap_mmap,
open: iomap_open,
release: iomap_release,
};
R.A. Sevenich © 2004 Introduction to Linux Device Driver Development 6 - 11
int init_module(void)
{
int res, i;
/* register device with kernel */
res = register_chrdev(IOMAP_MAJOR, "iomap", &iomap_fops);
if (res)
{
MSG("can't register device with kernel\n");
return res;
}
for (i = 0; i < IOMAP_MAX_DEVS; i++)
{
iomap_dev[i] = (Iomap *) kmalloc(sizeof(Iomap), GFP_KERNEL);
iomap_dev[i]->base = 0;
}
MSG("module loaded\n");
return 0;
}
void cleanup_module(void)
{
int i = 0;
Iomap *tmp;
/* delete the devices */
for (tmp = iomap_dev[i]; i < IOMAP_MAX_DEVS; tmp = iomap_dev[++i])
{
if (tmp->base) iomap_remove(tmp);
kfree(tmp);
}
unregister_chrdev(IOMAP_MAJOR, "iomap");
MSG("unloaded\n");
return;
}
R.A. Sevenich © 2004 Introduction to Linux Device Driver Development 6 - 12
Lastly, here is the user space program setup.c:
#include <stdio.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include "iomap.h"
#define BASE 0xf6000000 /* specific to your graphics card */
int main(int argc, char *argv[])
{
int fd1 = open("/dev/iomap0", O_RDWR);
int fd2 = open("/dev/iomap1", O_RDWR);
Iomap dev1, dev2;
if (fd1 == -1 || fd2 == -1)
{
perror("open");
return 1;
}
/* setup first device */
dev1.base = BASE;
dev1.size = 1024 * 1024;
if (ioctl(fd1, IOMAP_SET, &dev1))
{
perror("ioctl");
return 2;
}
/* setup second device, offset starting from first */
dev2.base = BASE + dev1.size;
dev2.size = 1024 * 1024;
if (ioctl(fd2, IOMAP_SET, &dev2))
{
perror("ioctl");
return 3;
}
return 0;
}
6.4 How iomap works - a specific example
The iomap.c allows us to create one or more devices where each device is a chunk of the frame buffer. Each such
device is accessible through the virtual file system e.g. open, close, read, write, etc. The user program begins by
opening two devices, iomap0 and iomap1. An opened device is not usable until initialized - a step which sets the
device's base address and size. This is done with an ioctl call. The user program could then write and read to the
devices to manipulate what is displayed on the monitor screen. However, what the given user program does instead
is to then quit, without even closing the devices. Nevertheless, the devices remain open and available. The reference
then suggests that we use the cp command to copy one device over the other - this will use the driver's read and
write functions. The result is a screwed up display, as expected.
We'll now work through this scenario in some detail. Let's assume that iomap.c has been compiled and the driver
installed via insmod. The next tasks to do are these:
• Make sure that the hard coded BASE in setup.c has been changed to match your card and that you choose a size
that will work (1024x1024 is hard coded in the original setup.c).
• Next compile setup.c, but before running it, make the needed device files with the appropriate permissions; i.e.,
mknod /dev/iomap0 c 42 0
mknod /dev/iomap1 c 42 1
chmod 666 /dev/iomap*
R.A. Sevenich © 2004 Introduction to Linux Device Driver Development 6 - 13
Now run setup, so that the system is ready to demonstrate how it can manipulate your X Windows display. The
suggestion from the reference is to copy part of the screen display on top of another part by entering at the command
line:
cp /dev/iomap1 /dev/iomap0
Let's follow the execution of setup to see what goes on. In particular, consider the calls made by setup that will
vector to the driver. These are, in order,
open two instances of the driver, minor numbers 0 and 1.
int fd1 = open("/dev/iomap0", O_RDWR);
int fd2 = open("/dev/iomap1", O_RDWR);
set up the parameters (base address and size) for both devices.
The driver defines the device as the Iomap struct (in iomap.h):
typedef struct Iomap
{
unsigned long base;
unsigned long size;
char *ptr;
} Iomap;
The struct contains
• a base address as lying somewhere in the frame buffer
• the device extent (bytes of some chunk of the frame buffer)
• a virtual memory pointer that the driver uses to access the device memory
So the setup program next initializes the just opened devices as follows:
/* setup first device */
dev1.base = BASE;
dev1.size = 1024 * 1024;
if (ioctl(fd1, IOMAP_SET, &dev1))
{
perror("ioctl");
return 2;
}
/* setup second device, offset 1 meg from first */
dev2.base = BASE + dev1.size;
dev2.size = 1024 * 1024;
if (ioctl(fd2, IOMAP_SET, &dev2))
{
perror("ioctl");
return 3;
}
In the next subsections we'll look at what this accomplishes at the driver level.
6.4.1 Opening instances of the driver
So, what does something such as the following do?
open("/dev/iomap0", O_RDWR);
The underlying driver function iomap_open merely checks the validity of the minor number and, if that's not OK,
returns an error.
R.A. Sevenich © 2004 Introduction to Linux Device Driver Development 6 - 14
6.4.2 Setting up device parameters (base address and size)
As we've seen, the setup program next initializes the base and size fields for the Iomap struct and then calls ioctl for
an already open (but not initialized) device passing the desired command and the address of the Iomap struct with
this sort of syntax:
ioctl(fd1, IOMAP_SET, &dev1);
This triggers these events at the driver level:
1. the driver level ioctl
• switches to the code for the requested ioctl command (IOMAP_SET)
• checks that the device has not already been set up
• copies the user space Iomap struct into a local copy
• checks the struct base and size fields to assure that they are page aligned
• calls iomap_setup, passing along the Iomap struct
2. iomap_setup
As described in section 6.3, this maps the frame buffer so that the driver can access it. In particular, it calls the
kernel function ioremap to get the virtual memory pointer and puts that into the Iomap struct.
Now the device as represented by the Iomap struct is initialized, accessible, and ready for use by such functions as
read and write. So when setup is done, there are two open and initialized minor devices which can be used. Again,
note that the userland 'setup' program does not close those device files.
6.4.3 Subsequent use of the devices
The setup program did only what its name implies. If we want to use the devices we can write another program to do
so - or even use them at the command line. The reference from which this has been extracted then asks the reader to
do this:
cp /dev/iomap1 /dev/iomap0
which copies one area of the frame buffer onto the other half.
6.4.4 The Read and Write Functionality in iomap.c
This driver shows how the read and write functionality expected by a user space program is provided by the
underlying driver level read and write functions, iomap_read and iomap_write. These use quite different functions
than did pp_read and pp_write in our earlier driver. There we were essentially transferring data back and forth
between userland memory (mapped to physical RAM) and kernel memory (also mapped to physical RAM). Here we
have mapped physical I/O memory to be directly accessible to the kernel space driver.
In user space the default behavior of read and write is blocking i.e. if the system call cannot proceed the caller
blocks so other processes can get useful work done in the meantime.
When the read or write can proceed the caller is unblocked. To get more specific about each, the behavior is as
follows:
• read - if no data is available, the process blocks. When data becomes available, the process is awakened and data
is returned to the caller. If there is less data than specified in the read's count argument, the amount available is
still delivered and the return value to the read system call is the number of bytes actually read.
• write - if there is no space in the write buffer, the process blocks. When some data has been written to the device
opening room in the buffer, the process is awakened and writes successfully to the buffer. If the amount of buffer
space is less than specified in the write's count argument, it writes as much as there is space and the return value
to the write system call is the number of bytes actually written.
Alternatively, to specify the nonblocking behavior, the O_NONBLOCK flag is used in the open system call. In both
cases, if the system call cannot proceed, it returns immediately with the return value -EAGAIN.
R.A. Sevenich © 2004 Introduction to Linux Device Driver Development 6 - 15
To see how the driver level calls support these behaviors we'll investigate the iomap_read function (iomap_write is
similar):;
}
The sequence of events in the read is clear:
• assure that the device has been set up (i.e. is valid)
• if the file pointer is already at or beyond the end of the file, return 0
• kmalloc enough memory as a buffer for the bytes to be read
• if the number of bytes requested would take the file pointer past the end of the file, adjust the byte count to the
number of bytes actually available
• read the number of bytes from the device into the buffer
• copy those bytes to user space
• adjust the file pointer appropriately
• kfree the buffer space
• return the number of bytes read
R.A. Sevenich © 2004 Introduction to Linux Device Driver Development 6 - 16
6.5 Minor but Interesting Modifications to iomap.c
In the two preceding sections we looked at code from the first reference. We can make modifications based on what
we saw in section 6.2. For example, we could have init_module automate the device setep that was heretofore being
done in the user code with hard coded frame buffer base address and size. For example, we could have init_module
• find the graphics card
• find the frame buffer's base address and size
• set up 16 devices, each mapping 1/16th of the buffer
This would require some changes elsewhere in the driver as well.
To avoid a dramatic driver revision, we suggest that you merely add a new ioctl command which will
• find the card
• find the frame buffer's base address and size
The new ioctl would use the code from the init_module of section 6.2. We could then open the device, use the new
ioctl to get the frame buffer parameters, initialize the devices as before, and finally use the devices as wished. This
will be explored in the activities section at the end of this chapter.
6.6 PCI Caveats
If your system is entirely PCI PNP compliant, it makes life relatively easy for the device driver implementer.
However, incompatibilities are quite possible. A non exhaustive list of some such problems would include:
• BIOS does not contain PCI PNP
• ISA device which is not PNP configurable
• PCI device which is not PNP
• Conflict with memory management software
We'll give a brief description of each of these problem areas.
BIOS does not contain PCI PNP
The PCI specification does not strictly require that the BIOS perform PNP configuration. Such a non PNP BIOS
will start the system with inoperable PNP devices. There is a PNP BIOS Specification which has been provided by
Intel, Phoenix, and Compaq - but is not part of the PCI specification. Such a situation leaves configuration entirely
to the Operating System.
ISA device which is not PNP configurable
This sort of device does not allow a way to configure needed resources in software; the needed resources are
determined by the hardware. This removes a great deal of flexibility in resolving any resource conflicts. The PNP
BIOS Specification mentioned in the previous section provides an optional (not required) way to handle such
devices. Its central feature is that the resources needed are to be stored in the system's CMOS setup, thereby making
the information available to the PNP BIOS PCI configurator.
PCI device which is not PNP
There exist PCI devices which are not PNP - they may, for example, be hardwired to an I/O space region. The PNP
BIOS may assign space for the device and everything may work fine if no resource conflicts are encountered.
Conflict with memory management software
The PNP BIOS assigns the needed device memory resources as the system boots. Properly done, there will be no
memory assignment conflicts. However, it is possible that a subsequently installed memory manager could cause a
conflict. This might also arise with improperly designed device drivers.
R.A. Sevenich © 2004 Introduction to Linux Device Driver Development 6 - 17
6.6.1 The bottom line
If the PCI BIOS meets the PNP BIOS Specification (separate from the PCI Specification), if the devices are PCI
PNP compliant, and if neither the OS nor device drivers introduces conflicts, then all is rosy. More likely the OS
may need to do some reallocation etc. Further, debugging problems can be quite difficult. For example, there may
be a non compliant card in the system, but fortuitously no resource conflicts, and the system works fine. Then the
user adds a fully compliant card and the latent problem now rears its head. The user will most likely blame the new
card and its vendor. To actually fix the blame correctly might be difficult. It is important that non compliance be
identified before purchase and then avoided.
6.7 Activities
6.7.1 Activity 1
Implement the module shown in Section 6.2. Record the results obtained for
• card vendor id
• device id
• frame buffer base address
• frame buffer size
See if you can find the vendor and device names in /usr/src/linux/include/linux/pci_ids.h.
Compare all the above results to what is reported by
lspci -v
R.A. Sevenich © 2004 Introduction to Linux Device Driver Development 6 - 18
6.7.2 Activity 2
This relies on the code described in Section 6.4. Get the tarball of the necessary code from the instructor. Change
the hardcoded BASE value in setup.c to match your card, based on the prefetchable memory address result from the
prior problem. Also change the size from 1024x1024 bytes appropriately. Then try the software. The detailed steps
are:
• expand/untar iomapi.tgz
• change to the newly created iomapi/ directory and run make
• make the BASE and size changes in the user program setup.c and then compile it
• create device nodes for the two minor devices
• mknod /dev/iomap0 c 42 0
• mknod /dev/iomap1 c 42 1
• change the device permissions i.e.
• chmod 666 /dev/iomap*
• install the device driver via insmod iomap.o
• run the user program
• then enter, cp /dev/iomap1 /dev/iomap0
Then describe what happened at the last step.
6.7.3 Activity 3
The setup program hard codes the base address. Remove that and implement a new ioctl command (driver level and
user level) so setup can determine the base address with the new ioctl command and then use that to accomplish its
later tasks. Note that the code from problem 1 will be incorporated into the driver level version of the new ioctl
command and not appear in init_module. Then redo the appropriate parts of problem above and run the new
approach.
6.7.4 Activity 4
Modify the setup.c program so that it uses the read and write functions and closes the devices when done.
6.7.5 Activity 5
The driver function iomap_setup uses the kernel function ioremap to give the driver a pointer to get access to the
frame buffer in physical memory. Is it possible to give a pointer to the user space program, so it can access the frame
buffer? Investigate the driver's iomap_mmap function and the man page for mmap. Then write a user program to
manipulate the frame buffer using the pointer..
R.A. Sevenich © 2004 Introduction to Linux Device Driver Development 6 - 19 | https://www.scribd.com/document/221715024/ch6-ldd | CC-MAIN-2018-39 | refinedweb | 6,205 | 53.21 |
The abode of the dead in the Bible.
[Hebrew šə’ôl.]
The abode of the dead in the Bible.
[Hebrew šə’ôl.]
The domain of the dead, according to the OT; the region where the departed are laid to rest.
Sheol was located beneath the earth (Num 16:30), under the waters (Job 26:5). All the dead descended there never to return (Job 7:9, 16), although the OT records two exceptions who went straight to heaven: Enoch (Gen 5:24) and Elijah (II Kgs 2:11). All the dead were treated equally (Job 3:13-19; Ezek 32:18-32) and according to Ecclesiastes there was in sheol "neither doing nor thinking, neither understanding nor wisdom" (Ecc 9:10). The belief that God ruled the universe from heaven to Sheol (Ps 139:7-8; Job 26:6), implied that death also belonged to God's domain (cf I Sam 2:6). But despite God's power over Sheol, the dead did not have any communication with him (Ps 88:6), nor could they praise him (Is 38:18; Ps 30:9). See ABADDON; GEHENNA; HADES.
Concordance
II Sam 22:6. Job 11:8; 17:16; 26:6. Ps 16:10; 18:5; 86:13; 116:3. Prov 1:12. Is 5:14; 14:11,15; 28:15, 18; 38:10, 18; 57:9. Jonah 2:2.)
According to Professors Stephen L. Harris and James Tabor, sheol is a place of "nothingness" that has its roots in the Hebrew Bible (or Talmud)..
This entry is from Wikipedia, the leading user-contributed encyclopedia. It may not have been reviewed by professional editors (see full disclaimer)
Some good "Sheol" pages on the web:
Mentioned in | http://www.answers.com/topic/sheol | crawl-002 | refinedweb | 284 | 73.68 |
Abstract work processor – takes work units and turns them into WorkResult instances. More...
#include <mitsuba/core/sched.h>
Abstract work processor – takes work units and turns them into WorkResult instances.
When executing a parallel task using Mitsuba's scheduling system, the actual work is done in an implementation of this interface.
The class is serializable so that it can be sent over the network if required. It is possible to keep local state in WorkProcessor instances (e.g. scratch space for computations), though anything not returned in the form of a WorkResult will eventually be lost. Each Worker (both locally and remotely) has its own WorkProcessor, and therefore no form of locking is required within instances of this class.
Virtual destructor.
Protected constructors.
Create a work result of the proper type and size.
Create a work unit of the proper type and size.
Implemented in mitsuba::ParticleTracer.
Retrieve this object's class.
Reimplemented from mitsuba::SerializableObject.
Reimplemented in mitsuba::ParticleTracer.
Look up a named resource, which has been bound to the associated parallel process.
Throws an exception if the resource is not known / bound.
Called once before processing starts.
This is useful for allocating scratch space or resolving references to resource objects. Lengthy computations should be performed in process() instead of here, since this this method will be called while the central scheduler lock is held. A thrown exception will lead to the termination of the parallel process.
Implemented in mitsuba::ParticleTracer.
Process a work unit and store the computed results.
The
active parameter can be used to signal a premature stop of the execution flow. In this case, the work result is allowed to be undefined (it will simply be ignored). A thrown exception will lead to the termination of the parallel process.
Implemented in mitsuba::ParticleTracer. | http://mitsuba-renderer.org/api/classmitsuba_1_1_work_processor.html | CC-MAIN-2020-29 | refinedweb | 298 | 51.34 |
Objectives : make an X11/GLX program run natively on Wayland/EGL, with minimal modifications to the code.
The Linux world is rapidly migrating from the legacy X11 display protocol and server, to Wayland. There are a lot of reasons why this change is necessary, but it's best watching this conference to understand why X is now left behind.
However, there are a few challenges, especially when it comes to OpenGL programs.
There a few different OpenGL APIs today (GL1, GL2, GL3, GLES1, GLE2...) ; on the desktop, the most popular has always been GL1/GL2, whereas GLES, by contrast, is mostly used on mobile OSes (Android, iOS...).
We also need more than pure OpenGL to draw to the screen : a glue for the underlying window system. It's called WGL on Windows, CGL on Mac OS X, and traditionally GLX on Linux/X11.
For instance, our good ol' glxgears benchmark runs on X11 using OpenGL1 and GLX :
glxgears running with GL/GLX
And now, here comes the problem : Wayland doesn't support desktop GL nor GLX.
Instead, it only supports GLES with a new binding named EGL.
We'd normally be forced to rewrite all our implementation code. But let's see how to deal with this case with minimum effort.
One year ago, jwz needed to port xscreensaver to the iPhone. As the iPhone knows GLES and nothing else, he wrote a GL-to-GLES1 wrapper which one can download from various places.
So for a code including GL headers :
#include <GL/gl.h>
we basically replace them with jwzGLES/GLES1 ones :
#include <GLES/gl.h> #include "jwzgles.h"
And to link replace :
-lGL
with :
-lGLESv1_CM -DHAVE_JWZGLES -ljwzgles
I recently needed to port a GLX program under native Wayland ; so I wrote the EGLX wrapper, which remaps GLX calls to EGL-Wayland ones (hence the name ;-) ).
You can download it from here with :
git clone
or alternatively download a tarball :
EGLX_0.1.tar.bz2 (88.9 Kb)
So for a code including GLX headers :
#include <GL/glx.h>
we basically replace them with EGLX ones :
#include "EGLX.h"
and put at the beginning of the main() function :
EGLX_main (0);
And to link add :
-lEGLX
In the EGLX source tree, once you've compiled the library, have a look at the modified version of "examples/glxgears.c".
Then build it with :
./compile_glxgears.sh
And run it with :
./glxgears
Wrapped glxgears running on Wayland ; note you can move the surface with the pointer
Here we go !
A video a available HERE.
Depth for the green-wheel?
Hello.
Hope this is not out-of-date.
Did not read the source-code,but what happened to the "Depth" of the green wheel in the wayland-Version?
Thanks for your work.
Kind regards
Christian
Hello Herr Schwarz,
Hello Herr Schwarz,
You mean the Z-order ? Yes, it's a bug in the jwzgles wrapper. As my work concentrates on porting code rather than doing pure OpenGL rendering, I didn't fix this. I suppose someone (or I) *may* do it eventually.
Add new comment | http://www.tarnyko.net/en/?q=comment/86929 | CC-MAIN-2019-26 | refinedweb | 510 | 74.69 |
Wrapper around tarfile with support for more compression formats.
Project description
Overview
Wrapper around tarfile to add support for more compression formats.
Usage
First, install the library with the tarfile compression formats you wish to support. The example below shows an install for zstandard tarfile support.
pip install xtarfile[zstd]
You can now use the xtarfile module in the same way as the standard library tarfile module:
import xtarfile as tarfile with tarfile.open('some-archive', 'w:zstd') as archive: archive.add('a-file.txt') with tarfile.open('some-archive', 'r:zstd') as archive: archive.extractall()
Alternatively, detecting the correct compression module based on the file extensions is also supported:
import xtarfile as tarfile with tarfile.open('some-archive.tar.zstd', 'w') as archive: archive.add('a-file.txt') with tarfile.open('some-archive.tar.zstd', 'r') as archive: archive.extractall()
Development
Install the project’s dependencies with
pip install .[zstd].
Run the tests via
python3 setup.py test.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/xtarfile/ | CC-MAIN-2020-45 | refinedweb | 182 | 70.39 |
:
Now let’s convert a numerical string to a number:.
For something like this, how does os know to stop at the space between the two numbers and give nValue1 the first portion, 12345 and nValue2 the second portion, 67.89?
It breaks at whitespace.
#typo
I think "There are six string classes for streams:" should be "There are six stream classes for string:"
Updated. Thanks!
Formatting Error:
“There are similarly two ways to get data out of a stringstream: 1) Use the str() function to retrieve the results of the buffer:”
Point 1) should be placed in a new line.
I have some confusions regarding to this code. The output is 12345, that is the value of variable strValue, a hyphen and 67.89, that is value of variable strValue2.
Allow me to read the code after the point where we are inserting a string of numbers into the stream. Stream holds 12345 67.89. Then we define a variable, extract the value from the stream and try to put it in the variable strValue. According to output, srtrValue is only assigned 12345 (in string form) and 67.89 was not extracted from the stream to be set as the value of strValue. Why? Does the whitespace breaks the extraction process (and all these things are related to the fact that >> can’t read whitespaces)? Is my question clear?
When I do this
I got an address. Seeing that, I am sure that cout < < os; is not invalid and has some meaning. What's that?
From this point, I can see an important use of this functionality that I can ask user for a (integral or double) number, keep that in a string variable and then using the above functionalities, insert the input into stringstream and then finally extract the contents in the buffer to make it a valid value for an integer or double variable. That way, if a user tries to input something non-integral, the program won’t end up in an infinite loop and I would be able to handle this situation manually.
2) Call erase() on the result of str():
where are we calling erase???
Thanks for pointing out the formatting error. Fixed.
1) Yes, whitespace breaks the formatting. If you remember from the lessons on cin, if you extract cin to a string, you only get up to the first whitespace. If you want the whole string, you have to use another method, like cin.getline().
2) When I tried to compile this snippet in Visual Studio:
I got an error about an invalid conversion. I’m not sure why your compiler is printing an address. Perhaps it’s doing an implicit conversion to a pointer value.
3) Update the erase example to remove the incorrect reference to erase().
Please use os.clear() before the line os << "12345 234234" << endl;
great !!!
In the code given below, it is printing value of s2 but not printing value of S1. Can someone help me why it is the case?
using namespace std;
#include<iostream>
#include<string>
#include<sstream>
int main()
{
stringstream os;
int nD=234234;
os << nD;
string s2;
os >> s2;
cout << s2 << endl;
os << "12345 234234" << endl;
string S1;
os >> S1;
cout << S1 << endl;
os >> S1;
cout << S1 << endl;
return 0;
}
Hello, or should I say “Hello world!”. I am still learning C++, and I would appreciate anyone how would help me.
I am trying to make a C++ program that would arrange three words in alphabetical order. Note that I did one for arranging three integers from least to greatest. Any help?
I Don’t see any erase() function called.
Templates (covered later in this tutorial) can help you create a pretty nice, generic Convert function, that converts between arbitrary compatible values, such as strings and different number types (and even custom classes, if they overload operator<< and operator>> properly).
Output:
Hi Alex,
There is an error in the section Clearing a stringstream for reuse. The second suggestion of using erase does not work. I think this is because os.str() returns a copy of the buffer and erase then just erases the copy leaving the original in tact. So the code in this case will still print “Hello World!”
Another point to note is that setting a buffer using str(“xx”) and then using the << operator on the stream will not append (as I at first thought) but will overwrite. So the following code:
stringstream os;
os.str("xxxxxxxxxx");
os << "World!";
cout << os.str() << endl;
will output:
World!xxxx
You are correct, using erase() doesn’t work because it clears a copy of the buffer.
That is interesting about the mixing of str() and the << operator. Doing so is kind of like mixing metaphors though -- better to stick with one or the other.
The text for this example still refers to erase().
Hi Alex,
First a typo in the >> example, the comment says “print the numbers separated by a dash” but the code just prints the first value.
Second you need to include < sstream > to get at stringstream.
Third, the behaviour of >> and str() is subtly different as shown by this code:
stringstream os;
os << "12345 67.89"; // insert a string of numbers into the stream
string strValue;
os >> strValue; // extract 1st value
cout << "value1 " << strValue << endl;
os >> strValue; // extract 2nd value
cout << "value2 " << strValue << endl;
cout << "whole string " << os.str() << endl; // print whole string!
which gives the following output:
value1 12345
value2 67.89
whole string 12345 67.89
In other words the >> operator takes values from the string, moving along every time it is used, but the str() function always returns the whole string no matter how many times it is called (even after using >>)
Thanks, I fixed the typo and made the distinction between >> and str() more clear.
Name (required)
Website | http://www.learncpp.com/cpp-tutorial/184-stream-classes-for-strings/ | CC-MAIN-2017-30 | refinedweb | 972 | 72.46 |
[01-Dec-2011 00:00:02] [connected at Thu Dec 1 00:00:02 2011]
[01-Dec-2011 00:00:15] [zenoss-logger (logger bot) has joined #zenoss]
[01-Dec-2011 00:00:19] kocolosk is now known as kocolosk|away
[01-Dec-2011 05:04:34] <cek> Hi. How do you monitor HTTP? I need a simple works/doesn't monitor. The default one doesn't support sending "\n" in request.
[01-Dec-2011 06:53:43] <cek> guys, where's monitoring classes defined?
[01-Dec-2011 06:53:57] <cek> i need a tree view of them, much like of device classes
[01-Dec-2011 06:54:25] <cek> oh, on events tab
[01-Dec-2011 07:55:31] kocolosk|away is now known as kocolosk
[01-Dec-2011 07:59:52] <jmp242> monitoring classes?
[01-Dec-2011 08:00:06] <jmp242> do you mean the templates?
[01-Dec-2011 08:18:48] <cek> nevermind. Now i'm looking for a way to create an event manually, though check_http invokation
[01-Dec-2011 08:19:12] <cek> That is, not datasources and such for graphing purposes, only events
[01-Dec-2011 08:29:40] <jmp242> zensendevent is a command line method to create events
[01-Dec-2011 08:29:59] <jmp242> there are also other web APIs I suppose
[01-Dec-2011 08:45:41] <cek> it's indeed datasource, but with command type.
[01-Dec-2011 08:46:00] <cek> TALES expr. badly documented. There should be a list of attributes there.
[01-Dec-2011 08:46:18] <cek> you have ${dev/manageIp} everywhere, yet docs don't tell this. They have getManageIp
[01-Dec-2011 08:46:35] <cek> same iwth id - what to use - device/Id or dev/id or dev/ID -- not clear
[01-Dec-2011 08:47:09] <jmp242> Mmm, that is true - I don't know why it's unclear, but I've not used them so can't provide guidance
[01-Dec-2011 08:49:22] <cek> ApacheMonitor does the stupitidest thing - it sends IP in Host field
[01-Dec-2011 08:50:58] <cek> User-Agent: check_http/v2053 (nagios-plugins 1.4.13) behaves correctly
[01-Dec-2011 10:17:38] <ali3n0> hi folks. I'd like to write a check to run from my zenoss collector and do a "select device from production_device_list where <condition>" like query. What's the suggested way? Should I use the API or is there a better solution?
[01-Dec-2011 10:21:41] <jmp242> zendmd?
[01-Dec-2011 10:21:49] <jmp242> or one of the APIs
[01-Dec-2011 10:37:01] <ali3n0> can I script zendmd? I mean could it be run non interactively?
[01-Dec-2011 10:39:43] <jmp242> yes
[01-Dec-2011 10:40:30] <sam_____> hi
[01-Dec-2011 10:40:53] <sam_____> I am getting an error parsing command results error in zenoss
[01-Dec-2011 10:41:15] <sam_____> it sucessfully added my CloudStack but can't see any data
[01-Dec-2011 10:41:52] <sam_____> ??
[01-Dec-2011 10:41:57] <sam_____> anyone there?
[01-Dec-2011 10:43:34] <sam_____> anyone here to help?
[01-Dec-2011 11:29:37] <rmatte> ali3n0:
[01-Dec-2011 11:30:34] <ali3n0> rmatte: nice
[01-Dec-2011 11:31:19] <rmatte> what are you trying to script out of curiosity?
[01-Dec-2011 11:38:59] <ali3n0> rmatte: I'd like to check for devices with a particular zDeviceTemplate associated
[01-Dec-2011 11:39:30] <ali3n0> it would be great to have a method that returns just that but I'm not able to find it
[01-Dec-2011 11:39:47] <ali3n0> anyway, the goal is to check if those devices are in production state or not
[01-Dec-2011 11:40:14] <ali3n0> actually I want to check if I've got >x "worker" running
[01-Dec-2011 11:40:31] <ali3n0> rmatte: any suggestion very appreciated
[01-Dec-2011 11:40:47] <ali3n0> so far I'm just getting a list of production devices via api
[01-Dec-2011 11:52:40] <rmatte> getting a list of devices that are in production is easy
[01-Dec-2011 11:52:50] <rmatte> for d in dmd.Devices.getSubDevices():
[01-Dec-2011 11:52:59] <rmatte> if d.productionState == 1000:
[01-Dec-2011 11:53:08] <rmatte> print "%s" % (d.id)
[01-Dec-2011 11:53:19] <rmatte> or...
[01-Dec-2011 11:53:24] <rmatte> print "%s" % (d.getDeviceName())
[01-Dec-2011 11:54:23] <rmatte> If you wanted to check for a template you'd do something like...
[01-Dec-2011 11:54:26] <rmatte> for d in dmd.Devices.getSubDevices():
[01-Dec-2011 11:54:30] <rmatte> if d.productionState == 1000:
[01-Dec-2011 11:55:01] <rmatte> if "TheNameOfTheTemplate" in d.zDeviceTemplate:
[01-Dec-2011 11:55:09] <rmatte> print "%s" % (d.getDeviceName())
[01-Dec-2011 12:00:01] [disconnected at Thu Dec 1 12:00:01 2011]
[01-Dec-2011 12:00:01] [connected at Thu Dec 1 12:00:01 2011]
[01-Dec-2011 12:00:11] [zenoss-logger (logger bot) has joined #zenoss]
[01-Dec-2011 12:06:18] <tvincent> I am hoping I am wrong here. But do I need to create a new datasource for every mbean attribute that I wan to graph? I was hoping to only create one mbean datasource and then multiple data points for attributes?
[01-Dec-2011 12:13:16] <ali3n0> rmatte: thanks for hint. I went for API and it works ok, next time I'll look into dmd
[01-Dec-2011 12:13:24] <ali3n0> quite sure it's more performing
[01-Dec-2011 13:09:45] kocolosk is now known as kocolosk|away
[01-Dec-2011 13:22:27] kocolosk|away is now known as kocolosk
[01-Dec-2011 15:52:32] <Gat0rvean> Is there a good way to backup Monitoring Templates to test removing them from a mapping?
[01-Dec-2011 16:06:23] <rmatte> does anyone know if a jitter score can actually go above 1?
[01-Dec-2011 16:06:45] <GameMagister> normally no
[01-Dec-2011 16:25:53] <jmp242> Gat0rvean: I'm not sure I understand your question exactly
[01-Dec-2011 16:26:01] <jmp242> but you could export them to a Zenpack...
[01-Dec-2011 16:57:30] <Gat0rvean> jmp242: I've went another route, I wanted to figure out what removing a monitoring template from a Device class would do, but I just went in and set "Enabled" to False and that did it, instead of backing it up and removing ti
[01-Dec-2011 17:18:56] <rmatte> Gat0rvean: just unbinding the template from the class would have the same effect
[01-Dec-2011 17:19:03] <rmatte> templates have to be bound to a class to be functional
[01-Dec-2011 18:11:26] <designated> Hackman238, Any word on that new zenpack for ipsla? last time I asked you said it was being released on the 19th of Nov but I haven't been able to find anything regarding a new release.
[01-Dec-2011 18:14:03] <rmatte> There are still some small kinks to work out with it, but it should be out soon enough
[01-Dec-2011 18:14:13] <rmatte> I've been helping him with enhancing/fixing it
[01-Dec-2011 18:14:19] <designated> rmatte, thank you
[01-Dec-2011 18:14:33] <rmatte> I'll ask him about it tomorrow.
[01-Dec-2011 18:20:17] <designated> right on broham, thanks for the reply
[01-Dec-2011 18:20:43] <rmatte> np, I'm out of here, later
[01-Dec-2011 18:32:57] kocolosk is now known as kocolosk|away
[01-Dec-2011 18:55:12] kocolosk|away is now known as kocolosk
[01-Dec-2011 23:38:57] <dswift> hello, running ZenAWS, trying to model, I get NameError: global name 'ShellCommandJob' is not defined
[01-Dec-2011 23:39:18] <dswift> Somehow Products.Jobber.jobs is not being imported
[01-Dec-2011 23:39:34] <dswift> Anyone else see something similar in 3.2.1
[01-Dec-2011 23:39:36] <dswift> ?
[02-Dec-2011 00:00:01] [disconnected at Fri Dec 2 00:00:01 2011]
[02-Dec-2011 00:00:01] [connected at Fri Dec 2 00:00:01 2011]
[02-Dec-2011 00:00:15] [zenoss-logger (logger bot) has joined #zenoss]
[02-Dec-2011 07:03:37] kocolosk is now known as kocolosk|away
[02-Dec-2011 07:15:47] kocolosk|away is now known as kocolosk
[02-Dec-2011 08:26:27] <Gat0rvean> Could anyone possibly help me decipher a Zenhub error: "User-supplied Python expression (here.getTotalBlocks() * .9) for maximum value caused error: ['usedBlocks_usedBlocks']", this happened after I set a Monitoring Template Data Source to false, and has been happening since.
[02-Dec-2011 08:39:38] <ali3n0> hi folks, how do I lower ping check to be error severity instead of critical?
[02-Dec-2011 08:56:17] <jmp242> ali3n0: well, you can edit the mapping or use an event transform
[02-Dec-2011 09:08:37] <ali3n0> jmp242 event transform?
[02-Dec-2011 09:08:50] <ali3n0> I've missed that in the docs
[02-Dec-2011 09:13:31] <jmp242>
[02-Dec-2011 10:33:08] <ali3n0> rmatte: hi. I've followed your suggestion and refactored my query to use dmd instead of API. Strange thing is that dmd takes twice the time to compute :-| Seems that there's zendmd take few seconds to start up, is it a normal behavior?
[02-Dec-2011 10:35:38] <jmp242> ali3n0: it is normal for zendmd to take a bit to launch
[02-Dec-2011 10:36:11] <ali3n0> jmp242 then I guess it's more performing to do my task via API. It's ok
[02-Dec-2011 10:36:18] f00f is now known as f00fster
[02-Dec-2011 10:37:53] <jmp242> Seems fine to me - I don't do that sort of stuff, but yes, that's why the API is there
[02-Dec-2011 10:40:48] <f00fster> hey guys need some help with wmi
[02-Dec-2011 10:40:54] <f00fster> Zenoss is having some kind of issue with the WMI connection on db-public and WMI flaps between
[02-Dec-2011 10:40:55] <f00fster> Device: db-public.prod.novus.local
[02-Dec-2011 10:40:55] <f00fster> Component: Broadcom BCM5709C NetXtreme II GigE _NDIS VBD Client
[02-Dec-2011 10:40:56] <f00fster> Severity: Error
[02-Dec-2011 10:40:58] <f00fster> Time: 2011/12/01 20:00:50.000
[02-Dec-2011 10:41:00] <f00fster> Message:
[02-Dec-2011 10:41:02] <f00fster> Could not get WMI Instance (Received NT code 0xc002001b from query: SELECT NetConnectionStatus,DeviceID FROM Win32_NetworkAdapter)
[02-Dec-2011 10:41:05] <f00fster> and then clears itself a few seconds later with
[02-Dec-2011 10:41:13] <f00fster> Event: 'Could not get WMI Instance'
[02-Dec-2011 10:41:13] <f00fster> Cleared by: 'Could not get WMI Instance'
[02-Dec-2011 10:41:13] <f00fster> At: 2011/12/01 20:04:50.000
[02-Dec-2011 10:41:15] <f00fster> Device: db-public.prod.novus.local
[02-Dec-2011 10:41:18] <f00fster> Component: Broadcom BCM5709C NetXtreme II GigE _NDIS VBD Client
[02-Dec-2011 10:41:19] <f00fster> Severity: Error
[02-Dec-2011 10:41:21] <f00fster> Message:
[02-Dec-2011 10:41:23] <f00fster> Could not get WMI Instance (Received NT code 0xc002001b from query: SELECT NetConnectionStatus,DeviceID FROM Win32_NetworkAdapter)
[02-Dec-2011 10:41:26] <f00fster> anyone know why ?
[02-Dec-2011 11:00:41] <ali3n0> jmp242: I thought it was a better idea to query dmd instead of api because of performance reasons but it was not the case
[02-Dec-2011 11:01:10] <ali3n0> anyway, is there a built-in facility to read rrd collected data?
[02-Dec-2011 11:10:43] <jmp242> Hmm Hackman238 rmatte do you know?
[02-Dec-2011 11:38:42] <dpetzel> ali3n0: your looking for a way to read RRD data from the API or DMD?
[02-Dec-2011 11:39:26] <ali3n0> dpetzel: sorry I didn't know rrd much, I've found rrdtool dump and I got it
[02-Dec-2011 11:39:48] <dpetzel> ali3n0: OK cool, there are also ways to query it from DMD as well if there is a need
[02-Dec-2011 11:40:15] <ali3n0> dpetzel: sounds cool. is there an rrd object or something?
[02-Dec-2011 11:41:19] <dpetzel> ali3n0: one sec, grabbing the link to the method on the zenoss trac site
[02-Dec-2011 11:42:16] <ali3n0> sure
[02-Dec-2011 11:44:47] <dpetzel>
[02-Dec-2011 11:44:54] <dpetzel> fetchRRDValue
[02-Dec-2011 11:45:16] <dpetzel> but you dont need to create an RRDView object, due to inheritence.. I believe there is a publicly posted example (looking)
[02-Dec-2011 11:47:13] <dpetzel> this uses getRRDValues in that same class
[02-Dec-2011 11:55:03] <mloven> Hey, jmp242, you've been involved in the 4.2 Core beta, yes?
[02-Dec-2011 11:58:36] <jmp242> not really, there isn't a beta yet that I know of
[02-Dec-2011 11:58:45] <jmp242> Should be one soon though
[02-Dec-2011 12:00:01] [disconnected at Fri Dec 2 12:00:01 2011]
[02-Dec-2011 12:00:02] [connected at Fri Dec 2 12:00:02 2011]
[02-Dec-2011 12:00:15] [zenoss-logger (logger bot) has joined #zenoss]
[02-Dec-2011 12:00:33] <mloven> In the past, it was just what zenpacks you had installed, but it seems different this time...
[02-Dec-2011 12:04:08] <Hackman238> mloven: The big differnce will be packs and compatibility with impact and insight
[02-Dec-2011 12:04:31] <Hackman238> mloven: I'm sure there will be other minor differnces, but those are the definate big ones
[02-Dec-2011 12:11:06] <mloven> ok. cool. Thanks!
[02-Dec-2011 14:17:31] <GameMagister> dpetzel: on that script you reference how would you use that in zenoss instead of the command line?
[02-Dec-2011 14:18:02] <dpetzel> GameMagister: give me a few, on a call. will get back to you
[02-Dec-2011 14:18:11] <GameMagister> Thanks
[02-Dec-2011 14:31:50] <dpetzel> GameMagister: I dont think you would actually use the script in its current format from the GUI, If that is what you after I think you need to look at writing custom reports. I've not done it myself, but there is some documentation out there. Based on Shanes feedback in that thread, it sounds as though the zendmd approach is simpllier depending on your needs
[02-Dec-2011 14:33:25] <GameMagister> thanks... i will have to look into that ... what i am looking to do is we have 14 vpn tunnels that i monitor and just want to have txt for the throughtput up not graphs because that eats up too much screen
[02-Dec-2011 14:34:55] <dpetzel> GameMagister: Gotcha, should be pretty doable, and I believe I've seen folks discussing similar stuff, I just have not needed to cross that bridge myself yet
[02-Dec-2011 16:22:14] kocolosk is now known as kocolosk|away
[02-Dec-2011 17:51:14] <GameMagister> here.hw.serialNumber != ""
[02-Dec-2011 17:51:57] <GameMagister> I am working with the custom device query and i keep getting a red box for the query
[02-Dec-2011 17:52:03] <GameMagister> here.hw.serialNumber != ""
[02-Dec-2011 17:52:16] <GameMagister> i have tried that line and it does not like it.
[02-Dec-2011 17:52:59] <GameMagister> never mind... my bad i just figured it out... sheesh
[02-Dec-2011 23:58:35] tvincent_ is now known as tvincent
[03-Dec-2011 00:00:01] [disconnected at Sat Dec 3 00:00:01 2011]
[03-Dec-2011 00:00:02] [connected at Sat Dec 3 00:00:02 2011]
[03-Dec-2011 00:00:16] [zenoss-logger (logger bot) has joined #zenoss]
[03-Dec-2011 12:00:01] [disconnected at Sat Dec 3 12:00:01 2011]
[03-Dec-2011 12:00:01] [connected at Sat Dec 3 12:00:01 2011]
[03-Dec-2011 12:00:15] [zenoss-logger (logger bot) has joined #zenoss]
[04-Dec-2011 00:00:01] [disconnected at Sun Dec 4 00:00:01 2011]
[04-Dec-2011 00:00:02] [connected at Sun Dec 4 00:00:02 2011]
[04-Dec-2011 00:00:15] [zenoss-logger (logger bot) has joined #zenoss]
[04-Dec-2011 09:02:36] ilan is now known as Guest68739
[04-Dec-2011 09:02:36] crazed is now known as Guest87129
[04-Dec-2011 12:00:01] [disconnected at Sun Dec 4 12:00:01 2011]
[04-Dec-2011 12:00:02] [connected at Sun Dec 4 12:00:02 2011]
[04-Dec-2011 12:00:16] [zenoss-logger (logger bot) has joined #zenoss]
[05-Dec-2011 00:00:01] [disconnected at Mon Dec 5 00:00:01 2011]
[05-Dec-2011 00:00:02] [connected at Mon Dec 5 00:00:02 2011]
[05-Dec-2011 00:00:15] [zenoss-logger (logger bot) has joined #zenoss]
[05-Dec-2011 09:13:03] kocolosk|away is now known as kocolosk
[05-Dec-2011 09:25:07] <jmp242> morning all
[05-Dec-2011 09:33:51] <fragfutter> luckily morning is long past, but good morning to you.
[05-Dec-2011 09:38:17] <Sam-I-Am> moo.
[05-Dec-2011 09:38:28] <Sam-I-Am> its definitely morning here
[05-Dec-2011 09:39:36] <jmp242> Anyone see this thread and have any ideas?
[05-Dec-2011 09:39:37] <jmp242>
[05-Dec-2011 09:40:19] <ali3n0> hi folks. If i've got a derive data point and its value is constantly 0, could it be that zenoss is not creating the rrd file?
[05-Dec-2011 09:47:09] <dpetzel> ali3n0: I think if the rrd was not created you see a NaN, but you can check the filesystemt o confirm if the RRD file is being created
[05-Dec-2011 09:48:10] <ali3n0> dpetzel: the point is it's not there for one device, but I can see the command is actually printing data
[05-Dec-2011 09:49:54] <ali3n0> the only difference between other devices that are ok is that this one is printing 0 value for that data point
[05-Dec-2011 09:50:27] <dpetzel> Your saying the graph is printing 0, as opposed to 0's being printed in the collector logs correct?
[05-Dec-2011 09:52:32] <ali3n0> dpetzel: I'm saying there's no rrd file created for that data point, but I'm expecting a rrd file with just zeros
[05-Dec-2011 09:52:54] <dpetzel> ali3n0: ahh. OK, totally misunderstood the issue.. sorry
[05-Dec-2011 09:53:04] <ali3n0> and I'm not sure that if I have DERIVE as collecting type it is not creating it by default
[05-Dec-2011 09:53:11] <ali3n0> dpetzel: no reason to apologize
[05-Dec-2011 09:53:29] <dpetzel> what is the min/max on the datapoint?
[05-Dec-2011 09:53:38] <ali3n0> I guess it does zero - zero / delta_seconds
[05-Dec-2011 09:53:40] <dpetzel> assuming other datapoints on that device are working?
[05-Dec-2011 09:53:50] <ali3n0> I check
[05-Dec-2011 09:54:13] <ali3n0> dpetzel: there're no min nor max
[05-Dec-2011 09:54:26] <ali3n0> it's just a DERIVE
[05-Dec-2011 09:55:26] <dpetzel> understood that its dervie, but a derive can have a min and max. Other datapoints on the device are working?
[05-Dec-2011 09:55:37] <ali3n0> yes
[05-Dec-2011 09:55:59] <ali3n0> I thought that min+max was for dropping not valid values
[05-Dec-2011 09:56:09] <dpetzel> you thought correct
[05-Dec-2011 09:56:17] <dpetzel> so if you had derive with a min of 1
[05-Dec-2011 09:56:21] <dpetzel> a 0 would never get graphed
[05-Dec-2011 09:56:34] <ali3n0> dpetzel: I see
[05-Dec-2011 09:57:04] <dpetzel> the other devices, you mentioned graph this SAME datapoint with values of 0?, or do those others have values higher than 0?
[05-Dec-2011 10:00:52] <ali3n0> dpetzel: wait, I think I've got it, the command somehow got overwritten with a previous version, my bad I supposed it still was at latest
[05-Dec-2011 10:01:08] <ali3n0> I'll wait for zenoss to cycle but quite sure it's that
[05-Dec-2011 10:48:07] Guest87129 is now known as crazed
[05-Dec-2011 10:48:37] crazed is now known as Guest13739
[05-Dec-2011 10:50:00] Guest13739 is now known as crazed
[05-Dec-2011 11:33:35] <johnnynoc> hello everybody!
[05-Dec-2011 12:00:01] [disconnected at Mon Dec 5 12:00:01 2011]
[05-Dec-2011 12:00:02] [connected at Mon Dec 5 12:00:02 2011]
[05-Dec-2011 12:00:15] [zenoss-logger (logger bot) has joined #zenoss]
[05-Dec-2011 13:27:05] <jmp242> hey all, on 3.2.1 - is there a way to in the event console go back several days? The first seen last seen don't seem to work reliably for me... I recall you could just scroll down and it would load more, but that doesn't seem to be working - maybe just MySQL is busy
[05-Dec-2011 13:32:09] <jmp242> Yup, mySql is really busy ... top is showing 262% CPU use - on an 8 core box though ... anything I can do to get back the zenoss web UI or do I need to wait / force restart some daemons?
[05-Dec-2011 14:05:22] <jmp242> ok
[05-Dec-2011 14:05:25] <jmp242> It recovered
[05-Dec-2011 14:05:40] <jmp242> apparently futzing with the event console can really bog down MySQL
[05-Dec-2011 14:05:46] <jmp242> and kill the zenoss UI
[05-Dec-2011 16:54:11] <Hackman238> Hey all!
[05-Dec-2011 16:54:19] <f00fster> heyy Hackman238
[05-Dec-2011 16:54:20] <f00fster> wb!
[05-Dec-2011 16:54:35] <Hackman238> f00fster: Been a crazy few days
[05-Dec-2011 16:54:36] <Hackman238> LOL
[05-Dec-2011 16:54:48] <f00fster> hah
[05-Dec-2011 16:54:53] <f00fster> youre telling me
[05-Dec-2011 16:55:06] <f00fster> installed chef last week
[05-Dec-2011 16:55:06] <Hackman238>
[05-Dec-2011 16:55:16] <f00fster> been trying to do our whole infastructure all over using chef
[05-Dec-2011 16:55:21] <Hackman238> f00fster: Chef cook your goose?
[05-Dec-2011 16:55:26] <f00fster> also moved every single instance from ec2 to rackspace cloud
[05-Dec-2011 16:56:10] <Hackman238> f00fster: Chef works great...huge time saver. Left Amazon for Rackspace? Nice!
[05-Dec-2011 16:56:31] <f00fster> omg i love it
[05-Dec-2011 16:56:38] <f00fster> yeah amazon for rackspace cloud
[05-Dec-2011 16:56:46] <f00fster> we were having too many outage issues
[05-Dec-2011 16:57:09] <Hackman238> f00fster: Glad our product is working well for you!
[05-Dec-2011 16:57:22] <f00fster> ahh youre racksopace yes?
[05-Dec-2011 16:57:39] <f00fster> you do networking monitorinjg for all of rackspace?
[05-Dec-2011 16:57:50] <f00fster> dude
[05-Dec-2011 16:57:53] <f00fster> i was out in texas
[05-Dec-2011 16:57:57] <f00fster> over the summer
[05-Dec-2011 16:57:58] <f00fster> san jose
[05-Dec-2011 16:58:22] <f00fster> what am i saying... dfw area plano etc...
[05-Dec-2011 16:58:32] <Hackman238> I do
[05-Dec-2011 16:58:57] <Hackman238> Very cool. One of our largest DC's is in DFW area
[05-Dec-2011 16:59:15] <f00fster> awesome
[05-Dec-2011 16:59:17] <f00fster> loved texas
[05-Dec-2011 16:59:30] <f00fster> esp the 103 summertime weather across the week i was there
[05-Dec-2011 17:01:02] <Hackman238> f00fster: Hahaha
Its crazy...the winter temperatures here don't even classify as chilly to a former northerner like myself
[05-Dec-2011 17:20:55] kocolosk is now known as kocolosk|away
[05-Dec-2011 17:30:07] <mattray> is anyone using zenbatchload with 3.2.1?
[05-Dec-2011 17:30:39] <mattray> the syntax changed from 3.1 to 3.2
[05-Dec-2011 17:30:50] <mattray> and I can't find documentation on it
[05-Dec-2011 17:47:40] <mattray> ahh, it's gotten stricter. I guess that's good
[05-Dec-2011 18:13:44] <mattray> for those who may care, this works:
[05-Dec-2011 18:14:20] <mattray> /Systems/base2 description="testing of base2"
[05-Dec-2011 18:14:21] <mattray> /Groups/XXX description="XXX group"
[05-Dec-2011 18:14:21] <mattray> /Locations/austin3 description="austin3", setAddress="78750"
[05-Dec-2011 18:14:21] <mattray> /Devices/Server/SSH/Linux
[05-Dec-2011 18:14:21] <mattray> 10.0.111.3 setTitle='crushinator.rob', setLocation='/Seattle', setGroups=['/base'], setSystems=['/apt/cacher-client','/ntp','/sudo','/users/sysadmins','/zenoss/server']
[05-Dec-2011 18:14:21] <mattray> 10.0.111.7 setTitle='walt.rob', setLocation='/Austin', setGroups=['/admin','/base'], setSystems=['/ntp','/sudo','/users/sysadmins','/zenoss/client']
[05-Dec-2011 20:07:44] kocolosk|away is now known as kocolosk
[05-Dec-2011 22:06:16] Guest68739 is now known as ilan
[05-Dec-2011 22:13:21] <trnzmeta> guys: to get netflow running I need netflow/plixer zenpack?
[05-Dec-2011 22:13:59] <trnzmeta> however that relies on integrating with existing plixer scrutinizer software (needing licenses)
[05-Dec-2011 22:14:26] <trnzmeta> is there any other way to get netflows/ip accounting?
[05-Dec-2011 22:14:32] <trnzmeta> community version?
[06-Dec-2011 00:00:02] [disconnected at Tue Dec 6 00:00:02 2011]
[06-Dec-2011 00:00:03] [connected at Tue Dec 6 00:00:03 2011]
[06-Dec-2011 00:00:15] [zenoss-logger (logger bot) has joined #zenoss]
[06-Dec-2011 05:55:53] <ali3n0> hi folks. I'm wondering: defining a data point for a graph, the "consolidation" function is referring to how to interpolate missing values?
[06-Dec-2011 06:01:50] <gypsymauro> hi
[06-Dec-2011 06:02:40] <gypsymauro> I've some host with dhcp , can I manage them with zenoss?
[06-Dec-2011 06:04:34] <ali3n0> gypsymauro: we've got boxes on ec2 subscribing to zenoss via api
[06-Dec-2011 06:06:32] <gypsymauro> uhm it would be nice to have the link between device and MAC address
[06-Dec-2011 06:12:01] <ali3n0> gypsymauro: I don't get what you mean
[06-Dec-2011 06:12:29] <ali3n0> where do you want it?
[06-Dec-2011 06:39:08] <ali3n0> I don't understand this rrd graph: isn't max supposed to be the max value drawn in the graph?
[06-Dec-2011 08:22:42] kocolosk is now known as kocolosk|away
[06-Dec-2011 08:26:13] <jmp242> morning all
[06-Dec-2011 09:55:13] <ali3n0> morning jmp242
[06-Dec-2011 10:01:59] <f00fster> morning guys
[06-Dec-2011 12:00:02] [disconnected at Tue Dec 6 12:00:02 2011]
[06-Dec-2011 12:00:02] [connected at Tue Dec 6 12:00:02 2011]
[06-Dec-2011 12:00:13] [zenoss-logger (logger bot) has joined #zenoss]
[06-Dec-2011 14:09:14] <jmp242> quiet today
[06-Dec-2011 14:14:31] kocolosk|away is now known as kocolosk
[06-Dec-2011 14:22:11] <syoma> hi dear
[06-Dec-2011 14:24:14] <syoma> if possible create a daily report observed the total number of days a month?
[06-Dec-2011 16:22:28] <cymruman> when installing zenoss and I type in "su - zenoss" it is asking for a password.. I have tried the root password.. What is the zenoss default password?
[06-Dec-2011 16:27:15] <Morthez> do a su first, then su - zenoss
[06-Dec-2011 16:28:01] <cymruman> thank you
[06-Dec-2011 16:28:22] <Morthez> no problem
[06-Dec-2011 17:06:01] nonsenso_ is now known as nonsenso
[06-Dec-2011 21:25:58] kocolosk is now known as kocolosk|away
[07-Dec-2011 00:00:01] [disconnected at Wed Dec 7 00:00:01 2011]
[07-Dec-2011 00:00:02] [connected at Wed Dec 7 00:00:02 2011]
[07-Dec-2011 00:00:16] [zenoss-logger (logger bot) has joined #zenoss]
[07-Dec-2011 02:13:16] <meishao> hi, zenoss admin
[07-Dec-2011 02:13:47] <meishao> can i ask a qustion for zenoss json api for java?
[07-Dec-2011 02:17:04] <meishao> somebody is online?
[07-Dec-2011 04:57:17] <tightwork> How can I filter out a ppp Virtual-Access interface entirely? These are DSL lines that go up and down randomly and is necessary for me to monitor.
[07-Dec-2011 08:09:41] <jmp242> morning all
[07-Dec-2011 09:38:11] <gypsymauro> hi
[07-Dec-2011 09:38:42] <gypsymauro> can I add a custom action when I trap an event? I can just select from email or page
[07-Dec-2011 09:40:30] <cluther> gypsymauro: You're looking for event commands instead of alerting rules.
[07-Dec-2011 09:40:41] <cluther> Go to Event Manager -> Commands.
[07-Dec-2011 09:41:06] <cluther> It's the same process for filtering events as alerting rules, but you specify the command to run instead of the person to email or page.
[07-Dec-2011 09:45:01] <gypsymauro> cluther: I don't understand, I added the command as you said but how can I specify to run that command on a specified event?
[07-Dec-2011 09:49:07] <cluther> When you go to Events -> Event Manager -> Commands and add a command you should have a "Where" section under the command you create that lets you specify what kinds of events your command will execute for.
[07-Dec-2011 09:54:52] <jmp242> anyone have anything interesting to say on:
[07-Dec-2011 10:02:28] <gypsymauro> cluther: what's the difference between alerting rules and event manager?
[07-Dec-2011 10:04:32] <cluther> Alerting rules go to people (by email or page) whereas event commands have to individual target. They just fork out and run whatever command you specify on the shell.
[07-Dec-2011 10:05:16] <cluther> Other than that, they're pretty much the same. In Zenoss 4 we're collapsing them into the same place to try to make it more intuitive.
[07-Dec-2011 10:05:58] <cluther> jmp242: That's an odd one. My guess would be that the monitored devices are saturated, or have some kind of security software on them is shutting down traffic.
[07-Dec-2011 10:06:41] <mattray> is the zenoss 3.2.1 rpm known to be wonky? Installing it with yum is not working
[07-Dec-2011 10:09:17] <jmp242> Can you match multiple attributes in a trap with an event transform? - see
[07-Dec-2011 10:10:03] <jmp242> Final weird forum post - ... here I have no idea, it always seemed to work for me for this sort of situation
[07-Dec-2011 10:11:51] <gypsymauro> cluther: great news... there is an idea about the release date of 4.x? (1 year or more?)
[07-Dec-2011 10:13:52] <cluther> mattray: What happens with the yum install?
[07-Dec-2011 10:14:14] <cluther> It worked for me last time I tried.
[07-Dec-2011 10:14:17] <mattray> cluther: as you can probably guess, I'm working on fixing the chef installation
[07-Dec-2011 10:14:27] <mattray> deps are installed, then it blows up
[07-Dec-2011 10:15:01] <mattray> I'm trying again, I'll report back with more useful feedback
[07-Dec-2011 10:18:17] kocolosk|away is now known as kocolosk
[07-Dec-2011 10:20:05] <cluther> jmp242: I responded to the multiple varbind trap mapping topic.
[07-Dec-2011 10:26:10] <cluther> jmp242: Stacking thresholds like that can be tricky. I don't know what could have happened, but I requested that he provide the exact threshold configurations.
[07-Dec-2011 10:29:24] <mattt> someone mentioned this the other day, but i forgot to note it
what's the best way to alert if something reboots?
[07-Dec-2011 10:32:16] <cluther> mattt: You could put a 30000 minimum threshold on the sysUpTime datapoint. sysUpTime is the number of centiseconds (1/100th of a second) since the machine booted.
[07-Dec-2011 10:32:34] <cluther> So 300 seconds (5 minute polling cycle) * 100.
[07-Dec-2011 10:33:33] <mattt> cluther: cool, will look at that ... are these channel logs logged anywhere public?
[07-Dec-2011 10:34:00] <cluther> mattt:
[07-Dec-2011 10:34:33] <cluther> Wow.. apparently we're behind on publishing the monthly logs.
[07-Dec-2011 10:35:03] <mattt>
[07-Dec-2011 10:35:05] <mattt> just noticed that
[07-Dec-2011 10:35:20] <mattt> thanks anyway cluther
[07-Dec-2011 10:35:45] <cluther> I sent nyeates a reminder to catch it up.
[07-Dec-2011 10:38:01] <gypsymauro> where can I found info about the monitoring of vmware? there is commercial parts of zenoss for doing that?
[07-Dec-2011 10:50:04] <cluther> gypsymauro: You can find the commercial parts at
[07-Dec-2011 10:51:45] <cluther> There are several options available from the community. Search for vmware
[07-Dec-2011 10:57:18] <rocket> Hello from the LISA conference. Stop by the Zenoss booth Today or Tomorrow if you are attending the conference.
[07-Dec-2011 11:18:56] <gypsymauro> tank you cluther
[07-Dec-2011 11:19:11] <gypsymauro> it was a nice suprise to know that zenoss is based on zope
[07-Dec-2011 12:00:01] [disconnected at Wed Dec 7 12:00:01 2011]
[07-Dec-2011 12:00:01] [connected at Wed Dec 7 12:00:01 2011]
[07-Dec-2011 12:00:15] [zenoss-logger (logger bot) has joined #zenoss]
[07-Dec-2011 12:01:41] <Jane_Curry> Could any devs here comment on - zentrap fails periodically with 3.2.1???
[07-Dec-2011 12:02:02] <Jane_Curry> It makes zentrap close to unusable
[07-Dec-2011 12:02:15] <Jane_Curry> Hi cluther....
[07-Dec-2011 12:02:29] <Jane_Curry> How's the ZenPack documentation going????
[07-Dec-2011 12:46:33] <rmatte> Are there any plans to implement the new google API for the maps portlet so that we don't have to use the stupid API key?
[07-Dec-2011 12:47:04] <rmatte> that zentrap issue looks like quite the show stopper
[07-Dec-2011 12:53:15] <Jane_Curry> rmatte - yup - not nice!
[07-Dec-2011 13:04:29] <Jane_Curry> Is it me, or has it gine VERY quiet on all thing Zenoss over the last few weeks?????
[07-Dec-2011 13:08:36] <f00fster> Jane_Curry, the chanel has gotten a bit quiet youre right
[07-Dec-2011 13:15:35] <rmatte> yeh, it has
[07-Dec-2011 13:21:02] <GameMagister_> holidays do that to most of the lists and IRCs that i am on
[07-Dec-2011 14:12:19] <jmp242> busy busy busy
[07-Dec-2011 14:12:29] <jmp242> not at my desk all the time so... yes less
[07-Dec-2011 14:15:00] <rmatte> same
[07-Dec-2011 14:15:59] <Jane_Curry> I would really like to relaunch the joint development Zenpack ideas - any idea where we are on infrastructure for that?
[07-Dec-2011 14:18:30] <rmatte> Not sure, but I agree, that would allow us to get a lot of good stuff out there fast
[07-Dec-2011 14:25:24] <rmatte> well, I was going to upgrade to 3.2.1, but that zentrap issue is a total show stopper for me
[07-Dec-2011 14:25:38] <rmatte> when are they going to have a release that's actually production-worthy? It's getting ridiculous.
[07-Dec-2011 14:26:36] <GameMagister_> rmatte - i have been running 3.2.1 for about 2 months now and i have not had a single issue with zentrap dying...
[07-Dec-2011 14:27:29] <GameMagister_> and i am pulling traps from ~40 routers and switches
[07-Dec-2011 14:29:24] <rmatte> It probably only affects a certain install method then or something
[07-Dec-2011 14:29:46] <GameMagister_> i am on centos 5.7 installed from RPM
[07-Dec-2011 15:03:24] <rmatte> Jane uses stack with Ubuntu as far as I'm aware
[07-Dec-2011 15:03:30] <rmatte> and there have been stack specific issues in the past
[07-Dec-2011 15:03:33] <rmatte> so that could be part of it
[07-Dec-2011 15:04:33] <GameMagister_> sounds like it
[07-Dec-2011 15:37:09] <Jane_Curry> Where I have seen the zentrap issue is on a Debian 5.0.5 build ....
[07-Dec-2011 16:20:41] <rjune> I'm using the latest version of ZenOSS on CentOS 5.7, When viewing the graph from SNMP devices, Muticast graphs are always incrementing
[07-Dec-2011 16:25:26] <rjune> I checked ethernetCsmacd > InNUcastPackets, which show those data points as DERIVE, but the MRTG system I'm trying to replace doesn't show constantly increasing graphs like ZENOSS is. Is there a way to pull the raw nubmers from RRD, or troubleshoot exactly what's going on?
[07-Dec-2011 16:36:54] <archlich> Is there any way to access any of the providers in the root/MicrosoftIIsv2 namespace using wmi/wmic?
[07-Dec-2011 16:37:09] <cluther> rjune: You can look at the RRD file directly. It'll be in $ZENHOME/perf/Devices/<device_id>/os/interfaces/<interface_id>/InNUcastPackets_InNUcastPackets.rrd
[07-Dec-2011 16:37:23] <rjune> cluther, working on that now.
[07-Dec-2011 16:37:31] <cluther> Run "rrdtool info <filename.rrd>" on that. Make sure it really is a derive with minimum of 0 instead of a guage.
[07-Dec-2011 16:37:50] <cluther> If the file got created and the datapoint was changed to DERIVE later, the RRD won't be recreated.
[07-Dec-2011 16:38:00] <cluther> You can delete the file and it'll be recreated as a DERIVE on the next poll.
[07-Dec-2011 16:39:10] <cluther> Jane_Curry: I tracked down a ticket for that zentrap issue. It got set as verification so that we could reverify against the 4.x trunk. There was speculation that the problem was already fixed, but not specifically what change fixed it.
[07-Dec-2011 16:39:31] <dswift> How can I run a collection against a device from the commandline, to debug why a zenpack believes a component is down? I am trying to debug the zenJavaApp zenpack
[07-Dec-2011 16:39:42] <cluther> Jane_Curry: I updated the ticket to get the problem fixed in the 3.2.x branch instead of just hoping that it's already solved for 4.x.
[07-Dec-2011 16:40:02] <cluther> dswift: What kind of datasources does that ZenPack use? COMMAND?
[07-Dec-2011 16:40:24] <cluther> dswift: If it's COMMAND then you can run "zencommand run -v10 --device=<device_id>" from the command line to collect and log verbosely.
[07-Dec-2011 16:42:35] <dswift> cluther: that looks to be it - thank you kindly
[07-Dec-2011 16:46:52] <dswift> cluther: I am a bit off, it uses a jmx data source, but I see that zenjmx <same args> does what I need - thank you!
[07-Dec-2011 16:47:15] <cluther> doh, of course it does. No problem.
[07-Dec-2011 16:52:31] <rjune> cluther, type is derive, min and max are both NaN
[07-Dec-2011 16:53:45] kocolosk is now known as kocolosk|away
[07-Dec-2011 16:53:46] <cluther> Are you sure that this is the right RRD file for the graph you're looking at?
[07-Dec-2011 17:04:19] <bseklecki> .1.3.6.1.4.1.388.11.2.4.2.100.10.1.18.1 = Gauge32: 43 number of MUs
[07-Dec-2011 17:04:29] <rjune> cluther, yes
[07-Dec-2011 17:04:31] <bseklecki> how the hell is there there ASCII text in my guage32?
[07-Dec-2011 17:04:40] <rjune> ifInNUcastPackets_ifInNUcastPackets.rrd
[07-Dec-2011 17:05:03] <cluther> rjune: For the same device and interface?
[07-Dec-2011 17:05:33] <cluther> rjune: I ask because it wouldn't make sense for that to continually increase unless through some bizarre coincidence the multicast packet rate was continually increasing.
[07-Dec-2011 17:06:31] <cluther> bseklecki: Net-SNMP decodes this kind of stuff based on the syntax in the MIB if possible.
[07-Dec-2011 17:06:45] <cluther> bseklecki: There definitely isn't text in the data.
[07-Dec-2011 17:07:12] <cluther> bseklecki: I've researched how to turn all of Net-SNMP's decoding off, but I've only ever gotten as far as you are now.
[07-Dec-2011 17:08:00] <cluther> Wait.. that's not true. You can try using "-m none -O enU" as parameters to snmp*
[07-Dec-2011 17:08:09] <rjune> cluther, yup. I agree with you
[07-Dec-2011 17:08:26] <rjune> It doesn't make any sense at all, and it doesn't jive with the SNMP data.
[07-Dec-2011 17:08:38] <rjune> the only thing that makes any sense is for some reason SNMP is treating it like a guage
[07-Dec-2011 17:09:19] <cluther> rjune: Zenoss isn't keyed by the SNMP type (Counter*, Gauge* or Integer*). Only the DS type in the RRD file matters.
[07-Dec-2011 17:10:12] <rjune> cluther, I know, it's set in MOnitoring Templates
[07-Dec-2011 17:10:51] <cluther> Make sure there are no custom graph definitions.
[07-Dec-2011 17:11:01] <cluther> You can use rrdtool dump to dump the file out to XML that is somewhat readable.
[07-Dec-2011 17:11:03] <rjune> where would I check that?
[07-Dec-2011 17:11:07] <rjune> yeah, I did that
[07-Dec-2011 17:11:16] <cluther> The values were incrementing in the dump?
[07-Dec-2011 17:11:23] <rjune> <!-- 2011-12-05 14:05:00 CST / 1323115500 --> <row><v> 1.2995792905e-02 </v></row> <-- most rows look like that
[07-Dec-2011 17:11:34] <cluther> Roughly the same value?
[07-Dec-2011 17:11:37] <rjune> increment for a bit.
[07-Dec-2011 17:11:40] <rjune> then drop back down
[07-Dec-2011 17:11:51] <cluther> So that's what you'd expect, but not what you see on the graph?
[07-Dec-2011 17:12:17] <rjune>
[07-Dec-2011 17:12:21] <rjune> That's the dat
[07-Dec-2011 17:12:22] <rjune> data
[07-Dec-2011 17:12:34] <cluther> Custom Graph Definition: Go to the monitoring template, highlight the graph and choose "Custom Graph Definition" from the gear menu.
[07-Dec-2011 17:13:26] <rjune> looks not set.
[07-Dec-2011 17:13:34] <rjune> nothing in the text box.
[07-Dec-2011 17:13:43] <rjune> don't see any other interactive widgets
[07-Dec-2011 17:15:39] <mattt> if i extend snmpd with a script that returns 0 or 1, do i need to save this data to rrd?
[07-Dec-2011 17:15:57] <mattt> i just want a threshold that alerts if the returned value is 1, i don't care historically what the values are
[07-Dec-2011 17:16:03] <rjune> cluther, here's an oddity
[07-Dec-2011 17:17:49] <cluther> mattt: Yes, you have to save it. Sorry.
[07-Dec-2011 17:18:25] <mattt> cluther: :~(
[07-Dec-2011 17:18:27] <mattt> hehe, ok, thanks
[07-Dec-2011 17:18:30] <cluther> mattt: Assuming you're talking about SNMP.
[07-Dec-2011 17:18:38] <mattt> cluther: yep, i am
[07-Dec-2011 17:21:23] <rjune> one datapoint on the graph was derive, the other data point was set to guage as per rrd
[07-Dec-2011 17:22:11] <rjune> If I go to ethernetCsmacd however, the type on that datapoint is derive
[07-Dec-2011 17:25:20] <rjune> any ideas on that?
[07-Dec-2011 17:25:41] <rmatte> rjune: what are you trying to do exactly?
[07-Dec-2011 17:25:44] <rmatte> need some context
[07-Dec-2011 17:27:40] <rjune> rmatte, Multicast data is being stored and calculated as a guage instead of derive.
[07-Dec-2011 17:27:50] <rmatte> oh, you're collecting ifInNUcastPackets
[07-Dec-2011 17:28:00] <rjune> yea
[07-Dec-2011 17:28:25] <rmatte> When you created the datasource it would have defaulted to gauge if you didn't change it before creating it
[07-Dec-2011 17:28:32] <rjune> ifOutNU is derive in the template page.
[07-Dec-2011 17:28:43] <rmatte> so if you created it as gauge but changed it after, you need to find all of the RRDs that were created as gauge and delete them
[07-Dec-2011 17:28:44] <rjune> This is stock
[07-Dec-2011 17:29:03] <rjune> ethernetCsmacd, which is created
[07-Dec-2011 17:29:04] <rjune> gotcha
[07-Dec-2011 17:29:06] <rmatte> isn't the stock datapoint called ifInUcastPackets?
[07-Dec-2011 17:29:08] <rjune> thanks.
[07-Dec-2011 17:29:10] <rmatte> without the extra N
[07-Dec-2011 17:29:15] <rjune> Ucast is unicast
[07-Dec-2011 17:29:19] <rjune> NUcast is multicast
[07-Dec-2011 17:29:26] <rjune> different data
[07-Dec-2011 17:29:29] <rmatte> right, so you actually added the multicast datapoint then right?
[07-Dec-2011 17:29:36] <rmatte> because I'm sure it's not there by default in Core
[07-Dec-2011 17:29:58] <rjune> I didn't add it.
[07-Dec-2011 17:30:04] <rmatte> weird
[07-Dec-2011 17:30:11] <rjune> but it's possible something else did. I installed a couple of ZenPacks
[07-Dec-2011 17:30:17] <rmatte> ah
[07-Dec-2011 17:30:18] <rjune> which brings me to my second question
[07-Dec-2011 17:30:46] <rjune> I'm working on a pack for our equipment. I want to create a componant like the interface list
[07-Dec-2011 17:30:57] <rjune> where can I find the manual that covers all that?
[07-Dec-2011 17:31:22] <rmatte> Honestly, the best spot is an unofficial document:
[07-Dec-2011 17:31:40] <rmatte> Jane Curry wrote that and it's the most straight forward documentation for doing it
[07-Dec-2011 17:31:49] <rmatte> but I hope you're a good coder because it's not simpler
[07-Dec-2011 17:31:52] <rmatte> simple*
[07-Dec-2011 17:31:56] <rjune> I'm acceptable
[07-Dec-2011 17:32:18] <rmatte> well, then have a go at it
[07-Dec-2011 17:32:57] <rjune> thanks for the info.
[07-Dec-2011 17:33:05] <rmatte> np
[07-Dec-2011 17:37:25] lonetech007_ is now known as lonetech007
[07-Dec-2011 17:57:26] lonetech007_ is now known as lonetech007
[07-Dec-2011 21:14:19] <fixxxermet> If I change my snmpd.conf to for example add 'disk /opt' and 'disk /var', do I have to worry about the OIDs changing and zenoss not finding the correct info for previous data anymore?
[08-Dec-2011 00:00:01] [disconnected at Thu Dec 8 00:00:01 2011]
[08-Dec-2011 00:00:02] [connected at Thu Dec 8 00:00:02 2011]
[08-Dec-2011 00:00:14] [zenoss-logger (logger bot) has joined #zenoss]
[08-Dec-2011 00:46:58] <froztbyte> fixxxermet: how do you mean?
[08-Dec-2011 02:51:00] <fragfutter> froztbyte: no. those entries just produce snmp traps.
[08-Dec-2011 02:51:07] <fragfutter> ah, wrong.
[08-Dec-2011 02:51:16] <fragfutter> fixxxermet: no. those entries just produce snmp traps.
[08-Dec-2011 03:11:20] <qkit> hi guys,
[08-Dec-2011 03:12:03] <qkit> i install a zenpack and it causing the cpu spike to 98% cpu utilization. Any way to uninstall it beside when i stop the zenoss?
[08-Dec-2011 03:28:44] <zykes-> one thing zenoss should really get
[08-Dec-2011 03:28:51] <zykes-> is a better inline editor for transforms
[08-Dec-2011 03:29:05] <zykes-> or the ability to just say "this file" for a transorm
[08-Dec-2011 03:29:26] <zykes-> would be soooo much easier then the small forms on the web interface
[08-Dec-2011 03:48:07] <Jane_Curry> zykes: Agreed! They talked about that yonks back but it never happened....
[08-Dec-2011 03:48:53] <Jane_Curry> qkit: As the zenoss user....
[08-Dec-2011 03:49:05] <Jane_Curry> zenpack --remove <ZenPack name>
[08-Dec-2011 03:49:18] <Jane_Curry> Then recycle zenhub and zopectl with
[08-Dec-2011 03:49:23] <Jane_Curry> zenhub restart
[08-Dec-2011 03:49:28] <Jane_Curry> zopectl restart
[08-Dec-2011 03:49:46] <Jane_Curry> You might just run top first to see what process is soaking the CPU
[08-Dec-2011 03:49:58] <Jane_Curry> Which ZenPack did you install???
[08-Dec-2011 09:14:43] <jmp242> morning all
[08-Dec-2011 09:44:28] kocolosk|away is now known as kocolosk
[08-Dec-2011 09:57:54] jellis is now known as Poised
[08-Dec-2011 10:26:49] <jmp242> Anyone have a comment for this thread?:
[08-Dec-2011 10:31:18] <Trebortech> jpm242: So when they remove the device and add again it showed?
[08-Dec-2011 10:33:00] <jmp242> that wasn't too clear to me
[08-Dec-2011 10:34:23] <Trebortech> that's why I asked :-)… My guess would be they didn't have it added in production state as you advised and when they recreated they selected the correct production state.
[08-Dec-2011 10:36:31] <nyeates> FYI, There will be a dev meeting in about 25 mins in here.
[08-Dec-2011 10:53:16] <jmp242> I did ask in the thread
[08-Dec-2011 10:57:38] <nyeates> Hi James
[08-Dec-2011 11:00:37] <nyeates> themactech: how goes it? Any zenoss questions or curiosities lately?
[08-Dec-2011 11:01:32] <themactech> sorry multitasking
[08-Dec-2011 11:01:35] pmcguire is now known as ptmcg
[08-Dec-2011 11:01:46] <themactech> No questions now, I have had to put zenoss stuff on backburner
[08-Dec-2011 11:01:59] <mattray> for anyone using Zenoss with Chef, just committed Zenoss 3.2.1 support
[08-Dec-2011 11:02:16] <themactech> has 2 engineers leave and we booked a few jobs, I've gone 30+ hours without sleep twice in last week
[08-Dec-2011 11:02:29] <mattray> yikes
[08-Dec-2011 11:02:55] <themactech> We are going to have to get together to make an outline for a presentation at Penn State Mac Admin conference sometime after the x-mas holiday
[08-Dec-2011 11:03:04] <nyeates> mattray: oh shnap! nice. I will let the OpsCode guys here know....im sitting in LISA now
[08-Dec-2011 11:03:59] <themactech> hey Matt, you still doing a lot of Mac stuff at your new place? If so you should look at the Penn State Mac Sysadmin conference
[08-Dec-2011 11:04:15] <nyeates> themactech: yes. for sure. I want to take a look into Matt Rays Mac OS X ZenPack, maybe update it for 3.0 and bring that to the conference
[08-Dec-2011 11:04:16] <themactech> went last year for first time, insane amount of gurus in one place
[08-Dec-2011 11:04:21] <mattray> themactech: unfortunately we're doing a lot of Windows
[08-Dec-2011 11:04:41] <themactech> you have my sincere sympathies
[08-Dec-2011 11:04:50] <themactech> I have to do windows too once in awhile
[08-Dec-2011 11:04:54] <mattray> nyeates: the OSX ZenPack was supposed to be a tutorial series, slowly fleshing out OSX completely
[08-Dec-2011 11:05:08] <mattray> changing jobs ended the series
[08-Dec-2011 11:05:15] <themactech> I curl in a fetal position in shower weeping afterwards, repeating over and over "it won't come off"
[08-Dec-2011 11:05:32] <mattray> themactech: Chef does have a lot of OSX support
[08-Dec-2011 11:05:35] <nyeates> mattray: "slowly fleshing out OSX completely" .... I do not get this
[08-Dec-2011 11:05:37] <themactech> I am now working on a promise vtrack profile
[08-Dec-2011 11:05:53] <mattray> nyeates: if you look at the ZenPack, it's quite limited. A little bit of modeling
[08-Dec-2011 11:06:09] <themactech> since I have given up making custom components until 4.2 and the better doc comes out, I am going the shell scripting filter route instead
[08-Dec-2011 11:06:22] <themactech> not my plan A but I need to deploy something better right now
[08-Dec-2011 11:06:33] <mattray> themactech: packages with dmgs and homebrew, services, all that stuff. Lots of folks manage OSX workstations with Chef
[08-Dec-2011 11:06:35] <themactech> I am going to department of state later today to deploy Zenoss
[08-Dec-2011 11:07:19] <themactech> the guys who write chef, munki, and deploy studio were all at the Penn State conference last year
[08-Dec-2011 11:10:13] <nyeates> themactech: any high-level info you might want about custom components in 4.2, that we should either look into or see if a dev could talk to now?
[08-Dec-2011 11:10:49] <Hackman238> Hey all
[08-Dec-2011 11:10:50] <mattray> nyeates: is the install going to take even more resources? 4 gigs of RAM for the minimal install is painful
[08-Dec-2011 11:11:02] <mattray> especially when you're testing writing installation
[08-Dec-2011 11:11:21] <mattray> there's now Java in the mix too right?
[08-Dec-2011 11:11:34] <Hackman238> mattray: Its RAM hungry on the account it uses a combo of memcached and jetty
[08-Dec-2011 11:11:35] <jgartman> There is.
[08-Dec-2011 11:11:43] <nyeates> Hi Shane
[08-Dec-2011 11:12:37] <mattray> Hackman238: oh joy. Zope, MySQL, Jetty, Memcached on a single box? Is it going to be documented how to separate these to multiple machines for open source users?
[08-Dec-2011 11:12:47] <Hackman238> mattray: Though I've been able to run tiny test instances with as little as 2GB of RAM if you're very careful not to spawn too many modeler processes
[08-Dec-2011 11:13:01] <mattray> Hackman238: it takes 20+ minutes to install though
[08-Dec-2011 11:13:04] <themactech> I can't really pitch in any insight on anything related to 4.2, I have not had time to look into it or do testing. The only reason I can be here for a bit is I got stranded by a client, he bailed on me for 30 minutes and I am stuck waiting for him. When he shows I have to disconnect
[08-Dec-2011 11:13:07] <Hackman238> mattray: Yep. It is documented and it's not too bad
[08-Dec-2011 11:13:22] <nyeates> mattray: there is java in the mix - I think mostly in the new event system. zeneventd
[08-Dec-2011 11:13:23] <mattray> Hackman238: good, I'll automate that
[08-Dec-2011 11:13:38] <mattray> nyeates: yeah, I just don't want everything on a single box
[08-Dec-2011 11:13:58] <Hackman238> mattray: The mysql thats included is now wrapped in a crispy shell and called 'zends'. I dont know if this will be the case in the Core release.
[08-Dec-2011 11:14:10] <Hackman238> nyeates: Hey, how goes it?
[08-Dec-2011 11:14:27] <ptmcg> zeneventd is still python, you mean zeneventserver
[08-Dec-2011 11:14:33] <nyeates> mattray: what I will do, is record Simons BoF tonight here at LISA on video, and post it. He is speaking about the features and architecture of the coming 4.x core
[08-Dec-2011 11:14:40] <cluther> Hackman238: ZenDS won't be in the core release.
[08-Dec-2011 11:14:52] <Hackman238> cluther: Gotcha. Good to know.
[08-Dec-2011 11:15:28] <Hackman238> cluther: Any chance we'll move to postgres?
[08-Dec-2011 11:15:29] <nyeates> ptmcg: thanks. zeneventserver = java, zeneventd = python... yes?
[08-Dec-2011 11:15:37] <ptmcg> yep
[08-Dec-2011 11:15:38] <jgartman> nyeates: yes
[08-Dec-2011 11:15:39] <Hackman238> nyeates: yep
[08-Dec-2011 11:16:12] <jgartman> Hackman238: The word on high is "not anymore"
[08-Dec-2011 11:16:34] <Hackman238> jgartman: Really? Even with the costs?
[08-Dec-2011 11:16:37] <jgartman> er, something like "not right now" would probably be more accurate.
[08-Dec-2011 11:16:38] <cluther> Hackman238: Not for 4.2, but we will.
[08-Dec-2011 11:16:53] <Hackman238> cluther: / jgartman: Gotcha
[08-Dec-2011 11:17:02] <Hackman238> cluther: That SMS pack update is working
[08-Dec-2011 11:17:09] <Hackman238> cluther: TY very much
[08-Dec-2011 11:17:17] <mattray> fwiw, Oracle is getting litigious about embedding mysql in commercial applications
[08-Dec-2011 11:17:29] <zenphil> FYI, the 4.2 release may be announced as 4.1.1 even though it has a lot of improvement.
[08-Dec-2011 11:17:56] <mattray> more aggressive than Sun was. Opscode ripped out MySQL for PostgreSQL in our commercial offering
[08-Dec-2011 11:17:58] <Hackman238> mattray: Crazy.
[08-Dec-2011 11:18:09] <Hackman238> zenphil: Good to know. Why's that?
[08-Dec-2011 11:19:49] <cgw> 4.1.1 just have perf and scale improvements as opposed to functionality?
[08-Dec-2011 11:20:13] <ptmcg> "just" he says
[08-Dec-2011 11:20:22] <ptmcg> a ton
[08-Dec-2011 11:21:11] <jgartman> cgw: 4.1.1 is a pretty significant release w/r/t perf/scale things. Has a lot of things we have learned from huge deployments.
[08-Dec-2011 11:21:27] <cgw> well... hence only 4.1.1 rather than 4.2 my point
[08-Dec-2011 11:21:27] <Jane_Curry> what about the new events functionality - will that make it to 4.1.1??
[08-Dec-2011 11:21:37] <Hackman238> jgartman: *cough*
[08-Dec-2011 11:21:48] <ptmcg> New events is in 4.0, what add'l were you looking for?
[08-Dec-2011 11:21:59] <nyeates> mattray: Intersting on the Oracle front. We are in the legal I beleive - paying them for the commercial inclusion.
[08-Dec-2011 11:22:00] <nyeates> for now
[08-Dec-2011 11:22:08] <jgartman> Hackman238: I'm on your system right now watching that one *specific* daemon stop/restart for some mysterious reason
[08-Dec-2011 11:22:28] <Jane_Curry> Core doesn't have 4.0 yet - what will Core users get in the "next significant release"?
[08-Dec-2011 11:23:15] <mattray> nyeates: we weren't even using MySQL technically, just Percona. We wanted a commercial license for libmysql
[08-Dec-2011 11:23:16] <Hackman238> jgartman: BTW, that troublesome notification schedule is under 'Crit_Evt_SMS_BB_1st_S_Notification'
[08-Dec-2011 11:23:19] <Jane_Curry> And when will the beta arrive - early december (2011
) was the latest estimate I heard
[08-Dec-2011 11:23:28] <ptmcg> Oof, sorry - yes, new event stuff will be in 4.1.1
[08-Dec-2011 11:23:30] <jgartman> Hackman238: Excellent, I will look at that as well.
[08-Dec-2011 11:24:08] <Hackman238> jgartman: Any idea why that daemon keeps committing hari kari without a leaving a suicide note?
[08-Dec-2011 11:24:11] <zenphil> Jane: soon, late December most likely
[08-Dec-2011 11:24:12] <Hackman238> jgartman: Thanks man
[08-Dec-2011 11:24:14] <Jane_Curry> Hi cluther - how's the promised documentation coming on???
[08-Dec-2011 11:24:32] <Jane_Curry> Do you need an external reviewer??
[08-Dec-2011 11:24:37] <nyeates> ZenPack devs.... just fyi... new zenPacks will now be primarily hosted at github.com/your_username - not github.com/zenoss
[08-Dec-2011 11:24:47] <jgartman> Hackman238: Right now I'm baffled. It's getting a sigterm and logging as such; doesn't seem to be a code path that is exploding and bringing it down.
[08-Dec-2011 11:25:38] <Hackman238> jgartman: Strange. Keep me posted. And thanks for the hard work, it's appreciated.
[08-Dec-2011 11:25:43] <mattray> nyeates: will there be a place to download built eggs?
[08-Dec-2011 11:25:50] <Jane_Curry> nyeates: Yeh - I saw your note yesterday and thought that was what it meant....
[08-Dec-2011 11:26:05] <mattray> err, ZenPacks?
[08-Dec-2011 11:26:13] <cluther> Jane_Curry: I haven't done it yet, but I'll be sure that you're in the first to know when anything can be reviewed.
[08-Dec-2011 11:26:51] <Jane_Curry> So the onus is now on ZenPack developers to drive github and maintain ZenPacks, rather than Zenoss co-ordinating this????????????????
[08-Dec-2011 11:28:02] <nyeates> mattray: Yes. We plan to implement egg downloading inside of each github repository in the "Downloads" section.
[08-Dec-2011 11:28:12] <Jane_Curry> I guess this is good for developers that know their way around git but bad for the smaller contributors who have just knocked up something useful and want to share...
[08-Dec-2011 11:28:48] <mattray> nyeates: and Zenoss will provide those Downloads in their own github for their ZenPacks?
[08-Dec-2011 11:28:53] <Hackman238> Jane_Curry: 'knocked up' in America means something else.
[08-Dec-2011 11:29:08] <Jane_Curry> <cluther> I caught something from you yesterday about updating the zentrap dies ticket - but I can't see any updates?????
[08-Dec-2011 11:29:37] <Jane_Curry> So sorry - two nations divided by a common language again
[08-Dec-2011 11:29:41] <nyeates> Jane_Curry: This change is good for both devs and zenoss and everyone.
[08-Dec-2011 11:30:52] <nyeates> Jane_Curry: It is one less step for you guys to do and remember. Less pull requests on your part, and we link to all zenpacks at
[08-Dec-2011 11:31:21] <Jane_Curry> nyeates: I can see it is good for devs and Zenoss but I suspect it may raise the bar too high for casual devs (is "raising the bar too high" naughty-speak too??)
[08-Dec-2011 11:32:32] <jgartman> Jane_Curry: What are you concerned about that casual devs will have trouble with?
[08-Dec-2011 11:32:45] <nyeates> Jane_Curry: You had to post it to your personal git anyway, so no extra work there. Are you thinking that it will be hard for you to learn how to accept other peopls changes?
[08-Dec-2011 11:35:25] <nyeates> mattray: correct. Egg downloads will be located in our own ZenPacks at github.com/zenoss
[08-Dec-2011 11:35:25] <rocket> Jane_Curry: technically, having your own repo will actually simplify things significantly, after all, all you have to do is make a repo and tell us about it....
[08-Dec-2011 11:35:55] <Jane_Curry> jgartman: I found it non-trivial getting to grips with git - I am not at all a "heavy" developer. In the past, Zenoss coped with push requests and maintenance
[08-Dec-2011 11:36:15] <rocket> Jane_Curry: instead of worrying about forking and submitting pull requests.....
[08-Dec-2011 11:36:34] <mattray> nyeates: are there any available now?
[08-Dec-2011 11:37:13] <mattray> nyeates: I see a lot of repos, but no downloads
[08-Dec-2011 11:37:18] <jgartman> Jane_Curry: Ah I see, git itself. You're right, it takes some getting used to.
[08-Dec-2011 11:37:28] <rocket> Jane_Curry: also, the current state of affairs is just an intermediary step.... eventually we'll have github integration in the product and all you have to do is push a button to share
[08-Dec-2011 11:37:53] <mattray> nyeates: ok, found some
[08-Dec-2011 11:38:17] <rocket> mattray: you're correct, we're currently building the infrastructure to automate all this stuff
[08-Dec-2011 11:38:26] <mattray> rocket: ok, good
[08-Dec-2011 11:38:27] <rocket> btw: this is Simon
[08-Dec-2011 11:38:54] <rocket> from the LISA showfloor, where are you anyway mattray?
[08-Dec-2011 11:39:10] <mattray> rocket: I'm not there, was supposed to be doing training this week
[08-Dec-2011 11:39:20] <mattray> I'd expect there to be a download for each ZenPack in the Zenoss GitHub account, even the community ones
[08-Dec-2011 11:39:37] <Jane_Curry> I know that became an onerous burden on Zenoss but I am a little concerned that some folk will give up rather than donate code
[08-Dec-2011 11:39:58] <Jane_Curry> Perhaps it is an area where the Zenoss Community Alliance could help users????
[08-Dec-2011 11:40:00] <rocket> trust me, it will all be glorious
[08-Dec-2011 11:41:06] <Jane_Curry> and wonderful and marvellous and splendiferous ..... eventually
[08-Dec-2011 11:41:15] <nyeates> Jane_Curry: Git has a learning curve, it will take time to get this all straight.... We think it is the forward-thinking and right way to go in the long run.
[08-Dec-2011 11:41:24] <nyeates> Pain now for gain later
[08-Dec-2011 11:41:36] <cluther> All of the git instructions are for people who want to do it themselves. Power to the people.
[08-Dec-2011 11:41:44] <Jane_Curry> LOng run - definitely. Especially when there is help built-in to Core
[08-Dec-2011 11:41:53] <rocket> Jane_Curry: again, this is not about saving us work, this is a intermediary step towards making all this easier and tearing down barriers to contribution
[08-Dec-2011 11:42:17] <jgartman> git will really be a boon to the type of development that happens around zenpacks in the community. I know it's not much consolation now.
[08-Dec-2011 11:42:43] <rocket> it actually worries me that you think otherwise...
[08-Dec-2011 11:42:44] <cluther> If you have some ZenPack code and want to share it, you could still just send it to us the old fashioned way.
[08-Dec-2011 11:43:53] <nyeates> An example of git's usability from LISA: A user in a zenoss forum asked how they could easily find a piece of example code for their issue. They hated having to download eggs one by one, install them, then look for the code. The instructor brought up git, and delved into 2 zenpacks code in the matter of 30 seconds.
[08-Dec-2011 11:45:22] <Jane_Curry> Anyone got any comments on the thread her about the NewDeviceMap modeler - looks like a long-running saga
[08-Dec-2011 11:47:21] <zenphil> I'll check Trac and add it as a ticket if it's not already known by the dev team.
[08-Dec-2011 11:52:32] <nyeates> By the way - anyone here not familiar with LISA, Large Installation System Administration Conference.... You ought to be.
[08-Dec-2011 11:54:39] <nyeates> Its THE premier place to be for IT Ops geeks. I talked to the originators of RRD and Nagios in the halls, and attended BoFs by industry heavy weights. Neat stuff. Look into it for next year
[08-Dec-2011 11:56:08] lonetech007_ is now known as lonetech007
[08-Dec-2011 11:57:03] <nyeates> With this lull, I am going to stop the IRC dev session here. Back to the conference floor for me.
[08-Dec-2011 12:00:01] [disconnected at Thu Dec 8 12:00:01 2011]
[08-Dec-2011 12:00:02] [connected at Thu Dec 8 12:00:02 2011]
[08-Dec-2011 12:00:12] [zenoss-logger (logger bot) has joined #zenoss]
[08-Dec-2011 12:04:34] <Jane_Curry> <zenphil> If you open a ticket, please could you update the forum thread with that info?? Thanks for doing this
[08-Dec-2011 14:52:38] <Hackman238> stevex: Any relation to stevez?
[08-Dec-2011 14:53:06] <stevex> Hackman238: ha, no
[08-Dec-2011 14:53:46] <Hackman238> stevex:
[08-Dec-2011 15:21:55] <valsielu> Hello all... I have installed Zenoss for the first time and am having issues with Linux memory alerting. Is this the correct place to ask for assistance? I've looked through the FAQ and forums already.
[08-Dec-2011 15:28:00] <rocket> valsielu: it is
[08-Dec-2011 15:28:22] <valsielu> excellent. thank you.
[08-Dec-2011 15:28:24] <rocket> valsielu: it can be quiet in here at times .. sometimes it makes sense to ask at different times of day
[08-Dec-2011 15:28:59] <rocket> I am at a conference at the moment and not much help right now myself but if you ask the question others may answer as they get time
[08-Dec-2011 15:29:20] <valsielu> Sounds good.
[08-Dec-2011 15:37:30] <valsielu> The end goal is for me to generate a critical event once the used memory of a Linux server reaches 90%.
[08-Dec-2011 15:40:27] <valsielu> I was able to set up a threshold around the memAvailReal_memAvailReal DataPoint that was a static value, and this generated an event.
[08-Dec-2011 15:43:44] <valsielu> The problem is that it's a static value, and not a percentage.
[08-Dec-2011 15:49:47] <valsielu> I'm not sure how to go about this... I've seen posts of people trying and failing either thresholds with a calculation as the Maximum value, such as device.hw.totalMemory / 90.
[08-Dec-2011 15:49:50] <dpetzel> valsielu: take a look at page 70 of the admin guide, you can use formulas and as such use a percentage
[08-Dec-2011 15:50:06] <valsielu> I've also seen people fail with event transforms.
[08-Dec-2011 15:50:12] <valsielu> roger... i'll check it out now.
[08-Dec-2011 16:00:56] kocolosk is now known as kocolosk|away
[08-Dec-2011 16:03:17] kocolosk|away is now known as kocolosk
[08-Dec-2011 16:54:07] <ipengineer> does anyone know what rrd type to use in zenoss when using cpuRawSystem?
[08-Dec-2011 16:55:52] <dhopp> ipengineer: I think you need to use derive
[08-Dec-2011 16:56:35] <ipengineer> do I need to add something to the forumla? For some reason I am getting a really high percentage value
[08-Dec-2011 16:59:08] <ipengineer> I am getting a value of like cur: 175889816.6%
[08-Dec-2011 18:17:10] lonetech007_ is now known as lonetech007
[08-Dec-2011 18:33:43] kocolosk is now known as kocolosk|away
[09-Dec-2011 00:00:01] [disconnected at Fri Dec 9 00:00:01 2011]
[09-Dec-2011 00:00:02] [connected at Fri Dec 9 00:00:02 2011]
[09-Dec-2011 00:00:14] [zenoss-logger (logger bot) has joined #zenoss]
[09-Dec-2011 08:25:51] <jmp242> Friday morning!!!
[09-Dec-2011 08:25:58] <jmp242> how is everyone?
[09-Dec-2011 08:56:09] <tightwork> Im ok,, nervous. had a job interview on Wednesday so just all messed up in suspense.
[09-Dec-2011 09:25:16] <tightwork> How could I remove ppp interface from being modeled in cisco model plugin?
[09-Dec-2011 09:27:12] <cluther> tightwork: Add it to the zInterfaceMapIgnoreNames property for the device class.
[09-Dec-2011 09:27:33] <cluther> zInterfaceMapIgnoreNames is a regular expression. Any interface names that match it will not be modeled.
[09-Dec-2011 09:27:56] <tightwork> great, thanks!
[09-Dec-2011 09:29:47] <tightwork> cluther: will I need to make that as a custom property ?
[09-Dec-2011 09:30:12] <cluther> tightwork: No, it's a standard configuration property.
[09-Dec-2011 09:30:42] <tightwork> ah i see it now, filter wigged out :-|
[09-Dec-2011 09:41:21] <tightwork> I setup a template for lm_sensors, although it is graphing at 30k instead of 30? I suppose I need an RPN expression?
[09-Dec-2011 09:42:29] <cluther> tightwork: Yeah. A lot of MIBS do a multiple of the original value to capture more precision.
[09-Dec-2011 09:42:41] <cluther> RPN would be 1000,/
[09-Dec-2011 09:44:18] kocolosk|away is now known as kocolosk
[09-Dec-2011 10:45:21] <tightwork> Hmm, Im using predictive threshold and setting the RPN changed the value, although the predictions and confidence band is not
[09-Dec-2011 10:46:16] <tightwork>
[09-Dec-2011 10:59:30] <Hackman238> tightwork: Not sure you can use the RPN to do this. this is because must of the differential is done by RRD and stored in its own ds.
[09-Dec-2011 10:59:40] <Hackman238> jgartman: How goes it?
[09-Dec-2011 10:59:45] <Hackman238> jmp242: How goes it?
[09-Dec-2011 10:59:53] <Hackman238> cluther: How goes it?
[09-Dec-2011 11:00:08] <jmp242> busy
[09-Dec-2011 11:00:18] <jmp242> doing netbackup 7.1 install and config on SL6.1
[09-Dec-2011 11:00:36] <jmp242> and some SL5 -> 6.1 upgrades though that's just reinstalls
[09-Dec-2011 11:01:02] <Hackman238> jmp242: Yeah its unfortunate there isn't a direct upgrade path thats reliable.
[09-Dec-2011 11:01:07] <jmp242> ehh
[09-Dec-2011 11:01:14] <jmp242> no biggy - nothing local to desktops
[09-Dec-2011 11:01:19] <jmp242> just a little down time
[09-Dec-2011 11:10:49] <Jane_Curry> Afternoon....
[09-Dec-2011 11:36:45] <jmp242> Jane_Curry / Hackman238 ... any other ideas for this guy?
[09-Dec-2011 11:37:29] <jmp242> cluther: if you've got a second, the thread you responded to has posted more info:
[09-Dec-2011 11:44:46] <Hackman238> jmp242: /window 6
[09-Dec-2011 11:53:16] <Jane_Curry> jmp242: I sent the guy a note privately offering a little consultancy
[09-Dec-2011 12:00:01] [disconnected at Fri Dec 9 12:00:01 2011]
[09-Dec-2011 12:00:01] [connected at Fri Dec 9 12:00:01 2011]
[09-Dec-2011 12:00:12] [zenoss-logger (logger bot) has joined #zenoss]
[09-Dec-2011 12:04:24] <f00fster> anyone have a system/pics of a system that sends alerts to a red amber light in the devops desk
[09-Dec-2011 12:04:31] <f00fster> thought it'd be really cool
[09-Dec-2011 12:04:34] <f00fster> links?
[09-Dec-2011 12:08:44] <mattray> f00fster: like?
[09-Dec-2011 12:08:48] <jmp242> sounds reasonable Jane_Curry
[09-Dec-2011 12:09:16] <jmp242> sorry, i'm in and out a bit today -busy busy
[09-Dec-2011 12:09:25] <mattray> f00fster: completely unrelated, to your question, did I see you talking about Chef/Zenoss stuff the other day? If so keep me in the loop
[09-Dec-2011 12:12:41] <f00fster> matthew, cheff zenoss ?
[09-Dec-2011 12:12:42] <f00fster> hrmm
[09-Dec-2011 12:22:57] <tightwork> $150 !
[09-Dec-2011 12:24:56] <tightwork> You could get a graphic vfd for less, and actually get output.
[09-Dec-2011 12:25:03] <tightwork> err, character vfd
[09-Dec-2011 12:25:21] <tightwork> usb too
[09-Dec-2011 12:25:31] <tightwork> but yea chef is awesome, thats my focus as well
[09-Dec-2011 13:21:08] <_robo_> hello: I'm using the dns monitor zenpack but it's not working. Is there a way to see what commands the dns monitor is executing?
[09-Dec-2011 13:22:45] <_robo_> or anyway to figure out whyi it's not working?
[09-Dec-2011 13:28:18] <_robo_> hmm, this is odd. So it looks like dns monitor uses the host command. What's weird is if I run the host command it as the zenoss user i get this error "host: /usr/local/zenoss/common/lib/libcrypto.so.0.9.8: no version information available (required by /usr/lib/libdns.so.64"
[09-Dec-2011 13:28:28] <_robo_> If I run 'host' as root everything works fine
[09-Dec-2011 13:44:09] <robo_> hm
[09-Dec-2011 14:36:05] <f00fster> mattray, dude... what were you saying about chef with zenoss ?
[09-Dec-2011 14:36:08] <f00fster> lets do this ?!
[09-Dec-2011 14:42:27] <mattray> f00fster:
[09-Dec-2011 14:55:11] <otakup0pe> wait is it no longer possible to use http auth for zenoss :|
[09-Dec-2011 14:55:23] <otakup0pe> it's all cookie based now ain't it
[09-Dec-2011 14:55:24] <otakup0pe> grr
[09-Dec-2011 15:02:25] <otakup0pe> oh nm i'm just being dumb
[09-Dec-2011 15:17:58] <otakup0pe> hey what format does start/end expect for getRRDValue
[09-Dec-2011 15:18:35] <otakup0pe> ah epoch
[09-Dec-2011 15:18:53] <f00fster> mattray, you are planning on updating it ? you made it whats going on ?
[09-Dec-2011 15:19:12] <mattray> f00fster: I just updated it for 3.2.1
[09-Dec-2011 15:19:39] <f00fster> mattray, you are the man
[09-Dec-2011 15:19:57] <f00fster> do you know how i can automtically add rackspace cloud servers on auto on a chef run on the server ?
[09-Dec-2011 15:20:00] <f00fster> or when it first installs
[09-Dec-2011 15:20:02] <f00fster> ?
[09-Dec-2011 15:20:11] <f00fster> mattray, i priv-messaged you
[09-Dec-2011 15:23:08] <mattray> adding servers to Zenoss is done automatically with the Chef cookbook. You just have to put the Chef-managed nodes in a role that maps to a Zenoss Device Class
[09-Dec-2011 15:43:47] <otakup0pe> ugh inconsistent apis. love the uid vs id
[09-Dec-2011 15:50:03] <otakup0pe> hm is there a jsonapi equiv to getGraphDefUrl
[09-Dec-2011 15:55:58] <otakup0pe> trying to figure out how to get a list of graphs from a device id
[09-Dec-2011 15:56:28] <otakup0pe> via json api. can get the templates but can't seem to figure out how to conver those to graph urls. using chrome dev tools is just confusing
[09-Dec-2011 15:58:17] <otakup0pe> and whats with these GET's on data:image/gif;base64
[09-Dec-2011 15:58:18] <otakup0pe> kinda kinky
[09-Dec-2011 16:01:14] <otakup0pe> anyone ? bueler ? :V
[09-Dec-2011 16:03:28] <otakup0pe> ohhhhhh it's encoded into the gopts request into rrd server
[09-Dec-2011 16:03:35] <otakup0pe> hey why doesn't the rrdserver take http auth
[09-Dec-2011 16:13:15] <otakup0pe> hey so what will break if i add a PAS to the RenderServer :v
[09-Dec-2011 16:13:25] <otakup0pe> as long as cookies are enabvled will it cause "problems" ?
[09-Dec-2011 16:13:45] <opapo> I don't see how to change the memory settings on
[09-Dec-2011 16:13:54] <opapo> I am on Zenoss 3.x
[09-Dec-2011 16:21:15] <opapo> What does this mean "Navigate to /Events/Perf/Memory and select More -> Transform from the menu. Insert the following transform and save:"
[09-Dec-2011 16:21:18] <opapo> in the tutorial
[09-Dec-2011 17:06:08] <valsielu> opapo: Which part of that istruction are you stuck on?
[09-Dec-2011 17:21:59] kocolosk is now known as kocolosk|away
[09-Dec-2011 17:22:36] <opapo> the part where it says after you install the zenpack "Navigate to ...."
[09-Dec-2011 17:23:01] <opapo> I don't know how to navigate to that spot
[09-Dec-2011 18:15:11] <eidolon> hi folks, i'm tryig to settle an argument with someone in the office
if i have some reasonable hardwware to throw at it - how large an installed base can Zenoss monitor and alert? I'm looking at possibly thousands of hosts. I want to do basic monitoring (ping, port check), but also stats gathering (load, memory, etc)
[09-Dec-2011 18:16:46] <mattray> eidolon: given a beefy enough box, thousands
[09-Dec-2011 18:16:55] <eidolon> how many thousands?
[09-Dec-2011 18:17:04] <eidolon> (my upper limit is somewhere around 8)
[09-Dec-2011 18:17:07] <eidolon> hah
[09-Dec-2011 18:17:08] <eidolon> 'eight'
[09-Dec-2011 18:17:13] <eidolon> stupid smiley substituter.
[09-Dec-2011 18:17:38] <mattray> you'll want to distribute that to multiple boxes
[09-Dec-2011 18:17:57] <mattray> back when I worked for Zenoss, the largest open source install I heard of was 25K
[09-Dec-2011 18:18:04] <eidolon> so, there's my next question. i know that zenoss can split up like that, but it's been a few years since i did this.
[09-Dec-2011 18:18:22] <eidolon> do you use gatherers to accept the snmp traps and they report to the front end?
[09-Dec-2011 18:18:38] <eidolon> we had problems with performance on about 600 hosts. the database was a mess
[09-Dec-2011 18:19:21] <mattray> I'm a little out of the loop these days, but talk to rmatte or Hackman238 about scaling it up.
[09-Dec-2011 18:19:33] <mattray> lots of techniques, depending on your bottlenecs
[09-Dec-2011 18:19:35] <eidolon> (seriously i'm being said 'no, icinga / nagios is better. we just write custom monitors for that vmware cluster. it'll be fine.)
[09-Dec-2011 18:19:53] <eidolon> and i find nagios / icinga's front ends to be abysmal.
[09-Dec-2011 18:20:09] <mattray> agreed
[09-Dec-2011 18:20:36] <mattray> the commercial product is a lot easier to scale out of the box, the open source depends on tracking down all the tweaks
[09-Dec-2011 18:20:46] * eidolon nods
[09-Dec-2011 18:20:53] <eidolon> we were running commercial at my last gig.
[09-Dec-2011 18:21:16] <eidolon> thanks.
[09-Dec-2011 18:21:45] <eidolon> ooo. zenoss.org supplies vmware images. awesome.
[09-Dec-2011 18:24:48] <eidolon> ballpark handwave. any idea what the enterprise / commercial product costs?
[09-Dec-2011 18:34:00] <opapo> I found one of my problem. bc needs to be installed.
[09-Dec-2011 18:34:09] <opapo> Then it crashed and I sent the report in.
[09-Dec-2011 18:34:20] <opapo> hope that helps someone
[09-Dec-2011 18:34:23] <opapo> got to go
[09-Dec-2011 19:04:11] zanefactory_ is now known as zanefactory
[10-Dec-2011 00:00:01] [disconnected at Sat Dec 10 00:00:01 2011]
[10-Dec-2011 12:00:01] [connected at Sat Dec 10 12:00:01 2011]
[10-Dec-2011 12:00:16] [zenoss-logger (logger bot) has joined #zenoss]
[11-Dec-2011 00:00:01] [disconnected at Sun Dec 11 00:00:01 2011]
[11-Dec-2011 00:00:01] [connected at Sun Dec 11 00:00:01 2011]
[11-Dec-2011 00:00:01] [disconnected at Sun Dec 11 00:00:01 2011]
[11-Dec-2011 00:00:02] [connected at Sun Dec 11 00:00:02 2011]
[11-Dec-2011 00:00:12] [zenoss-logger (logger bot) has joined #zenoss]
[11-Dec-2011 02:56:59] tvincent_ is now known as tvincent
[11-Dec-2011 12:00:01] [disconnected at Sun Dec 11 12:00:01 2011]
[11-Dec-2011 12:00:02] [connected at Sun Dec 11 12:00:02 2011]
[11-Dec-2011 12:00:14] [zenoss-logger (logger bot) has joined #zenoss]
[12-Dec-2011 00:00:01] [disconnected at Mon Dec 12 00:00:01 2011]
[12-Dec-2011 00:00:01] [connected at Mon Dec 12 00:00:01 2011]
[12-Dec-2011 00:00:12] [zenoss-logger (logger bot) has joined #zenoss]
[12-Dec-2011 09:03:08] <jmp242> Morning all
[12-Dec-2011 09:03:16] <jmp242> and a monday :~
[12-Dec-2011 09:08:03] <Hackman238> Morning!
[12-Dec-2011 09:08:07] <Hackman238> jmp242: How goes the war?
[12-Dec-2011 09:15:02] <jmp242> ehh
[12-Dec-2011 09:15:09] <jmp242> Symantec Netbackup fun
[12-Dec-2011 09:15:47] <Hackman238> jmp242: Sort of like a rollercoaster of 'it's working!' and 'wait, no its not...'
[12-Dec-2011 09:15:54] <Hackman238>
[12-Dec-2011 09:27:58] <jmp242> Well, I think it's working lol
[12-Dec-2011 09:28:14] <jmp242> but it likes to fake you out
[12-Dec-2011 09:28:18] <jmp242> as to what's available
[12-Dec-2011 09:30:04] <Hackman238> LOL
[12-Dec-2011 09:37:24] <jb> ok
[12-Dec-2011 09:37:35] <jb> why am I not seeing the place to configure alerts in 4.1.0?!
[12-Dec-2011 09:38:32] <jb> in 3.x, I would click on the username and see "Alerting Rules"
[12-Dec-2011 09:41:49] <jb> the documentation for all of the zen products are confusing now.
[12-Dec-2011 09:44:06] <Hackman238> jb: Triggers and Notifications can be configured on the 'Events' tab -> 'Triggers'
[12-Dec-2011 09:44:42] <jb> ah, so this replaces the "Alerting Rules" ?
[12-Dec-2011 09:45:30] <jb> h
[12-Dec-2011 09:45:32] <jb> hmm.
[12-Dec-2011 09:46:05] <jb> this is totally different
[12-Dec-2011 09:47:40] <Hackman238> jb: Completely
[12-Dec-2011 09:47:48] <Hackman238>
[12-Dec-2011 09:47:53] <jb> is it better?
[12-Dec-2011 09:47:58] <jb> because it seems confusing at the moment
[12-Dec-2011 09:48:04] <Hackman238> jb: It is.
[12-Dec-2011 09:48:21] <Hackman238> jb: In all honesty it seems confusing, but its much better.
[12-Dec-2011 09:48:45] <jb> so, instead of creating an "alerting rule," I now create a trigger. right?
[12-Dec-2011 09:49:16] <Hackman238> jb: Triggers fire based on events. Notifications are assigned to Triggers. So triggers trigger notifications.
[12-Dec-2011 09:49:25] <jb> ^#@(*
[12-Dec-2011 09:58:07] <jb> hrm, so you can't specify email addresses that arne't zenoss users
[12-Dec-2011 09:58:11] <jb> to receive email notifiations
[12-Dec-2011 09:58:23] <jb> oh, yeah you can
[12-Dec-2011 09:59:09] <jb> confusing
we'll see if this works.
[12-Dec-2011 10:06:25] <jb> i must say.. the documentation for this is very lacking.
[12-Dec-2011 10:06:43] <Hackman238> jb: ....I hear that
[12-Dec-2011 10:07:03] <jb> if I specify two devices for the trigger
[12-Dec-2011 10:07:17] <jb> will it trigger if the event is from EITHER (or) of the two devices?
[12-Dec-2011 10:08:41] <jb> oh, any/all.
[12-Dec-2011 10:10:56] <jmp242> Gaahhh, changing all the terms
[12-Dec-2011 10:11:03] <jmp242> this will be a real PITA for docs
[12-Dec-2011 10:11:06] <jmp242> and new users
[12-Dec-2011 10:11:42] <jb> jmp242: it's a PITA for existing users.
[12-Dec-2011 10:11:52] <Hackman238> jb: It depends on if theres an and or an or.
[12-Dec-2011 10:12:07] <jb> Hackman238: but you can't really specify AND/OR like you could in 3.x.
[12-Dec-2011 10:12:10] <Hackman238> Since you can't condition on two devices in an alert I think its a default or
[12-Dec-2011 10:12:39] <jb> i think its been replaced with "all/any"
[12-Dec-2011 10:12:57] <Hackman238> jb: Let me double check. Admitadly I set and forget this stuff
[12-Dec-2011 10:14:11] <jb>
[12-Dec-2011 10:14:44] <jb> what I think that means is: it will trigger is the device is either "wr-dc-ltm-390..." or "rg-dc-ltm-3900..."
[12-Dec-2011 10:14:55] <jb> and the component of the event for either device contains "wrxxentex"
[12-Dec-2011 10:15:12] <Hackman238> jb: Thats exactly right. You'll need two seperate triggers.
[12-Dec-2011 10:15:31] <Hackman238> jb: What I would do is add both of the devices to a group and condition off that
[12-Dec-2011 10:15:43] <jb> so that wouldn't work
[12-Dec-2011 10:15:43] <jb> ?
[12-Dec-2011 10:16:05] <Hackman238> jb: It would, but it's harder to maintain than a single grou[
[12-Dec-2011 10:16:12] <jb> yeha
[12-Dec-2011 10:16:14] <jb> just testing
[12-Dec-2011 10:16:19] <jb> it doesn't seem to be alerting though
[12-Dec-2011 10:16:21] <Hackman238> jb: But yes, that should work
[12-Dec-2011 10:16:38] <Hackman238> jb: You'll need to create a notification. In said notification select this trigger
[12-Dec-2011 10:16:43] <jb> in 3.x, if I created an alert, and events already existed that met that condition, it would generate alerts
[12-Dec-2011 10:16:46] <jb> right
[12-Dec-2011 10:17:20] <Hackman238> jb: Oh I see. Im my experience events generally need to reoccur
[12-Dec-2011 10:17:35] <jb> yeah let me force a new event
[12-Dec-2011 10:17:50] <Hackman238> jb: This could just be because my practice has always been to close and reopen the events for testing.
[12-Dec-2011 10:26:28] <Hackman238> jb: Any luck?
[12-Dec-2011 10:27:40] <jb> just got done creating a group
[12-Dec-2011 10:27:40] <jb> sec
[12-Dec-2011 10:35:56] <jb> i don't like how you can't have spaces in the Notification names
[12-Dec-2011 10:36:07] <Hackman238> jb: ...I agree.
[12-Dec-2011 10:36:31] <Hackman238> jb: Do yourself a huge favor and don't use dashes or any symbolb other that underscore or it could cause problems
[12-Dec-2011 10:36:38] <Hackman238> *symbol
[12-Dec-2011 10:36:40] <jb> yeah i'm not
[12-Dec-2011 10:37:09] <Hackman238> jb: Also be cautious not to make trigger names too long otherwise they will be hard to read in the notification trigger selection drop down
[12-Dec-2011 10:38:25] <jb> k, got one of them working
[12-Dec-2011 10:38:59] <Hackman238> jb: Nice
[12-Dec-2011 10:39:18] <Hackman238> jb: did the nested any under the and work?
[12-Dec-2011 10:39:51] <jb> yep
[12-Dec-2011 10:39:59] <Hackman238> jb: Very cool.
[12-Dec-2011 10:40:04] <jb> this is making me re-think my entire alerting setup
[12-Dec-2011 10:40:15] <Hackman238> jb: Yes, completely./
[12-Dec-2011 10:40:45] <Hackman238> jb: Its good though. We sent from having like 60 rules down to about 6 triggers.
[12-Dec-2011 10:41:06] <jb> yeah i think I'm making my triggers too granular
[12-Dec-2011 10:42:18] <Hackman238> jb: Definately easy to do in the older version
[12-Dec-2011 10:42:59] <jb> ok this trigger isn't working because the IP service monitor isn't working :/
[12-Dec-2011 10:43:02] <jb> it says TCP/8080 is up
[12-Dec-2011 10:43:04] <jb> but, it's not.
[12-Dec-2011 10:44:38] <Hackman238> jb: Hum. I can't help much with that. Personally I dont use the port tests at all
[12-Dec-2011 10:45:05] <Hackman238> jb: you could try bouncing zenstatus
[12-Dec-2011 10:50:47] <rmatte> yeh, restart zenstatus and see if that helps... you should also try a reindex in zendmd, I find that helps in cases like that
[12-Dec-2011 10:51:03] <Hackman238> No no no
[12-Dec-2011 10:51:11] <Hackman238> Don't reindex.
[12-Dec-2011 10:51:23] <Hackman238> rmatte: With relstorage the history table is innodb
[12-Dec-2011 10:51:32] <rmatte> oh
[12-Dec-2011 10:51:39] <rmatte> didn't realize he was on relstorage
[12-Dec-2011 10:51:46] <Hackman238> rmatte: It'll grow like cancer and eat up the disk
[12-Dec-2011 10:51:56] <Hackman238> rmatte: How's it going?
[12-Dec-2011 10:52:54] <jb> ok guys
[12-Dec-2011 10:52:57] <jb> need help with one more thing
[12-Dec-2011 10:53:10] <jb> i have an objects.xml from a zenpack that contains only transforms.
[12-Dec-2011 10:53:19] <rmatte> Hackman238: going alright, busy
[12-Dec-2011 10:53:35] <Hackman238> rmatte: Glad to hear
[12-Dec-2011 10:53:44] <jb> i want to import this into a new zenpack, so I simply copied the objects.xml into a new zenpack, created the proper event classes, etc.
[12-Dec-2011 10:53:48] <jb> but, no transforms appear.
[12-Dec-2011 10:53:49] <jb> any idea?
[12-Dec-2011 10:53:56] <Hackman238> jb: you might want to be sure that 'keep-history false' is in your zope.conf under <relstorage>
[12-Dec-2011 10:54:43] <Hackman238> jb: objects.xml is only laoded on pack install. You'll need to export the new pack, then install it over the existing one you just created.
[12-Dec-2011 10:54:47] <Hackman238> *loaded
[12-Dec-2011 10:55:18] <jb> ooH.
[12-Dec-2011 10:55:19] <jb> ok
[12-Dec-2011 10:55:22] <rmatte> yeh, Zenoss doesn't go through and load every objects.xml on startup lol
[12-Dec-2011 10:56:30] <Hackman238> jb: What rmatte said. Zenoss slow enough without reloading all zenpack objects on start
[12-Dec-2011 10:56:54] <jb> true
[12-Dec-2011 10:58:05] <jb> odd, still nothing
[12-Dec-2011 10:58:17] <jb> 2011-12-12 09:57:05,120 INFO zen.ZPLoader: Loading /opt/zenoss/ZenPacks/ZenPacks.community.DellOMSA-1.0.0-py2.7.egg/ZenPacks/community/DellOMSA/objects/objects.xml
[12-Dec-2011 10:58:49] <jb> heh, it deleted them all. let's try this again.
[12-Dec-2011 10:58:54] <Hackman238> jb:
[12-Dec-2011 10:59:08] <rmatte> Hackman238: the Firefox release happening in 8 days is the release that will improve javascript performance by 15 to 30 percent.
[12-Dec-2011 10:59:22] <rmatte> Will be interesting to see how true that is
[12-Dec-2011 11:00:10] <Hackman238> rmatte: Oh nice!
[12-Dec-2011 11:03:21] <jb> hrm, now it's not in dev mode so I can't export.
[12-Dec-2011 11:04:59] <Hackman238> jb: Ah bollocks
[12-Dec-2011 11:05:12] <Hackman238> jb: That generally doesn't happen
[12-Dec-2011 11:06:36] <Hackman238> jb: What I'd do is cp the zenpack to somewhere else, uninstall it, restart zenoss, readd it as dev mode, copy in your new parts, cd in to the 'ZenPacks'/'EGG-INFO' directory and zip -r ../your packname.egg * then install that. That'll be a dev mode egg
[12-Dec-2011 11:07:04] <jb> yeah thats what I'm oding now.
[12-Dec-2011 11:07:30] <jb> well, i just copied the ZenPackTemplate files back into the tree.
[12-Dec-2011 11:07:31] <Hackman238> jb: Sorry about that. Face palm on me
[12-Dec-2011 11:07:43] <Hackman238> jb: Did that work? I haven't tried that in v4
[12-Dec-2011 11:08:51] <jb> argh
[12-Dec-2011 11:08:57] <jb> everytime I export it, it kills my objects.xml
[12-Dec-2011 11:09:09] <jb> pre-export: -rw-rw-r-- 1 zenoss zenoss 1153839 Dec 12 10:08 objects.xml
[12-Dec-2011 11:09:14] <jb> post-export: -rw-rw-r-- 1 zenoss zenoss 43 Dec 12 10:08 objects.xml
[12-Dec-2011 11:09:16] <Hackman238> jb: yeah don't use the export until the objects are loaded.
[12-Dec-2011 11:09:29] <Hackman238> jb: You'll need to go zip it up manually I'm afraid
[12-Dec-2011 11:09:32] <jb> k
[12-Dec-2011 11:10:28] <Hackman238> jb: do the zip so that 'EGG-INFO' and 'ZenPacks' are in the root of the zip
[12-Dec-2011 11:11:04] <jb> argh, can't even remove the zenpack
[12-Dec-2011 11:11:19] <jb> i'll just try to install over it, I guess.
[12-Dec-2011 11:11:21] <Hackman238> e.g. cd $Zenhome/ZenPacks/ZenPacks.Your.Pack/
[12-Dec-2011 11:12:15] <opapo> the tutorial on Windows SNMP monitoring: does not seem to be for the 3.2 interface
[12-Dec-2011 11:12:35] <opapo> I need help "transforming" the memory event
[12-Dec-2011 11:12:38] <Hackman238> opapo: Its for the v2.5.2 one
[12-Dec-2011 11:12:57] <opapo> How do I get to "Transform"
[12-Dec-2011 11:13:20] <opapo> the tutorial says: After installing the ZenPack:
[12-Dec-2011 11:13:20] <opapo>
[12-Dec-2011 11:13:20] <opapo> Navigate to /Events/Perf/Memory and select More -> Transform from the menu
[12-Dec-2011 11:13:22] <Hackman238> opapo: You'll need to go to 'Events' -> 'Event Classes' -> '/Events/Perf/Memory' -> pick the gear icon in the lower left -> Transform
[12-Dec-2011 11:13:34] <fixxxermet> Is it easy to make multiple reports which show all graphs for each resource?
[12-Dec-2011 11:13:45] <fixxxermet> Similar to how Munin has a page with all graphs for each device
[12-Dec-2011 11:14:31] <Hackman238> fixxxermet: Sure. Add a new graph report. In that report add all the components listed fort he device typed in the filter and click add.
[12-Dec-2011 11:14:39] <jb> Hackman238: that worked, thanks!
[12-Dec-2011 11:14:48] <jb> 2011-12-12 10:14:33,563 INFO zen.AddToPack: Loaded 158 objects into the ZODB database
[12-Dec-2011 11:14:51] <fixxxermet> Hackman238: So I'd need to do that one-by-one for each device ?
[12-Dec-2011 11:14:58] <Hackman238> jb: NP
[12-Dec-2011 11:15:34] <Hackman238> fixxxermet: For that method, yes. If you're devices are cookie cutter then you could make a multigraph report and just add the devices
[12-Dec-2011 11:15:52] <opapo> Hackman238: i found the transform. Thanks
[12-Dec-2011 11:16:02] <fixxxermet> Sorry, what do you mean by cookie cutter?
[12-Dec-2011 11:16:03] <Hackman238> fixxxermet: A final way would be to write a plugin to add a new page like the interfacegraphs page
[12-Dec-2011 11:16:07] <Hackman238> opapo: NP
[12-Dec-2011 11:16:14] <fixxxermet> Hackman238: that sounds like the best way to do it
[12-Dec-2011 11:16:18] <Hackman238> fixxxermet: All the same
[12-Dec-2011 11:16:20] <fixxxermet> Got a link to relevant docs?
[12-Dec-2011 11:16:34] <fixxxermet> Hi,
[12-Dec-2011 11:16:34] <fixxxermet> I have a question about your "How To Gather and Chart Temperatures in your House" page. I have ordered samples of the DS18S20, however I am not sure how they will then interface with the computer... Computer -> DS9490R -> ??? -> DS18S20? What am I missing?
[12-Dec-2011 11:16:35] <Hackman238> fixxxermet: for which method?
[12-Dec-2011 11:16:38] <fixxxermet> I assume that the ??? is some type of hub for connecting multiple 1-wire devices, which is then interfaced to the computer over USB with the DS9490R. Eh?
[12-Dec-2011 11:16:42] <fixxxermet> Thanks for the help, and for taking the time to write up that page.
[12-Dec-2011 11:16:44] <fixxxermet> Kyle
[12-Dec-2011 11:16:47] <fixxxermet> shit!
[12-Dec-2011 11:16:47] <fixxxermet> Sorry, ctrl+c didn't work
[12-Dec-2011 11:16:56] <fixxxermet> Hackman238: plugin similar to interfacegrphs
[12-Dec-2011 11:18:36] <Hackman238> fixxxermet: I'm afraid there aren't any specific docs. Heres the page for that pack You should be able to extend it to basically any/all component class(es) on a device
[12-Dec-2011 11:19:53] <opapo> I have a Windows server I am monitoring, but when I monitor "Memory" after installing the snmpwindows zenpack I get the following error
[12-Dec-2011 11:20:08] <opapo> Type:
[12-Dec-2011 11:20:09] <opapo> Value: User-supplied Python expression (here.getRRDValue('MemoryTotal') * 0.9) for maximum value caused error: ['Memory_MemoryUsed']
[12-Dec-2011 11:20:23] <opapo> How do I fix this?
[12-Dec-2011 11:21:28] <rmatte> opapo: that's normal, you have to wait 3 polling cycles for the data to gather before it'll display the graph
[12-Dec-2011 11:21:41] <rmatte> 3 polling cycles at 5 minutes per polling cycle == 15 minutes
[12-Dec-2011 11:21:43] <opapo> It has been a day
[12-Dec-2011 11:21:54] <rmatte> What version of windows?
[12-Dec-2011 11:22:07] <opapo> Windows Server 2003
[12-Dec-2011 11:22:24] <rmatte> did you read the requirements section on the ZenPack page about requiring both the snmpwalk and bc commandline utilities for the pack to work?
[12-Dec-2011 11:22:40] <opapo> I installed bc and snmpwalk
[12-Dec-2011 11:22:40] <rmatte> If you're missing either of those commands it's not going to work
[12-Dec-2011 11:23:04] <rmatte> ok, go in to the template and run a test of the Memory datasource against that device
[12-Dec-2011 11:23:07] <rmatte> see what you get back
[12-Dec-2011 11:23:47] <fixxxermet> Hackman238: thanks for the help
[12-Dec-2011 11:24:21] <opapo> rmatte: How?
[12-Dec-2011 11:24:47] <rmatte> opapo: I don't have a 3.x install in front of me for reference, all my stuff is 2.5... Hackman238, do me a favour and walk him through that?
[12-Dec-2011 11:25:03] <opapo> I am in the interface for the server and see the SNMPDevice Template
[12-Dec-2011 11:25:17] <rmatte> ok, so double click on the datasource for memory
[12-Dec-2011 11:25:29] <rmatte> you should get a dialog come up
[12-Dec-2011 11:25:31] <opapo> ok
[12-Dec-2011 11:25:40] <rmatte> and there should be a place to enter a device name with a Test button next to it
[12-Dec-2011 11:25:47] <rmatte> so put the device name in and click test, see what it does
[12-Dec-2011 11:27:09] <opapo> It gives me the memory totals
[12-Dec-2011 11:27:44] <rmatte> What version of Zenoss are you running?
[12-Dec-2011 11:27:54] <opapo> I just input the "transform" code into the event so maybe it takes awhile to work
[12-Dec-2011 11:27:59] <opapo> I am running 3.2
[12-Dec-2011 11:28:06] <rmatte> the transform code wouldn't prevent the graph from showing
[12-Dec-2011 11:28:14] <rmatte> 3.2, not 3.2.1?
[12-Dec-2011 11:28:33] <rmatte> 3.2 had a major bug with zencommand, so that would explain it
[12-Dec-2011 11:28:36] <Hackman238> fixxxermet: NP
[12-Dec-2011 11:28:37] <opapo> sorry 3.2.1
[12-Dec-2011 11:29:04] <rmatte> can you try doing this as the zenoss user: zencommand run -v10 -d devicename
[12-Dec-2011 11:29:10] <rmatte> where devicename is the name of that device?
[12-Dec-2011 11:29:18] <rmatte> see if there are any errors
[12-Dec-2011 11:33:46] <opapo> rmatte: there are no errors. Just Debug and Info lines
[12-Dec-2011 11:39:59] <opapo> rmatte: Is there more information you need from me?
[12-Dec-2011 11:55:14] <rmatte> opapo: sorry, was pulled away from my desk for a bit
[12-Dec-2011 11:56:18] <rmatte> If you're not seeing errors and the datasource test is returning proper data then I don't know what to tell you... what I would suggest is that you make a local copy of the template on that device, delete the threshold, and see what the graph is showing
[12-Dec-2011 11:56:37] <rmatte> If it's showing that RRD files haven't been created, or whatever
[12-Dec-2011 12:00:02] [disconnected at Mon Dec 12 12:00:02 2011]
[12-Dec-2011 12:00:02] [connected at Mon Dec 12 12:00:02 2011]
[12-Dec-2011 12:00:15] [zenoss-logger (logger bot) has joined #zenoss]
[12-Dec-2011 12:00:56] <opapo> When I look at the datasources the "Source" column for CPU and Memory is like "${here/ZenPack...." instead of 1.3.6.1....
[12-Dec-2011 12:01:34] <rmatte> it's supposed to be, they are command datasources
[12-Dec-2011 12:01:57] <opapo> ok
[12-Dec-2011 12:05:12] <opapo> I can see graphs now
[12-Dec-2011 12:05:42] <opapo> so now what?
[12-Dec-2011 12:06:04] <opapo> I want thresholds
[12-Dec-2011 12:06:21] <rmatte> what is the memory graph showing?
[12-Dec-2011 12:06:45] <opapo> not enough time for graph to show anything
[12-Dec-2011 12:06:54] <opapo> but I see graphs
[12-Dec-2011 12:06:55] <rmatte> you said it had been all day?
[12-Dec-2011 12:07:02] <rmatte> so you should have some data
[12-Dec-2011 12:07:24] <opapo> I installed snmpwindows like thursday
[12-Dec-2011 12:07:52] <opapo> I also deleted the graphs and put them back in (for the server)
[12-Dec-2011 12:08:06] <rmatte> what do you mean by deleted then put back in?
[12-Dec-2011 12:08:24] <rmatte> like you literally edited the template?
[12-Dec-2011 12:09:08] <opapo> There is a place where I can see multiple graphs in one report. I deleted it from there and then added them again
[12-Dec-2011 12:09:24] <opapo> It may not have any bearing on what we are doing
[12-Dec-2011 12:09:36] <rmatte> if you're talking about a custom graph report, no it doesn't
[12-Dec-2011 12:09:44] <rmatte> here's how it works so that you understand...
[12-Dec-2011 12:10:07] <opapo> on phone
[12-Dec-2011 12:10:14] <rmatte> zencommand issues the command, parses the data from the output, then saves the data to a .rrd file.
[12-Dec-2011 12:10:21] <rmatte> If the .rrd file doesn't exist it creates it.
[12-Dec-2011 12:10:39] <rmatte> once that .rrd is created it stays there and doesn't get removed unless it hasn't been used for a long time or the device is deleted
[12-Dec-2011 12:11:20] <rmatte> The fact that you were receiving the message about it not being able to calculate the threshold based on RRD values tells me that the RRD was probably not created
[12-Dec-2011 12:11:38] <rmatte> or that you just haven't been collecting data long enough for it to be able to do the calculation
[12-Dec-2011 12:11:55] <rmatte> but 15 minutes worth of data is enough and it's been more than that at this point I believe
[12-Dec-2011 12:12:43] <rmatte> can you describe what the graph looks like?
[12-Dec-2011 12:12:51] <rmatte> is there a message about missing RRD files?
[12-Dec-2011 12:13:00] <rmatte> is there 'nan' values?
[12-Dec-2011 12:13:11] <rmatte> do you see any actual values?
[12-Dec-2011 12:14:14] <opapo> no actual values
[12-Dec-2011 12:15:34] <opapo> no errors
[12-Dec-2011 12:40:09] <f00fSteR> zenoss have a mengodb zenpack ?
[12-Dec-2011 12:40:48] <Hackman238> f00fSteR: I don't tihnk so
[12-Dec-2011 12:40:56] <Hackman238> f00fSteR: How goes it?
[12-Dec-2011 12:42:05] <otakup0pe> rmatte: wait you aren't with zenoss anymore ? where did you end up
[12-Dec-2011 12:42:30] <f00fSteR> Hackman238, It goes good. I be's hacking up mongo today to use against our ms sql servers
[12-Dec-2011 12:42:35] <f00fSteR> was looking for monitoring measures
[12-Dec-2011 12:51:37] <opapo> What do I have to do on my Windows server to make sure stats are properly collected.
[12-Dec-2011 12:52:09] <opapo> I can run zencommand run-v10 -d <device name> and there are no errors
[12-Dec-2011 12:52:15] <opapo> but I get no data
[12-Dec-2011 13:07:23] <rmatte> otakup0pe: I was never with Zenoss lol
[12-Dec-2011 13:07:35] <rmatte> otakup0pe: been working for Nova Networks for over 3 years now
[12-Dec-2011 13:08:41] <rmatte> opapo: can you go in to zendmd as the Zenoss user, do reindex() then commit(), then restart zenoss... after you've done that try to run zencommand again and see what you get
[12-Dec-2011 13:08:50] <rmatte> it sounds like zencommand isn't even seeing the datasource for some reason
[12-Dec-2011 13:08:59] <rmatte> you did restard Zenoss after installing the ZenPack I hope?
[12-Dec-2011 13:09:04] <rmatte> restart*
[12-Dec-2011 13:30:52] <tvincent-office> i need to add the monitoring of a process across a device tree? Anyone have any sample dmd code to add that?
[12-Dec-2011 13:32:35] <opapo> rmatte: I may not have restarted the zenoss. I'll restart it to make sure
[12-Dec-2011 13:34:19] <opapo> there are multiple daemons. Which one do I reset?
[12-Dec-2011 13:37:44] <rmatte> just restart all of them to be sure
[12-Dec-2011 13:37:55] <rmatte> generally you would just do zopectl restart, but sometimes that doesn't do the trick
[12-Dec-2011 13:38:04] <rmatte> as the zenoss user at the commandline do:
[12-Dec-2011 13:38:05] <rmatte> zenoss stop
[12-Dec-2011 13:38:16] <rmatte> then zenoss status to make sure they all stopped
[12-Dec-2011 13:38:19] <rmatte> then zenoss start
[12-Dec-2011 13:53:02] <otakup0pe> rmatte: my bad i might be confusing you with someone else :X
[12-Dec-2011 13:53:49] <opapo> rmatte: I restarted zenoss and the graphs still show nan for data
[12-Dec-2011 13:55:36] <opapo> Under the reports tab there is a "performance reports" section on the left.
[12-Dec-2011 13:56:02] <opapo> I click on Memory utilization and see my devices listed
[12-Dec-2011 13:56:36] <rmatte> otakup0pe: you're probably confusing me with Matt Ray.
[12-Dec-2011 13:56:58] <otakup0pe> that sounds probably !
[12-Dec-2011 13:57:11] <rmatte> opapo: did you try running zencommand by hand again to see what you get?
[12-Dec-2011 13:57:11] <opapo> The Windows server has a correct value for the "total", but "N/A" for "Available", "cache memory", etc
[12-Dec-2011 13:57:18] <rmatte> you should see the actual output from the command scripts
[12-Dec-2011 13:57:41] <rmatte> opapo: you're talking about the hardware section?
[12-Dec-2011 13:58:00] <rmatte> The pack only creates a graph/threshold, it doesn't populate the values under hardware, that's done by modeler plugins
[12-Dec-2011 14:21:50] <opapo> I have a little blip of Memory usage now
[12-Dec-2011 14:21:57] <opapo> Yeah!!!
[12-Dec-2011 14:22:10] <rmatte> good
[12-Dec-2011 14:22:21] <rmatte> now you can remove the local template and the threshold should be working
[12-Dec-2011 14:23:31] <opapo> I am not getting data for the cpu though
[12-Dec-2011 14:23:49] <opapo> do I need to transform that too?
[12-Dec-2011 14:23:54] <rmatte> I don't see why you wouldn't be
[12-Dec-2011 14:24:13] <rmatte> the two scripts used to gather that info are quite similar
[12-Dec-2011 14:24:48] <rmatte> what do you mean by "data for the cpu"?
[12-Dec-2011 14:24:57] <rmatte> the graph under the graphs section?
[12-Dec-2011 14:25:06] <rmatte> or the details under the hardware section?
[12-Dec-2011 14:26:06] <rmatte> Are you using the simple or advanced version of the pack?
[12-Dec-2011 14:26:57] <opapo> I am using the simple version. I would like an overall usage metric
[12-Dec-2011 14:27:05] <rmatte> yeh ok, that'll do it
[12-Dec-2011 14:27:08] <rmatte> hmmm
[12-Dec-2011 14:27:17] <rmatte> test the datasource like you did for the memory one
[12-Dec-2011 14:27:20] <rmatte> see if it returns a value
[12-Dec-2011 14:27:21] <opapo> When I test it it reports: OK|CPU1=0 CPU2=0 Total=0
[12-Dec-2011 14:27:34] <rmatte> ok, so it's working
[12-Dec-2011 14:27:47] <rmatte> you should be seeing 0 values on the graph after a bit
[12-Dec-2011 14:28:09] <rmatte> well not seeing, but under cur, avg, and max
[12-Dec-2011 14:28:36] <opapo> I see nan for cur:, avg", ...
[12-Dec-2011 14:30:06] <rmatte> if you do: zencommand run -v10 -d devicename again...
[12-Dec-2011 14:30:23] <rmatte> does one of the lines show something like: OK|CPU1=0 CPU2=0 Total=0?
[12-Dec-2011 14:32:28] <opapo> This is the results:
[12-Dec-2011 14:33:20] <rmatte> hmmm, it's not actually running anything
[12-Dec-2011 14:33:40] <rmatte> you did restart zenoss yes?
[12-Dec-2011 14:35:59] <opapo> I restarted zenoss and then I got some memory data (data in the rrd graphs for the memory)
[12-Dec-2011 14:36:07] <rmatte> did you reindex?
[12-Dec-2011 14:36:34] <rmatte> as the zenoss user type zendmd, then once zendmd loads type reindex() hit enter, when that finished type commit(), hit enter, then ctrl-d to exit
[12-Dec-2011 14:36:47] <rmatte> then restart Zenoss again and try running zencommand again
[12-Dec-2011 14:38:30] <opapo> can I do that as root?
[12-Dec-2011 14:45:56] <Hackman238> opapo: Please run all zenoss command as zenoss user
[12-Dec-2011 14:45:59] <opapo> I still get similar data
[12-Dec-2011 14:46:12] <opapo> hold on then
[12-Dec-2011 14:47:09] <opapo> all requested processes have been run as zenoss
[12-Dec-2011 14:47:15] <opapo> same result
[12-Dec-2011 14:50:52] <opapo> hold on restarting zenoss as zenoss
[12-Dec-2011 14:56:47] <opapo> I reindexed using zenoss, I restarted as zenoss, and I ran the command as zenoss
[12-Dec-2011 14:56:58] <opapo> I get the same results:
[12-Dec-2011 14:59:50] <rmatte> no you can not do that as root
[12-Dec-2011 15:00:43] <rmatte> well I'm out of ideas at this point. I'd need physical access to the box to dig and figure it out
[12-Dec-2011 15:00:55] <rmatte> you haven't been playing around with the template have you?
[12-Dec-2011 15:01:04] <opapo> no
[12-Dec-2011 15:01:05] <rmatte> the template is exactly as it was when it was first installed I hope?
[12-Dec-2011 15:01:07] <rmatte> k
[12-Dec-2011 15:01:08] <opapo> It is basic
[12-Dec-2011 15:01:34] <rmatte> are you still getting memory data for the device?
[12-Dec-2011 15:02:45] <opapo> I am no longer getting memory data
[12-Dec-2011 15:07:41] <opapo> I modified a local version of the snmpDevice template and took out the thresholds. I will refresh until I get data again
[12-Dec-2011 15:12:48] <rmatte> the threshold being there isn't what's preventing you from getting the data... it simply prevents you from seeing the graph when there is no data
[12-Dec-2011 15:12:56] <rmatte> there's something else causing it not to collect the data
[12-Dec-2011 15:18:21] <opapo> I have memory data for about 1.5 hours and then it stopped
[12-Dec-2011 15:35:22] <Hackman238>
[12-Dec-2011 15:36:38] <GameMagister_> hackman238: that is either really tacky or the best thing i have seen in days...
[12-Dec-2011 15:37:33] <Hackman238> GameMagister_: One of my guys over in our ORD datacenter posted it in response to my explaination of why zenoss qualifies everything but a perfect echo as down.
[12-Dec-2011 15:37:40] <rmatte> haha
[12-Dec-2011 15:39:01] <rmatte> I love this one:
[12-Dec-2011 15:39:02] <rmatte> lol
[12-Dec-2011 15:39:09] <GameMagister_> hence my or the best thin i have seen in days
[12-Dec-2011 15:45:21] <rmatte> Hackman238: here's one for you:
[12-Dec-2011 16:05:14] <Hackman238> Aw...service unavailable
[12-Dec-2011 16:09:44] <Hackman238> rmatte: Dead on
[12-Dec-2011 16:15:30] <mattray> grrr… zenbatchload is starting to really disappoint me
[12-Dec-2011 16:16:22] <Hackman238> mattray: Starting?
[12-Dec-2011 16:16:36] <mattray> it doesn't appear to have any authority
[12-Dec-2011 16:16:42] <Hackman238> mattray: Most of the arguments that can be passed don't seem to work.
[12-Dec-2011 16:16:48] <mattray> it won't move devices between device classes
[12-Dec-2011 16:16:55] <Hackman238> mattray: Nope
[12-Dec-2011 16:17:30] <Hackman238> mattray: Best solution I've found is to open an xmlrpc connection and do it by hand.
[12-Dec-2011 16:17:47] <mattray> zendmd works
[12-Dec-2011 16:17:59] <mattray> I was trying to use zenbatchload for stuff instead of zendmd
[12-Dec-2011 16:19:04] <Hackman238> mattray: Right. For chef right?
[12-Dec-2011 16:19:10] <mattray> yes
[12-Dec-2011 16:19:31] <mattray> it's fine on the first run, but any changes afterwards are partially kept
[12-Dec-2011 16:19:45] <Hackman238> mattray: What I ended up doing is writting a little python script that chef can call and pass arguments to. The python script executes and opens an xmlrpc connection and performs the operation.
[12-Dec-2011 16:19:58] <mattray> devices seem to get zProperties, but not Device Classes
[12-Dec-2011 16:20:24] <mattray> Hackman238: I made zendmd Resources
[12-Dec-2011 16:20:33] <mattray> for device class, location, system and group
[12-Dec-2011 16:20:45] <mattray> I just wanted to use zenbatch for everything
[12-Dec-2011 16:20:48] * mattray sighs
[12-Dec-2011 16:20:49] <Hackman238> mattray: Yeah I don't think setting the device class works since you ahve to call a method. Seems like methods that set attributes and to perform deviceAdd and delete work.
[12-Dec-2011 16:21:03] <Hackman238> mattray: Sorry man.
[12-Dec-2011 16:22:16] <mattray> when is 4.x rumored for open source?
[12-Dec-2011 16:22:20] <mattray> I'm tempted to leave this as is
[12-Dec-2011 16:22:30] <mattray> because I'm sure 4.x will break it again
[12-Dec-2011 16:22:59] <Hackman238> mattray: Mid Jan I believe
[12-Dec-2011 16:23:07] <mattray> ship it!
[12-Dec-2011 16:23:08] <Hackman238> mattray: You'd be correct
[12-Dec-2011 16:23:30] <rmatte> Is it just me or is it getting quite tedious having everything break every time there's an update?
[12-Dec-2011 16:23:41] <mattray> no, nobody likes that
[12-Dec-2011 16:24:00] <Hackman238> rmatte: ...it's the zenoss way
[12-Dec-2011 16:24:28] <Hackman238> The product is jsut updated very often. How often does nagios get any major updates?
[12-Dec-2011 16:24:56] <mattray> yeah, but the Nagios forks are healthier. Icinga
[12-Dec-2011 16:25:10] <mattray> I'm gonna try to take a long look at Sensu ()
[12-Dec-2011 16:25:25] <mattray>
[12-Dec-2011 16:25:37] <rmatte> Hackman238: what is it going to take to get that IPSLA pack out? People keep asking about it. The 3.1 version I sent to you was quite good, there are some further enhancements that I've made since then... If you have any fixes to implement, make the changes to the 3.1, then send the pack to me, I'll finalize my changes, and then she should be ready for release. Thoughts?
[12-Dec-2011 16:26:55] <Hackman238> rmatte: Should be really soon. I've just had too much on the plate. I'm more than half done eating, so should be soon for the second helping.
[12-Dec-2011 16:27:02] <Hackman238> Also...this:
[12-Dec-2011 16:27:04] <rmatte> cool
[12-Dec-2011 16:27:24] <rmatte> I've been doing tons of work with IPSLA lately which is why I actually had time to work on it
[12-Dec-2011 16:27:32] <Hackman238> rmatte: Gotcha.
[12-Dec-2011 16:27:43] <Hackman238> rmatte: That would be great
[12-Dec-2011 16:27:45] <rmatte> haha, good one (the meme)
[12-Dec-2011 16:28:15] <Hackman238>
[12-Dec-2011 16:29:41] <rmatte>
[12-Dec-2011 16:29:57] <rmatte> >:)
[12-Dec-2011 16:30:00] <GameMagister_> now that was a good one rmatte
[12-Dec-2011 16:30:32] <rmatte> Thank you
[12-Dec-2011 16:30:34] <Hackman238> rmatte: LOL!
[12-Dec-2011 16:45:44] <mattray> note to self:
[12-Dec-2011 16:54:44] <Hackman238> mattray:
[12-Dec-2011 17:04:07] kocolosk is now known as kocolosk|away
[12-Dec-2011 17:08:17] <opapo> I solved my problem
[12-Dec-2011 17:11:27] <opapo> There are two graphs that are labeled CPU
[12-Dec-2011 17:11:51] <opapo> There is a way I can create my own report
[12-Dec-2011 17:12:14] <rmatte> there should not be 2 graphs, if there were then you had some other template bound that shouldn't have been
[12-Dec-2011 17:12:28] <opapo> I was grabbing the CPU graph from the Device template and not the SNMP template
[12-Dec-2011 17:12:29] <rmatte> you probably had the snmp-informant template bound that comes with Zenoss by default
[12-Dec-2011 17:12:51] <rmatte> you should unbind that template since it won't work
[12-Dec-2011 17:12:53] <opapo> I do not have snmp-informant (that I know of) on that box
[12-Dec-2011 17:13:04] <rmatte> right, which is the whole point of my ZenPack hehe
[12-Dec-2011 17:13:07] <opapo> I will unbind the Device template
[12-Dec-2011 17:13:17] <rmatte> just saying that Zenoss has a template bound by default that makes use of snmp-informant
[12-Dec-2011 17:13:32] <opapo> oh
[12-Dec-2011 17:13:35] <rmatte> I wouldn't personally touch snmp-informant with a 10 foot pole, native apps are always better
[12-Dec-2011 17:13:55] <rmatte> which is why I developed the ZenPack
[12-Dec-2011 17:13:58] <rmatte>
[12-Dec-2011 17:14:00] <opapo> rmatte: I appreciate all your help
[12-Dec-2011 17:14:11] <rmatte> no problem
[12-Dec-2011 17:14:26] <opapo> This is working and I am grateful for your work on this ZenPack | http://community.zenoss.org/docs/DOC-12960 | CC-MAIN-2015-18 | refinedweb | 21,182 | 74.53 |
Welcome to the official Java SDK documentation. The first section, Getting Started, covers the basic functionality, laying the foundation for the later sections. If you want to see how to build a full-blown application on top of Couchbase, look for the Tutorial section next.
The Using the APIs section holds self-contained reference material about API usage. Go there if you want to dig into topics like storing data, using views and so on. Finally, Advanced Usage contains in-depth information about topics that come up during debugging and production.
This section shows you the basics of Couchbase Server and how to interact with it through the Java Client SDK. Here’s a quick outline of what you’ll do in this section:
Create a project in your favorite IDE and set up the dependencies.
Write a simple program that demonstrates how to connect to Couchbase Server and save some documents.
Write a program that demonstrates how to use create, read, update, and delete (CRUD) operations on documents in combination with JSON serialization and deserialization.
Explore some of the API methods that provide more specialized functions.
At this point we assume that you have a Couchbase Server 2.2 release running and you have the beer-sample bucket configured. If you need help setting up everything, see the following documents:
Using the Couchbase Web Console for information about using the Couchbase Administrative Console
Couchbase CLI for information about the command line interface
Couchbase REST API for information about creating and managing Couchbase resources
The TCP/IP port allocation on Microsoft Windows by default includes a restricted number of ports available for client communication. For more information about this issue, including information about how to adjust the configuration and increase the number of available ports, see MSDN: Avoiding TCP/IP Port Exhaustion.
To get ready to build your first app, you need to install Couchbase Server, download the Couchbase Java SDK, and set up your IDE.
Installing Couchbase Server
Get the latest Couchbase Server 2.2 release and install it.
As you follow the download instructions and setup wizard, make sure you install the beer-sample default bucket. It contains beer and brewery sample data, which you use with the examples.
If you already have Couchbase Server 2.2 but do not have the beer-sample bucket installed, open the Couchbase Web Console and select Settings > Sample Buckets. Select the beer-sample checkbox, and then click Create. A notification box in the upper-right corner disappears when the bucket is ready to use.
Downloading the Couchbase Client Libraries
To include the Client SDK in your project, you can either
manually include all dependencies in your
CLASSPATH, or if you want it to be
easier, you can use a dependency manager such as Maven. Since the Java SDK 1.2.0 release,
all Couchbase-related dependencies are published in the Maven Central Repository.
To include the libraries directly in your project,
download the archive and add
all the JAR files to your
CLASSPATH of the system/project. Most IDEs also allow
you to add specific JAR files to your project. Make sure you add the following
dependencies in your
CLASSPATH :
couchbase-client-1.2.1.jar, or latest version available
spymemcached-2.10.1.jar
commons-codec-1.5.jar
httpcore-4.1.1.jar
netty-3.5.5.Final.jar
httpcore-nio-4.1.1.jar
jettison-1.1.jar
If you use a dependency manager, the syntax varies for each tool. The following examples show how to set up the dependencies when using Maven, sbt (for Scala programs), and Gradle.
To use Maven to include the SDK, add the following dependency to your pom.xml file:
<dependency> <groupId>com.couchbase.client</groupId> <artifactId>couchbase-client</artifactId> <version>1.2.1</version> </dependency>
If you program in Scala and want to manage your dependencies through sbt, then you can do it with these additions to your build.sbt file:
libraryDependencies += "couchbase" % "couchbase-client" % "1.2.1"
For Gradle you can use the following snippet:
repositories { mavenCentral() } dependencies { compile "com.couchbase.client:couchbase-client:1.2.1" }
Now that you have all needed dependencies in the
CLASSPATH environment variable, you can set up your IDE.
Setting up your IDE
The NetBeans IDE is used in this example, but you can use any other Java-compatible IDE. After you install the NetBeans IDE and open it:
Select File > New Project > Maven > Java Application, and then click Next.
Enter a name for your new project and change the location to the directory you want.
We named the project “examples.”
Enter a namespace for the project in the Group Id field.
We used the
com.couchbase namespace for this example, but you can use your own if you like. If you do so, just make sure you change the namespace later in the source files when you copy them from our examples.
Now that your project, you can add the Couchbase Maven repository to use the Java SDK.
Click Finish.
In the Projects window, right-click Dependencies > Add Dependency.
Enter the following settings to add the Couchbase Java SDK from the Maven repository:
Group ID: com.couchbase.client
Artifact ID: couchbase-client
Version: 1.2.1
For now, you need to add only the Couchbase Java SDK itself because the transitive dependencies are fetched automatically.
Click Add.
Now all the dependencies are in place and you can move forward to your first application with Couchbase.
To follow the tradition of first programming tutorials, we start with a “Hello Couchbase” example. In this example, we connect to the a Couchbase node, set a simple document, retrieve the document, and then print the value out. This first example contains the full source code, but in later examples we omit the import statements and also assume an existing connection!" client.set("hello", "couchbase!").get(); // Return the result and cast it to string String result = (String) client.get("hello"); System.out.println(result); // Shutdown the client client.shutdown(); } }
The code in Listing 1 is very straightforward, but there is a lot going on that is worth a little more discussion:
Connect. The
CouchbaseClient class accepts a list of URIs that point to nodes in the cluster. If your cluster has more than one node, Couchbase strongly recommends that you add at least two or three URIs to the list. The list does not have to contain all nodes in the cluster, but you do need to provide a few nodes so that during the initial connection phase your client can connect to the cluster even if one or more nodes fail.
After the initial connection, the client automatically fetches cluster configuration
and keeps it up-to-date, even when the cluster topology changes. This means that you do not need to change your application configuration at all when you add
nodes to your cluster or when nodes fail. Also make sure you use a URI in this
format:
http://[YOUR-NODE]:8091/pools. If you provide only the IP address, your client will fail to connect. We call this initial URI the bootstrap URI.
The next two arguments are for the
bucket and the
password. The bucket is
the container for all your documents. Inside a bucket, a key — the identifier for a document — must be unique. In production environments, Couchbase recommends that you use a password on the bucket (this can be configured during bucket creation), but when you are just starting out using the
default bucket without a password is fine. The beer-sample bucket also doesn’t have a password, so just change the bucket name and you’re set.
Set and get. These two operations are the most important ones you will use
from a Couchbase SDK. You use
set to create or overwrite a document and you
use
get to read it from the server. There are lots of arguments and variations
for these two methods, but if you use them as shown in the previous example it
will get you pretty fair in your application development.
Note that the
get operation will read all types of information, including
binary, from the server, so you need to cast it into the data format you want.
In our case we knew we stored a string, so it makes sense to convert it back to
a string when we get it later.
Disconnect when you shutdown your server instance, such as at the end of
your application, you should use the
shutdown method to prevent loss of data.
If you use this method without arguments, it waits until all outstanding
operations finish, but does not accept any new operations. You can also call
this method with a maximum waiting time that makes sense if you do not want
your application to wait indefinitely for a response from the server.
The logger for the Java SDK logs from
INFO upwards by default. This means the Java SDK logs a good amount of
information about server communications. From our Hello Couchbase example the
log looks
From the log, you can determine which nodes the client is connected to, see whether views on the server are in development or production mode, and view other helpful output. These logs provide vital information when you need to debug any issues on Couchbase community forums or through Couchbase Customer Support.
With Couchbase Server 2.0, you have two ways of fetching your documents: either
by the unique key through the
get method, or through Views. Because Views are
more complex we will discuss them later in this guide. In the meantime, we show
get first:
Object get = client.get("mykey");
Because Couchbase Server stores all types of data, including binary,
get returns an object of type
Object. If you store JSON documents, the actual document is a
string, so you can safely convert it to a string:
String json = (String) client.get("mykey");
If the server finds no document for that key, it returns a
null. It is
important that you check for
null in your code, to prevent
NullPointerExceptions later down the stack.
With Couchbase Server 2.0 and later, you can also query for documents with secondary indexes, which we collectively call Views. This feature enables you to provide map functions to extract information and you can optionally provide reduce functions to perform calculations on information. This guide gets you started on how to use views through the Java SDK. If you want to learn more, including how to set up views with Couchbase Web Console, see Using the Views Editor in the Couchbase Server Manual.
This next example assumes you already have a view function set up with
Couchbase Web Console. After you create your View in the Couchbase Web Console, you can
query it from the Java SDK in three steps. First, you get the view definition
from the Couchbase name
of the view to load the proper definition from the cluster. The SDK needs them
to determine whether there is a view with the given map functions and also whether it
contains a reduce function or is even a spatial view.
You can query views with several different options. All options are available as
setter methods on the
Query object. Here are some of them:
setIncludeDocs(boolean) : and the
query objects in place, we can
issue the
query command, which actually triggers indexing on a Couchbase
cluster. The server returns the results to the Java SDK in the
ViewResponse
object. We can use it to iterate over the results and print out some details.
Here is a more complete example, which also includes the full documents and fetches only in ascending order:
21st_amendment_brewery_cafe 21st_amendment_brewery_cafe-21a_ipa 21st_amendment_brewery_cafe-563_stout 21st_amendment_brewery_cafe-amendment_pale_ale 21st_amendment_brewery_cafe-bitter_american
If you want to get delete documents, you can use the
delete operation:
OperationFuture<Boolean> delete = client.delete("key");
Again,
delete is an asynchronous operation and therefore returns a
OperationFuture object on which you can block through the
get() method. If you try
to delete a document that is not there, the result of the
OperationFuture is
false. Be aware that when you delete a document, the server does not
immediately remove a copy of that document from disk, instead it performs lazy
deletion for items that expired or deleted items. For more information about how
the server handles lazy expiration, see About Document
Expiration in the Couchbase Server Developer Guide.
You are now ready to start exploring Couchbase Server and the Java SDK on your own. If you want to learn more and see a full-fledged application on top of Couchbase Server 2.2, read the Web Application Tutorial. The Couchbase Server Manual and the Couchbase Developer Guide provide useful information for your day-to-day work with Couchbase Server. You can also look at the Couchbase Java SDK API Reference.
This tutorial builds on the foundation introduced in the Getting Started section provides more content than we describe in this tutorial; but it should be easy for you to look around and understand how it functions if you first start reading this tutorial here.
If you want to get up and running really quickly, here is how to do it with Jetty. This guide assumes you are using OS X or Linux. If you are using Windows, you need to modify the paths accordingly. Also, make sure you have Maven installed on your machine.
Download Couchbase Server 2.2 and install it. Make sure you install the beer-sample data set when you run the wizard because this tutorial uses it.
Add the following views and design documents to the
beer-sample bucket.
Views and design documents enable you to index and query data from the database. Later we will publish the views as production views. For more information about using views from an SDK, see Couchbase Developer Guide, Finding Data with Views.
The first design document name is
beer and view name is
by_name:
function (doc, meta) { if(doc.type && doc.type == "beer") { emit(doc.name, null); } }
The other design document name is
brewery and view name is
by_name:
function (doc, meta) { if(doc.type && doc.type == "brewery") { emit(doc.name, null); } }
Clone the Java SDK beer
In Maven,
Navigate to and enjoy the application.
This tutorial uses Servlets and JSPs in combination with Couchbase Server 2.2 to
display and manage beers and breweries found in the
beer-sample data set. The
easiest way to develop apps is by using an IDE such as Eclipse or NetBeans. You
can use the IDE to automatically publish apps to an application server such as
Apache Tomcat or GlassFish as a WAR file. We designed the code here to be as portable as possible, but you might need to change one or two things if you have a slightly different version or a customized setup in your environment.
In your IDE, create a new
Web Project, either with or without Maven support.
If you have not already gone through the Getting Started section for the Java SDK, you
should review the information on how to include the Couchbase SDK and all the
required dependencies in your project. For more information, see
Preparation.
Also make sure to include Google GSON or your favorite JSON library as well.
This tutorial uses the following directory structure:
|-target |-src |---main |-----java |-------com |---------couchbase |-----------beersample |-----resources |-----webapp |-------WEB-INF |---------beers |---------breweries |---------maps |---------tags |---------welcome |-------css |-------js
If you use Maven, you should also have a pom.xml file in the root directory. Here is a sample pom.xml so you can see the general structure and dependencies. The full source is at the repository we mentioned earlier. See couchbaselabs on GitHub for the full pom.xml file.
<project xmlns="" xmlns: <modelVersion>4.0.0</modelVersion> <groupId>com.couchbase</groupId> <artifactId>beersample-java</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>beersample-java</name> <dependencies> <dependency> <groupId>couchbase</groupId> <artifactId>couchbase-client</artifactId> <version>1.2.1<>
To make the application more interactive, we use jQuery and Twitter Bootstrap. You can either download the libraries and put them in their appropriate css and js directories under the webapp directory, or clone the project repository and use it from there. Either way, make sure you have the following files in place:
css/bootstrap.min.css (the minified twitter bootstrap library)
css/bootstrap-responsive.min.css (the minified responsive layout classes from bootstrap)
js/jquery.min.js (the jQuery javascript library)
From here, you should have a basic web application configured that has all the
dependencies included. We now move on and configure the
beer-sample bucket so
we can use it in our application.
Views enable you to index and query data from your database. The beer-sample bucket comes with a small set of predefined view functions, but to have our application function correctly we need some more views. This is also a very good chance for you to see how you can manage views inside Couchbase Web Console. For more information on the topics, see Couchbase Developer Guide, Finding Data with Views and Couchbase Manual, Using the Views Editor.
Because we want to list beers and breweries by their name, we need to define one view function for each type of result that we want.
In Couchbase Web Console, click Views .
From the drop-down list box, choose the beer-sample bucket.
Click Development Views, and then click Create Development View to define your first view.
Give the view the names of both the design document and the actual view. Insert the following names:
Design Document Name:
_design/dev_beer
View Name:
by_name
The next step is to define the
map function and optionally at this phase
you could define a
reduce function to perform information on the index
results. In our example, we do not use the
reduce functions at all, but you can play around with reduce functions ro see how they work. For more information, see Couchbase
Developer Guide, Using Built-in Reduce
Functions
and Creating Custom
Reduces.
Insert the following JavaScript
map function and click Save.
function (doc, meta) { if(doc.type && doc.type == "beer") { emit(doc.name, null); } }
Every
map function takes the full document (
doc ) and its associated
metadata (
meta ) as the arguments. Your map function can then inspect this
data and
emit the item to a result set when you want to have it in your index.
In our case we emit the name of the beer (
doc.name ) when the document has a
type field and the type is
beer. For our application we do not need to emit a
value; therefore we emit a
null here.
In general, you should try to keep the index as small as possible. You should
resist the urge to include the full document with
emit(meta.id, doc), because
it will increase the size of your view indexes and potentially impact application performance. If you need to access the full document or large parts
of it, use the
setIncludeDocs(true) directive, which does a
get() call with the document ID in the background. Couchbase Server might return a version of
the document that is slightly out of sync with your view, but it will be a fast and efficient operation.
Now we need to provide a similar map function for the breweries. Because you already know how to do this, here is all the information you need to create it:
Design Document Name:
_design/dev_brewery
View Name:
by_name
Map Function:
function (doc, meta) { if(doc.type && doc.type == "brewery") { emit(doc.name, null); } }
The final step is to push the design documents to production mode for Couchbase Server. While the design documents are in development mode, the index is applied only on the local node. See, Couchbase Manual, Development and Production Views. To have the index on the whole data set:
In Couchbase Web Console, click Views.
Click the Publish button on both design documents.
Accept any dialog that warns you from overriding the old view function.
For more information about using views for indexing and querying from Couchbase Server, see the following useful resources:
General Information: Couchbase Server Manual: Views and Indexes.
Sample Patterns: to see examples and patterns you can use for views, see Couchbase Views, Sample Patterns.
Time-stamp of our
project:
<>
This is not ready to run yet, because you have not implemented any of these classes yet, but we will do that soon. The
listener directive references the
ConnectionMananger class, which we implement to manage the connection instance to our Couchbase cluster. The
servlet directives define the servlet classes
that we use and the following
servlet-mapping directives map HTTP URLs to them. The final
welcome-file-list directive tells the application server where to route the root URL (
"/" ).
For now, comment out all
servlet,
servlet-mapping and
welcome-file-list directives with the
<!-- and
--> tags, because the application server will complain that they are not implemented. When you implement the appropriate servlets, remove the comments accordingly. If you plan to add your own servlets, remember to add and map them inside the
web.xml properly!
The first class we implement is the
ConnectionManager in the
src/main/java/com/couchbase/beersample directory. This is a
ServletContextListener that starts the
CouchbaseClient on application startup and closes the connection when the application shuts down. Here is the
full class:; } }
In this example, we removed the comments and imports to shorten the listing a bit. The
contextInitialized and
contextDestroyed methods are called on start-up and shutdown. When the application starts, we initialize the
CouchbaseClient with the list of nodes, the bucket name and an empty password. In a production deployment, you want to fetch these environment-dependent settings from a configuration file. We will call the
getInstance() method from the servlets to obtain the
CouchbaseClient instance.
When you publish your application, you should see in the server logs that the Java SDK correctly connects to the bucket. If you see an exception at this phase, it means that your settings are wrong or you have no Couchbase Server running at the given nodes. Here is an example server log from a successful connection: implement is the
WelcomeServlet, so go ahead and remove the appropriate comments inside the
web.xml file. You also want to enable the
welcome-file-list at this point. When a user visits the application, we show him a nice greeting and give him all available options to choose.
Because there is no Couchbase Server interaction involved, we just tell it to render the JSP template: file uses styling from Twitter bootstrap to provide a clean layout. Aside from that, it shows a nice greeting and links to the servlets interesting note to make here: it uses taglibs, which enables us to use the same layout for all pages. Because we have not created this layout, we do so now. Create the following layout.tag file in the /WEB-INF/tags directory:
<% clean afterwards. When you deploy your application, you should see in the logs that it is connects to the Couchbase cluster, and when you view it in the browser you should see a nice web page greeting.
Now we reach the main portion of the tutorial where we actually interact with Couchbase Server. First, we uncomment the
BeerServlet and its corresponding tags inside the web.xml file. We make use of the view to list all beers and make them easily searchable. We also provide a form to create, edit, or delete beers.
Here is the bare structure of our
BeerServlet, which will be filled with live data soon. Once again, we removed comments and imports for the sake of brevity: { } }
Because our web.xml file uses wildcards (
* ) to route every
/beer that is
related to this servlet, we need to inspect the path through
getPathInfo() and dispatch the request to a helper method that does the actual work. We use the
doPost() method to analyze and store the results of the web form. We also use
this method to edit and create new beers because we sent the form through a POST
request.
The first functionality we implement is a list of the top 20 beers in a table.
We can use the
beer/by_name view we created earlier to get a sorted list of all beers. The following Java code belongs to the
handleIndex method and builds the list:
// in the code above queries the view, parses the results with
GSON into a
HashMap object and eventually forwards the
ArrayList to the JSP layer. At this point we can implement the index.jsp template which iterates over the
ArrayList and prints out the beers>
Here we use JSP tags to iterate
over the beers and use their properties,
name and
id, and fill the table rows with this information. In a browser you should now see a table with a list of beers with
Edit and
Delete buttons on the right. You can also see a link to the associated brewery that you can click on. Now we implement the delete action for each beer, because it’s from the
get() method and if the server successfully deletes the item we get
true and can redirect to the index action.
Now that we can delete a document, we want to enable users to edit beers. The edit action is very similar to the delete action, but it reads and updates the document based on the given ID instead of deleting it. Before we can edit a beer, we need to parse the string representation of the JSON document into a Java structure so we can use it in the template. We again make use of the
handleEdit method gets a beer document back from Couchbase Server and parses it into JSON, the document is converted to a
HashMap object and then forwarded to the edit.jsp template. Also, we define a title variable that we use inside the template to determine whether we want to edit a document or create a new one. We can enable users to create new beers as opposed to editing an existing beer anytime we pass no Beer ID>
This template is a little bit longer, but that is mainly because we have lots of fields on our beer documents. Note how we use the beer attributes inside the value attributes of the HTML input fields. We also use the unique ID in the form method to dispatch it to the correct URL on submit.
The last thing we need to do for form submission to work is the actual form parsing and storing itself. Since we do form submission object. We then
use the
set command to store the document to Couchbase Server and use Google
GSON to translate information out of the
HashMap object into a JSON string. In this case, we could also wait for a
OperationFuture response and return an error if we determine the
set failed.
The last line redirects to a show method, which just shows all fields of the document. Because the patterns are the same as before, here is the
handleShow method:); }
Again we extract the ID and if Couchbase Server finds the document it gets parsed into a HashMap and forwarded to the show.jsp template. If the server finds no document, we get a return of null in the Java SDK. The template might notice the search box at the top. We can use it to dynamically filter our table results based on the user input. We will use nearly the same code for the filter as in the index method; except this time we make use of range queries to define a beginning and end to search for. For more information about performing range queries, see Ordering.
Before we implement the actual Java method, we need to put the following snippet in the js/beersample.js file. You might have already done this at the beginning of the tutorial, and if so, you can skip this step. This code takes any search box changes from the UI and updates the table with the JSON-up events on the search field and then does an AJAX query to the search method on the servlet. The servlet computes the result and sends it back as JSON. The JavaScript then clears the table, iterates over the result, and creates new rows with the new JSON results. the key range Couchbase Server returns. If we just provide the start range key, then we
get all documents starting from our search value. Because we want only those beginning with the search value, we can use the special
"\uefff" UTF-8 character at the end, which means “end here.” You need to get used to this convention, but it’s very fast and efficient when accessing the view.
The tutorial presents an easy approach to start a web application with Couchbase Server as the underlying data source. If you want to dig a little bit deeper, see the full source code at couchbaselabs on GitHub. This contains more servlets and code to learn from. This might be extended and updated from time to time, so you might want to watch the repo.
Of course this is only the starting point for Couchbase, but together with the Getting Started Guide and other community resources you the Couchbase Java Issues Tracker.
The 1.2.3 release is the third bug fix release for the 1.2 series. It is a pure bug fix release, increasing the stability of the SDK in various scenarios.
Fixes in 1.2.3
SPY-146: When using persistence and replication constraints (that is, PersistTo and ReplicateTo), together with “special” UTF-8 characters that take up 2 bytes instead of one (for example the pound sign or euro sign), in 1.2.2 and earlier it doesn’t work‐a normal set() works, but a set with a constraint will lead to a time-out. Now the UTF-8 key is properly encoded for the underlying protocol.
SPY-144: During special failure conditions on the server side, the callback stack of an operation might grow out of bounds. This is now mitigated, improving the general stability of the client.
SPY-136: When a node is rebooted and a client later than 1.2.1 is used, the SASL (authentication) mechanism list might not respond immediately, leading to authentication failures. Now, the client waits until a valid responds is returned.
JCBC-380: When Couchbase Server is configured with an alternative admin port (not using 8091), the SDK is now aware of the change completely and does not force you to use 8091. This is a regression fix.
The 1.2.2 release is the second bug fix release for the 1.2 series. It has important fixes for the replica read functionality and in general stabilizes the 1.2 release branch. Couchbase recommends that all 1.2.x users upgrade to the 1.2.2 release.
New Features and Behavior Changes in 1.2.2
JCBC-371: In this and a series of
other changes, the overhead for vBucket objects during rebalance and in general has
been reduced. During a rebalance process, existing Configurations are reused, leading
to less garbage collection (especially when more than one
CouchbaseClient object
is used). The internal implementation has also been changed to be more memory efficient.
This change is completely opaque. You just see less memory usage and garbage collector pressure in a profiler during rebalance.
JCBC-369: A small bug in the observe
logic used for
ReplicateTo and
PersistTo operations has been fixed, but more
importantly, the performance has been improved. The constant time for an operation that
uses persistence or replication constraints has been reduced by exactly one observe interval,
which defaults to 10 ms.
Previously, the loop waited an interval at the end, even when the result was already
correctly fetched. For applications making heavy use of
PersistTo and
ReplicateTo,
this should be a good performance enhancement. Also make sure to use Couchbase Server
version 2.2 to benefit from server-side optimizations in that area.
Fixes in 1.2.2
JCBC-373, JCBC-374: In a series of changes, the stability and performance of replica read operations has been greatly improved. The code now also multicasts to the active node, increasing the chance that a replica read operation returns successfully, even when a replica node goes down. Also, thread-safety issues have been fixed and the actual calls are optimized to go only to the nodes that can (based on the configuration) answer such a get request.
JCBC-368: During bootstrap, a deadlock with the Netty IO provider has been resolved. Now, the deadlock is avoided and an exception is thrown to indicate what went wrong during streaming connection setup.
JCBC-375: In some cases, when a streaming connection was dropped because of a race condition, the new connection could not be established. This change fixes the condition and makes sure there is always a valid state.
SPY-141: Wrong assertions that would incorrectly throw an exception when a negative CAS value is received have been removed. Because this is a valid CAS identifier, the assumption can lead to false positives.
SPY-140: The correct queue is now used for the listener callbacks. Previously, the underlying queue was bounded and therefore threw exceptions in the wrong places (the IO thread). Because the number of threads is bounded, the queue needs to buffer incoming listener callbacks accordingly.
The 1.2.1 release is the first bug fix release for the 1.2 series. It fixes some issues for newly added features in 1.2.0. Couchbase recommends that all 1.2.0 users upgrade to the 1.2.1 release.
New Features and Behavior Changes in 1.2.1
SPY-135: In addition to the exposed synchronous CAS with expiration methods, the asynchronous overloaded method is also exposed.
OperationFuture<CASResponse> casFuture = client.asyncCAS(key, future.getCas(), 2, value);
Fixes in 1.2.1
ExecutorServicewas not overridden through the factory, it is now properly shut down on
client.shutdown(). This is not the case in 1.2.0, which results in some threads still running and preventing the app from halting completely.
SPY-138: The default
ExecutorService
can now be overridden properly through the
setListenerExecutorService(ExecutorService executorService)
method.
If you override the default
ExecutorService, you are also responsible for shutting it down properly
afterward. Because it can be shared across many application scopes, the CouchbaseClient cannot shut it down on your behalf.
CouchbaseConnectionFactoryBuilder builder = new CouchbaseConnectionFactoryBuilder(); ExecutorService service = Executors.newFixedThreadPool(1); CouchbaseConnectionFactory cf = builder.buildCouchbaseConnection(/…/);
JCBC-366: Enabling metrics is now easier and works as originally designed. Now you can just enable it through the builder and do not need to set the property also.
CouchbaseConnectionFactoryBuilder builder = new CouchbaseConnectionFactoryBuilder(); builder.setEnableMetrics(MetricType.DEBUG); CouchbaseConnectionFactory cf = builder.buildCouchbaseConnection();
The 1.2.0 release is the first stable release of the 1.2 series and contains new features that are backward compatible. The underlying spymemcached library, which builds the foundation for many of those features, has been upgraded to 2.10.0.
New Features and Behavior Changes in 1.2.0
groupIdelement from
couchbaseto
com.couchbase.client. You can find a list of packages at.
PLAIN) if needed, but this should not be the case in general.
observepoll interval has been decreased from 100 ms to 10 ms, which should give better performance in most cases. Also, this aligns with replication performance improvements in the Couchbase Server 2.2 release.
JCBC-343: In addition to blocking on the future
or polling its status, you can now add a listener to be notified after it is completed. The
callback is executed in a thread pool autonomously. Every future provides a
addListener()
method where a anonymous class that acts as a callback can be passed in. Here is an example:
OperationFuture<Boolean> setOp = client.set("setWithCallback", 0, "content");
setOp.addListener(new OperationCompletionListener() { @Override public void onComplete(OperationFuture<?> f) throws Exception { System.out.println("I was completed!"); } };
JCBC-344: For easier administration and
configuration purposes, you can now create a
CouchbaseConnectionFactory based on system properties.
Here is an example (the properties can be set through a file as well):
System.setProperty("cbclient.nodes", ";192.168.1.2"); System.setProperty("cbclient.bucket", "default"); System.setProperty("cbclient.password", "");
CouchbaseConnectionFactory factory = new CouchbaseConnectionFactory(); CouchbaseClient client = new CouchbaseClient(factory);
If you need to customize options, the
CouchbaseConnectionFactoryBuilder class provides a new method to
construct a factory like this. The instantiation fails if any of the three properties are missing.
Fixes in 1.2.0
flushcommand did not work on memcached-buckets since 1.1.9. This is now fixed.. | http://docs.couchbase.com/couchbase-sdk-java-1.2/ | CC-MAIN-2013-48 | refinedweb | 6,118 | 63.7 |
Building Custom jQuery Event Types: Hesitate Event
Posted December 15, 2009 at 4:22 PM by Ben Nadel
If you've worked with jQuery for a while, you've probably bound event handlers to DOM elements. And, if you've done that, you may have also bound and triggered handlers to event types that aren't natively supported by the browser (ex. "drag", "drop"). This kind of seamless event management is, without a doubt, a huge part of what makes jQuery so powerful; but event binding is only part of it. In the jQuery Cookbook, Ariel Flesler explains that beyond binding to custom events, you can actually create custom events that will be triggered implicitly by the jQuery library.
I have seen this a few times before, but was never really able to wrap my head around it. With Ariel's tutorial in hand, however, I felt determined to try and play with this concept myself. As an experiment, I wanted to see if I could create a "hesitate" event type. The idea behind "hesitate" is that it would fire if the user moused over a given element and then remained over the element - without clicking - for a certain duration. The idea being that they intend to click the element, but they are hesitating to act upon that intent.
Before we get into the internals of the custom event type creation, let's take a look at the code that uses it. In the following demo, I am going to bind to the "hesitate" event on some image thumbnail links. If the user hesitates to click a thumbnail, I am going to increase the size of that thumbnail in an attempt to entice them to click it. As you will see below, the calling code can bind to our custom event type, "hesitate", just as it could to any other event type, native or otherwise.
- <!DOCTYPE HTML>
- <html>
- <head>
- <title>Building A Custom jQuery Event Type: Hesitate</title>
- <style type="text/css">
- a {
- float: left ;
- margin-right: 15px ;
- }
- </style>
- <script type="text/javascript" src="jquery-1.4a1.js"></script>
- <script type="text/javascript" src="jquery.event.hesitate.js"></script>
- <script type="text/javascript">
- // Override the Hesitate event duration.
- // Set it to be 1 second (1000 milliseconds).
- jQuery.event.special.hesitate.duration = 1000;
- // When the DOM is ready, interact.
- jQuery(function( $ ){
- // Gather the links.
- var links = $( "a:has( > img )" );
- // Set HREF and bind "hesitate" event.
- links
- .attr( "href", "javascript:void( 0 )" )
- .bind(
- "hesitate",
- function(){
- // If the user has hesitated over this
- // link, then entise them by enlarging
- // the nested image.
- $( this )
- .children()
- .stop()
- .animate(
- {
- width: 200
- },
- {
- duration: 1000
- }
- )
- ;
- }
- )
- .bind(
- "mouseout",
- function(){
- $( this )
- .children()
- .stop()
- .animate(
- {
- width: 100
- },
- {
- duration: 200
- }
- )
- ;
- }
- )
- ;
- });
- </script>
- </head>
- <body>
- <h1>
- Building A Custom jQuery Event Type: Hesitate
- </h1>
- <p>
- <a href="##"><img src="girl.jpg" width="100" /></a>
- <a href="##"><img src="girl.jpg" width="100" /></a>
- <a href="##"><img src="girl.jpg" width="100" /></a>
- </p>
- </body>
- </html>
The first thing I am doing here is overriding the "duration" of the "hesitate" event type. This is the amount of time the user will have to be non-active over the target element before the "hesitate" event is fired. In my example, this is done across the board (as a generic event type) and not on a per-binding basis (which could also be done). Then, just as I would with any event type, I bind my event handlers to "hesitate" event on the target links.
If I mouse over one of the links, but do not commit to the click, the nested image will animate to a larger size and look like this:
What you'll notice above is that my demo code does not define the logic of the "hesitate" event type or how it gets triggered; it simply binds to the event type on the target elements. The logic and the mechanics of the event are all handled by jQuery and my custom event type setup, which is defined by the included Javascript file, jquery.event.hestiate.js. Now that you see how the event type is getting used, let's take a look at how the event type is defined:
jquery.event.hesitate.js
- // Define the Hesitate event. This event fires if a person has
- // moused-over the given element and paused for the given duration
- // without clicking.
- //
- // NOTE: To create a custom duration, update the duration
- // property (in milliseconds):
- // jQuery.event.special.hesitate.duration.
- (function( $ ){
- // When the given element is entered, we need to set up the
- // timeout that will trigger the Hesitate event after the
- // appropriate pause duration.
- var prepareHesitate = function( event ){
- var target = $( this );
- // Store the timeout with the element's data so that we
- // can clear the timeout if the user acts within the
- // given duration.
- target.data(
- "hesitate.timer",
- setTimeout(
- function(){
- // Remove any hestitate context.
- removeHesitate( event );
- // Trigger the event handlers.
- target.triggerHandler( "hesitate" );
- },
- $.event.special.hesitate.duration
- )
- );
- };
- // When the user mouses out of the given element or clicks
- // on the given element, we want to remove the hesitation
- // timer.
- var removeHesitate = function( event ){
- // Remove the timer and its data key.
- removeHesitateTimer( $( this ) );
- }
- // This removes the hestation timer on the given element.
- var removeHesitateTimer = function( target ){
- // Clear the timer.
- clearTimeout(
- target.data( "hesitate.timer" )
- );
- // Remove the timer key.
- target.removeData( "hesitate.timer" );
- }
- // ------------------------------------------------------ //
- // ------------------------------------------------------ //
- // Define our special event, "hestiate":
- $.event.special.hesitate = {
- // This method gets called the first time this event
- // is bound to THIS particular element. It will be
- // called once and ONLY once for EACH element.
- setup: function( eventData, namespaces ){
- // Bind the three event handlers that we are going
- // to need to make sure this event fires correctly.
- $( this )
- .bind( "mouseenter", prepareHesitate )
- .bind( "mouseleave", removeHesitate )
- .bind( "click", removeHesitate )
- ;
- // Return void as we don't want jQuery to use the
- // native event binding on this element.
- return;
- },
- // This method gets called when this event us unbound
- // from THIS particular element.
- teardown: function( namespaces ){
- var target = $( this );
- // Remove bound events.
- target
- .unbind( "mouseenter", prepareHesitate )
- .unbind( "mouseleave", removeHesitate )
- .unbind( "click", removeHesitate )
- ;
- // We also want to remove the timer in case there is
- // one in progress.
- removeHesitateTimer( target );
- // Return void as we don't want jQuery to use the
- // native event binding on this element.
- return;
- },
- // This is the duration a user must pause over the
- // target element without acting before the hesitate
- // event will be triggered.
- duration: (2 * 1000)
- };
- })( jQuery );
This is my first time trying this, so I am 100% how it all wires together. But, from what I understand, all custom jQuery events are defined as named-structures off of:
jQuery.event.special
This event definition object should contain, at the very least, two core methods, setup() and teardown(). The setup() method is a sort of event constructor that gets called exactly once for each element the first time the custom event is bound to it. The teardown() method is a sort of event destructor that gets called exactly once for each element when the custom event is unbound from it.
What you do in these methods is up to you; but, because we are building completely custom events, we need to build on top of events that are natively supported by the browser (or at least other events that might be triggered in some way). As such, from within our setup() method, we need to bind event handlers to the core events that will power our custom event. In this case, for the "hesitate" event, there are three crucial event types to monitor:
- MouseEnter. When the user mouses into the target element, we have to start keeping track of their subsequent hesitation to click.
- MouseLeave. When the user mouses out of the target element, we no longer need to keep track of their activity.
- Click. When the user clicks on the target element, they can no longer be considered inactive or hesitating.
Once we bind to these core methods, we can then go about using them to create our custom event. In our particular case, when the user enters the target area, we create a timer that waits for inactivity. If the user clicks on the target element, or mouses out of it, we kill the inactivity timer. If the user does neither of these two things, the timer will execute and its callback will trigger the "hesitate" event on the target element. At this point, any subsequent handlers bound to this target element for the "hesitate" event will be executed.
While this works well, it should be noted that the core events (upon which are custom event is powered) are not shielded in any way. Meaning, if someone were to trigger a "click" event on our target element, it would certainly trigger the "click" handler that we are using to power the "hesitate" event.
As this is the first time that I have created a custom jQuery event type, I am sure that I am leaving juicy pieces of information out of my explanation. For instance, I have not talked about namespaces, additional event data, or per-binding custom settings; hopefully I can address such things in a future post.
What Other People Are Searching For
[ local search ]
creating custom events in jquery
[ local search ] creating custom event types in jquery
[ local search ] how do i create custom events in jquery
[ local search ] how do i create custom event types in jquery
Looking For a New Job?
Reader Comments
It would be interesting for you to compare the code to this:
You basically engineered it in a "clean room".
Man, you are a blogging machine!
Great stuff as always. Might be neat to use hesitate to guide a user toward a task that you think they might be wanting? Kinda a newbie nudge ;)
Expect a tech tweet tomorrow @ 9:30AM CST
I think it should be called "entice" instead of hesitate :)
(great post!)able"... just my first thoughts.
Good info on custom events!
@Glen,
I'll take a look at it. Quickly glanced and it looks like he based his on actual mouse movement / acceleration. Very cool.
@Elijah,
Thanks my man! I just love this stuff :)
@Chris,
That's also a good thought. At the end of the day, I just needed *something* to use in order to experiment with the topic :)
I just have to say, that you web developers are AWESOME! and don't get the credit you deserve :(
I have been following your blog for the last 2yrs. I had no idea all the stuff that goes into the websites that I navigate on a daily basis. WOW!
I have learned many cool things on your blog. I just feel like becoming a developer myself :)
Thanks!
@Katie,
Thank you very much :D I think you just made everyone's day (on this blog)... even though I know this comment is a few weeks old.
Thanks.
Always love to read and watch your posts. | http://www.bennadel.com/blog/1786-Building-Custom-jQuery-Event-Types-Hesitate-Event.htm | CC-MAIN-2013-48 | refinedweb | 1,808 | 62.48 |
Originally posted by Alex Givant: [B]Hi, guys. Here is my question related to socket creation timeout. We want to control process of socket creation and if socket hasn't been created in timeout period just continue with the program flow. Here I've wrote some simple program and it's shows me different results on different platforms:
import java.net.*;
import java.util.Date;
public class SocketTest
{
public static void main(String [] args)
{
Date date1, date2;
date1 = new Date();
try {
Socket s = new Socket("10.0.10.146", 1000);
} catch (Exception ex)
{
ex.printStackTrace();
}
date2 = new Date();
System.out.println("it's took us " + (date2.getTime() -
date1.getTime()) + " millisecs.");
}
}
Here I'm using "10.0.10.146" as IP address of non-exist computer When I run it on Windows 2000 - it gives me ~ 21.5 second. But Sun Solaris - 219.5 second (x10 from Windows time). So my question: Is any way to control that (beside creating thread which will wait for n seconds and if socket not exists yet will send some kind of exception)? Any answer appriciated. Alex. [This message has been edited by Alex Givant (edited November 27, 2001).][/B] | http://www.coderanch.com/t/205183/sockets/java/Socket-Timeout | CC-MAIN-2014-42 | refinedweb | 195 | 68.57 |
This compares ARGB but you could change it to just use RGB:
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Windows.Forms; namespace daniweb { public partial class frmScreenShot : Form { public frmScreenShot() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Point[] points = FindColor(button1.BackColor); System.Diagnostics.Debugger.Break(); } private static Bitmap GetScreenShot() { Bitmap result = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb); { using (Graphics gfx = Graphics.FromImage(result)) { gfx.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy); } } return result; } private static Point[] FindColor(Color color) { int searchValue = color.ToArgb(); List<Point> result = new List<Point>(); using (Bitmap bmp = GetScreenShot()) { for (int x = 0; x < bmp.Width; x++) { for (int y = 0; y < bmp.Height; y++) { if (searchValue.Equals(bmp.GetPixel(x, y).ToArgb())) result.Add(new Point(x, y)); } } } return result.ToArray(); } } }
How would I move my cursor to those coordinants then afterwards?
I tried this . . .
Cursor.Position = new System.Drawing.Point(points);
But got this error . . .
Argument '1': cannot convert from 'System.Drawing.Point[]' to 'System.Drawing.Size' (CS1503)
Any ideas?
The problem is you're more than like going to get more than one pixel that contains that color.... Like the windows task bar is the same color grey so if you match it then you will match all of the bottom pixels on your display. Anyway, to move your cursor to the first located pixel.
Modify the button click:
private void button1_Click(object sender, EventArgs e) { Point[] points = FindColor(button1.BackColor); if (points.Length > 0) Cursor.Position = points[0]; }
Is there a faster method of doing the same job as this?
When I try it really quickly, the program eats all my CPU and lags until finished.
Why don't you tell me what you're really trying to do? Yes, there is a faster way. The way i'm doing it processes the *entire* image but it could be changed to stop after it matched the first pixel.
Locating screen pixels is not very accurate and i'm having a hard time envisioning what useful task you could be doing with this :)
Please elaborate
Ok, I'm trying to get my program to search for a selected color on the screen, and then move your cursor to the x,y position of that color afterwards.
This is called a 'Color Aim Bot' or a 'Pixel Chaser'.
It needs to updated very quickly (around 25 - 50ms) and act very quickly aswell to be effective.
See where I'm going with this? :)
Nevermind, found some great code and its exactly what I've been looking for.
Thank you for your help!!
SOLVED
Please share :) | https://www.daniweb.com/programming/software-development/threads/214968/c-finding-a-pixel-by-color | CC-MAIN-2016-50 | refinedweb | 456 | 52.76 |
In this basic C++ program, we will have a look at how to find the size of int, float, double and char in your system.
sizeof the operator is used to find the size of the variable.
sizeof(dataType);
C++ Program to find the size of int, float, double and char in Your System
This program declares 4 variables of type int, float, double and char. Then, the size of each variable is evaluated using sizeof operator.
#include <iostream> using namespace std; int main() { cout<<"Size of int is "<<sizeof(int)<<" bytes"<<endl; cout<<"Size of float is "<<sizeof(float)<<" bytes"<<endl; cout<<"Size of double is "<<sizeof(double)<<" bytes"<<endl; cout<<"Size of char is "<<sizeof(char)<<" byte"<<endl; return 0; }
Output
Size of char: 1 byte Size of int: 4 bytes Size of float: 4 bytes Size of double: 8 bytes | https://www.codeatglance.com/cpp-program-to-find-size-of-int-float-double-and-char-in-your-system/ | CC-MAIN-2020-40 | refinedweb | 143 | 62.01 |
Python Mini Project – Speech Emotion Recognition with librosa
Keeping you updated with latest technology trends, Join DataFlair on Telegram
Python Mini Project
Speech emotion recognition, the best ever python mini project. The best example of it can be seen at call centers. If you ever noticed, call centers employees never talk in the same manner, their way of pitching/talking to the customers changes with customers. Now, this does happen with common people too, but how is this relevant to call centers? Here is your answer, the employees recognize customers’ emotions from speech, so they can improve their service and convert more people. In this way, they are using speech emotion recognition. So, let’s discuss this project in detail.
Speech emotion recognition is a simple Python mini-project, which you are going to practice with DataFlair. Before, I explain to you the terms related to this mini python project, make sure you bookmarked the complete list of Python Speech Emotion Recognition?
Speech Emotion Recognition, abbreviated as SER, is the act of attempting to recognize human emotion and affective states from speech. This is capitalizing on the fact that voice often reflects underlying emotion through tone and pitch. This is also the phenomenon that animals like dogs and horses employ to be able to understand human emotion.
SER is tough because emotions are subjective and annotating audio is challenging.
What is librosa?
librosa is a Python library for analyzing audio and music. It has a flatter package layout, standardizes interfaces and names, backwards compatibility, modular functions, and readable code. Further, in this Python mini-project, we demonstrate how to install it (and a few other packages) with pip.
What is JupyterLab?
JupyterLab is an open-source, web-based UI for Project Jupyter and it has all basic functionalities of the Jupyter Notebook, like notebooks, terminals, text editors, file browsers, rich outputs, and more. However, it also provides improved support for third party extensions.
To run code in the JupyterLab, you’ll first need to run it with the command prompt:
C:\Users\DataFlair>jupyter lab
This will open for you a new session in your browser. Create a new Console and start typing in your code. JupyterLab can execute multiple lines of code at once; pressing enter will not execute your code, you’ll need to press Shift+Enter for the same.
Speech Emotion Recognition – Objective
To build a model to recognize emotion from speech using the librosa and sklearn libraries and the RAVDESS dataset.
Speech Emotion Recognition – About the Python Mini Project
In this Python mini project, we will use the libraries librosa, soundfile, and sklearn (among others) to build a model using an MLPClassifier. This will be able to recognize emotion from sound files. We will load the data, extract features from it, then split the dataset into training and testing sets. Then, we’ll initialize an MLPClassifier and train the model. Finally, we’ll calculate the accuracy of our model.
The Dataset
For this Python mini project, we’ll use the RAVDESS dataset; this is the Ryerson Audio-Visual Database of Emotional Speech and Song dataset, and is free to download. This dataset has 7356 files rated by 247 individuals 10 times on emotional validity, intensity, and genuineness. The entire dataset is 24.8GB from 24 actors, but we’ve lowered the sample rate on all the files, and you can download it here.
Prerequisites
You’ll need to install the following libraries with pip:
pip install librosa soundfile numpy sklearn pyaudio
If you run into issues installing librosa with pip, you can try it with conda.
Steps for speech emotion recognition python projects
1. Make the necessary imports:
import librosa import soundfile import os, glob, pickle import numpy as np from sklearn.model_selection import train_test_split from sklearn.neural_network import MLPClassifier from sklearn.metrics import accuracy_score
Screenshot:
2. Define a function extract_feature to extract the mfcc, chroma, and mel features from a sound file. This function takes 4 parameters- the file name and three Boolean parameters for the three features:
- mfcc: Mel Frequency Cepstral Coefficient, represents the short-term power spectrum of a sound
- chroma: Pertains to the 12 different pitch classes
- mel: Mel Spectrogram Frequency
Learn more about Python Sets and Booleans
Open the sound file with soundfile.SoundFile using with-as so it’s automatically closed once we’re done. Read from it and call it X. Also, get the sample rate. If chroma is True, get the Short-Time Fourier Transform of X.
Let result be an empty numpy array. Now, for each feature of the three, if it exists, make a call to the corresponding function from librosa.feature (eg- librosa.feature.mfcc for mfcc), and get the mean value. Call the function hstack() from numpy with result and the feature value, and store this in result. hstack() stacks arrays in sequence horizontally (in a columnar fashion). Then, return the result.
#DataFlair -
Screenshot:
3. Now, let’s define a dictionary to hold numbers and the emotions available in the RAVDESS dataset, and a list to hold those we want- calm, happy, fearful, disgust.
#DataFlair - Emotions in the RAVDESS dataset emotions={ '01':'neutral', '02':'calm', '03':'happy', '04':'sad', '05':'angry', '06':'fearful', '07':'disgust', '08':'surprised' } #DataFlair - Emotions to observe observed_emotions=['calm', 'happy', 'fearful', 'disgust']
Screenshot:
Facing Failure in Interview?
Prepare with DataFlair – Frequently Asked Python Interview Questions
4. Now, let’s load the data with a function load_data() – this takes in the relative size of the test set as parameter. x and y are empty lists; we’ll use the glob() function from the glob module to get all the pathnames for the sound files in our dataset. The pattern we use for this is: “D:\\DataFlair\\ravdess data\\Actor_*\\*.wav”. This is because our dataset looks like this:
Screenshot:
So, for each such path, get the basename of the file, the emotion by splitting the name around ‘-’ and extracting the third value:
Screenshot:
Using our emotions dictionary, this number is turned into an emotion, and our function checks whether this emotion is in our list of observed_emotions; if not, it continues to the next file. It makes a call to extract_feature and stores what is returned in ‘feature’. Then, it appends the feature to x and the emotion to y. So, the list x holds the features and y holds the emotions. We call the function train_test_split with these, the test size, and a random state value, and return that.
#DataFlair - Load the data and extract features for each sound file def load_data(test_size=0.2): x,y=[],[] for file in glob.glob("D:\\DataFlair\\ravdess data\)
Screenshot:
5. Time to split the dataset into training and testing sets! Let’s keep the test set 25% of everything and use the load_data function for this.
#DataFlair - Split the dataset x_train,x_test,y_train,y_test=load_data(test_size=0.25)
Screenshot:
6. Observe the shape of the training and testing datasets:
#DataFlair - Get the shape of the training and testing datasets print((x_train.shape[0], x_test.shape[0]))
Screenshot:
7. And get the number of features extracted.
#DataFlair - Get the number of features extracted print(f'Features extracted: {x_train.shape[1]}')
Output Screenshot:
8. Now, let’s initialize an MLPClassifier. This is a Multi-layer Perceptron Classifier; it optimizes the log-loss function using LBFGS or stochastic gradient descent. Unlike SVM or Naive Bayes, the MLPClassifier has an internal neural network for the purpose of classification. This is a feedforward ANN model.
#DataFlair - Initialize the Multi Layer Perceptron Classifier model=MLPClassifier(alpha=0.01, batch_size=256, epsilon=1e-08, hidden_layer_sizes=(300,), learning_rate='adaptive', max_iter=500)
Screenshot:
9. Fit/train the model.
#DataFlair - Train the model model.fit(x_train,y_train)
Output Screenshot:
10. Let’s predict the values for the test set. This gives us y_pred (the predicted emotions for the features in the test set).
#DataFlair - Predict for the test set y_pred=model.predict(x_test)
Screenshot:
11. To calculate the accuracy of our model, we’ll call up the accuracy_score() function we imported from sklearn. Finally, we’ll round the accuracy to 2 decimal places and print it out.
#DataFlair - Calculate the accuracy of our model accuracy=accuracy_score(y_true=y_test, y_pred=y_pred) #DataFlair - Print the accuracy print("Accuracy: {:.2f}%".format(accuracy*100))
Output Screenshot:
Summary
In this Python mini project, we learned to recognize emotions from speech. We used an MLPClassifier for this and made use of the soundfile library to read the sound file, and the librosa library to extract features from it. As you’ll see, the model delivered an accuracy of 72.4%. That’s good enough for us yet.
Hope you enjoyed the mini python project.
Want to become next Python Developer??
Enroll for Online Python Course at DataFlair NOW!!
IndexError Traceback (most recent call last)
in
—-> 1 x_train,x_test,y_train,y_test=load_data(test_size=0.25)
in load_data(test_size)
3 for file in glob.glob(“C:\\Users\\N. Tejashwini\\Downloads\\speech-emotion-recognition-ravdess-data\\Actor_01”):
4 file_name=os.path.basename(file)
—-> 5 emotion=emotions[file_name.split(“-“)[2]]
6 if emotion not in observed_emotions:
7 continue
IndexError: list index out of range
I am getting the above error. How to solve could you please help me?
ParameterError: Invalid shape for monophonic audio: ndim=2 can be resolved by loading the file using librosa.
X = sound_file.read()
sample_rate=sound_file.samplerate
The above two lines in the method extract_feature can be replaced with the below line.
X, sample_rate = librosa.load(file_name)
The path seems to be incorrect in your code.
Replace line 3 in above code snippet with
for file in glob.glob(“C:\\Users\\N. Tejashwini\\Downloads\\speech-emotion-recognition-ravdess-data\\Actor_01\\*.wav”):
And, if you want to extract data for all the actors, try
for file in glob.glob(“C:\\Users\\N. Tejashwini\\Downloads\\speech-emotion-recognition-ravdess-data\\Actor_*\\*.wav”):
How to plot accuracy for this dateset model?
how to do visualization for this dataset
how to do visualization for this dataset
#DataFlair – Get the shape of the training and testing datasets
print((x_train.shape[0], x_test.shape[0]))
>(0, 0)
Getting this after completing all the above steps.
How to solve this
#DataFlair – Get the shape of the training and testing datasets
print((x_train.shape[0], x_test.shape[0]))
(0, 0)
I cannot load the data
can anybody help
@Aditya, I got that when I had the wrong path to the data set. It has a shape of (0,0) because no data is being loaded.
Check that you’re passing the correct path to the data.
njnj
Hello ,anyone can help me with increasing accuracy of the model.The accuracy for me it is coming around:59.9%
I have got accuracy of 59.9% with MLP classifier.So,anyone please help me to increase my accuracy.
could you please tell me how you load the data
Where have you tested? Please test on unseen dataset before uploading
Got this error when splitting the dataset:
ValueError Traceback (most recent call last)
in
1 #Split the dataset
—-> 2 x_train,x_test,y_train,y_test=load_data(test_size=0.2)
in load_data(test_size)
11 x.append(feature)
12 y.append(emotion)
—> 13 return train_test_split(np.array(x), y, test_size=test_size, random_state=9)
ValueError: With n_samples=0, test_size=0.2 and train_size=None, the resulting train set will be empty. Adjust any of the aforementioned parameters.
is there any other solution ?
I am not getting this one please
I got the same error too, please let me know how to go about it.
I have resolved it by making some changes…
import zipfile
def load_data(test_size=0.2):
x,y=[],[]
with zipfile.ZipFile(‘speech-emotion-recognition-ravdess-data.zip’, ‘r’) as z:
z.extractall(‘temp’)
for file in glob.glob(“temp\\Actor_*\\*.wav”):
——
The dataset is actually a .zip file which needs to be extracted( here I have extracted in a separate folder called ‘temp’ in read mode) and retrieved .wav files from temp folder in glob.glob() in for loop.
try this
Hey, you passed the path for the zip file in the “with zipfile.Zipfile()” command right?
File “”, line 6
with zipfile.ZipFile(‘speech-emotion-recognition-ravdess-data.zip’, ‘r’) as z:
^
SyntaxError: invalid character in identifier
I have used your code but its showing errors..how to solve this
and how to accesss the load data
change your quotation mark from backquote/backtick to single quote if you have copy-pasted the line(s) from here or else type the statement(s)…
Also make sure to pass the correct path.
Here the project is about recognising the emotion if the speech, So the output must be the emotin of our speech, like happy,angry etc
but here the output is accuracy…
what is the need of accuracy and how it is related to the project?
could anyone please clarify this.
Can you please show us how to test the model and the output of detecting emotion of input audio?
—————————————————————————
ModuleNotFoundError Traceback (most recent call last)
in
—-> 1 import librosa
2 import soundfile
3 import os, glob, pickle
4 import numpy as np
5 from sklearn.model_selection import train_test_split
~/conda/envs/python/lib/python3.6/site-packages/librosa/__init__.py in
10 # And all the librosa sub-modules
11 from ._cache import cache
—> 12 from . import core
13 from . import beat
14 from . import decompose
~/conda/envs/python/lib/python3.6/site-packages/librosa/core/__init__.py in
123 “””
124
–> 125 from .time_frequency import * # pylint: disable=wildcard-import
126 from .audio import * # pylint: disable=wildcard-import
127 from .spectrum import * # pylint: disable=wildcard-import
~/conda/envs/python/lib/python3.6/site-packages/librosa/core/time_frequency.py in
9 import six
10
—> 11 from ..util.exceptions import ParameterError
12 from ..util.deprecation import Deprecated
13
~/conda/envs/python/lib/python3.6/site-packages/librosa/util/__init__.py in
75 “””
76
—> 77 from .utils import * # pylint: disable=wildcard-import
78 from .files import * # pylint: disable=wildcard-import
79 from .matching import * # pylint: disable=wildcard-import
~/conda/envs/python/lib/python3.6/site-packages/librosa/util/utils.py in
13 from .._cache import cache
14 from .exceptions import ParameterError
—> 15 from .decorators import deprecated
16
17 # Constrain STFT block sizes to 256 KB
~/conda/envs/python/lib/python3.6/site-packages/librosa/util/decorators.py in
7 from decorator import decorator
8 import six
—-> 9 from numba.decorators import jit as optional_jit
10
11 __all__ = [‘moved’, ‘deprecated’, ‘optional_jit’]
ModuleNotFoundError: No module named ‘numba.decorators’
I’m getting this error. How can i resolve it?
pip install numba==0.48
use this in your cmd
Could this library be used for Voice Identification and authentication?
what other ML technique i can use on this project to improve accuracy?
how to convert video file of dataset to speech???
what kind of neural network use is in this projekt?
NameError Traceback (most recent call last)
in
13 chroma=np.mean(librosa.feature.chroma_stft(S=stft, sr=sample_rate).T,axis=0)
14 result=np.hstack((result, chroma))
—> 15 if mel:
16 mel=np.mean(librosa.feature.melspectrogram(X, sr=sample_rate).T,axis=0)
17 result=np.hstack((result, mel))
NameError: name ‘mel’ is not defined
This is the error I am getting
what should I do now? | https://data-flair.training/blogs/python-mini-project-speech-emotion-recognition/comment-page-2/ | CC-MAIN-2020-45 | refinedweb | 2,540 | 59.4 |
How to load single-page app faster
We work on apps with a lot of JavaScript code, styles. We have the endless process of adding new features, pages, elements everyday. Gradually we have a problem when size and loading time of the our bundled code increases.
It seems like present frontend development has some challenges for us. Many users work with our apps using low-end smartphones. Much code with business logic is located on client instead of backend.
Herewith many of us don’t think about the optimal use/ship of resouces. Our apps have an enormous trees of external dependencies whose authors also don’t think about size of their packages.
What can we do?
Use of the following modern techniques will help us to ship smaller bundles to browsers.
Tree shaking
This feature is used for dead code elimination. Tree shacking was implimented in many actual bundle tools like webpack or rollup for ES2015 modules.
If we have an entry point and imported module with some unused exports, we can reduce bundle size out of the box.
index.js:
import {willBundled} from './utils' willBundled()
utils.js:
export function willBundled () { console.log('Hello') } export function willEliminated () { console.log('Dead code') }
We see that the second export is declared but not used. So its will not be in final bundle.
This technique works only for ES2015 modules.
We want eliminate dead code also for packages whose use commonjs exports.
First we can try to automate it with plugins such a
webpack-common-shake or
rollup-plugin-commonjs.
In the second place when using big external libraries,
lodash for example, we can initially avoid inclusion to bundle.
If we import something as follows, whole
lodash code will be included:
import {omit} from 'lodash'
It happens because libraries were preliminarily transpiled to ES5 syntax with
require imports.
To reduce the import of such libraries, you should request only things you need:
import omit from 'lodash/omit'
Code splitting
This feature is used for split our code into many chunks instead of one bundle. It allows manage the priority of loading chunks and load their in parallel or lazily. Code splitting is currently supported by webpack, but isn’t still implemented in rollup.
We can split a code describing many entry points or dynamic imports.
webpack.config.js:
module.exports = { entry: { loader: './index', check: './check' }, output: { filename: '[name].chunk.js', chunkFilename: '[name].chunk.js', path: `${__dirname}/dist` } }
index.js:
import React from 'react' import {render} from 'react-dom' import check from './check' async function init () { const logined = await check() if (!logined) { window.location = '/login' return } const {default: App} = await import(/* webpackChunkName: "app" */ './app') render( <App />, document.getElementById('root') ) } init()
Building this project will turn three small chunks:
dist |- app.chunk.js |- check.chunk.js |- loader.chunk.js
Splitting also can be implemented automatically using webpack
CommonChunkPlugin.
webpack.config.js:
const webpack = require('webpack') module.exports = { entry: { app: './index', user: './pages/user', dashboard: './pages/dashboard' }, output: { filename: '[name].chunk.js', path: `${__dirname}/dist` }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: 'common' }) ] }
After building this project common code parts will be moved to separate chunk:
dist |- app.chunk.js |- common.chunk.js |- dashboard.chunk.js |- user.chunk.js
Splitting code can also be produced by the other plugins:
- extract-text-webpack-plugin—split CSS by extracting text from bundle into a file
- bundle-loader—split code and lazy load resulting bundles
Common code extracting
Code we are writing sometimes has some duplicated parts that increase the size of our bundle. Elements may use common styles. Functions may have similar logic.
If we detect this, we should extract common parts to higher-order function/class:
These techniques allow us avoid code duplication and reuse function/style logic.
import React, {Component} from 'react' class Dashboard extends Component { componentDidMount () { document.title = 'Dashboard' } render () { return ( <SomeComponent /> ) } } class Profile extends Component { componentDidMount () { document.title = 'Profile' } render () { return ( <AnotherComponent /> ) } }
Some common logic is in the example.
Each of components sets document title in its
componentDidMount life-cycle method.
Extracting this will turn more reusable code without duplication.
import React, {Component} from 'react' function withTitle (title) { return Decorated => class extends Component { componentDidMount () { document.title = title } render () { return ( <Decorated {...this.props} /> ) } } } @withTitle('Dashboard') class Dashboard extends Component { render () { return ( <SomeComponent /> ) } } @withTitle('Profile') class Profile extends Component { render () { return ( <AnotherComponent /> ) } }
Caching
After reducing the size of our bundle, we should directly think about loading it with browser. If we have single bundle, user browser will be forced to load it again after each code change. To avoid this, we can use browser technique called caching. Browser caching allows you speed up loading recources by saving files locally.
We laid a good basis to cache our code applying the tree shaking, splitting and extracting. After splitting, we have few small chunks. Each of them can be cached. With tools like webpack, we can easy configure caching.
webpack.config.js:
module.exports = { entry: { app: './index', utils: './utils' }, output: { filename: '[name].[chunkhash].js', chunkFilename: '[name].[chunkhash].js', path: `${__dirname}/dist` } }
Building this project will get chunks with chunk-specific hashes in filenames:
dist |- app.e2a5ac13d7b26742f4d7.js |- utils.e646121558170aeedd91.js
Now when we modify code in one module, building this project update only one chunk containing this module with new hash. User browser will have to load again only this updated chunk. Other ones will be taken from browser cache.
One more thing we can apply to build is a manual extracting vendor modules and lock their versions. External libraries are updated us less often than own code. So we should minimize the force loading of a chunk containing this libraries.
webpack.config.js:
const webpack = require('webpack') module.exports = { entry: { app: './index', utils: './utils', vendor: [ 'react', 'react-dom' ] }, output: { filename: '[name].[chunkhash].js', chunkFilename: '[name].[chunkhash].js', path: `${__dirname}/dist` }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: Infinity }) ] }
Building with this config will make the following output:
dist |- app.e2a5ac13d7b26742f4d7.js |- utils.e646121558170aeedd91.js |- vendor.95dc51f578ab5785150a.js
Wrapping up
That’s all. We’ve learned few useful methods to speed up loading of our resources. If you have a slow loaded app with a big bundle for shipping, try to apply all those techniques to your building process.
Research what you can do to reduce the loading time more. Here are some other approaches to help you optimize this more:
- Preload: What Is It Good For?
- Inlining critical CSS for better web performance
- The Benefits of Server Side Rendering Over Client Side Rendering
Think about loading performance at every turn. | https://andrepolischuk.com/how-to-load-single-page-app-faster/ | CC-MAIN-2017-51 | refinedweb | 1,084 | 59.6 |
How to Load External Flash Video (FLV) Files (AS2)
Note: This article has a companion piece, “How to Control Video (FLV) without a Component.” An ActionScript 3.0 version of this article is located in a more recent entry of this blog.
It has been possible to load external video into a movie since Flash MX (aka Flash 6). Loading FLV files, however, isn’t nearly as intuitive as loading other external media, such as SWFs, JPGs, MP3s, and the like. The
MovieClip.loadMovie() method, for example, loads an external SWF with a single line of code. Not so for FLV. So how is it done?
Many people take the route of one of the Flash MX/Flash MX 2004 Media Components or the Flash 8 FLVPlayback Component. These provide the convenience of drag-and-drop setup (just set the
contentPath property in your Component Inspector panel) and UI controls for playing, pausing, adjusting volume, and more. Certainly, nice features — but you may simply want a no-frills display, “Just give me the video.” Besides, these Components only ship with the Professional editions of Flash and they do add to the SWF footprint. The older Components weigh between 55KB and 68KB on their own. The newer Component weighs less, but requires a Flash Player 8 SWF and still adds 33KB to your movie.
An answer, short and sweet
Let’s get to business, then. Here’s a virtually 0KB way to add video to your SWFs, compatible back to Flash Player 6*.
- Click on the Options menu of your Library panel (the square-ish icon in the upper right corner) and choose New Video….
- Drag an instance of your new video object to the Stage. Set its height and width as desired.
- While the instance is selected, use the Property inspector to provide an instance name. In this example, we’ll use
videoPlayer.
- Add the following ActionScript to a keyframe of the timeline that holds the video object. If you like to be organized (and you do!), create a dedicated scripts layer, but any layer will suffice.
var nc:NetConnection = new NetConnection(); nc.connect(null); var ns:NetStream = new NetStream(nc); videoPlayer.attachVideo(ns); ns.play("externalVideo.flv");
* Important Note: According to the ActionScript Language Reference, the
NetConnection and
NetStream classes require Flash Player 7 or higher. In my own experience, I find success publishing to a Flash Player 6 SWF with ActionScript 2.0.
How it works
NetConnection is designed to provide playback of streaming FLVs from a local drive or HTTP address. By supplying the
NetConnection.connect() method with a
null parameter, we avoid dependence on Flash Media Server (formerly known as Flash Communication Server) in order to play video.
NetStream handles the video stream for
NetConnection, and our
videoPlayer instance cooperates with all of the above via the
Video.attachVideo() method. Finally, our
NetStream instance loads the external FLV via the
NetStream.play() method.
The desired video will begin playing before the file completely loads — when enough data have buffered — so this is a great way to load sizeable video content without significant download time.
April 14th, 2006 at 11:36 pm
Why doesn’t the Video class have an attachAudio() and an adjustVolume method? I find it somewhat strange on how to adjust the volume of a FLV. Attaching the video using attachVideo() logically makes sense;
VideoInstanceName.attachVideo(ns);
Now attaching the audio to the FLV using the MovieClip’s attachAudio() is strange! I think it would make more sense if the Video class has an attachAudio() that we can use. But we are still not there yet to adjust the volume! We must now add a Sound object by doing the following;
//controlling sound
this.createEmptyMovieClip(”flv_mc”, this.getNextHighestDepth());
flv_mc.attachAudio(stream_ns);
var audio_sound:Sound = new Sound(flv_mc);
audio_sound.setVolume(80);
Weird? Or is it just me?
April 15th, 2006 at 11:22 am
myIP,
Heh, well, I can’t answer your “why” question, of course.
I would love to know more about the in-house evolution of ActionScript. I imagine Colin Moock’s next book — whether it’s ActionScript 3.0: The Definitive Guide, Essential ActionScript 3.0, or whatever (all just conjecture on my part) — will illuminate some of that.
My only guess is that the current API is an outgrowth of historical precedent. The
MovieClipclass existed before the
Videoclass did. Sound has always been a part of Flash, and for reasons unknown to outsiders, the
MovieClipclass and
Soundclass were designed to be used in collaboration. Perhaps it would have been redundant, speaking from an under-the-hood point of view, to include audio members in the
Videoclass.
Some folks have a difficult enough time (at first) “getting” the relationship among
NetConnection,
NetStream, and
Video: it already seems like jumping through hoops, right? But once it makes sense, it makes sense. In any case — not to wax too existential — it is what it is. Even if video isn’t as intuitive a pursuit in Flash as others are, I’m glad to have both video and audio in the API!
And, as always, it’s easy enough write a wrapper class to tie these loose ends together.
April 15th, 2006 at 10:52 pm
David — thanks for this great tip. I’ve spent the great part of the whole day attempting to work something similar, and here you’ve done it!
Bravo, really. Quick question: is there a way to add some sort of listener in AS to see when the FLV is finished and send the playhead on to the next frame? Some kind of if/else statement?
Thanks again for your blog!
–Mark
April 16th, 2006 at 4:13 pm
Mark,
Great question! When I originally wrote this article, my intention was to follow up with a “part two” to cover what you’ve asked. I need to do a bit more research before I write a proper sequel, but I’ll tell you what I’ve toyed with so far.
The
Videoclass itself contains no events. (An event is a notification raised by an object when a certain incident occurs. An example of this is the
Button.onReleaseevent, which fires after someone clicks a button then releases the mouse.) The
Videoclass features plenty of useful properties and two methods — of which we’ve seen
Video.attachVideo()— but no events. So that’s a dry well.
NetConnectionis out, too: only one method, nothing more. But
NetStreamprovides what might be a promising event,
NetStream.onStatus. More on that in a moment.
Truth be told, I was hoping for, say, a
NetStream.onCompleteevent, but something about video streams apparently makes the notion either too difficult or impossible. (Perhaps video streams simply cannot carry with them data on the expected duration of their content?)
The next step, then, is to repeatedly compare the current position of the video against its length. But this isn’t a simple solution, either. Case in point: the
Mediaclass, which also plays video, states the following in its entry for the
Media.totalTimeproperty …
The
Mediaclass happens to be the basis for the weighty Media Components discussed above, so I’d like to avoid its use in pursuit of as small a footprint as possible. That said, the
Mediaclass does provide a
Media.completeevent. I’m guessing it’s founded on the developer-supplied
Media.totalTimeproperty.
Since the
NetStreamclass provides a
NetStream.timeproperty, we do have a way to determine what the current position of the video is. If we use some repeating event, such as
MovieClip.onEnterframe, or the above-mentioned
NetStream.onStatusevent, we could compare
Video.timeto a developer-supplied total. When the former is equal to or greater than the latter, the video has come to its end.
I don’t much care for the apparent necessity of a developer-supplied total, because there may be cases where the video’s length is unknown beforehand — and then what? But it’s a start. In the sample below, the number 25 refers to 25 seconds and is completely arbitrary.
Looking through the
NetStream.onStatusevent, I found that it does describe the video buffer (see the
NetStream.Buffer.Flushcode property). The case in which “Data has finished streaming, and the remaining buffer will be emptied” (ActionScript 2.0 Language Reference) may signal the end of a stream. Of course, it may also indicate network traffic, and that’s what I’d like to determine before publishing something “official” like a sequel. As soon as I figure it out, though, you’ll see an entry on it.
April 17th, 2006 at 3:31 pm
“Perhaps it would have been redundant, speaking from an under-the-hood point of view, to include audio members in the Video class.”- Stiller
I was also thinking the same. Yes, perhaps Moock will illuminate the subject in his next book. Thanks again David.
April 28th, 2006 at 4:21 pm
yay ive been needing this actionscript. thanx :p
May 9th, 2006 at 4:21 pm
Hi David,
That was elegant. Only problem I can’t get video - only audio to show up. Working with Flash MX 2004 on a Mac. Any suggestions?
thanks in advance
andrew
May 11th, 2006 at 7:28 pm
Andrew,
I was successful with this approach in both Flash MX 2004 and 8. Granted, I only have Flash for PC. Are you publishing for Flash Player 6 or higher?
May 31st, 2006 at 2:40 pm
I’ve been working with Captionate to include closed captioning with my Flash Videos. This has required me to load an external FLV using AS. All this works fine, the captions appear and they are synched with the video but I’m having trouble incorporating a Video Controller. Since my videos load after viewer presses “launch video” and then play automatically, I’d like the video to loop back to the beginning and then stop at the opening scene as it would using the FLV Playback Component. Can you show example of Actionscript that will meet my requirements of having a Playback Control with an external video, or direct me to information that can help. I have about 50 videos to caption, so I’d appreciate any help you can give. If you email me directly I can provide my source files. Thanks!!!!! - Diane
June 1st, 2006 at 10:11 am
Diane,
The FLVPlayback Component is even easier to use than the approach described in the above article. If you don’t mind the overhead of this Component — which, at 33KB, isn’t as bad as the older Components (some would argue isn’t bad at all) — and if you don’t mind publishing for Flash Player 8 or higher, just drag an instance of the FLVPlayback Component to the Stage, select the Parameters tab in the Property inspector, and set the contentPath parameter to a path reference to your FLV.
You can handle this via ActionScript by giving your Component instance an instance name, then using that to invoke the contentPath property of the object.
June 23rd, 2006 at 4:44 pm
Hello,
I was wondering how to get FLVPlayback component working with NetConnection and NetStream?
June 23rd, 2006 at 11:24 pm
Andy,
Actually, FLVPlayback takes care of all that for you. See my reply to Diane, above … all you need to do is set the contentPath parameter of that Component. Unless maybe I misunderstood your question?
June 26th, 2006 at 9:00 am
Hello David,
Thanks for your reply. I’m sorry I should have added some detail:
What isn’t clear to me in the F8 language reference regarding NetConnect, NetStream and the FLVPlayBack component is whether setting contentPath for FLVPlayBack is enough to ensure that my .flv video is being streamed to the the component. Or is there some undocumented Actionscript to connect a NetConnect and NetStream instance to FLVPlayBack? Is streaming even possible in the scenario or is it simply progressive download unless the URL I provide in contentPath is from a streaming URL via Flash Media Server?
Thanks again,
June 28th, 2006 at 11:36 am
Hey, Andy,
Yeah, FLVPlayback handles the simulated streaming. That’s one of the benefits of using Components: they’re designed to do the heavy lifting for you. In your case, just set the
contentPathparameter, either via the Property inspector or ActionScript. While this will only give you progressive download — unless you’re using Flash Media Server — it really does feel like streaming to the end user.
Keep in mind, of course, FLVPlayback requires that you publish for Flash Player 8 or higher. And it’s only available in the Pro version of Flash, while the approach discussed above can be done in Flash Basic.
June 29th, 2006 at 6:55 am
David,
We have Flash Pro 8 and we are running a .FLV movie. Using the FLVPlayBack we set the contentPath to filename.flv. Also, reading the above post with Andy and Diane we removed the AS code that you described in this article. But the problem we have is viewers are complaining that our video is “choppy” - meaning it starts and stops. As a side note - We are hosting this on a shared server. What are we doing wrong?
Thanks
June 29th, 2006 at 8:27 am
Gary,
There are several factors that determine the smoothness of a video’s playback, including overall size (its dimensions), bitrate and sample rate (of both the video and audio streams), number of channels (mono or stereo), compression, number of keyframes — even the visual characteristics of the content itself (lots of motion versus very little). Add network traffic to the mix, and there you have it … converting video for web use is as complex a discipline as anything else.
You may not be doing anything wrong. You should consider the above facets, though, and experiment with reducing the dimensions, reducing the bitrate, etc., until you produce something as small as reasonably possible, without an unacceptable loss in visual quality. It’s the same balance you must strike with, say, JPGs — but a greater number of properties to fiddle with.
July 1st, 2006 at 9:52 am
I am trying to make a button, and use it to load an external .flv into the FLVPlayback - Player 8 component.
I am not all that professional with flash yet.
Would love to be able to load it from xml file.
If you have an idea, or the knowledge, please post, and please include an example .fla and .xml if possible in zip or rar format as it may save tons of conversation as I have already stated, I am no Flash guru. The reason I need to learn this is I find I have a need to be able to create a .flv player that the clients can pick from many .flv movies to play the one desired. JustKaz
July 1st, 2006 at 7:37 pm
JustKaz,
I’ve got to chuckle. This article is geared away from the FLVPlayback Component, but all the recent comments are geared toward it. Maybe I should write an entry about FLVPlayBack.
What you’re after is certainly doable, but it really merits a tutorial to itself. I see at least four sub-goals, here: a) loading XML into Flash; b) using the loaded XML’s data in ActionScript; c) loading an external FLV into the FLVPlaybackComponent, which has been covered in other comments here; and d) doing the above at the behest of a button, which is probably the easiest part.
I’ve been asked to write an article or two on XML in Flash, and the topic is definitely on my list. In the mean time, here’s a good start.
Remember, big things are made up of lots of little things. Don’t try to swallow the elephant all at once.
Of course, one extremely simple solution — thinking outside the box, here — is to choose a particular name for the external FLV and hard code that … then tell your clients to rename their FLVs, in turn, to that name.
July 5th, 2006 at 2:49 pm
Hi David,
Thank you for your reply. I understand that the article was geared away from FLVPlayback but it seems so silly that there is not simple AS to connect FLVPlayback to a “real” stream, not progressive download.
Is there a way to connect MEdiaDisplay or FLVplayback to a stream using NetConnect and NetStream?
Thanks again,
Andy
July 6th, 2006 at 2:02 pm
Andy,
I may not have been clear on this — apologies, if not
— but to be explicit, true streaming cannot occur without Flash Media Server (or some other media streaming server software, if such a 3rd party solution exists for Flash). Once the server software is installed and configured, the ActionScript hookup is as easy as it was before: simply point it at the stream, rather than a file.
July 21st, 2006 at 9:41 am
David, I’ve spent a whole day try to figure it out and you made it seem so simple! Thanks.
My question is, how can i get flash to loop my flv video?
I’m using Flash 8
Thanks,
Brandon
July 21st, 2006 at 9:32 pm
Brandon,
Check out my reply to Mark’s comment (April 16, 2006). Using either the
MovieClip.onEnterFrameor
NetStream.onStatusapproach, you could call the
NetStream.play()method again when the video finishes. Does that make sense?
This FLV entry is one of my most popular articles, so I should probably write a follow up or two. Write back if this doesn’t answer your question.
July 25th, 2006 at 1:25 am
Hi David,
thanks for the info that u have shared . I have a doubt regarding the progressive streaming could you give a snippet explaining the progressive streaming.
July 25th, 2006 at 10:15 am
maharaja,
I’m afraid I don’t understand your question. There are two concepts in discussion so far: streaming and progressive download. Streaming requires server software; progressive download does not. What sort of snippet are you looking for?
July 26th, 2006 at 12:42 am
i want example in which it uses progressive streaming
i tried the following code:
//**** the code is in Flash 8
nc = new NetConnection();
nc.connect(null);
ns = new NetStream();
my_video.attachVideo(ns);
ns.bufferTime(0);
ns.play(”test.flv”);
//****
but according to my understanding the slider should not be accessible till video is completely loaded but in this case i can play with slider as soon i play the swf… may be i think that size of file is small so that it might be loading quickly . size of test.flv is approx 7 MB would u please put some light thanks in advance
July 26th, 2006 at 9:10 am
maharaja,
This article addresses the display of video without the use of Components — with a Video object only (and some ActionScript) — so I’m not sure what you mean by “slider”. Are you talking about one of the Media Components, or FLVPlayback?
July 27th, 2006 at 9:22 am
David,
thanks for making this information so readily available…it’s brought me much closer to understanding how to achieve what I’m trying to do…I’ve still got one more question though…
So I’m stumped on where I should locate my .flv file in relation to the final .swf that targets it. Does it matter? should I include the full path in my “ns.play(”externalVideo.flv”);” line? Do I have to upload my videos to the web first to test it out, etc etc etc.
thanks for your time!
July 27th, 2006 at 4:22 pm
Hi David,
Thanks for the article… it solved about 1/2 of my problem. I have about 30 flash videos, but want to make a single swf player, and just send the particular video filename to play directly to the swf player. No problem there, it’s working with your script. But, now I don’t have a way to control that video. I’m using Flash MX 2004 on a mac, so I can only publish to flashplayer7.
I know this isn’t the point of your article here, but I was hoping you could help. I’ve tried dragging the MediaPlayback component over and hooking it up to the video, but it doesn’t work. Any suggestions?
Thanks!
Dan
July 28th, 2006 at 3:20 pm
Thanks for your help….I’m not quite sure i understood what you meant (sorry, i’m new to flash and am not familiar with ActionScripting).
I entered the code to monitor the movie and then replaced the ‘trace’ with the NetStream.play() method you mentioned. It didn’t work…but that may not have been what you meant. Here is what my code looks like right now.
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
videoPlayer.attachVideo(ns);
ns.play(”772-2_l.flv”);
this.onEnterFrame = function() {
if (videoPlayer.time >= 20) {
ns.play(”772-2_l.flv”);
delete this.onEnterFrame;
}
}
July 28th, 2006 at 4:40 pm
Three replies to the previous three questions.
Eric,
The location of the FLV, SWF, and HTML document are all significant, especially if you’re using relative paths, as demonstrated above. If you’re using absolute paths, then yes, you’ll have to upload your FLVs to the server in order to test — because that’s there the absolute path points. There is a way around that, so take a look at (Perhaps) Unexpected Point of View: SWF Defers to HTML for a more detailed explanation.
Dan,
For that, if I understand you correctly, you’ll have to set up your path, as referenced in the line as a variable, then feed that variable to your SWF from the outside. There are two basic ways to handle this passing-in of variables: 1) append a query string to the SWF reference in your object param and embed elements, and 2) use FlashVars. From a practical standpoint, both approaches amount to the same thing.
Again, if I understand you, you want a single SWF to be able to load 30 different FLVs, and you want to be able to externally instruct the SWF which FLV to load. Did I hear you right?
Brandon,
You did fine — this was my mistake (thanks for catching it!). It’s not the
Videoclass that provides a time property, but rather, the
NetStreamclass. I amended my reply to Mark with correct ActionScript. In your code, the only thing that needs to change is the reference to
videoPlayer.time: change that to
ns.time. Make sense?
July 31st, 2006 at 12:39 am
hi David,
Iam using Flash 8 proffessional version.and not god in actionscript.. just began in it..iam doing a website now..In the website i have used a Mediaplayback component to play a flv..(not a flvplayback component).
flv file is loading from a folder..I uploaded the website..but the flv file playing by step by step..i meant loading little bit then playing..loading then playing..
i want to load it fully first then have to play smoothly.. iam also want to show a loading message in the time of loading..just like “loading…”
i tried a code ——-
onClipEvent(enterFrame){
_root.mymedia.autoPlay = false;
}
—–then it loading first but does’nt play automatically..i need to press play button
this webpage for a portfolio for a company..First impression is the best impression right?:) ..When a customer is opening this page they will not see a jerking video..If iam showing a “loading…” message, they will wait to see and it will play smoothly..
what is the soluiotn David?
Thanks
July 31st, 2006 at 2:32 pm
lijo,
Preloading a video is not unlike preloading a SWF or JPG. Because you’re using one of the Media Components, your first stop should be the
Mediaclass entry in the Components Language Reference. Note the
Media.bytesLoadedand
Media.bytesTotalproperties under the Properties summary. Those properties will give you comparable information to the
MovieClip.getBytesLoaded()and
MovieClip.getBytesTotal()methods described in How to Tell When an External SWF has Fully Loaded.
August 27th, 2006 at 10:48 am
Hello, I just get the audio, no video.
What can I be doing wrong?
This is what I got:
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
FLVPlayback.attachVideo(ns);
ns.play(”2.flv”);
I’m using a PC with Flash Professional 8.0.
August 27th, 2006 at 2:36 pm
Btw, everything works when I put a value for contentPath in the “Component Inspector” but I need to be able to change the content dynamicly. I’m going to have one player that can open different files depending on what data it receives (ex:). But I can’t get it to work when we have to set the contentPath value in a actionscript.
August 27th, 2006 at 4:14 pm
Markus,
I’m confused by your example code. The
attachVideo()method is defined by the
Videoclass, but you seem to be invoking it as a static method of the
FLVPlaybackclass. According to the documentation, the FLVPlayback Component “wraps” a
VideoPlayerinstance — so I wonder if you’re somewhat “mixing metaphors,” here.
If you want to use a FLVPlayback Component instance, all you have to do is give that Component an instance name and use the instance name to reference its
contentPathproperty. You don’t need any of that
NetConnectionor
NetStreambusiness.
On the other hand, if you want to forego the Component — which is the focus of this article — you use the ActionScript I show at the very top along with a Video object.
August 28th, 2006 at 3:24 am
Very good for learning purpose.
August 28th, 2006 at 7:01 am
Ah, yes I got it now. Thanks alot mate!
Hadn’t quite understood how all this worked, but its running smoothly now!
Thanks alot for your time David! Well appriciated!
August 28th, 2006 at 7:36 am
Glad to hear it, Markus!
Enjoy.
August 28th, 2006 at 8:00 am
hemanshu,
Thanks!
August 28th, 2006 at 8:46 am
Hi agian!
When I load a new .flv-file with
videoPlayer.contentPath = _root.id + “.flv”;
my navigationbar won’t show up. This worked fine when I had a value for contentPath written in the Component Inspector, but not now when I load a contentPath with the actionscript. Have you any idea if I need to reload the navigationbar or something like that after I have loaded a (new) contentPath.
(My goal is to have a player that can load several different .flv-files. opens 1.flv from the same dir. That works fine now, but when I do it like this, the navigationbar won’t show up anymore.)
Don’t know if it’s called navigationbar but couldn’t find any name for it.(The bar with the timeline and volume etc.)
August 28th, 2006 at 9:24 am
Markus,
I’m guessing you haven’t provided the skin in the Component Inspector. You can use both approaches, by the way: select the skin in the Component Inspector and set the
contentPathvia ActionScript. Or set both via ActionScript. Look up the
FLVPlaybackclass in the Components Language Reference to see what all your choices are. Components are objects, just like anything else, and their classes follow suit, as described in my Objects: Your ActionScript Building Blocks article.
September 1st, 2006 at 11:21 am
David, thanks so much for this code. I’ve read this whole thread and can’t seem to find what I need to modify… I am trying to use FlashVars so I can use one swf to play several different flv files. I have my embed and param tags set up correctly but I can’t figure outy what I need to put into your code…
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
videoPlayer.attachVideo(ns);
ns.play(”externalVideo.flv”);
I tried changing it to this:
ns.play(”openmediaPath”);
openmediaPath is my variable I define in the html. Am I using the wrong syntax?
September 1st, 2006 at 12:35 pm
Ryan,
You’re allllmost there! Notice that your
openmediaPathreference — which I assume is the variable you’re passing in via FlashVars — is quoted. Those quotes are killing it. You want to reference the value of
openmediaPath, not the string “openmediaPath.” Get it?
September 19th, 2006 at 2:22 pm
Hi Dave.
It looks like you have been very helpful to a lot of people, I think that is very cool. I hope that you can help me as well…
My issue seems to be strictly with absolute vs. relative paths.
When I use your code in my FLA and preview it in my browser it works like a charm. However, if I try to just view the SWF by itself OR even create an EXE, it doesnt work.
BUT, if I use an absolute URL to the FLV then it works in all scenarios. The problem is I am developing something to be deployed on CD-Rom. I will not be able to use an absolute path (nor do I think I should have to) to the FLV.
Any help is greatly appreciated…. TJ
September 19th, 2006 at 2:38 pm
TJ,
We’ll have to do a bit of troubleshooting, here. I pasted the exact code in my article into a new FLA with an external FLV in the same folder as the published SWF. Worked fine. Then I published a Windows EXE into the same folder and it continued to work. What version of the Flash Player are you publishing to? Have you tried this with another FLV?
September 19th, 2006 at 2:52 pm
WOW! Thanks so much for the quick response.
I just completed some more testing myself and noticed something…
Originally I was using Flash Pro 8, and publishing to Player 8. I noticed the security settings in the publish settings tab about local vs. network access and neither of them seemed to improve the outcome.
HOWEVER, I tried the same code with the same FLV using Flash MX2004 Pro, and publishing to Player 7 and it worked (almost). It found my FLV but only played audio… not video. I recreated my FLV using Flash MX2004 and it worked. I assume this was a codec issue with my original ver8 FLV.
The fact that I can get what I need with 7 is going to work with my current situation. But, I am definitely interested in trying to figure out what is going wrong with 8. I have tried a couple of different FLV’s and I also tried diff AS code (using the sample code from Flash 8 ). Again, it is always the same problem… preview in browser - no problem. SWF by itself or as EXE, it cannot find the FLV?
I really appreciate your assistance. Please let me know if there is anything else you need from me to help figure this bad boy out.
September 19th, 2006 at 7:30 pm
TJ,
That’s luck of the draw, I’m afraid. Sometimes I get overwhelmed with other things — but I’m glad I was able to respond quickly this time, too.
I’m interested in your problem, because none of this rings a bell with me. I didn’t have this issue in Flash MX 2004 and haven’t had it in Flash 8. I’ll try to help you if I can, but I need a bit more detail: are you on Mac or Windows? Write me offline — my last name @ quip.net — and I’ll take a look at your code. I’m on WinXP.
September 21st, 2006 at 6:25 pm
Note: For anyone following along, I took a look at TJ’s files. They work just fine on my machine, so TJ and I are baffled. This seems to indicate there’s something wrong specifically with TJ’s computer, security settings, Flash preferences, or some other TJ-only circumstance.
September 28th, 2006 at 4:37 am
Hi David,
Nice work!
I really appriciate what you are doing not only with flash but with helping ppl.
Now even im stuck up at one thing. I hope you can help me with this.
Im trying to buid a flv player which will pick movie file at runtime( like most ppl are doing) im using FlashVars its working good, but the trouble is that i want the seek bar to be able to point to prev sections and play from an earlier location ( something like youtube ).In my instance the slider doesnt appear unless the movie is completely played once. Im plainng to upload movies upto 30 mins duration and it would be difficult then. So do u have any ideas of how to make this work?
September 28th, 2006 at 10:30 am
Danish,
Thanks.
The trouble with what you hope to accomplish is that it isn’t possible to seek to sections of the video that haven’t yet loaded — unless you’re streaming the FLV from something like Flash Media Server. In my experience, the slider appears as soon as enough data have loaded … the FLVPlayback Component indicates load progress right in the slider, and it is indeed possible to seek among loaded frames. Are you using the FLVPlayback Component?
September 29th, 2006 at 2:35 am
Is it possible to load a FLV via nc.play(”file”) to a flvplayback component? I ask because there are methods i can use, such as seekToNavCuePoint with the component, whereas I can’t with NetStream. There’s more pros and cons as well. Any ideas?
September 29th, 2006 at 3:54 am
Hey David,
thanks for the help. it works, it was my mistake i wasnt putting the slider compnent correctly. but it works good now.
Although i was trying to compare the playback with you tube and was trying to find the best combination of bitrate and fps for encoding to flv, mine was always jerky. Then i ripped a video off you tube itself and tried to play that on my flvplayer and it was a lot better. The only thing is that it looks lower in quality (like antialiasing is turned on you tube and its off in mine). So this leads to anothr set of questions,
- What should be the optimal conversion parameters that the video plays decent enough?
- How is it possible that same file playes smooth on youtube’s player and looks grainey on my player?
- What possiblities does meta header hold, can this be credited to meta headers?
I know this is out of the topic … i can mail u if u want to discuss this outside..
Thanks again and keep up the good work.
October 3rd, 2006 at 2:18 pm
Wayne,
If you’re using the FLVPlayback Component, you can ignore the
FLVPlayback uses those classes along with additional code to handle the basics for you. That’s definitely one of the many benefits of using the Component, if you don’t mind the larger SWF file size and the requirement to publish to Flash 8 or higher. Just set the
NetStream/
NetConnectioncombo.
contentPathproperty of your FLVPlayback instance (via the Component Inspector or ActionScript) and you’re set.
October 3rd, 2006 at 2:22 pm
Danish,
Glad you got it working!
Consider this article at Community MX, by Tom Green and Scott Fegette (free content):
FLV Datarate and Bandwidth… Demystified
You may also want to look at Scott’s Breeze seminar at the Adobe Developer Center:
Producing Video for Web
Between the two of those, you should find lots of useful information, even if it doesn’t answer every one of your questions.
October 13th, 2006 at 5:31 am
Thanks for the lines of actionscript sure does load quick.
I wonder how I can add the play, pause, stop buttons etc….
along with this actionscript.
Thanks Again
Enrique
October 13th, 2006 at 8:42 am
Enrique,
You’ll be glad to hear that your goal isn’t hard at all. In fact, that would make a great follow up to this article — so I’ll write about that in the next few days.
For now, take a look at the
NetStreamclass. In the example code, the variable
nsrefers to a
NetStreaminstance. Methods are things an object can do (such as play), and you’re already using the
NetStream.play()method. Check out the methods summary for this class in the ActionScript 2.0 Language Reference and you’ll see others useful to your goal. But again, I’ll write about this in an actual post very soon.
October 13th, 2006 at 3:08 pm
Hi David,
You were so kind to reply to me back in April. Just wanted to let you know it was a MIME type issue of the FLV type not being recognized. Thanks a lot.
Thinking aloud, I guess I could do a URL-encoded variable in a link to load different FLV files with the one container swf, yes?
This would allow me to have a simple page with one SWF (video container) and a page of HTML links with a variable in the link such as 300monks.com/?video=artist1.flv
best
andrew
October 14th, 2006 at 7:12 pm
Andrew,
Ahh, those MIME types! Glad you resolved your issue.
You could certainly use a name/value pair to send information to the SWF. See this article for one example. Your suggestion is a bit different, in that your information is passed to the HTML document, rather than to the SWF itself. You’d need to use JavaScript to grab that query from the address, then pass it in via FlashVars, but it amounts to the same thing. Have fun with it!
October 23rd, 2006 at 4:50 am
hi david
thanks for a concise tute. clean and fun.
one question: can cue points with buttons to call those points be set using the video object with ns?
i know it’s a breeze with the FLVPlayback component and associated playback behaviors extension… but can it just as easily be built into your example with actionscript?
the reason i ask is i’m using a custom-built player with a certain shape/look… so using the FLVPlayback component isn’t an option…
-unless i’m mistaken & one can infact use the FLVPlayback component with custom buttons (& i don’t mean simple skinning
thanks!
s
October 23rd, 2006 at 11:54 am
sank,
I think you’re asking what Enrique did, recently. Have you checked out this articles companion piece, “How to Control Video (FLV) without a Component“? I think that gives you what you’re after.
The FLVPlayback Component has an API, just like the
NetStreamclass, so you can, in fact, manipulate it independently from its built-in controls. Just check out the
FLVPlaybackclass in the Components Language Reference and note the available methods (things it can [be told to] do) and events (things it can react to). But my hunch is that you’ll actually want to manipulate the
NetStreaminstance instead.
November 1st, 2006 at 1:01 pm
Hi,
I am trying to find/code an interface like MediaPlayback (with the buttons and the bar etc.) to play a .swf movie clip. I don’t have .flv files but a bunch of
.swf movie clips and I am trying to have a nice interface to play them in.
Everything I searched and found so far is about playing .flv files
Any ideas/pointers will be highly appreciated.
Thanks!
Esra…
November 2nd, 2006 at 9:50 am
Esra,
I like your idea, but consider this: FLVs are linear … they have a starting frame and a final frame, and the idea is to move from the beginning straight to the end. SWFs can be linear, but many (perhaps most?) aren’t. SWFs, for example, have nested clips with their own independent timelines. SWFs may jump from a later frame to an earlier one, or pause while ActionScript handles a bit of animations — or the entire SWF might be animated by ActionScript. So how should a MediaPlayback-like interface work?
November 2nd, 2006 at 9:27 pm
Hi,
I have installed fms2 in my local pc and sucessfully stream the flv .
Now my problem is I do not able to create seek bar .
I load the flv like given [videoPlayer.attachVideo(ns);]
How to create a seek bar ? Any suggestion ?
November 10th, 2006 at 2:09 pm
Hello dave, i have a question. Im developing a video player in flash, but what i want is that when it’s open, it doesn’t download til the user clicks the play button. Is this posible??
Best regards
Daniel
November 12th, 2006 at 3:04 am
David,
Is it possible to use cuePoints when playing my FLV without a MediaPlayer or FLVPlayback component?
If so, can go give a little AS hint?
Thanks
November 13th, 2006 at 8:39 am
Replying to the last three …
Jack,
I have very little experience personally with Flash Media Server, so I’m afraid I don’t have a ready answer off the top of my head. A seek bar, conceptually, can be compared with a preloader bar. What you need are two values: the total duration of the video, and the current location of the video (that is, how far into the file the video has played). I believe FMS does provide total duration (progressive download does not — you’d have to supply the value yourself, as even the FLVPlayback Component requires). The
It’s on my list.
NetStreamclass does provide a
timeproperty. Running these two numbers against each other gives you a ratio that you could then use to position a “handle” movie clip against a “track” movie clip. Not a bad idea for an article on this blog, actually.
Daniel,
When you say “the play button” (emphasis mine), I wonder if you’re using something like the FLVPlayback Component, which has a built-in play button. If so, you’d have to do a bit of fancy programming to override some of the FLVPlayback’s default behavior. If you’re using the bare-bones approach described in the blog article above, you could assign the
ns.play("externalVideo.flv");to the Button.onRelease event handler of a button — that would do it.
The Freaking Dutchman,
It should indeed be possible to roll your own cue points.
Given the
NetStream.timeproperty, comparable to the
Sound.position, you might experiment with the same approach outlined in my recent Cue Points for Audio Files article on the Adobe Developer Center.
November 13th, 2006 at 11:57 pm
David,
I’m new to the actionscripting in video…after reading all the article posted here… i had tried them and it work fine to me, just that there is one more thing i can’t get it… how to load different flv into the same swf file?
Can it be done using like,say, after the first flv, go to next frame? please guide me a little.
Thanks
November 14th, 2006 at 12:58 am
David,
sorry to post two time…just to tell that i came out a solution already. here is what i have done. to me it’s work fine. If anything that can be improve pls correct me:
but now facing a problem… how to make the flv played according to vertical center…because all the movie not in the same size and also my video object…anyone can do it please guide me…thx
November 14th, 2006 at 8:41 am
Jeff,
That fact that you’ve come this far on your own should be an encouragement.
I’m not exactly sure what you’re after, but it looks like you’ve got a good start. The
NetStream.Play.Stopmessage appears when playback has stopped. You should do some experimenting to determine if this only happens when the file has reached its end (the video is over) or if it also happens when network congestion causes the video to temporarily pause while buffering. You only provided instruction for one of your two
casestatements, which means the resizing will occur both for the
NetStream.Play.Startand the
NetStream.Play.Fullmessages — not sure if that’s what you want, but it might be. If you’re resizing like this, I don’t see why you’d need to vertically center. Can you explain?
November 14th, 2006 at 11:42 pm
well appearently i was making a fullscreen flash that run different movie sizes(example 1024×819, 1024×780)… well i got no problem with x size since all are in 1024…but because of y size not the same, i can’t make a “set” size for the video object…that’s why i was hoping to see if there is a way to make it play in the center(because my video object is 1024×768)
Anyway after i dig more into the tutorial while you are not around(since we are in a different half of the world)… i somehow found a solution to it…(and this previous script i posted seems to have some problem too)…
I have placed the files in
movie01.fla & movie.swf - the flash files(place flv named 01-05 will make
the swf work.
netstream.zip - flash files with sample flv included
the swf created can actually play the flv and when it finished it move to nextframe which another movie is loaded…
And if they can’t find the file, they will go back to first one(still haven’t think of how to make them skip to next frame instate of going back to beginning)…anything can be simplified pls tell
Anyway, thanks for guiding me.
…and sorry for a long post…
November 16th, 2006 at 2:07 pm
Jeff,
No worries about a long post. Sometimes my replies are pretty long.
You should be able to adjust the position of the Video object itself by adjusting its
_xand
_yproperties. Generally speaking, the way to center something is to take the width (or height) of the parent object, divide that by 2, then subtract the width (or height) of the desired object, also divided by two.
e.g.
When you say this …
… I don’t know if you mean video frames or movie clip timeline frames. If you mean timeline frames, just invoke the
MovieClip.gotoAndPlay()method (or
gotoAndStop(), etc.).
November 16th, 2006 at 5:14 pm
Hello! and thanks.
I’m building a custom class in as 2.0 that does a few things, and one of them is to set the contentPath of an existing FLVPlayer component instance. If I’m loading a movieClip, it’s easy to declare a MC variable in a method in my class file, then refer to it in my flash movie, but I’m baffled on how to refer to or type a var for the FLVPlayer component instance in my class file. I don’t really have to do it this way, but would like to know how!
November 16th, 2006 at 5:20 pm
zignorp,
How are you writing your class file? Are you extending the
MovieClipclass? If so, then your reference to the movie clip would be this — which is easy, as you’ve described. If not, then your reference to a movie clip would simply be its instance name, presumably passed into your class instance via the constructor or some other method (just as easy). In like fashion, you could either extend the
FLVPlaybackclass or reference its instance name in the same way (this approach is called composition). Have you tried that? I’m not sure where you’re getting stuck.
November 16th, 2006 at 9:41 pm
David,
thanks for the example you gave…I applied on it and it work just as i wanted now…
about this:
still haven’t think of how to make them skip to next frame instate of
going back to beginning
what i mean here is,like, if my timeline 4 frame. each of them have one different flv played(example 01.flv,02.flv,03.flv,04.flv)
lets say i forgot to put in 02.flv but i got 03 and 04, if i told flash to gotoAndPlay(1) if no flv of this name is detected(02.flv) …then they will skipped all the flv at the back(03.flv, 04.flv)and go back to frame 1.
i wonder if i wrote the script like, on the middle frame(frame 2, 3)
and putting this in the end of timeline
hope you know what i’m saying…
November 16th, 2006 at 10:00 pm
Jeff,
Aha, now I see what you’re doing. Well, honestly … I don’t see much benefit in using timeline frames to load your videos. That adds unnecessary complexity, don’t you think? Why not just use
NetStream.play()on your existing
mynsobject to load another FLV when the first one finishes? That’s the great thing about these objects: you only have to instantiate them once — after that, just keep using the same objects. Does that make sense?
November 17th, 2006 at 12:56 am
well i do try that at the first place…using one frame is that what you mean… some how that time i can’t get the things work well…i will try to give it another try…again thanks for guiding
November 17th, 2006 at 1:54 pm
Thanks David!
I am accessing my target movie clip through a method, which I’ll paste below.
I’m not sure what type to assign to the FLVplayer object, would this be a MovieClip as well?
function loadFilm(filmName:String, targetMC:MovieClip, filmID:Number, smFlv:String) {
smFlv = “flv320/”+filmName+”.flv”;
descSWF = “swfs/”+ filmName+”.swf”;
//playerFLV.contentPath=smFlv;
targetMC.unloadMovie();
targetMC.loadMovie(descSWF);
}
November 17th, 2006 at 2:33 pm
I just got it to work by extending the MC class AND adding it as a parameter of the function. I’m not sure why I had to do both, as the other target MC was working fine, but thanks for your help and education!
November 20th, 2006 at 9:29 am
To Jeff …
You got it. One frame is all you need. If that
NetStream.Play.Stopmessage is correctly indicating the conclusion of a video — and you’ll really have to experiment to determine that — then you can simply invoke
NetStream.play()against the
nsinstance. With your approach, you’re essentially doing the same thing, except you’re completely re-instantiating that
nsobject, along with the
NetConnectioninstance.
To zignorp …
Glad you got it! I, too, am surprised that you had to do both, but hey … it’s working.
November 21st, 2006 at 2:02 pm
i love you, i’ve been looke everywhere for a stright foward solution to play flv’s without components, i thought i would never find anything. thanks for the help man it was much needed.
November 27th, 2006 at 8:55 am
Aaron,
Glad to hear it! Thanks!
December 1st, 2006 at 2:58?
December 2nd, 2006 at 7:40 am
Chris,
My hunch has that you’re experiencing the phenomenon described here:
(Perhaps) Unexpected Point of View: SWF Defers to HTML
Unexpected “Gotcha” with Relative Paths in ActionScript
Make sure to read both.
December 11th, 2006 at 10:41 am
I’m using Flash 8 Pro and am new to video. I’d like my video to stream and play and at the end of the stream, I would like to go to a labeled frame in my animation and proceed.
I am doing that now with the timeline but that’s not working well.
Any help would be appreciated.
December 11th, 2006 at 3:02 pm
Just figured it out from your sample at top:
stop();
// Load the video
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
videoPlayer.attachVideo(ns);
ns.play(”videoname.flv”);
// Monitor the video
this.onEnterFrame = function() {
if (ns.time >= 30) {
gotoAndPlay(2);
;
delete this.onEnterFrame;
}
}
Thanks!
December 11th, 2006 at 3:11 pm
Joe,
Good for you!
I was going to direct you among those earlier comments for starters. I’ll probably write an actual article on the topic before too long, but in the mean time, way to go!
December 13th, 2006 at 6:36 am
hello ,
is it possible to load .mpeg,.avi,.mp3 as we are loading .flv through net stream.
and also i need the actionscript to find the format in perticular foder and then load in videoplayer. i mean can we write the code like if, else, condition to load differ formats which are avail in the folder.
Advance thanks
Anjan
December 13th, 2006 at 10:33 am
Anjan,
Flash loads more file types than ever, including JPG, GIF, PNG, MP3, XML, CSS, TXT, and probably a few more — but the only video format it supports is FLV. That said, I see you did ask about MP3. The older Media Components support MP3, but they don’t use the
NetStream class, as far as I know.
December 13th, 2006 at 10:49 pm
Hey David, I want to compliment you on how well written and helpfull your website is. I especially enjoyed the article on catching fruit flys - if you have any similiar techniques for women - please let me know.
My flash problem is that I designed a flash website for my friend incorporating his video demos. I imported the files into .flv format, compressing them as much as I could.
I then inserted the videos into movie symbols - so that the movie will play on the frame when accessed. Everything works fine on my computer. However online they do not load. The box does not even appear.
- I checked the relative path article, however this doesn’t seem to be the problem in my case. The files are all located at
[bunch of URLs]
The “Loading” doesn’t actually work - I tried copy and pasting the code you had for the media.
“stop();
// Load the video
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
videoPlayer.attachVideo(ns);
ns.play(”PETERBdirectingREEL20072.flv”);
// Monitor the video
this.onEnterFrame = function() {
if (ns.time >= 30) {
gotoAndPlay(2);
;
delete this.onEnterFrame;
}
}
Unfortunately this only produces an error.
I am sorry I am not more knowledgable - I just graduated with a B.A., can’t find a job - so am trying to do webpages in the meantime. I hope that one day I can be in your position to mentor people like myself.
PS - this is the first USEFULL blog site I’ve come across - thanks again.
December 14th, 2006 at 3:48 am
Collin,
Haha! The latter doesn’t necessarily involve Saran Wrap with fork holes — at least, not in my experience.
This might actually be your problem, Collin. There’s nothing essentially wrong with embedding video content directly into a SWF’s movie clips, but doing so will definitely bulk up the SWF’s file size — and if you decide to go that route, then you don’t need the ActionScript from the above article; in fact, you wouldn’t need ActionScript at all.
The ActionScript above — with
NetConnection,
NetStream, and so on — is something you can use when your video is external to the SWF. You don’t need the FLVPlayback Component or any other Component (I’m wondering if that’s what you meant by “the box”?) … the ActionScript handles the FLV loading by way of a Video object, as described way at the top. If by “the box” you mean the Video object, then that would make sense, because unless video is playing in it, a Video object can’t be seen.
I think your best bet is to start with a fresh FLA file, free of anything but the bare essentials as described in the article. Make sure your Video object has the instance name
videoPlayer. Somewhere, you must have missed a step, so retrace your path and see if you can find where one of the footprints turns left at Albuquerque.
December 18th, 2006 at 5:18 pm
Hi Guys,
Why can’t we use a relative path to flv file in ns.play() command. It appears to me that flv files must be on the same level as SWF (e.g ns.play(”myvideo.flv”) works, but ns.play(”\myFlvFolder\myvideo.flv”) would not )
Any thoughts would be appreciated.
Lnguyen
December 18th, 2006 at 5:31 pm
Lnguyen,
Ah, you’ll be pleased to know that you can, indeed, use relative paths!
In fact, if you think about it, the example in the original article shows a relative path — no path at all is a relative reference. The syntax of the path needs to be the same as for HTML, so flip those backslashes the other direction …
/myFlvFolder/myvideo.flv.
Check out the “Unexpected Point of View” and “Gotcha” articles for important information on relative paths in ActionScript.
December 21st, 2006 at 4:25 pm
I’m using Flash 8 to use flv videos and interation that will be delivered on CDs. I’m using the FLVPlayer component to successfully play the video, but have not been able to get the embedded event cues to work. Can you help?
I tried using the code that was successful in MX2004, but it doesn’t work. Or I’m missing something. I’m in dire straights here. Please help.
Thanks in advance. I love you blogs. Great information.
Denise
December 21st, 2006 at 5:00 pm
Denise,
The FLVPlayback Component is new to Flash 8, so that may explain why your Flash MX 2004 code isn’t working. At its most basic, you’ll need something like this:
The variable
listeneris an arbitrarily named
Objectinstance. A
cuePointproperty is created for this object and assigned to a function literal. This function acts on behalf of the
FLVPlayback.cuePointevent and performs whatever you tell it to. Your FLVPlayback instance must “subscribe” the event to the listener, which occurs via the
addEventListener()method. The function receives a parameter arbitrarily referenced as
evt, and it’s that parameter that will contain the reference to your cue points via its own
infoproperty. So, for example, to trace cue point names …
December 22nd, 2006 at 3:52 pm
Hi David,
Great site, very helpful.
Quick pointer for those experiencing the “stuttering” or choppy playback / choppy audio when using the FLVPlayback component. SET your bufferTime property to something higher than the default 0.1s I set mine to 5 and that solved the problem. Technically this is only supposed to matter when you’re streaming and not doing progressive download, but I garuntee it makes the difference!
Now, the problem I’m having is a rather quirky one. I use the FLVPlayback component and feed the contentPath property dynamically using FlashVars. For some reason, on a few occasions when you load the video the seek bar scrubber, and the totalTime of the video fail to show up, but then if you reload it will appear again. The metadata is indeed properly encoded and as I said, it works sometimes (most times, but not others) It seems to me like the metadata info isn’t always loading, maybe the file playing before the metadata is populating the component is causing a problem? Anybody else run into this before?
Thanks! Great site.
January 1st, 2007 at 8:21 pm
Pooch,
I haven’t personally run into the problem you describe, so I can only take a wild stab at a solution. If you look up the
FLVPlaybackclass in the Components Language Reference, you’ll see that the class features an
FLVPlayback.setSize()method. All v2 UI Components feature this method (if memory serves me), but the others inherit it from another class —
FLVPlaybackstands apart in that regard.
Anyway, this method allows you to resize the Component via ActionScript, and it’s a very different sort of resizing than what would happen if you simply set the instance’s
MovieClip._widthand
_heightproperties (yup, the
MovieClipclass also features in the mix, here). When Components resize, they initiate what I’ll call a “trickle down” effect, because it the resizing is passed along to all the sub-Components inside the main one, including buttons, sliders, and the like.
So if you use ActionScript to set your FLVPlayback instance to its own current width and height, it might just shake loose the problem causing your occasional missing seekbar scrubber.
January 3rd, 2007 at 2:27 pm
I’ll give that a go and let you know what I find.
Thanks for the idea.
January 4th, 2007 at 1:59 am
I am using Flash 2004 for player 7. I am using MediaPlayback controller for playing FLV file. But there is some problem with seek bar. When i am scrubbing the seekbar and then play it’s not working fine. PLZ suggest me the correct way to use MediaPlayBack controller.
January 12th, 2007 at 2:33 pm
Hi guys,
I see there is a ton of help here on movie components but I am lost with this part of the actionscript needed for my project. I have a MediaPlayback component loading a .flv from a URL, My flash movie consists of 2 frames, the first one is a picture when clicked it takes it to the second frame which contains the component with the video, I just want to find out how I can tell the component to play frame 1 again when the video is done within it.
Thank you so much for your time,
I appreciate it,
Alex
January 17th, 2007 at 12:15 am
Hiya David - I’m working on an interactive trail map that utilizes an .flv file progressively downloaded in the first frame. I have set the actions in the first frame to:
stop();
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
FLVPlayback.attachVideo(ns);
ns.play(”wachugoog4.flv”);
this.onEnterFrame = function() {
if (ns.time >= 20) {
gotoAndPlay(2);
;
delete this.onEnterFrame;
}
}
due to the fact that the flv runs about 20 seconds; and at the very end, I’ve taken a screenshot of the final image, converted to movie, fade it out and transition to the actual trail map. Great in theory. It most often works, however, if you’re on a dial-up or simply have a weak signal, then your going to experience both choppiness AND it will go back to the first frame (beginning of .flv) which is of course, not what I want. How would you suggest preloading the .flv (without including playback controls) so it’s guaranteed to be fully loaded, runs through, fades out at end and is deleted.
Here’s the link to the current app to show you what I’m up to — any suggestions are greatly appreciated!!
Thanks again!! I look forward to hearing from you!!
Your site is bookmarked on my bookmark bar by the way
Best -
Senan
January 17th, 2007 at 10:13 am
To Alex …
The goal of being alerted to the end of a video clip is a popular one in comments on this blog, as well as a number of forums I frequent. The way(s) it can be approached depend on the object used. In this case, you’re talking about one of the older Media Components, so your best bet is to fire up the Components Language Reference and look for events of the
Mediaclass. You’ll find a
Media.completeevent, which is dispatched when, according to the docs, “the playhead reaches the end of the media.” Unfortunately, this wording is a bit unclear. By “playhead,” in this case, they’re talking about the seek bar (the slider) on an instance of
MediaPlaybackor
MediaController, rather than the timeline playhead. Make sure your Media Component instance has an instance name, than use that in place of the “myMedia” used in the sample code for that event.
Given the popularity of this topic, I intend to write a blog entry that steps through an example both for the older Media Components as well as the newer FLVPlayback Component.
To Senan …
I suggest you invoke the
NetStream.play()method, as you’ve done, then immediately invoke
NetStream.pause(). Even though the video stream is paused, the FLV will continue to load. At this point, you may check the
NetStream.bytesLoadedproperty against the
NetStream.bytesTotalproperty in a loop to see when loading has completed. When that occurs, quit your loop and invoke
NetStream.pause()a second time, which un-pauses the video.
January 17th, 2007 at 11:20 am
Edited to incorporate my reply …
Senan,
I’m glad to help.
It’s important, though, that these comment entries don’t become the equivalent of a forum-style Q/A session — mainly because it would be too hard for me to keep up with them! If you see errors in your code, it’s often best to take a step back, then add one new line at a time, building up new expressions as you go. Add a bit, test; add a bit more, test.
Dig through the previous comments — April, 2006, to Mark — and you’ll see a few suggestions on how to test for the end of the video when using the
NetConnection/
NetStreamapproach.
MovieClip.onEnterFrameis an event that belongs to the
MovieClipclass, which means it can be assigned to the main timeline, which is what
thisrefers to in this context. It’s really just a way to perform something repeatedly in ActionScript, which can be useful for checking loading values, for example. You could just as well use the
setInterval()function. The decision on when to use it and when to stop it (with
delete) depends on your needs. When you no longer need to perform an action continuously, it’s generally a good idea to stop.
The
stop()function works very similarly to how the
MovieClip.stop()method does. If you need to stop the timeline in which this code resides, you’ll need one of those two. Functions can be thought of as “free range” methods, in that they aren’t associated with a class (such as
MovieClip). Check out the entry for each in the ActionScript 2.0 Language Reference for complete details, but in this particular case, the function stands on its own, and the method requires an object reference, such as
this.
Careful! The
NetStream.pause()method doesn’t accept any string parameters, such as the quoted name of your FLV file (which is different, by the way, from the one specified in the
play()method). The only parameter it does accept is a Boolean. Here, too, the Components Language Reference is your best bet.
I’m snipping the rest of your code, because you’re including a progress bar, which isn’t entirely necessary here. Could be useful — and I know the Help docs show it — but anything new like this should be ventured into with “baby steps.” Master one concept at a time.
All you absolutely need so far is to play, then pause an FLV stream. Play a stream first, to make sure that works, then add the pause line to make sure your results change. Does the video still play? If so, something is wrong. Work out each step along the way. Does it pause? Good, next step: test the
NetStream.bytesLoadedproperty.
To do that, and to check for it repeatedly, you might use a
MovieClip.onEnterFrameevent. If so, then you may want to save your work, start a new FLA, and test just the enterFrame concept. Look up this event in the ActionScript 2.0 Language Reference, make sure you truly “get” what the event does — how to start it, how to stop it — before using it in conjunction with your existing video-related file.
When you’ve mastered looping on a frame, bring that code into your video FLA and use it to trace the value of that
NetStreaminstance’s
bytesLoadedproperty.
In this way, with small but sure steps, you’ll eventually get to what you’re after.
January 17th, 2007 at 11:55 am
To Ravi Sharma …
Woops, didn’t mean to skip your question, Ravi. Unfortunately, I don’t think your comment gives me enough information to give you a solid answer. In any case, this particular blog entry has generated so many questions about the Media and FLVPlayback Components, I can see that a handful of articles on those topics would probably come in handy.
January 17th, 2007 at 12:13 pm
David - I really want to thank you for your patient & generous insights. I can understand & appreciate the desire to maintain a non-forum-like use of this environment. You’re providing a valuable resource here!! Thanks again and I will be putting the bib back on and vow to ‘progressively’ learn to walk before I….Flash [video]. All the best.
Senan
January 18th, 2007 at 11:58 am
Senan,
You’re welcome, and thanks for the kind words!
January 23rd, 2007 at 8:44 am
hi david. i am displaying several flvs on webpage at once - about 4. im using the custom UI FlvPlayback component at the moment, as it allows for easy skinning etc. here is the url:
However, problem is that each flv progressively downloads in the background, causing heavy bandwidth problems and the browser often just gets stuck and overloads. do you know of any way, that while still using progressive download, the video could just load the first frame - as a thumb, but *not* download in the background - i.e. just wait until the play button is pressed (obviously there would be buffer issues, but i can handle that). any play method would do, not just the flvplayback component. it seems very odd.. that adobe dont seem to provide a method to halt background downloading.. im being forced to look at Flash Media Server as a way of getting around the problem. Any thoughts appreciated.
January 23rd, 2007 at 9:53 am
if i may continue - looking for example at the flvplayback api docs:
LiveDocs link
and this:
‘if video is over 1 minute, it should be streamed’. then it seems reasonable to conclude that adobe just dont really want to create progressive download tools in thier api.. as it will mean they cannot raise revenues by selling steaming software - i.e. FCS/FMS. there are plenty of ways that background downloading could be paused etc, or stopped to deal with bandwidth issues. the omission of such tools to me, seems *deliberate*.
humbug
January 24th, 2007 at 9:41 am
angurio,
It sounds like you’re frustrated — and that’s never fun, so I’m sorry to hear that — but on the bright side, you’re definitely not forced into purchasing Flash Media Server. True, it isn’t possible to natively halt background downloading in AS2, but if that’s the situation … work with what you’ve got.
If you can’t stop such downloads, the answer may be to refrain from starting a download until you need it.
The
FLVPlaybackclass, documented in the Components Language Reference, serves as your entry point in hos this component works. You may have to consult the
VideoPlayerclass too, but ultimately, you’ll find that you can leave the
contentPathproperty empty in the Component Inspector, then supply that value with ActionScript layer. It is possible to “hijack” the controller buttons and have the Play button perform a load as well as a play (rather than just a play).
And you’re not stuck with
If you use a Video object, as described in the original article, you can use your own buttons to come up with a user interface that behaves exactly how you want.
FLVPlayback, either.
I respectfully disagree. Flash has evolved by leaps and bounds with each new release. ActionScript 3.0 provides considerably more control of all aspects of a SWF, including video. I know in particular that it’s possible to halt a load for audio — again, in AS3 — which is an important improvement over the way AS2 handled audio files. I experimented with AS3 and video yet, but I have high hopes. Many of the quirks in Flash relate to legacy compatibility issues.
There are ways to halt a given download, I agree. One of the “tricks” in AS2 is to load a known, very small “dummy” file to “kill” the other download. There are workarounds, to be sure. But again, my first approach in this situation would be to leave the
contentPathproperty blank — which means nothing loads in the background — then figure out a way to set that property via the Component’s skin buttons.
January 25th, 2007 at 11:43 am
thanks david, very much! that was a great help. perhaps i will update here when ive sorted it all out.. so i can help other souls in a similar position.
thanks again.
January 31st, 2007 at 3:39 am
I am using the Flash 8 FLVPlayback and my a custom UI Seekbar from the components panel. Problem is that the seekbar is not disappearing when I set its visibility to false
mySeekBar._visible = false;
It seems that once the SeekBar instance has been associated with the FLVPlayback instance, it will remain on screen.
Basically my flash movie has 60 sections, some of which include a video. So I have the video components all set out on the stage and if there is no video for a particular section, I hide all the video components using the following code. I guess because I am only hiding and stopping the video, the seekbar still knows the video is lurking around. I do not know how else to get rid of the video. Possibly I can set the content path to empty but I got an error when I tried this.
my_FLVPlybk._visible = false;
my_FLVPlybk.stop();
play_btn._visible = false;
pause_btn._visible = false;
mySeekBar._visible = false;
Still, surely setting the visibility of the seekbar to false should hide it?
January 31st, 2007 at 4:43 pm
Hi David, thanks for your helps.
I’ve a problem.
I’m making an Interactive CD. For it, I’m using an executable SWF file from which I’m loading other external SWF files.
How can I put a FLV video in this case? I make ths question, because when I tried to put your code in a SWF file, the video doesn’t charge.
I hope that you can understand me because I’m not english-speaker.
Greetings,
Armando Picón
February 2nd, 2007 at 4:58 pm
To Steven …
The FLVPlayback Component — in fact, every Flash Component I can think of — extends the
MovieClipclass, so in theory, yes, you should be able to set the
MovieClip._visibleproperty of that seek bar to
false. I haven’t studied the
FLVPlaybackclass in exhaustive detail, so I can only make guesses at this point. It’s possible that, as you suspect, the class “knows” when video is present and when it isn’t, and overrides (or resets) the
_visibleproperty of that seek bar. I think your
contentPathidea is a good one, but you said you got an error. What error was that?
To Armando …
My initial hunch is that you’re simply supplying an incorrect path to your FLV file. If you can get your project to run successfully from your hard drive, you should be able to move all your files and folders as they are to the CD, and everything should still work.
I’ve run FLVs from a CD, so I know it’s possible. Don’t give up yet!
February 5th, 2007 at 11:16 am
Ok… I’m sure that “normally” works in a CD.
But, Will it works from an executable SWF that load other SWF in an empty movie clip?? Because, I’m trying with many diffent ways for write the path… and not work :’(
February 5th, 2007 at 11:21 am
… and if the problem is about “security policies” ???
February 6th, 2007 at 9:06 am
Armando,
I’m afraid I don’t know enough detail about your circumstances to answer with greater clarity. Flash Player security issues often get confusing, so I definitely recommend the official Adobe TechNotes there. At this point, you may want to do some trouble shooting — perhaps routing
NetStream.onStatusmessages to a dynamic text field so you can look for possible errors while the SWF runs inside the Projector.
February 7th, 2007 at 2:14 pm
hi david,
fantastic blog…thanks so much for the info.
i have used your code for setting up a video to play in a small banner. on my desktop it’s working perfectly. (i’ve also found a good way to solve the question of how to let the swf know when the video is done playing, which hopefully will be of service to you and your readers.)
the problem i’m having is that when i post it on the web, the video is not playing right away. as you can see from the code the video is supposed to begin when the invisible button is clicked…however, the browser is displaying an error message, and then about 10-15 seconds later the video begins to play. (there is intentionally no audio in this video.)
any thoughts as to why it would play correctly on the desktop but not on the web?
thanks so much for any help,
colin
here’s the code i used:
fscommand(”showmenu”, “false”);
var my_nc:NetConnection = new NetConnection();
my_nc.connect(null);
var my_ns:NetStream = new NetStream(my_nc);
videoBox.attachVideo(my_ns);
my_ns.setBufferTime(35);
my_ns.play(”gopher_small3.flv”);
my_ns.seek(0);
my_ns.pause();
my_ns.onStatus = function(info) {
if (info.code == “NetStream.Play.Stop”) {
my_ns.seek(0);
my_ns.pause();
_root.gotoAndPlay(”complete”);
}
};
btn_play.onRelease = function(){
my_ns.play(”gopher_small3.flv”);
mcPostit._visible = false;
_root.gotoAndStop(”play”);
};
stop();
here’s the file up on the web: (it should start when you click the yellow note…if you’re patient you’ll see it takes 10-15 seconds to begin rolling.)
February 7th, 2007 at 2:17 pm
hmmm,
now it seems to be working pretty well…maybe because it was cached for me. could it have to do with the buffer time?
(i tried to check that, which is why the code i sent you has a BufferTime of (35)…the actual version on the web has a BufferTime of (5).
just trying to clarify,
colin
February 8th, 2007 at 8:22 pm
colin,
By setting a buffer time of 35, you’re asking Flash to hold off actually playing the video until 35 seconds have been loaded. The default value for this property is 0.1 (one tenth of a second). So that almost certainly explains the delay. And you betcha, FLVs cache just like other files, so you’ll have to clear your cache each time in order to test afresh — or use a random number to “trick” Flash out of it.
Thanks for the compliments!
February 13th, 2007 at 6:23 pm
Hi david, i have little experience in flash and i was wondering if you could tell me how to get the movie to repeat.
Thank you.
February 13th, 2007 at 6:59 pm
Arvid,
By “movie,” most Flash developers mean a FLA or SWF, but because you posted to this FLV entry, my hunch is that you’re asking how to replay the FLV video file. If that’s it, simply invoke the
NetStream.play()method again. Alternatively, you may invoke the
NetStream.seek()method; in any case, the
NetStreamclass is your best bet.
Check it out in the ActionScript 2.0 Language Reference to see what your options are — properties are characteristics the object has, methods are things the object can do, and events are things the object can react to. You may want to read Objects: Your ActionScript Building Blocks for a general overview on classes, if these terms don’t feel especially comfortable yet.
March 3rd, 2007 at 12:20 pm
hey David,
Great site, with awsome support!
Ive made a php script which randomly pick a filename from a .xml file. Now i want the file to be played in my movie. I was thinking of something like this: - but I cant get it to work.
sti = “”
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
videoPlayer.attachVideo(ns);
ns.play(sti);
My plan is to run the thing on a local network with php installed, which ‘method’ would you think could be the most appropriate ?
FLVPlayback og videoPlayer or something different? videoclip size is about 10mb pr clip.
Kaspar Hansen
March 6th, 2007 at 8:04 am
hi
i wonder how can i play flv with buttons? i have 3 videos and 3 buttons that will load the flv into a tv i created…i cant get the buttons to work
March 6th, 2007 at 8:35 pm
To Kaspar …
I have two thoughts. First, why not use Flash to load the XML itself? See the
XMLand
XMLNodeclass entries in the ActionScript 2.0 Language Reference. It’s likely you could do the whole thing without PHP, though there’s nothing wrong with your PHP approach. My second thought — actually, this is an observation — is that you’ll need to load that PHP data via something like the
LoadVarsclass. Your idea is entirely feasible, but that isn’t the way to set variables to external values in Flash.
To helena …
Hi! Have you seen the “How to Control Video (FLV) without a Component” article on this blog? That may give you a few pointers.
March 20th, 2007 at 5:04 am
Hi David
Thanks for the blog and your work on this topic. I have found it very useful. I am wanting to test for when the video has finished so I can trigger a new event. You mentioned this (below) earlier last year and was wondering if you ever got anywhere with it?
Great site:)
March 20th, 2007 at 6:55 pm
Hi David,
My video plays fine but there’s no audio at all. Here’s the code I used. I don’t think I missed anything major.
stop();
my_NC = new NetConnection();
my_NC.connect(null);
myStream = new NetStream(my_NC);
myVid.attachVideo (myStream);
// Set the buffer time
myStream.setBufferTime(100);
btnPlay.addEventListener(”click”, playFLV);
function playFLV(){
myStream.play(”1PExtro.FLV”);
}
March 20th, 2007 at 7:46 pm
To Phil …
Do you know, I have pursued that question on a handful of occasions since I wrote this entry … in all this time, I still haven’t hit what I feel is a definitive answer — but enough colleagues have taken to the
onStatusapproach, on their own, that “close enough” may just have to do.
Thanks for the patience, and I’ll make this topic the subject of my next blog entry. Promise.
To Darren …
Your code looks fine, so I’m curious, too, why your audio doesn’t play. The first thing I would do in this case is run the FLV file on its own (say, with Martijn de Visser’s FLV Player) to make sure it actually has audio. If it plays fine, then I’d check for any ActionScript in my FLA that may be setting the volume down in general.
March 22nd, 2007 at 9:03 pm
I’m trying to use your technique but I get only audio, no video (on Mac 10.3.9, flash player
The difference between your technique and mine is thatI split up the code to different areas. I have this code on the main time line:
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
The I have on the stage a movie clip with a button inside it. The button has this code:
on (press) {
_root.videoPlayer.attachVideo(ns);
_root.ns.setBufferTime(5);
_root.ns.play(”office.flv”);
_root.videocover.gotoAndStop(’vis’);
gotoAndStop(’on’);
}
So this only gets me the audio part of the video. A google search turned up nothing, I’m at a loss as to what to try next.
March 22nd, 2007 at 9:18 pm
Michael,
Even though your code has only changed a bit from my suggestion, the fact that it has changed at all may be enough to merit some testing. When inexplicable things like this crop up, I generally take a step back and start again with the basics: start from a place that I know works correctly, then slowly re-add the new stuff.
I recommend, in any case, that you put the first two lines of your
on()event handler with the earlier code. Here’s why. There’s really no need to attach the video or set the buffer time more than once. If someone clicks this button repeatedly, it performs more ActionScript than it needs to.
So I would create a quick new FLA, put only the code necessary — not even the button, yet — and make sure that works. If it does, add a button and move just the
play()line to that button. Then add the
gotoAndPlay()lines one by one, testing each time. If it doesn’t work, even from the most basic approach, play the FLV independently in a stand-alone FLV Player (I happen to use Martijn de Visser’s) and make sure the FLV is properly functional.
March 22nd, 2007 at 9:37 pm
Thanks david, I got it working a bit better. I took these lines out of the button code and put it on the main time line:
_root.videoPlayer.attachVideo(ns);
_root.ns.setBufferTime(5);
removing the _root. parts of course. Now the video loads. Only one problem left! I have a movieclip on the main timeline with this code (to stop/unload the flv):
close_btn.onRelease = function(){
_root.ns.close();
};
stop();
and a button called close_btn in the movie clip. This succeeds in stopping the video but it just freezes and does not disappear from the stage. I tried _root.ns.clear() as well but no dice.
March 22nd, 2007 at 9:46 pm
Michael,
Almost there! In addition to the
NetConnectionand
NetStreamclasses, you’re also dealing with a Video object, so take a quick look at the
Videoclass and you’ll find a
_visibleproperty.
March 22nd, 2007 at 10:06 pm
Thank YOU!!!! (Marry Me) lol
adding _root.videoPlayer._visible = false;
worked perfectly!
March 22nd, 2007 at 10:12 pm
Michael,
haha Awesome!
March 26th, 2007 at 9:38 am
Hey David,
I’m having an issue with extracting the code to play an flv into a class. I have a function call from the fla as such:
var vid = _parent.createVid(video_mc,”flv/intro.flv”);
vid.playFile();
This code calls a method from my starter class (attached to a parent swf) with this code:
public function createVid(mc:MovieClip,file:String){
var vidSettings = new classes.VideoSettings(mc,file);
return vidSettings;
}
This instantiates my ‘video’ class that i’m hoping would initialize everything to play the flv back. Here is that class code:
class classes.VideoSettings {
private var buffer:Number;
private var video:String;
private var video_mc;
private var mc:MovieClip;
private var stream:NetStream;
public function VideoSettings(mc:MovieClip,file:String){
this.mc = mc;
this.buffer = 3;
this.video = file;
this.init();
}
private function init(){
var connection_nc:NetConnection = new NetConnection();
connection_nc.connect(null);
this.stream = new NetStream(connection_nc);
this.stream.setBufferTime(this.buffer);
}
public function playFile(){
var vid:Video = this.mc.videoScreen;
vid.attachVideo(this.stream);
this.stream.play(this.video);
this.stream.onStatus = function(infoObject:Object){
trace(infoObject.code);
if(infoObject.code == “NetStream.Play.Stop”){
//skip_btn.onRelease();
}
}
}
}
When i trace out the status, i see that it is ‘playing’, but it actually just gets frozen on the first frame of the movie. I can even implement stream.seek(x) and jump to points in the movie, but it doesnt play back. Any help you can offer would be much appreciated. Thanks!
Tito
March 27th, 2007 at 9:53 am
Tito,
I’m assuming the movie clip referred to in this line …
… actually contains a Video object, right? If so, your approach shouldn’t be a problem; and yet — and this is the “fun” of programming, right? — seemingly inexplicable problems do crop up. I don’t immediately see an error with your ActionScript, so in a case like this, I would take a few steps back and gradually build up again to ActionScript in an external class file. Take very small steps and make a test with each new line of code. If you’ve made a mistake, you’ll likely catch it this way. I would also test the FLV itself. Was it properly encoded? Have you published to a high enough version of the Flash Player for the codec you’re using?
March 27th, 2007 at 12:11 pm
Hey David,
Thanks for your quick response! In regards to your questions:
‘this.mc’ is referring to a movieclip on the stage that contains a video object named ‘videoScreen’.
The flv itself is fine, since if i extract the code in my class functions to play the flv and place it within the fla, everything works fine. I’ve traced out each section of the methods and everything is being passed as it should and reaching the desired methods. The video even gets started/loaded, but as i mentioned previously, just hangs on the first frame of the movie
This is very confusing to me, since I dont see anything that could be causing it…
Do i have to make my class extend something like ‘movieclip’ ? i’ll keep testing, and post if i come up with any results. Thanks again for your assistance, I know many others as well as myself appreciate it
Tito
March 27th, 2007 at 1:39 pm
Hi David, this is my problem. I want to load the .flv file from another location relative to the html that has the .swf link. I’m using swfobject.js and passing my .flv filename using addVariable(). The swf file (which is the video player) is in a completely different location than the html but the flv file is in the same directory as the html. Unfortunately, Flash 8 decides to make the “contentPath” (or using your way, it doesn’t make a difference) to the .flv file relative to the .swf file and not the html. As a contradiction, if you use a skin for playback buttons, etc… it looks for it relative to the html and not the swf. That of course is fixable because Flash 8 let’s you specify your own custom url to the skin. But I need my contentPath to be relative to the HTML and not the .swf file that contains my player! Ugh. I don’t see any way of doing this yet… And why the heck does Flash 8 treat “contentPath” and skin paths differently?
March 27th, 2007 at 1:48 pm
Matt,
That is a weird phenomenon, isn’t it? For anyone else following along, I made a few observations on the same topic in “(Perhaps) Unexpected Point of View: SWF Defers to HTML” and “Unexpected ‘Gotcha’ with Relative Paths in ActionScript”.
Fortunately, you should still be okay. Use
addVariable()to pass in the location of the FLV, but don’t include a path. Because FLV paths, oddly enough, are associated with the SWF, use the
MovieClip._urlproperty to determine the SWF’s location, then keep only the first part of that string (up to the last slash) with, say,
String.substr()… then append your FLV, as passed in, to that path.
March 27th, 2007 at 2:43 pm
Maybe I misunderstood you but I don’t want to know the SWF’s location. It would be say here: /scripts/videoplayer.swf. But my html file (i.e. “how-to-multiply.html”) that embeds it is here: /courses/math1/ as well as the .flv file: “how-to-multiply.flv”. Let’s pretend I’ve got tons of courses like this and various .flv files in them. I want my videoplayer.swf to find “how-to-multiply.flv” in /courses/math1/ and not /scripts/. So I set contentPath=”how-to-multiply.flv” with addVariable() & actionscript and right now I’m getting 404 errors that say it can’t find /scripts/how-to-multiply.flv. My .flv files are stored along with the .html files that embed the videoplayer.swf and I can’t figure out how to make it load the .flv files from there except by saying contentPath=”/courses/math1/how-to-multiply.flv”. That’s a pain because it should look relative to the html file anyways and not from the swf. Did that make sense?
March 27th, 2007 at 3:12 pm
Matt,
Sorry, man. You understood me just fine — I goofed! I mistakenly thought the
_urlproperty would display the location of the HTML file, given the path wackiness we just discussed, but it shows the location of the SWF.
Is there a reason not to use absolute paths?
If they have to be relative, you can always use
../to back up a folder.
March 27th, 2007 at 3:48 pm
Thanks for your input. Absolute paths will work but obviously if I restructure the directories, I’d have to change them all. I’ve posted in Adobe Webforums but I see that you’ve responded there as well
Maybe Adobe will see this and fix it as I’m pretty sure it’s a bug.
March 27th, 2007 at 4:09 pm
Matt,
Hard to say if it’s a bug, but imagine … if they change this behavior in future Flash Players, all the content out there that currently works will fail. So it’s a dicey situation.
If you think in terms of your SWF’s location, though, you can backtrack to where the FLVs are with
../, so give that a shot. Good luck with that!
April 1st, 2007 at 11:45 am
Tito,
Woops, I missed your earlier reply from March 27. The only time you need to extend
MovieClip(or any class, for that matter) is when you need most or all of that class’s functionality in the new class. Imagine a
Petbase class. Instances of
Petcan walk, eat, and make noise. If you’re writing a
Dogclass, it probably makes sense to extend
Pet, because your dog objects will need to walk, eat, and make noise. By extending
Pet, those objects can already do all of those things. In addition, your
Dogclass will add functionality to chase sticks.
In my view, your class doesn’t need to extend
MovieClip… what you’re doing here, in a sense, is transferring timeline code into an external file. There’s nothing about class files per se that would change the way video is displayed. Unfortunately, nothing immediately jumps out at me in your sample code, so I’m kinda scratching my head too.
I hate to use the following as an excuse, but the last several months have been absolutely insanely busy for me. I’m almost finished a Flash book for friends of ED for this summer, so for better or worse, I’ve had to limit my blog and newsgroup replies to answers that spring to mind immediately.
April 17th, 2007 at 10:41 am
I know this is a basic issue but I can’t figure out how to Pause or Stop the FLV streaming on load. I don’t want it to just play, I want the user to click play. How can I do that in the script? Thanks in advance for your patience.
var rtmpRoot, instance, file, type;
var x:XML = new XML();
x.ignoreWhite = true;
x.onLoad = function(success) {
if (!success) {
trace(”Cannot load XML”);
} else {
trace(”Loaded”);
//trace(this);
file = this.childNodes[0].childNodes[0].childNodes[0].toString();
trace(file.substr(file.length - 3, 3));
type = file.toLowerCase().substr(file.length - 3, 3);
trace (type);
}
};
x.load(”movie.xml”);
April 17th, 2007 at 7:31 pm
Jeff,
When you stay “Pause or Stop the FLV streaming on load,” do you mean in response to the
XML.onLoadevent? If so, you would reference your
NetStreaminstance in the
onLoadhandler — the function in your code above — and invoke, say, the
NetStream.pause()method.
Does that answer your question? If not, ask again and I’ll try again.
May 8th, 2007 at 11:38 pm
Hi David,
I experienced a problem with video playback which was very similar to what TJ described above. Searching for solutions I came across this page.
As it turns out, the solution to the problem was fairly simple:
I have a hebrew version of windows and I was working on files that were located on my desktop. Foreign language Windows versions give the Desktop a name in the local language which means that the absolute path to my FLV file included incorrect characters.
Once I moved the files to an English-Only path (i.e. C:/MyPresentation/myVideo.flv) everything worked. Perhaps TJ’s files worked on your computer and not his, because he works on a non-english OS.
May 10th, 2007 at 8:03 am
Hi David,
I am writing a large piece of education software for schools. It is mostly written in Flash but uses Director to handle the FileIO. After 9 months of development one of the final problems that I have is that the FLV files will not run when the application (which is an EXE) is run over a UNC path.
The path to the FLV needs to be absolute as the software allows schools to install ‘resource packs’ (containing FLVs, JPGs etc, etc) on any server and the application pulls in the resources from these different locations. All the other ‘resources’ load in fine (i.e. the SWFs, MP3s and JPGs) but the FLVs will not play. I am using the FLvPlayback componant and I assume that I am hitting a security issue with the playback of FLV files across UNC paths (which I assume Flash treats with the same security as Cross-Domain). Is there a solution or is it the case that there is no way to playback an FLV file across a UNC path.
Kind Regards,
J.
May 12th, 2007 at 7:37 am
Is it possble edit the code to have a button on frame 1 play the video component say on frame four?
May 13th, 2007 at 8:56 pm
To Ilan …
Interesting. I certainly hadn’t thought of something like your suggestion for TJ’s files. I do remember that they worked just fine on my machine, so it’s hard to say if it was a language-level (or character-level) issue, but you’ve raised a thought-provoking point.
To James …
I don’t know the answer to this personally, but I’ll check with a few colleagues who may know. I’ve noted your personal email address and will reply there.
To Brian …
That may just be it if Jeff is using the FLVPlayback Component. Good thought! I’m curious what the XML connection is, so I hope Jeff writes back.
To Tony …
That is possible, but just have to make the “connections” work. For example, if the button is on frame 1 and the FLVPlayback Component (or any Component) is on frame 4, then they don’t exist at the same time. One of the ways you can get around this is to put the Component on frame 1 along with the button, but set its alpha or visibility to zero. It has to “be there” where the button is in order for ActionScript to be able to talk to it. But then you could use the button to a) send the playhead to frame 4 and b) turn the Component’s visibility back on.
May 16th, 2007 at 4:30 pm
This article is just what I was looking for. And it has worked great… on my local disk. I have not been able to get it to work when I move everything onto my server. Is there some reason the .flv files won’t load once they are on a server?
Thanks!
May 16th, 2007 at 4:59 pm
Nevermind - Called my webhost and they added the appropriate MIME type.
May 16th, 2007 at 5:25 pm
craig,
Glad to hear it!
May 17th, 2007 at 1:59 am
how can you make the video stop once you leave that frame. I have the video component in frame 4 and when I click the menu button to return to frame 1 lets say. I can still hear the media playing, if i return to frame 4 i can’t see the media, but if i click on a button to play that or another media then it’ll stop but only to reload the media into the component.
May 17th, 2007 at 10:46 am
once l leave that frame where the component is. I can still hear the audio. Is there a way to make it stop once you leave that frame. Other than that this script is amazing, thank you so much for it.
May 17th, 2007 at 2:17 pm
Tony,
When you say “video component,” do you mean the FLVPlayback Component? If so, check out the
FLVPlayback.stop()and
FLVPlayback.close()methods in the Components Language Reference. I would suggest invoking one (or both) of those in your FLVPlayback instance before leaving the frame. If you’re using the non-Component approach, consider invoking
NetStream.close()on your
NetStreaminstance before leaving the frame.
May 31st, 2007 at 12:11 pm
hi david,
i am new to work with flv. if i got a flashing logo to act as a simple preloader (no number loaded that kind of fancy things i need) for my streaming flv, what is the actionscripts to tell my logo to dismiss and call my total loaded flv to appear and start play? my flv is attached with the default FLVPlayback skin for streaming already. the logo is a simple movie clip within the fla….
thx for your help!
May 31st, 2007 at 1:52 pm
beryl,
The answer to your question depends on the mechanism you’re using to detect that the FLV has loaded. You’re using the FLVPlayback Component, so that means you could be using the
VideoPlayerclass, which the Component wraps …
VideoPlayerfeatures
bytesLoadedand
bytesTotalproperties, so if you’re checking those in an
onEnterFrameloop, you could simply issue a
play()action when
bytesLoadedis greater than or equal to
bytesTotal.
Does that steer you in the right direction? If not, let me know.
June 29th, 2007 at 9:57 am
I’m not sure what I’ve done wrong, but all I get are error messages and no video:
**Error** Symbol=Symbol 329, layer=video, frame=1:Line 16: Statement must appear within on/onClipEvent handler
var nc:NetConnection = new NetConnection();
**Error** Symbol=Symbol 329, layer=video, frame=1:Line 17: Statement must appear within on/onClipEvent handler
nc.connect(null);
**Error** Symbol=Symbol 329, layer=video, frame=1:Line 18: Statement must appear within on/onClipEvent handler
var ns:NetStream = new NetStream(nc);
June 29th, 2007 at 10:48 am
Will,
Those errors mean you’re trying to attach code directly to an object — I’m guessing the Video object — rather than in a keyframe. Code that is directly attached must appear within either an
on()event handler or the
onClipEvent()event handler, which isn’t how I wrote the blog entry’s ActionScript. Put that code in a keyframe, and you should be all right. See my “museum pieces” article for additional notes on
on()and
onClipEvent().
July 14th, 2007 at 8:50 pm
David,
I am trying to load a list of movies to play from an XML document. The XML loads into Flash just fine but I can’t seem to pass the variable to the netStream.play() function.
Here is my code…
//create global sound object
globalVolume = new Sound();
//new netconnection object
connection = new NetConnection();
connection.connect(null);
stream = new NetStream(connection);
video.attachVideo(stream);
stream.setBufferTime(0);
//since the movie is playing set the state to true
playstate = true;
//load the XML file
var videoPlaylist = new XML();
var videoPaths = new Array();
videoPlaylist.ignoreWhite = true;
videoPlaylist.load(”videopath.xml”);
videoPlaylist.onLoad = function(success) {
if (success) {
trace(”Loaded XML file successfully”);
currentVideo = videoPlaylist.lastChild.firstChild.childNodes;
//populate the array storing the paths to video files
for (i=0; i
July 16th, 2007 at 8:21 am
Sean,
Unfortunately, your code seems to have been cut off — looks like the
<character may have been the culprit. Have you verified that whatever variable is intended to hold a file location actually holds that location (i.e., have you used
trace()to see what you’re sending the
play()method)?
July 18th, 2007 at 1:59 am
First off I’d like to thank you for all the great stuff on your blog. Two thumbs up !
Now my question is a little off this topic but I was wondering if you could help me before I have no hair left because I’ve pulled it all out. Seriously… I’ve been trying to find an answer for months now and have searched and searched and searched some more. In fact it’s 2:40am and I’ve been looking for a solution almost 6 hours tonight and that’s just today.
I’m trying to make a Video Poster for my blog. They are movie posters with a trailer. I want them to be all contained in one SWF file. Figured most of it out but now the file downloads the whole FLV video every time someone visits my page. This is blowing out my Bandwidth to the point where I have five File Storage accounts and have to constantly change my code to a new one every time my bandwith is exceeded.
I’m using the video player from Adobe with the skin on auto hide and using Progressive download. You can see it on my Website.. The Ratatouille one. The others are using the Flowplayer which is OK but not really what I need because I can’t contain the poster in the SWF file and Flowplayer together.
So if by chance you could spare a moment to help me before I’m bald I’m sure my girlfriend will thank you. : )
P.S. Here is the FLA file if that helps.
July 24th, 2007 at 7:07 pm
David,
I am trying figure out how to play an FLV file once and then at the end of the flv video have it goto the next scene. I seem to figure this out and I am more of a designer and don’t really understand a lot of actionscript.
Thanks.
Brad
July 25th, 2007 at 11:59 am
To Colin …
What I would suggest, in this case, is to drop the skin (I’ll tell you why in a sec) and leave the
sourceparameter empty in the Parameters tab of the Property inspector (in the AS2 version of FLVPlayback, the corresponding parameter is
contentPath). If the FLVPlayback Component doesn’t know which FLV to load, it can’t start eating your bandwith.
Add your own button (this is why the skin has got to go) and have that button call your FLVPlayback instance by its instance name ‐ provide an instance name via the same Parameters tab — and have your button invoke FLVPlayback.source on the instance name, then
FLVPlayback.play(). Assuming the instance name
videoPlayerand a button with the instance name
myButton…
To Brad …
Check out “How to Determine the Completion of a Flash Video (FLV) File,” and instead of using
trace(), invoke an appropriate
MovieClipmethod on the main timeline (might be
gotoAndPlay(), for example).
July 26th, 2007 at 4:24 pm
Hi David,
Glad I found you, and thanks for your tireless explanations… I tried getting this together - followed your instructions as written. I can hear the audio for the clip just fine, but I can’t see any video. Do you have any idea why I would be able to hear the video, but not see it?
July 26th, 2007 at 5:47 pm
It looks like my .flv files were at fault… I reprocessed them without editing them first and it’s working. Sorry to clutter up your killer flash blog.
July 30th, 2007 at 6:33 pm
Andrew,
No worries! Glad you found your answer, man.
July 31st, 2007 at 1:04 pm
I guess this means the Adobe Skin is out eh. What a shame. I kind of liked the button with the glow and everything. It’s very stylish. Is it possible to use just the button from the Adobe Skin ? Do you know of any good free tutorials on creating your own Progressive Download Video Player ? Didn’t you have one ? I’ll look about. Thanks a million. : )
July 31st, 2007 at 9:20 pm
Colin,
If you like the Adobe skin, have at it! I personally prefer the non-Component approach because of the file size savings. It’s certainly possible to use just a single button from the original skin set (see the FLVPlayback Custom UI folder in the Components panel of Flash 8 or the Video folder in the Components panel of Flash CS3) — in that case, you’d use the FLVPlayback Component with the “no skin” setting, then wire up the stand-alone button(s) as described in the “Skinning FLV Playback Custom UI components individually” heading of the ActionScript 2.0 Components Language Reference. If you’re using ActionScript 3.0, you don’t even have to go to any trouble: the stand-along parts sense each other automatically and just work.
August 3rd, 2007 at 4:47 am
Hi David,
I am using the FLV Component (Flash 8) in an app that allows the user to open and view multiple FLVs (it’s all contained in 1 SWF though) that are progressively downloaded. I am finding that when the component is removed from the stage the FLV continues to load in in the background. This means that, once the user has clicked on a few different FLVs things start to load in really slowly becuase Flash is loading all the other FLVs in the background! I have tried using myFLVObject.close() but it seems to have no effect.
If you launch and FLV, close it, wait a few minutes and then launch it again you can see that the whole thing has loaded in! Do you know of a way to stop this happening?
Thanks for any help you can offer!
James
August 5th, 2007 at 8:08 pm
James,
The Components Language Reference doesn’t list a
close()method for the
FLVPlaybackclass. As it turns out, there is an
FLVPlayback.closeVideoPlayer()method, which might be what you’re after, but you would have to invoke that method on an instance currently present on the Stage.
I agree, it’s pretty weird that your FLVPlayback instance continues to load content after it’s been removed, but I’ve seen the occasional phantom object reference in Flash from time to time, especially when the scenario deals with something as complex as FLVPlayback.
FLVPlaybackclass again and experiment with those before removing your FLVPlayback instance. Let me know if that does it for you.
August 13th, 2007 at 9:46 am
I’m afraid I’m new to all this and I’ve yet to get it to work. I just wish I could find a tutorial that actually works. I’ve looked everywhere but can’t find one that works for Flash CS3. You’d think a tutorial on making custom video players would be popular seeing that every media rich web site has them. Thanks for taking the time to write a reply. You’re like the only one. It means alot.
August 14th, 2007 at 10:16 am
I have been successful at implementing flash video on our site with the new import feature in CS3. Except I only want the video to load when clicked on. Im trying to save bandwidth. Any help would be appriciated.
August 14th, 2007 at 11:30 am
Hi David,
I’m afraid my post is not related exactly to yours but I was just wondering if you had come accross this issue and could help me out.
I am using an instance of a MediaPlayback component to dynamically load a specific flv whose name is passed as parameter: myMediaPlayback.setMedia(myFlv, “FLV”);
The ‘Automatically Play’ property is ticked off, as I want the user to press the play button to get it started. This is almost working, however, some of the audio plays very briefly and then it stops. How could I prevent the audio from playing at all until the play button is clicked? Thanks very much for your time.
August 14th, 2007 at 3:14 pm
To Colin …
The example I’ve shown in this particular blog entry is based on ActionScript 2.0, which is available in Flash CS3 if you configure your publish settings that way for the FLA in question (see File > Publish Settings > Flash tab). If you’re looking for a way to load FLV video into a Video object in ActionScript 3.0, it would go like this:
Note that much of the above code is the same in AS3 as it is in AS2. You’ve got
attachNetStream()instead of
attachVideo(), but other than that … well, there is that
listenerbusiness, but that’s just a failsafe. If your FLV is encoded with metadata (likely, but not guaranteed, depending on how it was encoded), those three lines in the middle ensure that you don’t see a warning in the Compiler Errors panel when you compile. All they do is assign a function to AS3’s
NetStream.onMetaDataevent with a dummy (empty) function. The function doesn’t need to do anything, but if it’s absent and the FLV does have metadata, you get the warning.
To Kevin …
If you’re using the FLVPlayback Component (sounds like you are), then leave the
sourceparameter empty — you’ll see that in the Parameters tab of the Property inspector (it’s called
sourcein ActionScript 3.0 and
contentPathin ActionScript 2.0) — and make sure the FLVPlayback Component on your Stage has an instance name. At that point, assign an event handler to the FLVPlayback instance — responding to a mouse click, say — that sets the
sourceor
contentPathparameter at runtime.
You may find that this overrides any built-in buttons — the VCR controls — in your FLVPlayback Component, assuming you’re using an optional skin, so if that’s the case, create a button symbol that has a rectangle only in its Hit frame (this makes the button invisible at runtime). Make that rectangle large enough to fit the visible area of your FLVPlayback Component not counting the VCR controls, and place the button in a layer higher than the Component. Program the button, instead of the FLVPlayback instance, to set the Component’s
sourceor
contentPathparameter. The event handling for the button would be the same as that shown above for the Component.
To Elena …
Interesting … I’m not sure why or how the audio could play without the video playing as well. In any case, your own solution should follow along the same vein as my reply to Kevin. The exact syntax will be different (e.g. a
setMedia()method instead of a direct
contentPathproperty), but the principle is the same. Keep in mind that any of the selectable parameters of the Component are available via ActionScript as properties by way of its instance name. If may help if you leave the “Automatically Play” parameter off at first, then use ActionScript to set the desired FLV file and, additionally, to play it.
August 16th, 2007 at 12:41 pm
Thanks very much for your response, veeery much appreciated! I’ll try that.
August 18th, 2007 at 2:09 pm
I tried the tutorial on “How to Save Bandwidth when Displaying Flash Video” and I’m afraid to say it didn’t work. I hope you don’t take this the wrong way because I do appreciate all that you do, but I did find the tutorial a little hard to follow. I feel like the instructions don’t follow a natural progression like A,B,C, D, but rather go A,B, then to D all of a sudden… which can be off setting if you’re not experienced enough to figure out what C is.
These are the errors I got when I tried to publish the file after completing the tutorial.
1093: Syntax error. videoPlayer.source = “×220.flv”;
1078: Label must be a simple identifier. videoPlayer.source = “×220.flv”;
August 19th, 2007 at 8:33 pm
Colin,
Aww, sorry to hear that! The Notes on Design blog has a certain preferred range for number of words and I had already gone over, so that might be part of the problem. In any event, I’ll do my best to clarify here.
That fact that you left a comment about the Notes on Design tutorial on this entry worries me a bit, because the ActionScript in this particular entry is strictly ActionScript 2.0 (your error messages are the ActionScript 3.0 sort) and this one doesn’t deal with the FLVPlayback component except in the Comments section. It’s important to recognize these two approaches to Flash video as distinct, and I mention it just to cover the bases.
The two messages you’ve shown look to me like the result of a single error, not your fault at all. I can’t tell for sure, because WordPress (the software for my blog) often turns straight quotation marks (" … ") into curly quotes (“ … ”) — and that’s my hunch. Make sure you’re quoting the location of your FLV with straight quotes. That should solve it.
August 19th, 2007 at 9:06 pm
Yeah.. I didn’t want the first post to ” Hey this doesn’t work ! ” if you know what I mean.
You mean they give you a limit to the number of words you use even if it means people can’t follow the tutorial. That’s not good.
I used the code from the tutorial. It has the straight quotation marks. I even tried the tutorial once again and it didn’t work. Where you able to get it to work with the CS3 action script ? I don’t see how it could give me an error while working for you other then you might have been testing the flv file locally and not with a http//: address. Do you think that’s the problem ?
August 19th, 2007 at 9:23 pm
Colin,
Heh, no worries, but I appreciate the thought.
They didn’t limit me in any way, but rather, suggested a preferred range, and I went over (and I’m sure I’m not the only one). If the final result of my writing was confusing, the fault lies with me.
I’m looking at their blog again, and I see curly quotes — but I wouldn’t be surprised if the punctuation might render differently in different browsers. In my own testing, both the AS2 and AS3 code worked just fine. It shouldn’t matter whether the FLV is local or on the server, referenced by a relative or absolute path, though you may have problems if the SWF file is on one domain and the FLV file is on another (that wouldn’t show the error messages you’re seeing, though).
August 21st, 2007 at 6:25 pm
I used this method to create a video player with two active NetStream objects (a video and its reflection). Unfortunately, the reflection, or rather, the second NetStream object didn’t appear in Firefox 2.0.0.6. After a little bit of frustration -OK, a LOT of frustration- I deduced that Firefox sets a default max-persistent-connections-to-server in its about:config file.
I was able to change this value (type “about:config” in URL and filter by “http”) however, that doesn’t really solve the issue. My video file works fine on my machine, but I can’t expect other users to change this default value, nor do I understand the greater implications in doing so.
Have you encountered this issue? Do you know of a workaround using the same method? I’ve been reading up on using the AS 3.0 FLVplayback component, but I’ve already written the whole file in AS 2.0 using the NetStream method. I’m hoping not to have to rewrite everything. Suggestions? I simply need to load two of the same video files at the same time and treat them equally.
Thanks for the help in advance -j
August 28th, 2007 at 10:52 am
Jordan,
I’m curious about the situation you’re describing, because if you’re pulling in those FLVs via HTTP — that is, you’re not using Flash Media Server — then those requests are garden variety requests. They would be no different, in principle, from an HTML page that loads dozens of JPGs. In other words, these aren’t persistent connections.
I don’t doubt that your adjustment to Firefox fixed the issue, but that might have just been a fluke. I threw together a quick test case …
… and I’m seeing both videos play, in Firefox and IE.
August 30th, 2007 at 10:52?
August 31st, 2007 at 7:43 am
Izhar,
In actual practice, you would replace
"externalVideo.flv"with the actual name (and path, if necessary) of your FLV file. Are you doing that? In any case, you don’t need any of the
NetConnectionand
NetStreamcode if you’re using the FLVPlayback Component, but you do have to let that Component know what video file you intend to play. You can do so without ActionScript at all if you use the Parameters tab of the Property inspector.
August 31st, 2007 at 11:33 pm
Hi David Stiller,
Thank you for your reply.
That was elegant. Only problem I can’t get video - only audio to show up. Working with Flash 8 Pro on a windows. Any suggestions?
thanks
Izhar Hussain
September 3rd, 2007 at 9:53 am
Izhar,
That depends on what approach you’re using to get video into your SWF.
If you’re using the approach described in the original blog entry, you will indeed get audio only … unless you correctly configure your Video object. You’ll need to create the Video asset as described in your Library, drag it to the Stage, and give it the instance name referenced in the ActionScript. If you’re using FLVPlayback, it should all work without a hitch as soon as you point the
contentPathparameter to your FLV file. My hunch is that you’re now using the non-FLVPlayback approach, but haven’t given your Video object the instance name
videoPlayer.
September 6th, 2007 at 4:53 am
Hi David,
Thank you for your reply.
Ah, yes I got it now. Thanks alot !
Hadn’t quite understood how all this worked, but its running smoothly now!
Thanks alot for your time David!
I hope that you can help me as well…
Izhar Hussain
September 7th, 2007 at 8:40 pm
Hello David - I have read this blog entry with interest because of a problem I am having. Simply, I have created a swf incorporating the FLVPlaback component referencing an external flv that I wish to have play in a html-based cross-platform CDROM. If I use an absolute file path (includng cd drive letter) from the swf to the flv then the flv plays correctly, however if I try to use a relative path then only the controller appears in a blank white box in my html page. This obviously is unacceptable because one does not know what the cd drive letter of the users computer is and also it eliminates Mac users.
Does the above code take care of this problem? I saw you mention somewhere in your responses above that you have been successful in getting flv files to play on a cdrom.
I am desperate for a solution, and after asking for help on several flash discussion forums, nobody has a solution to this problem. Yet I cannot believe that I am the only one who wants to deploy flv on a cdrom.
Thanks in advance.
September 16th, 2007 at 10:18 am
Hi david, I have searched the net for an answer to my question. But I cant find out any help. And I have just came across your blog, I hope you can help
I have created this flash video player that plays only one file. That works fine. But when I load up my XTML page of my site it loads automaticaly. I dont want my video file to load automaticaly.. I want it only to load when the person press’s the play button. Could you point me in the right direction
Im very new to flash! im using action script 2.
My code:
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
ns.setBufferTime(10);
ns.onStatus = function(info) {
if(info.code == “NetStream.Buffer.Full”) {
bufferClip._visible = false;
}
if(info.code == “NetStream.Buffer.Empty”) {
bufferClip._visible = true;
}
if(info.code == “NetStream.Play.Stop”) {
ns.seek(0);
}
}
theVideo.attachVideo(ns);
ns.play(”caroline2.flv”);
rewindButton.onRelease = function() {
ns.seek(0);
}
playButton.onRelease = function() {
ns.pause();
}
var videoInterval = setInterval(videoStatus,100);
var amountLoaded:Number;
var duration:Number;
ns[”onMetaData”] = function(obj) {
duration = obj.duration;
}
function videoStatus() {
amountLoaded = ns.bytesLoaded / ns.bytesTotal;
loader.loadbar._width = amountLoaded * 188.0;
loader.scrub._x = ns.time / duration * 188.0;
}
var scrubInterval;
loader.scrub.onPress = function() {
clearInterval(videoInterval);
scrubInterval = setInterval(scrubit,10);
this.startDrag(false,0,this._y,187, this._y);
}
loader.scrub.onRelease = loader.scrub.onReleaseOutside = function() {
clearInterval(scrubInterval);
videoInterval = setInterval(videoStatus,100);
this.stopDrag();
}
function scrubit() {
ns.seek(Math.floor(loader.scrub._x/187*duration));
}
var theMenu:ContextMenu = new ContextMenu();
theMenu.hideBuiltInItems();
_root.menu = theMenu;
var i1:ContextMenuItem = new ContextMenuItem(”:::: Video Controls :::::”,trace);
theMenu.customItems[0] = i1;
var i2:ContextMenuItem = new ContextMenuItem(”Play / Pause Video”,pauseIt,true);
theMenu.customItems[1] = i2;
var i3:ContextMenuItem = new ContextMenuItem(”Replay Video”,replayIt);
theMenu.customItems[2] = i3;
var i4:ContextMenuItem = new ContextMenuItem(”Copyright 2007″,trace,true);
theMenu.customItems[3] = i4;
function pauseIt() {
ns.pause();
}
function replayIt() {
ns.seek(0);
}
_root.createEmptyMovieClip(”Vsound”,_root.getNextHighestDepth())
vSound.attachAudio(ns);
var so:Sound = new Sound (vSound);
so.setVolume(100);
mute.onRollOver = function() {
if(so.getVolume() == 100) {
this.gotoAndStop(”onOver”);
}
else {this.gotoAndStop(”MuteOver”);
}
}
mute.onRollOut = function() {
if(so.getVolume() == 100) {
this.gotoAndStop(”on”);
}
else {this.gotoAndStop(”Mute”);
}
}
mute.onRelease = function() {
if(so.getVolume() == 100) {
so.setVolume(0);
this.gotoAndStop(”muteOver”);
}
else {
so.setVolume(100);
this.gotoAndStop(”onOver”);
}
}
September 17th, 2007 at 4:53 pm
Hi David,
My issue is also the audio only plays, but the real issue is that my content path is across domains. Meaning, the flv is on 1 server and the swf container file is on another. Will this matter?
September 18th, 2007 at 8:39 am
To Izhar …
You’re welcome! Good luck as you continue to learn. I can tell you first hand, the learning never stops.
To Brian …
I believe it — and that sense of desparation is one of my least favorite aspects of development (if not the least favorite). In light of your anxiety, I feel badly for responding so late! I’ve had an intense month myself due to a couple out of town trips.
Brian, I wonder if what you’re seeing is possibly related to something I recounted in “(Perhaps) Unexpected Points of View: SWF Defers to HTML”? That’s a thought, anyway. In the very least, you should start to use a few debugging techniques, such as
trace()or the Debugger panel, to start peeking under the hood of your SWF. Because your SWFs are running in a browser, you may want to use remote debugging, as described here:
To Matthew …
The reason your video plays immediately is because of this line here:
ns.play("caroline2.flv");
… so you’ll need to get rid of that. If the
NetStreaminstance doesn’t know the location of your FLV file, it can’t start loading it.
Instead, change your Play button’s behavior from what it is —
ns.pause();— to
ns.play("caroline2.flv");. Makes sense so far, right?
Only problem is, you also want that button to invoke
NetStream.pause();. Seems like, ultimately, you’ll want the Play button to invoke
play()first, then
pause()later, and I can already see one way to check for that. The
NetStream.timeproperty tells you how far along the video has played. So how about something like this:
Note that I supplied the optional parameter to
NetStream.pause(), to ensure that the method does what you expect (it is a toggle, after all, without the parameter, and therefore doesn’t necessarily mean “pause”). You’ll probably want to use that same optional parameter in your Pause button’s event handler (specifying
trueinstead).
To Anthony …
Different domains will indeed make a difference. The security sandbox has changed (becomming more strict) with each new release of Flash Player for a couple versions now. It’s entirely possible to serve up content from one domain and consume it in a SWF from another, but you have to take the necessary measures.
Flash Player 9 Security white paper
Flash Player 8 Security white paper
That said, I would start small and make sure you get the video to run properly first without the added complexity of cross domain issues.
September 18th, 2007 at 8:38 pm
Hi David,
After reading through all these posts I worked up the code you see below. the good news is that it works. For those looking to do the same, which is to load an external FLV for a kiosk type app, this will load a FLV from a local resource, position it, and play ( looping ).
My problem, is that I need to be able to replace the playing flv, with another Flv. I can’t seem to get the name of the instance created, to kill it and then spawn a new net connection to the next clip I need (this is for a card game, all files are rendered flv’s). It seems the instance name changes so I am having trouble moving to the next step (remove current FLV at the pixel location, and load a new one).
Perhaps I am way off the mark and should somehow encapsulate into a movie clip? That seems a bit antiquated but maybe not.
Target deployment is CS3, AS3, on a standalone terminal.
Any light you can shed on how to kill, unload this loaded FLV so I can start a new one up? I searched long and hard but have yet to find a nugget of information to springboard off of again. Your posts in this thread is what got me to where I am today, thanks so much.
- Scott (smic)
function setupDealer1():void {
var videoPath = new String();
videoPath = “theme/p1_join_01.flv”;
trace(”position 1, DealerScreen videoPath is” + videoPath);
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
var vid1:Video = new Video();
this.addChild(vid1);
vid1.x = 40.8
vid1.y = 230
vid1.width = 207
vid1.height = 467
vid1.attachNetStream(ns);
ns.play(videoPath);
ns.addEventListener(NetStatusEvent.NET_STATUS, statusHandler);
function statusHandler(event:NetStatusEvent):void {
// trace(event.info.code);
switch (event.info.code) {
case “NetStream.Play.Start” :
trace(”Start [” + ns.time.toFixed(3) + ” seconds]”);
break;
case “NetStream.Play.Stop” :
trace(”Stop [” + ns.time.toFixed(3) + ” seconds]”);
ns.play(videoPath);
break;
}
}
var netClient:Object = new Object();
netClient.onMetaData = function(meta:Object)
{
// trace(meta.duration);
};
ns.client = netClient;
}
September 18th, 2007 at 8:39 pm
and I am sorry, should have posted this to the non component post.
September 20th, 2007 at 10:19 am
Thanks for your help david. I will put your wise words to good use. Im very new to flash! I hope to one day be as good as you
Keep up the good work
Kind regards
Matthew
September 25th, 2007 at 3:35 pm
Hi David,
I’m a NOVICE to Flash Video. I purchased Flash Video Pro 8 to encode videos online.
I have encoded my first flash video online at, however, the FLVPlayback component .swf controller is “not publishing with the video”.
I have used the SteelOverAll.swf controller and as you can see from the link above, it does not display online.
What can I do to fix this step-by-step? I would like my controller to publish with the video online.
Thank you,
Carl
Orlando, Florida
September 26th, 2007 at 8:54 am
To Scott …
ActionScript 3.0 is different from ActionScript 2.0 in a number of important ways, so I’m glad this blog entry was able to help you to this point.
When I read this part …
… a couple things come to mind. First, I notice you’ve wrapped most of your code inside a custom
setupDealer1()function. Nothing wrong with that, per se, but you should be aware that declaring your variables inside the
setupDealer1()function scopes them to that function. If you attempt to reference, say, your
vid1instance in later code, you’ll find that it doesn’t exist. In order to make your various instances —
vid1,
ns, etc. — more globally accessible, declare them outside the function, then use the function itself to refer to those variables and use them in whatever way makes sense.
My other thought was triggered by your phrase “spawn a new net connection,” which suggests to me that you may believe you need a new
NetConnectioninstance every time you want a new video (along with, perhaps, a new
NetStreaminstance, and so on). In case that’s what you meant, you’ll be happy to hear that you only need one instance of the related classes apiece and can re-use them as often as you like.
You shouldn’t have to kill the existing FLV, but rather, invoke that
NetStream.play()method as desired with a new file path.
To Matthew …
Thanks for that! I’m always glad to hear it when these articles are helpful.
To Carl …
The SteelOverAll skin — in fact, all of the FLVPlayback skins — are actual separate SWF files that must be uploaded to the server in addition to the FLV and the SWF that houses the FLVPlayback component. These files must all be in the same relative location to each other on the server as they are locally. The first step is to ascertain that your skin has been uploaded. If so, something else has gone awry and I’ll try to help you through that.
September 28th, 2007 at 3:10 pm
Yes, I have uploaded the SteelOverAll.swf skin to the same exact folder on the server as the .fla, .flv and .swf (4 files total). If you look at, then you will see a space below the video.
The video is 320×240
The controller is “Over the Video”
The stage setting is 320×240
There is a space below the video…
This space is there with the “external controller.swf” and the “over the video controller.swf”. In both scenarios, when I tested it locally, I saw the controllers and “the space”. When I uploaded it to the server, I didn’t see the controllers, but had that “the space” publish…
Hope you can help…
September 28th, 2007 at 6:59 pm
Carl,
Aha, this looks like a security sandbox issue. I used my browser to view source on your resume page. That showed me that your Universal.swf file is located here …
djcarl.com/_flash/
… which Flash Player considers a different domain from this …
resume.djcarl.com/
… simply because of the addition of the subdomain resume. Flash Player is okay with loading Universal.swf itself, but Unversal.swf in turn requests another SWF file (SteelOverAll.swf) that appears to be hosted on another domain, and that’s too dicey for recent versions of Flash Player. (Note that if you reference the SWF directly —
— the controls load, because from this point of fiew, Unversal.swf is loading “safe” content from the same domain.)
The quickest fix, if you can arrange it, is to reference Universal.swf from the same domain (in this strict definition of “same”) as the HTML page that loads it. In other words, in your HTML, change this …
… to this …
If you can’t do that, you’ll have to put a cross domain policy file on the machine that hosts djcarl.com (the one without the resume subdomain).
September 29th, 2007 at 5:06 pm
David,
I have taken your advice. Thank you! I told you that I’m a NOVICE. I’m without success. Here is what I did:
I took the four files (SteelOverAll.swf, Universal.swf, Universal.fla and Universal.flv) from the folder and moved them to the subdomain resume folder.
Within the resume folder, we have the four (4) files and the index page (1). Five files total.
I have also added the crossdomain.xml to the djcarl.com root directory
The code on resume.djcarl.com now references and still the same result… (Take a look)
Also, those same 4 files “are still” in the (a) folder. They are in the (b) resume subdomain folder and I have them in the (c) root directory of djcarl.com with the crossdomain.xml file
I’m wondering if my Flash video set-up was incorrect because when I tested the page locally, I saw the controller with the video, however, I saw that space below the video too?
Could it be that the space below the video may be the cause to “SteelOverAll.swf” and “SteelExternalAll.swf” controllers not publishing?
Maybe I need a step-by-step in the Encoding Video process?
Thanks,
Carl
September 29th, 2007 at 5:25 pm
Sorry David! It worked once I uploaded it real-time! Nice!
How can I get rid of that space below the video in the set-process?
Thanks!!!
Carl
September 29th, 2007 at 7:25 pm
Carl,
Ah, glad to hear that! The key was the subdomains, then, so file that factoid away for future reference.
As for the space below … under the current circumstances, you’ve embedded a SWF that’s 206 pixels high and put it into a space that’s 240 pixels tall, so the height of the SWF is what it is. If you choose one of the “Under” skins (rather than SteelExternalAll.swf, for example) you’ll find that the controller moves beneath the area that displays the video content. That may just fill that space perfectly.
October 1st, 2007 at 2:22 pm
Thank you David! I’m glad I found your blog! You helped me out big time!!! I communicated my issue to many people and you were the only one to come through to solve this specific issue with the controller. Take care!!!
Carl
Orlando, Florida
October 2nd, 2007 at 1:04 pm
Carl,
Nice!
October 2nd, 2007 at 6:51 pm
David,
Thanks…that solved it. with the changes suggested I can now do movie replacements with ease. I did add more code to change the x,y, height and width on the fly as they are loaded in, and I am back on track.
Thanks again.
October 9th, 2007 at 10:05 am
Scott,
Glad to hear it.
October 12th, 2007 at 4:07 pm
David,
Hopefully this one hasn’t been asked yet; if so, please reference the answer.
I’m currently doing Flash 9 / AS3 / FMS2 development at work. I have a working example of video playback (using AS2 and the Video class) that I have live right now (). Videos seem to be streaming just fine via the standard rtmp protocol for FMS2, which is running on our server. Everything uses the standard AS2 NetStream and NetConnection framework.
However, I’m looking to move this into the FLVPlayback component and can’t figure out how to play them. My understanding this would all be done through the source parameter of my FLVPlayback component — i.e.,
video_player.source = (path to video). Only I can’t figure out what the path should be!
Or am I just looking at this the wrong way?
Many thanks in advance for any help you can provide on this subject.
October 13th, 2007 at 6:48 pm
Alex,
In ActionScript 3.0, you’re right, it’s the
FLVPlayback.sourceproperty you’re after. Now, you mentioned that in the AS2 world, you had this working just fine with the
NetStreamapproach, so you must have had a set of RTMP addresses handy, right? When you typed that
NetStream.play()method, you provided an RTMP path as your parameter — it’s that same path you’ll need to supply to
source.
October 17th, 2007 at 1:28 pm
Dave,
It should be noted that my working example is closely based off an example from adobe.com’s dev center for the Flash Media Server 2. I can’t recall if this was one of the included examples that came with FMS2, but it’s fairly straightforward - I just went back in and gave it a little customization.
That said, the working AS2 / Flash 8 example I have works by connecting the client net connection (called client_nc) to the rtmp url (saved as a string). Then, when a video item in the list is clicked, a listener set up on the list processes the video request by using an event object as its source. Essentially, the contents of this object is the string literal of the file name - which is what is displayed in the list. At the point, the video net stream is set to play the targeted video:
video_ns.play(eventObject.target.value); // parameter is simply the name
of the flv file, less the “.flv” extention at the end.
Finally, the video is played on the Video object using the following line:
Replay_Video.attachVideo(video_ns);
In other words, to answer your question if I had a set of RTMP addresses handy, the answer is, “I’m not sure.” The system works but I’m not entirely sure what the full addresses are for the videos that stream.
This is where I get all confused, for a few different reasons.
1. At no point during this program does anything make an explicit call to the FMS2 in the lines
(player).source = “rtmp://[my_server]/[some_file].flv
I have tried doing this explicitly but to no avail.
2. Do I need to set up a net stream and net connection for this to work? Or is this somehow “built-in” to the new FLVplayer component?
3. Are there any working examples of this?
Thanks again for any help you can provide on this.
October 30th, 2007 at 10:17 pm
Great tutorial!!! Just what I was looking for. One more thing, how can I have it so the swf just sits there on the page until clicked. Upon clicking, it would play the flv.
Thanks.
November 1st, 2007 at 3:00 pm
Kamil,
For something like that, you could omit the
ns.play("externalVideo.flv");line so that it could be triggered in response to the click. If you had a button somewhere, you could assign a function to the
Button.onReleaseevent like so:
If you didn’t have a button or movie clip handy, you could trigger that line with a
Mouse.onMouseUpevent handler:
November 7th, 2007 at 5:03 pm
Wow, I must say I am glad you still update this article! I want to thank you for the information. I haven’t found anything like it… I am having a problem though. This is the first time I am trying to use video without the component… so like Markus back in 06 stated… (although he wanted to use a component, I think… I just want the video to ’steam’ without controlling it at all… its a background video.
I can only hear the test video, not actually see it (the actual video has no sound)…
plus, I have embedded cue points in the flv and was wondering if you could send me down the right path with those… I just want to have the actionscript add a movie clip to the root each time the cue point is triggered.
Thanks!!
November 7th, 2007 at 5:33 pm
Lauren,
I think this is the single most popular article on the blog, so it generates a lot of comments.
I’m always happy to keep stuff fresh, and very soon now, I plan to write ActionScript 3.0 versions of the most frequently visited articles here.
Markus did manage to get his issue resolved — the audio-but-no-video issue, at any rate — and I think, at the time, he was confusing components with the Video object this approach requires. Did you drag a copy of the Video object to the Stage yet (you’ll need to create it in the Library first)? Does that Video object have an instance name (see the Property inspector when you have the object selected), and is that the instance name you’re using in front of the
attachVideo(ns);line?
My “How to Use Flash Video (FLV) Cue Points” article should give you a good head start on video cue points, but don’t hesitate to add questions to that one if you need additional help.
November 7th, 2007 at 5:52 pm
Awesome — I am well.. I have been looking at this code way too long… I spelled video incorrectly… thank you for picking up my slack…
As for the article… i am getting a 404 error and I searched for it on your site and I can’t seem to find it.
I know this would be pretty simple minded of me… but can I just trace(cuePoints) ? Or something to that effect?
I simply want something.cuePoint = function () {
attachMovie(”plus1″,”plus”, 100)
} and each cuepoint would attach the same movieclip…
Thanks… I really appreciate your speedyness! You respond faster than my professor can even get over to my station!
THANKS!
November 7th, 2007 at 8:16 pm
Lauren,
Wow, that’s odd. I republished that cue points article and it seems to be showing now (for other friends on other networks, too). Must have been something wrong with WordPress that day (thanks for picking up myslack!).
Ha! Luck of the draw, that. Let me know if you still can’t see the cue points article. That should help you see how to trace what you’re after.
November 8th, 2007 at 1:04 pm
Hi David,
You have helped me before and I truly appreciate your response time and KNOWLEDGE!!!
I have 2 questions:
1. How does one set-up Flash Videos with Flash Pro 8 that shows the time length of the video like youtube.com does with its videos?
2. Where can I learn EASY “step-by-step” how to set-up a Flash video player like the one on yahoo, i.e.,
Thank you!
Carl
Orlando, Florida
November 11th, 2007 at 2:44 pm
Thanks for this tutorial. How would you go about adding multiple videos? I created a key frame for each Video and each carries a key frame with it’s own AS. I changed the Instance name for each but only one of them works. Any idea how to add multiple videos?
November 13th, 2007 at 11:58 am
To Carl …
The version of Flash, per se, isn’t as important to the solution as the version of ActionScript you’ll be using. This particular blog entry was written for ActionScript 2.0, which is ideal for Flash 8 or Flash MX 2004. (Flash CS3 would also allow you to use AS2, but you could alternatively use AS3.)
Since you’ll be using AS2, you may actually be able to figure out quite a bit from the other AS2-based articles on this site. “How to Build a Flash Video (FLV) Progress Bar,” for example, shows how to extract and use length/duration values from your FLVs, and you’ll find plenty more simply by searching the word “video” in the search field of the blog’s main page.
To be frankly honest — and at the same time friendly, if frank can be friendly
— I think that an easy, step-by-step guide to building a Yahoo!-style video player would have to be a very long document indeed. The key to achieving such a goal, at least in programming, is to break down the ultimate endeavor into as many sub-parts as needed, mastering each small part as you go.
A big help, along those lines, is to consider your various parts as the objects they are, and to understand that objects are defined by classes, which define their properties (characteristics), methods (things they can do), and events (things they can react to). In terms of Flash video — if you’re not using FLVPlayback — your main classes of interest will be
NetStreamand
Video.
To Tony …
All you need is one instance apiece of the classes shown:
NetConnection,
NetStream, and
Video. If you let your Video object stretch across all those frames, you should be fine. As long as the Video object is associated with its
NetStreaninstance at the beginning of your span of frames, you’re good to go. To change what video is shown, you’ll simply invoke
NetStream.play()on your
NetStreaminstance (here,
ns) and specify the name of a new FLV file. And if you like, you don’t even need all the extra frames. By using buttons or maybe detecting the completion of each FLV, you can play new videos as often as you like — all from the same single timeline frame.
November 13th, 2007 at 11:23 pm
Thanks David!
Do you have a book out? You should. You’re very good!
November 14th, 2007 at 10:05 am
Carl,
Thanks! As a matter of fact, I just had my first book published a few months ago.
I co-authored Foundation Flash CS3 for Designers (friends of ED) with a good friend of mine, Tom Green. and wrote the interactivity chapter for How to Cheat in Adobe Flash CS3 (Focal Press), written by another good friend of mine, Chris Georgenes.
November 15th, 2007 at 1:27 am
Hi David,
I have a small problem. I m playing flv file from webserver. The thing is I want to get status from flash saying that NetStream has finished playing the flv file. I trace NetStream.onStatus. There i get NetStream.Play.Stop flag once playing is finished. But the problem is if I click play button again the trace doesnt show NetStream.onStatus in the output.
The code goes as follows: -
var duration:Number = 0;
var ratio:Number = 0;
var idTracking:Number = 0;
var idLoading:Number = 0;
_global.ns1.onMetaData = function(infoObject:Object):Void {
duration = infoObject.duration;
ratio = tracker._width / duration;
idTracking = setInterval(updateKnob, 50);
idLoading = setInterval(updateLoader, 50);
for (prop:String in infoObject) {
trace(prop + “: ” + infoObject[prop]);
}
}
_global.ns1.onStatus = function(infoObject:Object) {
trace(”ns1.onStatus called: (”+getTimer()+” ms)”);
for (var prop in infoObject) {
trace(”\t”+prop+”:\t”+infoObject[prop]);
if(infoObject[prop] == “NetStream.Buffer.Full”)
{
startWatchStream1();
}else if(infoObject[prop] == “NetStream.Buffer.Full”)
{
stopWatchStream1();
}
if(infoObject[prop] == “NetStream.Play.Stop”) {
stopWatchStream1();
}
}
trace(”");
if (this.time > 0 && this.time >= (duration - 0.5)) {
clearInterval(idTracking);
delete this.onStatus;
}
}
_global.ns1.onPlayStatus = function(infoObject:Object) {
trace(”NetStream.onPlayStatus called: (”+getTimer()+” ms)”);
for (var prop in infoObject) {
trace(”\t”+prop+”:\t”+infoObject[prop]);
}
}
startWatchStream1 = function():Void {
delete this.onEnterFrame;
this.onEnterFrame = function()
{
tplayerstatus = _global.ns1.time;
if(ns1.time == duration) {
trace(”!”+duration);
stopWatchStream1();
}
}
}
stopWatchStream1 = function():Void {
playButton._visible = true;
stopButton._visible = false;
playButton.enabled = true;
stopButton.enabled = false;
ratio = 0;
updateKnob();
tplayerstatus = “”;
delete this.onEnterFrame;
}
my_video.attachAudio(_global.ns1);
function updateKnob():Void {
knob._x = tracker._x + _global.ns1.time * ratio;
}
knob.onPress = function():Void {
clearInterval(idTracking);
_global.ns1.pause(true);
this.onMouseMove = function():Void {
if (tracker._xmouse > 0 && tracker._xmouse = 98) {
loader._xscale = 100;
clearInterval(idLoading);
}
}
tracker.onRelease = function():Void {
if (this._xmouse > 0 && this._xmouse
November 15th, 2007 at 2:12 am
Continuing to the previous post.. I hv put following code for the play Button
on(release) {
var filename = _global.flvpath+_global.lastsound+”.flv”;
playButton._visible = false;
stopButton._visible = true;
playButton.enabled = false;
stopButton.enabled = true;
_global.ns1.play(filename);
startWatchStream1()’
}
November 19th, 2007 at 1:56 pm
Do I need to have Flash Media Server installed to get this to work? I loaded my files onto 2 different servers. The server that has FMS works properly while the other one doesn’t. If my contentPath directs to the server with FMS, only then will it work.
November 19th, 2007 at 2:11 pm
Scott,
You mention
contentPath, so it sounds like you’re using the FLVPlayback component. The approach described in this blog entry is specifically geared toward not using FLVPlayback — not that there’s anything wrong with the component … it’s just that the code shown above isn’t intended for FLVPlayback use. Either which way, though, FLVs do not necessarily need Flash Media Server.
November 20th, 2007 at 8:47 pm
ace,
Woops! Sorry I missed your comment just before Scott’s.
Wow, that was a lot of code! Unfortunately, it looks like some of it was even cut off. You had one question — why isn’t
onStatusdispatched when the video is played? — and for better or worse … honestly, I’m just looking at too much here to give you a useful answer. To make matters worse, even if I copied and pasted your code into a FLA, that still wouldn’t be enough, because part of it is missing — plus, I don’t know how your assets were arranged in the file. I do see you’re handling an
onPlayStatusevent, which isn’t supported in AS2 (that’s an AS3
NetStreammember), so maybe that’s the issue?
When I run into unexpected behavior in my scripts, the first thing I do is try to isolate the issue into small chunks until I can better see what’s going on. For something like this, I would save my work, start a new FLA, and write up a new throw-away
NetStream.onStatushandler and test it like mad. Trace out starting and stopping, all without the extra baggage of the original code. If what I see makes sense, I start bringing in chunks of the other file section by section (sometimes line by line). It’s work, for sure, it in my experience, it leads to the answer every single time.
November 20th, 2007 at 9:52 pm
[Follow up on Alex Baker, several posts back …]
Alex and I corresponded briefly via email and managed to make a bit of progress with his issue.
November 24th, 2007 at 8:21 pm
Hi David,
I can’t believe I just read through this entire blog but I’m very impressed! I’m a total novice (untrained) and only recently began using Flash MX 2004 to update my site which was completely built on Flash (by someone else). I used your original script as is and it works like a charm locally on my PC but not through my server. I initially thought I may have the same problem above as someone who needed MIME types from his web Host, but the technical support at my Host said the MIME is already present and had no explanation or advice as to why the video doesn’t play on my site. I can confirm that all the related files (the html, the .swf and the .fla) are located in the same directory, just as when on my pc. I’ve given the video ages of time to load to see if its related to the size of the video, but it just never plays. Is there anything you think I should try? Below is my coding.
The SWF associated with the coding is called: “VideoStreamTest2.swf” and is loaded by a Button having the following script:
on (release) {
loadMovieNum(”VideoStreamTest2.swf”, 2);
}
And this is the coding for “VideoStreamTest2.swf”
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
videoPlayer.attachVideo(ns);
ns.play(”ThePhilippines_Draft11.FLV”);
Thanks in Advance!
Kurt
November 27th, 2007 at 12:45 am
Kurt,
Wow! That’s a lot to read! Thanks for the kind words.
Interesting. Well, you covered two questions I would have asked (the MIME setting and file locations on the server). Your best bet at this point is to break down the complexity just a bit. You’ve got two things going on: a) loading a SWF and b) loading an FLV. What happens if you test VideoStreamTest2.swf just on its own — both on your PC and on the server?
January 7th, 2008 at 11:32 pm
thanks for your help last time. here is another one! how to load flv randomly?
January 8th, 2008 at 4:48 pm
David,
Great site. Hope you can help me.
Like Brad of July 24, 2007, I’m trying to to play an FLV file and once it ends have it go to another scene. But I don’t want to use a button to have it go to the other scene (in my project I want to FLV file to play - it’s in scene 2, and then go back to scene 1). I would like the FLV file to automatically go back to scene 1 once it is complete.
Also like Brad I’m more of a designer than programmer. So any help you can provide me with this problem is sincerely appreciated.
Thanks in advance,
Robert
January 8th, 2008 at 9:50 pm
hi david,
i am putting my question a bit into details. could u tell me the script to load my flv randomly on the main page of my “papajaypictures”? it is really impressed your help last time when i didn’t even know how to load flv! thanks!!
January 13th, 2008 at 1:26 pm
To beryl …
There are a number of ways I can think of to interpret your question, so it may help me to get a bit more information on what you’re after. If you have a small list of FLV files, you could certainly store them in an
Arrayinstance (an array is essentially just a list), then pick an element from that array using
Math.random(). Check it out:
That would cause a file name to be chosen at random from the arbitrarily named
videosarray. Every time someone refreshed the page, a different video would play. Add as many file names to that array as you please. The random selection takes its cue from the
Array.lengthproperty of the
videosarray.
Math.random()returns a number between zero and one (actually, greater than or equal to zero and less than one). In turn, that value is multiplied by the number of elements in the array, which is then rounded down to the nearest integer by
Math.floor(). Finally, the result is fed into the
videosarray to retrieve one of its elements.
To Robert …
Instead of responding to a button click, you can instead respond to the end of the video itself. In either case, you’re handling an event, it’s just that the event changes. If you’re working in ActionScript 2.0, check out “How to Determine the Completion of a Flash Video (FLV) File” and let me know if that makes sense to you. Instead of the
If you’re using ActionScript 3.0, the syntax will be slightly different, so either way, let me know if you get stuck.
trace("Video complete");line of that example, you can use
gotoAndPlay()or any other instruction you like.
January 23rd, 2008 at 11:29 am
Thanks David for your insight into my problem. Seems though I only have things partially worked out.
After taking your advice I created this script:);
}
};
myVideo.attachVideo(ns);
ns.play(”culturalCenters.flv”);
It works perfectly! It does everything I want it to do. So, after copying and pasting it for a couple of my other scenes, I applied it to those scenes. Below is an example from one of those scenes:);
}
};
programVideo.attachVideo(ns);
ns.play(”programs.flv”);
The only difference with this script and the previous one is, of course, I using a different .flv file and I named my “name”.attachVideo(ns) script differently. Although when I first tried this I just kept the “name”.attachVideo(ns) script the same as the original.
But regardless, this script does not work at all. It seems that when the .flv finishes playing it doesn’t go back to Scene 1, Frame 5 like I want it to. But rather it either goes to the “Cultural Center” video like the original script does, or it will go to a preceding video, even though, again, the script has the “gotoAndPlay” script that tells it to go to Scene 1, Frame 5.
I’m at a lost as to what I’m doing wrong. Please help if you can.
Thanks in advance.
Robert
January 23rd, 2008 at 8:32 pm
Robert,
You’re using two different approaches in determining the end of your video: a) the
listener(
Object) approach and b) a
NetStream.onStatusevent handler that checks for
NetStream.Play.Stop. Of those, the
listenerapproach works in conjunction with the FLVPlayback component, and the other works with the
NetStreamclass (that is, no FLVPlayback component), so I’m not sure what mechanism you’re using to play your FLVs.
You said the first of your script blocks works, so that suggests to me that you’re using the FLVPlayback component, because the
gotoAndPlay()inside the
completehandler sounds as if it succeeds. If that’s so, your
onStatushandler may not be doing anything useful at all — again, because that approach isn’t supposed to be used with FLVPlayback.
That “name” you’re talking about needs to match the instance name you’ve given to your Video object, otherwise ActionScript isn’t speaking meaningfully to an object in that line. If you’re using the FLVPlayback component, you’ll need to give it an instance name using the Property inspector — and you’ll need to stick with
FLVPlayback-specific properties, methods, and events. If you’re using a Video object, you’ll need to give itNetStream-specific properties, methods, and events.
Does that make sense? It think you’re close, but it sounds like you’re (maybe?) confusing or combining more than one approach. In cases like this, if often helps tremendously to simplify the scenario. Save your work, start a brand new FLA file, then take small steps toward the goal(s) you have in mind, making sure you understand exactly what’s going on from step to step.
January 24th, 2008 at 6:00 pm
As a follow-up to my last message:
Following your information I created this script:
var duration:Number = 0;
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
myVideo.attachVideo(ns);
ns.play(”templinMessage.flv”);
ns.onMetaData = function(evt:Object):Void {
duration = evt.duration;
};
ns.onStatus = function(evt:Object):Void {
if (this.time > 0 && this.time >= duration) {
gotoAndPlay(”Scene 1″, 1);
delete this.onStatus;
}
}
Unfortunately, it doesn’t work. Although in playing around with it, I did manage to get the movie to stop playing as I scripted it to. But when I tried to make it to go to the scene I wanted using the “gotoAndPlay” script, it didn’t want to work.
I feel I’m close, but insufficient programming skills on my part prevents me from figuring this out.
Again, your help needed and appreciated.
Robert
January 27th, 2008 at 10:02 pm
Robert,
Check out my reply to one of your other posts (just after my comments to Kate). That should do it — but write back if you’re still stuck.
February 19th, 2008 at 9:06 am
Check my site I’m working on doing one page for all of my videos i just need to load the videos into one player and I'’m stuck with the script Its all in one folder the videos and the file with the player I need a simple> on press >load movie “life.flv” type script please help?
February 19th, 2008 at 3:05 pm
Hello! I used to implement this using an Flash AS3 document class (package) but see strange problem. When I test movie Standalone it works great even if works via AMFPHP which is at remote server and files are remote. BUT. When I put code into webpage which is at the same server as AMFPHP, it halts right after class variables init and issues no error messages. After I click it starts work. Looks like it was with IE6 and FlashPlayer 8 when you needed to “click to activate”. But that’s not that case. It also in mozilla. I do not know what to do. Is there any workaround on that issue?
February 27th, 2008 at 11:21 am
I am experiencing a weird issue. I added video playback to my flash movie to play before a large loading process takes place. I was hoping it would talk to the user while stuff is loading in the background. What happens is that it plays the first couple seconds of the movie, pauses everything while the other stuff loads, then continues the movie with the other stuff already loaded.
Anyway to separate the threads in flash?
March 17th, 2008 at 8:58 pm
To Randall …
I’m unusually behind in my blog replies, so I’m not sure my response will still be useful to you — I hope so! but it’s been so long … — to get a button to load your video, you could give your button symbol an instance name (let’s say
myButton) and then:
I’m not sure how this relates to a folder full of videos, though. Did you want the button click to progress from one video to the next? In other words, first click plays first video, second click plays second, third plays third, and so on? If so, you could put all your videos into an array and do something like this:
To Egeshi …
The syntax is a little bit different in AS3, so I hope you used actual AS3 code in your document class. The Internet Explorer “click to activate” issue wasn’t just a Flash 8 problem, but rather a problem for all Active Content, including all versions of Flash Player, QuickTime, Java applets, and so on. Are you sure this isn’t the “click to activate” issue?
To Ronnie …
Flash isn’t multithreaded, so any sort of multithreading desired has to be faked with complex timers. I’ve heard/read about hacks like that, but haven’t every tried it. I wouldn’t think your download should choked out the video, but I’m afraid I haven’t tried that either. Sorry I couldn’t be a help on this one!
March 26th, 2008 at 11:38 am
“the FLV files will not run when the application (which is an EXE) is run over a UNC path”
Brian.
JEFF, YOU SOLUTION DONT WORK… PROJECTOR DONT LOAD FLV MOVIES WITH RELATIVE PATHS. THAT SUCKS.
March 27th, 2008 at 3:31 am
hi
i hav a flv player, inside a html page,
in html page one button is there,
that button should be invisible until user click & watch half of the flv movie(suppose it reach to a particular cue point),
after reaching particular cue point,that html button should be automatically active,
any idea how to do this type of thing using javascript in flash,plz provide the code for that
April 2nd, 2008 at 11:56 am
neeraj,
I replied to your question in the cue points blog entry.
April 3rd, 2008 at 3:46 pm
Thank you so much for your useful tips and advice. I used AS2 to build a nice video player using your code. So thanks again.
But now I’m having a real problem in AS3 with flv video. I have a main movie, on whose menu are two buttons, one called “music” and the other called “films”, used to navigate to their respective sections of the site. Each button loads an external swf. The “films” swf consists of two movie clips which have streaming flv videos. These streaming videos are made possible in the usual way, by creating a video holder object, a NetStream object, and attaching them. Blah Blah.
Here’s the infuriating part: when I then click the “music” button in the main menu to navigate to that section of the site, Flash loads the external “music” swf into the same loader object as the “films” swf, and everything from the “films” swf goes away, EXCEPT for the effing video stream! It just floats there in the background. It stops playing, but I can’t get it to GO AWAY no matter what I do.
I’ve tried accessing the external “films” swf from the main menu buttons and trying to somehow get them to wipe off the video container, but it just doesn’t work. I’ve tried loading the video container for the films into the main timeline, but that doesn’t work, because the externally loaded swfs can’t find the video container. I’ve even tried making the “films” section into a hidden movie clip within the main timeline. AARGH!
Just talking about it makes me want to tear my hear out. Do you have any idea how I might fix this problem? I really would love some help.
Thank you so much!
Truly,
Michael J
April 4th, 2008 at 8:18 pm
Michael,
My first inclination is to reference the
NetStreaminstance inside the loaded SWF file and invoke
NetStream.close()on it before loading something else with the same
Loaderinstance. It sounds like you’ve already tried something like that, but have you noodled around — say, with
trace()— to make sure you’re actually connecting with the desired
NetStreaminstance?
April 24th, 2008 at 1:02 pm
is it possible to do something like so PLAYER_NAME.source = FlashVars?
April 24th, 2008 at 2:10 pm
Morgan,
There is.
Since you mentioned “source,” my hunch is that you’re referring to the
FLVPlayback.sourceproperty, which is ActionScript 3.0. If that’s it, just set your
sourceto the expression
root.loaderInfo.parameters.videoSource, where
videoSourceis a FlashVars variable of the same name.
If you’re dealing with the FLVPlayback component prior to AS3, just reference the FlashVars variable directly (no need for the
root.loaderInfo.parametersobject reference). Prior to AS3, the
sourceproperty is called
contentPath.
More detail here: “How to Retrieve FlashVars Data in ActionScript 3.0” and here “How to Tell a SWF What File(s) to Load — From the Outside” (AS2).
April 29th, 2008 at 4:09 pm
great post, great comments. i spend lot of time reading you. very useful info. thanx for sharing knowledge.
May 1st, 2008 at 12:35 pm
Such a great thread! My problem is simple, but the solution is elusive (to me).
My video is loading perfectly fine. But when it ends, it goes to black. I’d like to give the user something more interesting to look at.
How do I tell the Flash file to load a new FLV or SWF (I guess on a new level) when the video is over?
Cheers!
May 1st, 2008 at 1:43 pm
Actually, it would be even better if I could just tell my movie to play frame 2 when the video is over.
Can I do this??
May 7th, 2008 at 10:58 pm
To daniel …
Thanks! Glad to hear that. It always makes me smile when I hear that someone gets something out of these posts and replies.
To Joe …
The trick to what you’re after is determining when the video has finished playing. There’s an article on that topic here: “How to Determine the Completion of a Flash Video (FLV) File (AS2),” so see if that gets you started.
May 8th, 2008 at 10:56 am
how would i add player controls? Similar to a FLVcomponent?
May 8th, 2008 at 11:06 am
manny,
Rolling your own can potentially get complicated, but here are a few pointers:
How to Control Video (FLV) without a Component
How to Fast Forward and Rewind Video (FLV) Content
How to Build a Flash Video (FLV) Progress Bar
May 8th, 2008 at 11:18 am
Hello Dear David..
So i used the code for my magazine. I’m using a magazine system for windows application with flash. Anyway.. I used the cod but there’s a problem in the components. The code is working in my local but i wanna use an URL for the ‘ns.play(”externalVideo.flv”);’ like this;
ns.play(””); but it’s not working then the browser is guiding me to the Settings of Adobe flash site… isn’t there any solution for URL alternative?
May 8th, 2008 at 12:51 pm
David,
Thanks a million for all the help you provide on this site. It’s great to find people who help just to help. I have been trying to make html-based links that will load different videos into a player, all without a page refresh. I think I am about there with what I have read on your blog, but I am running swfobject 2 (not very well either), and I don’t know how to declare the flashvars (i guess?) to be able to send the video file name to the ns.play in the actionscript. I see how to do it in swfobject 1.x, but it seems to change. Can you maybe shed a bit of light?
I have the player there, and it will play static files, but when I replace the video url with a variable, and even have a text field show that variable, it never makes it in to the flash file. thanks very much once again.
May 8th, 2008 at 1:33 pm
actually, i have managed to get the flashvars into the player with:
var flashvars = {};
flashvars.video = (”videoname.flv);
and it will load the video that I want, but I need to be able to add this video=whatever.flv to be attached to an html link that won’t refresh the page, but rather sends that video to the netstream…
once again, thanks. I was at a roadblock before I found this site.
May 20th, 2008 at 12:21 am
Hi David,
Some time ago someone posted about playing a .flv file over UNC - did you ever work out a solution to this one?
FLVs can be very handy for internal networks but without UNC functionality the whole thing relies on drive mappings which aren’t always consistent…
Thanks for th great info
May 20th, 2008 at 11:24 pm
To Fatih …
Is your magazine something that gets distributed on CD-ROM? I ask, because the security sandbox has significantly changed in Flash Player over the years. Flash Player 7 was stricter than previous, and Flash Player 8 tightened that even more (and then 9 … you get the idea).
The long and short of it is, Flash Player (and most browsers, nowadays) are simply going to warn the user when local content — such as files on a CD-ROM — try to access the Internet. These are paranoid times.
To Mike …
Sorry I missed your question! I’m working on two books right now, which has been a real challenge to my evening routine.
I’m glad you figured it out! Good for you!
To Daniel …
I’m checking in with a colleague on this one, Robert Reinhardt (Flash Bible), and will post back if I get a definitive answer.
June 11th, 2008 at 8:09 am
I am fairly new to ActionScript 2.0 and love your blog which has helped me make my SWF skin for Flash 8 and higher.
However, I am seriously struggling with the .swf and .flv running on a web server. It executes just fine on the local and internal mapped network drives, but when I place the following files on the internal web server, only the .swf skin appears and the progress bar constantly cycles and the dynamic time display never goes past 0:00. I can’t get my FLVPlybk to run when the files are on the web server only when they are ran from my local network.
I have also tried the NetConnection and NetStream and it didn’t work. However, I don’t think my employer has Flash media Server loaded on the web server.
1.) swfobject.js
2.) MCB_20_Contract_Formation.swf
3.) MCB_20_Contract_Formation.html
4.) Contract Formation_FINAL.flv
Below is the ActionScript 2.0 from my frame 1. I have tried to include the following attachMovie but it still won’t work. I get the error “The class or interface ‘FLVPlayback’ could not be loaded.” I need some help I have worked on this for 4 days and can’t get it to work.
// Attach the container clip
var myVideo:MovieClip = this.attachMovie(”videoHolder_mc”, “myVideo”, 0);
// Set interval that waits a millisecond
var wait:Number = setInterval(this, “onWaited”, 1);
// Method executed once interval is triggered
function onWaited():Void
{
trace(”onWaited”);
// Clear the interval so it doesn’t call this method over and over
clearInterval(wait);
// Load up the video
var vp:FLVPlayback = myVideo.vp;
vp.skin = “MCB_20_Contract_Formation.swf”;
vp.contentPath = “Contract Formation_FINAL.flv”;
}
import mx.video.*;
my_FLVPlybk.backButton = my_bkbttn;
my_FLVPlybk.forwardButton = my_fwdbttn;
my_FLVPlybk.playButton = my_plybttn;
my_FLVPlybk.pauseButton = my_pausbttn;
my_FLVPlybk.stopButton = my_stopbttn;
my_FLVPlybk.seekBar = my_seekBar;
my_FLVPlybk.bufferingBar = my_buffrgbar;
my_FLVPlybk.volumeBar = my_vBar;
my_FLVPlybk.contentPath = “Contract Formation_FINAL.flv”;
June 17th, 2008 at 5:27 am
I’ve created an intro for my website using flash. I had first embeded a video that is basically a clip of someone talking. The sound after being embedded wasn’t very good at all. I then created an flv file which I’ve included using a flv playback in my flash into. The flash intro includes text that I displayed during pauses in the flv video.
My issue now with the progressive download is that I can’t match up the video with the flash.
Do you know if there is a way to start the progressive download at the beginning of the swf but actually start playing it at a particular point in the timeline?
I appreciate any help or advice.
June 19th, 2008 at 11:35 am
To Daniel …
I checked with Robert Reinhardt, and he said UNC paths have worked just fine for him. Interesting, right? So I tried a quick demo myself — loading both an MP3 file and an FLV — at at first, my test failed. But then I noticed something. In UNC paths, of course, the slashes lean back — they’re backslashes (
\) — and that’s the punctuation used for escape sequences.
If my UNC path was, say, \\Grendel\videoFile.flv, then ActionScript might actually interpret that as \Grendel\ideofile.flv. The v disappears because it is escaped by the backslash that precedes it. Only one backslash appears before the G because in the case of backslashes, a preceding backslash indicates the second backslash should be taken literally.
To correct that, you would have to use this:
\\\\Grendel\\videoFile.flv
… and in my tests, that works for code-based references. The FLVPlayback component doesn’t seem to need the extra backslashes; at least, not on my machine.
To Moneissa …
If you’re calling the FLV file from Flash Media Server, the
contentPathparameter needs a different value, because Flash Media Server uses a different protocol to deliver files (rtmp, rather than http). This difference affects both FLVPlayback and the
NetStreamapproach.
With
NetStreamover rtmp, you don’t pass
nullto the
connect()method of your
NetConnectioninstance. Instead, you pass in the path to the relevant Flash Media Server folder.
With FLVPlayback, you’ll have to precede the reference to your FLV file with
rtmp://.
Let me know if that does it for you! If not — because, for example, you’re not using Flash Media Server after all, or for whatever reason — let me know.
To Jessica …
You can start a progressive download then immediately pause playback (
Netstream.pause()or
FLVPlayback.pause()), then resume again when enough of the FLV has loaded. The
NetStream.bytesLoaded/
bytesTotaland
FLVPlayback.bytesLoaded/
bytesTotalproperties give you the values you need to determine how much of the video you want to load before proceeding.
The “How to Tell When an External SWF has Fully Loaded” article on this blog will give you a basic run-down on how to compare
bytesLoadedand
bytesTotalproperties to determine how much of an external file has loaded. You’ll probably want to pause the main timeline while you wait, and then you feel that enough of the file has come in (maybe half, maybe all?), you can send the main timeline to whatever frame you like, where another bit of keyframe code will invoke the appropriate resuming method on your
NetStreamor
FLVPlaybackinstance (invoke
pause()again for
NetStreamor
play()for
FLVPlayback).
June 19th, 2008 at 4:03 pm
Hi David:
You are a real gem of evidence that the internet can be a source of information and selfless generosity.
I know this blog was targeted specifically for run-time flv scripting, but my question is a hybrid one:
I know that I can use my existing FLVPlayback component (which currently works fine for progressive flv’s) for true Flash Video streaming, but will FLV Playback work with in conjunction with netConnect & netStream bandwidth detection script?
Greatly appreciate your valuable time and knowledge.
June 19th, 2008 at 7:09 pm
Hey David,
You. Da. Man! (and kudos to Robert Reinhardt too!).
First test worked nicely with the .flv in a .swf, and though up until now I’ve simply been using Dreamweaver to embed the .flvs into .htmls, I’ll happily change the system if my second test doesn’t work (.flv straight into .html).
Thanks heaps for the info, I googled over a whole day away trying to find a solution, and as it stands now, this is the only place on all the internets with this information written down!
Thanks again
June 19th, 2008 at 7:44 pm
Daniel,
Glad to hear that! Here’s hoping it works for you. Let me know how it goes!
June 27th, 2008 at 12:05 am
Sir,
I have read your loading external flv file, but i want to a continuous play ie in loop.
if you have any more please send it to me.
Thanks & Regards
Sumantra
July 16th, 2008 at 3:08 pm
Hi David.
Firstly, thanks for the great script, it’s helped immensely.
At first I had the same problem as a few other of the comments on here - audio, but no video. I changed the instance name from ‘videoplayer’ to ‘vid_player’ and now I get both. I have no idea if this was dumb luck - it certainly wasn’t skill - but I thought I’d share.
Thanks again.
John.
July 16th, 2008 at 3:10 pm
One more thing - did you ever solve this problem?
“Bravo, really. Quick question: is there a way to add some sort of listener in AS to see when the FLV is finished and send the playhead on to the next frame? Some kind of if/else statement?”
Thanks.
September 10th, 2008 at 7:13 pm
Hi David,
I have been enjoying reading this ongoing article on Flash Video.
I noticed you spoke about writing a article on XML and FLV.
Did this ever come about.
I am currently trying to find a way to auto load a
FLV into a swf from an XML document.
I know it can be done, I just would like to know how to do it myself.
This swf is also loading information into dynamic text boxes at the same time.
The idea is to have my CMS create an XML doc that has all the information for teh dynamic text boxes and the FLV info that will then load to the SWF Container via actionscript.
I could buy a XML Video Component from somewhere, but I would then still have the issue of having a 2 XML docs to deal with when I only want one.
September 24th, 2008 at 2:34 pm
Hi David,
I am trying to load my flv, (it’s working) send it to a frame label after it is finished playing.
the colde I am using does not go to the next frame, can you see what I am doing wrong?
The video loads and plays, but then just stops and does not proceed to frame label “alice”
thanks!
[code]
//actionscript 3.0
this.stop();
import fl.video.*;
var flvPlayer:FLVPlayback = new FLVPlayback();
addChild(flvPlayer);
flvPlayer.source = “”;
video1.addEventListener(VideoEvent.COMPLETE, onPlaybackComplete);
function onPlaybackComplete(ev: VideoEvent):void {
gotoAndStop(”alice”);
}
[/code]
September 25th, 2008 at 4:56 am
Hi,
I am new to Flash development. I have created a flash player. It was working fine with I tested locally (by double clicking the file in the folder)
I have used both
c:\Player.swf?flvurl=S1.flv
c:\Player.swf?flvurl=\\SYS02\transfer\S2.flv
both were working fine.
When I uploaded the file in IIS server (SYS01), it stops playing. It plays the
but not\\SYS02\transfer\S2.flv
Player.swf and S1.flv are in the same folder.
S2.flv is in Machine SYS02, in which SYS01 user is administrator. The shared folder is given full access to Everyone.
in SYS02 machine’s Administrative tool -> computer management -> Open session and file, i can see the S2 file being accessed whenever I access the site. But It’s not playing.
Can someone tell me why?
This is quite urgent for me.
Please mail me if you have any answer.
Many Thanks.
Cheers,
Bala
balaji.mk@gmail.com
September 25th, 2008 at 5:57 am
P.S:
I hardcoded the path in the code as
flvurl = “\\\\SYS02\\Transfer\\S2.flv”;
flv.contentPath = flvurl;
even in this scenario, it works fine when access the SWF locally (c:\player.swf), but not when accessed in Webserver ().
Any clue?
Cheers.
September 25th, 2008 at 1:20 pm
To Sumantra …
For that, you need to detect the end of the video and instruct the FLV to seek to the beginning. You can see several approaches in “How to Determine the Completion of a Flash Video (FLV) File (AS2),” but in a nutshell (for non-FLVPlayback usage) you’ll write an event handler for the
NetStream.onStatusevent.
To John …
By using
videoplayer(all lowercase), you might have been tapping, by coincidence, into a reserved word. That happens to me every now and then, it’s frustrating because generally speaking, you can name a variable whatever you like, as long as you adhere to the usual caveats (not punctuation other than
$and
_, no starting a variable name with a number, etc.).
Wow, that was a long time ago! I do remember Mark’s question, and in all this time, I’ve come to the conclusion that the
onStatusapproach — the one I just suggested to Sumantra — is the easiest way to go. (I hinted at that to Mark, way back when, but was more comfortable at the time with the solution I ended up posted to the link in my previous reply. Unlike my suggestion to Sumantra, you wouldn’t invoke
seek()in that event handler. Instead, you would invoke
MovieClip.play(),
MovieClip.gotoAndPlay(), or the like, in place of
this.seek(0).
To Joseph …
I haven’t yet written a blog tutorial on loading FLVs from XML, but the good thing about the process is, once you learn it, you can reuse the same principle for any sort of file. There’s nothing special about XML in relation to FLVs versus MP3s versus JPGs. To an extent, you could even start by listing out your FLVs in an array, then setting up a variable to count through the indexes of that array. In terms of the suggestions in my replies to John and Sumatra, you could increment that counter variable at the end of each video, like this:
Of course, doing it that way means the counter would eventually exceed the number of elements in the array. You could work around that with an
ifstatement:
For XML, it would be similar enough (and would depend, of course, on the arrangement of XML nodes you decide to use). In the case of XML, you would (somewhere along the line) have a series of, say,
<video>tags, and your counter variable would loop through those in the same way.
Does that help get you started?
To Jan …
The culprit is this line here:
video1.addEventListener(VideoEvent.COMPLETE, onPlaybackComplete);
… because you’re associating your event handler with an instance named
video1, instead of the variable name you actually give your
FLVPlaybackinstance (
flvPlayer).
To Balaji …
I’m afraid I haven’t used UNC paths in client work, so I don’t have any personal insight into why you might be seeing the issues you’re seeing. I have heard from people who do use (or who have used) UNC paths successfully, but I don’t know if they were using IIS, Apache, or some other software.
Sorry I can’t help you on this one! If there’s any way you can route that path through an HTTP address, that’s worth a shot, for sure.
September 26th, 2008 at 1:19 am
David,
Thanks for the prompt reply.
But, we require IIS to be set up in the destination machine if we want to use the http instead of UNC, that is almost not possible in my scenario.
For now, we have decided to copy the files temporarily to the local folder and clean up when done playing locally.
once again, Thanks for your prompt reply.
Cheers.
September 28th, 2008 at 2:57 am
Dear David
I want to use curPoint in my FLVPlayer in Action script 2 . Could you suggest me how can i use it as well as handle the event for the same.
Regards
Animesh
September 28th, 2008 at 7:48 pm
Animesh,
Check out this article, “How to Use Flash Video (FLV) Cue Points.” That should give you a good start, if not meet your needs entirely. Write back in a comment for that article if you have specific questions after reading and experimenting.
October 10th, 2008 at 9:43 am
Hi David,
I found your blog very interesting. In fact i have a similar kind of requirement where i want to develop an audio player in flash that can play .wax files.
The url of the file goes like this:
http://[sitename]/[filename].wax
and my code goes like this:
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
videoPlayer.attachVideo(ns);
ns.play(”http://[sitename]/[filename].wax”);
Just tried out the same code that i saw above.
This audiostream url when opened in browser, plays the song in the system default player.
But its not working.
Can you help me out?
Regards,
Nisha
October 10th, 2008 at 10:42 am
Nisha,
WAX files are just pointers — just XML documents that point to other files — and the files they point to are WMA files, which Flash doesn’t support. I suppose you could use the WAX format (that particular arbitrary XML structure) and have it point to MP3s instead. In that case, you’d have to load that WAX file as you would any other XML document and parse it to locate the actual file names.
In your
ns.play()line, you’re asking the
NetStreaminstance to play an XML file. It can’t, so it sounds like your operating system is doing the best it can with the requested file. Instead, you need that parameter to point to a Flash-compatible audio file. Actually, this shouldn’t be an audio file at all: it needs to be a video file!
If you want to build an audio player, you should be using the
Soundclass … you can omit
NetConnection,
NetStream, and
Videoaltogether.
November 3rd, 2008 at 1:09 pm
I used the NetConnectionNetStream for a video player and when I test it swf it works perfectly. All the controls, the buffer, scrubber, everything fine. When I test in a browser, everything works but the video. I can hear audio and scrub it, just can’t see it.
November 24th, 2008 at 2:36 pm
Hello, David
Im new in scripting and i used 2 buttons, so when i would click on each the video would play in component. I tried different things and nothing.
When i test it and when i click on button video doesnt play in component.
thank you
function showVid1(evt:MouseEvent):void{
vidComp.source = “flash/short_jump.flv”;
}
vid1.addEventListener(MouseEvent.CLICK,showVid1);
function showVid(evt:MouseEvent):void{
vidComp.source = “flash/odpirazapira.flv”;
}
vid2.addEventListener(MouseEvent.CLICK,showVid);
November 25th, 2008 at 10:44 am
To Cou …
Off the top of my head, I’m afraid I can’t think of a solution. Have you tried reproducing your code — just the bare essentials — in another FLA file?
To Robert …
This article is written for ActionScript 2.0 (AS2), and the code you’re showing is ActionScript 3.0 (AS3). That said, your code looks fine. Are you trying this in a FLA file configured for AS3? Is the component’s instance name
vidComp? Setting the
sourceproperty may not be enough, either. You might also have to actually instruct the component to play:
November 29th, 2008 at 7:07 pm
Hey, how could I attach the Video object dynamically to the stage?
this.attachMovie(”Video1″,”video1_video”,this.getNextHighestDepth());
am I not casting the correct type for this object?
thanks what a wonderful resource.
December 1st, 2008 at 11:58 am
I thought the best way to attack this was to create an mc called movieHolder and then have the Video object inside of that which I could call as needed, but I think I have some details that need ironing out.
December 1st, 2008 at 12:20 pm
Patrick,
Yeah, it’s a bit cumbersome in ActionScript 2.0. In AS3, you can create a
Videoinstance simply by instantiating it:
var videoPlayer:Video = new Video()
… which then eventually needs to be added to a display list:
addChild(videoPlayer)
In AS2, however, certain objects can’t be created with the
newkeyword. This list includes (at least) movie clips and videos. Your
attachMovie()workaround is definitely the way to go, but you’ll notice that Video objects can’t be given a linkage identifier, so they can’t be attached directly at runtime. In addition, the
MovieClip.attachMovie()method is specifically aimed at movie clips, which aren’t related to the
Videoclass in AS2.
As long as your
Video1asset is a movie clip symbol, you should be all right. Give that movie clip a linkage identifier (which you’ll need for
attachMovie()), and make sure that movie clip has a made-by-hand Video object inside it. In other words, create a Video object in the Library, then add it to Layer 1, frame 1 of an otherwise empty movie clip symbol. Make sure to give the Video object an instance name inside that symbol.
Then, when you attach that movie clip at runtime, you’ll be able to reference it by way of its own instance name (your second
attachMovie()parameter). Follow that instance name with a dot, then provide the instance name of the Video object, and your full object reference will work just fine.
Does that make sense?
December 1st, 2008 at 12:59 pm
absolutely made sense. stupid error on my part to forget linkage. Thanks.
December 1st, 2008 at 1:26 pm
Patrick,
Sweet! Glad to hear that. Don’t worry yourself about it, man. I forget to dot my
is and cross my
ts all the time.
December 2nd, 2008 at 3:11 am
Problem loading multiple FLV files.
Thanks for the post. It works for me for 3 or 4 instances, but I start having trouble when i have more instances. My objective is to load several, lets say 10 small FLV files into memory, so that I can quickly switch between them.
I created a simpleflv object that incorporates basically all of your code…a netconnection, netstream and video object.
Im tracing all of the NetStatus events… things work great, and then at some point, some of the NetStream objects just stop working, i dont get see any more events fired when I try to call stream.seek(0).
I hope this is not to vague - just wanted to see if you (or anyone) had encountered this problem and have any clues. I saw some other similar symptoms:
Similar at the bottom:
“buffer the video stops playing and wont resume and I don’t even seem to get any NetStatus Events or any other obvious errors or events.”
Thanks! - topher
December 2nd, 2008 at 12:34 pm
I added some online tracing code to display the netstream.bytesLoaded and netstream.bufferLength on each instance. Everything is cool till i add a 5th instance to the stage, then all instances go to 0 on all values. Its like the garbage collector kicked in or something. But even the new instance is not playing! Hmmmm.
December 3rd, 2008 at 7:26 am
Oh, sorry i didnt pay attention that is as2, but i solved problem, instead of / i put \ and it worked.
Thanks for reply, robert
January 10th, 2009 at 9:47 pm
I don’t know if this would help someone… i hope so.
//];
};
Sorry about my english… i just speak spanish
January 10th, 2009 at 9:52 pm
and this is the xml.
this will load external movies from an xml… includes buttons in order to play different movies. If you need any help to play movies “automatic” (sorry I don’t know the word in english) or need help to play just 1 movie, leave a post. (please in spanish or very simple english)
January 10th, 2009 at 9:55 pm
January 23rd, 2009 at 12:38 am
David!
Thanks for valuable information. It helped to me understand FLV’s.
March 6th, 2009 at 10:59 pm
Hi David.
I have a question. I know how to change the mouse pointer and works really good but… How do I change it just on an event? I mean I need to change the mouse pointer on rollover and it must be different according to the button. Is it possible?
May 11th, 2009 at 8:57 pm
David very very thanks for this video guide but I got problem in this script that i am using FLASH MX Pro 2004 but when I press ctrl+enter to test movie it displays blank, only showing BG color which is white , I have flash player 10 version installed … please tell what the problem is here
June 14th, 2009 at 2:13 pm
I have searched high and low for hours all over the web looking for a tutorial on preloading an flv. in actionscript 2.0 Then I came across your blog and I have begun to understand a few more things but I can sure use your help on this subject as I have a client that does not want a regular preloader but one that will load at least 50% of the flv in buffer time and display the result while the user waits for the flv to load. This would need to be built with a text that will flash repeating until the correct set amount of the video loads. One of the places I’m stuck is which tut do I follow as I already have the flv component on the stage with a skin for stop and playback. As I wait for your answer I’ll have a look and read all your tutes on this and try to figure out.
I would have thought that just adding the buffer bar component and a little AS would have done the trick but I guess I’m way off here.
June 19th, 2009 at 2:20 pm
hi all, well i found the following code (AS3) working pretty well…
var videoPlayer:Video = new Video();
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
ns.play(”external_flv.flv”);
videoPlayer.attachNetStream(ns);
addChild(videoPlayer);
am no expert… found this by hit and trial..
i just had a question that…
how do i adjust the flash player height and width dynamically according to the external flv file?? as of now the flash player has static dimensions!!! do i need to use the scale movie property??
June 22nd, 2009 at 11:37 am
This code, to load FLV’s from XML works great, but it is on a button press. I really need to have this work automatically (not on button press). I have had no luck finding out how to do this one the web. Any help would be great.
//];
};
June 22nd, 2009 at 11:41 am
my biggest thing is that i can’t use netstream and everything is setup around a the flvplayback component (because i am using actionscript cuepoints in AS2) and netstream doesn’t support this. My client now wants all files remotely loaded through .xml. I have each video in loaded into an individual .swf and from the main wrapper, i just need make them accessible from .xml. | http://www.quip.net/blog/2006/flash/how-to-load-external-video | crawl-002 | refinedweb | 33,803 | 72.97 |
I am just an idiot, but thats my opinion. For those with MSPGCC compilers, we have a more difficult time finding code examples, and many of the code examples given either don’ explain very well (cryptic Coding, un-commented code) or they are for the CCS or IAR, and they dont use the same syntax as the MSPGCC compiler. So here is how to create an interrupt handler for non-PUC/POR interrupts.
I will not go into interrupt vector masking, that is beyond me at this moment, but im not saying that i wont cover it later on, once i understand why you would want to mask it…..
So lets start at what headers and other setup items you need before, creating the interrupt handler.
First the signal.h has to be included into your code.
#include<signal.h>
this will give you access to the special function of
interrupt(VECTOR ) service_routine (void) {/*interrupt code*/ }
this is the same as
#pragma vector=WDT_VECTOR
__interrupt void watchdog_timer(void){ }
These are the Defined vectors for interrupts right from the header files.(mspgcc headers)
#define PORT1_VECTOR 4 /* 0xFFE4 Port 1 */
#define PORT2_VECTOR 6 /* 0xFFE6 Port 2 */
#define USI_VECTOR 8 /* 0xFFE8 USI */
#define ADC10_VECTOR 10 /* 0xFFEA ADC10 */
#define TIMERA1_VECTOR 16 /* 0xFFF0 Timer A CC1-2, TA */
#define TIMERA0_VECTOR 18 /* 0xFFF2 Timer A CC0 */
#define WDT_VECTOR 20 /* 0xFFF4 Watchdog Timer */
#define NMI_VECTOR 28 /* 0xFFFC Non-maskable */
all the interrupts should be self expainatory, vector = the source of the interrupt.
since now we have all the basics we can now right a small program that uses interrupt, we will just create a small WDT interval timer.
/*WDT interval timer- code based on msp430 examples*/
//compiler=mspgcc
#include<msp430x22x2.h>
#include<signal.h> //interrupt service routine
#include <io.h> //usually included on msp430 header, but for sfr register access.
void main(void) {
WDTCTL = WDT_MDLY_32; //~30mS intervals
P1DIR |=BIT1;
IE1 |= WDTIE; //enable interrupt
_BIS_SR(LPM0_bits + GIE); //not low power mode and enable interrupts
}//end of main
//interrupt service routine
interrupt(WDT_VECTOR) watchdog_timer(void)
{
P1OUT ^= BIT1;
}//end of interrupt
this should give you a good start on your Interrupts but there is still one thing that you may need. Changing the power modes when a interrupt is being serviced, the power mode will revert back to the power mode that it was in when the interrupt was called.
There are 2 functions that we can use to clear or set power modes while in an interrupt.
First one is to set the mode on exit of the routine, this is done by changing the copy of the status register that is saved to the stack.
_BIS_SR_IRQ( ... )
you would use this the same way you would use the _BIS_SR(…)
The second one will clear the bits you select
_BIC_SR_IRQ(...) same usage as the other, except it will just clear the bits not modify them.
***the use of _BIx_SR_IRQ() should only be used in an interrupt service request, the compiler will give you a warning but will produce the correct code if you use it anywhere else.***
****remember to enable Interrupts by using BIS_SR(GIE) or eint()****
Edit 6-23-2011
MSPGCC Uniarch branch of mspgcc has been released, It supports newer chips like the msp430G2453 (the newer 20pin DIPs) This is an initiative to unify the current branches of mspgcc. Interrupts for this version is slightly different. Once I test it or get confirmation from another user I will post the correct format for uniarch branch……but what would be better would be unify the branches so we don’t have so much confusion with these version discrepancies and nuances of the trees.
As of right now uniarch is still being worked on and there and is not fully recommended unless you need support for the newer 20pin Dips (G2x53 G2x52). Please don’t let my opinion dissuade your choice of compiler, mspgcc works great for me but uniarch may work better for you.
Thank you Tissit for your Comment
“In current gcc, you can (should) include msp430.c instead of the specific header and use the -m switches (in a Makefile) to tell the compiler which chip you’re using. It will find the right headers automatically. “
If I forget something let me know and I will update | http://justinstech.org/index.php/category/programing/page/2/ | CC-MAIN-2017-26 | refinedweb | 710 | 64.64 |
Quickstart: Printing from your app (XAML)
This Quickstart shows the simplest way to add print functionality to your Windows Store app using C++, C#, or Visual Basic.
Watch this brief video for an overview of the process.
At a high level, to print from your Windows Store app using C++, C#, or Visual Basic,. For more info about formatting your app's content for printing, see the Summary and next steps.
Prerequisites
- You must be familiar with C# or Visual Basic, XAML,.
Instructions
1. Open the app's source code for editing
This procedure describes how to open the Print Sample sample app. If you are using your own app, open it in Visual Studio and skip to the next step.
Important The code examples shown in this Quickstart refer to the Print Sample sample app. You might need to add more code from the sample app to use these examples in your own app.
- Open the Windows Store app Print sample and download the C# example to your computer.
- In Visual Studio, click File > Open Project and go to the folder that contains the solution file of the sample app that you downloaded in the previous step.
- Select the PrintSample solution file and click Open. PrintSample app.
- If the app runs without error, return to Visual Studio and click Debug > Stop Debugging.
3..
Tip If you need to support printing from more than one page in your app, you can put this print code in a common base class and have your app pages derive from it. For an example of how to do this, see the
BasePrintPage class in the Print Sample sample app.
Note Only the screen that is displayed to the user can be registered for printing. If one screen of your app has registered for printing, it must unregister for printing when it exits. If it is replaced by another screen, the next screen must register for a new Print contract when it opens.
First, declare the PrintManager and PrintDocument. The PrintManager type is in the Windows.Graphics.Printing namespace along with types to support other Windows printing functionality. The PrintDocument type is in the Windows.UI.Xaml.Printing namespace along with other types that support preparing XAML content for printing. You can make it easier to write your printing code by adding the following using or Imports statements to your page.
Create the registration method to initialize the properties your app will require for printing.
In the Print Sample sample app, this method is in the base class that is used by the different displays of the app.
protected virtual void RegisterForPrinting() { // Create the PrintDocument. printDocument = new PrintDocument(); // Save the DocumentSource. printDocumentSource = printDocument.DocumentSource; // Add an event handler which creates preview pages. printDocument.Paginate += CreatePrintPreviewPages; // Add an event handler which provides a specified preview page. printDocument.GetPreviewPage += GetPrintPreviewPage; // Add an event handler which provides all final print pages. printDocument.AddPages += AddPrintPages; // Create a PrintManager and add a handler for printing initialization. PrintManager printMan = PrintManager.GetForCurrentView(); printMan.PrintTaskRequested += PrintTaskRequested; // Initialize print content for this scenario PreparePrintContent(); }
When the user goes to the page, register for printing by creating instances of PrintManager and PrintDocument and registering handlers for their printing events.
When the user leaves the page, disconnect the printing event handlers. If you have a multiple-page app and don't disconnect printing, an exception is thrown when the user leaves the page and then comes back to it.
4. Format your app's content for printing
Windows printing raises events when the user wants to print and when it wants the app to provide the formatted content to print.
When a user selects a printer on the Devices charm, the PrintTaskRequested event is raised. The PrintTaskRequested event handler shown in this step creates a PrintTask by calling the PrintTaskRequest.CreatePrintTask method and passes the title for the print page and the name of a PrintTaskSourceRequestedHandler delegate. Notice that in this example, the PrintTaskSourceRequestedHandler is defined inline. The PrintTaskSourceRequestedHandler provides the formatted content for printing and is described later.
In this example, a completion handler is also defined to catch errors. It's a good idea to handle completion events because then your app can let the user know if an error occurred and provide possible solutions. Likewise, your app could use the completion event to indicate subsequent steps for the user to take after the print job is successful.
protected virtual void PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs e) { PrintTask printTask = null; printTask = e.Request.CreatePrintTask("C# Printing SDK Sample", sourceRequested => { //.SetSource(printDocumentSource); }); }
After the print task is created, the PrintManager requests a collection of print pages to show in the print preview UI by raising the Paginate event. In the Paginate event handler, you create the pages to show in the print preview UI and to send to the printer. The code you use to prepare your app's content for printing is specific to your app and the content you print.
This example of a Paginate event handler is taken from the Print sample sample app. Refer to the sample app's source code to see how it formats its content for printing.
protected virtual void CreatePrintPreviewPages(object sender, PaginateEventArgs e) { // Clear the cache of preview pages printPreviewPages.Clear(); // Clear the printing root of preview pages PrintingRoot.Children.Clear(); // This variable keeps track of the last RichTextBlockOverflow element that was added to a page which will be printed RichTextBlockOverflow lastRTBOOnPage; // Get the PrintTaskOptions PrintTaskOptions printingOptions = ((PrintTaskOptions)e.PrintTaskOptions); // Get the page description to deterimine how big the page is PrintPageDescription pageDescription = printingOptions.GetPageDescription(0); // We know there is at least one page to be printed. passing null as the first parameter to // AddOnePrintPreviewPage tells the function to add the first page. lastRTBOOnPage = AddOnePrintPreviewPage(null, pageDescription); // We know there are more pages to be added as long as the last RichTextBoxOverflow added to a print preview // page has extra content while (lastRTBOOnPage.HasOverflowContent && lastRTBOOnPage.Visibility == Windows.UI.Xaml.Visibility.Visible) { lastRTBOOnPage = AddOnePrintPreviewPage(lastRTBOOnPage, pageDescription); } if (pagesCreated != null) { pagesCreated.Invoke(printPreviewPages, null); } PrintDocument printDoc = (PrintDocument)sender; // Report the number of preview pages created printDoc.SetPreviewPageCount(printPreviewPages.Count, PreviewPageCountType.Intermediate); }
The preceding example shows a very simple print scenario. Only one page is created, and the content is scaled to fill all of the available area. Other topics in this section show examples of more complex printing scenarios.
In the AddPages event handler, you add pages from the page collection to the PrintDocument object to be sent to the printer. If a user specifies particular pages or a range of pages to print, you use that information here to add only the pages that will actually be sent to the printer.
This example of an AddPages event handler is taken from the Print sample sample app.
protected virtual void AddPrintPages(object sender, AddPagesEventArgs e) { // Loop over all of the preview pages and add each one to add each page to be printied for (int i = 0; i < printPreviewPages.Count; i++) { // We should have all pages ready at this point... printDocument.AddPage(printPreviewPages[i]); } PrintDocument printDoc = (PrintDocument)sender; // Indicate that all of the print pages have been provided printDoc.AddPagesComplete(); }
Summary and next steps
In this Quickstart, you added Windows printing to your app, without modifying how users interact with your app.
In the next tutorial, How to print using an in-app print button, you will invoke print functionality from a Windows Store app using C++, C#, or Visual Basic with a print button in the app. From there, you can explore some more advanced printing functions.
Your app can give the user even more print options, as How to change standard options in the print preview UI and How to add custom options to the print preview UI demonstrate.
And for more printing scenarios that are available in Windows Store apps, see the Windows Store app Print sample sample app.
Related topics | http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh465204 | CC-MAIN-2014-23 | refinedweb | 1,316 | 54.42 |
Elvish Shell 2018-11-17T16:17:27Z Elvish 0.12 Release Notes 2018-11-08T00:22:20Z Qi Xiao <p>Version 0.12 has been released six months after 0.11, bringing many new features and bugfixes.</p> <p>As usual, prebuilt binaries can be found in <a href="../get">get</a>.</p> <h1 id="breaking-changes">Breaking Changes</h1> <ul> <li><p>The <code>shared:</code> namespace has been removed.</p></li> <li><p>Line continuations now use backslashes instead of backquotes, in line with POSIX syntax.</p></li> <li><p>The <code>resolve</code> builtin now returns a string.</p></li> <li><p>The variables <code>$edit:loc-{pinned,hidden}</code> have been moved into the <code>edit:location:</code> namespace, now <code>$edit:location:{pinned,hidden}</code></p></li> <li><p>The variable <code>$edit:arg-completer</code> has been moved to <code>$edit:completion:arg-completer</code>.</p></li> </ul> <h1 id="notable-fixes-and-enhancements">Notable Fixes and Enhancements</h1> <ul> <li><p>The <a href="../ref/epm.html">Elvish package manager</a> has landed (thanks to @zzamboni!).</p></li> <li><p>A <code>str:</code> module has been added (<a href="">#576</a>).</p></li> <li><p>Styling of the web interface (<code>elvish -web</code>) has been reworked, now featuring a dark theme as well as a light theme.</p></li> <li><p>Namespaces can now be accessed by as variables with a trailing <code>:</code> in the name (e.g. the <code>edit:</code> namespace variable can be accessed as <code>$edit:</code>). These variables can be indexed like maps (<a href="">#492</a>, (<a href="">#631</a>)).</p></li> <li><p>Support for urxvt-style key sequences has been improved (<a href="">#579</a>).</p></li> <li><p>Numbers can now be used as normal variable names (e.g. <code>$1</code>).</p></li> <li><p>The interactive namespace can now be built dynamically by assigning to the <code>$-exports-</code> variable in <code>rc.elv</code> (<a href="">#613</a>).</p></li> <li><p>Closures can now be introspected (<a href="">#560</a>, <a href="">#617</a>).</p></li> <li><p>The variable for customizing matchers in completion mode has graduated from <code>$edit:-matcher</code> to <code>$edit:completion:matcher</code>.</p></li> <li><p>The <code>joins</code> command no longer ignores leading empty values (<a href="">#616</a>).</p></li> <li><p>The <code>while</code> special command no longer swallows exceptions (<a href="">#615</a>).</p></li> <li><p>The <code>finally</code> block of the <code>try</code> special command no longer swallows exceptions (<a href="">#619</a>).</p></li> <li><p>A set of builtin commands for manipulating environment variables - <code>has-env</code>, <code>get-env</code>, <code>set-env</code>, <code>unset-env</code> - has been added.</p></li> <li><p>The prompts are now rendered asynchronously. The appearance of <a href="../ref/edit.html#stale-prompt">stale prompts</a> can be customized.</p></li> <li><p>Experimental support for customizing the <a href="">eagerness of prompts</a>.</p></li> <li><p>Elvish now writes a <code>\r</code> to the terminal before suspending the editor (<a href="">#629</a>; thanks to @krader1961 for the analysis!).</p></li> <li><p>New <code>edit:history:fast-forward</code> command to import command history after the current session started.</p></li> <li><p>The completion mode no longer completes the longest common prefix (<a href="">#637</a>).</p></li> <li><p>New <code>store:del-dir</code> command for deleting directory history.</p></li> <li><p>Add chdir hooks <a href="../ref/builtin.html#before-chdir"><code>$before-chdir</code></a> and <a href="../ref/builtin.html#after-chdir"><code>$after-chdir</code></a>.</p></li> <li><p>Location mode now supports the notion of workspaces (<a href="">#643</a>).</p></li> <li><p>The output of <code>elvish -buildinfo -json</code> is now actually vaid JSON (<a href="">#682</a>).</p></li> <li><p>New <a href="../ref/builtin.html#styled"><code>styled</code></a> and <a href="../ref/builtin.html#styled-segment"><code>styled-segment</code></a> commands (thanks to @fehnomenal!) (<a href="">#520</a>, <a href="">#674</a>).</p></li> <li><p>New builtin <code>$notify-bg-job-success</code> variable for suppressing notification of the success of background jobs (thanks to @iwoloschin!) (<a href="">#689</a>).</p></li> <li><p>New builtin <code>$num-bg-jobs</code> variable for tracking number of background jobs (<a href="">#692</a>).</p></li> <li><p>The <code>edit:complete-getopt</code> command now supports supplying a description for arguments of options (thanks to @zzamboni!) (<a href="">#693</a>).</p></li> <li><p>Complex candidates built with <code>edit:complex-candidate</code> are now indexable (thanks to @zzamboni!) (<a href="">#691</a>).</p></li> <li><p>New <code>-norc</code> flag for skipping <code>rc.elv</code> (thanks to @iwoloschin!) (<a href="">#707</a>).</p></li> <li><p>Elvish now guards against commands messing up terminal attributes (<a href="">#706</a>).</p></li> </ul> Elvish 0.11 Release Notes 2018-11-08T00:22:20Z Qi Xiao <p>Version 0.11 has been released four months after 0.10, bringing many new features and bugfixes. There is no newsletter accompanying this release (instead, there is a <a href="">tweet</a>).</p> <p>As usual, prebuilt binaries can be found in <a href="../get/">get</a>.</p> <h1 id="breaking-changes">Breaking Changes</h1> <ul> <li><p>The syntax for importing modules in nested directories with <code>use</code> has changed.</p> <p>Previously, <code>use</code> accepts colon-delimited components, and replace the colons with slashes to derive the path: for instance, <code>use a:b:c</code> imports the module <code>a/b/c.elv</code> under <code>~/.elvish/lib</code>, under the namespace <code>a:b:c</code>. Now, to import this module, you should use <code>use a/b/c</code> instead, and it will import the same file under the namespace <code>c</code>.</p> <p>It is not yet possible to rename the module when importing it; this makes it hard to import modules with the same filename living under different directories and will be addressed in the next version.</p> <p>The current implementation of <code>use</code> still supports the use of colons to affect the name under which the module is imported: for instance, <code>use a/b:c</code> imports the file <code>a/b/c.elv</code> under the name <code>b:c</code>. However, this feature should be considered undocumented and will be removed in the next version.</p></li> <li><p>Module imports are now scoped lexically, akin to how variables are scoped. For instance, <code>use re</code> in one module does not affect other files; neither does <code>{ use re }</code> affect the outer scope.</p></li> <li><p>The variable a function <code>func</code> maps to is now <code>$func~</code> instead of <code>$&func</code>. The ampersand <code>&</code> is now no longer allowed in variable names, while the tilde <code>~</code> is. A <a href="">tool</a> has been provided to rewrite old code.</p></li> <li><p>Strings are no longer callable (<a href="">#552</a>). A new <a href="../ref/builtin.html#external">external</a> has been added to support calling external programs dynamically.</p></li> <li><p>It is now forbidden to assign non-strings to environment variables. For instance, <code>E:X = []</code> used to assign the environment variable <code>X</code> the string value <code>"[]"</code>; now it causes an exception.</p></li> </ul> <h1 id="notable-fixes-and-enhancements">Notable Fixes and Enhancements</h1> <h2 id="supported-platforms">Supported Platforms</h2> <ul> <li><p>Support for Go 1.7 has been dropped, and support for Go 1.9 has been added.</p></li> <li><p>Elvish now has experimental support for Windows 10. Terminal and filesystem features may be buggy. <a href="../get/">Prebuilt binaries</a> for Windows are also available.</p></li> <li><p>Prebuilt binaries for AMD64 and ARM64 architectures on Linux are provided.</p></li> </ul> <h2 id="language">Language</h2> <ul> <li><p>It is now possible to <code>use</code> relative paths. For instance, in module <code>a/b/c/foo.elv</code> (under <code>~/.elvish/lib</code>), <code>use ./bar</code> is the same as <code>use a/b/c/bar</code>, and <code>use ../bar</code> is the same as <code>use a/b/bar</code>. The resolved path must not escape the <code>lib</code> directory; for instance, <code>use ../bar</code> from <code>~/.elvish/lib/foo.elv</code> will throw cause a compilation error.</p></li> <li><p>A new builtin variable, <a href="../ref/builtin.html#value-out-indicator"><code>$value-out-indicator</code></a>, can now be used to customize the marker for value outputs (<a href="">#473</a>).</p></li> <li><p>A new builtin command <a href="../ref/builtin.html#to-string"><code>to-string</code></a> has been added.</p></li> <li><p>Special forms like <code>if</code> now works correctly with redirections and temporary assignments (<a href="">#486</a>).</p></li> <li><p>A primitive for running functions in parallel, <a href="../ref/builtin.html#run-parallel"><code>run-parellel</code></a>, has been added (<a href="">#485</a>).</p></li> <li><p>The <a href="../ref/builtin.html#splits"><code>splits</code></a> builtin now supports a <code>&max</code> option.</p></li> <li><p>A new <a href="../ref/builtin.html#src"><code>src</code></a> builtin can now be used to get information about the current source.</p></li> <li><p>A new builtin variable <a href="../ref/builtin.html#args"><code>$args</code></a> can now be used to access command-line arguments.</p></li> <li><p>The <a href="../ref/language.html#deleting-variable-or-element-del"><code>del</code></a> special command can now delete map elements (<a href="">#79</a>).</p></li> </ul> <h2 id="editor">Editor</h2> <ul> <li><p>A maximum wait time can be specified with <a href="../ref/edit.html#edit-prompts-max-wait">$edit:-prompts-max-wait</a> to prevent slow prompt functions from blocking UI updates (<a href="">#482</a>).</p></li> <li><p>Execution of hook functions are now correctly isolated (<a href="">#515</a>).</p></li> <li><p>A new <a href="../ref/edit.html#matcher">matcher</a> <code>edit:match-substr</code> has been added.</p></li> <li><p>The editor is now able to handle Alt-modified function keys in more terminals (<a href="">#181</a>).</p></li> <li><p>Location mode now always hides the current directory (<a href="">#531</a>).</p></li> <li><p>Ctrl-H is now treated the same as Backspace (<a href="">#539</a>).</p></li> <li><p>It is now possible to scroll file previews with <span class="key">Alt-Up</span> and <span class="key">Alt-Down</span>.</p></li> <li><p>The height the editor can take up can now be restricted with <a href="../ref/edit.html#editmax-height"><code>$edit:max-height</code></a>.</p></li> </ul> <h2 id="misc">Misc</h2> <ul> <li><p>The Elvish command supports a new <code>-buildinfo</code> flag, which causes Elvish to print out the version and builder of the binary and exit. Another <code>-json</code> flag has also been introduced; when present, it causes <code>-buildinfo</code> to print out a JSON object.</p></li> <li><p>Elvish now handles SIGHUP by relaying it to the entire process group (<a href="">#494</a>).</p></li> <li><p>The daemon now detects the path of the Elvish executable more reliabily, notably when Elvish is used as login shell (<a href="">#496</a>).</p></li> <li><p>When an exception is thrown and the traceback contains only one entry, the traceback is now shown more compactly.</p> <p>Before:</p> <pre><code>~> <span class="sgr-32">fail</span><span class=""> x<br></span>Exception: x<br>Traceback:<br> [interactive], line 1:<br> fail x<br></code></pre> <p>Now:</p> <pre><code>~> <span class="sgr-32">fail</span><span class=""> x<br></span>Exception: x<br>[tty], line 1: fail x<br></code></pre> </li> </ul> Elvish 0.10 Release Notes 2018-11-05T00:33:48Z Qi Xiao <p>Version 0.10 has been released two and a half months after 0.9, bringing many new features and enhancements. The <a href="newsletter-sep-2017.html">second issue</a> of Elvish Newsletter accompanies this release.</p> <h1 id="breaking-changes">Breaking changes</h1> <ul> <li><p>If you are upgrading from an earlier version, Elvish will complain that your database is not valid. This is because Elvish now uses BoltDB for storage. A <a href="">database migration tool</a> is available.</p></li> <li><p>Breaking changes to the editor API:</p> <ul> <li><p>The <code>$edit:completer</code> map is now known as <code>$edit:arg-completer</code>.</p></li> <li><p>The keybinding API has been changed (again). Keybindings for different now live in their own subnamespaces. For instance, keybindings for insert mode used to be <code>edit:binding[insert]</code> but is now <code>edit:insert:binding</code>.</p></li> <li><p>Module names of some editor modes have also been changed for consistency. The completion mode now uses the <code>edit:completion</code> module (used to be <code>edit:compl</code>). Location mode: <code>edit:location</code>; navigation mode: <code>edit:navigation</code>.</p></li> <li><p>Byte output from prompts now preserve newlines. For instance, if you have <code>edit:prompt = { echo haha }</code>, you will now have a trailing newline in the prompt, making your command appear on the next line. To fix this, simple replace <code>echo</code> with <code>print</code>, which does not print a trailing newline. (<a href="">#354</a>)</p></li> </ul></li> <li><p>Breaking changes to the language core:</p> <ul> <li><p>Due to the switch to persistent data structures, assignments of maps now behave as if they copy the entire container. See the section in <a href="../learn/unique-semantics.html">some unique semantics</a> for an explanation.</p></li> <li><p>The implicit <code>$args</code> variable is gone, as well as its friends: positional variables <code>$0</code>, <code>$1</code>, …, and the special <code>$@</code> shorthand for <code>$@args</code>. Lambdas defined without argument list (<code>{ some code }</code>) now behave as if they have an empty argument list. (<a href="">#397</a>)</p> <p>Old lambdas that rely on <code>$args</code> or its friends now must declare their arguments explicitly. For instance, <code>fn ls { e:ls --color=auto $@ }</code> needs to be rewritten to <code>fn ls [@a]{ e:ls --color=auto $@a }</code>.</p></li> <li><p>Support for using backquotes for output capture (e.g. <code>echo uname is `uname`</code>) has been removed. Use parentheses instead (e.g. <code>echo uname is (uname)</code>).</p></li> <li><p>Backquotes are repurposed for line continuation. A backquote followed by a newline is equivalent to a space. (<a href="">#417</a>)</p></li> </ul></li> <li><p>The signature of the <code>splits</code> builtin has been changed. The separator used to be an option <code>sep</code> but is now the first argument. For instance, <code>splits &sep=: a:b:c</code> should now be written as <code>splits : a:b:c</code>.</p></li> </ul> <h1 id="notable-fixes-and-enhancements">Notable fixes and enhancements</h1> <ul> <li><p>Thanks to the BoltDB migration, Elvish is now a pure Go project! This allows for fully statically linked executables and easy cross compilation. (<a href="">#377</a>)</p></li> <li><p>Enhancements to the language core:</p> <ul> <li><p>It is now possible to define options when declaring functions (<a href="">#82</a>).</p></li> <li><p>Interrupting Elvish code with Ctrl-C now works more reliably (<a href="">#388</a>).</p></li> <li><p>Piping value outputs into a command that does not read the value input (e.g. <code>range 1000 | echo haha</code>) no longer hangs (<a href="">#389</a>).</p></li> </ul></li> <li><p>New builtins functions and variables (documented in the <a href="../ref/builtin.html">builtin module reference</a>):</p> <ul> <li><p>New <code>assoc</code> and <code>dissoc</code> builtin that outputs modified versions of container types.</p></li> <li><p>New <code>keys</code>, <code>has-keys</code> and <code>has-values</code> builtins (<a href="">#432</a>, <a href="">#398</a>, <a href="">#407</a>).</p></li> <li><p>A new blackhole variable <code>$_</code> has been added. (<a href="">#401</a>)</p></li> <li><p>New <code>replaces</code> builtin for replacing strings. (<a href="">#463</a>)</p></li> <li><p>New <code>not-eq</code> builtin for inequality.</p></li> <li><p>New <code>drop</code> builtin, mirroring <code>take</code>.</p></li> </ul></li> <li><p>Enhancements to the editor:</p> <ul> <li><p>Matching algorithm used in completion is now programmable with <code>$edit:-matcher</code> (<a href="">#430</a>); see <a href="../ref/edit.html">documentation</a>.</p></li> <li><p>Elvish can now able to complete arguments with variables. For instance, if you have a directory with <code>a.mp4</code> and <code>a.txt</code>, and variable <code>$foo</code> containing <code>a</code>, <code>echo $foo.<Tab></code> now works (<a href="">#446</a>). However, the completion will expand <code>$foo</code> into <code>a</code>, which is not intended (<a href="">#474</a>).</p></li> <li><p>It is now possible to manipulate the cursor position using the experimental <code>$edit:-dot</code> variable (<a href="">415</a>).</p></li> <li><p>The default prompt now replaces <code>></code> with a red <code>#</code> when uid = 0.</p></li> </ul></li> <li><p>An experimental custom listing mode (known as “narrow mode” for now) has been introduced and can be started with <code>edit:-narrow-read</code>. This means that it is now to implement listing modes entirely in Elvish script.</p> <p>Experimental re-implementations of the several standard listing modes (location mode, history lising mode and lastcmd mode) are provided as the bundled <code>narrow</code> module. Read <a href="">its source in eval/narrow.elv</a> for more details.</p></li> <li><p>Improvements to the daemon:</p> <ul> <li><p>The daemon now quits automatically when all Elvish sessions are closed. (<a href="">#419</a>)</p></li> <li><p>The daemon can now spawned be correctly when Elvish is not installed in <code>PATH</code>.</p></li> </ul></li> <li><p>Elvish no longer quits on SIGQUIT (usually triggered by <code>Ctrl-\</code>), matching the behavior of other shells. It still prints a stack trace though, which can be useful for debugging. (<a href="">#411</a>)</p></li> <li><p>A <code>-compileonly</code> flag for the Elvish binary is added. It makes Elvish compiles a script (in memory) but does not execute it. It can be used for checking the well-formedness of programs and is useful in editor plugins. (<a href="">#458</a>)</p></li> </ul> Elvish Newsletter, Sep 2017 Issue 2018-11-05T00:33:48Z Qi Xiao <p>Welcome to the second issue of Elvish Newsletter!</p> <p>Elvish is a shell that seeks to combine a full-fledged programming language with a friendly user interface. This newsletter is a summary of its progress and future plans.</p> <h1 id="release-of-0.10-version">Release of 0.10 Version</h1> <p.</p> <p.</p> <p>Maps (<code>[&k=v &k2=v2]</code>) <a href="../learn/unique-semantics.html">unique semantics</a> page.</p> <p>For a complete list of changes, see the <a href="0.10-release-notes.html">release notes</a>.</p> <h1 id="community">Community</h1> <ul> <li><p>We now have an official list of awesome unofficial Elvish libraries: <a href="">elves/awesome-elvish</a>. Among others, we now have at least two very advanced prompt themes, chain.elv from @zzamboni and powerline.elv from @muesli :)</p></li> <li><p>Diego Zamboni (@zzamboni), the author of chain.elv, has written very passionately on Elvish: <a href="">Elvish, an awesome Unix shell</a>.</p></li> <li><p>Patrick Callahan has given an awesome talk on <a href="">Delightful Command-Line Experiences</a>, featuring Elvish as a “very lively, ambitious shell”.</p></li> <li><p>Elvish is now <a href="">packaged</a> in Debian.</p></li> <li><p>The number of followers to <a href="">@RealElvishShell</a> has grown to 23.</p></li> </ul> <h1 id="plans">Plans</h1> <p>The mid-term remains the same as in the <a href="newsletter-july-2017.html">previous issue</a>: stabilizing the language core and enhancing usability of the user interface.</p> <p>The short-term plan is captured in the <a href="">milestone</a> for the 0.11 version. Among other things, 0.11 is expected to ship with <code>epm</code>, <a href="">the standard package manager</a> for Elvish, and a more responsive interface by running <a href="">prompts</a> and <a href="">completions</a> asynchronously. Stay very tuned.</p> <h1 id="conclusions">Conclusions</h1> <p>In the last newsletter, I predicted that we will be featuring <em>Elvish for Python Users</em> and <em>Tetris in Your Shell</em> in a future newsletter. It seems we are getting close to that pretty steadily.</p> <p>Have fun with Elvish!</p> <p>- xiaq</p> Elvish Newsletter, July 2017 Issue 2018-11-05T00:33:48Z Qi Xiao <p>Welcome to the first issue of Elvish Newsletter!</p> <p>Elvish is a shell that seeks to combine a full-fledged programming language with a friendly user interface. This newsletter is a summary of its progress and future plans.</p> <h1 id="status-updates">Status Updates</h1> <ul> <li><p>18 pull requests to the <a href="">main repo</a> have been merged in the past four weeks. Among them 13 were made by @xofyargs, and the rest by @myfreeweb, @jiujieti, @HeavyHorst, @silvasur and @ALSchwalm. The <a href="">website repo</a> has also merged 3 pull reqeusts from @bengesoff, @zhsj and @silvasur. Many kudos!</p></li> <li><p>The <a href="">website</a> was <a href="../blog/live.html">officially live</a> on 3 July. Although the initial <a href="">submission</a> to HN was a failure, Elvish gained <a href="">quite</a> <a href="">some</a> <a href="">popularity</a> on Reddit, and <a href="">another</a> HN submission made to the homepage. These, among others, have brought 40k unique visitors to the website, totalling 340k HTTP requests. Thank you Internet :)</p></li> <li><p>A lot of discussions have happened over the IM channels and the issue tracker, and it has become necessary to better document the current status of Elvish and organize the development effort, and this newsletter is part of the response.</p> <p>There is no fixed schedule yet, but the current plan is to publish newsletters roughly every month. Preview releases of Elvish, which used to happen quite arbitrarily, will also be done to coincide with the publication of newsletters.</p></li> <li><p>There are now IM channels for developers, see below for details.</p></li> </ul> <h1 id="short-term-and-mid-term-plans">Short-Term and Mid-Term Plans</h1> <p>The next preview release will be 0.10, and there is now a <a href="">milestone</a> for it, a list of issues considered vital for the release. If you would like to contribute, you are more than welcome to pick an issue from that list, although you are also more than welcome to pick just any issue.</p> <p>Aside from the short-term goal of releasing 0.10, here are the current mid-term focus areas of Elvish development:</p> <ul> <li><p>Stabilizing the language core.</p> <p>The core of Elvish is still pretty immature, and it is definitely not as usable as any other dynamic language, say Python or Clojure. Among others, the 0.10 milestone now plans changes to the implementation of maps (<a href="">#414</a>), a new semantics of element assignment (<a href="">#422</a>) and enhanced syntax for function definition (<a href="">#82</a> and <a href="">#397</a>). You probably wouldn’t expect such fundamental changes in a mature language :)</p> <p>A stable language core is a prerequisite for a 1.0 release. Elvish 1.x will maintain backwards compatibility with code written for earlier 1.x versions.</p></li> <li><p>Enhance usability of the user interface, and provide basic programmability.</p> <p>The goal is to build a fully programmable user interface, and there are a lot to be done. Among others, the 0.10 milestone plans to support manipulating the cursor (<a href="">#415</a>) programmatically, scrolling of previews in navigation mode previews (<a href="">#381</a>), and invoking external editors for editing code (<a href="">#393</a>).</p> <p.</p></li> </ul> <p>Like many other open source projects, you are welcome to discuss and challenge the current plan, or come up with your ideas regarding the design and implementation.</p> <p>(So what’s the long-term goal of Elvish? The long-term goal is to remove the “seeks to” part from the introduction of Elvish at the beginning of the post.)</p> <h1 id="development-im-channels">Development IM Channels</h1> <p>To better coordinate development, there are now IM channels for Elvish development: <a href="">#elvish-dev</a> on freenode, <a href="">elves/elvish-dev</a> on Gitter and <a href="">@elvish_dev</a> on Telegram. These channels are all connected together thanks to <a href="">fishroom</a>.</p> <p>For general questions, you are welcome in <a href="">#elvish</a> on Freenode, <a href="">elves/elvish-public</a> on Gitter, or <a href="">@elvish</a> on Telegram.</p> <h1 id="conclusion">Conclusion</h1> <p>This concludes this first issue of the newsletter. Hopefully future issues of this newsletter will also feature blog posts from Elvish users like <em>Elvish for Python Users</em> and popular Elvish modules like <em>Tetris in Your Shell</em> :)</p> <p>Have Fun with Elvish!</p> <p>- xiaq</p> The Elvish Website is Officially Live! 2018-11-05T00:33:48Z Qi Xiao <p>After being “in construction” for ages, the Elvish website is now officially live. It is (still) not complete yet, but in the spirit of “release early”, here it is :)</p> <p>This website will be the entry point of all Elvish information. It will host documents (including both <a href="../learn/">learning materials</a> and <a href="../ref/">references</a>), as well as release notes or other announcements. The <a href="">GitHub repository</a> continues to host code and issues, of course.</p> <p>The website has no comment facilities: commenting is outsourced to <a href="">Hacker News</a> and <a href="">r/elv</a>.</p> <p>The <a href="../">homepage</a> introduces each section, and highlights some key features of Elvish with “ttyshots”. Please start there to explore this website!</p> <h1 id="technical-stack">Technical Stack</h1> <p>The website is built with a <a href="">static website generator</a> from a bunch of <a href="">MarkDown, configuration files and messy scripts</a>, and hosted on a <a href="">DigitalOcean</a> server with <a href="">nginx</a>.</p> <p>Thanks to <a href="">Cloudflare</a>, this website has a good chance of withstanding kisses of death from Hacker News, should there be any. It uses Cloudflare’s “strict” SSL configuration, meaning that both traffic from you to Cloudflare and Cloudflare to the origin server are fully encrypted with verified certificates. The origin server obtains and renews its certificate from the wonderful <a href="">Let’s Encrypt</a> service.</p> Elvish 0.9 Release Notes 2018-11-05T00:33:48Z Qi Xiao <p>Version 0.9 has been released to coincide with the official publication of the Elvish website, which will be hosting all release notes in the future.</p> <p>This version is released slightly more than a month after 0.8. Despite the short interval, there are some interesting additions and changes.</p> <h1 id="breaking-changes">Breaking Changes</h1> <ul> <li><p>Lists have become immutable.</p> <p>Support for assigning individual list elements has been temporarily removed. For instance, the following is no longer possible:</p> <pre><code><span class="sgr-35">li</span><span class=""> = </span><span class="sgr-1">[</span><span class="">lorem ipsum foo bar</span><span class="sgr-1">]</span><span class=""><br></span><span class="sgr-35">li</span><span class="sgr-1">[</span><span class="">1</span><span class="sgr-1">]</span><span class=""> = not-ipsum</span></code></pre> <p>You need to use this for now:</p> <pre><code><span class="sgr-35">li</span><span class=""> = </span><span class="sgr-1">[(</span><span class="sgr-32">explode</span><span class=""> </span><span class="sgr-35">$li</span><span class="sgr-1">[</span><span class="">:1</span><span class="sgr-1">])</span><span class=""> not-ipsum </span><span class="sgr-1">(</span><span class="sgr-32">explode</span><span class=""> </span><span class="sgr-35">$li</span><span class="sgr-1">[</span><span class="">2:</span><span class="sgr-1">])]</span></code></pre> <p>Element assignment will be reintroduced as a syntax sugar, after the conversion to persistent data structure is finished.</p> <p>Assignments to map elements are not affected.</p></li> <li><p>The <code>true</code> and <code>false</code> builtin commands have been removed. They have been equivalent to <code>put $true</code> and <code>put $false</code> for a while.</p></li> <li><p>The default keybinding for last command mode has been changed from <span class="key">Alt-,</span> to <span class="key">Alt-1</span>.</p></li> <li><p>The “bang mode” is now known as “last command mode”.</p></li> <li><p>The <code>le:</code> module (for accessing the Elvish editor) has been renamed to <code>edit:</code>. You can do a simple substitution <code>s/le:/edit:/g</code> to fix your <code>rc.elv</code>.</p></li> <li><p>The 3 listing modes – location mode, history listing mode and last command mode – are being merged into one generic listing mode.</p> <p>Most of their builtins have been merged: for instance, they use to come with their own builtins for changing focused candidate, <code>le:loc:up</code>, <code>le:histlist:up</code> and <code>le:bang:up</code>. These have been merged into simply <code>edit:listing:up</code>, that operates on whichever listing mode is active.</p> <p>A new binding table, <code>$edit:binding[listing]</code> has also been introduced. Bindings put there will be available in all 3 listing modes, with bindings in their own tables (<code>$edit:binding[loc]</code>, <code>$edit:binding[histlist]</code> and <code>$edit:binding[lastcmd]</code>) having higher precedence.</p></li> <li><p>The readline-style binding module has been renamed from <code>embedded:readline-binding</code> to just <code>readline-binding</code>. Future embedded modules will no longer have an <code>embedded:</code> prefix either.</p></li> </ul> <h1 id="notable-fixes-and-enhancements">Notable Fixes and Enhancements</h1> <ul> <li><p>This release has seen more progress towards breaking up the huge, untested <a href="">edit</a> package. For instance, the syntax highlighter and command history helpers now live in their own packages, and have better test coverages.</p></li> <li><p>An experimental web interface has been added. It can be used by supplying the <code>-web</code> flag when running Elvish, i.e. <code>elvish -web</code>. The default port is 3171, which is <a href="">a way</a> to write “ELVI”. An alternative port can be specified using <code>-port</code>, e.g. <code>elvish -web -port 2333</code>.</p></li> <li><p>Per-session command history has been reintroduced (<a href="">#355</a>).</p></li> <li><p>Elvish now forks a daemon for mediating access to the database. This is to prepare for the switch to a pure Go database and removing the current C dependency on SQLite. A new <code>daemon:</code> module has been introduced.</p></li> <li><p>A new <code>edit:complex-candidate</code> builtin has been introduced to construct complex candidates from completers.</p></li> <li><p>A new <code>re:</code> module, containing regular expression utilities, has been introduced.</p></li> </ul> <h1 id="known-issues">Known Issues</h1> <p>The daemon implementation has a known issue of some intermediate process not being reaped correctly and there is an outstanding <a href="">pull request</a> for it. In the worst case, this will leave 2 processes hanging in the system.</p> The Philosophy 2018-11-05T00:33:46Z Qi Xiao <div class="toc"> <p>Table of Content: <a id="toc-toggle" href="">[Hide]</a></p> <div id="toc-list"> <ul> <li><a href="#the-language">The language</a></li> <li><a href="#the-user-interface">The user interface< development of Elvish is driven by a set of ideas, a <strong>design philosophy</strong>.</p> <h1 id="the-language">The language</h1> <ul> <li><p>Elvish should be a real, expressive programming language.</p> <p.</p> <p>Elvish is not alone in this respect. There are multiple ongoing efforts; <a href="">this page</a> on the wiki of oilshell (which is one of the efforts) is a good reference.</p></li> <li><p>Elvish should try to preserve and extend traditional shell programming techniques, as long as they don’t conflict with the previous tenet. Some examples are:</p> <ul> <li><p>Barewords are simply strings.</p></li> <li><p>Prefix notation dominates, like Lisp. For example, arithmetics is done like <code>+ 10 (/ 105 5)</code>.</p></li> <li><p>Pipeline is the main tool for function composition. To make pipelines suitable for complex data manipulation, Elvish extends them to be able to carry structured data (as opposed to just bytes).</p></li> <li><p>Output capture is the auxiliary tool for function composition. Elvish functions may write structured data directly to the output, and capturing the output yields the same structured data.</p></li> </ul></li> </ul> <h1 id="the-user-interface">The user interface</h1> <ul> <li><p>The user interface should be usable without any customizations. It should be simple and consistent by default:</p> <ul> <li><p>Prefer to extend well-known functionalities in other shell to inventing brand new ones. For instance, in Elvish Ctrl-R summons the “history listing” for searching history, akin to how Ctrl-R works in bash, but more powerful.</p></li> <li><p>When a useful feature has no prior art in other shells, borrow from other programs. For instance, the <a href="../learn/cookbook.html#navigation-mode">navigation mode</a>, summoned by Ctrl-N, mimics <a href="">Ranger</a>; while the “location mode” used for quickly changing location, mimics location bars in GUI browsers (and is summoned by the same key combination Ctrl-L).</p></li> </ul></li> <li><p>Customizability should be achieved via progammability, not an enormous inventory of options that interact with each other in obscure ways.</p></li> </ul> The Name 2018-11-05T00:33:47Z Qi Xiao <h1 id="etymology">Etymology</h1> <p>In <a href="">roguelikes</a>, items made by the elves have a reputation of high quality. These are usually called <em>elven</em> items, but “elvish” was chosen because it ends with “sh”, a long tradition of Unix shells. It also rhymes with <a href="">fish</a>, one of the shells that influenced the philosophy of Elvish.</p> <h1 id="stylization">Stylization</h1> <p>The word “Elvish” should be capitalized like a proper noun. However, when referring to the <code>elvish</code> command, use it in lower case with fixed-width font (like in this sentence).</p> <h1 id="related-words">Related Words</h1> <p>The adjective for Elvish (as in “Pythonic” for Python, “Rubyesque” for Ruby) is <strong>Elven</strong>.</p> <p>Whoever practices the Elvish way is called an <strong>Elf</strong>. The <a href="">GitHub organization</a> is called Elves for this reason.</p> Bundled Modules 2018-11-05T00:33:46Z Qi Xiao <div class="toc"> <p>Table of Content: <a id="toc-toggle" href="">[Hide]</a></p> <div id="toc-list"> <ul> <li><a href="#readline-binding">readline-binding< Elvish binary is bundled with some Elvishscript modules.</p> <h1 id="readline-binding">readline-binding</h1> <p>Contains readline-like keybindings. To use, put the following in <code>~/.elvish/rc.elv</code>:</p> <pre><code><span class="sgr-32">use</span><span class=""> readline-binding</span></code></pre> | https://elv.sh/feed.atom | CC-MAIN-2018-51 | refinedweb | 6,182 | 50.12 |
Is RCON supported with Venice yet? Cant seem to get B3 to connect. So either it is not working or I am doing something wrong.
Thanks.
Code: Select all
def checkVersion(self):
version = self.output.write('version')
self.info('server version : %s' % version)
if version[0] != 'BF3':
raise Exception("the BF3 parser can only work with Battlefield 3")
if int(version[1]) < BF3_REQUIRED_VERSION:
return
# raise Exception("the BF3 parser can only work with Battlefield 3 server version %s and above. You are tr"
# "ying to connect to %s v%s" % (BF3_REQUIRED_VERSION, version[0], version[1]))
Return to “Help and Support”
Users browsing this forum: No registered users and 3 guests | https://forums.veniceunleashed.net/viewtopic.php?f=40&t=8841 | CC-MAIN-2021-10 | refinedweb | 110 | 57.57 |
09 February 2012 10:07 [Source: ICIS news]
SINGAPORE (ICIS)--?xml:namespace>
The country’s vehicle production in January totalled 1.3m units, a 27.5% year-on-year drop and down by 23.2% month on month, the CAAM said.
Passenger car sales in the month declined by 23.8% on year and 15.2% from December 2011 to 1.16m units, with production falling by 24.3% year on year and 22.8% from the previous month to 1.05m units.
The CAAM said the sharp decline in car sales was primarily caused by the Lunar New Year holiday on 22-28 January, when buying activity weakened during the festive season.
Car production and sales data are indicators of base oil demand and plastic consumption in manufacture of car | http://www.icis.com/Articles/2012/02/09/9530741/china-vehicle-sales-decrease-by-26-in-january-on-festive.html | CC-MAIN-2014-42 | refinedweb | 131 | 71 |
PRANG::XMLSchema::Whatever - node type for nested anything
package My::XML::Element::Type; use Moose; use PRANG::Graph; has 'error_fragment' => is => "rw", isa => "PRANG::XMLSchema::Whatever", ;
Some schema allow sections of responses to be schema-free; typically this is used for error responses which are allowed to include the errant section of XML.
Fortunately, PRANG is flexible enough that this is quite easy to do. The result of the operation is a nested set of PRANG::XMLSchema::Whatever objects, which have two properties
contents and
attributes, which store the sub-elements and attributes of the element at that point. There is also the attribute
nodenames which stores the node names of nodes. Once it is supported, there will also be an attribute indicating the XML namespaces of attributes and elements (currently they will not round-trip successfully).
This API is somewhat experimental, and may be broken down into various versions of 'whatever' - see the source for more.. | http://search.cpan.org/dist/PRANG/lib/PRANG/XMLSchema/Whatever.pm | CC-MAIN-2017-17 | refinedweb | 157 | 55.58 |
>
Hey, I am literally untouched by OOP and also by c# so this question will be rather trivial.
Lets say I want to have 100+ of skills: classes Fireball, Frostbolt, Heal, ... which represent my ingame skills and will be attached to GOs.
I want them all to have some common variables and functions: SkillStart, SkillEnd, SkillInterupt, ...
Normally, I would create common abstract ancestor class for them which would implement those common functions.
But they already inherit from MonoBehaviour so they cannot inherit from another class, right?
Also I have no idea how monobehaviour works behind the scenes so I dont want to do something really dumb.
Answer by jdean300
·
Aug 16, 2016 at 11:30 PM
Have your skill base class inherit from MonoBehaviour:
public abstract class SkillBase : MonoBehaviour
{
//put the common variables/functions here
}
public class Fireball : SkillBase
{
//fireball specific stuff here
}
So is it just like that? Wasnt sure whether it wont mess the monobehaviour functionality on children. Really had no idea how the unity magic stuff happens behind scenes. Shouldnt be the SkillBase class abstract?
Yes it should be abstract - but yes it is that simple. Unity doesn't break inheritance.
Okay.
Information about Classes and Instantiate Objects C#
2
Answers
Call a method of a class derived from MonoBehaviour from a class that isn't.
1
Answer
OOP Conceptualization in Unity
1
Answer
MonoBehaviour Update called twice, fields being set to null
0
Answers
Setting parent through custom script not working.
0
Answers | https://answers.unity.com/questions/1230369/how-to-inherit-from-other-class-in-c.html | CC-MAIN-2019-26 | refinedweb | 247 | 63.49 |
go to bug id or search bugs for
Description:
------------
PHP 5.2.9 does auto detection for strnlen(). On Linux the detection results in strnlen() availability.
The function is only available, when _GNU_SOURCE is defined though. File main/spprintf.c uses it without _GNU_SOURCE in PHP 5.2.9.
This is due to an incomplete backport from MAIN and 5.3.
See
and
and compare with
Patch:
--- main/spprintf.c 2009-02-04 16:03:12.000000000 +0100
+++ main/spprintf.c 2009-03-29 21:58:10.000000000 +0200
@@ -76,6 +76,7 @@
* SIO stdio-replacement strx_* functions by Panos Tsirigotis
* <panos@alumni.cs.colorado.edu> for xinetd.
*/
+#define _GNU_SOURCE
#include "php.h"
#include <stddef. | https://bugs.php.net/bug.php?id=47831 | CC-MAIN-2015-27 | refinedweb | 115 | 65.28 |
Hi, Yesterday night, the first release of vSecurity was made publicly available at tuxedo-es.org cvs, which can be found at: As a short introduction, "vSecurity is a new approach to Linux kernel security inspired and partially based on grSecurity, using the Linux Security Modules framework, improving and bringing several security enhancements in a non-intrusive manner to the Linux kernel sources." I was working on it since the thread about Linux kernel security ramped into a "flame", without giving things so clear for those who only wanted to know what was the final decision (and the kernel hackers thoughts) on it. During the (around) 3 weeks that it needed to be at least more stable and well-documented (regarding the source code comments and not a technical paper explaining it, which is going to be finished and published ASAP) code, I knew that, in most cases, some of the typical security faults that happen to Linux users could be solved without using much more than the LSM and a well designed engine using it and adding hooks on those places where we can catch up the "exploitation" of the security faults. vSecurity currently protects (in a "Plug & Play" manner) against: - Execution (mmap()'ing in elf_map()) of binaries in untrusted paths. (and also protection against tricky uses of mprotect() to bypass such protections, which are formerly known as Trusted Path Execution, TPE). - BSD Jails implementation, based on Serge Hallyn's code. - Chroot() Jails (even if they are broken by design *sigh*) protections. (Basic anti-escaping: double chroot()'ing, etc, a few capabilities protections, etc.IPC and SHM protections are not yet implemented, also setuid bit protections are not yet implemented too). Anyways, I encourage to use the BSD Jails functionality instead of simple chroot() jails. (An userland support tool for change namespaces, "auto" jailing, is going to be available as soon as Serge and me finish it, that will help on BSD Jails use automation). - Linking protections: symlinking and hardlinking,FIFOs not yet in 0.1-cvs. - Socket restrictions: per-socket-type style restrictions: "server" sockets, "client" sockets and all-sockets.Supports per-GID and per-UID configuration basis, prepared for kernel-configuration time and if module is compiled outside and separate of the kernel, with module parameters, same as TPE protections). (Using an ACL engine relying on a sysfs subsystem "secfs"). - RAW I/O protections and kernel symbols protections. (No so-called live-patching for a while :) ) - RLIMIT_NPROC enforcing, check also in fork() calls so ulimits will apply and checked each call to know if user can do it or not). Native and enhanced support in BSD Jails (which also have Serge's "network virtualization" engine. Useful against so-called fork() bombs. - Other enhancements and security improvements. It's not as mature as I want, but I decided to release it as soon as possible to get feedback, bug reporting (sure it has, we all do mistakes ;) ), etc. Please, keep in mind that It's a development release, I wouldn't like to receive comments about "how a big crap is this" and such, until a stable release gets finished :). Code is well-documented, but as I commented a few lines above, I will make available a paper explaining it further, ASAP. Also, I would like to thank Seth Arnold from Immunix for helping me with my (again) extensive lack of knowledge, Serge Hallyn from IBM for helping with BSD Jails code and testing, suggestions, etc, Stephen Smalley for his suggestions, comments and help on some protections implementation, Brad Spengler for helping when I asked about some grSecurity pearls, and David B. Harris from OFTC (and whole OFTC staff) for hosting my crap there :). I hope this would be useful and interesting, and, again, I would appreciate any feedback on it. Thanks in advance, enjoy it. -- Lorenzo Hernández García-Hierro <lorenzo@gnu.org> [1024D/6F2B2DEC] & [2048g/9AE91A22][]
Linux is a registered trademark of Linus Torvalds | https://lwn.net/Articles/121298/ | CC-MAIN-2017-30 | refinedweb | 657 | 50.36 |
> __pnotify_exit() would need to call the exit callback for all clients
> except for the client failing the fork call. To do this wouldn't the
> following be needed in __pnotify_fork()?
If the fork fails in copy_process, we go to cleanup in copy_process,
not exit.c. So, with the revision, if the the pnotify kernel module
subscriber returns a failure for the process, that failure is passed
along to the copy_process call. There, we go to bad_fork_cleanup_namespace
where a pnotify_exit is done on the process that failed to fork.
In the old version, the pnotify_exit would have also been run within
__pnotify_fork. In the new version, we don't run the pnotify_exit
from __pnotify_fork because we know it will be run in the fork failure
path of copy_process. That should mean that pnotify_exit will only
execute once. I think that means that your suggestion for adding
a pnotify_unsubscribe isn't necessary? The unsubscribe is done by
__pnotify_exit in this case. Or am I still missing the point here?
Sorry if it isn't getting through my head.
See the RCU test version of pnotify in the download site under
pnotify-test. My attempts at posting that patch to the list seem to be
eaten by the list server right now. When that's fixed, I'll start posting
stuff here.
Erik | http://oss.sgi.com/archives/pagg/2005-09/msg00065.html | CC-MAIN-2014-52 | refinedweb | 220 | 65.62 |
27.12.2005 by bsiegert@
We finally have a new release, over two years after #7! To celebrate this event, rotate the wlog and start a new one.
27.12.2005 by tg@
I've been prodded by bsiegert@ to write here again. Curious, isn't it? After the last release I've been the only one to write here. But today is somehow unproductive... I can't get myself to do something; will probably hunt some autoconf bugs later. I got a new laptop HDD, 80 GB and waaaaaay faster, and re-installed BSD. pb@openbsd, who has arrived at the OpenBSD booth @22C3 in the meantime, didn't recognise me as I showed up in front of him until I threatened to throw all 70 or so MirOS CDs we have at them.
28.12.2005 by tg@
Another very cold (outside) and hot (inside) day at the 22nd Chaos Communication Congress (Berlin, Germany). The "others" are out for food (bsiegert@, a friend of his and our booth slave), Thai, this time, while I'm still sitting here and just fixed mplayer (that included fixing and upgrading a shitload of other ports). Drinking a newly found thing, vanilla flavoured Soy milk, and a local specialty (Faßbrause) I'm hacking away, while the NOC complains that we, all of us together, are using a mere 7% of the 16 Gbit/s uplink, and the CAcert.org guy is seemingly confused (but they at least do their thing so that it WFM).
Opera segfaults, and I guess my next target will be porting ptrace support for the Linuxulator from NetBSD®, or asking Kurt Miller, who seems to have already done it, for his patch. Drinking more milk and juice and less alcohol during the night time should also help... but I'm more sleepy than really tired. They offer Club-Mate, but not the brother IceT, so I'm left off the caffeïne circle (coffee's too expensive as well).
I notice I can't write coherent "day-to-day palaver" log entries... I s'pose I should go back to coding. Who is going to read this anyway? People are busy complaining the FTP servers are slow (I think FTP deserves to die fast anyway).
29.12.2005 by bsiegert@
I am writing this just after midnight, so the second day of 22C3 has just ended. Did some updated ports for GNOME 2.12.2, hopefully I will have it finished by the time GNOME 2.14 comes out ...
I saw three more or less interesting talks today. The first one was by Dan Kaminsky is called "Black Ops Of TCP/IP 2005.5". He basically showed what you can do with a really fat pipe: scan the entire internet! He also showed a real-time traffic graphing tool and an estimate of the number of machines infected by the Sony rootkit: at least 700.000 machines, more likely over a million. To quote Bruce Schneier: "What happens when the creators of malware collude with the very companies we hire to protect us from that malware?"
After that, there as a talk about PyPy, a Python implementation written in Python. This actually makes sense because it is self-hosting and it can translate Python code into C and even JavaScript for native compilation. The third talk was a real highlight -- "Das literarische Code-Quartett". Examples of good and bad code, commented in a very fun way. Definitely a must.
30.12.2005 by tg@
The chaos continues. But some real work is done – we now can support the scenario "some shared library depends on another of their kind" (for now, only unofficially, but it will be MFCs by bsiegert@ I think).
Today is clean-up and go day. We asked the people from OpenBSD (we have to clean up and work, no time), NetBSD® (they want to drive away early, like 18:00, due to the weather), DragonFly BSD (they say there will be ice rain so they'll hunt home at 15:00) to eat with us at the great Indian restaurant, and FreeBSD didn't even show up (the same procedure as every year). But we're gaining popularity not only among the other BSDs, but as well with the congress participiants (a spokesman calling them "Dear congress... err... people" in a speaker announcement).
Some media are writing off each other, leading to people believing we have released MirOS Windows XP or something. We had to unconfuse; we hope to be able to correct this mistake in each publication where it shows up.
I've got headaches. Everything is being broken down, including the big HP switches, so the network'll probably cease to exist RSN. Benz is watching a last presentation, then we'll head to the Indian, then back home. See you all in the new (christian/western) year!
01.01.2006 by tg@
I've hacked on an enforcement for ports versioning and drafted the "package era" scheme we'll probably be using, pending results of the discussion with all other active MirPorts developers (hrhr).
The INDEX was regenerated after I fixed several ports with damaged version numbers but the versions used before that are quite probably not upgradable.
sirc and ssfe are now capable of displaying "cool looking" unicode (and ASCII) time stamps.
I changed all my (user and root) passwords and generated a new ssh key after returning from 22C3 (where I shut down the boxen remotely, as the last thing before they switched off the network). This is the best thing to do, since keys and passwords should be rotated yearly, or at least periodically, anyway, and I can't think of a better time than after the Chaos Communication Congress.
02.01.2006 by tg@
I've ordered a new dedicated server which will cost me a lot less, namely 19.90 € the first 18 months and then 29 € (also per month) with the same functionality at the same hoster. I'm compiling a new snapshot these days to set it up with this – so thor has outlived and will not be continued, but switching will not be a pain either.
My friend bogus was here for a bottle of Met and just did the same. The new hostnames will be fungor (his choice) and... well, 魔王 (まおう) is mine. The meal we had at the yugoslawian (croatian) was tasteful, by the way.
I baked an Atheros kernel for gecko2's Soekris net4801 he purchased (which was formerly known as loki) which works... much to my surprise. But it's not ready for commit, e.g. I nuked the wi(4) support to compile, ifconfig(8) doesn't operate properly, etc. (but he can access wireless LANs with it). I wouldn't buy ath(4) tho (I just don't trust them).
I somehow miss bsiegert@ here – there's lots of fixes he may (should) be doing now...
Somehow we're gaining good press and user reviews (and slander which shows that the "others" are not only recognising us but also see us as dangerous to them (their popularity? user base? I've converted at least one OpenBSD person to MirOS during 22C3). Nice to know.
I tought bogus some MirPorts and upgraded the ext2fs-progs port in the meantime (also adding a static flavour later, to benefit a weird setup of my new dedicated server). The idea is to have a 16 MiB wd0a with a partition ID != 0x27, containing a /boot installed with -P as to recognise the partition, and one or two ramdisk kernels, and some text files (e.g. disklabel, fdisk output). Then, a 16 MiB extfs with a gzip'd image of the first 16 MiB (including MBR, PBR, 4.2BSD FFS), a stand-alone MBR, and what else you could need to recover. The rest is a standard 0x27 partition with the wd0a of a regular boot, /home, swap, whatever. The "irregular" wd0a need not even be in there.
13.01.2006 by tg@
I've fixed a few things (code cleanliness) and built a snapshot to see if it works (another one – there was one on 03.01. already which bsiegert@ has announced today at freshmeat). This one also has taken care of the always changing domains. I'm updating MirOS #8 (by mkdir updates) with current MirPorts as well.
My little brother and bogus came here, teaching me Maths, drinking Met and having fun, after a good meal. I need it; university is some weird shit, something else really. It's not my favourite but I still want to do 2 semesters before going to work (so I can continue later if I want).
Nothing else in peculiar... bsiegert@ has got a girlfriend, thusly #8-stable is lagging quite a bit. My new dedicated server also could need some more attention.
15.01.2006 by tg@
Things are settling down... installed software on 魔王
but still not complete. It now does mail (for all domains), OpenVPN,
a minimalistic www proxy, and of course NTP and its own (non-public)
DNS. But that's about it. Time will show.
Also, I need to phone the hoster regarding the domain issues. They're worse than appearing at first, since the wildcard is gone.
Fixed some annoying minor bugs in roff2htm and /cvs/CVSROOT.
17.01.2006 by tg@
Wow, I've been attending university once again. This time for that #1 boring thing – Economics (BWL), held by a female VWL doctor with a voice more cruel than should be allowed... at least we do not have to do an exam, only attend and do a presentation and home work. And I scored well in English (the other class in which attendance is mandatory). I've worked on my Maths, and theorectical CS is trivial. But as for the others, I don't know. Plus in the beginning they told us that we would automatically be subscribed for the exams – I was told today I should better have done that myself in December. So I probably can't do any exams except English this semester.
Been working on djbdns today, once again. Now I've incorportated a lot more patches (from tinydns.org) and can do AXFR via inetd(8). So I will probably use AXFR and NOTIFY requests in the future, with two friends (bogus and maybe gecko2 or someone else) doing backup NS for me (and HERC might still do too, but using classical rsync/scp). And the best thing: it actually works and required virtually no patches. There's still no (working) UCSPI-TCP port though. We did have one in the past, from OpenBSD, but it never worked correctly, nor addressed all the issues we had with it. (DJB sucks.)
I discovered more bugs in pkg_upgrade(8) which bsiegert@ hopefully will fix (or at least decide which fix is correct, I can think of at least three possible fixes, preferring the one most complex).
I had announced the snapshot of Jan 13 on FM and it actually showed up.
*.mirsolutions.de works, once again. Costly phone call to the provider sponsored by yours truly. Now go and donate some money via PayPal.
The comment on the GPLv3 actually got modded +1, Insightful on Symlink, the German slashdot equivalent (which, in contrast to its English counterpart, still can be accessed with Lynx correctly).
A new Call for papers by the FROSCON Orga. This is dubbed the "LinuxTag Bonn" and replaces the former LinuxTag Karlsruhe (now Wiesbaden, where ever that may be) for us... we've organised a BSD room (the orga team are drinking mates of mine so it wasn't too difficult). DragonFly BSD will come (per Joerg) and Wim will obviously attend. NetBSD® hopefully will appear too; as for FreeBSD® I couldn't ask them since they weren't there (again as usual) at 22C3. The OpenBSD magazine has it too (as does Symlink).
Did I mention our kernels are now always gzip'd? And we now got a permit to use GNU FDLd sources in CVS by RMS himself (please read my enquiry, with definition of "IT", too).
I tried to ask the Opera guys for a statically linked native Linux binary or even (preferred) an OpenBSD binary. They told me some info about glibc and Linux incompatibilities, I'll try...
Older mailing list activity includes: an analysis of handling this year's leap second (FreeBSD 0, MirOS 2), FOSDEM, user enquiries, and spam. I suggest you read it for yourself.
20.01.2006 by tg@
Published a cpio ball of ocvs+ncvs1 and historic. bsiegert@ agreed they be closed and sealed now. It's only on herc and maou tho.
Slowly going on with setting up maou. After all, thor''ll cease to exist mid-February, IIRC.
Removed ads. G**gle closed my account for supposed abuse.
Added Debian GNU/Linux i386 emulation libs; makes Opera work. I'll hack it up even further though.
I think I'll use /usr/bin/logger in axfrdns (net/djbdns).
Planning on putting this on Planet Symlink (by a conversion script to be hacked) – aus der es-ist-zwar-kein-blog-aber-warum-nicht Abteilung... I wonder if XTaran will do it.
Enough for today. Gotta do some work; then dinner at the Croatian, with wbx, le, Angelo (the first Mac OSX worm creator), Judith, miro, bogus etc.; then using the usual place to hang around, maybe hack on the website some more.
24.01.2006 by tg@
Got something decent to eat, drink (beer, cola) and snack. Hacked, djbdns-axfr, sirc/ssfe now improved, savecore(8) does gzip(1)d files and the zlib API sucks. compress(1)' implementation also sucks.
All hardware sucks, all software sucks... but actually the overall suckage of MirOS is pretty darn low.
26.01.2006 by tg@
Oh, already last day of the semester? (Well, tomorrow. Luckily, so I've still a minimal chance to be allowed to take exams this time... I better should; on 30th of January, the first one is scheduled). In English I graduated with an 1.3 (that's like 96%), and Economics was taken for granted.
I fixed php5-core but encountered a package tools bug which Benny, hopefully, will fix. I've also redesigned my keyboard layout since I don't read Japanese anyway, but having Umlauts (Meta-style) in Opera is more important (and I've got back my Ellipsis ;). I get ä by pressing either Meta-d or Mode_switch-d (and not Mode_switch-a which was used by dot.Xmodmap.light for DAUs) as I'm used to from the text console, wscons(4).
I was thrown out of Netzladen today... no idea if I'll continue to hang around there. Probably not, saves me 4 € monthly.
On the other hand, this leaded to an unexpected, not-Mate-induced, peak in productivity, not only yielding a much cooler, artistic, new keyboard layout, but to the release of joe-3.1jupp5 as well.
And because I didn't find this, admittedly older, reference in the bookmark list I keep, I thought I don't want to keep it from you, as it's also my opinion on trends and AJAX: Felix von Leitner speaks on hypes.
29.01.2006 by bsiegert@
Wow, exactly one month since I have written my last wlog entry. After 22C3, I have done very little work on MirOS, owing to two factors: my girlfriend and the january exams (seven of them!). The latter are over now, and I feel confident about the results for courses like Optics, Solid State Physics and (worst of all) Statistical Properties of Polymers, to name but a few.
I am still struggling with firefox 1.5 and its component libs. The problem seems to be related to shared library interdependencies. The current state of my port might work on -current. I could just churn out an update of #8-stable that contains the linker bugfix and have that as a minimum requirement.
What else? If you have the opportunity, go see Lücke im System (the original title is Absolut) at a cinema. IMHO, it is the first "hacker" movie which is credible both in story and technical aspects. And what makes it all the more frightening is that the movie is based on a true story. The synopsis: Two friends develop a virus which one of them has to install at a bank. He wakes up in the hospital two days later, having had an accident after work that day. He has lost any recollection of that day. What has happened? Did he really install the virus? Are they after him?
30.01.2006 by tg@
Benny, do you still live in 2005? ;-)
I managed to appear at two exams today, finally: Operating Systems 1 and Technical Computer Science 1 (basically, Physics and Electronics). I hope I've passed both but actually I am not sure. Weird stuff.
There's an mksh R26c with a few updates, and this one is about to be submitted to Debian again. I wonder when Gentoo will update.
I'm pondering to update Lynx but I'd like to have a libiconv to link with so I can enable japanese-utf8 support. On other news, I still got no answer from Bruno Haible, maybe I should mail him again. We need to have that libutf8 code.
I'd make a snapshot and install 魔王 for the second time but there's still an infrastructure bug pending in ports, some samples checks by Benny, and a few other port fixes, so I'll probably postpone it another while. This sucks but we can bear with it; thor is still up and running stable enough for a while (yet can't test new ports, sigh) and the redirection is working for now; no abundant traffic. The state of the base system is quite well, it's only ports which need more work (much more). Of course there are a few bugs, but that's normal, you'll have to live with them as usual. We try to fix them, though.
Dang! Hubert Feyrer has changed his "blog software" so I must update the hyperlinks. (Scripts around vi(1)? What were you thinking? To do a thing like that... you script ed(1)!) I've sent him some more material for his fun pages – reading symlink is still worth it sometimes, but rarely.
I at Chemnitzer Linuxtage? Possible, if someone sponsors me. I must get there (and back) safely – by train or, preferred, car sharing with somebody from the Bonn region, and live there somewhere (a place to sleep). Any offers? Mail me.
31.01.2006 by tg@
bsiegert@ will probably kill me, or use some other means of violence (who knows), but at least it's done. mgcc(1) now aborts if CFLAGS (and COPTS, or rather, _DEFCOPTS) are not honoured, with an optional abort, not yet active, if they are given twice. This depends on a variable to be set in the environment, thus doesn't affect manual builds except by an informal note.
We now have mmap(2) malloc(3), TCP tuning diffs (SYN packets 4 bytes smaller), and my libc is still working. I am amazed. I will rebuild my entire system then.
nl_langinfo(CODESET), citrus iconv(3), security-fixed perl(1)... now he just can't kill me ;) Also did some major www updates to keep track of source changes (still commented out though).
More later... if I'm still living by then ;)
Seems as if Benny is sleeping... weird, he said his exams period was over... fixed build of base system, so I could do a snapshot again, if I wanted (and ports were ready - damn pkgtools bug).
h2ph(1) was indeed used, but it seems to be minor. gcc now builds as well (non-C languages just ignore -fhonour-copts which seems easier to me), except libjava which I didn't test due to tiredness (lack of time and sleep).
I somehow expect iconv(3) and nl_langinfo(3) CODESET support to have some impact on something... but nothing until now. Wait to see whether we rename libcitrus_iconv to libiconv (selection via -L works).
01.02.2006 by tg@
I've been working on libiconv integration into MirPorts today which, the way I did it, also benefits Darwin. I also hacked a bit on varouus iconv(3)-using ports including centericq, and changed the linuxulator, respectively the porting framework, so that opera runs better.
Should I really go to the exam tomorrow? Chances are I get 40% while to pass you need to have more than 50%.
Soryu (惣流・アスカ・ラングレー
is his nickname, "Stanley Rost" is the real name according to his CMS'
ambiente stream at radioio.com – a site which offers two quality
variants on the website (AM quality and FM quality, wtf?)
Now the fun part: Opera opens a pop-up and offers to download an m3u file when asking for an mp3 stream (thank goddess, I only have mpg123 installed, playing music on the pentium Ⅰ router). The filename: A1med.m3u (this of course raises suspicions) – so I test-run the AM stream and get presented an A1lo.m3u. Interesting. Viewing the source it's an easy task to see the URI, so I ftp(1) A1hi.m3u which in fact exists! I guess it's a subscriber-only feature, but 128 kbps 44k1Hz J/S MP3 is a lot better than 64 kbps 22k05Hz J/S, isn't it? Now I'm listening to the stream and will sleep (or at least try to). I decided that I have no chance to pass the exam scheduled for tomorrow, that's the only reason to still be awake.
02.02.2006 by tg@
So, I did sleep long and not take the exam. I would not have passed, anyway.
Some lazy day today, but I'll continue hacking on various stuff. And (as announced) I broke mySQL for there is no maintainer. We have real, happy, users of MirOS who also appear in IRC, so I fixed a few things, based upon their feedback. Also I persuaded a bunch of BSD guys to add #bsd (or even #mirbsd) on Freeforge to their connect list and autojoin.
Tomorrow I'll have to do a few different things over the day, so may not have the time to work on MirOS.
09.02.2006 by tg@
Still trouble with my life cycle. Getting up early nearly killed me, so I slept during noon a little while. But at least there are a few of my friends still not leaving me.
I must admit that I'm spending a larger amount than I used to or I'd like to, even, on "common" internet activity – chatting (Jabber, ICQ, MSN, Yahoo, IRC) and web-based message boards (with Opera). It is not what I'd like to do but there are a few persons I got to know over time. Besides, with Benny spending time with a girlfriend... which I'm still hoping to eventually acquire as well.
I started a bulk build and, annoyed by the crap we took over from "a BSD focusing on clean code", did some major commits. This probably has broken some more stuff but I'm doing bulk builds to see where. I won't fix ports which don't build (except for the easy cases) just mark them as ${BROKEN}, so we at least know.
Does anyone still have wishes for the next snapshot? I'm about ready to build one. Except for ports, as usual. Lack of communication can be quite annoying.
With mmap(2) malloc(3) we need the OpenBSD X11 fixes ported. I asked ciruZ already, but if someone volunteers, please say so since it's not yet clear whether he will try it at least.
That's all, folks. If I got more feedback I'd write more, besides, I don't even know which topics are of interest to you.
homsn (Daniel Hommel) has packaged mksh(1) for Arch GNU/Linux!
14.02.2006 by tg@
Benny is in Japan now – nice, eh? I think I'd better get a new snapshot built and 魔王 installed before it's too late for merging the old server. I've played a bit with the build system though (some stuff I always wanted to re-do, if we weren't going for syspkgs, there was more work in that area).
At the moment, no lectures at university, I'm sleeping too long (and too much probably) and not getting anything productive done. I already am waiting for FOSDEM but probably can't go to CLT.
Ports are in a rather questionable state, I'm prepared having to fix everything on maou prior to installing. Someone ought to continue bulk build and break work.
15.02.2006 by tg@
Built a snapshot in an overnighter. Have fun, help testing. Caution, ports are a mess.
No idea how I can tell Benny by different means... we've got a place to stay in Leuven – 2 developers, 2 Trittbrettfahrer.
20.02.2006 by tg@
I've been outside a lot, but under-the-hood FOSDEM planning coninues and we'll probably have CDs with yet another new snapshot, and I ought to bring the MirShirts with me as well.
Hacked a little on vnconfig(8) (in preparation for the key file hack inspired by GeNUA's Marcus Popp) and ssh(1), sshd(8) (in order to make them exchange randomness with the peer (via our own arc4random_push(3) interface so it's strictly optional).
Also added a workaround to lynx(1) to improve handling of the broken CAcert.org website. Fix comes later.
bsiegert@ actually phoned me today, meaning he still lives...
I've updated the essentials/pkgtools port after fixing a few bugs in pkg_upgrade. I've also updated mc (difficult, and I don't like some of the changes) and, finally, mirex (contrib/samples) (even with the new, not yet in use, gzsig(1) key but still without bsiegert@ having looked whether his information is correct). Makes me wonder if the version of that port is now correct...
Forcing USE_CXX=no ports to use 'false' as ${CXX} since now.
21.02.2006 by tg@
Today I just was in a hacking mood and besides updating ssh(1) wrote vnconfig(8) keyfile support from scratch using PEM, fixed djb fetching of distfiles, updated and fixed misc/mc for good, helped porters which need iconv.m4, added SQLite2 to php-core and a little advertising (for the MirPorts Framework), hacked net/openvpn the same as ssh, fixed the arc4random_push(3) stuff I use for months in the kernel, so that it is finally usable, did a few man pages and build improvements, even fixed a lot of OpenSSH code regarding to gcc warnings.
bsiegert@ actually showed up in IRC today... did not do much though. I wonder whether we'll be able to do FOSDEM like we want, since I'm in the mood for everything save housework which includes washing clothes, for example certain t-shirts.
23.02.2006 by tg@
Commit ID: 10043FE5D720803A93E and 10043FE634705689581. I don't want to continue any more. Fuck, if 魔王 had not frozen (due to the heat probably) we've had had a snapshot by end of 22nd of February already. Now thor has aborted with a sig11 in a libjava build and only odem is left compiling (my laptop, at 100% CPU speed of 1200 MHz AMD). It would have completed the task with no problem if there had not been minor (gcc -W* not realising an uninitialised variable was being used) as well as major (use of libcrypto) trouble in vnconfig(8), save a few other problems. I'm doing extra shifts and still cannot guarantee that what we'll sell at FOSDEM will build again when you try, or work as it is expected. (I did test vnconfig(8) though, not all modi tho...)
Again, I'm so bored and sick of computers, but can't help it, FOSDEM is a duty. At least we got ourselves included on the flyers by AllBSD, to be presented at FOSDEM too, thanks to the work of Daniel and others (including overnighters). And I'm still trying to finish a functioning and not embarrassing ISO image.
When it comes to hardware trouble I'm quite helpless. I'd like to be able to have some holidays, too. Being stuck at home (time between the semesters) doesn't help, it only gives you spare time to sleep (really too) much and not getting any real work done.
Oh, by the way... virtually nobody remembered my birthday. The folks at #UnixNL were very friendly, though.
24.02.2006 by tg@
Commit ID: 10043FF4D4816FF87C6 – it gets worse.
While I had a good afternoon, I'm slightly pissed now. bogus said no and won't join us for FOSDEM. I hope ciruZ gets persuaded enough, also we won't go today but tomorrow at 05:00 CET instead, so he'll get some more spare time to prepare.
This also gives me time to make a FOSDEM snapshot... dating the 25th then, probably.
somewhen VERY EARLY before FOSDEM 2006, by tg@
Yataa! I did it! We have got an apparently working CD9660 image of a new snapshot, to be released at FOSDEM. I'm burning a CD-R, just to be sure, now, that nothing goes wrong AGAIN even in the very case of this laptop not working any more (but it does WELL, thanks Acer!).
Now it's 05:15 CET and we should be driving in the very direction of Bruxelles already for a ¼ hour. Going.
25.02.2006 by tg@
FOSDEM is fun, good belgian beer, nice people, food and all.
bsiegert@ wants to go to sleep now, maybe he drunk too much (only 1! bottle) of Grimbergen Optimo Bruno...
27.02.2006 by tg@
FOSDEM is over, my visitor gecko2 has left and my room is a little bit cleaned up (mostly thanks to him ;).
I think it was a success (we earned more than OpenBSD on saturday if I'm reading Saad Kadhi's photos correctly, and we sold FOUR T-Shirts). FOSDEM is the most fun event anyway.
We might have a person interested in kernel development soon...
Found a panic (regarding timeout(9) not initialised) in ahc(4) (or a SCSI subsystem not touched by atapiscsi(4)) by trying to cdparanoiarip a dirty CD-ROM. Can't investigate though.
I'm not doing much work on MirOS now, priorising 魔王 to be set up correctly soon. Sorry guys.
Benny is back in Strasbourg (France) and I hope he'll join us people working on MirOS again soon if his girlfriend allows... I'm also still expecting a wlog entry from his 日本 holiday.
01.03.2006 by tg@
I really ought to make a new page, out of the following, called /?features...
Differences to MirOS #7
There should be a complete change log, but we have about 30 MiB of CVS commit logs to read for writing one, so we're only listing the most important ones here:
- Much faster
- Improved and portable MirPorts Framework
- Updated lots of ports and base system programmes
- 64 bit time_t (on i386)
- Correct leap second handling
- Full gcc-3.4.6 (prerelease; propolice) support for C, C++, Objective-C, Pascal, (on i386) Java™, Ada
- GNU CVS 1.12 including own enhancements
- uname(1) now returns MirBSD
- compat_openbsd(8) – binary compatibility layer for OpenBSD-3.8 and MirOS #7-stable systems (almost 100%) and most old MirOS #7-current versions
- compat_linux(8) and OSS audio improvements
- Working LKMs (loadable kernel modules)
- Improvements in the random number generators, ext2fs, msdosfs, and ntfs support
- Kernel pppoe(4) support, much faster and can terminate unknown sessions (useful after reboot)
- Using sv4cpio/sv4crc instead of ustar as package format
- USB 2.0 support
- Update to XFree86® 4.5
- Ramdisk (bsd.rd) now uses GENERIC kernel, comes with many rescue tools (even sshd(8))
- Package tools are now part of MirPorts
- libpng, libexpat are now part of the base system
- Reiser CCCP used as fall-back cpp(1)
- Support for rsh removed
- 8-bit (latin1 and EUC-JP) manual page support in nrcon (nroff), HTML manual pages, french spacing
- New tools: gzsig(1), getcap(1), ifwatchd(8), ntpd(8), spamd(8) and friends, tcpdrop(8), wssetfont(8), xmlwf(1), ...
- Support for hardcoding ARP table entries at boot in /etc/arp.conf
We're quite sure this list isn't complete and we might even have forgotten some change of major importance, but this should give you a good idea why to upgrade.
Differences to OpenBSD
We always get asked how we compare to the other BSDs. Since we have originally forked off OpenBSD we'll list a few "main differences" (the list is nowhere complete, but a good start):
- No hot-tempered head developer
- Portable porting framework
- Much better infrastructure
- Generic framework for wrapping GNU autotools
- Up-to-date third-party tools (GNU Binutils, GCC, CVS, RCS, Sendmail, Perl, Lynx, Texinfo, X-Window, Libtool) avoiding the many porting errors
- Compilers for C, C++, Objective-C, Pascal, (on i386) Java™, Ada
- Slim base system – no Kerberos, AFS, YP/NIS+, SMP, binary compatibility for unused operating systems, BIND, non-C code
- ISDN support
- Privacy improvements
- Support for the i386 and (not now) sparc architectures
- Feature enhancements in the Linux emulation
- Binary compatibility to OpenBSD (almost 100%)
- evilwm replaces wm2
- We still use XFree86™ 4.5
- BSD dæmon
- Rewritten master and partition boot record with boot manager support
- GENERIC kernel is used on bsd.rd
- The ramdisk contains a lot of rescue tools, even sshd(8)
- Support for disabling fsck(8) for ffs filesystems with softdep enabled (default in the MirOS installer) in /etc/fstab. Includes automatic sorting of the fstab file implemented in korn shell.
- Highly improved set of shell script infrastructure using security features of the Korn shell which is /bin/sh in MirOS. Automatic discovery of IDE hard disc drives which need their write cache disabled.
- mksh(1) is the Korn shell, highly improved
- CTM, growfs(8), ffsinfo, wtf(1)
- TLS-enabled Lynx and Sendmail with automatically generated server certificate (boot-time) and CAcert.org support
- AT&T nroff instead of GNU groff
- Default /etc/profile file for smoother user interface
- Support for hardcoding ARP table entries at boot in /etc/arp.conf
- Many more ports which are not in OpenBSD for political reasons
... and more.
Built a cross-compiler to i386-gnu-linux-gnu with Debian GNU/Linux's libs and headers. Built printf(1) - all other tools I attempted didn't work: sh(1) mksh(1) date(1) id(1) and maybe more. GCC also builds okay natively (tested that, including libjava - poor odem).
Next up is bringing the sparc (32-bit) port back in shape. Some nice discussions with Tonnerre in IRC reaffirm my decision to not ever have a sparc64 port (gcc sucks). i386 is our primary platform, sparc and in the future amd64 will be secondary platforms, with the option to add a macppc or alpha port if Benny or Tonnerre are up to the task.
To the curious reader: I will import OpenBSD 3.9-STABLE at some time into the vendor branch and merge it all. But at the moment, sparc will come first because we have got actual customers ;) hi CcSsNET
gcc 4.1.0 is out – all I can do is laugh at the bug list shown in their release announcement... GNU Tar (a version with a known (directory traversal, I think) bug), and the other thing, and that gcc 4.1.1 will take another two months (wondering what else will go wrong). Positive, however, is the ProPolice Ⅱ built-in support and that it's said it runs on Interix unpatched. I wonder if we should better make a port out of it (for MirPorts) instead of our system compiler – OTOH I think many people (centericq on OpenBSD users, for instance) benefit a lot of a mgcc(1) mirport...
I'll visit my best friend tomorrow, stay until sunday evening, so no internet for me (no computer at all, even). Probably he'll be the only person to celebrate (post morten ;) my birthday with. Not many people, as usual, remembered it anyway. (He forgot it too.) But I nevertheless had had a great time. No, I won't tell.
My mobile phone (> 6 years old Trium Astral) is making trouble... the first time since about a year it has had this kind of error (shows connection to a GSM provider but it's away as soon as I try to place a call). Any ideas? No, I won't change cell phones. Only fix.
No idea what else to write. BENNY! I'm still waiting!
19.03.2006 by tg@
I haven't been as lazy (or, well, occupied) yesterday and today as I was before (despite stomach illness) and started migrating thor to the new dedicated server which is now also running IRC, VPN, etc. and uses sophisticated firewalling. In the process, I have fixed a bug (code vs documentation) in readlink(1) and updated some ports. Today I also ran through style(9) and made it consistent, even discovered (undocumented switch) the Bill Shannon mode of indent(1) doing to sizeof what we want.
Since thor is going to be defunct in two, three days, I will have to work some more to "make it". Also I'm setting up DNS anew; I will still be using MirDNS as DynDNS clone with heartbeat protocol and djbdns as backend on maou and herc, but Tonnerre and TGEN offered me a backup NS each which I'll gladly be using provided NOTIFY and AXFR are working properly. I also enhanced inetd(8) by DJB ucspi-tcp compatible environment variables.
Maybe I'll use mirbsd.org as primary domain now and the old mirbsd.org will serve as fallback in case 魔王 is unreachable (it's pretty stable unless I try to build a snapshot).
I bought a Nokia 6150 (old enough so I know I can use it) via ePray, still waiting for it to arrive (and hopefully a PSU too). I do already have the leather bag though... doesn't help me much.
Seems like spring is coming. Still cold but good bearable in the sun which is shining quite well the last few days.
23.03.2006 by tg@
thor's gone, maou's running... sort of. There is still trouble, with the MirDNS #3 code for example, but I got it sort of running (like the old server, without some of the improvements) for now.
maou's making trouble with the hardware, though approximately thirty passes of memtest86 don't show any error at all. Maybe heat? CPU issues? It just freezes, no panic or any serial console output or syslog at all.
I've written a helper, converting UTF-8 to SGML entities, for Benny to write a larger wlog entry. It can convert basically any UTF-8 because it's a simple (slow) shell script, making use of iconv(1) and hexdump(1); output is decimal entities (not sedecimal/hexadecadic) for better portability, and ASCII is passed and not converted to &, <, and >, so he can use HTML already in the input.
Caught a flu, not bad after still recovering from stomach stuff.
Trying to figure out my timetable for the summer semester. Really it is not trivial at all. Though after all I'll probably won't study (for real) anyway.
Please do not forget to update your sendmail.
I should probably write much more here, but... nah, unfunny.
Read the summary about porting (Berkeley) Unix to the i386 architecture by the well known Jolitzens. Some interesting facts. Found at Dæmonnews.
27.03.2006 by tg@
What do we do with maou? It froze again this night. In my opinion we ought to provide stable services, but how the hell am I supposed to if I do not even get a kernel panic? I'm starting to think whether to set up some kind of "ping watchdog" with automatic web interface reboot in a shell script.
Furthermore, look at this:
[ DNS ] mirbsd.org NS record currently not present at tld1.ultradns.net mirbsd.org NS record currently not present at tld2.ultradns.net mirbsd.org NS record currently not present at tld3.ultradns.org mirbsd.org NS record currently not present at tld4.ultradns.org mirbsd.org NS record currently not present at tld5.ultradns.info mirbsd.org NS record currently not present at tld6.ultradns.co.uk [ Whois ] Name Server:PDC0.MIRBSD.ORG Name Server:BDC0.MIRBSD.ORG Name Server:BDC1.MIRBSD.ORG Name Server:PDC1.66H.42H.DE
I've come, again, to the conclusion that it all sucks. Interestingly I discovered (yeah, right, didn't even know) that ntpd(8) is on the CD (yeah, the 4 Megs one). Fun stuff to do with that ahead.
Today I've hacked quite a few things: fix _ASM_SOURCE use (Makefiles and code), clean up rnd(4) and kernel build, even help the sparc port; reduce the size of the persistent entropy pool, generated manual pages and thus distribution; add no_msn flavour to centericq; import new and last (branch gcc-3_4 is now closed) gcc and gpc and libtool, start all the usual merge and upgrade work (gcc not yet finished); ask cvs(1) to not error out if CVSREADONLYFS and it cannot lock var-tags or history; apply the OpenSSH and OpenVPN randomness pushback hack to OpenSSL too, affecting KEX on SSLv3 and TLSv1, also add my ASN.1 OCTET STREAM hack, taken from my vnconfig(8) patch; change ssh(1)/sshd(8) default ciphers to prefer secure over fast (these days it's okay like that I suppose); bring out a new mirmake; implement $RANDOM (with arc4random(3) until a write occured, like in mksh(1)) for sh(1); document ports that disable systrace(1) in the INDEX.
Damn FSF. Libtool is REALLY using /usr/mpkg/bin/bash (note the path) as shell, preferring over /bin/sh (eh, what's wrong with mksh?).
Tonnerre found that to config = mmap(NULL, st.st_size, PROT_READ | PROT_WRITE, MAP_ANON, -1, 0UL); breaks on Limupf... and why. It demands use of MAP_PRIVATE (in contrast to what mmap(2) says, on BSD of course). And they want to be compatible, hah!
Benny thinks he found a bug in perl(1) - my gdb(1) backtrace however tells me he'd better look at fseeko() from /usr/lib/libc.so.38.2
I thought spring was there... but it rained cats and dogs later that day. And no new anime episodes to watch – for weeks!
Hubert says NetBSD® runs as DomU on Xen3. Me wanna!!!
29.03.2006 by tg@
An meiner Fachhochschule gehen zur Zeit eMails zu einer Aussage des
Herrn Prof. Dr. Matthias Jarke, Präsident der Gesellschaft für
Informatik e.V., im Rahmen eines Interviews zur Eröffnung des
Informatikjahrs, herum, die lautet: "Selbstverständlich wird das
Ausbilduingsniveau von Bachelor-Absolventen deutlich unterhalb des
bisherigen Diploms liegen, wohl nur knapp oberhalb einer an das Abitur
angehängten IT-Ausbildung."
Ich kann mich der Aussage selber nicht ganz anschließen, denn eine IT-Ausbildung bei der IHK ist im Gegenteil eher wertvoller als ein Studium. Zwar lernt man, wie ein Kommilitone schrieb, dort keine "design patterns", dafür mehrfach (flach und falsch) Grundlagen von Programmiersprachen, aber wenn man seine Ausbildung selbst in die Hand nimmt, Wert auf vieles legt und sich engagiert sowie in der ohnehin zur Verfügung stehenden freien Zeit liest oder sich anderweitig weiterbildet (gerne während Kaffeetrinkens) statt die Zeit mit Counter-Strike, Blobby Volley, Browsergames oder sich (bei Anderen statt bei der Jugend- und Auszubildendenvertretung!) darüber zu beschweren, daß man nichts als Rechner schleppen tun muß/darf. Ich habe wenig Ausbildungsrelevantes gelernt und in der Berufsschule eigentlich nur Wirtschaft (wußte ich vorher, war es mir aber sogar wert), habe aber viel "nebenbei" gelernt, zum Beispiel, Telex, Kabel ziehen im DVT/HVT, ATM, Taktsynchronisation im SDH2000+ Netz, usw. und besonders wertvoll war, in einem großen Unternehmen immer wieder an anderen Orten zu arbeiten, ganze Prozeßketten kennenzulernen, über den Tellerrand zu schauen und zu sehen, was in der Realität wirklich benötigt wird: Skripte und schnelle (aber für Kollegen noch verständliche, also auf niedrigem Niveau) Frickellösungen, die, wenn sie nicht mehr tun, halt neugeschrieben werden, aber dafür prozeßorientiert, gut dokumentiert und in SAP R/3 verbucht. Keine "design patterns", kein Java oder auch nur C (naja, bei meiner Abschlußarbeit habe ich etwas in C geschrieben, aber außer Headern, Deklarationen und Optionen parsen waren das vielleicht noch 10 Zeilen Code). Ach ja, und ich habe gelernt, wie scheiße MS Office ist und daß Openoffice noch schlechter ist.
The time of adding entropy exchange to networked dæmons is now over, I suppose. I have added the function to ntpd(8), it is performed when an OpenNTPD client talks to it, since we know it sends out random data (arc4random(3)) instead of its own xmttime.
Today I have also completely re-written HTTPS certificate validation code for lynx(1) in an attempt to make it work with CAcert.org (a page whose certificates contain multiple CNs in the DN). It works so far, I have submitted a link to our CVSweb to the lynx-dev mailing list, will submit a full patch later so it might get into lynx 2.8.6dev.18 soon.
I will have to write an ASN.1 OCTET STREAM encoding/decoding module, in PEM format, like vnconfig(8) uses for its keys, for openssltool(1), for the sake of completeness. Well, later, as time permits.
Still have to debug the heartbeat server stuff and MirDNS #3. Also will be as time permits.
Time ought to already have permitted bsiegert@ to commit his pending wlog entry, though…
I'm inmidst of merging gcc 3.4.6 (final), so HEAD doesn't build now. This will be sorted out later as well, though.
Another thing I'd like to do for the next snapshot is either finally rewrite the installer or add an automated Live CD feature to the CDs I burn (e.g. for FROSCON). In addition to that, I'm pondering to write an MS-DOS only boot loader (to start a kernel loaded via MS-DOS I/O from FAT, NTFS (via ntfsdos.exe), CD-ROM, etc. by means of himem.sys and a small relocation/memmove function). I still wonder if I can manage to add 'boot -acs...' functionality. This beast would of course be written in gas-intel-howto(7) and be built as a normal part of MirOS userland (machdep). Kinda loadlin.exe on drugs. But this may prove useful later. (Also, our bootloader ought to adhere to the multiboot specification in order to make it runnable from grub, to bootstrap MirOS from GNU/Linux systems – can you say Thinkpad dear Mr. JanA?).
The Jolitzens have quite a lot of interesting material on their page (e.g. regarding the current BSDs' developers and past). I wonder which parts of 386BSD 1.0 made it into MirBSD, what do they think of OpenBSD and whether we will get, some time, a kernel architect. (I'd be happy, for now, even with a kernel developer; I still plan to teach myself by writing herculesfb(4) though. Tho I have to do a gcc 4.1 port as well, and do lots of other things.)
Martin Michlmayr has built, while we're on the topic gcc 4.1, Debian with it and documented that; together with hints, he also linked to Take some time to read this if you intend to touch any C++ code.
Kind of another interesting read from my research into Jolix: the story on XENIX and how Linus can't code (with proof by Lars Wirzenius). It also suggests, although whom do you believe, that there were more than just six files involved in porting. I'm strangely fascinated by their stories and web pages and wonder what to do with it. I doubt they'd work for MirOS tho (even if they could play all the kernel design they want).
Another thing I researched into yesterday was TAOUP; I found that Plan 9 did invent UTF-8 with a funny story. (Why doesn't it surprise me today when I see this story is hosted by Markus Kuhn?) I wonder if we simply could switch to UTF-8 only operation mode too. I'd like it. No umlauts and only basic ISO_646.irv:1991 (that's ASCII for you stupid americans aka ANSI_X3.4-1968) for the programmes which don't. That was basically what my plans for the "C" locale were. Well, we do export nl_langinfo, setlocale etc. as weak symbols for users to override so I suppose I'll do the switch. But quietly, so Benny doesn't realise it. (Damn.)
Ich bin eben über einen Vortrag zu Plan 9 gestolpert,
ein System, das selbst einem Unix-Alteingesessenen
noch komisch vorkommt. Die meisten Leser hier wird
freuen, daß man 'ne Maus benutzen soll.
Vortrag:
Plan 9: (oder)
Es gibt auch p9p (Plan 9 from User Space), um das mal auf Windows (frühe Alpha) oder Unix auszuprobieren.
Den C-Compiler hätte ich gern, um gcc zu ersetzen, aber die Lizenz ist leider auch nicht so wirklich frei.
Interessant: es ist von Oberon abgeleitet.
Sehr schön auch: ETHZ Oberon ist unter einer 3-clause BSD-style Lizenz freigegeben, also quasi "freier gehts nicht".
Und auf der oben genannten Homepage kann man die Bücher "Compilerbau" und "Algorithmen und Datenstrukturen" von Prof. Wirth frei herunterladen, allerdings die Oberon-Variante, klar. Und natürlich einen Haufen Oberon-Literatur.
Ich hatte vor einiger Zeit tatsächlich mal ETHZ Oberon nativ installiert, war ganz lustig, aber ich bin dann doch nicht so der Mausschubser…
I still have DNS trouble which bogus cannot reproduce; his dig shows tld1 answering, host doesn't, he can't ping. But I just got an eMail from someone using so I guess something is just really FUBAR or wrong here.
30.03.2006 by tg@
Today, it's porting kencc and fixing gcc. Duh.
All I wish for now are proper COFF support in the kernel and support for the *.8 object format (intermediate) in libbfd; some startup files to make 8l output work and maybe we can use our libc if converted from ar(1) to iar format. Later, we can add ELF to 8l.
Funny people on IRC. No, really. Why should Unicode die?
On ICB, Theo's been an arsehole again
/group hackers [=Status=] You are now in group hackers some interesting facts about the Plan 9 compiler: <*deraadt*> who are you? <*deraadt*> developers only. it's now part of "Inferno" and thus under MIT licence I'm that MirBSD guy just trying to port it in order to look if it can be used to compile at least simple programmes <deraadt> So please fuck off. okay, I just wanted to be nice and tell you /quit
... what do I do? Nothing.
The only positive thing is that, despite the rain, it's been a nice, quite interesting, day in various regards. Too bad I'm still awake and probably won't make it in time tomorrow either...
31.03.2006 by tg@
Today, it's porting kencc and fixing gcc. Duh.
It was a fucked up day, the weather was bad, people, events were bad and this day should be banned...
... at least I got gcc working.
I can't seem to either run (kernel) or convert (binutils) a COFF (or ECOFF, tried both) executable. Why?
The solution is probably really to teach 8l ELF... although this will be very much work since 8l is not the only linker.
Benny is still not committing, he rather wants to go to bed. He sent out an announcement for the MirOS #8-stale sendmail(8) security update though (after I MFC'd it ;).
Did I mention gcc is a pile of crap? Well, I had to pay for using an alpha version of GP – but the rest still is the biggest pile of... interesting stuff... we have in the OS.
Well, kencc doesn't do Propolice, W^X, NXSTACK, NXHEAP etc. (and ELF might help with the latter three but I don't know if I'm up to it, and Theo won't do it, see above...) so it's probably only going to be used as an alternative compiler for those who dare. Security checks (format string warnings, __attribute__ stuff etc.) are done with gcc.
Oh, I forgot... the INT 80h API sucks
#include <sys/syscall.h> .intel_syntax noprefix .text #define SYSCALL(x) \ mov eax,SYS_ ## x; \ call syscall outstr: /* strlen */ mov edi,edx xor ecx,ecx dec ecx mov al,0 cld repne scasb not ecx dec ecx /* minus trailing NUL byte */ /* write */ push ecx push edx push 1 /* fd */ SYSCALL(write) pop eax pop eax pop eax ret exit: push eax SYSCALL(exit) ret syscall: int 0x80 ret
... anyway, this works - provided that the ELF contains .section .note.miros.ident,"a",@progbits, or you make an OLF out of it (which binutils and gdb can't use). Speaking of suckage. (suckage.netbsd.ch by Tonnerre is down tho.)
06.04.2006 by tg@
Lately I've been working on a Live CD which is to be built as a part of the normal 'dist-q' process. I'm improving continuously; I unveiled some bugs in the system during that and am currently rebuilding MirBSD at 900 MHz, let's see how long it takes without Ada and GCJ ;)
My coffee provider has an enhanced set of offers and a new website design, check it out. Today I ordered the first time online there, they use "Bankeinzug" and give 2% discount on that, even. Cool. Of course, SSL secured (hi entropy).
More later…
… oops… it's already this late. TODO: fix kernel msgs (a la "swapconf: blah not found"), use rd0a for devices (XXX howto, can I preload it into the kernel? I even think so), get rid of the huge time consuming MAKEDEV stage in /etc/rc (and don't swapon rd0c *g*), make a liveboot (with sercons by high order bits), last bring back X.
07.04.2006 by tg@
Café Libertad delivered in less than 24 hours. The DPD person today surprised me at about 11 o'clock. And they put lots of anarchist advertising material, a poster and (YAY!) some (notebook!) stickers in as well as a "self-organisational newsletter". Me likey.
Only today I got notice that Benny is having a one-week trip with no internet access… and that's only because of some allbsd.de mails and not because he told me. And that despite me trying to impress him, and the rest of my readership, with this live CD (and my call for some testers). I don't know where he travels to, I can only suppose it's an important thing related to studies, for he explained me some of _that_ bunch of problems recently (and I don't know either how he can manage; that's one of the reasons I stopped studying altogether).
From the category "useless patches I designed and took me some time…
H4sIAAAAAAACA6VXa1PjxhL9bP+KXie7kbGELb8AAwlk2ZtQxeItINlKEcolS2NbhaxRjcYG35v9 7/f0jPxiIUslrkUrjXpOd58+0zM6TyPx2KM4zXWQJEMp9W5YPv73v/LV+2saxYnoUT2c5/VchfV8 kdcDFU7qcWu/W4fDNKpvOK5vBeHOy0poFYt5nI5J4b88lin5uwflKB6NyJuRl5GnMPAkes/ztkdK e3SaKWo2Gl1qNnvtbq/dIa+BX4nharXa39p3/F5r39qXT07I812/QTVzPTkpe/WdndL3H2PVv+7R P8iSMzKu6o12vbG3DlCP6cNjRt/TTr1c+/dO9tZOuuT7vcZer+VvOaE6fPQzkf58ffZEEQahbSA4 yLrfoabfa7d7fpe0nFqM0hLjUugXIDrkHxx06r5f9wHW6uFfp0HjB7URBWN4ZY926L3MFioeTzQ5 YZV9t1wTgbl22KR0M5Eq1yKlyjRWwRB6q9AvSZALRUd6fNLtTnbbzcluJH4s176JaK5dNlzjboDB wzCPDBbRDv/RRRyKNBeC4pwmQonhgjKhprHWIgIxFIkgAQ2kJzB4kOqeHmI9kTMNQecQd+gZGA1l u7ALk1nEap+lSQwQYJhgc4aa5cKlbDZM4jAxXkZSTV2aSqyGhWuF2XK7EGarUCYjwzcqAG9RzP6G M3aVk1QYypSMZiGcsFEYymkWpAt2H8lwNhWpDtjYwMBeaiRI00ALFQdJTpg9jyPM5oxoGKeBWjz1 s2uIYuJPEUQQzYXSWMZwscZhR7DlwZEI9AzEsDukS3JkicvlSHsG5iFQgqazXBP8ZEmwgIGgkUwS +cAIQXifyodERGPBuL2ilrEJF8nqgmT4WEawTgTFe1L2XZ6/UWimYTQSKjduTT0rp9d0fl0hLED6 fH7za/+3G/p8enV1ennzBycASuk+TiPXwIjHDPnlLmcYT7MkFpHLxWW4afAYT2dT2CAAvaEjxBVk sA2DYSIMTBI8uCslTQO8iuUsR25mJrDHSuY5pWKcxGORhuKQa5xKEnM2mAYLq5dm191nwTSsYijn koeMU4rkQIlQqsiZDfC8P9C041IURJEa6PLSci7jqIxaBWPh8H21TP8re6VRpjBn5OQ6Ekq5VDEW PXqb062X3uEy5wsqK0IPiXpaoXJ3VCnXXpr7p/72ZCoRfpVbb0JmzLwNF8kdcQuiJMIMLMk5avln WnFpMEDtx2kwFdXD5zw/8emdGxykrrS5E6i5BeWNbjfOJcMCicPYAqeSeIy14/PtF7Q4w/5+0/V9 0L+/7/pNpn8axKmDEChQ49ClcBIo2sH9/PYOxJaGscwH0D3kNJIDXgIMnEheTkMlRzk/8nQ8ZYiR czJvERje0jE1XL5PoG/cH3Kr/Tpps8kQ+vdm+6YK8vm5378Z/P7hCsSklaqdjuYXaqwZAKYTEUR8 4/mH0MDDBJyQ44QYGQstM+3YtDgh+Jn0PqafenlvXqlW6Q3PqkI7tVfMO392JpVKOZZEODGt3TyH WMP0w+SHHj+UVvEFWsYOcAGILEwpDjrcOZsNU5FvV2ITjbPlkS8kklyU0LdUngmOvngxVCK451oU 8ZwjHjyUVlVBw9QyKSJy6fK3iwuXGkaSsBqRU1gekV81YyVU6tHxQUaczrH6ow1dAsL07koxv/C+ YuMjs/EdUBsmuFoN20goBpCMpaLZPDBUtH334DVMQM38B18bkb57Rw4TkWn66y9yViIpimXGLH92 pGrysm2E42YdA41dkkcgBg0U6beKuq4M2bUJurXn4kBRa3aabqv1irCxNNF1j42mbgv8Gvl3DAnC EjQJvLXXbZsm20De9R3io5Lp++FEhPekggfele6LDsNnGc+k4WBgFAFJYgLu+dkFA/JBYY//ifqD q7P+5cUfPb75fFV1Ma9kegj1P324PPvw++DT6dWNS++K0CD7IwiEzaAEIwSG5v6KrrY0OtyqiV1c pdXyL0THwnkiuWIOmx0dF73D6u5Z2XETfCK6lZPixlt2oBqvidpK+kfAb658btG0zRGtSaIeFTQt WSgie0rDkgK7Lm32ryrac+G8qmpmab6ibC8EvFm3L6a5chg4Mg1lLqpmX/26W3MFeL7Zz/hhq4ar yr00L5nxn5lszVcbxA61LRSz97cYW77pGTuz2FaG5ukFS1uElemaka97jMlrzKsYJ5VEBpHBXfeO WIY6sTV06ey8//6Xs/PL//RRjSgxu0bDtK9lHVgDSTAUyVfFsJt1s2Pb4kHD3XtFf+EIomQ3GuhF Juh46Q3H1/TRWTsj83qW8qG12FJrW/nwzgXRXuDZEkfDRIb35qgnCcczo1jrzzEGuebBY1pB2An2 JbK3RvF/BdSIuHjlWyKW5xOT7V6bs201um6r88p0R3wkXBL+Lh8WYt/gmA2eofeZLrU+cg75FLNU 9HItPC/HzzG+MThtI+uCJ5zAOVlzsrSLs9JstPdJBOFkd6l76N1qfajBnJk50HzYHmRmuDiSFJY2 RLatHZM9Iw/MHGeo18uovdy/i853TO3VAFA8zzx9Kbw+h9QoOvIye5j9iOtmdGio+GowQxzZky59 IyVe4/vDclGpvprKtznqFBE6uooFf33iHEjOW/4U0SKvFqdcy6fdQWxYoZylepDdNu6gkZlaBbbh +E3RQJc08pgZWEpnreLlPYuVV+z6aXUKMnnaLcIegVSQFZuQoTZMkKRFtqNK4AszJadRtNllu3hz PTi/fv/rlZMPd3M9wFc1FkghXssmc3KJk3Bg1B+E+HosNo0nev4/Dg3uDVITAAA=
(yeah, base64 gzip'd)
I should be working even more on the Live CD but that's it for today (after realising that the above patch is not useful unless /boot gains ISO 9660 filesystem reading support. (Also it seems to not work.)
After poking around a bit, I found out this diff indeed does work, I just need to use workdir/usr/mdec/boot instead of the logical workdir/etc/boot.x86 because the latter contains a mkisofs(8) boot info table which forces El Torito boot.
After poking around even more I shockedly found out
that our /boot can actually read (just not 'ls') ISO 9660 CDs
(when used as hard discs) without further patching.
(Now that I'm writing this wlog entry, this isn't that surprising – after all, I had patched in "no emulation" boot some time ago.)
So it can be used, and this patch shall be committed instead. I'll retain the early version from above though because it expresses quite some of my frustration of today.
I hacked another bunch into it now… support for images of hard disc drives (with 512 byte sectors instead of 2048), using a specified PBR (512-byte) sector (instead of sector 0) or even (hard disc images, only, for obvious reasons) MBR partition table support (including that userpt stuff). userpt is also supported for CD-ROM images, though it's probably not very useful (unless booting e.g. a kernel from wd1). IMHO these things are all nice to have, will prove useful and make a unique selling (and marketing! hi Daniel) point.
I'll forget the idea about porting it to GNU/Linux though – it doesn't even have nlist… how am I supposed to get the offsets of my declared-as-global functions within the ELF first-stage boot loader now? Some Lunox or Kinderunix guru reading this and want to send me an unidiff? (Only -i must work, -I or neither-of-these-specified does not need to be used. Partition tables must work, though.)
09.04.2006 by tg@
There is not much to say today. I'm slowly improving but there are a days or times where I need to rest too. At least I fixed the web pages (plain text versions) of the licence templates (rcs -kb), added a link to the MirOS one from the ISC one (like ealier in the web version) and fixed a spelling mistake in ours.
I got a new user for 魔王 and I hope he pays and behaves well… if so, I'm not going "into red numbers" with the box again.
I wonder if it's a good idea to hardcode 魔王の IP address on the live CDs – but then, MirOS doesn't have more than a few hundred users world-wide, NTP intervals are large, and the first rdate(8) call doesn't hurt either. (Too bad there's no way to send any entropy back with an NTP answer packet – at least I did not find a way to…
11.04.2006 by tg@
The live CD's completed, uploaded at BitTorrent, I organised some press coverage at Dæmonnews (and hope the word spreads). I fleshed out bugs (at least these I could find) and shrinked the size again.
Benny is in Dresden, GDR, by the way.
12.04.2006 by tg@
I've fixed a lot more things in the live CD, created a /cvs snapshot and started to change more things (e.g. NFS exporting the live / for a method to easily pxeboot other live CDs as live NFSes).
After Zapata has closed early (mother of the cook fell ill) and we'd eaten at the Croatian again, cnuke@ and I are sitting at Jannis' place and I tried to pxeboot his IBM X41 (failed due to his Broadcom NIC). I think it works, though. Met (honey wine) is tasting good tho. They are playing StarCraft (a fun game, but with a weird custom map) and I grin in the background, not really knowing what to do (except drinking some (admittedly too much) honey wine).
I found out that one can't post to the GNU Pascal lists via GMane (a bad thing since I was advertising for them). I wonder if the other few things I noted to the people will be fixed soon (enough).
gcc 4.1 looks promising but I haven't started porting efforts yet. I currently wonder whether I even want to do it before #9 (whose release criterium was OpenBSD 3.9 being merged in). I look like I want it, but I think I better shan't. We definitively need someone to work on ports for the release, too, though. And I'd better fix sparc. (Sadly, my new CD-boot and sparc dual-boot don't combine.)
NetBSD® makefs(8) will hopefully replace mkisofs(8). Even if I'm to patch in -boot-info-table support by myself. Schily must die.
At the moment, I'm building MirOS snapshots (and auto-live-CDs) like exemplars of Ford Model T. Trying to improve, I suppose. I don't see a lot of rough edges left (though a rewritten boot loader could e.g. say which root device the kernel to use).
Yay! Freeforge is growing. Even though 魔王 froze today, again (BitTorrent was running, but the crash was during an rsync).
19.04.2006 by tg@
Just came back from a great trip to Bruxelles. In the meantime, that damned dedicated server froze again – without any BitTorrent and rtorrent involved. gecko2 now has the licence to reboot.
I've prepared today what will be the Setup/Live CD tomorrow (the one which will be distributed at LinuxTag).
Benny has been alive today!
08.05.2006 by tg@
At the moment, I am developing on my trustworthy SPARCstation 20 (to which a digital VT420 is attached as console because a monitor would be too heavy for me to lift it) since my laptop is fried again (PSU, already for a while, and the TFT inverter, for which I try to get a replacement). After somehow getting GNU screen to honour flow control, it's really not too bad, and I've gotten used to it. Besides, amber rocks!
I don't get any help from people when I post requests to the mailing lists. For example: fdialog, the live CD, python, discussion requests, like the gcc language stuff, Xen, motd, spamd, IRC, EXEC_ECOFF support and bugs, infrastructure/scripts/out-of-date, "mmake clean is broken", "/cvs/CVSROOT/*.sh", Bruno Haible, and some more bug stuff. That's why I am developing merely for myself at the moment. MirOS #9's release is depending on a criterium (merged in current stable version of OpenBSD, at the time of releasing), but I probably won't release it without the wide char functions working and the SPARC port revived. Furthermore, I am diving into MS-DOS® coding… you've been warned.
Expect a new version of mksh to be released RSN (like, in a few days). Most important new feature: ~/.mkshrc, by request of a Debian user who also prodded me to enhance the manual page mksh(1) – it includes the latest fixes by OpenBSD too though. I also cvs admin -b'd portable mksh's extensions (four files) into -rHEAD so that people can test any mksh extension development directly (without the Attic).
Do not expect the website to change much, or be updated (probably as calendars don't get updated by anyone *sigh*). I will work a little on improving stuff found during more extensive testing of the live CD and portable mksh in the next days and then look where my current interest is tending towards. Watch source-ch^W^Wmiros-changes@ for info. It may look as if it has turned back into MirBSD.
Stability issues on the server still have not been sorted out, and I am out of ideas. But we can't easily do without, either.
Finally, a word: while it may be hidden from the mainstream, and its activity not be reflected on the web site, mailing lists, freshmeat, a trade fair, symlink, OSnews, Dæmonnews, allbsd, undeadly, etc. I don't see it sinking into oblivion. But I am going to focus on, merely (until I get responses like the recent mksh discussion), developing on what I think is needed. This may include a framebuffer device and/or X server/module for a 20+ year old graphics card. I'm, also, looking for employment and would kind of like to "bring in" MirOS, but I don't think that's going to happen. At least not now – even some finnish person who can't even program sprintf(3) made a job out of it. (He didn't discover the bug in that function for years, either.)
22.05.2006 by tg@
This wlog entry is probably not read by many. Thanks to gecko2, I've got set up at least an AnonCVS mirror (anoncvs@unixforge.de:/cvs IPv4, anoncvs@hephaistos.tb.as8758.net:/cvs IPv6), and remotely possibly, this page might, with a few broken links/images, be visible.
I'm "developing" on NWT at the moment – a Mitac 4023 notebook (Cyrix 486DLC with 33, 66 or 80 MHz, no idea; 12 MiB RAM (and a custom kernel); a 450 MB HDD replacing the old 110 MB one and, yuck, french keyboard (slightly remapped) in US mode of course). I've put an almost usable filesystem on the disc (the contents of bsd.rd's mr.fs), added a few programmes and a dmassage'd GENERIC minus what I don't use on the book (like ext2fs), that works. Its display is okay, (D)STN LCD in VGA greyscale, and I am already getting used to that damn keyboard, but more than less(1) and ssh(1) isn't feasible. Not really good to do any developing work.
The server situation is desastrous. I'm thinking of giving up having an own dedicated server and just paying a few people for the services, that is, AnonCVS, AnonRSYNC, website + CVSweb, name and mail server. I think I already know with whom and how to do it, I but need to get out of the contract and, beforehand, back the data. Strato at first tried, I was impressed, to help but now runs a "let's ignore him" strategy. I can understand that, after all I'm only paying 19.90 € per month, but nevertheless they're denying me service.
Oh, by the way – I got odem back working, just its display is, still, a mess: the green part doesn't show. Headaches.
Benny has been helping with ports and the interim (excuse for a) web site^Wpages, thanks.
Hiroki Sato managed not only to get production IPv6 address space to keep *.allbsd.org reachable but also fixed the mirroring problem, so I think we have two working anoncvs mirrors at the moment. Again, thanks to all the people involved with BSD or not even (e.g. a certain Debian Developer springs to mind) who are helping to ensure the MirOS Project doesn't continue to exist in oblivion but is still discoverable by the general public.
27.05.2006 by tg@
Not that this is going to be read... congratulations to a few mates, celebrate your birthday, may you already be able to walk on four legs, being able to walk on two comes the day after.
Benny's going to rewrite the website's content this summer (simplify but not change the layout); mksh R27c, mirmake, cksum and mircpio have had new releases; there have been a lot of minor changes; base is in a good state and ports work on Mac again (including mc).
Debian's cvs(1) must've smoked something weird… it formats the RCS ID timestamps yyyy-mm-dd instead of yyyy/mm/dd. For now instructed gecko2 to place a hand-crafted cvs binary from MirOS sources (plus Han Boetes' arc4random for GNU/Linux and hand-compiled libc ndbm) into the anoncvs home directory on hephaistos. That box is also ntp.mirbsd.org, IPv4, even though not running OpenNTPD, because the live CD gives some unfriendly messages at startup otherwise. (To prevent a phk-dlink like disaster, he's been informed though. I hope something else comes up in short terms, though.)
It could rain a little less.
28.05.2006 by tg@
Waldemar Brodkorb, a friend (and beer drinking mate) of mine, has had to leave the OpenWRT project in order to fork. Sounds familiar? Well, I am now a full FreeWRT developer as well. Just wanted to tell you, so you don't worry – I won't lessen working on MirOS. Rather, I may be able to impregnate the GNU-dominated world of embedded systems with a little BSD spirit. The reasons for him leaving have been outlined in his blog as well.
02.06.2006 by tg@
This is available under
MirOS now has I18N support. Totally untested. Please test whether it "works", the manual pages don't disagree with SUSv3 and ISO 9899:1999, the code adheres to the manual pages, the code is bug-free; write some more (missing) manual pages, etc.
03.06.2006 by tg@
Forking seems to be common against my Verpeiler mates; first wbx and OpenWRT/FreeWRT (and he's done an OpenBSD/WbxBSD split too, with MirOS stuff inside), after – of course – me OpenBSD/MirBSD; now, Angelo Laub (yeah, that MacOSX worm guy is a drinking mate of mine) does an OpenBSD fork as well (or, at least he's asked me for help).
Benny is never there when you need him except later, but the old and new fxp(4) codes both work on HERC, so what, I leave in the new "old", he'll test on monday, and I'll go snapshot now. Expect some surprises, if everything goes well.
TGEN and Tonnerre are interesting people. Sad they're usually quiet, in IRC (#bsd).
09.06.2006 by tg@
I finally got maou rebooted, I'm currently backing it up via serial, yes, 56kbps, console ;) and have already found a person who'll take it over so I'll be relieved of the payment soon. I'll just rent space, at gecko2s box for now.
gdb doesn't work with the J or Z malloc.conf(5) options…
Found some more annoying bugs in libc/i18n, should be all fixed now. Also, I removed a few unused programmes and libraries; no need for the year-old unmaintained and unaudited stuff to linger around.
The tries to update libncurses failed… see the commit message, if you really want to know more.
10.06.2006 by tg@
There was a soccer competition at my university – although ex, I participiated, and it wasn't even me playing badly that we lost, but the others (Economists, Mecha builders etc.) brought some professional players so we didn't stand a chance. 4:0 4:0 1:1 and out.
I didn't have much success trying to trace down my LCD issues. It is in both cases a low-voltage differential thingie with digital (serial) transfer, so no idea why green is missing. Looks like I have invest my first FreeWRT wage into an LCD, or rather, a laptop – or ask the local Arab whether he's got an idea.
Still haven't done much for FreeWRT, but tomorrow, wbx@ will show me how the system "usually" works under GNU/Lunox. Also, I will start by doing an mksh port, let him check it and then try a 'svn ci', in the hope I didn't do anything wrong, to test that.
Oh, the surprises are unveiled I guess. I've just cross-built a (not yet tested) GENERIC for sparc. More surprises to come.
11.06.2006 by tg@
I had some initial FreeWRT ci with wbx@ today and better would ask gmane and marc guys for archives, before it's too late.
I built a sparc bsd.net kernel (with elf2aout(1) on i386!) but can't netboot it... it's been too long since I did that (>2 years).
I had four Altbier (beer) and some Julishka and Krushkovac today, so I'm not really coherent... but it tastes delicious!
12.06.2006 by tg@
Not much success with sparc…– as if there were some bug, deep hidden inside the kernel. I will try building a #9-beta kernel on the box (natively on #7-stable) then. UPDATE: Didn't make a difference either. Can please someone tell me why it freezes in midst of a printf(9)?
Not much success with "real life" either and it's just too hot for real FreeWRT work. Also, I ought to add .gz read/write support to config(8) -e…
15.06.2006 by tg@
Yay! My laptop works again. Did cost me 50 € and lots of sweat, though.
As we have had a sendmüll update, I am to issue a first #9-beta snapshot (i386) to the people. It already comes with brk malloc, non-g libs, etc. as it's resembling the upcoming release. There is still few stuff missing:
- Send out an eMail "status report"
- Update ports: rsync, unzip, zip, mplayer, gmake, bison, maybe bind (assigned to bsiegert@)
- Update SSH and similar stuff
- Have a look at if there's a newer GNU Pascal (probably not)
- Fix sparc
- Add gzio support to config(8) -e
- …
Markus Rosellen is sponsoring us a show-case Compaq Proliant 800 for the FROSCON, which to install is bsiegert@'s task, again. Thanks!
pkgsrc® on Interix sounds funny, MirPorts is easier or better in some regards, but lacks others. It's not used at the moment anyway.
Why must it always be so hot even while raining?
16.06.2006 by tg@
A shitty day. The weather was superb. Sunny, dry and not too hot due to the still resident rain remnants from yesterday, not sticky either. Yet I had noone to kill time with except my trusty laptop and sparc. I "forgot" to breakfast either, and apparently I'm too late to go shopping now as well. Doesn't matter though, I keep a few things at home for emergency hunger cases ;) and had bought a lot of beer 2 days ago because yesterday was national holiday anyway. I might have diner, no idea with whom though, in the city later.
On the western frontier… I've built myself a sparc kernel which does now boot (some delay(9) calls added), but doesn't cleanly execute any binary, save the following one:
#include <fcntl.h> #include <stdio.h> #include <unistd.h> main() { int fd; printf("Hello, World!\n"); fflush(stdout); if ((fd = open("/dev/console", O_RDWR)) == -1) { fprintf(stderr, "cannot open /dev/console\n"); } else { write(fd, "This is the console!\n", strlen("This is the console!\n")); close(fd); } for (fd = 0; fd < 10; ++fd) { printf("."); fflush(stdout); sleep(2); } printf("\nexiting...\n"); fflush(stdout); fflush(stderr); return 0; }
This includes finding and fixing a few bugs in libc, building and installing csu, building and installing the static libc stuff, first, though. And I only get this line: "This is the console!" (Afterwards, I end up in ddb(4) which is sort of cool, really, as I can type "machine prom" to cleanly finish off the infantile operating system.
Due to the many recent fixes, I must build and release a snapshot to the public first though, afterwards I might tend to the pending issues (such as gzio support for config(8) and sparc userland). And of course the status report eMail.
Fun. I built (almost) the entire system with the cross compiler, and I wonder whether it works at all or what works. Discovered a few bugs, mostly Makefiles, in between – explains why macppc did not work. I could probably build lynx(1), mkisofs(8) and rcs(8) and its friends, but that's not worth the effort, and they can easily be made natively. Still, almost all non-GNU tools are built now.
17.06.2006 by tg@
It's warm, but still cold enough to not freeze my laptop during that all-night release build. It succeeded, even in less than 6 hours (at 1 GHz), and I invented the idea of gzip(1)'d ISO files in torrents which helps people with slow internet connections…
Now trying to get sparc going, and tomorrow there's a hacking + Jugo session with wbx@ again.
Except for a little TRAP 04 (fp instr while fp disabled) I've got my sparc running multiuser and starting to build ld.so, shared libraries, perl, all the stuff you can't cross-build, and ports.
I also gave up on the amd64, macppc and pmax ports. We're restricted to i386 and sparc for now, due to lack of resources.
still counts as 18.06.2006 by tg@
Today's entry is not a wlog but a blog entry, sorry people, but wbx@ prodded (provoked too) me after an 18-hour hacking session to write about FreeWRT been cross-built. Guess: Which host operating system, target OS editor, shell? (You probably already know without reading that blog entry.)
MirOS also profited from it – fixed a corner case in $PS1 home directory to tilde character (bash-like) expansion.
Now I have two operating systems to take care of at MARC, GMane, OSnews, DistroWatch, Freshmeat, Slashdot (no longer since they're not lynx-compatible any more), Symlink, and whatnot. Damn!
wbx@ will regret it some day to have me as core developer… I'm the first one to write an UTF-8 commit message and compiling an editor with UTF-8 support although that is globally disabled also goes to me. I also named patches "interestingly" and cursed almost every other project in the world, mostly Linux, but also GNU, OpenWrt, and a few other entities, as well as both hard- and software, in today's svn commit messages. And that only was the first day… I already have been thinking about evil plans with entropy, arcfour, openntpd, and an astonishing number of other things I already forgot.
Note to self: mksh's Build.sh is not designed for cross-compilations. Almost as evil as pppd(8). Fix it for the next major release.
À propos Subversion: It is as shitty as CVS, only slower. I'm serious. I really mean it. I mean, I've ranted a lot about svn before, but now that I've actually used it… it's not gotten better. It's really slow and sucks. Rather the contrary. Well, it can do renames or moves, right? Thanks, I'd rather have working $FreeWRT$ expansion than that (yes). Oh, and please, could we set that globally instead of have it being made a property of every single fucking file in existence and having to take special care for newly-added files? CVS rules seriously (I'm positive now).
23.06.2006 by tg@
This will be the last wlog entry, as we're preparing to go to the FrOSCon 2006 now. After exactly six months, this ends the life of MirOS #8 without prejudice.
agreed bsiegert@
Good luck, have fun, take care etc.pp | https://www.mirbsd.org/wlog-8.htm | CC-MAIN-2015-32 | refinedweb | 13,266 | 72.26 |
Folks,
Is there an established design pattern for setting up audit trails for entity beans? I thought I'd better check before launching into my own design.
Basically, I want to record every update to a given bean type in a seperate, "shadow" table. I was considering just defining a new bean, and using the session facade to copy the values across after every update to the main bean type. It's not very elegant, but it's easy enough to do.
I'd be open to any better suggestions.
Patterns: Entity bean audit trail (5 messages)
- Posted by: Kenny MacLeod
- Posted on: April 21 2004 10:55 EDT
Threaded Messages (5)
- Patterns: Entity bean audit trail by Senthil Chinnaiyan on April 21 2004 11:07 EDT
- Patterns: Entity bean audit trail by Kenny MacLeod on April 21 2004 11:25 EDT
- Patterns: Entity bean audit trail by Kenny MacLeod on April 21 2004 11:26 EDT
- Patterns: Entity bean audit trail by Mircea Crisan on April 22 2004 02:34 EDT
- Patterns: Entity bean audit trail by Senthil Chinnaiyan on April 22 2004 08:05 EDT
Patterns: Entity bean audit trail[ Go to top ]
I think, EJB doesn't have that functionality. Implementing it from the database side using trigger will be much easier and effective.
- Posted by: Senthil Chinnaiyan
- Posted on: April 21 2004 11:07 EDT
- in response to Kenny MacLeod
I think ejb should come up with a new functionality like "Triggers", becaue, it already has relationships, cascade delete and all.
Thanks,
Senthil.
Patterns: Entity bean audit trail[ Go to top ]
I'm not looking for EJB itself to handle this, I'm just looking for a design pattern that I can use to achieve the desired effect.
- Posted by: Kenny MacLeod
- Posted on: April 21 2004 11:25 EDT
- in response to Senthil Chinnaiyan
I was hoping that XDoclet provided such functionality, but no such luck :-(
Patterns: Entity bean audit trail[ Go to top ]
Oh, and database triggers aren't an option in this case, I'm lumbered with MySQL 4, which doesn't support triggers.
- Posted by: Kenny MacLeod
- Posted on: April 21 2004 11:26 EDT
- in response to Senthil Chinnaiyan
Patterns: Entity bean audit trail[ Go to top ]
Hi,
- Posted by: Mircea Crisan
- Posted on: April 22 2004 02:34 EDT
- in response to Kenny MacLeod
If you havse some DAOs for the stuff you want to audit you could make a set of AuditDAOs and AuditWrapperDAOs implementations. AuditDAOs just log the audits in the 'shadow' table. A call on an AuditWrappersDAOs will split into a call to a DAOImpl and a call to a AuditDAO. You can configure your dao factory to return DAOImpls or AuditWrapperDAOs, depending if the auditing is on/off.
Best regards, Mircea
Patterns: Entity bean audit trail[ Go to top ]
How about this one? I haven't tried this yet. I just had this idea. I am not
- Posted by: Senthil Chinnaiyan
- Posted on: April 22 2004 08:05 EDT
- in response to Mircea Crisan
sure will it work.
Assumptions:
1. Audit implementation does not participate in any transaction of the business
flow. <br>
2. Audit will be done as asychoronously, errors on audit will be reported in
a TABLE or log file. This is to improve the performance.
<br>
Steps:<br>
1. Develop and Implement the business logic in session facade as synchronous<br>
2. Implement the Audit logic in Message facade as Asynchronous<br>
3. Have a wrapper method in the session facade, that is going to be the business
interface method for the client, iside the method first invoke the actual business
implementation with transaction and after successful, invoke the audit method
on the MDB.
<br>
Example:
public interface MoneyTransferFacade extends EJBObject {<br>
public void transfer(MoneyTransferDTO dto) throws RemoteException, AccountException;<br>
}
public class MoneyTransferFacadeBean implements SessionBean {<br>
.....
public void transfer(MoneyTransferDTO dto) throws Exception {<br>
transferActual(dto);<br>
transferAudit(dto);<br>
}
// This is the method actually implements the business logic. So set the transaction
attribute only to this method, ex: requiresNew
public void transferActual(MoneyTransferDTO dto) throws AccountException {<br>
// Here call the Entity Beans ot DAO methods.<br>
try{<br>
Account.deposit(dto.toAccount, dto.money);<br>
Acctount.withdraw(dto.fromAccount, dto.money);<br>
catch(Exception ex) {<br>
ctx.setRollBackOnly();<br>
throw new AccountException();<br>
}<br>
}
// This is to invoke the MDB, So, don't set any transactional attribute to
this method.<br>
public void transferAudit(MoneyTransferDTO dto) {<br>
<br>
// Here create a Object Message with MoneyTransferDTO and send it to MDB<br>
}<br>
.....<br>
}
MDB:<br>
public class MessageMoneyTransferAudit implements MessageDrivenBean, MessageListener
{
.....
public void onMessage(Message msg) {<br>
ObjectMessage om = (ObjectMessage) msg;<br>
try {<br>
MoneyTransferDTO dto = (MoneyTransferDTO) om.getObject();<br>
// Here invoke the Entity Bean or DAO
}<br>
catch(JMSException ex) {
// On exception invoke ErrorLogBean to report, which maps to a Error_Log_Table<br>
ErrorLog.log();<br>
}<br>
}
.....<br>
}
DAOs or EntityBeans:
Account ==> Maps to ACCOUNT_TABLE<br>
AccountAudit ==> Maps to ACCOUNT_AUDIT table
Thanks,
Senthil. | http://www.theserverside.com/discussions/thread.tss?thread_id=25417 | CC-MAIN-2016-18 | refinedweb | 832 | 50.36 |
.It is assumed that the reader has gone through the project How to get started with AVR and Interface LCD with AVR.
Components Required
1. ATMega16 Development board
3. SIM 300/900 GSM Module
4. 12V/2A Power Supply
5. SIM card with balance (or at least message offer maybe)
10. A PC or a Laptop (Optional. Needed in case of debugging)
Initial Setup
See my previous tutorial “GSM BASED INTRUDER ALERTER” if you are using the GSM modem for the first time.
Fig. 1: Prototype of AVR ATMega16 and GSM Module based Mobile controlled Home Automation System
About Relays
The switches at our home need to be operated manually by hand or “mechanically triggered” in order to work. If we need to control the switch using a microcontroller which does nothing but produces 5V or 0V at its output pins then we would require extra mechanical arrangements like a servo with an arm, to press the switch. Instead of building such complicated arrangements we can go with a relay. These can directly be controlled by electrical means.
Working of Relay
Fig. 2: Image of LCd module attached to Home Automation System displaying appliance status
Fig. 3: Circuit Diagram showing NC connection of SPDT Relay
The above shown diagram is of a SPDT (Single Pole Double Throw) Relay. It consists of 5 terminals. Two of them are from the coil where the input to drive the relay is supposed to be given. The other three are NO (Normally Open), NC (Normally Closed) and COM (Common).
When no input is given to the coil, there is no magnetic field produced. So the “NC” and “COM” terminals are connected and the “NO” terminal is left free.
Fig. 4: Circuit Diagram showing NO connection of SPDT Relay
When the input is given, the current flowing through the coil produces magnetic field (Basic physics) and thus attracting the lever, which breaks the connection between “COM” à “NC” and makes a connection between “COM” à “NO” terminals.
Again when the input is removed, the spring attached to the lever pulls it back and “COM” à “NC” connection is re-established.
Free-wheeling diode
There is a problem in connecting a relay directly to an electronic circuit. When the input power is suddenly removed to switch OFF the relay, a voltage spike occurs due to the presence of the inductive load (The coil inside the relay is an inductor right?). This voltage spike can permanently damage the electronic circuit to which the relay is connected to. And thus we require a diode.
A diode connected in reverse bias with respect to the input supply, will prevent the voltage spike (produced by the relay when the supply is suddenly switched OFF) from reaching the other part of the control circuit.
Fig. 5: Circuit Diagram showing Free-Whelling Diode connected to Relayto prevent voltage spike
Next, we need something to supply enough current to the relay input so that it doesn’t trip unexpectedly. So we use a transistor in between microcontroller and relay. And the circuit becomes like this:
Fig. 6: Circuit Diagram of BC547 Transistor based Relay Driver
Advantages of Relay
No degradation of the switched signal.
1. Offers isolation between the AC supply and the Circuit.
2. Lower Impedance and easier to interface.
3. Robust.
Code Explanation
The code is build mostly around the library files “GSM.h” (Thanks to Engineers Garage tutorials) and “LCD.h” which contain the necessary functions for GSM modem interfacing and LCD interfacing.
GSM.h contains the following functions:
gsm_init() : Does the initial testing like checking for response after sending “ATr”, checks for the presence of SIM card, Network and then sets the modem into Text Mode.
gsm_read() : Tries to read the message stored at location ‘1’ of the SIM. If there is a message then it stores the first 9 characters of it in the array “msg[]”. Then checks if the string in “msg[]” matches with the keyword or not.
gsm_delete() : Deletes the message stored at location ‘1’ of the SIM.
gsm_waitfor(char c) : Waits for a particular characters specified in the variable ‘c’ . If the wait is longer than the timer set in the Watch Dog timer then the whole program resets.
Algorithm
1. Set PB2 as output and initialize the LCD function
2. Initialize the GSM modem and set the Message format to text mode.
3. Delete the message at location ‘1’ on the SIM.
4. Enter an infinite loop and check for an incoming message constantly.
5. If there is an incoming message, then store the number and the 1st nine characters of the message in the arrays “number[]” and “msg[]”.
6. Display the phone number and the message on the LCD screen.
7. Compare the saved message with the keyword “Motor on ”and if they match then set PB2 to high state.
8. Compare the saved message with the keyword “Motor off” and if they match then set PB2 to low state.
9. Delete the read message and go to the next iteration.
Trouble shooting
1. LCD doesn’t show anything/ Shows blocks on the first line
Adjust the potentiometer connected to the contrast pin/Make sure all the connections are right.
2. Motor doesn’t get turned ON
Check whether you are sending the correct message or not. Remember you need to add a space after “Motor on” and no space after “Motor off”. Check the LCD after sending the message to see if the controller is grasping your text correctly.
Project Source Code
### /* * gsmEG.c * * Created: 3/14/2014 1:21:32 PM * Author: GANESH SELVARAJ */ #define F_CPU 16000000UL #include <avr/io.h> #include <util/delay.h> #include <stdlib.h> #include <string.h> #include "GSM.h" #include "lcd.h" void gsm_read() { int k; clrscr(); LCD_write_string("System Activated"); gotoxy(1,16); UART_Transmit_string("AT+CMGR=1r"); gsm_waitfor('r'); gsm_waitfor('n'); if(UART_Receive()=='+') { gsm_waitfor('M'); if(UART_Receive()=='G') { gsm_waitfor('A'); gsm_waitfor(','); gsm_waitfor('"'); for(k=0;k<13;k++) number[k] = UART_Receive(); gsm_waitfor(','); gsm_waitfor(','); gsm_waitfor('+'); gsm_waitfor('n'); for(k=0;k<9;k++) msg[k]=UART_Receive(); gsm_waitfor('K'); gsm_waitfor('n'); _delay_ms(300); clrscr(); LCD_write_string("Ph:"); LCD_write_string(number); gotoxy(1,0); LCD_write_string("Msg:"); LCD_write_string(msg); _delay_ms(2000); if(!strcmp(msg,"Motor on ")) { PORTB |= (1<<PB2); } if(!strcmp(msg,"Motor off")) { PORTB &= ~(1<<PB2); } gsm_delete(); } } _delay_ms(1000); } int main(void) { DDRB |= (1<<PB2); lcd_init(); LCD_write_string("Initializing... "); gsm_init(); gsm_delete(); while(1) { gsm_read(); } return 0; } GSM #ifndef GSM #define GSM #include <avr/io.h> #include <util/delay.h> #include <string.h> #include <avr/wdt.h> #include <avr/interrupt.h> #include "lcd.h" char msg[10]; char number[14]; int i,j; void UART_Init( unsigned int baud ); void UART_Transmit_char( unsigned char data ); unsigned char UART_Receive( void ); void UART_Transmit_string( char *string ); void UART_Init( unsigned int baud ) { /* Set baud rate */ UBRRH = (unsigned char)(baud>>8); UBRRL = (unsigned char)baud; /* Enable receiver and transmitter */ UCSRB = (1<<RXEN)|(1<<TXEN); /* Set frame format: 8data, 1stop bit */ UCSRC = (1<<URSEL)|(0<<USBS)|(3<<UCSZ0); } void UART_Transmit_char( unsigned char data ) { /* Wait for empty transmit buffer */ while ( !( UCSRA & (1<<UDRE)) ) ; /* Put data into buffer, sends the data */ UDR = data; } unsigned char UART_Receive( void ) { /* Wait for data to be received */ while ( !(UCSRA & (1<<RXC)) ) ; /* Get and return received data from buffer */ return UDR; } void UART_Transmit_string( char string[] ) { int i=0; while ( string[i] > 0) UART_Transmit_char(string[i++]); } /*************************************************************/ void gsm_init(void); void gsm_read(void); void gsm_send(char *number,char *string); void gsm_delete(void); void gsm_waitfor(char c); void gsm_waitfor(char c) { //enabling watchdogtimer with a time of 2.1secs wdt_enable(7); //waiting for the byte to be received while(UART_Receive()!= c); //resetting watchdogtimer and turning off the watchdogtimer wdt_reset(); wdt_disable(); } void gsm_init() { UART_Init(103); // baudrate=9600 gotoxy(1,0); LCD_write_string(" Testing Modem "); _delay_ms(500); UART_Transmit_string("ATr"); gsm_waitfor('O'); gsm_waitfor('K'); gotoxy(1,0); LCD_write_string(" Modem : OK "); _delay_ms(1000); INS: gotoxy(1,0); LCD_write_string(" Checking SIM "); _delay_ms(500); UART_Transmit_string("AT+CSMINS?r"); gsm_waitfor( 'n'); gsm_waitfor(','); if(UART_Receive() == '2') { gotoxy(1,0); LCD_write_string(" SIM NOTFOUND "); _delay_ms(1000); goto INS; } else if(UART_Receive() == '1'); gsm_waitfor( 'K'); gsm_waitfor( 'n'); gotoxy(1,0); LCD_write_string(" SIM FOUND "); _delay_ms(1000); REG: gotoxy(1,0); LCD_write_string(" Network Status "); _delay_ms(500); UART_Transmit_string("AT+CREG?r"); gsm_waitfor( 'n'); gsm_waitfor(','); if(UART_Receive() == '2') { gotoxy(1,0); LCD_write_string("Network NotFound"); _delay_ms(1000); goto REG; } else if(UART_Receive() == '1'); gsm_waitfor( 'K'); gsm_waitfor( 'n'); gotoxy(1,0); LCD_write_string(" Network Found "); _delay_ms(1000); UART_Transmit_string("AT+CMGF=1r"); gotoxy(1,0); LCD_write_string("Setting Textmode"); gsm_waitfor('O'); gsm_waitfor('K'); gotoxy(1,0); LCD_write_string(" Textmode set "); _delay_ms(1000); } void gsm_delete() { UART_Transmit_string("AT+CMGD=1r"); gsm_waitfor('K'); gsm_waitfor('n'); _delay_ms(500); } #endif LCD #include<avr/io.h> #include<util/delay.h> #include<inttypes.h> #include "lcd.h" void LCD_write_string(const char *str) //store address value of t he string in pointer *str { int i=0; while(str[i]!=' | https://www.engineersgarage.com/contributions/gsm-based-ac-appliance-control/ | CC-MAIN-2020-05 | refinedweb | 1,458 | 55.74 |
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Here is a frustrating knot I am beginning to unravel.
R has a namespace structure to help reduce errors resulting from functions, methods, objects, classes having the same name from two different packages. Makes sense. Those R objects that are supposed to be available to other packages are said to be exported, and the designation of exported objects occurs in a file named NAMESPACE in the package root (no file extension).
Seems straightforward enough, right? Here’s the rub:
Not all packages available from the CRAN repository actually have a NAMESPACE file. This means the package doesn’t have a specified namespace. A package without a NAMESPACE file should really only specify the dependency using the “Depends:” field in the DESCRIPTION file, which will basically load the whole package in the background when your custom package is loaded.
A related problem arises when your package depends on another package with an extremely limited NAMESPACE file. Check the NAMESPACE file of that packages source. If it really only has a one or two “export( stuff )” fields, perhaps only a a few lines total, chances are it is not a sufficient NAMESPACE specification for you to use the “Import:” field in your DESCRIPTION file. If you do try, chances are that you will receive errors during package check or package build. If you are unsure, you can start by listing all package dependencies in the “Depends: ” field, and then move one-by-one the unsure package names to the “Imports: ” field until you are satisfied.
This issue is mentioned in the Bioconductor instructions for package developers:
It includes some useful suggestions and scenarios in addition to those listed here.
When I originally wrote this post, I suggested manually modifying your NAMESPACE file in order to get the package to build. I no longer suggest that as an option. Ideally, you will create your NAMESPACE file automagically using Roxygen, and your Import/Depends specifications as well as in-source roxygen commands (e.g. @import) will be sufficient to generate a functional NAMESPACE file that does not cause warnings or errors during package build. It can be done! Just takes some fiddling to understand what the errors are.
Finally, in general, I agree with the Bioconductor directive that all packages have a namespace specification. A thoughtful discrimination between external and internal methods is going to be useful for long-term stability of packages, especially as the number of R packages increases. For now, NAMESPACE does not appear to be required by CRAN, but that does not mean you should not make one, nor does it mean others will not find it extremely useful!
p.s. If you use roxygen (or roxygen2) you will need to remove/comment all import tags from your roxygen-comments related to the namespace-absent packages. Commenting-out those tags is preferable, so that function-level dependencies are still documented in the source file in Roxygen notation, which is useful for others (as well. | https://www.r-bloggers.com/error-package-does-not-have-a-name-space/ | CC-MAIN-2019-51 | refinedweb | 515 | 51.99 |
Hey guys, First off, am I correct in assuming that the browser loads pages using a single thread i.e. if you write a big for loop in javascript every other operation will hang until the loop completes. Silverlight has a System.Threading namespace, how many threads can I create with it? In one of the Mix session videos I heard that Silverlight uses the browser networking stack for any communication with the server. What are the limitations other than no support for cross-domain access. At this point I am waiting for the Orcas Beta 1 download to complete, just can't wait to get started on Silverlight.
Thanks,Vaibhav
As you noticed, the System.Threading namespace is nearly 100% exposed in the 1.1 Silverlight alpha. As currently exposed, there are no limits on the number of threads that can be created by System.Threading except the normal memory limitations of the OS.
I am one of the software developers working on the final design of System.Threading and it has been somewhat difficult to filter what will be exposed in System.Threading when we consider that the client applications will be running in the browser and a number of operations (such as drawing the UI) can only reliably occur from a particular thread. This forces a complex code-pattern that neither the System.Threading classes nor the classes that allow browser or UI manipulation do not currently 100% enforce. For now, your best bet is to try to write your code in multiple threads (if it makes sense for your app), but be aware that some operations may need to be called from the original thread or controlled by some type of synchronization primitive to ensure that the engine's call to the browser does not expose an underlying thread-safety issue.
I envision some extremely powerful games that could be written in the browser by using Silverlight to implement clever multithreaded processing to track game-state and/or AI.
Hope that helps!Todd
Hi Guys,
On the subject of threading, I am trying to create a code driven animation using the System.Threading.Timer class. The problem is Timer callbacks run from another thread, so when I try to move and element I am getting "Invalid Cross-Thread access".
Is there a way to create a thread safe heartbeat?
Here is some sample code to replicate the issue
------- XAML-----------
<Canvas x: <Ellipse Canvas.</Ellipse></Canvas>
-----------------------------
------------------- Code------------------
using System;using System.Windows;using System.Windows.Controls;using System.Windows.Documents;using System.Windows.Ink;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Animation;using System.Windows.Shapes;using System.Threading;namespace SilverlightProject1{ public class Page : Canvas { Ellipse elpBall; private Timer timer; public void Page_Loaded(object o, EventArgs e) { elpBall = this.FindName("elpBall") as Ellipse; timer = new Timer(Move, null, 1, -1); } private void Move(Object state) { this.elpBall.SetValue(Canvas.LeftProperty, 5); } }}
-------------------------------------
Cheers,
Javier
More functionality to allow this is planned and should be there in releases before RTM, but I believe I can give you an idea of code soemthing to make this work before some more functionality is included.
In this alpha, try creating a timeline and check the time elapsed each time the callback occurs and do your work there.
For the final released product, we hope to deliver a more complete and easier way to do this.
Todd Reifsteck, Microsoft
Another option could be to use the System.Windows.Browser.HtmlTimer in System.Silverlight.dll.
HtmlTimer is not a high resolution timer (and you would get the warning below at compile time), but it might just do for what you need.
'System.Windows.Browser.HtmlTimer' is obsolete: 'This is not a high resolution timer and is not suitable for short-interval animations. A new timer type will be available in a future release.
This posting is provided "AS IS" with no warranties, and confers no rights.
Hi,
the HTML Timer won't work. To update the UI thread (or use timers in general) do the following:
1) Add an empty timeline to your silverlight alpha project
2) in the page load event handler, give the timeline a 1 second duration (or whatever granularity you desire).Also handle the completed event.
3) In the completed event do whatever you want then begin the timer again.
EXAMPLE
=========================
void Page_Load(object o, EventArgs args){
}
{
txtCount.Text = i.ToString();
i++;
myTimer.Begin();
}
You can optionaly call begin BEFORE doing stuff. Investigate Critical Sections first.
Idiosyncratic Nomenclature
There isn't a way to sync an operation with the UI thread currently in 1.1 Alpha and Silverlight is not thread safe so we don't allow users to modify on the non UI thread.Using the HtmlTimer is a good alternative or use the animation/storyboard approach. -markProgram ManagerMicrosoftThis post is provided "as-is"
FYI,
this is NOT an accurate approach but just an example of periodically updating the UI thread. To get an accurate timer you should use the ACTUAL System.Threading.Timer class to change values and only use timelines to update the UI with newer values. For example:
i++;
What about the case in calling web service aynschrounously? Is it safe to modify UI in the callback?
Thanks
It still wont work. you'll have to use the same strategy.
xlj1000:
What about the case in calling web service aynschrounously? Is it safe to modify UI in the callback?
hello.
according to my tests, it is (ie, there's already support for making the callback call on the correct thread but it simply isn't public yet).(IF YOUR PROBLEM HAS BEEN ANSWERED OR SOLVED, MARK IT AS ANSWER)
Hey, I feel your pain... I've been there and have JUST gotten over it ().
I'll be posting an article soon that will show how to do what I mention in that post. Sorry I don't have a clear answer right now, but I need to get to bed.
-Timothy Khouri / Architect / Author
When this thread started, support for threading (specifically handling UI updates from different threads) was poor. There was no first-class mechanism such as "Control.Invoke". You had to work around this limitation by using other types such as a HTML timer or Silverlight storyboards, which both executed (queued) payloads on the UI thread.
Things have changed in Silverlight 2 beta 1. All ScriptObjects and DependencyObjects have a Dispatcher property of type Dispatcher. (This property is marked with EditorBrowsable(Advanced) though, which means that unless you have configured VS to show advanced members, you won't see this property. Could it be that you missed this property because of that, Timothy?) The dispatcher lets you execute a payload on the UI thread, and it is exactly what it was designed for (unlike the HTML timer or Silverlight storyboard). In other words, you should be able to update your UI from a different thread like this:
[code=C#]new Thread(()=> { mySilverlightTextBlock.Dispatcher.BeginInvoke(()=> mySilverlightTextBlock.Text = "Updated from a non-UI thread.");}).Start();Or a slightly less syntactically exotic version:
[code=C#]Thread myThread = new Thread(new ThreadStart(StartThread));myThread.Start();void StartThread() { mySilverlightTextBlock.Dispatcher.BeginInvoke(UpdateText);}void UpdateText() { mySilverlightTextBlock.Text = "Updated from a non-UI thread.";}
In addition to the dispatcher, don't forget there's also the BackgroundWorker. It makes sense to use this type when you have some work you want to do on a background thread, but update the UI as this work progresses or completes.
- Wilco Bauwer (MSFT) /
That is absolutely beautiful (the Dispatcher.BeginInvoke)! I think there's going to be an incredible amount of "catching up" that the development community is going to have to get used to with the new names / ways of doing things in Silverlight.
Speaking of which... is there a way (I realize I'm hijacking this thread, but... I'll continue anyway).. is there a way to set an "X,Y" location to an element in code (a clean way)?
I'll give the scenario:
There's a Canvas control that has dynamically loaded ... rectangles... how do I set the r.X and r.Y? I'm currently using the "margin" property to cheat... I realize I should probably be doing some funky "SetValue" thing that taps into the Canvas, etc... but I'm hoping for a clean solution.
Thanks,
You'll have to use "the funky" SetValue methods if you're using C#:
[code=C#]myCanvas.SetValue(Canvas.LeftProperty, value);
Not sure what your scenario is exactly, but using a different container control (such as StackPanel) might be more appropriate. It's probably best to start a new thread on this though. | http://silverlight.net/forums/t/665.aspx | crawl-002 | refinedweb | 1,446 | 56.96 |
29 January 2010 05:01 [Source: ICIS news]
SINGAPORE (ICIS news)--Asia’s benzene values shed $25-30/tonne (€18-22) during Friday morning’s trading to reach the lowest level seen in almost two months on ample supply and the recent downturn in energy futures, traders and producers said.
Benzene prices have lost a hefty $135-145/tonne or 12-13% of its value from last Friday when prices were assessed at $1,045-1,050/tonne FOB ?xml:namespace>
Sentiment among buyers and sellers dived further on Friday as offers for March loading lots reached $920-925/tonne FOB (free on board)
Price discussions were at $900-915/tonne FOB
Benzene values were at $900-910/tonne FOB
The recent downtrend in energy values to $73/bbl continued to impact sentiment in the market, traders said.
However, surplus supply of benzene in this region was the key factor that was pushing prices lower, some producers and traders said.
High availability of spot parcels pushed some traders to offload four March loading cargoes in quick succession on Thursday afternoon.
“The surplus is too much in this region for February and March,” said a Korean producer.
Aromatics production margins have been healthy in the past weeks as the spread with feedstock naphtha was more than the $150/tonne needed for costs to break even. Hence, most regional crackers and reformers were running almost full and had no immediate intention to cut production, traders and producers added.
Naphtha prices were hovering around $680/tonne CFR (cost and freight)
($1 = €0.72). | http://www.icis.com/Articles/2010/01/29/9329889/asia+benzene+nears+two-month+low+on+crude+high+supply.html | CC-MAIN-2013-20 | refinedweb | 260 | 53.44 |
Trusted Execution Environment ACPI Profile
Licensing: Microsoft agrees to grant to you a no charge, royalty-free license to its Necessary Claims on reasonable and non-discriminatory terms solely to make, use, sell, offer for sale, import, or distribute any implementation of this specification. “Necessary Claims” are those claims of Microsoft-owned or Microsoft-controlled patents that are technically necessary to implement the required portions (which also include the required elements of optional portions) of this specification, where the functionality causing the infringement is described in detail and not merely referenced in this Specification.
1.0 Background
This specification defines the ACPI device object for a TPM 2.0 device and the control methods associated with the ACPI device object required for Windows 8. The control methods implement the equivalent of the TCG physical presence ACPI interface, the equivalent of the Platform Reset Attack Mitigation interface and optionally an ACPI method to send a command to the TPM 2.0 device.
An additional static ACPI table (TPM2) is used to define the mechanism for communicating between the TPM 2.0 device and the Windows 8 OS.
Note
Microsoft refers to the Trusted Computing Group’s “TPM.Next” term as “TPM 2.0”
2.0 Requirements
This specification assumes a computing platform that supports ACPI-based communication as specified in [ACPI09] between an OS and a firmware environment.
3.0 Usage scenarios (for example only)
3.1 Sending a physical presence command
A typical usage scenario is as follows:
Within the OS environment, an application detects the TPM 2.0 device is not fully provisioned for use for Windows 8. (An example of how this could happen is if a new OS image is installed after a previous OS image provisioned the TPM 2.0.)
The application launches an OS wizard to ready the TPM 2.0 device for use.
The wizard interacts with the computer administrator via UI and determines the administrator needs to clear the TPM 2.0 device to provision it because the TPM 2.0 device reset lockout authorization value is not available.
To clear the TPM 2.0 device, the OS requests (by executing an ACPI control method for the TPM 2.0 device object) the firmware perform the operation to clear the TPM 2.0 device upon the next boot provided a physically present user confirms they approve of clearing the TPM 2.0 device.
The OS restarts the platform.
During the early portion of the boot process, the firmware recognizes the pending request from the OS to clear the TPM 2.0 device.
The firmware presents a UI to a physically present user asking them to take some action to confirm clearing of the TPM 2.0 device.
A physically present user confirms clearing of the TPM 2.0 device.
The firmware clears the TPM 2.0 device using the platform hierarchy authorization.
If necessary, to persist the clearing of the TPM 2.0 device, the platform is rebooted immediately.
The OS boots.
The OS queries (via an ACPI control method on the TPM 2.0 device) if the last OS request to clear the TPM 2.0 device was either (a) successful, (b) was not confirmed by the physically present user or (c) had some other error. In the following, we assume the TPM 2.0 device was cleared successfully.
The TPM 2.0 device provisioning wizard within the OS performs additional commands to ready the device for use by Windows.
3.2 Requesting memory to be cleared on the next boot
This scenario illustrates how the memory clear feature of the system helps thwart attacks that harvest system memory for key material after the platform is unexpectedly restarted.
From within the OS, an administrator on a system with a TPM 2.0 device turns on the BitLocker feature for the OS volume.
The BitLocker feature calls the TPM 2.0 device ACPI control method to set the ClearMemory bit defined in the TCG Platform Reset Attack Mitigation Specification.
The BitLocker feature encrypts the OS volume.
The administrator leaves the system unattended with the screen locked.
A malicious person steals the system while it is running.
The malicious person inserts a USB stick and quickly removes the system battery and re-inserts it.
The system starts booting when the battery is re-inserted.
Because the ClearMemory bit was set previously the firmware clears the entire system memory before launching any code not provided by the platform manufacturer.
The malicious person configures the firmware during boot to boot to the USB device even though the code on the USB device is not properly signed.
The code on the USB device scans the system memory for the BitLocker Volume Master Key but it is not found.
Warning
Steps 11 through 16 are similar to the earlier steps, but use the UEFI interface instead of ACPI
The malicious person attempts to boot the system normally.
Because BitLocker was enabled with the TPM key protector, this permits BootMgr to “unseal” the volume master key for the OS volume because the correct measurements are in the TPM 2.0 device when BootMgr runs.
Boot proceeds to the OS logon screen.
The malicious person again removes then re-inserts the battery and boots code from a USB device.
Because the ClearMemory bit was set, the system firmware erases the entire system memory during boot.
Even though code from the USB device scans the system memory, the OS volume encryption key is not in memory.
3.3 Issuing a command to the TPM 2.0 device
This example is not applicable for all system architectures.
The Windows TPM 2.0 driver wants to issue a command to the TPM 2.0 device.
The Windows TPM 2.0 driver writes the command to execute to the physical address read from the ACPI-defined Control Area earlier during the Windows TPM 2.0 driver initialization.
The Windows TPM 2.0 driver executes the ACPI control method to execute a TPM 2.0 command.
The Windows TPM 2.0 driver polls the registers in the control area until they indicate the TPM command has completed.
The Windows TPM driver reads the command response from the physical address read from the ACPI-defined Control Area earlier during Windows TPM driver initialization.
4.0 General ACPI Requirements for the TPM 2.0 System and Device
4.1 Power considerations
ACPI D1/D2
The TPM 2.0 device MAY support ACPI D1 and/or ACPI D2 but MUST behave as if it was in power state ACPI D0 while in D1 or D2.
ACPI S3 (Sleep)
The TPM 2.0 MAY support S3 but entry into and exit from the S3 low power state for the device MUST be controlled by the system/platform manufacturer.
The OS (or other software running in the OS environment) MUST NOT be able to place the TPM 2.0 device in S3 or cause the TPM 2.0 device to exit from S3. For example, if the TPM 2.0 device is on a bus, the OS MUST NOT be able to power down the bus causing the TPM 2.0 device to enter S3.
The Windows 8 TPM driver will attempt to issue a TPM2_Shutdown command prior to entering S3 (sleep).
If a hardware platform does support S3 and the TPM does not retain its state while the system is in S3, the platform MUST issue the necessary TPM2_Init and TPM2_Startup(TPM_SU_STATE) commands during S3 resume. It is possible the OS may not have completed the TPM2_Shutdown command prior to entry into S3. This could cause the return result of TPM2_Startup(TPM_SU_STATE) to return an error. The system firmware that resumes from S3 MUST deal with a TPM2_Startup error appropriately. For example, by either disabling access to the TPM via hardware, issuing a TPM2_Startup(TPM_SU_CLEAR) command and configuring the device securely by taking actions like extending a separator with an error digest (0x01) into PCRs 0 through 7 and locking NV indices.
The system MUST account for time elapsed during S3 by decrementing TPM dictionary attack failure count (TPM_PT_LOCKOUT_COUNTER) for the time the system was in S3 per the lockout interval (TPM_PT_LOCKOUT_INTERVAL). This may require a platform implementation to provide standby voltage to retain TPM clock and/or state during S3 or a platform could also securely provide information regarding how much time elapsed while the system was in a low power state so the TPM can reliably updates its authorization failure count for its dictionary attack logic.
Low Power States for Connected Standby Systems
Windows 8 does not perform any additional actions associated with the TPM upon entry and exit from low power states for Connected Standby systems. The platform MUST performing any actions needed for the TPM to behave as though it was in D0 whenever the system enters and exits from low power states for Connected Standby systems. This MAY require a platform implementation to provide standby voltage to power the TPM clock and/or retain state. Alternatively, a platform MAY need to securely provide information regarding how much time elapsed while the system was in a low power state to the TPM, so the TPM can reliably updates its authorization failure count for its dictionary attack logic.
System Off
The system SHOULD securely account for time elapsed during full shutdown by decrementing TPM dictionary attack failure count (TPM_PT_LOCKOUT_COUNTER) for the time the system was in S5 per the lockout interval (TPM_PT_LOCKOUT_INTERVAL).
4.2 ACPI tables
A system with a TPM 2.0 device MUST provide a device object table with a hardware device ID and an OS vendor specific static table (TPM2) as described below.
Both the TPM2 table and the TPM 2.0 device object MUST be persistent once the platform is shipped to a customer. (E.g. Firmware options MUST NOT permit hiding of the TPM2 table or the TPM 2.0 device object.) An exception is if a system is shipped with a non-default option to provide TPM 1.2 functionality instead of TPM 2.0 functionality (i.e. for compatibility with older operating systems like Windows 7.) In this situation the TPM2 table and the TPM 2.0 device object MAY be removed via a BIOS configuration option and enumeration of a TPM 1.2 performed. Note: A Connected Standby System for Windows 8 is required to ship, by default, with a TPM 2.0 visible to the operating system. Please contact Microsoft for technical guidance about switching between a TPM 2.0 and TPM 1.2 on a hardware platform.
4.3 TPM 2.0 Device Object ACPI Table
4.3.1 Bus Hierarchy
The Device Object table MUST be under the DSDT table in the ACPI namespace.The TPM 2.0 Device Object MUST be located under the system bus at “root\_SB”.
4.3.2 Hardware Identifier
The actual plug and play hardware identifier (e.g. _HID) for the TPM 2.0 device object MUST be “MSFT0101”or the device MUST have a compatible ID of “MSFT0101” and the _HID could be vendor specific.
4.3.3 Resource Descriptors
The ACPI TPM 2.0 Device Object MUST claim all resources used by the TPM 2.0 device.
4.3.4 Control Methods
4.3.4.1 Platform Reset Attack Mitigation
The system MUST implement all ACPI and UEFI related parts of [TCG08] for UEFI. The device object MUST implement the control method interface defined in [TCG08], section 6. The interface is required even if the platform unconditionally clears memory on every boot. The clearing of memory MUST NOT be conditional on the TPM 2.0 device state (in contrast [TCG08] does not requiring clearing of memory if the TPM 1.2 is not owned). Also, sections 3, 5 of [TCG08] MUST be implemented.03.) The implementation MUST auto-detect an orderly OS shutdown and clear the ClearMemory bit on such events.
Special note for UEFI based ARM systems with a TPM 2.0: On UEFI based ARM systems with a TPM 2.0, Windows 8 will unconditionally request memory be cleared using the UEFI interface on every boot. Implementing the ACPI interface is still required, but the interface MAY be implemented to not change the state of the ClearMemory or DisableAutoDetect flags. (Note: Microsoft recommends the ACPI interface be implemented per the TCG specification so calling the ACPI interface does change the state of ClearMemory or DisableAutoDetect.)
4.3.4.2 Physical Presence Interface
The system MUST implement the specification defined in [TCG11] per the additional notes below:
The control methods defined in section 2 MUST be implemented with the following restrictions:01FF.)
The implementation MUST return a value of “2: Reboot” for “Get Platform-Specific Action to Transition to Pre-OS Environment.” PPI operations MUST occur for a transition of a restart and SHOULD occur for a shutdown transition.
Implementation of the following control methods is optional: “Submit TPM Operation Request to Pre-OS Environment” (may return “2: General Failure”) and “Submit preferred user language” (may return “3: Not implemented”).
Connected Standby systems MAY hardcode NoPPIClear to TRUE and not implement operations 17 and 18. This means they do not need to implement any confirmation dialogs for physical presence actions because no physical presence operations will require user confirmation.
The firmware MUST leave the storage and endorsement hierarchies enabled when it passes control to initial program loader code like the Windows Boot Manager.
4.4 Memory Mapped I/O Interface
For hardware platforms that use the Memory Mapped I/O Interface, this section and the information in section 4.4 describes the TPM 2.0 driver interaction with the hardware. An example of a system that uses the memory mapped I/O interface is a system with a Start Method value of 6 in the TPM2 table.
4.4.1 TCG TPM Interface Specification Requirements
The system MUST comply with the TPM 1.2 hardware interface requirements in [TCG12] for the following sections:
Section 9.1: TPM Locality Levels
Section 9.2: Locality Uses
Section 9.3: Locality Usage per a Register
Section 10: TPM Register Space
Section 11: System Interaction and Flows
Except: All of section 11.2.4 Failure Mode
Except section 11.2.5: Command Duration, normative item 2
Except All of section 11.2.6: Timeouts
Except All of section 11.2.8: Self Test and Early Platform Initialization
Except All of section 11.2.9: Input Buffer Size
Except section 11.2.10: Errors, normative items 2c and 3.
Section 13: TPM Hardware Protocol
For future draft specifications of [TCG12] please contact Microsoft.
4.4.2 Support for cancelling a command
Windows requires the TPM 2.0 device to permit cancelling of a TPM 2.0 command using the memory mapped I/O interface by exhibiting the behavior described below.
The previously unused bit 24 of the STS Register is defined as write only and referred to as commandCancel.
A write of ‘1’ to commandCancel during the command execution phase MAY cancel the currently executing command and a response MUST be returned. The response indicates if the command was cancelled (no TPM 2.0 state change, but a cancel response code TPM_RC_CANCELLED is returned) or completed (a regular TPM 2.0 response is returned indicating the result of the command). Writes to the commandCancel register when the TPM is not in the command execution state MUST be ignored.
4.4.3 Additional Requirements
All TPM commands MUST complete within a maximum of 90 seconds.
If the TPM 2.0 driver requests to cancel a command, it must complete or cancel within 90 seconds.
The following TIMEOUT values MUST be implemented: TIMEOUT_A = 1 second, TIMEOUT_B = 2 seconds, TIMEOUT_C = 1 second, TIMEOUT_D = 1 second.
The minimum input buffer size MUST be 0x500 (or larger).
5.0 References
Send comments about this topic to Microsoft | https://docs.microsoft.com/en-us/previous-versions/windows/hardware/hck/jj923067(v=vs.85) | CC-MAIN-2019-39 | refinedweb | 2,641 | 57.06 |
NSI Modifies "whois" Agreement 131
drwiii writes "Our good friends at NSI have modified their WHOIS agreement yet again, and it now seems to forbid any repackaging of the results returned from the query, even if your interest is not commercial. Also, notice how the agreement now appears before any results are returned. " I noticed it says "significant portion", but it also never really defines it, either...
Re:WHOIS is useless these days anyway! (Score:1)
Besides, now you don't have to wait a couple of years to modify your domain by sending out e-mails that takes months to answer after filling out the forms over at NSI. With Domain Manager at register.com you can change your DNS information yourself without having to wait for two months just to get a confirmation, then another two months to have that confirmation answered. Simplicity. Enter your new DNS info, wait for most DNS servers' cache to reload usually about 4-6 hours and your in business.
sil@antioffline.com
sil@macroshaft.org
root@regret.org
joquendo@register.com
register.com whois / Helpful info on register.com (Score:1)
word of warning about register.com -- They automatically have your MX (mail) records setup to send to their siteamerica.com email hosting "service" They want to charge some ungodly amount of money per year for this "service". Your not currently able to change your MX record with their web based administration tools (they tell me it's coming in a month or so!). So you have to email them. They say to expect a response within 48-72 hours, but are usually much quicker.
I thought they weren't that great, but from what I'm hearing about NSI, they seem to be the lesser of two evils
Re:WHOIS is useless these days anyway! (Score:1)
whois -h whois.register.com cooldomain.org
(and obviously replace cooldomain.org with whatever you're looking up)
So, i guess in order to get domain contact info, you would need to write a script of sorts that checks each whois host (nsi's and register.com's at the moment -- more to come in the future, i'm sure) until it finds the domain you're looking for...
Re:Grr (Score:4)
It broke my scripts. All I want to do is find out if a name is taken already before I allow a user to proceed thinking all is well.
I'll bet that's the idea, only they are targeting the new registrars who might want to automate the process of registration.
The biggest mistake in breaking NSI's monopoly was that they got to retain the actual root servers and the whois database. IMHO, the whois database should be regarded as a public record like the property records are.
Each registrar should be REQUIRED to have at least two root servers located on different networks, and a complete copy of the whois database. Whois updates and new DNS entries should be circulated like a newsfeed between the registrars. Each registrar should be assigned a night or nights where they circulate the entire contents of their databases so that consistancy can be checked and maintained. Database feeds should be provided free of charge to any and all who want the feed (provided they have the pipe to handle the data, 1200 baud users need not apply) as a REQUIRED public service.
This might be an example of what a Geek Union [slashdot.org] would be good for. "We have already cached the root servers. Open the whois databases or we'll all switch to new root servers and lock you out".
oops. (Score:2)
590 Spring Creek Court
Marietta, GA 30068
US
Domain Name: AMORPHOUS.ORG
Administrative Contact, Technical Contact, Zone Contact:
Brooks, David (DB24252) dbrooks@COMSTAR.NET
770.977.0460
Billing Contact:
Brooks, David (DB24252) dbrooks@COMSTAR.NET
770.977.0460
...oops. Does this constitute a majority? Even though this is my own information, am I still forbade to give it out at my discretion?
--
Dave Brooks (db@amorphous.org)
Re:WHOIS is useless these days anyway! (Score:1)
a> try registering a domain name with Netsol or register.com.. they won't let you if it's registered....
b> do an nslookup using the rootnameservers (put a dot at the end of the domain) (one of the root nameservers is a.root-servers.net)... this will tell you if a name is currently pointing somewhere.. but won't tell you if the name it's self is on hold... (on hold would be a late payment or tradmark dispute type issue)
c> go to register.com's whois and it will lookup information in both Netsol and their databases...
notice the diffrence in information provided between nudesource.org(a domain registered via register.com) and yahoo.com( a domain registered via netsol)
The most anyoing fact about this is there are lots of free hosting companys that have automated scripts that ONLY utilize Netsol's databases and forms....
Hope this helps,
Chris
Re:Legal Eagles... and republication (Score:1)
"By submitting this query, you agree to abide by this policy." hardly seems to apply to a script that can't really understand it...
Correction (Score:2)
The MX hasnt been thrown into domain manage because the cgi scripts are still being worked on.
Picture this for a second as an Admin or Tech Support person in the Internet related field such as register.com
Customer: Hi, I just purchased WebTV and I want to host my domain on it. Also please set my MX info to l0ser.webtv.whatever.
--------snip-------
Currently it is being worked on and if anyone here needs an MX record changed or any other info for that matter I'll stick my foot in my mouth and offer my e-mail where I PERSONALLY will change the info for you. Any spams and I will block you in a heartbeat. Any moronic please redirect my domain to my PalmTop and I'll rm -f it.
-----end snip-----
joquendo@register.com
Re:Probably to FIGHT spammers... (Score:1)
Yeah, this license might have an effect on spam, but its effect on the availiabilty of the information in general is chilling.
Re:register.com (Score:1)
Browser Problem I'm sorry, but this site is not viewable with Lynx. Thank you for your understanding.
Says it all...
Re:Telnet access (Score:1)
But the response begins with their admonition about how not to use it, concluding with the preposterous statement "By submitting this query, you agree to abide by this policy."
/. effect, kinda-sorta? (Score:1)
what would it take to get a devoted Free replacement available? granted, these buggers have the first-hand information because of their position, but there's got to be SOMETHING that can be done about their attitude....
anticompetitive? (Score:1)
This strikes me as part of NSI's attempt to retard competition in the registrar arena while proclaiming all the best intentions.
Speaking of competition, has anyone had success with one of the alternate registrars yet?
AOL is in trouble (Score:3)
Re:/. effect, kinda-sorta? (Score:1)
Of course, if anyone comes up with an idea of what to do to the creatins, let me know... IANAL, but what if everyone took the whois information from a few sites, and put it in another database? That way, no one person is replicating a "substantial portion" of the database? Who knows.. just a thought
"..by submitting this query..." (Score:1)
That's what this is anyway, a result, not a query. Is NSI trying to make us think results are queries now?
Now, if I submitted the result as a query, then I'd be 'agreeing' to their little request. But how many of you go around submitting those results as queries anyway?
Not that I agree with their request.
Re:register.com (Score:1)
Re:411 (Score:1)
Not sure what the legal basis of this decision was, but I'm sure it can & will be used as a precedent if & when NSI decides to sue someone.
Answer: don't believe them. Ignore their claims. (Score:3)
Their claim is invalid for the following reasons:
Any one of these would invalidate their claim, even if they fixed the others! (Remember this, in case they fix any.) I don't think their claim could ever stand a chance in court.
So does anyone want a CGI script that's a whois gateway? Install it on your site to automatically violate NSI's claim. It would force them to either openly ignore you or take you to court, where they'd have no case. If anyone wants to snub NSI like this, ask me and I'll write a simple whois gateway for you.
On another front, it really seems to me that if all the sysadmins are pissed off at NSI, we could all start pointing our DNS's to an alternate root DNS server (maybe in addition to NSI). What, exactly, is stopping us from doing this? Even if only half the sysadmins did it, the others would follow suit so as not to lose access to all those alternate domains.
Re:it's a feature (Score:1)
22 lines from start to finish of the actual form
for a domain with 3 backup NS's.
Sorry, still don't agree (Score:2)
Well, I don't. I still don't. That's why I'm now repackaging, disseminating, and modifying (for HTML) the WHOIS record of my old ISP, Internet Direct. [idirect.com]
gemini:~$ whois idirect.
Registrant:
TUCOWS Interactive Limited (IDIRECT-DOM)
5150 Dundas Street West #306
Etobicoke ON, M9A 1C3
CA
Domain Name: IDIRECT.COM
Administrative Contact, Technical Contact, Zone Contact:
Administrator, DNS (LH90) dnsadmin@IDIRECT.COM
416-233-7150 (FAX) 416-233-6970
Record last updated on 29-Oct-98.
Record created on 21-Nov-94.
Database last updated on 6-Jul-99 08:47:29 EDT.
Domain servers in listed order:
NS.IDIRECT.COM 199.166.254.254
NS2.IDIRECT.COM 199.166.254.4
CNS2.IDIRECT.COM 207.136.80.18
CNS1.IDIRECT.COM 207.136.66.20
I called and complained (Score:2)
I simply stated the following:
1. That my information was now under a new policy that seemed to discourage it's dissemination.
2. That I was not pleased about this "business decision" of theirs.
She was most entirely uninterested in listening to my points. I've spoken with walls and gotten more useful feedback.
So, I encourage all that can afford a 3 to 7 minute phone call to give NSI a call today, and let them know you don't exactly aprove of their changing their policy with regards to the data we gave them when we registered a domain.
I think I'm going to call and see if I can't speak to somebody about how this "business decision" was reached.
scottwimer
By reading this message.. (Score:3)
Huh? You guys using some interface or something? (Score:1)
What ever happened to remebering URL's?
-------
Q: What's up?
A: A direction.
Re:Telnet access (Score:1)
EisPick asks, "When you say telnet access, do you mean the *nix whois command?"
Nope. Our earlier astute observer is referring to another (former) way to get at whois, via telnet. At the prompt, you would type,
telnet rs.internic.net [internic.net]
or
telnet whois.internic.net [internic.net]
Just like telnetting anywhere else. Once logged in, at their prompt, you'd type,
whois domain-name.foo
I just pinged rs.internic.net, and the server responds. But if you try to telnet in--to either subdomain--it just hangs. I successfully telnetted to two other places, so the problem is not on my end. Looks like it's broken on purpose by NSI. Arrogant jerks.
Re:WHOIS is useless these days anyway! (Score:2)
NetSol's whois database isn't the only one to suffer from lack-of-usefulness.
After repeatedly being the victim of smurf attacks (yes, there are still many broken networks [powertech.no] out there), I wrote a perl script which analyzed the Netflow export from a Cisco 7000-series router, tested the source IPs' networks for "brokenness," and used whois.arin.net to get contact information for those networks. Much to my dismay, I was getting stuff like...
150.174.97.255 52 Virginia State University (NET-VSUNET)
"Grey, Michael" vsuars@VCUVM1.BITNET
161.223.245.0 32 Indian Health Service (NET-IHS-BNET)
"Jaramillo, Valentino" [No mailbox]
192.48.125.0 33 Solar Energy Research Institute (NET-SERI-2)
"Powers, Chuck" [No mailbox]
Some of these organizations have had their IP allocations since the mid-1980s and apparently haven't updated their contact information in all this time. (BITNET? Can we say "way of the dodo"?) Of course, since there's no "enforcement" to keep the contact information up-to-date, things won't be changing anytime soon. (At least the
.nu registry [] has strong wording in their policy [] regarding valid contact information...)
"[No mailbox]" shouldn't be allowed as a contact e-mail address, in my opinion. With the abundance of free/near-free e-mail services out there ( HotMail [hotmail.com], Net@ddress [netaddress.com], etc.), there is no excuse for not having a valid, working e-mail address. If you don't have an e-mail address, then you probably don't need to have IP addresses, either...
Re:WHOIS is useless these days anyway! (Score:2)
c> go to register.com's whois and it will lookup information in both Netsol and their databases...
Unfortunatly, apparently not.
[sjames:~]$ whois yahoo.com@whois.register.com
[whois.register.com]
No match for "yahoo.com".
Get your domain name at
Re:411 (Score:1)
As a side note, since the whois information is not freely distributed, NSI claims not copyright but licensing agreement right. So this argument wouldn't work for them.
Re:Answer: don't believe them. Ignore their claims (Score:1)
But, I do agree. Ignore it. Just know a good lawyer who doesn't mind fighting it out with NSI.
Re:register.com (Score:2)
Jerry
Isn't this a relaxation of NSI policy? (Score:3)
of the database as a whole: "Compilation, repackaging, dissemination, or other use of the WHOIS database in its entirety, or a substantial portion thereof, is not allowed without NSI's prior written permission."
The restriction that NSI began attaching in May said: "You agree that you will not reproduce, sell, transfer, or modify any of the data presented in response to your search request, or use of [sic] any such data for commercial purpose, without the prior express written permission of Network Solutions."
So in fact this seems to be a step back towards open records. Now, whether their claim that use of the entire database is "not allowed" has any legal force is something a lawyer would have to answer. They don't explicitly claim copyright, except with the "All rights reserved" statement and my memory is that the phone companies failed with similar "compilation copyrights" on white pages in the past.
But would it hold up in court? (Score:1)
> By submitting this query, you agree to abide by this policy.
... but to _see_ this license, you have to submit a query, which automatically means you've agreed to the license! This is like taking a contract, sealing it in an envelope, and giving it to someone, with a clause in the contract that reads "By opening the envelope in which this contract was contained, you agree to abide by its terms."
Granted, this would be a bit harder to make fly if you did enough queries to get "a substantial portion" of the database, but still definately an issue.
Government Problems? (Score:1)
This is obviously to stop register.com and the like, but anyone who's dealt with NSI before shouldn't be surprised.
Re:Telnet access (Score:1)
# nmap -sT -p23 rs.internic.net
Starting nmap V. 2.2-BETA4 by Fyodor (fyodor@dhp.com,)
Interesting ports on rs.internic.net (198.41.0.6):
Port State Protocol Service
23 filtered tcp telnet
Re:anticompetitive? (Score:1)
Register.com - Domain Name Registration Services
Browser Problem.
I'm sorry, but this site is not viewable with Lynx. Thank you for your understanding.
This is lightyears ahead??
---------------
On
Re:Telnet access (Score:2)
It still works for me:
$ telnet whois.internic.net 43
Trying 198.41.0.6...
Connected to rs.internic.net.
Escape character is '^]'.
slashdot.org
Access to Network Solutions' WHOIS information is
....
etc
Evil bastards (Score:1)
Re:411 (Score:1)
Their "agreement" can't be binding (Score:2)
So what, you might say. So I have scripts -- like many other people -- that use the whois db info in a "repackaged" format. And most run without my intervention and have been for a while. So am I now in violation of their agreement? Hell, I may not even know where some of those scripts are anymore! (Possibly a slight exaggeration, but you see the point.)
All I'm trying to say is that their "agreement" seems spurious and can't possibly be binding. I mean, who is agreeing to the terms of the "agreement" if the whois db info is being slurped by a script? The author of the software? Yeah, right. Try that one, and I'm suing MS for a mint. OK, maybe the user account that the script runs under? I'd love to see NSI try to sue nobody@lazlo.qualcomm.com. They going to sue my company? I hope they have a lot of lawyers and a lot of money; there's got to be plenty of companies doing the same thing.
The hell with NSI, I say. Seriously, what is wrong with people these days?
-B
How to transfer domain from NSI to register.com? (Score:1)
Re:Net::Whois (Score:1)
This is taken from a diff that makes Whois.pm work again. It is against Whois.pm 1.13. Insert these lines after line 200.
(There's a variable ($text) that gets the info from a socket. Just substitute null for the whole disclaimer phrase with a regex assign.)
201,205c201
my $disclaimer;
$disclaimer = EOF;.
EOF
$text=~s/$disclaimer//;
Re:success with one of the alternate registrars (Score:1)
Re:By reading this message... (Score:1)
Re:Net::Whois (Score:1)
I can't make the code format correctly in a reply.
There pissed... (Score:1)
does any one know of any site with the followiing description
Re:Their "agreement" can't be binding (Score:1)
By opening this envelope and reading this
letter you agree to pay me $100. You
have one week to reply before I call
my lawyers.
Thank you.
seems legally identical to me.
whois is now so broken that it is nearly useless (Score:1)
NSI's new terms seem aimed specifically at keeping someone from building a comprehensive whois database from the individual databases. I distinctly remember being able to query NSI's database from [register.com], but that link seems to be gone now. I never really hated NSI until now.
FYI, register.com's whois server is at whois.register.com.
Woogie
Re:Grr (Score:1)
forget boycotting the whois database - provide an alternative! why should we rely on NSI for this information?
and somehow, i dont think we'd succeed in boycotting the root servers, either, unless someone is going to donate the machines and we can convince the rest of the world to follow us.
but the whois database could be better implemented anyway. and it should be free.
my $ 0.02
:)
Re:blah at NSI (Score:1)
Not to belittle your anti-NSI sentiments, for I think NSI are generally right bastards, but you *could* be perceived as a trifle biased, since you do work for register.com.
Re:But would it hold up in court? (Score:1)
It's like having a license on the software packaging that says "by reading this license you agree to abide by it"......
good point
Come one! Moderate the guy up!!
Maybe we could all submit millions of queries simultaneously to their servers?!
Re:WHOIS is useless these days anyway! (Score:1)
---
workaround (Score:1)
Then their server will let you in
Re:success with one of the alternate registrars (Score:1)
Hm, time for a modified whois client? (Score:1)
This information is my information. I paid for it to be entered into this database. As did many others. Meanwhile, the folks at NSI have been buying a new Lexus each year instead of improving their service. They've gotten fat and ugly on the spoils of their monopoly or so it seems.
#undef RANT_MODE
So I think I want to have this information `at my fingertips' without these silly ever-changing lawyertalk-addendums. So I'll just create a modified whois-client which filters out the crud and gives me what I paid for... Anyone interested just mail me...
Cheers//Frank
Re:This agreement is a very good thing (Score:1)
In other words, "bug off, spammers". May I point out that I have not received one piece of spam to my whois contact email addresses since NSI added this agreement to the whois record. May I also point out that I would get about two or three spams a week (if not more) sent to my whois address as recently as last fall, before NSI added the agreement.
Can I just say one thing? BS. =) Not only have 10 other people atleast said this exact thing, so I'm not sure why you're repeating it in the first place, but honestly, do you think spammers really give a damned about an extra few lines in the whois database? They don't.
1) If they did, these same people would abide by ISP AUPs that state spamming is not to be done through their mail servers on their domains, etc etc. They've never cared about that, why should it be different for something imposed by NSI?
2) Do you honestly think you could prove that the spammer got the info from NSI? You couldn't. Therefore why should they be worried about a legal implication such as this?
I think you're just imagining things about receiving less spam.
--
Mark Waterous (mark@projectlinux.org)
I see what they're up to... (Score:1)
Didn't the Supreme Court just [not] rule on this? (Score:1)
For those who don't want to read it, the Supreme Court (United States) in refusing to hear the case, upheld a decision by a Federal court saying that West, the people who publish all those law books, does not have the exclusive copyright on publishing laws and judicial issues (court decisions, etc).
In addition, others will now also be allowed to use West's page numbering system which has become so standard in the legal system, it's almost a second language.
My argument is this: If domain names are like "page numbers" (indicators of where to find something, such as an IP address), and their registration information is public domain information (as are court opinions. the REASON I SAY THIS is not to usurp privacy concerns, but my contention that WHOIS is like a phone book, hence your "information" is public), then doesn't this mean that NSI does not have copyright protection for this information and database collection, and, hence, its' "restrictions" are invalid?
Now, this might not have held before other registrars were allowed, but since they are, this is more a shared system than ever, and so is more like a phone book than a private listing of customers.
#include " its_all_about_the_pentiums.wierd_al [kinet.org]"
This agreement is a very good thing (Score:1)
NSI is doing the right thing my making spammers legally responsible if they use WHOIS information to harvest spam addresses.
- Sam
Re:/. effect, kinda-sorta? (Score:1)
URG
Re:Probably to FIGHT spammers... (Score:1)
(sigh)
There is no honor among government monopolies.
Re:Probably to FIGHT spammers... (Not.) (Score:1)
Thinking this revised "license" will help stop spam is a pipe dream -- Network Solutions routinely sends spam to the contact e-mail addresses in its database. And since when has licensing or law stopped spammers?
Does anyone remember the last time Network Solutions tried acting in the customer's best interest? Information about domains' last-updated dates was removed from the whois database. Woo, that really stopped the domain hoarding, didn't it? Of course, they must have figured out it didn't do squat -- the information is back. If Network Solutions really wanted to help "the problem," they'd require payment before domain activation. That would at least curb hoarders who register a domain, sit on it for a month, let it be dropped for non-payment, and start the cycle over. That's akin to holding a domain hostage -- the hoarder hasn't paid for it, and it wastes NetSol's resources. You'd think they'd act in their own best interests on this one...
Anyway, my guesses about the new license:
The writing has been on the wall for a long time. The big change that should have tipped everyone off was when [internic.net] was essentially replaced with [netsol.com], a site where Network Solutions can also peddle its domain parking/web hosting/e-mail services. I'm sure a bunch of clueless upper-management types go there to register a domain, see all the stuff about foreign terms like "nameservers," "DNS," "content hosting," etc., and then see where Network Solutions can handle it all for them! (For a fee, of course.) Just then, the sound of a cash register ding can be heard at Network Solutions' office, and an angel gets set on fire.
Just business as usual with "the dot screw-the-customer people."
Re:register.com (Score:1)
For a domain registrar, you would think they'd would ensure their Web site is viewable by as many browsers as possible. That's just good e-commerce (ugh, I hate that word) sense...
NSI - The Spoiled Brats of the Web (Score:1)
NSI served notice (as I understand) to the large domain hosting firms hours before the change in the whois was made. However, as there was no way to test their script modifications, most found they had useless scripts Wednesday morning.
They are definitely striking back at Register.Com as well. Take for example a domain modification. If you simply send in a modify template without checking first to see if the domain is a regular domain, a WhirlNick domain or a register.com domain and it turns out to be a WhirlNick domain you receive email telling you how to modify the domain. If it is a Register.Com domain you are told the domain name isn't registered. Totally bogus answer aimed at causing confusion.
Perhaps ICANN should serve hours notice on NSI and Register.Com that they will, effective immediately, provide a consolidated whois server and both companies are required to send their daily updates to ICANN's server.
Remember, NSI no longer sets the rules. ICANN is in charge. NSI is subject to ICANN's wishes which if we all get involved translates into OUR wishes.
NSI == gang of mental midgets? (Score:1)
Their statement is completely unenforceable.
--j
Telnet access (Score:3)
register.com (Score:1)
CmdrTaco: Lawbreaker (Score:1)
It would be nice if it wrapped properly on an 80 column terminal, too. *sigh*
Grr (Score:1)
NSI Agreement (Score:4)
What's the point? (Score:1)
The new NSI chief's name is Jim Rutt (Score:1)
Instead, it's getting worse. As has been pointed out, NSI is basically announcing its claim of compilation copyright on the whois database. This is the same greedy crap that West Publishing does with court rulings, and that many an online service does with the postings of its members.
This is evil and must be stopped.
Jim Rutt is a smart guy. I advised him to drop the claims on whois and get to the business of fixing their broken customer service system. So far he is heading in directly the opposite direction.
Yesterday ICANN announced [icann.org] that 15 candidate registrars have been approved to add to the five existing ones. There are 37 more awaiting certification. Probably 5 to 10 will survive as more than mere niche players. Let's insist on better customer support, service, reliability and lack of greed, and may the best registrar win.
It won't be NSI, though.
--------
Okay, NSI. (Score.
Yahoo (YAHOO-DOM) YAHOO.COM
yahoo.com (DUZEN3-DOM) DUZEN.COM
yahoo.com, jcarr (JY2887) jcarr_10@YAHOO.COM
303-843-2121 (FAX) 303-843-2221
yahoo.com, trisdog (TY1503) trisdog6@YAHOO.COM
303-571-4930 (FAX) 303-571-4911
yahoo.com, trisdog (TY1504) trisdog6@YAHOO.COM
303-571-4930 (FAX) 303-571-4911
To single out one record, look it up with "!xxx", where xxx is the
handle, shown in parenthesis following the name, which comes first.
There. I repackaged it into this page. Come get some!
--
Re:WHOIS is useless these days anyway! (Score:2)
Try their web interface at instead.
Yep, that works perfectly. I do wish the ehois worked though, It's a little nicer to parse in a script than web returns.
You never have to look at that message (Score:2)
#!/bin/sh
whois $1 | grep -v "portion thereof"
$ alias whois=whois.sh
-jwb
Isn't the compilation owned by the US taxpayers? (Score:1)
Re:anticompetitive? (Score:1)
JOhn
Re:anticompetitive? (Score:1)
Actually I think it is because they use a secure server to register domains. Remember how lynx doesn't support https?
Alert!: This client does not contain support for HTTPS URLs.
I spidered the first page of port. It [styx.net] reads well with lynx, so it must be some other reason. Why don't you write to them and complain?
Did you ever try to write to NIS and hope for a response that wasn't totally stupid or ignorant?
This does not apply to me (Score:1)
So - can i happily download the FULL database and use it as a source of a free replacement ?!?
(i dont know if this is covered by an older/other license term which does not violate german or european laws [note: ALL microsoft license terms have parts that violate german law - even the german versions of these licenses... especially those "you agree to this license before you get the chance to read it" is completely invalid and can be happily ignored in germany])
--
Jor
--
Re:Net::Whois (Score:1)
Why do I always seem to be fixing stuff that other people break?
Oh wait... that's my job.
Enforceable doesnt matter (Score:1)
NSI has learned from the masters: whether it's enforceable or not, they're doing their best to delay the transition, those annual reg fees are lifeblood. They know someone will take them to court over this, and even so, win or lose, the court costs won't be coming out of the salary budget, that's for certain.
Re:How to transfer domain from NSI to register.com (Score:1)
---
Re:Grr (Score:2)
The problem is gathering the data. It's easy to determine if a name is active, the hard part is determining that a name is on hold or just registered (Newly registered names don't seem to become active as quickly as one might hope). Of course if the current DNS system is replaced, the NSI whois is worthless anyway since it would no longer reflect the true state of the DNS.
As for the root server issue, the load doesn't have to be huge if the new 'underground' system is planned properly. Caching servers could help a lot. Currently, we have root servers a-m (or at least my named.ca does) Why not go from A - ZZ instead? Then define a 'hub' server and several designated alternates to coordinate the updates.
Once the load is balanced and reasonable, now comes the matter of getting the servers. There is a good business case for providing a server to the cause. Since the system is meant to replace NSI's monopoly, it stands to reason that reasonable fees (certainly not more than is currently charged) could be imposed on registration, and that those fees would be divided amongst the owners of the root servers. (or, a simple rule. Root servers are all authoritative to register a domain name.) The new registrars might even get involved to protect their business interests and investment in becoming a registrar.
In my spare time, I'm thinking about a usenet like distribution system for DNS. The only real problem to solve is the issue of collisions for new registrations. Perhaps a simple database of new registrations with a simple locking mechanism. Every night, the contents of the database could be dumped into the DNS feed to the root servers. As soon as every 'ring 0' server says it's got it, the record is dropped from the new regs database.
In that sort of system, whois would be a two step process. First query a random root server. If no result, query the new regs database. The new process could be hidden so that the whois output looks just like it does now (minus the legal babble).
Simply having a CONTINGENCY plan for all of this would probably bring NSI into line. After all, if it were ever implemented, they're instantly bankrupt (and subject to a bazillion refunds and/or lawsuits). It would be the world's fastest buisness failure. Simple rumblings wouldn't have the same effect, it must be an actual plan with actual willingness to implement it.
A final note: The above is NOT a hijacking maneuver!! That has been (foolishly) tried before. It is simply a perfectly legal end run.
Re:Probably to FIGHT spammers... (Score:1)
Re:NSI Agreement (Score:1)
God you all whine a lot.
I've said it once and I'll say it again... (Score:1)
Re:WHOIS is useless these days anyway! (Score:1)
The only reason that this issue is becoming increasingly unworkable and highly unstable is due to the passive and active resistance by NSI to the privatization and redistribution of their monopoly.
Federally funded info (Score:1)
If so doesnt that mean they can't put such a restrictive use on it?
And what about company info that is pre-NSI (e.g. Apple info, DEC info etc.)
Does this count? (Score:1)
Re:CmdrTaco: Lawbreaker (Score:2)
Re:anticompetitive? (Score:2)
Strong points of register.com:
Negative aspects:
All in all it's lightyears ahead of NIS, and I'm quite happy.
411 (Score:2)
WHOIS is useless these days anyway! (Score:2)
That said, does anyone know of ANY way to reliably tell if a domain has been registered now? WHOIS doesn't tell you, you can't just do an nslookup, etc. Could the boneheads... er... powers that be have not thought of this problem? I seem to have no way of knowing if a domain is registered without going to a website of one of the registrars and hoping their info is accurate.
Seems this multiple-registrars thing has made stuff more complex, not simpler like you'd expect any intelligent group of people to do. Its B.S. that I can no longer reliably get information about who to contact in a domain, and that said data isn't 100% public domain.
Uhoh... Can't access WHOIS via TCP/IP... (Score:2)
Ooops... I repackaged the query in a TCP stream.
Ooops... I did it again. The TCP stream was repackaged into IP packets.
Oh bother. My IP packets were repackaged into ATM frames on the backbone.
*sigh*
Time to start wiring up the direct serial link from my dumb-terminal to their database. Oh wait, that won't work. The serial port will repackage the bytes by inserting parity and stop bits.
Aw, hell, I'll go grab the yellow pages instead.--Joe
--
This is how you x-fer it (Score:1)
When you fill out the form (hosting) they will send you a confirmation to the original e-mail address you used to register it. You have to reply to the confirmation. (HAVE TO) It normally takes about 3-4 weeks or more depending on when they decide to answer there damn e-mail. Be advised they do take a while. Until then no one over at register.com can do anything to force them to move it, or speed up the process.
Renewals: Being that the domain in question was more than likely registered through them, when renewal time comes around, you will have to have them release the domain back into the registry pool in order to re-register it. I'm sure you are aware that there is like a 90 day grace period they give the original owner to renew their domain. But since you wouldn't wanna wait, about a week or two before it expires contact NSI and tell them you have no intention to re-register with them and have decided to register the name elsewhere. They'll be pissed and probably will give you some mumbo jumbo response, but until the name is freed up you wont be able to just re-register it through register.com when it expires.
joquendo@register.com
name.space (Score:1)
jsm writes:
You can set your pc's nameserver to one of namespace's, and get to sites such as,,,, and (as well as the boring old
.coms, .nets, .edus et cetera.)
These new TLDs form a kind of half-there web underground. name.space has registered hundreds of new TLDs (Top Level Domains)... excessive quantity, maybe, but a cool idea.
Interestingly, their policy is to protect "whois" information of their clients.
From the "about us" page of their site ( [namespace.org]):
I found them one day when I idly typed " [alternic.net]" into netscape, and found a link to name.space. (the alternic page is currently "down for construction")
A fascinating idea, many small registration services. What it (possibly) destroys, is the idea that ALL domain names (and therefore internet resources) are accessible from everywhere, because of this monster global database (interNIC). The formation of many unregulated and unorganized registration services is the fragmentation, in some sense, of the internet, into many little niches and cliques. These many name spaces (to borrow name.space's name) might overlap, but still seem very distinct. Perhaps, however, this is necesary-- it would in many ways model other media and facets of society; perhaps this is a good thing, when the web is growing at the fantastic rate that it is.
Very interested in the ideas of the Slashdot Cyber-Futurologicists.
rh
Re:workaround (Score:1)
death to all copyright crap!
Re:anticompetitive? (Score:1)
I will give them credit, however, for a tailored message.
I use lynx at work, since my only internet connection is because of a shell account I have on another's SunOS box. The proxy allows his machine to go through, and only on port 80. My job puts me on the phones, so I have a lot of free time to read on the Internet. And for that, lynx is great. (Except that
I just thought that a "good company" would cater to all people browsing their site. Keeping lynx out of the secure parts is fine. Out of reading material is a bit too far. I have the time _now_ to read it. When I go home, I'd rather just do whatever it was that I could not do here. Whatever. Again, I wasn't complaining, just commenting.
Re:Do we have no choice but to accept new rules? (Score:1)
Since the rules don't apply to them, they don't apply to anybody else.
And remember the old days when a
And
it's a feature (Score:2)
Re:Wonders... (Score:2)
Perhaps the whole board might qualify, but there are faster ways of "stealing" that information.
James | https://slashdot.org/story/99/07/07/1744250/nsi-modifies-whois-agreement | CC-MAIN-2017-51 | refinedweb | 6,750 | 74.59 |
cpucoolerchart 0.1.dev1
CPU cooler performance and price database
CPU Cooler Chart (CCC) is CPU cooler performance and price database. It merges data from CPU cooler performance measurements and price information from Coolenjoy and Danawa.
CPU Cooler Chart is comprised of two parts, the API server part (this project) and the web client part. You can find the web part at github.com/clee704/cpucoolerchart-web.
Install
CPU Cooler Chart depends on lxml. You need to install liblxml2 and libxslt to install lxml. For more information, see Installing lxml.
If you are ready to install lxml, you can install CPU Cooler Chart. There are many ways to do that but using pip is recommended:
$ pip install --pre cpucoolerchart
Currently --pre argument is needed but it will be unnecessary once a non-developmental release is out.
Running
Before running the web server, you must initialize a database:
$ cpucoolerchart createdb
It will make a SQLite database at instance/development.db under the current directory. Although not tested, there is no restrictions on the choice of the database to use as long as SQLAlchemy supports it. See Config for how to change database options.
Now the database is ready and empty. Run the following command to fill it with data:
$ cpucoolerchart update
It will fetch measurement data from Coolenjoy. It might spit out some warnings due to inconsistencies in the data or because you haven’t provided Danawa API keys. Nothing is a serious problem for now.
To see the data, first you need to run a web server:
$ cpucoolerchart runserver
It will run a development server at port 5000. Open your browser and go to. It should show some heatsink makers in JSON format. Go to to download a CSV file that contains all data. For the complete list of HTTP APIs, see the docs. Meanwhile, you can read views.py file for what’s there.
For production, there are many options to run a web server (you should not use the development server in production). CPU Cooler Chart is built with Flask, which means it’s WSGI-compatible. The endpoint is cpucoolerchart.wsgi:app. Or you can make a custom Python file and create an app there:
from cpucoolerchart.app import create_app app = create_app({ 'SQLALCHEMY_DATABASE_URI': 'postgres://user:pass@somewhere:5432/ccc' })
Links
- GitHub repository
- Documentation
- CPU Cooler Chart (deployed site)
- Downloads (All Versions):
- 0 downloads in the last day
- 7 downloads in the last week
- 97 downloads in the last month
- Author: Choongmin Lee
- Keywords: cpu heatsink cooler performance price database
- License: GNU AGPL v3
- Categories
- Development Status :: 3 - Alpha
- Environment :: Web Environment
- Framework :: Flask
- Intended Audience :: Developers
- License :: OSI Approved :: GNU Affero General Public License v3
- Operating System :: OS Independent
- Programming Language :: Python :: 2.6
- Programming Language :: Python :: 2.7
- Programming Language :: Python :: 3.3
- Programming Language :: Python :: Implementation :: CPython
- Topic :: Communications
- Topic :: Internet :: WWW/HTTP :: Dynamic Content
- Topic :: Internet :: WWW/HTTP :: WSGI :: Application
- Package Index Owner: choongmin
- DOAP record: cpucoolerchart-0.1.dev1.xml | https://pypi.python.org/pypi/cpucoolerchart/0.1.dev1 | CC-MAIN-2016-18 | refinedweb | 496 | 56.76 |
See Also
Discussion
I wonder a lot, "How do I subclass built-in types?"
There's a related question: "How do I figure out if something is sort of like a particular type?"
My goal is to take something, and say, "Does this act pretty much like an integer?" Or "does this act pretty much like a float?" Or "does this act pretty much like a dictionary?"
You could: count up all the behaviors you rely on. Then test if they all exist. If they all exist, consider that item a fit.
But, that seems really hard, if you've got a whole class with a ton of methods, all of which use the item. "Counting up" seems pretty hard in that case, and it seems like it would require a lot of discipline.
Is there, then, a set of tests that we can run over an item, to see if it acts "pretty much like" an int, a float, a dict, a string, blah blah blah...? (Or, at least supports the interface for all those things?)
What do people do about this?
Because I read all these things saying, "Don't use type!" "Don't use isInstance!" But I don't see much in the way of what to use.
-- LionKimbro 2004-09-12 17:10:47
[lwickjr]: I like to use issubclass. I suppose one could define a module in the Standard Library consisting entirely of empty classes with appropriate names, and inherit from them:
Module interfaces:
... class dictLike: pass ...
User module:
import interfaces ... class Shelf(interfaces.dictLike,...): ...
Then other users could write isinstance(Thing, interfaces.dictLike), and be assured that anything that passes the test /promises/ to be "like a dictionary".
For instance, on the int class, there are some gazillion methods:
#!python >>> dir( 42 ) ['abs', 'add', 'and', 'class', 'cmp', 'coerce', 'delattr', 'div', 'divmod', 'doc', 'float', 'floordiv', 'getattribute', 'getnewargs', 'hash', 'hex', ', 'str', 'sub', 'truediv', 'xor'] >>> }}}
If you want to make something that's functionally like an int, can you get around having to implement all these methods?
Maybe I have the wrong page title; Maybe this shouldn't be called "SubclassingBuiltInTypes," but rather "SimulatingBuiltInTypes."
-- LionKimbro 2004-09-13 00:00:50 | https://wiki.python.org/moin/SubclassingBuiltInTypes?action=fullsearch&context=180&value=linkto%253A%2522SubclassingBuiltInTypes%2522 | CC-MAIN-2018-26 | refinedweb | 364 | 75 |
RAND(3) BSD Programmer's Manual RAND(3)
rand, srand - bad random number generator
#include <stdlib.h> void srand(unsigned int seed); int rand(void); int rand_r(unsigned int *seed); re- peatable by calling srand() with the same seed value. If no seed value is provided, the functions are automatically seeded with a value of 1. The rand_r() is a thread-safe version of rand(). Storage for the seed must be provided through the seed argument, and needs to have been ini- tialized by the caller.
arc4random(3), rand48(3), random(3)
The rand() and srand() functions conform to ANSI X3.159-1989 ("ANSI C"). The rand_r() function conforms to ISO/IEC 9945-1 ANSI/IEEE ("POSIX") Std 1003.1c Draft 10. MirOS BSD #10-current June 29,. | http://www.mirbsd.org/htman/i386/man3/srand.htm | CC-MAIN-2014-10 | refinedweb | 128 | 77.23 |
Introduction to data cleaning using Pandas
I’ve been using Excel for data cleaning until I discovered how powerful pandas are for data analysis and data cleaning. In this article I want to go over basics of how to use pandas for cleaning data in excel files.
Importing data and taking a look
As a first step, lets look at the raw data we have, to understand what needs to be done as part of cleaning. I’m skipping installation of python and Jupyter notebook in this article. If you are completely new to python and want to install Jupyter, here are some links to guide you through the procees-
BeginnersGuide/NonProgrammers - Python Wiki
Automate the Boring Stuff with Python - Practical Programming for Total Beginners by Al Sweigart is "written for office…
wiki.python.org
I have the Anaconda Navigator installed on my Mac. Follow along this link to install the software-
Once you have Anaconda installed, click on the jupyter notebook
If you are opening up jupyter for the first time, command prompt should provide you with a local host url. Enter this url in your browser window and the jupyter notebook should open up.
To follow along , download the Austin_Animal_Center_Intakes.csv file here. Save the file to your local and run this piece of code in jupyter.
Importing the file into pandas
import pandas as pd
import numpy as np
import os
filepath = “/Users/ayyagamv/Desktop/Tableau/Assignments/Capstone”
filename = “Austin_Animal_Center_Intakes.csv”
filePathFileName = filepath + “/” + filename
outputFile=os.path.join(“/Users/ayyagamv/Desktop/Tableau/Assignments/Capstone/Austin_Animal_Center_Intakes_cleaned.csv”)
df = pd.read_csv(filePathFileName)
Here we import pandas using the alias ‘pd’, then we read in our data.
df.head() - shows us the first 5 rows and headers - it gives us an idea what to expect.
df.tail() - shows us the last 5 rows. Lets try df.head.
df.head()-Output
df.tail()-Output
df.columns -Output
df.shape- Output
df.isnull()- Output
Looking at the first and last 5 rows, I can see that some cells in the Name column are blank, panda displays this as NaN. The second obvious issue I see is that some cells in the name field have an asterisk*. We would ideally want to remove the asterisk.
Lets replace the cells without any data in the Name column with the value ‘None’ using this line
df = df.astype(object).where(pd.notnull(df),None)
Onto the next issue with data. I want to remove the asterisk in the Name column. It can be done with this line
df[‘Name’]=df[‘Name’].apply(lambda x:str(x).replace(‘*’,’’))
Lets take a look now at what we have
I can also see that the MonthYear column has time which is not required in that column. Lets ged rid of that.
Firs step is to convert the data frame object to date.time format and then replace the date time with just date. This can be done with just 2 lines of code.
df[‘MonthYear’] = pd.to_datetime(df[‘MonthYear’])
df[‘MonthYear’] = df[‘MonthYear’].apply(lambda x: x.date())
Finally, write the output to an other file and specify the location of the file.
outputFile=os.path.join(“/Users/ayyagamv/Desktop/Tableau/Assignments/Capstone/Austin_Animal_Center_Intakes_cleaned.csv”)
df.to_csv(outputFile)
This was a brief introduction to data cleaning using pandas. The data is now at a point where it can be imported into Tableau for further analysis. | https://medium.com/@madhavayyagari/introduction-to-data-cleaning-using-pandas-64102b97dd62 | CC-MAIN-2021-39 | refinedweb | 567 | 66.33 |
I’m enjoying learning Swift, but it didn’t take long before I took to Google looking for #if 0 in Swift.
#if 0 (pronounced, by me at least, as “pound if zero”) is a quick and easy way to get around C’s lack of support for nested multiline comments. Consider this snippet:
In C (and C++, and Objective-C), that’s a big no-no. GCC proclaims
warning: "/*" within comment and then unceremoniously dies with
error: unexpected expression before '/' token. Even the syntax highlighter I use in WordPress trips up on it and leaves the last
*/ without decoration. Amusing.
So rather than using
/* and
*/ to comment out a block of code, I’d rely on
#if 0, like this:
Voilá. Problem solved. Once I’m done experimenting or troubleshooting a bug I can either delete the code within the
#if 0 block, or remove the
#if and
#endif pair.
Of course I tried using my trusty
#if 0 when coding in Swift, only to find that it isn’t supported. This didn’t shock me;
#if is a C preprocessor directive after all. But I still wanted a way to quickly comment out a block of code and not worry about whether there were other comments within the block. So, again, I went straight to Google looking for #if 0 in Swift. What I should have been searching for is nested multiline comments in Swift..
Straight from the horses mouth (also known as the Swift Programming Language Guide): Unlike multiline comments in C, multiline comments in Swift can be nested inside other multiline comments. … Nested multiline comments enable you to comment out large blocks of code quickly and easily, even if the code already contains multiline comments.
Well, isn’t that handy! Now I can comment out large blocks of code at will by placing
/* and
*/ around them. Life is good. 🙂
1 thought on “#if 0 In Swift”
Nested comments can be confusing. There is #if false and #endif in swift. | https://dev.iachieved.it/iachievedit/if-0-in-swift/ | CC-MAIN-2021-04 | refinedweb | 333 | 71.24 |
Rygel, a home media solution (UPnP AV MediaServer) that allows users to easily share audio, video, and pictures to other devices, is now at version 0.17.7.
With Rygel, users will be able to browse the media collection from the TV or PS3 on a PC running GNOME, and they will have the possibility to play any of said media.
Highlights of Rygel 0.17.7:
• Keywords have been added to the .desktop file;
• All public classes have been converted to use GObject-style construction;
• .smi subtitles are now supported;
• Downgrade hacks are now applied to the media renderer;
• An issue with translation strings being split has been fixed.
Check out the official changelog for a complete list of updates and new features.
Download Rygel 0.17.7 right now from Softpedia. Remember that this is a development version and it should NOT be installed on production machines. It is intended for testing purposes only. | http://linux.softpedia.com/blog/Rygel-0-17-7-MediaServer-Fixes-GStreamer-324618.shtml | CC-MAIN-2015-14 | refinedweb | 156 | 66.23 |
console.alert makes screen unresponsive when called from within form_dialog window
Hello,
I am running into the following problem: when I call a console.alert() from within a form_dialogs, the screen freezes completely and becomes unresponsive. Is there a way around it?
To illustrate:
import console, dialogs fields = [{‘type’:’check’, ‘key’:’testing’, ‘title’:’atest’ }] dialogs.form_dialog(fields = fields)
And in the dialogs.py module, in the tableview_did_select function, right under
if t == ‘check’, add:
console.alert('this','is','a','test')
Any help is much appreciated,
G
try using @in_background
Yep I've tried but it pushes the window prompt behind the form_dialog window and makes it unusable.
Would you be willing to have a look at it, I could send you my files/github repo to run on your side.
Thanks,
G
Right. forgot:
use console.hud_alert for simple notifications.
Alternatively, you might need to use a thread, or maybe dismiss the dialog first -- cnsole.alert doesn'tplay nice with wait_modal.
Alternatively, you can attach your own view to a "shield view".
Thanks for the suggestions. I will try them ! | https://forum.omz-software.com/topic/4569/console-alert-makes-screen-unresponsive-when-called-from-within-form_dialog-window | CC-MAIN-2022-05 | refinedweb | 180 | 61.22 |
In this Pandas tutorial, we will go through the steps on how to use Pandas read_html method for scraping data from HTML. First, in the simplest example, we are going to use Pandas to read HTML from a string. Second, we are going to go through a couple of examples in which we scrape data from Wikipedia tables with Pandas read_html. In a previous post, about exploratory data analysis in Python, we also used Pandas to read data from HTML tables.
Import Data in Python
When starting off learning Python and Pandas, for data analysis and visualization, we usually start practicing importing data. In previous posts, we have learned that we can type in values directly in Python (e.g., creating a Pandas dataframe from a Python dictionary). However, it is, of course, more common to obtain data by importing it from available sources. Now, this most commonly done by reading data from a CSV file or Excel files. For instance, to import data from a .csv file we can use Pandas read_csv method. Here’s a quick example of how to but make sure to check the blog post about the topic for more information.
import pandas as pd df = pd.read_csv('CSVFILE.csv')
Now, the above method is only useful when we already have data in a comfortable format such as csv or JSON (see the post about how to parse JSON files with Python and Pandas).
Most of us use Wikipedia to learn information about subjects that interest us. Additionally, these Wikipedia articles often contain HTML tables.
To get these tables in Python using pandas we could cut and paste it into a spreadsheet and then read them into Python using read_excel, for instance. Now, this task can, of course, be done with one less step: it can be automized using web scraping. Make sure to check out what web scarping is.
Prerequisites
Now, of course, this Pandas read HTML tutorial will require that we have Pandas and its dependencies installed. We can, for instance, use pip to install Python packages, such as Pandas, or we install a Python distribution (e.g., Anaconda, ActivePython). Here’s how to install Pandas with pip:
pip install pandas.
Note, if there’s a message that there’s a newer version of pip available check the post about how to upgrade pip. Note, we also need lxml or BeautifulSoup4 installed and these packages can, of course, also be installed using pip:
pip install lxml.
Pandas read_html Syntax
Here’s the simplest syntax of how to use Pandas read_html to scrape data from HTML tables:
pd.read_html('URL_ADDRESS_or_HTML_FILE')
Now that we know the simple syntax of reading an HTML table with Pandas, we can go through the read_html examples.
Pandas read_html Example 1:
In the first example, on how to use Pandas read_html method, we are going to read an HTML table from a string.
import pandas as pd html = '''<table> <tr> <th>a</th> <th>b</th> <th>c</th> <th>d</th> </tr> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> </tr> <tr> <td>5</td> <td>6</td> <td>7</td> <td>8</td> </tr> </table>''' df = pd.read_html(html)
Now, the result we get is not a Pandas DataFrame but a Python list. That is, if we use the type() function we can see that:
type(df)
If we want to get the table, we can use the first index of the list (0):
Pandas read_html Example 2:
In the second, Pandas read_html example, we are going to scrape data from Wikipedia. In fact, we are going to get the HTML table of Pythonidae snakes (also known as Python snakes).
import pandas as pd dfs = pd.read_html('')
Now, we get a list of 7 tables (
len(df)). If we go to the Wikipedia page, we can see that the first table is the one to the right. In this example, however, we may be more interested in the second table.
dfs[1]
Pandas read_html Example 3:
In the third example, we are going to read the HTML table from the covid-19 cases in Sweden. Here we’ll use some additional parameters o the read_html method. Specifically, we will use the match parameter. After this, we will also need to clean up the data and, finally, we will do some simple data visualizations.
Scraping Data with Pandas read_html and the match Parameter:
As can be seen, in the image above, the table has this heading: “New COVID-19 cases in Sweden by county”. Now, we can use the match parameter and use this as a string input:
dfs = pd.read_html('', match='New COVID-19 cases in Sweden by county') dfs[0].tail()
This way, we only get this table but still in a list of dataframes. Now, as can be seen in the image above we have three rows, at the bottom, that we need to remove. Thus, we are going to remove the last three rows.
Removing the Last rows using Pandas iloc
Now, we are going to remove the last 3 rows using Pandas iloc. Note, we use -3 as the second parameter (make sure you check the Pandas iloc tutorial, for more information). Finally, we also make a copy of the dataframe.
df = dfs[0].iloc[:-5, :].copy()
In the next section, we will learn how to change the MultiIndex column names to a single index.
MultiIndex to Single Index and Removing Unwanted Characters
Now, we are going to get rid of the MultiIndex columns. That is, we are going to make the 2 column index (the names) to the only column names. Here, we are going to use DataFrame.columns and DataFrame.columns,get_level_values():
df.columns = df.columns.get_level_values(1)
Finally, as can be seen in the “date” column, we have some notes from the WikiPedia table we have scraped using Pandas read_html. Next, we will remove them using the str.replace method together with a regular expression:
df['Date'] = df['Date'].str.replace(r"\[.*?\]","")
Changing the Index using Pandas set_index
Now, we continue by using Pandas set_index to make the date column the indexes. This is so that we can easily create a time series plot later.
df['Date'] = pd.to_datetime(df['Date']) df.set_index('Date', inplace=True)
Now, to be able to plot this we need to fill the missing values with zeros and change the data types of these columns to numeric. Here we use the apply method, as well. Finally, we use the cumsum() method to get the added values for each new value in the columns:
df.fillna(0, inplace=True) df = df.iloc[:,0:21].apply(pd.to_numeric) df = df.cumsum()
Time Series Plot from HTML Table
In the final example, we take the data we scraped using Pandas read_html and create a time series plot. Now, we also import matplotlib so that we can change the location of the legend of the Pandas plot:
%matplotlib inline import matplotlib.pyplot as plt f = plt.figure() plt.title('Covid cases Sweden', color='black') df.iloc[:,0:21].plot(ax=f.gca()) plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))
Conclusion: How to Read HTML to a Pandas DataFrame
In this Pandas tutorial, we learned how to scrape data from HTML using Pandas read_html method. Furthermore, we used data from a Wikipedia article to create a time series plot. Finally, it would have been possible to use Pandas read_html with the parameters index_col to set the ‘Date’ column as index column.
Great article
it has to be modified – replace -3 with -5 in following line:
df = dfs[0].iloc[:-3, :].copy()
and one more thing – in last snippet there is one bracket too much – instead of:
plt.legend(loc=’center left’, bbox_to_anchor=(1.0, 0.5)))
use this:
plt.legend(loc=’center left’, bbox_to_anchor=(1.0, 0.5))
Thanks for your feedback, Jan. I am glad you liked the article and appreciate that you found my typos/errors.
thanks for sharing,
as a constructive feedback, you have parenthesis imbalance in
plt.legend(loc=’center left’, bbox_to_anchor=(1.0, 0.5)))
it should be
plt.legend(loc=’center left’, bbox_to_anchor=(1.0, 0.5))
and in order to visualize the plot, a call to plt.show() is needed.
Thanks, Orlando. I have now fixed this. | https://www.marsja.se/how-to-use-pandas-read_html-to-scrape-data-from-html-tables/ | CC-MAIN-2020-24 | refinedweb | 1,391 | 64.91 |
Contents
Smart Pointers can greatly simplify C++ development. Chiefly, they provide automatic memory management close to more restrictive languages (like C# or VB), but there is much more they can do.
I already know smart pointers, but why should I use boost ?
- What are Smart Pointers?
- The first: boost ::scoped_ptr<T>
- Reference counting pointers
- Example: Using shared_ptr in containers
- What you absolutely must know to use boost smart pointers correctly
- Cyclic References
- Using weak_ptr to break cycles
- intrusive_ptr - lightweight shared pointer
- scoped_array and shared_array
- Installing Boost
- Resources
What are Smart Pointers?
The name should already give it away::
Let's start with the simplest one:
The first: boost ::scoped_ptr<T>.
The following sample uses a
scoped_ptr
for automatic
destruction:.
- For this purpose, using
scoped_ptris more expressive than the (easy to misuse and more complex)
std::auto_ptr: using
scoped_ptr, you indicate that ownership transfer is not intended or allowed.
Reference counting pointers:
:
Then, we assign it to a second pointer
mySample2
. Now,
two pointers access the same data:
We reset the first pointer (equivalent to
p=NULL
for a
raw pointer). The
CSample
instance is still there, since
mySample2
holds a reference to it:
Only when the last reference,
mySample2
, goes out of
scope, the
CSample
is destroyed with it:
Of course, this is not limited to a single
CSample
instance, or two pointers, or a single function. Here are some use cases
for a
shared_ptr
.
- use in containers
- using the pointer-to-implementation idiom (PIMPL)
- Resource-Acquisition-Is-Initialization (RAII) idiom
- Separating Interface from Implementation.
Important Features.)
- Works on many platforms, proven and peer-reviewed , the usual things.
Example::
std::vector< CMyLargeClass *> vec;
vec.push_back( new CMyLargeClass(" bigString" ) );
However, this throws the task of memory management back to the
caller. We can, however, use a
shared_ptr
:
:
>>IMAGE
}
What you absolutely must know to use boost smart pointers correctly
.
This means:
-.
Rule 2: No circular references
- If you have two objects
referencing each other through a reference counting pointer, they are
never deleted. boost
provides
weak_ptr
to break such cycles (see below).
Rule 3: no temporary shared_ptr
- Do not construct temporary
shared_ptr
to pass them to functions, always use a named (local) variable. (This
makes your code safe in case of exceptions. See the boost
: shared_ptr
best practices
for a detailed explanation.)
Cyclic References
Reference counting is a convenient resource management mechanism, it has one fundamental drawback though: cyclic references are not freed automatically, and are hard to detect by the computer. The simplest example is this:
:
.
The problem is not solvable with a "better" shared pointer implementation (or at least, only with unacceptable overhead and restrictions). So you have to break that cycle. There are two ways:
- Manually break the cycle before you release your last reference to it
- When the lifetime of
Dadis known to exceed the lifetime of
Child, the child can use a normal (raw) pointer to
Dad.
- Use a
boost ::weak_ptrto break the cycle.
Solutions (1) and (2) are no perfect solutions, but they work with
smart pointer libraries that do not offer a
weak_ptr
like boost
does. But let's look at
weak_ptr
in detail:
Using weak_ptr to break cycles:
.
intrusive_ptr - lightweight shared pointer.
To use a type
T
with
intrusive_ptr
, you
need to define two functions:
intrusive_ptr_add_ref
and
intrusive_ptr_release
.
The following sample shows how to do that for a custom class:
;)
scoped_array and shared_array
They are almost identical to
scoped_ptr
and
shared_ptr
- only they act like
pointers to arrays, i.e., like pointers that were allocated using
operator
new
[]
.
They provide an overloaded
operator
[]
.
Note that neither of them knows the length initially allocated.
Installing Boost
Download the current boost version from boost .org , and unzip it to a folder of your choice. The unzipped sources use the following structure (using my folders):
I add this folder to the common includes of my IDE:
- in VC6, this is Tools/Options , Directories tab, "Show Directories for... Include files ",
- in VC7, this is Tools/Options , then Projects/VC++ directories , "Show Directories for... Include files ".
Since the actual headers are in the boost
/
subfolder, my sources has
#include
"
boost
/smart_ptr.hpp"
.
So everybody reading the source code knows immediately you are using boost
smart pointers, not just any
ones.
Note about the sample project
The sample project contains a sub folder boost / with a selection of boost headers required. This is merely so you can download and compile the sample. You should really download the complete and most current sources (now !).
VC6: the min/max tragedy.
boost
tries to fix that as good
as they can, but sometimes you will run into problems. If this happens,
here's what I do: put the following code before the first
include
:
#define _NOMINMAX // disable windows.h defining min and max as macros
#include " boost /config.hpp" // include boost s compiler-specific " fixes"
using std::min; // makle them globally available
using std::max;
This solution (as any other) isn't without problems either, but it worked in all cases I needed it, and it's just one place to put it.
Resources
Not enough information? More Questions?
- boost users mailing list
Questions about boost ? That's the place to go.
Articles on Code Project:
- An Introduction to boost by Andrew Walker
- Designing Robust Objects with boost by Jim D'Agostino, a very interesting article: it seems to cover too much topics at once, but it excels at showing how different tools, mechanisms, paradigms, libraries, etc. work together..
- 顶
- 0
- 踩
- 0
- • (CodeBlocks+MingW)安装和使用Boost
- • ubuntu12.04+boost_1_54_0
- • Ceph源码编译
- • VC++2010下编译STLport,Boost
- • 最新版本Mysql 5.7.19三种安装方式手 | http://blog.csdn.net/metasearch/article/details/6156548 | CC-MAIN-2017-34 | refinedweb | 925 | 55.44 |
This is one of a series of posts on languages, you can read more about that here..
You can find more detail and proper introductory material at. And this is my first observation - the language has great documentation.
What's to like?
I’m gonna go get hammered with Papyrus.
>>IMAGE.
You had just one job.
So you handle errors yourself. Go has an inbuilt interface called error -
type error interface {
Error() string
}
and allows a function to return it along with the intended return type, which has a surface similarity with multiple return values in Groovy/Python. Now, I can see this kind of in place error handling driving people insane -
if f, err := os.Open(filename); err != nil {
return err
}.
Because there are no exceptions there is no finally construct - consequently you're subject to bugs around resource handling and cleanup. Instead there is the 'defer' keyword, that ensures an expression is called after the function exits, providing an option to release resources with some clear evaluation rules. -
package main
import "fmt"
func sum(i int, j int) (int, error) {
return i + j, nil
}
func main() {
s, err := sum(5,10)
if err != nil {
fmt.Println("fail: " + err.Error())
}
fmt.Println(s)
}
Alternatively, to make a method called 'plus' the receiving type, is stated directly after 'func' keyword -
package main
import "fmt"
type EmojiInt int
func (i EmojiInt) plus(j EmojiInt) (EmojiInt, error) {
return i + j, nil
}
func main() {
var k EmojiInt = 5
s, err := k.plus(10)
if err != nil {
fmt.Println("fail: " + err.Error())
}
fmt.Println(s)
}
This composition drive approach leads us into one the most interesting areas of the language, that's worth its own paragraph.
Go does not have inheritance or classes.
If it helps at all, here's a surprised cat picture -
>>IMAGE great decision. Controversial, but great. You can still define an interface -
type ActorWithoutACause interface {
receive(msg Message) error
}.
This ain't chemistry, this is art.
Dependency management seems to be a strong focus of the language. Dependencies are compiled in, there's no dynamic linking, and Go does not allow cyclic dependencies. Consequently build times in Go are fast. You can't compile against an unused dependency - this won't compile -
package main
import "fmt"
import "time"
func main() {
fmt.Println("imma let u finish.")
}
prog.go:3: imported and not used: "time
which may seem pedantic but scales up well when reading existing code - all imports have purpose. You can use the dependency model to fetch remote repositories, eg via git. I have more to say on that when it comes to externalities.
I mentioned that Go builds are fast. That's an understatement. They're lightning fast, fast enough to let Go be used for scripting..
Go doesn't have an implicit 'self/this' concept, which is great for avoiding scoping headaches a la Python, as well as silly interview questions. When names are imported, they are prefixed such that imported names are qualified, all unbound names are in the package scope -
package main
import "fmt"
import "time"
func main() {
time.Sleep(30)
fmt.Println("imma let u finish.")
}.
Go allows pointers. For the variable 'v', '&v' holds the address of v rather than its value.
package main
import "fmt"
func main() {
v := 1;
vptr := &v
fmt.Println(v)
fmt.Println(vptr)
fmt.Println(*vptr)
fmt.Println(*&v)
}
1
0xc010000000
1).
Go has two construction keywords for types - new and make. The new keyword allocates memory but doesn't initialise and returns a pointer. The make keyword performs allocation and initialization and returns the type directly. using int32 to describe money however.
You have just saved yourself from a fate worse than the frying pan
The Go concurrency model prefers CSP to shared memory. There are synchronization controls available in the sync and atomic packages (eg CAS, Mutex) but they don't seem to be the focus of the language. In terms of mechanism, Go uses channels and goroutines, -
package main
import "fmt"
import "time"
func emit(c chan int) {
for i := 0; i<100; i++ {
c <- i
fmt.Println("emit: ", i)
}
}
func rcv(c chan int) {
for {
s := <-c
fmt.Println("rcvd: ", s)
}
}
func main() {
c := make(chan int, 100)
go emit(c)
go rcv(c)
time.Sleep(30)
fmt.Println("imma out")
}
Channels are pretty cool. They provide a foundation for building things like server dispatch code and event loops. I could even imagine building a UI with them. runtime.gomaxprocs global,.
Externalities
Onto some things that bother me about Go.
Rust. blameless post-mort.
Conclusions
Go seems to hit a sweetspot between C/C++, Python JavaScript, and Java, possibly reflecting its Google heritage, where those languages are I gather, sanctioned. It seems to be trying to be a more effective language rather then a better language, especially for in-production use.
Should you learn it and use it? Yes, with two caveats. How much you like static type systems, and how much you value surrounding tool lenses and HLists in Go while staying sane..
2013/06/02: updated the Node/Erlang concurrency and clarified pointer observations with feedback from @jessemcnelis. Somehow in this wall of text, I forget to mention readability, thankfully was reminded by @davecheney | http://dehora.net/journal/2013/06/01/on-go/ | CC-MAIN-2016-22 | refinedweb | 872 | 66.13 |
If.
API contract
Alright, so what kind of destruction do we need to do to your API contract? Hopefully not much at all.
Fundamentally, you need a way for the client to make a conditional request for data. If your API supports
ETag and
If-None-Match then you’re already there. Queries against a timestamp are usually not good enough, as data could change twice with the same timestamp. You’ll want something more precise like a resource hash or version.
Assuming your API has a good way to handle conditional requests, now you need to decide how the client should ask the server to delay a response.
It might be tempting to make the server automatically delay all requests that have failed conditionals. Then your API contract wouldn’t need to change, and all existing plain-polling clients would magically become long-polling clients! However, this may break clients that depend on conditional checks responding quickly. We recommend making the long-polling behavior opt-in to be safe.
As for how to do the opt-in, we suggest using the
Prefer header. The
Prefer header is already an RFC, and one of the things you can do with it is tell the server that you are willing to wait for a response up to a certain amount of time. For example:
GET /resource HTTP/1.1 Host: example.com If-None-Match: "etag-of-resource" Prefer: wait=120
This is saying the client wants a response from the server within 2 minutes. Your API could use this as a hint that it’s acceptable to delay the response.
Updating your API documentation is easy, just add an explanation of the
Prefer header.
Implementation, client side
On the client side, simply update any polling requests to ask for long-polling. The client code otherwise stays the same. For example, if you’ve got polling code in Python that looks like this:
import time import requests etag = None while True: headers = {}(5)
All you need to do is modify a couple lines of code:
import time import requests etag = None while True: headers = {'Prefer': 'wait=120'} # <----- add hint(0.1) # <----- reduce delay between requests
Hopefully modifying your actual client code projects is just as easy. It might take a little more effort if your polling isn’t using conditional requests or a backoff strategy yet, but that shouldn’t be too hard to fix.
Implementation, server side
The real work is on the server side. How you go about supporting long-polling greatly depends on your programming language and/or server stack.
Here we’ll describe how to implement using Pushpin, an open source proxy server that makes building realtime APIs easy.
First, install Pushpin and configure it to forward traffic to your backend.
Next, when the backend receives a request containing a conditional that fails, respond with a “no data” response along with instructional headers. For example, here’s how a “no data” response might look for an
If-None-Match conditional request:
HTTP/1.1 200 OK ETag: "etag-of-resource" Grip-Status: 304 Grip-Hold: response Grip-Channel: /resource; prev-id=etag-of-resource Grip-Timeout: 120
Pushpin removes the instructional
Grip-* headers from the response and changes the status code from 200 to 304, but it doesn’t forward it to the client right away. Instead it waits up to 120 seconds before responding, unless it receives data on the
/response channel.
If no data is received in time, Pushpin sends a responds to the client that looks like this:
HTTP/1.1 304 Not Modified ETag: "etag-of-resource"
Lastly, whenever the resource changes, the backend publishes the resource’s new value to Pushpin’s private control API:
POST /publish/ HTTP/1.1 Host: localhost:5561 Content-Type: application/json { "items": [ { "channel": "/resource", "id": "new-etag-of-resource", "prev-id": "previous-etag-of-resource", "formats": { "http-response": { "code": 200, "headers": [ [ "Content-Type", "text/plain" ] ], "body": "The content of the resource." } } } ] }
This will cause Pushpin to send a response to the client that looks like this:
HTTP/1.1 200 OK ETag: "new-etag-of-resource" Content-Type: text/plain The content of the resource.
Conclusion
Realtime push doesn’t have to be complicated. If you’re already doing plain-polling with your API, switching to long-polling can be easy with the right tools and it barely affects your API contract and client code. There’s really nothing to lose. | https://realtimeapi.io/hub/moving-polling-long-polling/ | CC-MAIN-2019-47 | refinedweb | 745 | 62.58 |
VSTO 2005 Second Edition Beta (aka VSTO2005SE) - this is a new free product that complements VSTO 2005. See this announcement from KD Hallman if you want to know general details about the product and the roadmap.
I am here to discuss technical details of what it is. First of all - there is a new design time experience for building managed Add-Ins for Office 2003 applications (Excel, Word, Outlook, Visio and PowerPoint - this is for those who use Office 2003 and VS 2005) as well as support for building managed Add-Ins for Office 2007 applications (InfoPath jumped on this band wagon as well).
There is not much difference between Office 2003 and Office 2007 projects. Here, I can count those differences below:
The VSTO2005SE projects are very similar to what the Outlook Add-In project looked in VSTO 2005. The very first difference is that the name of the entry point class has changed - it is not longer ThisApplication, but is rather ThisAdd. So, instead of writing this.Inspectors to get to the Outlook's Inspectors collection you will write this.Application.Inspectors.
If you want to take advantage of new Office 2007 functionality that is exposed to add-ins you will need to implement a ComVisible public class deriving from any arbitrary interface e.g. IRibbonExtensibility, FormRegionStartup (one does not have to implement ICustomTaskPaneConsumer - VSTO runtime takes care when you call ThisAddin.CustomTaskPanes.Add(new UserControl(), "My task pane"). Next you will need to return this class from ThisAddIn's RequestService override. Here is a little example:
public partial class ThisAddIn
{
private
Unless I missed something that pretty much concludes the general design time discussion. In my next posts I will probably talk more about how to add a Ribbon to VSTO add-ins.
We will also be shipping a new VSTO runtime redist. Unlike, VSTO 2005 Design Time - the new redist is not a new product, but is rather an upgrade for the original runtime redist. The reason for the runtime upgrade is that it incorporates this addition CustomTaskPanes functionality and support for arbitrary services that VSTO customizations can now expose. Also, we fixed a number of breaking changes in Excel's ListObject functionality that affected the behavior of ListObject's data-binding on Office12.
One final note - you MOST probably will have trouble using this software if you ever installed VSTO v3 CTP - unfortunately, due to the poor setup support in VSTO v3 CTP, uninstalling it won't solve the problem. You may try to uninstall any the CTP, VSTO 2005 and all the traces of Visual Studio from the machine - then it MIGHT solve the problems. However, the most reliable solution is just re-installing the OS. That is not fun and I am profusely apologizing that you might have to do that. We did much better job with this release to ensure we do have a clear servicing path for this product.
Hi Misha,
After reading quite a few posts and trying out various shortcuts or hacks to acheive an "Application Level Task Pane" for Word 2003, i have really come to a grinding halt !! few of the paths that i followed were
1. Tried to modify the XML of a WORD document by adding the _AssembleName=* and _AssemblyLocation custom document properties....
2. I am now trying to acheive this by Attaching Managed Code Extensions to Documents...
by that i mean Can I use the ... Serverdocuement.Addcustomization ...
method to attach my custom task pane to any office 2003 word document/s through the add-in..!!
.. i guess my question would be that in one of these posts Misha did point out that it is possible to attach a task pane at an Application level but could only be acheived by someone like her who knows the internals of ActionsPane and VSTO
and it isn't for the *****WeakHearted*****.... so if you could point me in the right direction or suggest an alternative, that would be great !!!
I know that Custom Task panes are possible in word 12/ 2007... but i require to achieve this with word 2003 edition... as our target audience is not likely to move to office 2007 for quite some time !!!
If i haven't been clear please do ask for clarifications !!!
thax in advance,
Billy
while its not about VSTO 2005 SE..but i would love to know your thoughts on this ..
one more voice for the actions pane access from within managed add-in. Currently our add-in uses a custom dialog floating on top of the document. We planned to put it into the actions pane once we drop Office XP support. But it looks there is still a long wait for us, as our customers do not upgrade to Office 2007 in foreseeable future and there is no easy way to exploit the actions pane in Office 2003.
Any good news for us?
Thanks a lot,
Michael.
Hi Michael,
I am really sorry to disappoint you. Unfortunately, in this release we did not come around to supporting ActionsPane for the add-ins.
Thanks, Misha, for the quick reply. We'll try to be more creative then.
Misha, Just to make sure I under you correct:
VSTO 2005 SE does NOT support ActionsPane for Excel 2003?
while VSTO 2005 does, on a document- level.
If that's the case, given our project heavily uses action pane and needs to support Excel 2003, I would stick with the VSTO 2005 ( 1st edition ).
Pleaes advice.
VSTO2005SE runtime is a superset of VSTO2005 runtime. So, ActionsPane for doc-level customization on Excel 2003 and Word 2003 is supported.
The original deployment paper targeted deployment aspects of customizations built using VSTO 2005 release
Guys, the financial industry is not going to support Office 2007 any time soon, we're just now converting to Excel 2003...
When are you planning to support creation of host items or at least working with actions pane in Excel 2003? Without this, the add-in has little use to us - we need to generate rich Excel spreadsheets from an application level add-in. Took me a while to realize this would not be possible via VSTO 2005 SE.
Misha,
I am uploading my VSTO SE application to test for Office 2007.
Can you tell me if through VSTO SE, i can support new default extensions of .xlsx,xlsm in my project. I am able to support .xls support for Office 2007. Basically what i am looking for is, if can i open through VSTO SE in office 2007 dedault extension of .xlsx and save in this format and open in this format
Kim,
Sorry, I could not understand what you are trying to do exactly so if you could clarify your scenario that would help. I will try to write something but I am not sure whether it directly applies to your scenario.
If you have a customized .XLS file - you can save it as an .XLSX file without loosing functionality i.e. opening such file in Excel will cause the customization to run as expected.
VSTO 2005 SE does not have additional support for directly designing in Office 2007 (as in VS2005 you could host .xls files directly inside Visual Studio), but again you can design using Office 2003 and then save files in new format.
i dont know why microsoft missed document level customisation functionality with VSTO 2005SE,Which was available with VSTO2005.does it not looks like old was gold?and even 2005 is no more available.what to do?when microsot is going to release new one?now how to go with document level customisation?
If you would like to receive an email when updates are made to this post, please register here
RSS
Trademarks |
Privacy Statement | http://blogs.msdn.com/mshneer/archive/2006/09/14/vsto2005se-announcement.aspx | crawl-002 | refinedweb | 1,294 | 63.59 |
An easy way to parse XML in Python is using Python xml.etree.ElementTree, which parses the XML document/data into a tree structure, where each node is an Element object. Only within few lines of code, one can extract all the XML information including tag and attributes. ElementTree looks perfect until the line number of certain tag block within the original XML file is wanted. In this post, we will hack into the Python source file, add line number support for the ElementTree, rebuild the Python and demonstrate our awesome hacking using simple testing script, just 4 FUN! K.R.K.C.
0. Question: can we get the line number using xml.etree.ElementTree?
1. Analysis gives the detailed usage of ElementTree. Apparently, it does not support line number. On one hand, this is reasonable – why do we need line number if the XML is parsed into a tree structure. On the other hand, while tree structure saves most of the information from the XML file, it loses the line number information for certain tag block within the original file, which may be useful for debugging. shows one way to get the line number information using xmlparser.CurrentLineNumber. However, we do not want to deal with the low-level parser and we want to have the line number from the ElementTree. Can we do that? Yes, hack Python!
2. R.t.D.C. provides the latest ElementTree implementation within the Python 2.7.8 implementation. To parse a XML file, we only need to call ElementTree.parse(‘filename’) within the application. Let us find that parse() method. Because we do not determine the parser option, ElementTree.parse() method would make up a default parser for us:
parser = XMLParser(target=TreeBuilder())
Then let up jump into XMLParser class within the same source file. Looking at the constructor function, we will find the XML parser we are going to use to expat, a C-based XML parser library. (pyexpat is just a Python wrapper for the expat implementation).
parser = expat.ParserCreate(encoding, "}")
Once the parser is created, all the following work is setting different callbacks for the expat parser. These callbacks tell the expat how to process the parsed XML information. There is a one callback we are especially interested in.
parser.StartElementHandler = self._start
This callback is used to tell expat how to handle each new element/node parsed from the XML data. The start key word here stands for the starting point of this element/node. Let us go to the XMLParser._start() method, which will call the target.start() method.
return self.target.start(tag, attrib)
What is target.start() method? Remember the target argument we passed into the XMLParser constructor? That is it. The target is the TreeBuilder class within the same source file. Let us jump into TreeBuilder.start() method.
self._last = elem = self._factory(tag, attrs)
Check the constructor of TreeBuilder, we will find the _factory() method by default is the Element class. Now the story happens here is pretty clear: The XMLParser parses the XML data and saves the information as Element into a tree structure. The application can extract these information from Element object directly. Then a reasonable place to place the line number is the Element class too. Cool, we have done! Wait…but where does the line number come from? Remember the parser we have created in XMLParser constructor? It has a member called self._parser, which is exactly the xmlparser object, which means…(leave me a msg if it is not clear…)
3. Hack
3.1. Download the Python source file (I am a fan of Python 2.X)
3.2. Hack the ElementTree
Python-2.7.8/Lib/xml/etree/ElementTree.py, where we will:
add line number into the Element class and update the corresponding constructor and other methods which will create a new Element instance;
update the TreeBuilder.start() method to have an extra line number argument and call our new Element constructor with line number support;
update the XMLParser._start() method to inject the line number and call our updated TreeBuilder.start() method to create new Element with line number
4. Test
Configure and make your new Python. Then use our new Python to test a simple ElementTree application. Here it goes~
[root@daveti test]# cat pyxml.py
import xml.etree.ElementTree as ET
tree = ET.parse(‘country_data.xml’)
root = tree.getroot()
for e in root:
print e.lineNum, e.tag, e.attrib
[root@daveti test]# /root/python/Python-2.7.8/python ./pyxml.py
3 country {‘name’: ‘Liechtenstein’}
10 country {‘name’: ‘Singapore’}
16 country {‘name’: ‘Panama’}
[root@daveti test]#
5. Code – pyet
All the code is available at my github and follows GPLv2.
Work hard to make it simple, man
magnificent publish, very informative. I’m wondering
why the opposite experts of this sector do not notice this.
You should continue your writing. I am confident, you’ve a huge readers’ base already!
This site was… how do I say it? Relevant!! Finally I have found something which helped me.
Thanks!
Good site you have got here.. It’s difficult to find excellent writing like yours these days.
I really appreciate people like you! Take care!!
Quality articles is the key to invite the users to pay a quick visit the web site,
that’s what this web page is providing.
I have read so many posts regarding the blogger lovers except this post is really
a pleasant paragraph, keep it up.
Hi there fantastic website! Does running a blog like this take a large amount of
work? I’ve virtually no expertise in computer programming however I had been hoping to start my
own blog soon. Anyhow, should you have any recommendations or tips for new blog owners please share.
I understand this is off topic nevertheless I just wanted
to ask. Thanks!
I couldn’t refrain from commenting. Very well written!
Hey fantastic website! Does running a blog similar to this take a large amount of work?
I have virtually no knowledge of programming but I was hoping to start my own blog in the near future.
Anyhow, should you have any suggestions or tips for new blog owners please share.
I understand this is off subject nevertheless I just wanted to ask.
Appreciate it!
It’s fantastic that you are getting thoughts from this piece of writing as well as from our
dialogue made here.
I genuinely enjoy studying on this website, it holds good content. Never fight an inanimate object. by P. J. O’Rourke. fedecadbedad
Hello! I know this is kind of personal experience and thoughts online.
Please let me know if you have any suggestions or tips for new aspiring bloggers.
Appreciate it!
Thanks , I have just been looking for info about this subject for a
while and yours is the greatest I have came upon till now.
However, what concerning the conclusion? Are you sure concerning the supply?
I do agree with all of the ideas you’ve presented for your post.
They’re really convincing and will certainly work.
Still, the posts are too quick for beginners. Could you please
extend them a little from next time? Thank you for the
I have fun with, cause I discovered exactly what I used to be taking a look for.
You’ve ended my four day lengthy hunt! God Bless you man. Have a great
day. Bye
Thank you for sharing your thoughts. I truly appreciate your efforts and I will be waiting for your next
write ups thank you once again. | https://davejingtian.org/2014/07/04/python-hacking-make-elementtree-support-line-number/ | CC-MAIN-2020-10 | refinedweb | 1,263 | 68.06 |
Ever records from Postgres DB. One endpoint will stream data to the client and another will read whole data into memory and return in one chunk.
If I work in Node.js environment, there’s usually Express.js framework in front of it with Sequelize orm. For this experiment I decided to try something different and choose Koa.js framework and Knex orm. Let’s start.
I’ll setup the project first:
Now time to add app dependencies. You can see all packages here. To setup my development environment I’ll use Docker and docker-compose. Let’s see how Dockerfile.dev looks like:
Pretty standard right? Now docker-compose.yml to add DB dependency and bootstrap whole thing:
Now that environment is pretty much ready, I’ll continue with application logic itself. Let’s look at app.js:
I first load .env vars, import Koa, my custom error handling middleware and router. The error handling middleware looks like this:
According to documentation, error handling middleware has to be added first in Koa app in order to capture all exceptions. Next stop is router:
Interesting thing to mention is that in app.js I use router.allowedMethods() middleware that handles unsupported methods with 405 Method Not Allowed for me. Lets look at the handlers next. nostream:
Pretty sure you’re wondering how that db looks like:
config is just simple object literal that exposes some env vars. You can see it here. I require knex, establish db connection and export instance of it. Since all node modules are singletons, no matter how many times I’ll require this package, initiation will be performed only once. Everything else in nostream handler is pretty much straightforward. Please refer to Koa or Knex documentation for more details. Next let’s look at stream handler:
Here I call .stream() on my query to get stream instance. I then pipe this query stream to client. In order for that to happen I have pipe function that returns a promise and we don’t exit the handler instantly but rather wait until streaming is done or error occurs. I added stringify package here because response (writeable stream) expects an input of a type string or an instance of Buffer and DB stream operates with Object types.
By the way, all ctx.throw will be captured by errorHandler middleware we created previously. Now before I jump into testing my server I need some data in DB. Since I have Knex already installed locally, I need a config file for it to be able to run migrations, seeds etc:
./node_modules/.bin/knex init
This will generate knexfile.js. I have slightly changed it to use my env vars. You can see it here. Now I’ll generate the migration:
./node_modules/.bin/knex migrate:make users
This will create a migration file in migrations/{timestapm}_users.js You can review it here. Before I run it, start the application:
docker-compose up --build
Now since app is up and running, time to run migration:
POSTGRES_HOST=localhost npm run migrate:up
I specify postgres host here since I run migration from host machine for DB that runs in docker environment under pg namespace and if I don’t specify it, pg name will be used from env vars which will end up with failed connection attempt.
Now what I need is some records in users table for my API to serve. Knex cli can ease this process. It has command to generate a seed file:
./node_modules/.bin/knex seed:make create_users
This will generate a seed file in seeds directory. You can see what I did with it here. If you’ll run into issues running it, try reducing amount of records you try to create. Currently it’ll try to create 60k records. Lets run it:
POSTGRES_HOST=localhost npm run db:seed
OK, with all that in place, I can now test both endpoints and see how well they perform. Let’s start with nostream endpoint:
And now stream endpoint:
So, streaming might be less memory intensive operation but it takes a bit longer to retrieve all data (60k users in this case). That certainly works when sending/processing large amounts of data and could be perfect fit for file processing or BI where we have to work with large data sets. When it comes to common tasks though, say admin panel that retrieves 10–100 records per page, most likely streaming wouldn’t be the best fit.
Not only because it takes a bit more time, but also due to code complexity as it requires more code to achieve same output. It all boils down to good old saying: “choose the right tool for the job”. I hope you have learned something useful. You can find the whole project here. | https://aciddaniel.medium.com/node-js-streams-in-action-5c4a5a64f6b4?source=post_page-----5c4a5a64f6b4-------------------------------- | CC-MAIN-2021-21 | refinedweb | 802 | 75.2 |
This is your resource to discuss support topics with your peers, and learn from each other.
02-09-2011 02:58 PM - edited 02-09-2011 03:04 PM
I'm just getting started on a Tablet AIR application and have Flash Builder 4 installed and running in trail mode fine. I've run through the HelloWorld example in the Blackberry documents and got it deployed to the simulator just fine as well. I then started the project that will be the actual submitted project. A port of an app I have for sale for iPhone/iPad, Android and WP7.
While running through the Development guide, I implemented the various methods for activate, deactivate and low memory. I'm having an issue with "Definition qnx:events could not be found", same error for qnx:system. However, I do see it as part of the SDK as listed under Flex Build Path -> Build path libraries under Project properties. I came here to find a solution and did for someone using FB 4.5 Burrito.
My question is, before I get too deep in this FB 4.1, should I go ahead and run Burrito 4.5 Preview instead since we'll all be there eventually anyway? I don't have any money invested in this and being an individual developer, no company backing, the cost of FB is hard to swallow. I'd rather start with something that's going to last me a while.
Thank you for your thoughts on this.
Nick
02-09-2011 03:03 PM
I'd be interested in hearing opinions on this.
From my perspective using Burrito is not an option as Adobe clearly states is it not to be used for production code, only for testing/experimentation.
So, our company will stay with FB 4.0.1 to develop the first release of our Playbook application. We will re-assess when Burrito gets closer to a firm release date.
02-09-2011 03:03 PM
Since posting this two minutes ago I've fixed my import problem by changing the lines from
import qnx.events; import qnx.system;
to
import qnx.system.*; import qnx.events.*;
and the project builds fine now.
But, back to the original question. Do I go with an Actionscript Mobile app in Burrito or stick with Flex Project in 4.1?
Thanks,
Nick
02-09-2011 03:05 PM
I've been using FB4 for sometime and it works just fine. This was an upgrade from Flex Builder 3.x (which was a upgrade from Flex Builder 2.x, and so on) and the transition was OK. Once 4.5 is not a "preview" release, I will consider upgrading to that depending on the upgrade price. I typically dont like to be a tester on IDEs since it is so central in my day to day operation.
In terms of price, you have to determine on your own the level of development you plan on doing with BB and Android. It is an investment, but if you dont have a product plan and a strategy in re-cooping your costs and effort, then go free and cheap with your development environment.
02-09-2011 03:33 PM
Regardless of which IDE you choose, they both have the same flaw that when you have to many images or files in your workspace the IDE refuses to package the bar file. 4.5 does have the mobile application and I would have to say that developing in 4.5 would probably be the way to go to familiarize yourself with the Hero framework. So the best of the two evils is 4.5.
02-09-2011 03:50 PM
If you happen to be a student or are unemployed, it is possible to get flash builder 4 for free.
02-09-2011 04:22 PM - edited 02-09-2011 04:23 PM
@L7ColWinters: Why are you including so many loose images? If this is a problem, just package them into a SWC, that's probably a better way to go away as you will get code complete and not have to have a bunch of [Embed] tags throughout your code.
@dooglehead: Yeah, and if you get that version, you can then further upgrade to Flash Builder Standard for only $99. A steal, really.
02-09-2011 05:52 PM
@dooglehead: I believe you cannot produce commercial applications from this version. It is meant to learn or keep your skills sharp.
02-09-2011 06:02 PM
I use that version (I am a student), and used it to create my playbook app.
02-09-2011 06:05 PM
I'm not saying that you physically cant, what I recall is that the license says that you should not without violating the license. How Adobe enforces that is anyones guess. | http://supportforums.blackberry.com/t5/Adobe-AIR-Development/Which-Flash-Builder-to-use/td-p/785263 | CC-MAIN-2015-32 | refinedweb | 807 | 72.76 |
Package internet in ubuntu-docs: "press return" instead of "press enter"
Bug Description
Binary package hint: ubuntu-docs
In several places in the package "internet", part of ubuntu-docs, the documentation directs people to press the Return key.
However, most PC keyboards have no key called Return, which can be confusing for many people. Instead, the documentation should mention "Enter" rather than "Return".
Here is one instance:
https:/
Thanks for reporting this bug. "Return" seems to be the standard name for this key - not all keyboards have an "Enter" key (the one on the numeric keypad), but many do call the Return key "Enter". As such, I don't think that the term should be changed.
See here for more information:
http://
Being a pack-rat, i have several keyboards at home, both working as well as broken.
I just did a count and i have ten keyboards at home, including the two that are currently in use, but not counting the Mac keyboards.
On all of the Mac keyboards that i have (from Mac128+ and up) and on most of the (8-bit) home computers, that key *is* called Return.
However, on nine out of my ten PC keyboards, the big key (to call it that) has "Enter" printed on it, but never "Return". One of the keyboards just has an arrow printed on the key.
Therefore i submit that calling a key "Return" when it usually has "Enter" printed on it, is confusing for users. Especially to new users who may never have heard of such a thing as a "Return" key.
Actually of the 20+ machines in this office, there are none with words and all with a symbol that coannot be replicated in unicode. Actually, historically return (as in carriage return) is as acceptable.
I say this is a really unneccesary change as there is no other key that it could be confused with.
I've seen several keyboards in my life, but never with return on it. Always with Enter. So I suggest to keep it this way. If you're really think this can make things hard to understand for people you could always make the word enter a tooltip. ;)
I think this issue is significant enough to merit an entry in the Style Guide. I'll open this up to the ubuntu-docs mailing list and report back.
A question to Phil Bull:
I saw there was a bit of a discussion on the ML after your initial post and it looks like most respondents would prefer "Enter" over "Return".
Would this suffice to justify a change in the docs?
Hi,
Yep, it looks like people would prefer to move over to "Enter", so I've confirmed the bug.
Phil - what was Gnome's view on this?
The last I heard, Milo had spoken to Shaun over at GNOME and it was planned as a topic for word-a-day.
I just checked the GNOME mailing list archives, and there's no sign of it in there. They must never have gotten around to it.
This bug was fixed in the package ubuntu-docs - 9.04.1
---------------
ubuntu-docs (9.04.1) jaunty; urgency=low
* Images should not be executable (LP: #206371) - Sahak Petrosyan
* Couple of typos (LP: #282358, LP: #266997) - Sahak Petrosyan
* ubuntu-
* Permit building html for other languages in Makefile - Mitsuya Shibata
* Use the same background image as Ubuntu website (LP: #305760)
* Make search available for users without javascript - Dustin Kirkland
* Various content improvements - Phil Bull
* Use "Enter", not "Return" - Joel Goguen (LP: #213104)
-- Matthew East <email address hidden> Thu, 11 Dec 2008 12:47:51 +0000
Please don't assign the whole Documentation Team to a bug. If you are working of fixing it, then assign it to yourself - otherwise assign the person working on it. | https://bugs.launchpad.net/ubuntu/+source/ubuntu-docs/+bug/213104 | CC-MAIN-2015-22 | refinedweb | 636 | 69.62 |
Details on the set-delete flow
Aerospike Server version 3.12.1 or above
As of version 3.12.1, released in April 2017, set-delete is deprecated. The new feature of deleting all the data in a set or namespace is now supported in the database.
See the following truncate documentation:
Truncate can also be executed from the client APIs. Here is the java documentation:
Aerospike Server version 3.12.0 or below
When a set-delete command is issued on a node, it flips a flag on the set. On the next nsup run, partitions are reduced one by one (primary index’s rb tree) and, for each, deleted records (belonging to the set marked as such) are put into the dq (delete queue).
The
dq is only used for nsup, to put records that are: evicted, expired and set-deleted. nsup runs every 120 seconds by default, for each namespace, sequentially. (see nsup-period - - to tune this).
So, all deleted records for the first partition are dumped on this dq queue. Then, another thread, part of the nsup process looks at this queue and transfers them over into the transaction queue (called q in the logs), for a transaction thread to pick them up from there, do the job (delete), and park them in wr (writes in progress) for the prole part to be taken care of.
On the prole side, those delete transactions go straight into the transaction queue.
The next partition will not be reduced until the delete queue (dq) gets below a specific count (10,000). So if evictions or expirations are also hapening, this would delay the next partition reduction.
In build 3.5.8 and above, the default nsup-delete-sleep value changed from 0 to 100 micro seconds (time to sleep between generation of each delete transaction generated). This throttles exactly how fast the dq queue is consumed and how fast the transaction queue is built up. (This is more important for the transaction queue in order to help avoid filling up the wr queue too fast which could cause spike in memory usage, and contention with other writes.) | https://discuss.aerospike.com/t/set-delete-flow/1167 | CC-MAIN-2018-30 | refinedweb | 358 | 71.04 |
@pnorcks: should be OK now, thanks for the report
Search Criteria
Package Details: mock 1.4.7.1-2
Dependencies (11)
- distribution-gpg-keys
- python
- python-distro
- python-pyroute2
- createrepo_c (optional) – for mockchain command
- dnf-plugins-core (optional) – to create RPMs for Fedora >= 24 and for Mageia
- lvm2 (lvm2-git) (optional) – for lvm_root plugin
- nosync (optional) – to speed up yum/dnf database access
- pigz (optional) – for parallel compression of chroot cache
- python-requests (optional) – for mockchain command
- yum-utils (optional) – to create RPMs for Fedora <= 23 (including EL5, EL6 and EL7)
Required by (0)
Sources (3)
Latest Comments
larchunix commented on 2017-11-17 19:05
pnorcks commented on 2017-11-17 14:15
When trying to use mock 1.4.7-1, I run into an exception:
Traceback (most recent call last):
File "/usr/bin/mock", line 79, in <module>
from mockbuild import util
File "/usr/lib/python3.6/site-packages/mockbuild/util.py", line 41, in <module>
from pyroute2 import IPRoute
ModuleNotFoundError: No module named 'pyroute2'
pnorcks commented on 2016-03-14 04:00
@Duologic: I'm not sure what you mean by "collaborate". Can you clarify?
I really prefer to run mock with 'sudo', both for reason I mentioned in my previous comment, and also because it makes clear that I'm running the program as root. Running mock with 'usermode' blurs that distinction...
Duologic commented on 2016-03-13 14:25
Can you collaborate on getting it running in 'usermode'?
pnorcks commented on 2015-06-04 22:46
I adopted the package.
Note that I removed the 'usermode' dependency from this package, since I prefer running mock with 'sudo', and it simplifies packaging.
pnorcks commented on 2015-02-05 20:35
@roheim: Thanks!
I'm now seeing an install failure. Error output is below.
error: failed to commit transaction (conflicting files)
mock: /usr/sbin exists in filesystem
mock: /usr/sbin/mock exists in filesystem
Errors occurred, no packages were upgraded.
roheim commented on 2015-02-05 18:01
@pnorcks: done.
Also upgraded to newest version.
pnorcks commented on 2015-01-28 06:39
I recommend passing '--sysconfdir=/etc' to ./configure so that the mock's many configuration files will live under /etc/ instead of /usr/etc.
roheim commented on 2014-08-28 21:46
This package is currently broken, but will be fixed.
Peter_Littmann commented on 2014-01-16 10:04
I suggest to use mock-git which I just uploaded and let this package rest in peace. | https://aur.archlinux.org/packages/mock/ | CC-MAIN-2017-47 | refinedweb | 412 | 53.92 |
Contains
struct picotm_spinlock and helper functions.
More...
#include <assert.h>
#include <stdatomic.h>
#include "compiler.h"
The
struct picotm_spinlock data structure provides an spin lock that is independent from the operating system. It's useful for portable modules or creating more complex data structures.
The spin lock uses a very simple implementation. It's non-recursive, so a thread cannot acquire a spin lock twice at the same time. It's also not dead-lock safe. The advantage of the simple implmentation is that it cannot fail with an error.
An instance of
struct picotm_spinlock is initialized by a call to
picotm_spinlock_init().
Alternatively, the macro
PICOTM_SPINLOCK_INITIALIZER initializes static lock variables, or stack-allocated locks. When both, function and macro initialization, is possible, the macro form os the prefered one.
After the initialization, the spinlock is in an unlocked state. A call to
picotm_spinlock_lock() acquires the spin lock, and a call to
picotm_spinlock_unlock() release the spin lock.
A call to
picotm_spinlock_lock() can possibly block the thread for an unbounded amount of time. A call to
picotm_spinlock_try_lock() only tries once to acquire the lock, and returns a boolean value signalling success or failure.
The spin lock's locking and unlocking functions act as memory barriers. Therefore load and store operations before, within, or after a critical section take effect ontheir side of the respective barrier. | http://picotm.org/docs/picotm-doc-0.11.0/dc/d87/a00032.html | CC-MAIN-2022-05 | refinedweb | 223 | 51.04 |
Suppose I have a Tensorflow tensor. How do I get the dimensions (shape) of the tensor as integer values? I know there are two methods, tensor.get_shape() and tf.shape(tensor), but I can't get the shape values as integer int32 values.
For example, below I've created a 2-D tensor, and I need to get the number of rows and columns as int32 so that I can call reshape() to create a tensor of shape (num_rows * num_cols, 1). However, the method tensor.get_shape() returns values as Dimension type, not int32.
import tensorflow as tfimport numpy as nps.
import tensorflow as tf
import numpy as np
s.
Code to get the shape as a list of ints
tensor.get_shape().as_list()
To complete your
tf.shape() function is incomplete, Add the following code to complete:
tensor2 = tf.reshape(tensor, tf.TensorShape([num_rows*num_cols, 1]))
Or
tensor2 = tf.reshape(tensor, tf.TensorShape([-1, 1]))
Hope this answer helps. | https://intellipaat.com/community/4037/how-to-get-tensorflow-tensor-dimensions-shape-as-int-values?show=4047 | CC-MAIN-2019-47 | refinedweb | 158 | 62.04 |
QWebView - main GUI thread stops to respond after trying to load a page
Hello,
I am running few processes with qApplication:qwebview on the same machine.
once in a while after trying to load a page, the main thread stops to respond. (only timer events continue, but the code in the main GUI thread does not).
I am loading a page with webView.setUrl, then waiting for loadfinished and meanwhile waiting in QEventLoop to keep the browser responsive.
It works fine most of the time but sometimes after trying to load a page the main thread stops responding (linux process goes to S state).
Anyone has an idea how to debug this thing ?
Thanks.
Citing from "this article"::
[quote. [/quote]
My guess is the extra eventloop you create may be the reason for your problems.
Thanks for the reply,
I didn't understand from the article though how to solve the problem or how to workaround this problem,
do you have any suggestions ?
I have to wait synchronously for page loadfinished in order to continue the application, and therefore I am using QEventLoop every time I am waiting for a page to finish loading.
Thanks.
The problem can be solved by not using an extra eventloop. Why do you have to wait synchronously for loadFinished anyways?
If you can't find any other way to get your software to work without the extra eventloop, atleast that might be a point to start debugging. Maybe you can build a wrapper around QEventloop to make sure you don't create more than one extra eventloop and to make sure the eventloop ends after a certain timeout interval.
Here's a "link to a thread": that discussed a similar problem.
well, the reason I have to wait synchronously for loadFinished is this:
I am building a web robot, that travels on a website and performs stuff there, so when I load a certain page I want to wait that it finished to load before I can do whatever I want on that page ( I need all the elements to be there for sure).
so I have created a wait_load function that after load started I start an eventloop, also start a timer for timeout that exits the eventloop if more then 60 seconds or so passed. the other condition to exit the eventloop is that a pageload event has fired.
the code looks like that:
@def waitLoad(self, timeout):
retry = 1
max_retries = 15
while True:
self.timer.start(timeout * 1000)
self.eloop.exec_()
if self.readyState == True:
return True
else:#retry loading page
retry = retry + 1
if retry > max_retries:
return False
self.webView.stop()
self.wait(5)
self.prepareLoad()
self.webView.reload()
return True
def wait(self, waittime):
self.timer.start(waittime * 1000)
self.eloop.exec_()
def loadFinished(self, ok):
self.timer.stop()
self.eloop.exit()
if ok:
self.readyState = True
def timerTimeout(self):
self.eloop.exit()@
You don't need an eventloop to do that. Just connect your robots startWork function to the loadFinished signal. The timeout signal could be connected to a tryReload function or a loadNextPage function.
I'm noticing you're using python. I'm not sure if connect for signals and slots is available there, but since it's such a crucial feature of Qt it most certainly is.
do you mean that I do not need an eventloop to wait for the page to finish loading ?
Sometimes event loop loops infinitely when using network requests (I don't know why tho). Therefore I suggest to use event loop "manually" to process events as long as you are really need to.
@
SomeProcess process;
process.start();
QEventLoop loop;
while (process.isRunning())
loop.processEvents();
process.getResults();
@
before I started using QEventLoop, I manualy processed events using QApplication.processEvents(), that made the same bug, GUI thread hangs...
So I tried QEventLoop, but same bug happened.
You think eventloop.processEvents is different ?
[quote author="NirBlinder" date="1371026555"]do you mean that I do not need an eventloop to wait for the page to finish loading ?[/quote]
You don't need an extra eventloop. Your application (QApplication or QCoreApplication) already has a running eventloop, so there's no need for a second one. You don't need to wait synchronously for the signal loadFinished. Just connect to the loadFinished signal and thats it.
Maybe I'm missing something, but from the use case you described there's no need for the extra degree of complexity you're adding with the second eventloop or the processEvent calls.
That is interesting , as I remember if I dump the eventloop, the webpage doesn't build itself, items are not painted at all, but maybe I am doing something wrong... ?
Do you call something like this anywhere in you app?
@
QApplication app;
app.exec();
@
In what context is the QWebView running (main thread of GUI application, QProcess, ...)?
My application is currently running in main thread of GUI application.
its constructor looks something like this:
@class MyBrowser(QApplication):
def init(self):
super(MyBrowser, self).init(None)
self.webView = QWebView()
self.page = WebPage(self.webView)
self.page.setUserAgent()
self.webView.setPage(self.page)
self.timer = QTimer()
self.timer.setSingleShot(True)
self.timer.timeout.connect(self.timerTimeout)
self.timeoutReached = False
self.webView.showMaximized()
self.readyState = False
self.webView.loadFinished.connect(self.loadFinished)
self.eloop = QEventLoop()@
and what I do is creating an instance of it:
@myBrowser = MyBrowser()@
and then something like:
@myBrowser.load("")
myBrowser.waitLoad(60)
myBrowser.load(someotherpage)
myBrowser.someCustomFunction()@
and so on...
So I do not use
@myBrowser.exec()@
because there is no real user handling the browser.
Is that understood ?
Is that the right approach ?
Ah ok so thats why you have no running eventloop and thus add your own.
Since I haven't used Qt with Python I can't really comment on that, but from the c++ perspective it seems weird. Maybe you should post a question in the "Language Bindings subsection ": of this forum.
Ok thank you anyway , I will try that .
Maybe I will switch to QT with C++, I heard its more stable.
Thank you for the help , I appreciate it. | https://forum.qt.io/topic/28179/qwebview-main-gui-thread-stops-to-respond-after-trying-to-load-a-page | CC-MAIN-2018-34 | refinedweb | 1,019 | 66.84 |
Actually, there are two Timer classes in the JDK. You and him are using two different classes. The code the OP isusing is correct for the Timer class he is using. With that said, he already posted this in another thread in this forum, at which I answered his question.
No he is not using his Timer class correctly, and he should read the Java Doc.
He imported
import java.util.Timer;this the one he is using.
He cannot use it in that way.
You are thinking of javax.swing.Timer which he might want to use but is not using.
He will get a compile error with his code because of an Invalid Constructor call.
You did not need the unnecessary sub class. but if you did want to use it then you should have put this in the Timer constructor:
time = new Timer(5,new TimerListener());
putting the this keyword means that nothing will be rendered due to the fact that in your actionPerformed method in the Board class was empty.
Hope it helped
Gen.
You should actually avoid using 'this' in constructors because it is one of the conditions that can cause Java to leak because it's not fully initialized so it is best to get out of that bad habit. A subclass is a good way to avoid it, but a Factory is better but well beyond what he's doing. However, you're right he used the subclass incorrectly. | http://www.gamedev.net/index.php?app=forums&module=extras§ion=postHistory&pid=4904126 | CC-MAIN-2013-48 | refinedweb | 246 | 82.75 |
Hi Zach,
thanks for your additional input. You are absolutely right: The long
namespace should be big enough. We are going to insert up to 2^32 values
into the list.
We only need support for get(index), insert(index) and remove(index)
while get and insert will be used very often. Remove is also needed but
used very rare.
Kind regards
Matthias
On 10/13/2011 04:49 PM, Zach Richardson wrote:
> Matthias,
>
> Answers below.
>
> On Thu, Oct 13, 2011 at 9:03 AM, Matthias Pfau<pfau@l3s.de> wrote:
>> Hi Zach,
>> thanks for that good idea. Unfortunately, our list needs to be rewritten
>> often because our data is far away from being evenly distributed.
>
> This shouldn't be a problem if you use long's. If you were to space
> them at original write (with N objects) at a distance of
> Long.MAX_VALUE / N, and N was 10,000,000 you could still fit another
> 1844674407370 entries in between.
>
>> However, we could get this under control but there is a more severe problem:
>> Random access is very hard to implement on a structure with undefined
>> distances between two following index numbers. We absolutely need random
>> access because the lists are too big to do this on the application side :-(
>
> I'm guessing you need to be able to implement all of the traditional
> get(index), set(index), insert(index) type operations on the "list."
> Once you start trying to do that, you start to hit all of the same
> problems you get with different in memory list implementations based
> on which operation is most important.
>
> Could you provide some more information on what operations will be
> performed the most, and how important they are. I think that would
> help anyone recommend a path to take.
>
> Zach
>
>> Kind regards
>> Matthias
>>
>> On 10/13/2011 02:30 PM, Zach Richardson wrote:
>>>
>>> Matthias,
>>>
>>> This is an interesting problem.
>>>
>>> I would consider using long's as the column type, where your column
>>> names are evenly distributed longs in sort order when you first write
>>> your list out. So if you have items A and C with the long column
>>> names 1000 and 2000, and then you have to insert B, it gets inserted
>>> at 1500. Once you run out of room between any two column name
>>> entries, i.e 1000, 1001, 1002 entries are all taken at any spot in the
>>> list, go ahead and re-write the list.
>>>
>>> If your unencrypted data is uniformly distributed, you will have very
>>> few collisions on your column names and should not have to re-write
>>> the list to often.
>>>
>>> If your lists are small enough, then you could use ints to save space,
>>> but will then have to re-write the list more often.
>>>
>>> Thanks,
>>>
>>> Zach
>>>
>>> On Thu, Oct 13, 2011 at 2:47 AM, Matthias Pfau<pfau@l3s.de> wrote:
>>>>
>>>> Hi Stephen,
>>>> this is a great idea but unfortunately doesn't work for us either as we
>>>> can
>>>> not store the data in an unencrypted form.
>>>>
>>>> Kind regards
>>>> Matthias
>>>>
>>>> On 10/12/2011 07:42 PM, Stephen Connolly wrote:
>>>>>
>>>>> could<mailto>
>>>>> <mailto<tel:219.384.5143>
>>>>>
>>>>> /A Smart Grid technology company focused on helping consumers
of
>>>>> energy
>>>>> control an often under-managed resource./
>>>>>
>>>>>
>>>>>
>>>>
>>>>
>>
>> | http://mail-archives.apache.org/mod_mbox/incubator-cassandra-user/201110.mbox/%3C4E97173D.1050408@l3s.de%3E | CC-MAIN-2017-26 | refinedweb | 540 | 70.33 |
Are you sure?
This action might not be possible to undo. Are you sure you want to continue?
Cat. No. 64265X
Contents
What’s New . . . . . . . . . . . . . . . . . . . . . Reminder . . . . . . . . . . . . . . . . . . . . . . Introduction . . . . . . . . . . . . . . . . . . . . . Passive Activity Limits . . . . . . . Who Must Use These Rules? . Passive Activities . . . . . . . . . Activities That Are Not Passive Activities . . . . . . . . . . . . Passive Activity Income and Deductions . . . . . . . . . . Grouping Your Activities . . . . Recharacterization of Passive Income . . . . . . . . . . . . . Dispositions . . . . . . . . . . . . How To Report Your Passive Activity Loss . . . . . . . . . ...... ...... ...... ...... ...... ...... ...... ...... 1 1 2 2 2 2 4 5 7 8 9
Department of the Treasury Internal Revenue Service
Passive Activity and At-Risk Rules
For use in preparing
2004 Returns
. . . . . . 10
Comprehensive Example . . . . . . . . . . . 10 At-Risk Limits . . . . . . . . . . . . . . . Who Is Affected? . . . . . . . . . . . Activities Covered by the At-Risk Rules . . . . . . . . . . . . . . . . At-Risk Amounts . . . . . . . . . . . Amounts Not At Risk . . . . . . . . Reductions of Amounts At Risk . . Recapture Rule . . . . . . . . . . . . . . . . 21 . . . . 21 . . . . . . . . . . . . . . . . . . . . 21 22 23 23 23
How To Get Tax Help . . . . . . . . . . . . . . 24 Index . . . . . . . . . . . . . . . . . . . . . . . . . . 26
What’s New
Definition of at-risk amounts expanded. The following rules apply to amounts borrowed after May 3, 2004.
• You must file Form 6198 if you are engaged in an activity included in (6) under Activities Covered by the At-Risk Rules and you have borrowed certain amounts described in Certain borrowed amounts excluded under At-Risk Amounts in this publication.
• You may be considered at risk for certain
amounts described in Certain borrowed amounts excluded under At-Risk Amounts secured by real property used in the activity of holding real property (other than mineral property) that, if nonrecourse, would be qualified nonrecourse financing.
Reminder
Get forms and other information faster and easier by: Internet • FAX • 703–368–9694 (from your fax machine). Comments and suggestions.
Passive Activity Limits. Before applying this limit on passive activity losses, you must first deterCAUTION mine the amount of your loss disallowed under the at-risk rules explained in the second part of this publication.
ing definitions and how the passive activity rules apply to these corporations, see Form 8810 and its instructions. Closely held corporation. questions. If you have a tax question, visit or call 1-800-829-1040. We cannot answer tax questions at either of the addresses listed above. Ordering forms and publications. Visit to download forms and publications, call 1-800-829-3676, or write to one of the three addresses shown under How To Get Tax Help in the back of this publication.
Passive activity credits..
Passive Activities
There are two kinds of passive activities.
• Trade or business activities in which you
do not materially participate during the year.
• Rental activities, even if you do materially
participate in them, unless you are a real estate professional. Material participation in a trade or business is discussed later, under Activities That Are Not Passive Activities. Treatment of former).
Useful Items
You may want to see: Publication ❏ 527 Residential Rental Property (Including Rental of Vacation Homes) Partnerships
Trade or Business Activities
A trade or business activity is an activity that:
• Involves the conduct of a trade or business (that is, deductions would be allowable under section 162 of the Internal Revenue Code if other limitations, such as the passive activity rules, did not apply),
❏ 541
Who Must Use These Rules?
The passive activity rules apply to:
Form (and Instructions) ❏ 4952 Investment Interest Expense Deduction ❏ 6198 At-Risk Limitations ❏ 8582 Passive Activity Loss Limitations ❏ 8582-CR Passive Activity Credit Limitations ❏ 8810 Corporate Passive Activity Loss and Credit Limitations See How To Get Tax Help near the end of this publication for information about getting these publications and forms. Page 2
• Is conducted in anticipation of starting a
trade or business, or
• • • • •
Individuals, Estates, Trusts (other than grantor trusts), Personal service corporations, and Closely held corporations.
•.
Even though the rules do not apply to grantor trusts, partnerships, and S corporations directly, they do apply to the owners of these entities. For information about personal service corporations and closely held corporations, includ-
Rental Activities. Exceptions. Your activity is not a rental activity if any of the following apply. 1.. 2. do not include the following. a. Services needed to permit the lawful use of the property, b. Services to repair or improve property that would extend its useful life for a period substantially longer than the average rental, and c. Services that are similar to those commonly provided with long-term rentals of real estate, such as cleaning and maintenance of common areas or routine repairs. 3. You provide extraordinary personal services in making the rental property available for customer use. Services are extraordinary personal services if they are performed by individuals and the customers’ use of the property is incidental to their receipt of the services.. a. You own an interest in the trade or business activity during the year. b. The rental property was used mainly in that trade or business activity during the current year, or during at least 2 of the 5 preceding tax years. c.. 5. You customarily make the rental property available during defined business hours for nonexclusive use by various customers. 6..
Commercial revitalization deduction.:
TIP
• 2 years after the decedent’s death if no
estate tax return is required, or
Special $25,000 allowance..).
• 6 months after the estate tax liability is
finally determined if an estate tax return is required.. Example. Mike, a single taxpayer, had the following income and loss during the tax year: Salary . . . Dividends . Interest . . Rental loss . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $42,300 . 300 . 1,400 . (4,000) Page 3
loss to offset his other income because he actively participated. Phaseout rule..
Minus required reduction (see above) Adjusted special allowance . . . . . . Passive loss from rental real estate Deduction allowable/Adjusted special allowance (see above) . . . . Amount that must be carried forward
10,000 $15,000 $31,000 15,000 $16,000
the year, some of your income and deductions from the working interest may be treated as passive activity gross income and passive activity deductions. See Temporary Regulations section 1.469-1T(e)(4)(ii). 3. The rental of a dwelling unit that you also used for personal purposes during the year for more than the greater of 14 days or 10% of the number of days during the year that the home was rented at a fair rental. 4. An activity of trading personal property for the account of those who own interests in the activity. See Temporary Regulations section 1.469-1T(e)(6). 5. Rental real estate activities in which you materially participated as a real estate professional. See Real Estate Professional, later. You should not enter income and losses from these activities on Form CAUTION 8582. Instead, enter them on the forms or schedules you would normally use.
• Taxable social security and tier 1 railroad
retirement benefits.
• Deductible contributions to individual retirement accounts (IRAs) and section 501(c)(18) pension plans.
• The exclusion from income of interest from
qualified U.S. savings bonds used to pay qualified higher education expenses.
• The exclusion from income of amounts received from an employer’s adoption assistance program.
• Passive activity income or loss included
on Form 8582.
Exceptions to the phaseout rules. par t ner sh i p , S c o r p o r a t i o n , o r o t h e r pass-through entity, the special exception for the low-income housing credit will not apply unless you also acquired your interest in the pass-through entity after 1989. Ordering rules. If you have more than one of the exceptions to the phaseout rules in the same tax year, you must apply the $25,000 phaseout against your passive activity losses and credits in the following order. 1. The portion of passive activity losses not attributable to the commercial revitalization deduction. 2. The portion of passive activity losses attributable to the commercial revitalization deduction. 3. The portion of passive activity credits attributable to credits other than the rehabilitation and low-income housing credits. 4. The portion of passive activity credits attributable to the rehabilitation credit and low-income housing credit for property placed in service prior to 1990. 5. The portion of passive activity credits attributable to the low-income housing credit for property placed in service after 1989.
!
Material Participation
A trade or business activity is not a passive activity if you materially participated in the activity.
• Any rental real estate loss allowed because you materially participated in the rental activity as a real estate professional (as discussed later, under Activities That Are Not Passive Activities).
• Any overall loss from a publicly traded
partnership (see Publicly Traded Partnerships (PTPs) in the instructions for Form 8582).
• The deduction for one-half of self-employment tax.
• The deduction allowed for interest on student loans.
• The deduction for qualified tuition and related expenses.: Adjusted gross income, modified as required . . . . . . . . . . . . . . . . . . . $120,000 Minus amount not subject to phaseout . . . . . . . . . . . . . . . . . . Amount subject to phaseout rule . . . Multiply by 50% . . . . . . . . . . . . . . Required reduction to special allowance . . . . . . . . . . . . . . . . . . Maximum special allowance . . . . . Page 4 100,000 $20,000 × 50% $10,000 $25,000
Activities That Are Not Passive Activities
The following are not passive activities. 1. Trade or business activities in which you materially participated for the tax year. 2. well for
other trade or business in which capital is not a material income-producing factor. 7. Based on all). Retired or disabled farmer and surviving spouse of a farmer.. Corporations..
• Any person other than you received compensation for managing the activity, or
• Any individual spent more hours during
the tax year managing the activity than you did (regardless of whether the individual was compensated for the management services). Participation. In general, any work you do in connection with an activity in which you own an interest is treated as participation in the activity. Work not usually performed by owners. You do not treat the work you do in connection with an activity as participation in the activity if both of the following are true.
• • • • • • •
Develops or redevelops it. Constructs or reconstructs it. Acquires it. Converts it. Rents or leases it. Operates or manages it. Brokers it.
• The work is not work that is customarily
done by the owner of that type of activity.
Closely held corporations. A closely held corporation can qualify as a real estate professional if more than 50% of the gross receipts for its tax year came from real property trades or businesses in which it materially participated.
• One of your main reasons for doing the
work is to avoid the disallowance of any loss or credit from the activity under the passive activity rules. Participation as an investor. You do not treat the work you do in your capacity as an investor in an activity as participation unless you are directly involved in the day-to-day management or operations of the activity. Work you do as an investor includes:
Passive Activity Income and Deductions
In figuring your net income or loss from a passive activity, take into account only passive activity income and passive activity deductions. Self-charged interest..
Real Estate Professional. Qualifications. You qualified as a real estate professional for the year if you met both of the following requirements.
• Studying and reviewing financial statements or reports on operations of the activity,
• Preparing or compiling summaries or analyses of the finances or operations of the activity for your own use, and
• Monitoring the finances or operations of
the activity in a nonmanagerial capacity. Spouse’s participation. RECORDS. Limited partners. If you owned an activity as a limited partner, you generally are not treated as materially participating in the activity. However, you are treated as materially participating in the activity if you met test (1), (5), or (6) under
• More than half of the personal services
you performed in all trades or businesses during the tax year were performed in real property trades or businesses in which you materially participated.
Passive Activity Income
Passive activity income includes all income from passive activities and generally includes gain from disposition of an interest in a passive activity or property used in a passive activity. Passive activity income does not include the following items.
• You performed more than 750 hours of
services during the tax year in real property trades or businesses in which you materially participated. Do not count personal services you performed as an employee in real property trades or businesses unless you were a 5% owner of your employer. You were a 5% owner if you owned
• Income from an activity that is not a passive activity. These activities are disPage 5
cussed under Activities That Are Not Passive Activities, earlier.
•.
Disposition of property interests.. Exception for more than one use in the preceding 12 months.:
plies only if you meet all of the following conditions.
• At the time of disposition, you held your
interest in the property in a dealing activity (an activity that involves holding the property or similar property mainly for sale to customers in the ordinary course of a trade or business).
• Your other activities included a nondealing
activity (an activity that does not involve holding similar property for sale to customers in the ordinary course of a trade or business) in which you used the property for more than 80% of the period you held it.
• Personal service income. This includes
salaries, wages, commissions, self-employment income from trade or business activities in which you materially participated, deferred compensation, taxable social security and other retirement benefits, and payments from partnerships to partners for personal services.
• You did not acquire or hold your interest in
the property for the main purpose of selling it to customers in the ordinary course of a trade or business.
Passive Activity Deductions.
• Income from positive section 481 adjustments allocated to activities other than passive activities. (Section 481 adjustments are adjustments that must be made due to changes in your accounting method.)
• $10,000, or • 10% of the total of the fair market value of
your interest in the property and the fair market value of all other property used in that activity immediately before the disposition. Exception for substantially appreciated property. The gain is passive activity income if the fair market value of the property at disposition was more than 120% of its adjusted basis and either of the following conditions applies.
• Income or gain from investments of working capital.
•.
• Deductions for expenses (other than interest expense) that are clearly and directly allocable to portfolio income.
• You used the property in a passive activity
for 20% of the time you held your interest in the property.
• Qualified home mortgage interest, capitalized interest expenses, and other interest expenses (other than self-charged interest) properly allocable to passive activities. For more information on self-charged interest, see Self-charged interest under Passive Activity Income and Deductions, earlier.
• Any income from intangible property, such
as a patent, copyright, or literary, musical, or artistic composition, if your personal efforts significantly contributed to the creation of the property.
• You used the property in a passive activity
for the entire 24-month period before its disposition. If neither condition applies, the gain is not passive activity income. However, it. Disposition of property converted to inventory. ap-
• Any other income that must be treated as
nonpassive income. See Recharacterization of Passive Income, later.
• Losses from dispositions of property that
produce portfolio income or property held for investment.
• Overall gain from any interest in a publicly
traded partnership. See Publicly Traded Partnerships (PTPs) in the instructions for Form 8582.
• State, local, and foreign income taxes. • Miscellaneous itemized deductions that
may be disallowed because of the 2%-of-adjusted-gross-income limit.
• State, local, and foreign income tax refunds.
• Income from a covenant not to compete. • Reimbursement of a casualty or theft loss
included in gross income to recover all or part of a prior year loss deduction, if the loss deduction was not a passive activity deduction.
• Charitable contribution deductions. • Net operating loss deductions. • Percentage depletion carryovers for oil
and gas wells.
• Capital loss carrybacks and carryovers. • Deductions and losses that would have
been allowed for tax years beginning before 1987 but for basis or at-risk limits.
• Alaska Permanent Fund dividends. • Cancellation of debt income, if at the time
the debt is discharged the debt is not allocated to passive activities under the interest expense allocation rules. See chapter 5 of Publication 535, Business Expenses, for information about the rules for allocating interest. Page 6
• Net negative section 481 adjustments allocated to activities other than passive activities. (Section 481 adjustments are adjustments required due to changes in accounting methods.)
• Casualty and theft losses, unless losses
similar in cause and severity recur regularly in the activity.
• The deduction for one-half of self-employment tax.
• A movie theater activity and a bakery activity,
rental and Healthy Food’s grocery business into a single trade or business activity. Grouping of real and personal property rentals.. Certain activities may not be grouped. In general, if you own an interest as a limited partner or a limited entrepreneur in one of the following activities, you may not group that activity with any other activity in another type of business.
• A Baltimore activity and a Philadelphia ac-.
tivity, or
• Four separate activities.
Example 2.. Consistency and disclosure requirement.. Regrouping by the IRS. If any of the activities resulting from your grouping is not an appropriate economic unit and one of the primary purposes of your grouping (or failure to regroup) is to avoid the passive activity rules, the IRS may regroup your activities. Rental activities. In general, you cannot group a rental activity with a trade or business activity. However, you can group them together if the activities form an appropriate economic unit and:
• Holding, producing, or distributing motion
picture films or video tapes.
• Farming. • Leasing any section 1245 property (as defined in section 1245(a)(3) of the Internal Revenue Code). For a list of section 1245 property, see Section 1245 property under Activities Covered by the At-Risk Rules, later.
• Exploring for, or exploiting, oil and gas resources.: 1. The similarities and differences in the types of trades or businesses, 2. The extent of common control, 3. The extent of common ownership, 4. The geographical location, and 5. The interdependencies between or among activities, which may include the extent to which the activities: a. Buy or sell goods between or among themselves, b. Involve products or services that are generally provided together, c. Have the same customers, d. Have the same employees, or e. Use a single set of books and records to account for the activities. Example:
•. Limited entrepreneur. neur is a person who: A limited entrepre-
• Has an interest in an enterprise other than
as a limited partner, and
• The rental activity is insubstantial in relation to the trade or business activity,
• Does not actively participate in the management of the enterprise. Activities conducted through another entity. A personal service corporation, closely held corporation, partnership, or S corporation must group its activities using the rules discussed in this section. Once the entity groups its activities, you, as the partner or shareholder of the entity, may group those activities (following the rules of this section):
• The trade or business activity is insubstantial in relation to the rental activity, or
•. Example.
• With each other, • With activities conducted directly by you,
or
• With activities conducted through other
entities. You may not treat activities grouped together by the entity as separate activities.
CAUTION
!
• One activity,
Personal service and closely held corporations. You may group an activity conducted through a personal service or closely held corporation with your other activities only to determine whether you materially or significantly participated in those other activities. See Material Participation, earlier, and Significant Participation Passive Activities, later. Page 7
Worksheet A. Significant Participation Passive Activities
Name of activity (a) Hours of participation ( ( ( ( ( ( ( Totals ( (b) Net loss ) ) ) ) ) ) ) ) (c) Net income
Keep for Your Records (d) Combine totals of cols. (b) and (c) ///////////////////////////////////////// ///////////////////////////////////////// ///////////////////////////////////////// ///////////////////////////////////////// ///////////////////////////////////////// ///////////////////////////////////////// /////////////////////////////////////////
Publicly traded partnership (PTP). You may not group activities conducted through a PTP with any other activity, including an activity conducted through another PTP. Partial dispositions. If you dispose of substantially all of an activity during your tax year, you may treat the part disposed of as a separate activity. However, you can do this only if you can show with reasonable certainty:
pation Passive Activities, later, if the activity is a significant participation passive activity and you also have a net loss from a different significant participation passive activity. Limit on recharacterized passive income.. Investment income and investment expense. To figure your investment interest expense limitation on Form 4952, treat as investment income any net passive income recharacterized as nonpassive income from rental of nondepreciable property, equity-financed lending activity, or licensing of intangible property by a pass-through entity.
• The amount of deductions and credits disallowed in prior years under the passive activity rules that is allocable to the part of the activity disposed of, and
Column . Column (b). Enter the net loss, if any, from the activity. Net loss from an activity means either:
• The amount of gross income and any
other deductions and credits for the current tax year that is allocable to the part of the activity disposed of.
• The activity’s current year net loss (if any)
plus prior year unallowed losses (if any), or
• The excess of prior year unallowed losses
over the current year net income (if any). Enter -0- here if the prior year unallowed loss is the same as the current year net income. Column (c). Enter net income, if any, from the activity. Net income means the excess of the current year’s net income from the activity over any prior year unallowed losses from the activity. Column (d).. Worksheet B. List only the significant participation passive activities that have net income as shown in column (c) of Worksheet A. Column (a). Enter the net income of each activity from column (c) of Worksheet A. Column (b). Divide each of the individual net income amounts in column (a) by the total of
Recharacterization of Passive Income
Net income from the following passive activities may have to be recharacterized and excluded from passive activity income.
Significant Participation Passive Activities. Corporations. An activity of a personal service corporation or closely held corporation is a significant participation passive activity if both of the following statements are true.
• Significant participation passive activities, • Rental of property when less than 30% of
the unadjusted basis of the property is subject to depreciation,
• Equity-financed lending activities, • Rental of property incidental to development activities,
• Rental of property to nonpassive activities,
and
• Licensing of intangible property by
pass-through entities. If you ParticiPage 8
• The corporation is not treated as materially participating in the activity for the year.
• One or more individuals, each of whom is
treated as significantly participating in the activity, directly or indirectly hold (in total) more than 50% (by value) of the corporation’s outstanding stock. Worksheet A. Complete Worksheet A, Significant Participation Passive Activities, if you have income or losses from any significant participation activity. Begin by entering the name of each activity in the left column.
Worksheet B. Significant Participation Activities With Net Income
Name of activity with net income (b) Ratio See instructions (c) Nonpassive income See instructions
Keep for Your Records (d) Passive income Subtract col. (c) from col. (a)
(a) Net income
Totals
1.000
column (a). The result is a ratio. In column (b), enter the ratio for each activity as a decimal (rounded to at least three places). The total of these ratios must equal 1.000. Column (c). Multiply the amount in the Totals row of column (d) of Worksheet A by each of the ratios in column (b). Enter the results in column (c). Column .)
Rental of Property Incidental to a Development Activity
Net passive income from this type of activity will be treated as nonpassive income if all of the following apply.
This recharacterization rule does not apply if: 1. The expenses reasonably incurred by the entity in developing or marketing the property exceed 50% of the gross royalties from licensing the property that are includible in your gross income for the tax year, or.
• You recognize gain from the sale, exchange, or other disposition of the rental property during the tax year.
• You started to rent the property less than
12 months before the date of disposition.
• 1.469-2(f)(5) of the regulations. section. Example..
Dispositions activCAUTION ity, the loss may be limited by the capital loss rules. The limit is generally $3,000 for individuals ($1,500 in the case of married individuals filing separate returns). See Publication 544, Sales and Other Dispositions of Assets, for more information.
Rental of Property to a Nonpassive Activity.
Equity-Financed Lending Activities
If you have gross income from an equity-financed lending activity, the lesser of the net passive income or the equity-financed interest income is nonpassive income. For more information, see Temporary Regulations section 1.469-2T(f)(4).
Example..
Page 9
Ray’s deductible loss for 2004 is $5,000, figured as follows: Sales price . . . . . . . . . . . . . . . . . . $30,000 Minus: adjusted basis . . . . . . . . . . . Minus: capital loss limit . . . . . . . . . . Capital loss carryover . . . . . . . . . . . Allowable capital loss on sale . . . . . . Carryover losses allowable . . . . . . . Total current deductible loss . . . . . . 42,000 3,000 $9,000 $3,000 2,000 $5,000 Capital loss . . . . . . . . . . . . . . . . . . $12,000). Partial dispositions. If you dispose of substantially all of an activity during your tax year, you may treat the part of the activity disposed of as a separate activity. See Partial dispositions under Grouping Your Activities, earlier.
show a loss from operations of $15,000 in 2004. Their records also show a gain of $2,776 from the sale in January 2004 of section 1231 assets used in the activity. The section 1231 gain is reported in Part I of Form 4797 and is identified as being from a passive activity (FPA). For 2003, they completed the worksheets for Form 8582 and calculated that $6,667 of Activity A’s Schedule E loss for 2003 was disallowed by the passive activity rules. That loss is carried over to 2004 as a prior year unallowed loss and will be used to figure the allowed loss for 2004. 2. Activity B is a rental real estate activity. Its income and expenses are reported on Schedule E. Charles and Lily’s records show a loss from operations of $11,600 in 2004. For 2003, they completed the worksheets for Form 8582 and calculated that $8,225 of Activity B’s Schedule E loss for 2003 was disallowed by the passive activity rules. That loss is carried over to 2004 as a prior year unallowed loss and will be used to figure the allowed loss for 2004. 3. Partnership #1 is a trade or business activity and is not a publicly traded partnership (PTP). Partnership #1 reports a $4,000 distributive share of its 2004 profits to Charles and Lily in box 1 of Schedule K-1 (Form 1065). They report that profit on Schedule E. For 2003, they completed the worksheets for Form 8582 and calculated that $2,600 of their distributive share of the loss from Partnership #1 in 2003 was disallowed by the passive activity rules. That loss is carried over to 2004 as a prior year unallowed loss and will be used to figure the allowed loss for 2004. 4. Partnership #2 is a trade or business activity and also a PTP. In December 2004) that they report on Schedule D. The partnership reports a $1,200 distributive share of its 2004 losses to them in box 1 of Schedule K-1 (Form 1065). They report that loss on Schedule E. For 2003, they followed the instructions for Form 8582 and calculated that $2,445 of their distributive share of Partnership #2’s 2003 loss was disallowed by the passive activity rules. That loss is carried over from 2003 and reported on Schedule E loss for 2004. (For discussion of PTPs, see the instructions for Form 8582.) 5. Partnership #3 is a single trade or business activity and is not a PTP. Charles and Lily sold their entire interest in Partnership #3 in November 2004. To indicate they made an entire disposition of a passive activity, they enter EDPA on the appropriate lines. They recognize a $4,000 ($15,000 selling price minus $11,000 adjusted basis) long-term capital gain, which they report on Schedule D. For 2003, they completed the worksheets for Form 8582 and calculated that $3,000 of
Ray deducts the $5,000 total current deductible loss in 2004. He must carry over the remaining $9,000 capital loss, which is not subject to the passive activity loss limit. He will treat it like any other capital loss carryover. Installment sale of an entire interest.. Partners and S corporation shareholders.. Dispositions by gift. If you give away your interest in a passive activity, the unused passive activity losses allocable to the interest cannot be deducted in any tax year. Instead, the basis of the transferred interest must be increased by the amount of these losses. Dispositions by death. Page 10
How To Report Your Passive Activity Loss
More than one form or schedule may be required for reporting your passive activities. The actual number of forms depends on the number and types of activities you must report. Some forms and schedules that may be required are:
• Schedule C (Form 1040), Profit or Loss
From Business,
• Schedule D (Form 1040), Capital Gains
and Losses,
• Schedule E (Form 1040), Supplemental
Income and Loss,
• Schedule F (Form 1040), Profit or Loss
From Farming,
• Form 4797, Sales of Business Property, • Form 6252, Installment Sale Income, • Form 8582, Passive Activity Loss Limitations, and
• Form 8582-CR, Passive Activity Credit
Limitations. Regardless of the number or complexity of passive activities you have, you should use only one Form 8582.
Comprehensive Example
The following example shows how to report your passive activities. In addition to Form 1040, Charles and Lily Woods use Form 8582 (to figure allowed passive activity deductions), Schedule E (to report rental activities and partnership activities), Form 4797 (to figure the gain and allowable loss from assets sold that were used in the activities), and Schedule D (to report the sale of partnership interests).
General Information
Charles and Lily are married, file a joint return, and have combined wages of $132,000 in 2004. They own interests in the activities listed below. They are at risk for their investment in the activities. They did not materially participate in any of the business activities. They actively participated in the rental real estate activities in 2004 and all prior years. Charles and Lily are not real estate professionals. 1. Activity A is a rental real estate activity. The income and expenses are reported on Schedule E. Charles and Lily’s records
their distributive share of the partnership’s loss for 2003 was disallowed by the passive activity rules. That loss is carried over to 2004 as a prior year unallowed Schedule E loss. Charles and Lily’s distributive share of partnership losses for 2004 reported in box 1 of Schedule K-1 (Form 1065) is $6,000. 6. Partnership #4 is a trade or business activity that is a limited partnership. Charles and Lily are limited partners who did not meet any of the material participation tests. Their distributive share of 2004 partnership loss, reported in box 1 of Schedule K-1 (Form 1065), is $2,400. For 2003 they completed the worksheets for Form 8582 and calculated that $1,500 of their distributive share of loss for 2003 was disallowed by the passive activity rules. That loss is carried over to 2004 as a prior year unallowed loss and will be used to figure the allowed loss for 2004.. 1. They write “Activity A” on the first line under “Name of activity.” Then they enter: a. $2,776 gain in column (a) from Form 4797, line 2, column (g), b. ($15,000) loss in column (b) from Schedule E, line 22, column A, and c. ($6,667) prior year unallowed loss in column (c) from their 2003 worksheets. They combine the three amounts. The result, ($18,891), is an overall loss so they enter it in column (e). 2. Charles and Lily write “Activity B” on the second line under “Name of activity.” Then they enter: a. ($11,600) loss in column (b) from Schedule E, line 22, column B, and b. ($8,225) prior year unallowed loss in column (c) from their 2003 worksheets. Then they combine these two figures and enter the total loss, ($19,825), in column (e). 3. They separately add the amounts in columns (a), (b), and (c). a. They enter $2,776 in column (a) on the Total line and also on Form 8582, Part I, line 1a. b. They enter ($26,600) in column (b) on the Total line and also on Form 8582, Part I, line 1b. c. They enter ($14,892) in column (c) on the Total line and also on Form 8582, Part I, line 1c. 4. They combine lines 1a, 1b, and 1c, Form 8582, and put the net loss, ($38,716), on line 1d. Worksheet 3.. Reporting income from column (d), Worksheets 1 and 3..
for their net losses from real estate activities with active participation (Activities A and B). They enter all amounts as though they were positive (without brackets around losses). They then complete Form 8582, Part IV.
• They enter $38,716 on line 5 since this is
the smaller of the loss on line 1d or the loss on line 4.
• They enter $150,000 on line 6 since they
are married and filing a joint return.
• They enter $138,655, their modified adjusted gross income, on line 7. (See page 3 for discussion of modified adjusted gross income.) 2004 loss of $1,200 with its prior year loss of $2,445, and combined the Partnership #3 2004 loss of $6,000 with its prior year.
Step One —Completing the Tax Forms Before Figuring the Passive Activity Loss Limits
Charles and Lily complete the forms they usually use to report income or expenses from their activities. They enter their combined wages, $132,000, on Form 1040. They complete Schedule D, line 8, showing long-term capital gains of $15,300 from the disposition of Partnership #2 and $4,000 from the disposition of Partnership also combine the Partnership #3 $6,000 current year loss with its $3,000 prior year loss, and enter the two combined amounts in column (f) on Schedule E, Part II, line 28..
• They subtract line 7 from line 6 and enter
the result, $11,345, on line 8.
• They multiply line 8 by 50% and enter the
result, $5,673, on line 9. No matter what the result, they cannot enter more than $25,000 on line 9.
• They enter the smaller of line 5 or line 9,
$5,673, on line 10.
• They add the income on lines 1a and 3a
and enter the result, $6,776, on line 15.
• They add lines 10 and 15 and enter the
result, $12,449, on line 16.
Step Four —Completing Worksheet 4.
• In the two left columns, they write the
name of each activity, A and B, and the schedule and line number on which each activity is reported.
Step Two .) Worksheet 1. Worksheet 1 is for rental real estate activities with active participation. Charles and Lily enter the gains and losses from
• They fill in column (a) with the losses from
Worksheet 1, column (e). They add up the amounts, and enter the result, $38,716, in the Total line without brackets.
• They figure the ratios for column (b) by
dividing each amount in column (a) by the amount on the column (a) Total line. They enter each result in column (b). The total of the ratios must equal 1.00.
Step Three —Completing Form 8582
Next, Charles and Lily complete Form 8582, Part II, to determine the amount they can deduct
• They multiply the amount from line 10,
Form 8582, $5,673, by each of the ratios Page 11
in Worksheet 4, column (b) and enter the results on the appropriate line in column (c). The total must equal $5,673.
Form 8582, $41,216, as a positive number. b. On line B, they enter the amount from line 10 of Form 8582, $5,673. c..
• They subtract column (c) from column (a)
and enter each result in column (d).
year loss plus the prior year unallowed loss. They find these amounts by adding columns (b) and (c) on Worksheets 1 and 3.
• In column (b), they enter the unallowed
loss for each activity already figured in Worksheet 5, column (c). They must save this information to use next year in figuring their passive losses.
Step Five —Completing Worksheet 5. 1. In column (a), they enter the losses from Worksheet 3, column (e) and Worksheet 4, column (d). These losses are entered as positive numbers, not in brackets. They add the numbers and enter the total, $36,943, on the Total line. 2. They divide each of the losses in column (a) by the amount on the column (a) Total line, and enter each result in column (b). The ratios must total 1.00. 3. Now they use the computation worksheet for column (c) (see the worksheet in the instructions for Form 8582) to figure the unallowed loss to allocate in column (c). a. On line A of the computation worksheet, they enter the amount from line 4 of
• In column (c), they figure their allowed
losses for 2004 by subtracting their unallowed losses, column (b), from their total losses, column (a). These allowed losses are entered on the appropriate schedules. Reporting allowed losses. Charles and Lily enter their allowed losses from Activities A and B on Schedule E, Part I, line 23, because these are rental properties. They report their allowed loss from Partnership #4 on Schedule E, Part II, line 28D.
Step Six —Using Worksheets 6 and 7. Worksheet 6. They complete Worksheet 6 with the activities from Worksheet 5.
Step Seven —Finishing the Reporting of the Passive Activities
Charles and Lily summarize the entries on Schedule E, Schedule D, and Form 4797, and enter the amounts on the appropriate lines of their Form 1040. They enter:
• The total Schedule D gain, $22,076, on
line 13a, and
• The Schedule E loss, ($21,094), on line
17. Charles and Lily are now able to complete their tax return, having correctly limited their losses from their passive activities.
• They write the name of each activity and
the schedule and line number to be used in the two left columns of Worksheet 6.
• In column (a), they enter the total loss for
each activity. This includes the current
Page 12
1040
L A B E L H E R E
Form
Department of the Treasury—Internal Revenue Service
U.S. Individual Income Tax Return
For the year Jan. 1–Dec. 31, 2004, or other tax year beginning Your first name and initial
2004
Woods Woods
(99)
IRS Use Only—Do not write or staple in this space.
, 2004, ending
, 20
Label
(See instructions on page 16.) Use the IRS label. Otherwise, please print or type.
OMB No. 1545-0074 Your social security number
Charles
If a joint return, spouse’s first name and initial Last name
123 567
Apt. no.
00 00
4567 1234
Spouse’s social security number
Lily 6925 Country Road
Home address (number and street). If you have a P.O. box, see page 16.
Important!
You must enter your SSN(s) above. You Yes No Spouse Yes No
City, town or post office, state, and ZIP code. If you have a foreign address, see page 16.
Presidential Election Campaign
(See page 16.) 1 2 3
Anytown, VA 22306
Note. Checking “Yes” will not change your tax or reduce your refund. Do you, or your spouse if filing a joint return, want $3 to go to this fund? Single Married filing jointly (even if only one had income) Married filing separately. Enter spouse’s SSN above and full name here. 5 4
Filing Status
Check only one box.
Head of household (with qualifying person). (See page 17.) If the qualifying person is a child but not your dependent, enter this child’s name here. Qualifying widow(er) with dependent child (see page 17)
Boxes checked on 6a and 6b No. of children on 6c who: ● lived with you ● did not live with you due to divorce or separation (see page 18) Dependents on 6c not entered above Add numbers on lines above
Exemptions
6a Yourself. If someone can claim you as a dependent, do not check box 6a b Spouse (4) if qualifying (3) Dependent’s c Dependents: (2) Dependent’s
(1) First name Last name social security number relationship to you
2
child for child tax credit (see page 18)
If more than four dependents, see page 18. d Total number of exemptions claimed
2
Income
Attach Form(s) W-2 here. Also attach Forms W-2G and 1099-R if tax was withheld.
7 Wages, salaries, tips, etc. Attach Form(s) W-2 8a Taxable interest. Attach Schedule B if required b Tax-exempt interest. Do not include on line 8a 9a Ordinary dividends. Attach Schedule B if required b Qualified dividends (see page 20) 10 11 12 13 Alimony received Business income or (loss). Attach Schedule C or C-EZ Capital gain or (loss). Attach Schedule D if required. If not required, check here Other gains or (losses). Attach Form 4797 15a IRA distributions Pensions and annuities 16a b Taxable amount (see page 22) b Taxable amount (see page 22) 8b
7 8a 9a 9b 10 11 12 13 14 15b 16b 17 18 19 20b 21 22
132,000
Taxable refunds, credits, or offsets of state and local income taxes (see page 20)
22,076
If you did not get a W-2, see page 19. Enclose, but do not attach, any payment. Also, please use Form 1040-V.
14 15a 16a 17 18 19 20a 21 22 23 24 25 26 27 28 29 30 31 32 33 34a 35 36
Rental real estate, royalties, partnerships, S corporations, trusts, etc. Attach Schedule E Farm income or (loss). Attach Schedule F Unemployment compensation 20a b Taxable amount (see page 24) Social security benefits Other income. List type and amount (see page 24) Add the amounts in the far right column for lines 7 through 21. This is your total income Educator expenses (see page 26) Certain business expenses of reservists, performing artists, and fee-basis government officials. Attach Form 2106 or 2106-EZ IRA deduction (see page 26) Student loan interest deduction (see page 28) Tuition and fees deduction (see page 29) Health savings account deduction. Attach Form 8889 Moving expenses. Attach Form 3903 One-half of self-employment tax. Attach Schedule SE Self-employed health insurance deduction (see page 30) Self-employed SEP, SIMPLE, and qualified plans Penalty on early withdrawal of savings 23 24 25 26 27 28 29 30 31 32 33 34a
(21,094)
132,982
Adjusted Gross Income
Alimony paid b Recipient’s SSN Add lines 23 through 34a Subtract line 35 from line 22. This is your adjusted gross income
Cat. No. 11320B
35 36
Form
For Disclosure, Privacy Act, and Paperwork Reduction Act Notice, see page 75.
132,982 1040
(2004)
Page 13
SCHEDULE D (Form 1040)
Department of the Treasury (99) Internal Revenue Service
Capital Gains and Losses
Attach to Form 1040. See Instructions for Schedule D (Form 1040). Use Schedule D-1 to list additional transactions for lines 1 and 8.
OMB No. 1545-0074
Attachment Sequence No.
2004
12 00 4567
Name(s) shown on Form 1040
Your social security number
Charles and Lily Woods Part I Short-Term Capital Gains and Losses—Assets Held One Year or Less
(a) Description of property (Example: 100 sh. XYZ Co.) (b) Date acquired (Mo., day, yr.) (c) Date sold (Mo., day, yr.) (d) Sales price (see page D-6 of the instructions)
123
(e) Cost or other basis (see page D-6 of the instructions)
(f) Gain or (loss) Subtract (e) from (d)
1
2 3 4 5 6
Enter your short-term totals, if any, from Schedule D-1, 2 line 2 Total short-term sales price amounts. Add lines 1 and 2 in 3 column (d) Short-term gain from Form 6252 and short-term gain or (loss) from Forms 4684, 6781, and 8824 Net short-term gain or (loss) from partnerships, S corporations, estates, and trusts from Schedule(s) K-1 Short-term capital loss carryover. Enter the amount, if any, from line 8 of your Capital Loss Carryover Worksheet on page D-6 of the instructions Net short-term capital gain or (loss). Combine lines 1 through 6 in column (f)
4 5 6 7
( )
7
Part II
Long-Term Capital Gains and Losses—Assets Held More Than One Year
(a) Description of property (Example: 100 sh. XYZ Co.) (b) Date acquired (Mo., day, yr.) (c) Date sold (Mo., day, yr.) (d) Sales price (see page D-6 of the instructions) (e) Cost or other basis (see page D-6 of the instructions) (f) Gain or (loss) Subtract (e) from (d)
8
Partnership #2 EDPA Partnership #3 EDPA
12-2-91 12-15-92
12-4-04 11-18-04
25,300 15,000
10,000 11,000
15,300 4,000
9 10 11 12
Enter your long-term totals, if any, from Schedule D-1, line 9
9
40,300
Total long-term sales price amounts. Add lines 8 and 9 in 10 column (d) Gain from Form 4797, Part I; long-term gain from Forms 2439 and 6252; and long-term gain or (loss) from Forms 4684, 6781, and 8824 Net long-term gain or (loss) from partnerships, S corporations, estates, and trusts from Schedule(s) K-1 Capital gain distributions. See page D-1 of the instructions Long-term capital loss carryover. Enter the amount, if any, from line 13 of your Capital Loss Carryover Worksheet on page D-6 of the instructions Net long-term capital gain or (loss). Combine lines 8 through 14 in column (f). Then go to Part III on the back
Cat. No. 11338H
11 12 13 14 15 (
2,776
13 14 15
)
22,076
For Paperwork Reduction Act Notice, see Form 1040 instructions.
Schedule D (Form 1040) 2004
Page 14.
2004
13 00 4567
Name(s) shown on return
Your social security number
Part I
Note. If you are in the business of renting personal property, use Schedule C or C-EZ (see page E-3). Report farm rental income or loss from Form 4835 on page 2, line 40.
Charles and Lily Woods Income or Loss From Rental Real Estate and Royalties
123
1 List the type and location of each rental real estate property: A B C
Brick Duplex -Condo --
6924 -- 26 Country Road Anytown, VA 22306 6915 Country Road Anytown, VA 22306.)
25,000 600 1,500 1,200 2,000 1,000
8,300 210 525 420 700 390
3 4
33,300 Wages and Other (list)
9,000 700 600 2,000 2,400 9,000
8,510 245 210 700 840 3,150
12
17,510
salaries
18
19 Add lines 5 through 18
19
30,000
15,900
19 20
45,900 14,000
20 Depreciation expense or depletion 20 4,000 10,000 (see page E-4) 21 19,900 40,000 21 Total expenses. Add lines 19 and 20 22 Income or (loss) from rental real estate or royalty properties. Subtract line 21 from line 3 (rents) or line 4 (royalties). If the result is a (loss), see page E-4 to find out if (11,600) (15,000) 22 you must file Form 6198 23 Deductible rental real estate loss. Caution. Your rental real estate loss on line 22 may be limited. See page E-4 to find out if you must f i l e Form 8582. Real estate professionals must complete line 3,546 6,155 ) ( ) ( 23 ( 43 on page 2 24 Income. Add positive amounts shown on line 22. Do not include any losses 25 Losses. Add royalty losses from line 22 and rental real estate losses from line 23. Enter total losses here 26 Total rental real estate and royalty income or (loss). Combine lines 24 and 25. Enter the result here. If Parts II, III, IV, and line 40 on page 2 do not apply to you, also enter this amount on Form 1040, line 17. Otherwise, include this amount in the total on line 41 on page 2
For Paperwork Reduction Act Notice, see Form 1040 instructions.
Cat. No. 11344L
) 24 25 (
9,701
)
26
(9,701)
Schedule E (Form 1040) 2004
Page 15
Schedule E (Form 1040) 2004 Name(s) shown on return. Do not enter name and social security number if shown on other side.
Attachment Sequence No.
13 123 00
Page
2
Your social security number
Charles and Lily Woods
Caution. The IRS compares amounts reported on your tax return with amounts shown on Schedule(s) K-1.
4567
Part II
Income or Loss From Partnerships and S Corporations
Note. If you report a loss from an at-risk activity for which any amount is not at risk, you must check column (e) on-6 before completing this section. 28 A B C D
(a) Name (b) Enter P for partnership; S for S corporation (c) Check if foreign partnership (d) Employer identification number
Yes
No
(e) Check if any amount is not at risk
Partnership Partnership Partnership Partnership
#2 #3 #1 #4
(EDPA) (EDPA)
P P P P
(g) Passive income from Schedule K–1 (h) Nonpassive loss from Schedule K–1
10-1672810 10-9876243 10-5566650 10-7435837
Nonpassive Income and Loss
(i) Section 179 expense deduction from Form 4562 (j) Nonpassive income from Schedule K–1
Passive Income and Loss
(f) Passive loss allowed (attach Form 8582 if required)
PTP (3,645) A From (9,000) B (2,600) 4,000 C (148) D 4,000 29a Totals (15,393) b Totals 30 Add columns (g) and (j) of line 29a 31 Add columns (f), (h), and (i) of line 29b 32 Total partnership and S corporation income or (loss). Combine lines 30 and 31. Enter the result here and include in the total on line 41 below Part III
33 A B Passive Income and Loss
(c) Passive deduction or loss allowed (attach Form 8582 if required) (d) Passive income from Schedule K–1
30 31 ( 32
4,000 15,393 (11,393)
)
Income or Loss From Estates and Trusts
(a) Name (b) Employer identification number
Nonpassive Income and Loss
(e) Deduction or loss from Schedule K–1 (f) Other income from Schedule K–1
A B 34a b 35 36 37 Totals Totals Add columns (d) and (f) of line 34a Add columns (c) and (e) of line 34b Total estate and trust income or (loss). Combine lines 35 and 36. Enter the result here and include in the total on line 41 below
(a) Name (b) Employer identification number (c) Excess inclusion from Schedules Q, line 2c (see page E-6) (d) Taxable income (net loss) from Schedules Q, line 1b
35 36 ( 37
(e) Income from Schedules Q, line 3b
)
Part IV
38
Income or Loss From Real Estate Mortgage Investment Conduits (REMICs)—Residual Holder
39 Combine columns (d) and (e) only. Enter the result here and include in the total on line 41 below
39 40 41
Part V
Summary (21,094)
40 Net farm rental income or (loss) from Form 4835. Also, complete line 42 below 41 Total income or (loss). Combine lines 26, 32, 37, 39, and 40. Enter the result here and on Form 1040, line 17 42 Reconciliation of farming and fishing income. Enter your gross farming and fishing income reported on Form 4835, line 7; Schedule K-1 (Form 1065), box 14, code B; Schedule K-1 (Form 1120S), box 17, code N; and Schedule K-1 (Form 1041), line 14 (see page E-6) 43 Reconciliation for real estate professionals. If you were a real estate professional (see page E-1), enter the net income or (loss) you reported anywhere on Form 1040 from all rental real estate activities in which you materially participated under the passive activity loss rules
42
43
Schedule E (Form 1040) 2004
Page 16
Form
4797
Sales of Business Property
(Also Involuntary Conversions and Recapture Amounts Under Sections 179 and 280F(b)(2))
Attach to your tax return. See separate instructions.
OMB No. 1545-0184
2004
Attachment Sequence No. Identifying number
Department of the Treasury Internal Revenue Service (99)
27
Name(s) shown on return
Charles and Lily Woods
1
123-00-4567
1
Enter the gross proceeds from sales or exchanges reported to you for 2004 on Form(s) 1099-B or 1099-S (or substitute statement) that you are including on line 2, 10, or 20 (see instructions)
Part I
Sales or Exchanges of Property Used in a Trade or Business and Involuntary Conversions From Other Than Casualty or Theft—Most Property Held More Than 1 Year (see instructions)
(a) Description of property (b) Date acquired (mo., day, yr.) (c) Date sold (mo., day, yr.) (d) Gross sales price (e) Depreciation allowed or allowable since acquisition (f) Cost or other basis, plus improvements and expense of sale (g) Gain or (loss) Subtract (f) from the sum of (d) and (e)
2
FPA - Land from Activity A
1-4-91
1-5-04
6,000
3,224
2,776
3 4 5 6 7
Gain, if any, from Form 4684, line 39 Section 1231 gain from installment sales from Form 6252, line 26 or 37 Section 1231 gain or (loss) from like-kind exchanges from Form 8824 Gain, if any, from line 32, from other than casualty or theft Combine lines 2 through 6. Enter the gain or (loss) here and on the appropriate line as follows: Partnerships (except electing large partnerships) and S corporations. Report the gain or (loss) following the instructions for Form 1065, Schedule K, line 10, or Form 1120S, Schedule K, line 9. Skip lines 8, 9, 11, and 12 below. All others. If line 7 is zero or a loss, enter the amount from line 7 on line 11 below and skip lines 8 and 9. If line 7 is a gain and you did not have any prior year section 1231 losses, or they were recaptured in an earlier year, enter the gain from line 7 as a long-term capital gain on Schedule D and skip lines 8, 9, 11, and 12 below.
3 4 5 6 7
2,776
8 9
Nonrecaptured net section 1231 losses from prior years (see instructions) Subtract line 8 from line 7. If zero or less, enter -0-. If line 9 is zero, enter the gain from line 7 on line 12 below. If line 9 is more than zero, enter the amount from line 8 on line 12 below and enter the gain from line 9 as a long-term capital gain on Schedule D (see instructions)
8 9
Part II
10
Ordinary Gains and Losses
Ordinary gains and losses not included on lines 11 through 16 (include property held 1 year or less):
11 12 13 14 15 16 17 18
Loss, if any, from line 7 Gain, if any, from line 7 or amount from line 8, if applicable Gain, if any, from line 31 Net gain or (loss) from Form 4684, lines 31 and 38a Ordinary gain from installment sales from Form 6252, line 25 or 36 Ordinary gain or (loss) from like-kind exchanges from Form 8824
11 12 13 14 15 16
(
)
17 Combine lines 10 through 16 For all except individual returns, enter the amount from line 17 on the appropriate line of your return and skip lines a and b below. For individual returns, complete lines a and b below: a If the loss on line 11 includes a loss from Form 4684, line 35, column (b)(ii), enter that part of the loss here. Enter the part of the loss from income-producing property on Schedule A (Form 1040), line 27, and the part of the loss from property used as an employee on Schedule A (Form 1040), line 22. Identify as from “Form 4797, line 18a.” 18a See instructions b Redetermine the gain or (loss) on line 17 excluding the loss, if any, on line 18a. Enter here and on Form 1040, 18b line 14
For Paperwork Reduction Act Notice, see page 8 of the instructions.
Cat. No. 13086I
Form
4797
(2004)
Page 17
Form
8582
Passive Activity Loss Limitations
See separate instructions. Attach to Form 1040 or Form 1041.
OMB No. 1545-1008
Department of the Treasury (99) Internal Revenue Service
Attachment Sequence No.
2004
88
Name(s) shown on return
Identifying number
Part I
Charles and Lily Woods 2004 Passive Activity Loss
123-00-4567
Caution: See the instructions for Worksheets 1, 2, and 3 on pages 7 and 8 before completing Part I. Rental Real Estate Activities With Active Participation (For the definition of active participation see Special Allowance for Rental Real Estate Activities on page 3 of the instructions.) 1a Activities with net income (enter the amount from Worksheet 1, column (a)) b Activities with net loss (enter the amount from Worksheet 1, column (b)) c Prior years unallowed losses (enter the amount from Worksheet 1, column (c)) d Combine lines 1a, 1b, and 1c 1a 1b ( 1c (
2,776 26,600 14,892
) ) 1d ) ) 2c ( )
(38,716)
Commercial Revitalization Deductions From Rental Real Estate Activities 2a ( 2a Commercial revitalization deductions from Worksheet 2, column (a) b Prior year unallowed commercial revitalization deductions from 2b ( Worksheet 2, column (b) c Add lines 2a and 2b All Other Passive Activities 3a Activities with net income (enter the amount from Worksheet 3, column (a)) b Activities with net loss (enter the amount from Worksheet 3, column (b)) c Prior years unallowed losses (enter the amount from Worksheet 3, column (c)) d Combine lines 3a, 3b, and 3c 4
3a 3b ( 3c (
4,000 2,400 4,100
) ) 3d
(2,500)
Combine lines 1d, 2c, and 3d. If the result is net income or zero, all losses are allowed, including any prior year unallowed losses entered on line 1c, 2b, or 3c. Do not complete Form 8582. (41,216) 4 Report the losses on the forms and schedules normally used If line 4 is a loss and: ● Line 1d is a loss, go to Part II. ● Line 2c is a loss (and line 1d is zero or more), skip Part II and go to Part III. ●
5 6 7
Special Allowance for Rental Real Estate With Active Participation
Note: Enter all numbers in Part II as positive amounts. See page 8 for an example. 5 6 7
Enter the smaller of the loss on line 1d or the loss on line 4 Enter $150,000. If married filing separately, see page 8 Enter modified adjusted gross income, but not less than zero (see page 8) Note: If line 7 is greater than or equal to line 6, skip lines 8 and 9, enter -0- on line 10. Otherwise, go to line 8.
38,716
150,000 138,655
8 9 10
11,345 8 Subtract line 7 from line 6 Multiply line 8 by 50% (.5). Do not enter more than $25,000. If married filing separately, see page 8 Enter the smaller of line 5 or line 9 If line 2c is a loss, go to Part III. Otherwise, go to line 15.
9 10
5,673 5,673
Part III
11 12 13 14 15 16
Special Allowance for Commercial Revitalization Deductions From Rental Real Estate Activities
Note: Enter all numbers in Part III as positive amounts. See the example for Part II on page 8. 11 12 Enter the loss from line 4 13 Reduce line 12 by the amount on line 10 Enter the smallest of line 2c (treated as a positive amount), line 11, or line 13 14
Enter $25,000 reduced by the amount, if any, on line 10. If married filing separately, see instructions
Part IV
Total Losses Allowed
15 16
Add the income, if any, on lines 1a and 3a and enter the total Total losses allowed from all passive activities for 2004. Add lines 10, 14, and 15. See pages 10 and 11 of the instructions to find out how to report the losses on your tax return
Cat. No. 63704F
6,776 12,449 8582
For Paperwork Reduction Act Notice, see page 12 of the instructions.
Form
(2004)
Page 18
Form 8582 (2004)
Page
2
Caution: The worksheets must be filed with your tax retur n. Keep a copy for your records. Worksheet 1—For Form 8582, Lines 1a, 1b, and 1c (See page 7 of the instructions.)
Current year Name of activity (a) Net income (line 1a) (b) Net loss (line 1b) (c) Unallowed loss (line 1c) (d) Gain (e) Loss Prior years Overall gain or loss
Activity A Activity B
2,776
(15,000) (11,600)
(6,667) (8,225)
(18,891) (19,825)
Total. Enter on Form 8582, lines 1a, 1b, and 1c Name of activity
2,776 (14,892) (26,600) Worksheet 2—For Form 8582, Lines 2a and 2b (See pages 7 and 8 of the instructions.)
(a) Current year deductions (line 2a) (b) Prior year unallowed deductions (line 2b) (c) Overall loss
Total. Enter on Form 8582, lines 2a and 2b
Worksheet 3—For Form 8582, Lines 3a, 3b, and 3c (See page 8 of the instructions.)
Current year Name of activity (a) Net income (line 3a) (b) Net loss (line 3b) (c) Unallowed loss (line 3c) (d) Gain (e) Loss Prior years Overall gain or loss
Partnership #1 Partnership #4
4,000 (2,400)
(2,600) (1,500)
1,400 (3,900)
Total. Enter on Form 8582, lines 3a, 3b, and 3c
4,000 (4,100) (2,400) Worksheet 4—Use this worksheet if an amount is shown on Form 8582, line 10 or 14 (See page 9.)
Name of activity
Form or schedule and line number to be reported on (see instructions) (a) Loss (b) Ratio (c) Special allowance (d) Subtract column (c) from column (a)
Activity A Activity B
Sch. E, line 23 Sch. E, line 23
18,891 19,825
.487938 .512062
2,768 2,905
16,123 16,920
Total
38,716 1.00 Worksheet 5—Allocation of Unallowed Losses (See page 9 of the instructions.)
Name of activity
Form or schedule and line number to be reported on (see instructions) (a) Loss
5,673
33,043
(b) Ratio
(c) Unallowed loss
Activity A Activity B Partnership #4
Sch. E, line 23 Sch. E, line 23 Sch. E, line 28D
16,123 16,920 3,900
.436429 .458003 .105568
15,512 16,279 3,752
Total
36,943
1.00
35,543
Form
8582
(2004)
Page 19
Form 8582 (2004)
Page
3
Worksheet 6—Allowed Losses (See pages 9 and 10 of the instructions.)
Name of activity
Form or schedule and line number to be reported on (see instructions) (a) Loss (b) Unallowed loss (c) Allowed loss
Activity A Activity B Partnership #4
Sch. E, line 23 Sch. E, line 23 Sch. E, line 28D
21,667 19,825 3,900
15,512 16,279 3,752
6,155 3,546 148
Total
45,392 35,543 9,849 Worksheet 7—Activities With Losses Reported on Two or More Different Forms or Schedules (See page 10.)
(a) (b) (c) Ratio (d) Unallowed loss (e) Allowed loss
Name of Activity:
FormTotal
1.00
Form
8582
(2004)
Page 20.
1. Stock owned directly or indirectly by or for a corporation, partnership, estate, or trust is considered owned proportionately by its shareholders, partners, or beneficiaries. 2. An individual is considered to own the stock owned directly or indirectly by or for his or her family. Family includes only brothers and sisters (including half-brothers and half-sisters), a spouse, ancestors, and lineal descendants. 3. If a person holds an option to buy stock, he or she is considered to be the owner of that stock. 4.. 5. Stock that may be considered owned by an individual under either rule (2) or (3) is considered owned by the individual under rule (3).
4. A storage facility (other than a building or its structural components) used for the distribution of petroleum.. Qualified corporation. A qualified corporation is a closely held corporation, defined earlier, that is not:
CAUTION
!:
• You have a loss from any part of an activity that is covered by the at-risk rules, and
Activities Covered by the At-Risk Rules
If you are involved in one of the following activities as a trade or business or for the production of income, you are subject to the at-risk rules. 1. Holding, producing, or distributing motion picture films or video tapes. 2. Farming. 3. Leasing section 1245 property, including personal property and certain other tangible property that is depreciable or amortizable. See Section 1245 property, next. 4. Exploring for, or exploiting, oil and gas. 5. Exploring for, or exploiting, geothermal deposits (for wells started after September 1978). 6. Any other activity not included in (1) through (5) that is carried on as a trade or business or for the production of income. Section 1245 property. Section 1245 property includes any property that is or has been subject to depreciation or amortization and is: 1. Personal property,
• You are not at risk for some of your investment in the activity.: 1. The adjusted basis of: a. The partner’s partnership interest, or b. The shareholder’s stock plus any loans the shareholder makes to the corporation, 2. The at-risk rules, and 3. The passive activity rules. See “Limits on Losses” in Publication 541, and “Limitations on Losses, Deductions, and Credits” in “Shareholder’s Instructions for Schedule K-1 (Form 1120S).”
Who Is Affected?
The at-risk limits apply to individuals (including partners and S corporation shareholders), estates, trusts,.
2. Other tangible property (other than a building or its structural components) that is: a. Used in manufacturing, production, extraction or furnishing transportation, communications, electrical energy, gas, water, or sewage disposal services, b. A research facility used for the activities in (a), or c. A facility used in any of the activities in (a) for the bulk storage of fungible commodities, 3. A single purpose agricultural or horticultural structure, or
• A personal holding company, • A foreign personal holding company, or • A personal service corporation (defined in
section 269A(b) of the Internal Revenue Code, but determined by substituting 5% for 10%). Qualifying business. A qualifying business is any active business if all of the following apply. Page 21
1. During the entire 12-month period ending on the last day of the tax year, the corporation had at least: a. One full-time employee whose services were in the active management of the business, and.) 2. Deductions due to the business that are allowable to the corporation as business expenses and as contributions to certain employee benefit plans for the tax year exceed 15% of the gross income from the business. 3..
• Amounts borrowed by a corporation from
a person whose only interest in the activity is as a shareholder of the corporation,
• Amounts borrowed from a person having
an interest in the activity as a creditor, or
• Amounts borrowed before May 4, 2004,
for an activity described in (6) under Activities Covered by the At-Risk Rules, earlier.
• Amounts borrowed after May 3, 2004, secured by real property used in the activity of holding real property (other than mineral property) that, if nonrecourse, would be qualified nonrecourse financing. Related persons. Related persons include:
• • • •
Films and video tapes, Farms, Oil and gas properties, and Geothermal properties.
• Members of a family, but only an
individual’s brothers and sisters, half-brothers and half-sisters, spouse, ancestors (parents, grandparents, etc.), and lineal descendants (children, grandchildren, etc.),
For example, if a partnership or S corporation produces two films or video tapes, the partners or S corporation shareholders may treat the production of both films or video tapes as one activity for purposes of the at-risk rules.
• Two corporations that are members of the
same controlled group of corporations determined by applying a 10% ownership test,
At-Risk Amounts
You are at risk in any activity for: 1. The money and adjusted basis of property you contribute to the activity, and 2. Amounts you borrow for use in the activity if: a. You are personally liable for repayment, or b. You pledge property (other than property used in the activity) as security for the loan. inCAUTION crease your amount at risk by the contribution and the amount borrowed to finance the contribution. You may increase your at-risk amount only once.
• The fiduciaries of two different trusts, or
the fiduciary and beneficiary of two different trusts, if the same person is the grantor of both trusts,
• A tax-exempt educational or charitable organization and a person who directly or indirectly controls it (or a member of whose family controls it),
• A corporation and an individual who owns
directly or indirectly more than 10% of the value of the outstanding stock of the corporation,
• A trust fiduciary and a corporation of which
more than 10% in value of the outstanding stock is owned directly or indirectly by or for the trust or by or for the grantor of the trust,.
• The grantor and fiduciary, or the fiduciary
and beneficiary, of any trust,
• A corporation and a partnership if the
same persons own over 10% in value of the outstanding stock of the corporation and more than 10% of the capital interest or the profits interest in the partnership,
• Two S corporations if the same persons
own more than 10% in value of the outstanding stock of each corporation,
Aggregation of Activities
Activities described in (6) under Activities Covered by the At-Risk Rules, earlier, that constitute a trade or business are treated as one activity if:
• An S corporation and a regular corporation
if the same persons own more than 10% in value of the outstanding stock of each corporation,
!
• You actively participate in the management of the trade or business, or
• A partnership and a person who owns directly or indirectly more than 10% of the capital or profits of the partnership,
•. Page 22:
• Two partnerships if the same persons directly or indirectly own more than 10% of the capital or profits of each,
• Two persons who are engaged in business under common control, and
• An executor of an estate and a beneficiary
of that estate.
To determine the direct or indirect ownership of the outstanding stock of a corporation, apply the following rules. 1. Stock owned directly or indirectly by or for a corporation, partnership, estate, or trust is considered owned proportionately by or for its shareholders, partners, or beneficiaries. 2. Stock owned directly or indirectly by or for an individual’s family is considered owned by the individual. The family of an individual includes only brothers and sisters, half-brothers and half-sisters, a spouse, ancestors, and lineal descendants. 3. Any stock in a corporation owned by an individual (other than by applying rule (2)) is considered owned directly or indirectly by the individual’s partner. 4.. Effect of government price support programs. A government target price program.
However, you are considered at risk for qualified nonrecourse financing secured by real property used in an activity of holding real property. Qualified nonrecourse financing is financing for which no one is personally liable for repayment and that is:.
• Borrowed by you in connection with the
activity of holding real property,
• Secured by real property used in the activity,
• Not convertible from a debt obligation to
an ownership interest, and
• Loaned or guaranteed by any federal,
state, or local government, or borrowed by you from a qualified person.:
• The negative at-risk amount (treated as a
positive amount), or
• A person related to you in one of the ways
listed under Related persons, earlier. However, a person related to you may be a qualified person if the nonrecourse financing is commercially reasonable and on the same terms as loans involving unrelated persons.
•.
Amounts Not At Risk.
• A person from which you acquired the
property or a person related to that person.
• A person who receives a fee due to your
investment in the real property or a person related to that.
Page 23:
news by email.
Walk-in. Many products and services are available on a walk-in basis.
• Get information on starting and operating
a small business.
•.. Phone. Many services are available by phone.
• Services. You can walk in to your local
Taxpayer Assistance Center every business day. Distribution Center nearest to you and receive a response within 10 business days after your request is received. Use the address that applies to your part of the country.
• Ordering forms, instructions, and publications. Call 1-800-829-3676 to order current-year forms, instructions, and publications and prior-year forms and instructions. You should receive your order within 10 days.
• Call the Taxpayer Advocate toll free at
1-877-777-4778.
• Call, write, or fax the Taxpayer Advocate
office in your area.
• Call 1-800-829-4059 if you are a
TTY/TDD user.
• Asking tax questions. Call the IRS with
your tax questions at 1-800-829-1040.
• Visit.
For more information, see Publication 1546, The Taxpayer Advocate Service of the IRS — How To Get Help With Unresolved Tax Problems.:
•.
• Western part of U.S.:
Western Area Distribution Center Rancho Cordova, CA 95743-0001 and
press 2 to listen to pre-recorded messages covering various tax topics.
• E-file your return. Find out about commercial tax preparation and e-file services available free to eligible taxpayers.
• Eastern part of U.S. and foreign
addresses: Eastern Area Distribution Center P.O. Box 85074 Richmond, VA 23261-5074 CD-ROM for tax products. You can order Publication 1796, IRS Federal Tax Products CD-ROM, and obtain:
• Refund information. If you would like to
check the status of your.
• Check the status of your 2004 refund.
Click on Where’s My Refund. Be sure to wait at least 6 weeks from the date you filed your return (3 weeks if you filed electronically). Have your 2004 tax return available because you will need to know your filing status and the exact whole dollar amount of your refund.
• Current-year forms, instructions, and publications.
• Download forms, instructions, and publications.
• Order IRS products online. • Research your tax questions online. • Search publications online by topic or
keyword.
• Prior-year forms and instructions. • Frequently requested tax forms that may
be filled in electronically, printed out for submission, or saved for recordkeeping.
• Internal Revenue Bulletins.
Buy the CD-ROM from National Technical Information Service (NTIS) at cdorders for $22 (no handling fee) or call 1-877-233-6767 toll free to buy the CD-ROM for $22 (plus a $5 handling fee). The first release is
• View Internal Revenue Bulletins (IRBs)
published in the last few years.
• Figure your withholding allowances using
our Form W-4 calculator. Page 24.
Page 25
Index
To help us develop a more useful index, please let us know if you have ideas for index entries. See “Comments and Suggestions” in the “Introduction” for the ways you can reach us.
A
Active participation . . . . . . . . . 22 Activity: Appropriate economic unit . . . . . . . . . . . . . . . . . . . . . . . 7 Nonpassive . . . . . . . . . . . . . . . . . 4 Trade or business . . . . . . . . . . . 2 Amounts borrowed . . . . . . . . . . 22 Amounts not at risk . . . . . . . . . 23 Appropriate economic unit . . . . . . . . . . . . . . . . . . . . . . . . 7 Assistance (See Tax help) At-risk activities: Aggregation of . . . . . . . . . . . . . 22 Separation of . . . . . . . . . . . . . . 22 At-risk amounts . . . . . . . . . . . . . 22 Government price support programs . . . . . . . . . . . . . . . . 23 Increasing amounts . . . . . . . . 23 Nonrecourse financing . . . . . . 23 At-risk limits . . . . . . . . . . . . . . . . 21 Closely held corporation . . . . 21 Loss defined . . . . . . . . . . . . . . . 21 Partners . . . . . . . . . . . . . . . . . . . 21 S corporation shareholders . . . . . . . . . . . . . 21 Who is affected . . . . . . . . . . . . 21 At-risk rules: Activities covered by . . . . . . . . 21 Exceptions to . . . . . . . . . . . . . . 21 Excluded business . . . . . . . . . 22 Qualified corporation . . . . . . . 21 Qualifying business . . . . . . . . . 21 Recapture rule . . . . . . . . . . . . . 23
Qualified . . . . . . . . . . . . . . . . . . . 21
D
Deductions, passive activity . . . . . . . . . . . . . . . . . . . . . 6 Disabled farmer . . . . . . . . . . . . . . 5 Disclosure requirement . . . . . . 7 Dispositions: Death . . . . . . . . . . . . . . . . . . . . . 10 Gift . . . . . . . . . . . . . . . . . . . . . . . . 10 Installment sale . . . . . . . . . . . . 10 Partial . . . . . . . . . . . . . . . . . . . . . . 8
Modified adjusted gross income . . . . . . . . . . . . . . . . . . . . . 4 More information (See Tax help)
N
Nonrecourse loan . . . . . . . . . . . 23
P
Participation . . . . . . . . . . . . . . . . . 5 Active . . . . . . . . . . . . . . . . . . . . . 22 Material . . . . . . . . . . . . . . . . . . . . . 4 Passive activity . . . . . . . . . . . . . . 2 Comprehensive example . . . . . . . . . . . . . . . . . 10 Credits . . . . . . . . . . . . . . . . . . . . . 2 Disposition . . . . . . . . . . . . . . . . . . 9 Former . . . . . . . . . . . . . . . . . . . . . 2 Grouping . . . . . . . . . . . . . . . . . . . 7 Limits . . . . . . . . . . . . . . . . . . . . . . . 2 Material participation . . . . . . . . 4 Rental . . . . . . . . . . . . . . . . . . . . . . 3 Rules . . . . . . . . . . . . . . . . . . . . . 2, 7 Who must use these rules . . . . . . . . . . . . . . . . . . . . . 2 Passive activity deductions . . . . . . . . . . . . . . . . . 6 Passive activity income . . . . . . 5 Passive income, recharacterization of . . . . . . . 8 Publications (See Tax help) Publicly traded partnership . . . . . . . . . . . . . . 2, 8
Reductions of amounts at risk . . . . . . . . . . . . . . . . . . . . . . . 23 Related persons . . . . . . . . . . . . . 22 Rental activity: $25,000 offset . . . . . . . . . . . . . . . 3 Active participation . . . . . . . . . . 3 Exceptions . . . . . . . . . . . . . . . . . . 3 Phaseout rule . . . . . . . . . . . . . . . 4 Real estate professional . . . . . 5 Retired farmer . . . . . . . . . . . . . . . . 5
S
Section 1245 property . . . . . . . 21 Self-charged interest . . . . . . . . . 5 Separate activity . . . . . . . . . . . . 22 Significant participation passive activities . . . . . . . . . . . . . . . . . . . 8 Special $25,000 allowance . . . . 3 Suggestions for publication . . . . . . . . . . . . . . . . . 2 Surviving spouse of farmer . . . . . . . . . . . . . . . . . . . . . . 5
E
Excluded business, definition of . . . . . . . . . . . . . . . . . . . . . . . . . 22
F
Farmer . . . . . . . . . . . . . . . . . . . . . . . 5 Form: 6198 . . . . . . . . . . . . . . . . . . . . . . 21 8582 . . . . . . . . . . . . . . . . . . . . . . 11 8810 . . . . . . . . . . . . . . . . . . . . . . . 2 Former passive activity . . . . . . 2 Free tax services . . . . . . . . . . . . 24
T
Tax help . . . . . . . . . . . . . . . . . . . . . 24 Taxpayer Advocate . . . . . . . . . . 24 Trade or business activities: Definition of . . . . . . . . . . . . . . . . . 2 Real property . . . . . . . . . . . . . . . 5 TTY/TDD information . . . . . . . . 24
G
Grouping passive activities . . . . . . . . . . . . . . . . . . . 7
H
Help (See Tax help)
W
Worksheet 1 . . . . . . . . . . . . . . . . . 11 Worksheet 3 . . . . . . . . . . . . . . . . . 11 Worksheet 4 . . . . . . . . . . . . . . . . . 11 Worksheet 5 . . . . . . . . . . . . . . . . . 12 Worksheet 6 . . . . . . . . . . . . . . . . . 12 Worksheet 7 . . . . . . . . . . . . . . . . . 12 Worksheet A . . . . . . . . . . . . . . . . . 8 Worksheet B . . . . . . . . . . . . . . . . . 8
Q
Qualified person, nonrecourse financing . . . . . . . . . . . . . . . . . . 23 Qualifying business, at-risk rules . . . . . . . . . . . . . . . . . . . . . . 21
B
Borrowed amounts . . . . . . . . . . 22
I
Income, passive activity . . . . . . 5
C
Closely held corporation . . . . . 2, 21 Comments on publication . . . . 2 Corporations: Closely held . . . . . . . . . . . . . . . 5, 8 Controlled group of . . . . . . . . . 21 Personal service . . . . . . . . . . 5, 8
L
Limited entrepreneur . . . . . . . . . 7 Limited partners . . . . . . . . . . . . . . 5 Losses, closely held corporations . . . . . . . . . . . . . . . 2
R
Real estate professional . . . . . . 5 Recapture rule under at-risk limits . . . . . . . . . . . . . . . . . . . . . . 23 Recharacterization of passive income . . . . . . . . . . . . . . . . . . . . . 8
■
M
Material participation . . . . . . . 4, 5
Page 26
Tax Publications for Individual Taxpayers
General Guides
1 Your Rights as a Taxpayer 17 Your Federal Income Tax (For Individuals) 334 Tax Guide for Small Business (For Individuals Who Use Schedule C or C-EZ) 509 Tax Calendars for 2005 553 Highlights of 2004 Tax Changes 910 IRS Guide to Free Tax Services
See How To Get Tax Help for a variety of ways to get publications, including by computer, phone, and mail.—How to Get Help With Unresolved Coverage Tax 9465 Installment Agreement Request
Catalog Number
11700 20604 11744 11862 11980 12490 12906 13141 13177 13329 13600 62299 63704 63966 10644 12081 13232 25379 14842
1040 U.S. Individual Income Tax Return Sch A&B Itemized Deductions & Interest and Ordinary Dividends Profit or Loss From Business Sch C Sch C-EZ Net Profit From Business Capital Gains and Losses Sch D Sch D-1 Continuation Sheet for Schedule D Supplemental Income and Loss Sch E Earned Income Credit Sch EIC Profit or Loss From Farming Sch F Sch H Household Employment Taxes Sch J Farm Income Averaging Credit for the Elderly or the Disabled Sch R Self-Employment Tax Sch SE 1040A U.S. Individual Income Tax Return Interest and Ordinary Dividends for Sch 1 Form 1040A Filers Child and Dependent Care Sch 2 Expenses for Form 1040A Filers Credit for the Elderly or the Sch 3 Disabled for Form 1040A Filers 1040EZ Income Tax Return for Single and Joint Filers With No Dependents 1040-ES Estimated Tax for Individuals Amended U.S. Individual Income Tax Return 1040X
Page 27 | https://www.scribd.com/document/545992/US-Internal-Revenue-Service-p925-2004 | CC-MAIN-2018-30 | refinedweb | 13,303 | 54.63 |
Holy cow, I wrote a book!
In our
discussion __purecall,
we saw that you can declare a pure virtual function with the
= 0 syntax,
and if you try to call one of these functions from the base class,
you will get the dreaded R6025 - pure virtual function call
error.
__purecall
= 0
In that article, I wrote that a pure virtual function is
"a method which is declared by the base class, but for which
no implementation is provided."
That statement is false.
You can provide an implementation for a pure virtual method in C++.
"That's crazy talk," I hear you say.
Okay, let's start talking crazy:
#include <iostream>
class Base {
public:
Base() { f(); }
virtual void f() = 0;
};
class Derived : public Base {
public:
Derived() { f(); }
virtual void f() { std::cout << "D"; }
};
int main(int, char **)
{
Derived d;
return 0;
}
What happens when the test
function constructs a Derived?
test
Derived
Trick question,
because you get a linker error
when you try to build the project.
There are many questions lurking here,
like "Why do I get a linker error?"
and "Why isn't it a compiler error?"
We'll get back to those questions later.
For now, let's get the code to build.
class Base {
public:
Base() { call_f(); }
virtual void f() = 0;
void call_f() { f(); }
};
Okay, with this change (hiding the call to f
inside a function called call_f),
the code compiles,
so now we can answer the question:
f
call_f
Answer: You get the dreaded purecall error,
because the base class constructor
has engaged in a conspiracy with the function call_f
to call the function f from its constructor.
Since f is a pure virtual function,
you get the purecall error.
Okay, next question:
Why didn't the original code result in a compiler error?
Answer:
The compiler is not required to do a full code flow analysis
to determine whether you are calling a pure virtual method
from a constructor.
The language forbids it, but no diagnostic is required
and the behavior is undefined.
Member functions can be called from a constructor (or destructor)
of an abstract class;
the effect of making a virtual call (10.3) to a pure virtual
function directly or indirectly for the object being created
(or destroyed) from such a constructor (or destructor) is undefined.
But why did it result in a linker error?
Answer:
As we learned during the discussion of __purecall,
C++ objects change identity during their construction,
and at the point that the Base constructor is running,
the object is still a Base,
so the final overrider method is Base::f
Therefore, when you called
f() from the Base constructor,
you were actually calling Base::f.
Base
Base::f
f()
And you never defined Base::f,
so the linker complained.
"Wait, I can define Base::f?"
Sure, let's do it.
At the end of the program (even after the definition
of main)
add this code:
main
void Base::f()
{
std::cout << "B";
}
Now the program compiles,
and when you run it, well, we saw that the standard leaves this
undefined, so you might crash, or monkeys might fly out of your nose,
or the runtime library may go back in time and kill your parents.
(We'll see in a future article
how undefined behavior can lead to time travel.
How's that for a teaser!)
But one implementation might generate this program output:
BD
This particular implementation decided not to try very hard to detect the
case where you are calling Base::f during the
constructor and just lets the call happen,
and it ends up calling the method you defined later.
"But if I'm not allowed to call the pure virtual function from
a constructor or destructor,
and if I call the method
after construction, it always calls the version of the function
that the derived class overrode,
then how could this code ever execute at all (legitimiately)?
In other words,
what conforming program could ever print the letter B?"
B
The function cannot be called implicitly, but it can be called explicitly:
class Base {
public:
Base() { /* f(); */ }
virtual void f() = 0;
};
void Base::f()
{
std::cout << "B";
}
class Derived : public Base {
public:
Derived() { f(); }
virtual void f() { std::cout << "D"; Base::f(); }
};
int main(int, char **)
{
Derived d;
return 0;
}
First, we got rid of the illegal call to f()
in the base class constructor (to keep our code legit).
Next, we adjusted our override version of f
so that it calls the base class method after doing some
custom work.
This time, the program prints DB,
and the code is perfectly legitimate this time.
No undefined behavior, nothing up my sleeve.
DB
What happened here?
The derived class constructor called the f
method, which maps to
Derived::f.
That function prints the letter D,
and then it calls the base class version
Base::f explicitly.
The base class version then prints the letter B.
Derived::f
This is actually nothing new; this is how overridden
methods work in general.
The only wrinkle here is that the base class method
can be called only via explicit qualification;
there is no way to call it implicitly.
This was a rather long-winded way of calling out a weird
corner case in C++ that most people don't even realize exists:
A pure virtual function can have an implementation. | http://blogs.msdn.com/b/oldnewthing/archive/2013/10/11/10455907.aspx | CC-MAIN-2014-23 | refinedweb | 894 | 67.08 |
#include <rte_member.h>
Parameters used when create the set summary table. Currently user can specify two types of setsummary: HT based and vBF. For HT based, user can specify cache or non-cache mode. Here is a table to describe some differences
Definition at line 158 of file rte_member.h.
Name of the hash.
Definition at line 159 of file rte_member.h.
User to specify the type of the setsummary from one of rte_member_setsum_type.
HT based setsummary is implemented like a hash table. User should use this type when there are many sets.
vBF setsummary is a vector of bloom filters. It is used when number of sets is not big (less than 32 for current implementation).
Definition at line 171 of file rte_member.h.
is_cache is only used for HT based setsummary.
If it is HT based setsummary, user to specify the subtype or mode of the setsummary. It could be cache, or non-cache mode. Set is_cache to be 1 if to use as cache mode.
For cache mode, keys can be evicted out of the HT setsummary. Keys with the same signature and map to the same bucket will overwrite each other in the setsummary table. This mode is useful for the case that the set-summary only needs to keep record of the recently inserted keys. Both false-negative and false-positive could happen.
For non-cache mode, keys cannot be evicted out of the cache. So for this mode the setsummary will become full eventually. Keys with the same signature but map to the same bucket will still occupy multiple entries. This mode does not give false-negative result.
Definition at line 192 of file rte_member.h.
For HT setsummary, num_keys equals to the number of entries of the table. When the number of keys inserted in the HT setsummary approaches this number, eviction could happen. For cache mode, keys could be evicted out of the table. For non-cache mode, keys will be evicted to other buckets like cuckoo hash. The table will also likely to become full before the number of inserted keys equal to the total number of entries.
For vBF, num_keys equal to the expected number of keys that will be inserted into the vBF. The implementation assumes the keys are evenly distributed to each BF in vBF. This is used to calculate the number of bits we need for each BF. User does not specify the size of each BF directly because the optimal size depends on the num_keys and false positive rate.
Definition at line 210 of file rte_member.h.
The length of key is used for hash calculation. Since key is not stored in set-summary, large key does not require more memory space.
Definition at line 216 of file rte_member.h.
num_set is only used for vBF, but not used for HT setsummary.
num_set is equal to the number of BFs in vBF. For current implementation, it only supports 1,2,4,8,16,32 BFs in one vBF set summary. If other number of sets are needed, for example 5, the user should allocate the minimum available value that larger than 5, which is 8.
Definition at line 227 of file rte_member.h.
false_positive_rate is only used for vBF, but not used for HT setsummary.
For vBF, false_positive_rate is the user-defined false positive rate given expected number of inserted keys (num_keys). It is used to calculate the total number of bits for each BF, and the number of hash values used during lookup and insertion. For details please refer to vBF implementation and membership library documentation.
For HT, This parameter is not directly set by users. HT setsummary's false positive rate is in the order of: false_pos = (1/bucket_count)*(1/2^16), since we use 16-bit signature. This is because two keys needs to map to same bucket and same signature to have a collision (false positive). bucket_count is equal to number of entries (num_keys) divided by entry count per bucket (RTE_MEMBER_BUCKET_ENTRIES). Thus, the false_positive_rate is not directly set by users for HT mode.
Definition at line 248 of file rte_member.h.
We use two seeds to calculate two independent hashes for each key.
For HT type, one hash is used as signature, and the other is used for bucket location. For vBF type, these two hashes and their combinations are used as hash locations to index the bit array.
Definition at line 258 of file rte_member.h.
The secondary seed should be a different value from the primary seed.
Definition at line 263 of file rte_member.h.
NUMA Socket ID for memory.
Definition at line 265 of file rte_member.h. | https://doc.dpdk.org/api-18.05/structrte__member__parameters.html | CC-MAIN-2022-27 | refinedweb | 778 | 67.55 |
As we start off on our journey building mobile games using the Unity game engine, it's important that readers are familiar with the engine itself before we dive into the specifics of building things for mobile platforms. Although there is a chance that you've already built a game and want to transition it to mobile, there will also be readers who haven't touched Unity before, or may have not used it in a long time. This chapter will act as an introduction to newcomers, a refresher for those coming back, and will provide some best practices for those who are already familiar with Unity.
In this chapter, we will build a 3-D endless runner game in the same vein as Imangi Studios, LLC's Temple Run series. In our case, we will have a player who will run continuously in a certain direction, and will dodge obstacles that come in their way. We can also add additional features to the game easily, as the game will endlessly have new things added to it.
Over the course of this chapter, we will create a simple project in Unity, which we will be modifying over the course of this book to make use of features commonly seen in mobile games. While you may skip this chapter if you're already familiar with Unity, I find it's also a good idea to go through the project so that you know the thought processes behind why the project is made in the way that it is, so you can keep it in mind for your own future titles.
This chapter will be split into a number of topics. It will contain a simple, step-by-step process from beginning to end. Here is the outline of our tasks:
- Project setup
- Creating the player
- Improving scripts using attributes
- Having the camera follow the player
- Creating a basic tile
- Making the game endless
- Creating obstacles
Now that we have our goals in mind, let's start building our project:
- To get started, open Unity on your computer. For the purpose of this book, we will use Unity 2017.2.0f3, but the steps should work with minimal changes in future versions.
Note
If you would like to download the exact version used in this book, and there is a new version out, you can visit Unity's download archive at.
- From startup, we'll opt to create a new project by clicking on the
Newbutton.
- Next, under
Project name*put in a name (I have chosenÂ
MobileDev) and make sure that
3Dis selected. If
Enable Unity Analytics is enabled (the check to the left of it says
On), click on the
Enable Unity Analyticsbutton again in order to disable it for the time being; we will add it ourselves later on when we go through Chapter 5, Advertising with Unity Ads. Afterwards, click on
Create projectand wait for Unity to load up:
- After it's finished, you'll see the Unity Editor pop up for the first time:
- If your layout doesn't look the same as in the preceding screenshot, you may go to the top-right section of the toolbar and select the drop-down menu there that reads
Layers. From there, selectÂ
Defaultfrom the options presented.
Note
If this is your first time working with Unity, then I highly suggest that you read the Learning the Interface section of the Unity Manual, which you can access atÂ.
Now that we have Unity opened up, we can actually start building our project. To get started, let's build a player that will always move forward. Let's start with that now:
- Let's create some ground for our player to walk on. To do that, let's go to the top menu and select
GameObject|
3D Object|
Cube.
- From there, let's move over to the
Inspectorwindow and change the name of the object to
Floor. Then, on the
Transformcomponent, set the
Positionto
(0, 0, 0), which we can either type in, or we can right-click on the
Transformcomponent and then select the
Reset Positionoption.
- Then, we will set the
Scaleto
(7, 0.1, 10):
In Unity, by default, 1 unit of space in Unity is representative of 1 meter in real life. This will make the floor longer than it is wide (X and Z), and we have some size on the ground (Y), so the player will collide and land on it because we have a
Box Collider component attached to it.
- Next, we will create our player, which will be a sphere. To do this, we will go to
Game Object|
3D Object|
Sphere.
- Rename the sphere to
Playerand set the
Transformcomponent's
Positionto
(0, 1, -4):
This will place the ball slightly above the ground, and shifts it back to near the starting point. Note that the camera object (you can see a camera icon to point it out) is pointing toward the ball by default because it is positioned at
0,Â
1,Â
-10.
- We want the ball to move, so we will need to tell the physics engine that we want to have this object react to forces, so we will need to add a
Rigidbodycomponent. To do so, go to the menu and select
Component|
Physics|
Rigidbody. To see what happens now, let's click on the
Playbutton that can be seen in the middle of the top toolbar:
As you can see in the preceding screenshot, you should see the ball fall down onto the ground when we play the game.
Note
You can disable/enable having the
Game tab take the entire screen when being played by clicking on the
Maximize On Play button at the top, or by right-clicking on the
Game tab and then selecting
Maximize.
- Click on the
Playbutton again to turn the game off and go back to the
Scenetab, if it doesn't happen automatically.
We want to have the player move, so in order to do that, we will create our own piece of functionality in a script, effectively creating our own custom component in the process.
- To create a script, we will go to the
Projectwindow and select
Create|
Folderon the top-left corner of the menu. From there, we'll name this folder
Scripts. It's always a good idea to organize our projects, so this will help with that.
Note
If you happen to misspell the name, go ahead and select the object and then single-click on the name and it'll let you rename it.
- Double-click on the folder to enter it, and now you can create a script by going to
Create|
C# Scriptand renaming this to
PlayerBehaviour(no spaces).
Note
The reason I'm using the "behaviour", "spelling" instead of "behavior" is that all components in Unity are children of another class called
MonoBehaviour, and I'm following Unity's lead in that regard.
- Double-click on the script to open up the script editor (IDE) of your choice and add the following code to it:
using UnityEngine; public class PlayerBehaviour : MonoBehaviour { // A reference to the Rigidbody component private Rigidbody rb; // How fast the ball moves left/right public float dodgeSpeed = 5; // How fast the ball moves forwards automatically public float rollSpeed = 5; // Use this for initialization void Start () { // Get access to our Rigidbody component rb = GetComponent<Rigidbody>(); } // Update is called once per frame void Update () { // Check if we're moving to the side var horizontalSpeed = Input.GetAxis("Horizontal") * dodgeSpeed; rb.AddForce(horizontalSpeed, 0, rollSpeed); } }
In the preceding code, we have a couple of variables that we will be working with. The
rb variable is a reference to the game object's
Rigidbody component that we added previously. It gives us the ability to make the object move, which we will use in the
Update function. We also have two variables
dodgeSpeed and
rollSpeed, which dictates how quickly the player will move when moving left/right, or when moving forward, respectively.
Since our object has only one
Rigidbody component, we assign
rb once in the
Start function, which is called when the game starts, as long as the game object attached to this script is enabled.
Then, we use the
Update function to check whether our player is pressing keys to move left or right as based on Unity's Input Manager system. By default, the
Input.GetAxis function will return to us a negative value moving toÂ
-1 if we press A or the left arrow. If we press the right arrow or D, we will get a positive value up toÂ
1 returned to us, and the input will move toward a
0 if nothing is pressed. We then multiply this by
dodgeSpeed in order to increase the speed so that it is easier to be seen.
Note
For more information on the Input Manager, check outÂ.
Finally, once we have that value, we will apply a force to our ball'sÂ
horizontalSpeed units on the X-axis and
rollSpeed in the Z-axis.
- Save your script, and return to Unity.
- We will now need to assign this script to our player by selecting the
Playerobject in the
Hierarchywindow, and then in the
Inspectorwindow, drag and drop the
PlayerBehaviourscript from the
Projectwindow on top of the
Playerobject. If all goes well, we should see the script appear on our object, as follows:
Note that when writing scripts if we declare a variable as
public, it will show up in the
Inspector window for us to be able to set it. We typically set a variable as public when we want designers to tweak the values for gameplay purposes.
- Save your scene by going to
File|
Save Scene. Create a new folder called
Scenesand save your scene as
Gameplay. Afterward, play the game and use the left and right arrows to see the player moving according to your input, but no matter what, moving forward by default:
We could stop working with the
PlayerBehaviour class script here, but I want to touch on a couple of things that we can use in order to improve the quality and style of our code. This becomes especially useful when you start building projects in teams, as you'll be working with other people--some of them will be working on code with you, and then there are designers and artists who will not be working on code with you, but will still need to use the things that you've programmed.
When writing scripts, we want them to be as error-proof as possible. Making the
rb variable
private starts that process, as now the user will not be able to modify that anywhere outside of this class. We want our teammates to modify
dodgeSpeed and
rollSpeed, but we may want to give them some advice as to what it is and/or how it will be used. To do this in the
Inspector window, we can make use of something called an attribute.
Attributes are things we can add to the beginning of a variable, class, or function declaration, which allow us to attach an additional functionality to them. There are many of them that exist inside Unity, and you can write your very own as well, but, right now, we'll talk about the ones that I use most often.
If you've used Unity for a period of time, you may have noted that some components in the
Inspector window, such as the
Rigidbody, have a nice feature--if you move your mouse over a variable name, you'll see a description of what the variables are and/or how to use them. The first thing you'll learn is how we can get the same effect in our own components by making use of the
Tooltip attribute. If we do this for the
dodgeSpeed and
rollSpeed variables, it will look something like this:
[Tooltip("How fast the ball moves left/right")] public float dodgeSpeed = 5; [Tooltip("How fast the ball moves forwards automatically")] public float rollSpeed = 5;
Save the preceding script and return to the editor:
Now, when we highlight the variable using the mouse and leave it there, the text we placed will be displayed. This is a great habit to get into, as your teammates can always tell what it is that your variables are being used for.
Note
For more information on the
Tooltip attribute, check out,Â.
Another thing that we can use to protect our code is the
Range attribute. This will allow us to specify a minimum and maximum value for a variable. Since we want the player to always be moving forward, we may want to restrict the player from moving backward. To do that, we can add the following highlighted line of code:
[Tooltip("How fast the ball moves forwards automatically")] [Range(0, 10)] public float rollSpeed = 5;
Save your script, and return to the editor:
We have now added a slider beside our value, and we can drag it to adjust between our minimum and maximum values. Not only does this protect our variable, it also makes it so our designers can tweak things easily by just dragging them around.
Currently, we are using the
Rigidbody component in order to create our script. When working as a team member, others may not be reading your scripts, but are still expected to use them when creating gameplay. Unfortunately, this means that they may do things that have unintended results, such as removing the
Rigidbody component, which will cause errors when our script is run. Thankfully, we also have the
RequireComponent attribute, which we can use to fix this.
It looks something like this:
using UnityEngine; [RequireComponent(typeof(Rigidbody))] public class PlayerBehaviour : MonoBehaviour
By adding this attribute, we state that when we add this component to a game object and it doesn't have a
Rigidbody attached to its game object, the component will be added automatically. It also makes it so that if we were to try to remove the
Rigidbody from this object, the editor will warn us that we can't, unless we remove the PlayerBehaviour component first. Note that this works for any class extended from
MonoBehaviour; just replace
Rigidbody with whatever it is that you wish to keep.
Now, if we go into the Unity editor and try to remove the
Rigidbody component by right-clicking on it in the
Inspector and selecting
Remove Component, the following message will be seen:
This is exactly what we want, and this ensures that the component will be there, allowing us not to have to include if-checks every time we want to use a component.
Note that previously we did not use a
Tooltip attribute on the private
rb variable. Since it's not being displayed in the editor, it's not really needed. However, there is a way that we can enhance that as well, making use of XML comments. XML comments have a couple of nice things that we get when using them instead of traditional comments, which we were using previously. When using the variables/functions instead of code in Visual Studio, we will now see a comment about it. This will help other coders on your team have additional information and details to ensure that they are using your code correctly.
XML comments look something like this:
/// <summary> /// A reference to the Rigidbody component /// </summary> private Rigidbody rb;
It may appear to be a lot more writing is needed to use this format, but I did not actually type the entire thing out. XML comments are a fairly standard C# feature, so if you are using MonoDevelop or Visual Studio and type
///, it will automatically generate the summary blocks for you (and the
param tags needed, if there are parameters needed for something like a function).
Now, why would we want to do this? Well, now, if you select the variable in Intellisense, it will display the following information to us:
This is a great help for when other people are trying to use your code and it is how Unity's staff write their code. We can also extend this to functions and classes to ensure that our code is more self-documented.
Unfortunately, XML comments do not show up in the
Inspector, and the
Tooltip attribute doesn't show info in the editor. With that in mind, I used
Tooltips for public instructions and/or things that will show up in the
Inspector window, and XML comments for everything else.
Note
If you're interested in looking into XML comments more, feel free to check out:Â.
With all of the stuff we've been talking about, we can now have the final version of the script, which looks like the following:
using UnityEngine; /// <summary> /// Responsible for moving the player automatically and /// reciving input. /// </summary> [RequireComponent(typeof(Rigidbody))] public class PlayerBehaviour : MonoBehaviour { /// <summary> /// A reference to the Rigidbody component /// </summary> private Rigidbody rb; [Tooltip("How fast the ball moves left/right")] public float dodgeSpeed = 5; [Tooltip("How fast the ball moves forwards automatically")] [Range(0, 10)] public float rollSpeed = 5; /// <summary> /// Use this for initialization /// </summary> void Start () { // Get access to our Rigidbody component rb = GetComponent<Rigidbody>(); } /// <summary> /// Update is called once per frame /// </summary> void Update () { // Check if we're moving to the side var horizontalSpeed = Input.GetAxis("Horizontal") * dodgeSpeed; // Apply our auto-moving and movement forces rb.AddForce(horizontalSpeed, 0, rollSpeed); } }
I hope that you also agree that this makes the code easier to understand and better to work with.
Â
Currently, our camera stays in the same spot while the game is going on. This does not work very well for this game, as the player will be moving more the longer the game is going on. There are two main ways that we can move our camera. We can just move the camera and make it a child of the player, but that will not work due to the ball's rotation. Due to that, we will likely want to use a script instead. Thankfully, we can modify how our camera looks at things fairly easily, so let's go ahead and fix that next:
- Go to the
Projectwindow and create a new C# script called
CameraBehaviour. From there, use the following code:
using UnityEngine; /// <summary> /// Will adjust the camera to follow and face a target /// </summary> public class CameraBehaviour : MonoBehaviour { [Tooltip("What object should the camera be looking at")] public Transform target; [Tooltip("How offset will the camera be to the target")] public Vector3 offset = new Vector3(0, 3, -6); /// <summary> /// Update is called once per frame /// </summary> void Update () { // Check if target is a valid object if (target != null) { // Set our position to an offset of our target transform.position = target.position + offset; // Change the rotation to face target transform.LookAt(target); } } }
- Save the script and dive back into the Unity Editor. Select the
Main Cameraobject in the
Hierarchywindow. Then, go to the
Inspectorwindow and add the
CameraBehaviourcomponent to it. You may do this by dragging and dropping the script from the
Projectwindow onto the game object or by clicking on the
Add Componentbutton at the bottom of the
Inspectorwindow, typing in the name of our component, and then clicking on Enter to confirm once it is highlighted.
- Afterward, drag and drop the
Playerobject from the
Hierarchywindow into the
Targetproperty of the script in the
Inspectorwindow:
- Save the scene, and play the game:
The camera now follows the player as it moves. Feel free to tweak the variables and see how it effects the look of the camera to get the feel you'd like best for the project.
We want our game to be endless, but in order to do so, we will need to have pieces that we can spawn to build our environment; let's do that now:
- To get started, we will first need to create a single piece for our runner game. To do that, let's first add some walls to the floor we already have. From the
Hierarchywindow, select the
Floor object and duplicate it by pressing Ctrl + D in Windows or command + D on Mac. Rename this new object asÂ
Left Wall.
Â
- Change the
Left Wallobject's
Transformcomponent by adjusting the
Scaleto
(1, 2, 10). From there, select the
Movetool by clicking on the button with arrows on the toolbar or by pressing the W key.
Note
For more information on Unity's built-in hotkeys, check out:Â.
- We want this wall to match up with the floor, so hold down the V key to enter the Vertex Snap mode.
In the Vertex Snap mode, we can select any of the vertices on a mesh and move it to the same position of another vertex on a different object. This is really useful for making sure that objects don't have holes between them.
- With the Vertex Snap mode on, select the inner edge and drag it until it hits the edge of the floor.
Note
For more info on moving objects through the scene, including more details on Vertex Snap mode, check outÂ.
- Then, duplicate this wall and put an other on the other side, naming it
Right Wall:
As you can see in the preceding screenshot, we now protect the player from falling off the left and right edges of the play area. Due to how the walls are set up, if we move the floor object, the walls will move as well.
Note
For info on moving Unity's camera or navigating to the scene view, check out:Â.
The way this game is designed, after the ball rolls past a single tile, we will no longer need it to be there anymore. If we just leave it there, the game will get slower over time due to us having so many things in the game environment using memory, so it's a good idea to remove assets we are no longer using. We also need to have some way to figure out when we should spawn new tiles to continue the path the player can take.
- Now, we also want to know where this piece ends, so we'll add an object with a Trigger collider in it. Select
GameObject|
Create Empty and name this object
Tile End.
- Then, we will add a
Box Collidercomponent to our
Tile Endobject. Under the
Box Colliderin the
Inspectorwindow, set the
Sizeto
(7, 2, 1)to fit the size of the space the player can walk in. Note that there is a green box around that space showing where collisions can take place. Set the
Position property to
(0, 1, 10)to reach past the end of our tile. Finally, check the
Is Triggerproperty so that the collision engine will turn the collider into a trigger, which will be able to run code events when it is hit, but will not prevent the player from moving:
Like I mentioned briefly before, this trigger will be used to tell the game that our player has finished walking over this tile. This is positioned past the tile due to the fact that we want to still see tiles until they pass what the camera can see. We'll tell the engine to remove this tile from the game, but we will dive more into that later on in the chapter.
- Now that we have all of the objects created, we want to group our objects together as one piece that we can create duplicates of. To do this, let's create an
Empty Game Object by going to
GameObject |Â
Create Empty and name the newly created object toÂ
Basic Tile.Â
- Then, go to the
Hierarchywindow and drag and drop the
Floor,
Tile End,
Left Wall, and
Right Wallobjects on top of it to make them children of the
Basic Tileobject.Â
- Currently, the camera can see the start of the tiles, so to fix that, let's set the
Basic Tile'sÂ
Position toÂ
(0, 0, -5)Â so that the entire tile will shift back.
- Finally, we will need to know at what position we should spawn the next piece, so create another child of
Basic Tile, give it the name,Â
Next Spawn Point, and set its
Positionto
(0, 0, 5).
Note
Note that when we modify an object that has a parent, the position is relative to the parent, not its world position.
Notice that the spawn point is on the edge of our current title. Now we have a single tile that is fully completed. Instead of duplicating this a number of times by hand, we will make use of Unity's concept or prefabs.
Prefabs, or prefabricated objects, are blueprints of game objects and components that we can turn into files, which can be duplicates. There are other interesting features that prefabs have, but we will discuss them as we make use of them.
- From the
Projectwindow, go to the
Assetsfolder and then create a new folder called
Prefabs. Then, drag and drop the
Basic Tileobject from the
Hierarchywindow to the
Projectwindow inside the
Prefabsfolder. If the text on the
Basic Tilename in the
Hierarchywindow becomes blue, we will know that it was made correctly:
With that, we now have a tile prefab that we can create duplicates of the tile through code to extend our environment.
Now that we have a foundation, let's now make it so that we can continue running instead of stopping after a short time:
- To start off with, we have our prefab, so we can delete the original
Basic Tilein the
Hierarchywindow by selecting it and then pressing the Delete key.
- We need to have a place to create all of these tiles and potentially manage information for the game, such as the player's score. In Unity, this is typically referred to as a
GameController. From the
Projectwindow, go to the
Scriptsfolder and create a new C# script called
GameController.
- Open the script in your IDE, and use the following code:
using UnityEngine; /// <summary> /// Controls the main gameplay /// </summary> public class GameController : MonoBehaviour { [Tooltip("A reference to the tile we want to spawn")] public Transform tile; [Tooltip("Where the first tile should be placed at")] public Vector3 startPoint = new Vector3(0, 0, -5); [Tooltip("How many tiles should we create in advance")] [Range(1, 15)] public int initSpawnNum = 10; /// (); } } /// <summary> /// Will spawn a tile at a certain location and setup the next position /// </summary> public void SpawnNextTile() { var newTile = Instantiate(tile, nextTileLocation, nextTileRotation); // Figure out where and at what rotation we should spawn // the next item var nextTile = newTile.Find("Next Spawn Point"); nextTileLocation = nextTile.position; nextTileRotation = nextTile.rotation; } }
This script will spawn a number of tiles, one after another, based on the
tile and
initSpawnNum properties.
- Save your script and dive back into Unity. From there, create a new
Emptygame object and name it
Game Controller. Drag and drop it to the top of the
Hierarchywindow. For clarity's sake, go ahead and reset the position if you want to. Then, attach the
Game Controllerscript to the object and then set the
Tileproperty by dragging and dropping the
Basic Tileprefab from the
Projectwindow into the
Tileslot:
- Save your scene and run the project:
Great, but now we will need to create new objects after these, but we don't want to spawn a crazy number of these at once. It's better that once we reach the end of a tile, we create a new tile and remove it. We'll work on optimizing this more later, but that way we always have around the same number of tiles in the game at one time.
- Go into the
Projectwindow and create a new script called
TileEndBehaviour, using the following code:
using UnityEngine; /// <summary> /// Handles spawning a new tile and destroying this one /// upon the player reaching the end /// </summary> public class TileEndBehaviour : MonoBehaviour { [Tooltip("How much time to wait before destroying " + "the tile after reaching the end")] public float destroyTime = 1.5f; void OnTriggerEnter(Collider col) { // First check if we collided with the player if (col.gameObject.GetComponent<PlayerBehaviour>()) { // If we did, spawn a new tile GameObject.FindObjectOfType<GameController>().SpawnNextTile(); // And destroy this entire tile after a short delay Destroy(transform.parent.gameObject, destroyTime); } } }
- Now, to assign it to the prefab, we can go to the
Projectwindow and then go into the
Prefabsfolder. From there, click on the arrow beside the
Basic Tileto open up its objects and then add a
Tile End Behaviourcomponent to the
Tile Endobject:
- Save your scene and play.
You'll note now that as the player continues to move, new tiles will spawn as you continue; if you switch to the
Scene tab while playing, you'll see that as the ball passes the tiles they will destroy themselves:
It's great that we have some basic tiles, but it's a good idea to give the player something to do or, in our case, something to avoid. In this section, you'll learn how to customize your tiles to add obstacles for your player to avoid:
- So, just like we created a prefab for our basic tile, we will create a single obstacle through code. I want to make it easy to see what the obstacle will look like in the world and make sure that it's not too large, so I'll drag and drop a
Basic Tileprefab back into the world.
- Next, we will create a cube by going to
GameObject|
3D Object|
Cube. We will then name this object
Obstacle. Change the
Y Scaleto
2and position it above the platform at
(0, 1, .025):
- We can then play the game to see how this'll work:
- As you can see in the preceding screenshot, the player gets stopped, but nothing really happens. In this instance, we want the player to lose when he hits this and then restart the game; so, to do that, we'll need to write a script. From the
Projectwindow, go to the
Scriptsfolder and create a new script called
ObstacleBehaviour. We'll use the following code:
using UnityEngine; using UnityEngine.SceneManagement; // LoadScene public class ObstacleBehaviour : MonoBehaviour { [Tooltip("How long to wait before restarting the game")] public float waitTime = 2.0f; void OnCollisionEnter(Collision collision) { // First check if we collided with the player if (collision.gameObject.GetComponent<PlayerBehaviour>()) { // Destroy the player Destroy(collision.gameObject); // Call the function ResetGame after waitTime has passed Invoke("ResetGame", waitTime); } } /// <summary> /// Will restart the currently loaded level /// </summary> void ResetGame() { // Restarts the current level SceneManager.LoadScene(SceneManager.GetActiveScene().name); } }
- Save the script and return to the editor, attaching the script to the
Obstacleproperty we just created.
- Save your scene and try the game:
As you can see in the preceding screenshot, once we hit the obstacle, the player gets destroyed, and then after a few seconds, the game starts up again. You'll learn to use particle systems and other things to polish this up, but at this point, it's functional, which is what we want.
You may note that when the level is reloaded, there are some lighting issues in the editor. The game will still work correctly when exported, but this may be a minor annoyance.
- (Optional) To fix this, go to
Window|
Lighting|
Settings. Uncheck the
Auto Generate option from there, and click on--once it is finished, our issue should be solved.
Generate Lighting
Note
It isn't an issue with our game, but if you employ the fix above in your own titles, you must remember to go here every time you alter a game level and rebuild the lightmap for it to be updated correctly.
- Now that we know it works correctly, we can make it a prefab. Just as we did with the original tile, go ahead and drag and drop it from the
Hierarchyinto the
Projecttab and into the
Prefabsfolder:
- Next, we will remove the
Obstacle, as we'll spawn it upon creating the tile.
- We will make markers to indicate where we would possibly like to spawn our obstacles. Duplicate the
Next Spawn Objectobject and move the new one to
(0, 1, 4). We will then rename the object asÂ
Center. Afterwards, click on the icon on the top left of the blue box and then select the blue color. Upon doing this, you'll see that we can see the text inside the editor, if we are close to the object (but it won't show up in the
Gametab by default):
- We want a way to get all of the potential spawn points we will want in case we decide to extend the project in the future, so we will assign a tag as a reference to make those objects easier to find. To do that at the top of the
Inspectorwindow, click on the tag dropdown and select
Add Tag. From the menu that pops up, press the + button and then name itÂ
ObstacleSpawn.
Note
For more information on tags and why we'd want to use them, check outÂ.
- Go ahead and duplicate this twice and name the others
Leftand
Right, respectively, moving them 2 units to the left and right of the center to become other possible obstacle points:
- Note that these changes don't affect the original prefab, by default; that's why the objects are currently black text. To make this happen, selectÂ
Basic Tile, and then in the
Inspectorwindow under the
Prefabsection, click on
Apply.
- Now that the prefab is set up correctly, we can go ahead and remove it by selecting it and pressing Delete.
- We then need to go into the
GameControllerscript and modify it to have the following code:
using UnityEngine; using System.Collections.Generic; // List /// <summary> /// Controls the main gameplay /// </summary> public class GameController : MonoBehaviour { [Tooltip("A reference to the tile we want to spawn")] public Transform tile; [Tooltip("A reference to the obstacle we want to spawn")] public Transform obstacle; [Tooltip("Where the first tile should be placed at")] public Vector3 startPoint = new Vector3(0, 0, -5); [Tooltip("How many tiles should we create in advance")] [Range(1, 15)] public int initSpawnNum = 10; [Tooltip("How many tiles to spawn initially with no obstacles")] public int initNoObstacles = 4; /// (i >= initNoObstacles); } } /// <summary> /// Will spawn a tile at a certain location and setup the next position /// </summary> public void SpawnNextTile(bool spawnObstacles = true) { var newTile = Instantiate(tile, nextTileLocation, nextTileRotation); // Figure out where and at what rotation we should spawn // the next item var nextTile = newTile.Find("Next Spawn Point"); nextTileLocation = nextTile.position; nextTileRotation = nextTile.rotation; if (!spawnObstacles) return; // Now we need to get all of the possible places to spawn the // obstacle var obstacleSpawnPoints = new List<GameObject>(); // Go through each of the child game objects in our tile foreach (Transform child in newTile) { // If it has the ObstacleSpawn tag if (child.CompareTag("ObstacleSpawn")) { // We add it as a possibilty obstacleSpawnPoints.Add(child.gameObject); } } // Make sure there is at least one if (obstacleSpawnPoints.Count > 0) { // Get a random object from the ones we have var spawnPoint = obstacleSpawnPoints[Random.Range(0, obstacleSpawnPoints.Count)]; // Store its position for us to use var spawnPos = spawnPoint.transform.position; // Create our obstacle var newObstacle = Instantiate(obstacle, spawnPos, Quaternion.identity); // Have it parented to the tile newObstacle.SetParent(spawnPoint.transform); } } }
Note that we modified the
SpawnNextTile function to now have a default parameter set to
true, which will tell us if we want to spawn obstacles or not. At the beginning of the game, we may not want the player to have to start dodging immediately, but we can tweak the value to increase or decrease the number we are using.
- Save the script and go back to the Unity editor. Then, assign the
Obstaclevariable in the
Inspectorwith the obstacle prefab we created previously.
- It's a bit hard to see things currently due to the default light settings, so let's go to the
Hierarchywindow and select the
Directional Lightobject.
A directional light acts similarly to how the sun works on earth, shining everywhere from a certain rotation.
- With the default settings the light is too bright, making it difficult to see, so we can just change the
Colorto be darker. I used the following:
- Save your scene and play the game:
Note
For more information on directional lights and the other lighting types that Unity has, check out:Â.
As you can see in the preceding screenshot, we now have a number of obstacles for our player to avoid, and due to how the player works, he will gradually get faster and faster, causing the game to increase in difficulty over time.
There we have it! A solid foundation, but just that, a foundation. However, that being said, we covered a lot of content in this chapter. We discussed how to create a new project in Unity, we built a player that will move continuously, as well as take inputs to move horizontally. We then discussed how we can use Unity's attributes and XML comments to improve our code quality and help us when working with teams. We also covered how to have a moving camera. We created a tile-based level design system, where we created new tiles as the game continued, randomly spawning obstacles for the player to avoid.
Throughout this book, we will explore more that we can do to improve this project and polish it, while adapting it to being the best experience possible on mobile platforms. However, before we get to that, we'll actually need to figure out how to deploy our projects. | https://www.packtpub.com/product/unity-2017-mobile-game-development/9781787288713 | CC-MAIN-2020-40 | refinedweb | 6,285 | 63.83 |
So I'll start off by writing that I am new to this site (today), as well as to the Ruby programming language (3 days ago), so don't feel afraid to rip apart my code--I am trying to learn and get better.
Basically.. I am creating a console calculator that is able to read a simple math problem (or string of math problems) from the user and solve the equation. It doesn't use order of operations or anything fancy (yet) and it is basically working except for this one weird bug I can't figure out.
Userinput = "1 + 2 + 3 - 4"
# First I split the user input into an array of stirngs and then loop over the
# array of strings and depict whether a string is a key or hash (see code below)
# program should store these characters in a hash like so..
hash = { nil=>1, "+"=>2, "+"=>3, "-"=>4 }
Type a math problem (ex. 40 / 5): 40 / 5 + 2 - 5 * 5 - 5 * 5 - 100
-450
{nil=>40, "/"=>5, "+"=>2, "-"=>100, "*"=>5}
Type a math problem (ex. 40 / 5): 1 + 2 - 0 + 3
4
{nil=>1, "+"=>3, "-"=>0}
Type a math problem (ex. 40 / 5): 10 - 5 * 2 + 8 + 2
12
{nil=>10, "-"=>5, "*"=>2, "+"=>2}
=begin
main.rb
Version 1.0
Written by Alex Hail - 10/16/2016
Parses a basic, user-entered arithmetic equation and solves it
=end
@operationsParser = "" # global parser
@lastKeyAdded = ""
private
def appointType(sv)
if sv =~ /\d/
sv.to_i
else
sv
end
end
private
def operate(operations)
sum = 0
operations.each do |k, v|
if k.nil?
sum += v
else
case k
when '+' then sum += v
when '-' then sum -= v
when '*' then sum = sum * v
when '/' then sum = sum / v
else
end
end
end
sum
end
private
def solveEquation
print "Type a math problem (ex. 40 / 5): "
userInput = gets.chomp
#array to hold all numbers and their cooresponding operation
operations = {} # <== Empty hash
#split the user input via spaces
@operationsParser = userInput.split(" ")
#convert numbers into numbers store operators in hash ( nil => 40, "/" => 5) -- would be 40 / 5
@operationsParser.each do |stringValue|
if appointType(stringValue).is_a? Integer
operations[@lastKeyAdded != "" ? @lastKeyAdded : nil] = appointType(stringValue)
else #appointType will return a string by default
keyToAdd = appointType(stringValue)
@lastKeyAdded = keyToAdd
end
end
#check if operators(+, *, -, /, or nil) in the keys are valid, if not, error and exit, if so, operate
operations.each do |k,v|
case k
when '+'
when '-'
when '*'
when '/'
when nil
else
# Exit the program if we have an invalid operator in the hash
puts "Exiting program with error - Invalid operator used (Only +, -, *, / please)"
return
end
end
sum = operate(operations)
puts sum, operations
end
solveEquation
Ok so the problem is the data structure that you chose, a hash by definition has to always maintain a set of unique keys to map to its values. Now something you could try if you are dead set on using a hash is mapping all the keys to empty arrays then add numerical values to that then process that operation on every value in it respective array(since you are ignoring order of operations any way)
h = Hash.new([]) #to set the default value of each key to an empty arrary
then when you process your array it should look like this
{nil =>[1], '+' => [1, 2, 3], '-' => [3, 7], '*' => [4, 47], '/' => [3, 5]} | https://codedump.io/share/vt1erIcAnh2M/1/ruby-calculator---hash-not-storing-correctly | CC-MAIN-2017-17 | refinedweb | 551 | 63.32 |
LONDON (ICIS)--Petrochemical firms are showing little buying interest in propane cargoes despite falling prices, sources said Friday.?xml:namespace>
The propane-naphtha spread has widened to -$105/tonne, but buyers are preferring lower-priced ethylene as the feedstock of price.
“Even at propane-naphtha around -100, [there is] still no sign of increased interest from petchems. That’s again being explained that since ethylene prices remain low propane is not the preferred feedstock,” said one shipbroker.
A petrochemical buyer added: “There’s no demand. from petchems because of the downstream margins. Propylene is much stronger than ethylene so everybody is looking at heavier feedstock.” | http://www.icis.com/resources/news/2014/02/07/9751482/petchems-snub-propane-despite-falling-prices/ | CC-MAIN-2016-18 | refinedweb | 105 | 57.57 |
Typecasting is a way to convert variables, constants or expression from one type to another type. Conversion from one type to another is often required in programming.
Consider a case where you want to find average of three numbers. Let us write a program to find average of three numbers.
#include <stdio.h> int main() { int num1, num2, num3; float average; num1 = 91; num2 = 85; num3 = 83; average = (num1 + num2 + num3) / 3; printf("Average = %f", average); return 0; }
Average of 91, 85 and 83 is 86.33. But our program shows 86. What's wrong going here? Is the C compiler gone mad? Why it is not showing exact average? I have also used
float data type that is capable of storing real types.
It's not the compilers fault. In the expression
(num1 + num2 + num3) / 3, all variables and literals are integer type. Hence, integer division is performed instead of float division.
To ensure fractional division, we must typecast one of the operands to
float. In the expression
(float) (num1 + num2 + num3) / 3. Parenthesis and typecast operator has highest precedence. Hence, first sum of
num1 + num2 + num3 is evaluated and converted to
float type. Then after division is performed.
So to overcome the above integer division, we must typecast the expression to
float type.
C supports two types of typecasting -
Implicit typecasting
Implicit typecast is automatic type conversion done by the compiler. Compiler automatically handles data type conversion. It converts variables and constants of lower type to higher type whenever required.
The automatic type conversion done by the compiler uses integer promotion rule.
Integer promotion
Compilers are smart at optimizing code for better performance. In the process of code optimization, the C compiler will perform integer promotion. The compiler automatically converts all operands to a common type (higher type used in expression). The process of converting a lower type to higher is known as integer promotion.
Example of implicit typecast
#include <stdio.h> int main() { char ch = 'A'; int val = ch + 10; /* char ch is promoted to int before addition */ printf("val = %d", val); return 0; }
In the above program
char is automatically converted to higher type
int before performing addition.
Important note: Implicit conversion may result in data or sign loss. For example - when promoting
long long to
unsigned long long negative sign is lost. Also while promoting
unsigned long long to
float you may lose data.
Hence, it is often recommended to cast explicitly.
Explicit typecasting
Explicit typecasting is manual type conversion from one type to another type. In explicit cast we have full control over the conversion. Explicit conversion can be performed bi-directional i.e. you can cast both a lower type to higher as well as a higher type to lower.
Syntax of explicit typecast
(new-type) <variable-expression-literal>
Where
new-type is a valid C data type.
Read more - List of all valid C primitive and derived data type
Example of explicit typecast
#include <stdio.h> int main() { int num1, num2, num3; float average; num1 = 91; num2 = 85; num3 = 83; average = (float)(num1 + num2 + num3) / 3; printf("Average = %f", average); return 0; }
Important note: Explicit typecasting can also result in data loss. Conversion from
float to
int will lose decimal part.
<pre><code> ----Your Source Code---- </code></pre> | http://codeforwin.org/2017/08/typecasting-c-programming.html | CC-MAIN-2017-47 | refinedweb | 546 | 58.69 |
I have a problem with a task for school. I want my last method to test if two rectangles are the same. The only problem there is that I can't seem to differentiate between the two different heights, widiths and the different point(this is the left-low corner point of the rectangle) of the two different rectangles, any advice?
Thanks a lot
class Point():
def __init__(self,x,y):
self.x=x
self.y=y
class Rectangle():
def __init__(self,Point,w,h):
self.Point=Point
self.widith=w**strong text**
self.height=h
def same(self,Rectangle):
if Rectangle.self.Point==self.Point and Rectangle.self.widith==self.widith and Rectangle.self.height==self.height:
return True
else:
return False
First of all don't use the same name for function params and classes. It makes the code confusing and error prone. Try this:
class Rectangle: def __init__(self, point, width, height): self.point = point self.widith = width self.height = height
Now I assume that
point variable is an instance of
Point class. In that case comparing one point to another via
== will fail, because by default
== checks if two objects are the same in the sense of being the same object in memory.
Thus your implemenatation of
same method may look like this:
def same(self, other): return ( self.point.x == other.point.x and self.point.y == other.point.y and self.width == other.width and self.height == other.height )
If you overwrite builtin
__eq__ method (which is responsible for the behaviour of
== operator) on
Point class like this:
class Point: def __init__(self, x, y): self.x = x self.y = y def __eq__(self, other): return self.x == other.x and self.y == other.y
then
same method can be simplified to:
def same(self, other): return ( self.point == other.point # now __eq__ will be called here and self.width == other.width and self.height == other.height ) | https://codedump.io/share/KKTlhspC9Ieh/1/python-how-can-i-differentiate-between-two-variables-of-two-different-objects-of-the-same-class | CC-MAIN-2017-26 | refinedweb | 323 | 70.39 |
SQLAlchemy ships with a connection pooling framework that integrates with the Engine system and can also be used on its own to manage plain DB-API connections.
At the base of any database helper library is a system group or “pool” of active database connections which are reused from request to request in a single server process..
Pool instances may be created directly for your own use or to supply to sqlalchemy.create_engine() via the pool= keyword argument.
Constructing your own pool requires supplying a callable function the Pool can use to create new connections. The function will be called with no arguments.
Through this method, custom connection schemes can be made, such as a using connections from another library’s pool, or making a new connection that automatically executes some initialization commands:)
Or with SingletonThreadPool:
import sqlalchemy.pool as pool import sqlite p = pool.SingletonThreadPool(lambda: sqlite.connect(filename='myfile.db'))
Bases: sqlalchemy.pool.Pool
A Pool that allows at most one checked out connection at any given time.
This will raise an exception if more than one connection is checked out at a time. Useful for debugging code that is using more connections than desired..
Bases: sqlalchemy.log.Identified
Abstract base class for connection pools.
Construct a Pool.
Add a PoolListener-like object to this pool.
listener may be an object that implements some or all of PoolListener, or a dictionary of callables containing implementations of some or all of the named methods in PoolListener.
Dispose of this pool.
This method leaves the possibility of checked-out connections remaining open, It is advised to not reuse the pool once dispose() is called, and to instead use a new pool constructed by the recreate() method.
Bases: sqlalchemy.pool.Pool
A Pool that imposes a limit on the number of open connections.
Construct a QueuePool..
Remove all current DB-API 2.0 managers.
All pools and connections are disposed. | https://codepowered.com/manuals/SQLAlchemy-0.6.1-doc/html/reference/sqlalchemy/pooling.html | CC-MAIN-2022-33 | refinedweb | 319 | 57.67 |
AWS Open Source Blog
Using a Network Load Balancer with the NGINX Ingress Controller on Amazon EKS
Kubernetes Ingress is an API object that provides a collection of routing rules that govern how external/internal users access Kubernetes services running in a cluster. An ingress controller is responsible for reading the ingress resource information and processing it appropriately. As there are different ingress controllers that can do this job, it’s important to choose the right one for the type of traffic and load coming into your Kubernetes cluster. In this post, we will discuss how to use an NGINX ingress controller on Amazon EKS, and how to front-face it with a Network Load Balancer (NLB).
What is a Network Load Balancer?
An AWS.
Exposing your application on Kubernetes
In Kubernetes, these are several different ways to expose your application; using Ingress to expose your service is one way of doing it. Ingress is not a service type, but it acts as the entry point for your cluster. It lets you consolidate your routing rules into a single resource, as it can expose multiple services under the same IP address.
This post will explain how to use an ingress resource and front it with a NLB (Network Load Balancer), with an example.
Ingress in Kubernetes
Kubernetes supports a high-level abstraction called Ingress, which allows simple host- or URL-based HTTP routing. An Ingress is a core concept (in beta).
Typically, your Kubernetes services will impose additional requirements on your ingress. Examples of this include:
- Content-based routing: e.g., routing based on HTTP method, request headers, or other properties of the specific request.
- Resilience: e.g., rate limiting, timeouts.
- Support for multiple protocols: e.g., WebSockets or gRPC.
- Authentication.
An ingress controller is a DaemonSet or Deployment, deployed as a Kubernetes Pod, that watches the endpoint of the API server for updates to the Ingress resource. Its job is to satisfy requests for Ingresses. NGINX ingress is one such implementation. This blog post implements the ingress controller as a Deployment with the default values. To suit your use case and for more availability, you can use it as a DaemonSet or increase the replica count.
Why would I choose the NGINX ingress controller over the Application Load Balancer (ALB) ingress controller?
The ALB ingress controller is great, but there are certain use cases where the NLB with the NGINX ingress controller will be a better fit. I will discuss scenarios where you would need a NLB over the ALB later in this post, but first let’s discuss the ingress controllers.
By default, the NGINX Ingress controller will listen to all the ingress events from all the namespaces and add corresponding directives and rules into the NGINX configuration file. This makes it possible to use a centralized routing file which includes all the ingress rules, hosts, and paths.
With the NGINX Ingress controller you can also have multiple ingress objects for multiple environments or namespaces with the same network load balancer; with the ALB, each ingress object requires a new load balancer.
Furthermore, features like path-based routing can be added to the NLB when used with the NGINX ingress controller.
Why do I need a load balancer in front of an ingress?
Ingress is tightly integrated into Kubernetes, meaning that your existing workflows around
kubectl will likely extend nicely to managing ingress. An Ingress controller does not typically eliminate the need for an external load balancer , it simply adds an additional layer of routing and control behind the load balancer.
Pods and nodes are not guaranteed to live for the whole lifetime that the user intends: pods are ephemeral and vulnerable to kill signals from Kubernetes during occasions such as:
- Scaling.
- Memory or CPU saturation.
- Rescheduling for more efficient resource use.
- Downtime due to outside factors.
The load balancer (Kubernetes service) is a construct that stands as a single, fixed-service endpoint for a given set of pods or worker nodes. To take advantage of the previously-discussed benefits of a Network Load Balancer (NLB), we create a Kubernetes service of
type:loadbalancer with the NLB annotations, and this load balancer sits in front of the ingress controller – which is itself a pod or a set of pods. In AWS, for a set of EC2 compute instances managed by an Autoscaling Group, there should be a load balancer that acts as both a fixed referable address and a load balancing mechanism.
Ingress with load balancer
The diagram above shows a Network Load Balancer in front of the Ingress resource. This load balancer will route traffic to a Kubernetes service (or Ingress) on your cluster that will perform service-specific routing. NLB with the Ingress definition provides the benefits of both a NLB and an Ingress resource.
What advantages does the NLB have over the Application Load Balancer (ALB)?
A Network Load Balancer is capable of handling millions of requests per second while maintaining ultra-low latencies, making it ideal for load balancing TCP traffic. NLB is optimized to handle sudden and volatile traffic patterns while using a single static IP address per Availability Zone. The benefits of using a NLB are:
- Static IP/elastic IP addresses: For each Availability Zone (AZ) you enable on the NLB, you have a network interface. Each load balancer node in the AZ uses this network interface to get a static IP address. You can also use Elastic IP to assign a fixed IP address for each Availability Zone.
- Scalability: Ability to handle volatile workloads and scale to millions of requests per second.
- Zonal isolation: The Network Load Balancer can be used for application architectures within a Single Zone. Network Load Balancers attempt to route a series of requests from a particular source to targets in a single AZ while still providing automatic failover should those targets become unavailable.
- Source/remote address preservation: With a Network Load Balancer, the original source IP address and source ports for the incoming connections remain unmodified. With Classic and Application load balancers, we had to use HTTP header X-Forwarded-For to get the remote IP address.
- Long-lived TCP connections: Network Load Balancer supports long-running TCP connections that can be open for months or years, making it ideal for WebSocket-type applications, IoT, gaming, and messaging applications.
- Reduced bandwidth usage: Most applications are bandwidth-bound and should see a cost reduction (for load balancing) of about 25% compared to Application or Classic Load Balancers.
- SSL termination: SSL termination will need to happen at the backend, since SSL termination on NLB for Kubernetes is not yet available.
For any NLB usage, the backend security groups control the access to the application (NLB does not have security groups of it own). The worker node security group handles the security for inbound/ outbound traffic.
How to use a Network Load Balancer with the NGINX Ingress resource in Kubernetes
Start by creating the mandatory resources for NGINX Ingress in your cluster:
$ kubectl apply -f
The above manifest file also launches the Network Load Balancer(NLB).
Now create two services (apple.yaml and banana.yaml) to demonstrate how the Ingress routes our request. We’ll run two web applications that each output a slightly different response. Each of the files below has a service definition and a pod definition.
Create the resources:
$ kubectl apply -f
$ kubectl apply -f
Defining the Ingress resource (with SSL termination) to route traffic to the services created above
If you’ve purchased and configured a custom domain name for your server, you can use that certificate, otherwise you can still use SSL with a self-signed certificate for development and testing.
In this example, where we are terminating SSL on the backend, we will create a self-signed certificate.
Anytime we reference a TLS secret, we mean a PEM-encoded X.509, RSA (2048) secret. Now generate a self-signed certificate and private key with:
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout
tls.key -out tls.crt -subj "/CN=anthonycornell.com/O=anthonycornell.com"
Then create the secret in the cluster:
kubectl create secret tls tls-secret --key tls.key --cert tls.crt
Now declare an Ingress to route requests to
/apple to the first service, and requests to
/banana to second service. Check out the Ingress’
rules field that declares how requests are passed along:
apiVersion: extensions/v1beta1 kind: Ingress metadata: name: example-ingress annotations: nginx.ingress.kubernetes.io/ssl-redirect: "false" nginx.ingress.kubernetes.io/force-ssl-redirect: "false" nginx.ingress.kubernetes.io/rewrite-target: / spec: tls: - hosts: - anthonycornell.com secretName: tls-secret rules: - host: anthonycornell.com http: paths: - path: /apple backend: serviceName: apple-service servicePort: 5678 - path: /banana backend: serviceName: banana-service servicePort: 5678
Create the Ingress in the cluster:
kubectl create -f
Set up Route 53 to have your domain pointed to the NLB (optional):
anthonycornell.com. A.
ALIAS abf3d14967d6511e9903d12aa583c79b-e3b2965682e9fbde.elb.us-east-1.amazonaws.com
Test your application:
curl -k
Banana
curl -k
Apple
Can I reuse a NLB with services running in different namespaces? In the same namespace?
Install the NGINX ingress controller as explained above. In each of your namespaces, define an Ingress Resource.
Example for test:
apiVersion: extensions/v1beta1 kind: Ingress metadata: name: api-ingresse-test namespace: test annotations: kubernetes.io/ingress.class: "nginx" spec: rules: - host: test.anthonycornell.com http: paths: - backend: serviceName: myApp servicePort: 80 path: /
Suppose we have three namespaces – Test, Demo, and Staging. After creating the Ingress resource in each namespace, the NGINX ingress controller will process those resources as shown below:
Cleanup
Delete the Ingress resource:
kubectl delete -f
Delete the Secret:
kubectl delete secret tls-secret rm tls.crt tls.key
Delete the services:
kubectl delete -f
kubectl delete -f
Delete the NGINX ingress controller:
kubectl delete -f
We hope this post was useful! Please let us know in the comments. | https://aws.amazon.com/blogs/opensource/network-load-balancer-nginx-ingress-controller-eks/ | CC-MAIN-2021-17 | refinedweb | 1,645 | 53.92 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.