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 |
|---|---|---|---|---|---|
The article explains the background and usage of recursion in C#. It illustrates the usage of recursion to iterate though the file system in a specified folder / drive. Most beginners in programming are confused with the usage of recursion and therefore here I am trying to explain it in an easy way with a simple usable code. The advantage of this code snippet is that it can be used in any other project if the users are dealing with file system. In part 2 and 3, I will explain how to extend the same code to write the output in a file and read from it, and also how to search the file based on specific criteria.
Before I explain how to use recursion in C#, it's really important to give some background information about recursion and why it's important.
Basically, in simple terms, recursion is a function that calls itself iteratively until it reaches a stopping point. In another words, recursion is a common method of simplification to divide a problem into sub-problems of the same type. As a computer programming technique, this is called "divide and conquer" and is key to the design of many important algorithms particularly in Arterial Intelligence programming.
The file system is a very good example of recursive programming. Let us say we want to iterate through all the files in all the folders under C:\Program Files\Adobe\Acrobat 5.0 folder as in the above image, the following definition is correct:
ENU has some files and has a parent folder which is HELP. Similarly, HELP has some files and has a parent folder which is Acrobat 5.0 and so on until it reaches the target folder of C:\Program Files\Adobe\Acrobat 5.0. And it could be correct the other way around, i.e. C:\Program Files\Adobe\Acrobat 5.0 has some files and a child folder, Acrobat 5.0 has some files and a child folder until it reaches the final child ENU.
Therefore, if we write down the code to iterate though one of these folders and its files and call it repeatedly, then we have solved the problem. In other words, we are dividing the Bigger Problem of iterating through the Adobe folder to sub-problems which is just iterating through a single folder and calling it iteratively and the problem is resolved.
Basically it is defining a problem in the form of itself and calling it repeatedly. However the important point to notice is that there should be a Stopping Point or 'End Condition'.
Enough of the theory. Now let us have a look at some actual C# code.
namespace Recursion
{
class IterateFolders
{
public static void Main(string[] args)
{
//Create a Directory object using DirectoryInfo
DirectoryInfo dir =
new DirectoryInfo(@"C:\Program Files\Adobe\Acrobat 5.0");
//Pass the Directory for displaying the contents
getDirsFiles(dir);
}
//this is the recursive function
public static void getDirsFiles(DirectoryInfo d)
{
//create an array of files using FileInfo object
FileInfo [] files;
//get all files for the current directory
files = d.GetFiles("*.*");
//iterate through the directory and print the files
foreach (FileInfo file in files)
{
//get details of each file using file object
String fileName = file.FullName;
String fileSize = file.Length.ToString();
String fileExtension =file.Extension;
String fileCreated = file.LastWriteTime.ToString();
io.WriteLine(fileName + " " + fileSize +
" " + fileExtension + " " + fileCreated);
}
//get sub-folders for the current directory
DirectoryInfo [] dirs = d.GetDirectories("*.*");
//This is the code that calls
//the getDirsFiles (calls itself recursively)
//This is also the stopping point
//(End Condition) for this recursion function
//as it loops through until
//reaches the child folder and then stops.
foreach (DirectoryInfo dir in dirs)
{
io.WriteLine("--------->> {0} ", dir.Name);
getDirsFiles(dir);
}
}
}
}
The output will show all folders for the specified folder and list the details of each file including full path, size, extension and date created.
This is the Part 1 of the 3 part series tutorial about recursion and the file system. Part 2 will show how to extend the same code to save the output of this program in a text file and then read from it. And finally in Part 3, I will extend the functionality to search a text file based on specific criteria and find files. By a bit more effort the same code can be used to write a CD / DVD Catalogue utility which can catalogue CDs/DVDs and then search through the code for specific files.
Part I of a three part series, posted on Sat 14th May. | http://www.codeproject.com/Articles/10409/Recursion-using-C?msg=4139984 | CC-MAIN-2015-22 | refinedweb | 751 | 53.51 |
Many web applications require users to sign in and out in order to perform important tasks (like administration duties). In this article, we'll create an authentication system for our application.
In the previous article, we built a contact page using the Flask-WTF and Flask-Mail extensions. We'll use Flask-WTF, once again, this time to validate a user's username and password. We'll save these credentials into a database using yet another extension called Flask-SQLAlchemy.
You can find the source code for this tutorial on GitHub. While following along with this tutorial, when you see a caption, such as
Checkpoint: 13_packaged_app, it means that you can switch to the GIT branch named "13_packaged_app" and review the code at that point in the article.
Growing the Application
So far, our Flask app is a fairly simple application. It consists of mostly static pages; so, we've been able to organize it as a Python module. But now, we need to reorganize our application to make it easier to maintain and grow. The Flask documentation recommends that we reorganize the app as a Python package, so let's start there.
Our app is currently organized like this:
flaskapp/ └── app/ ├── static/ ├── templates/ ├── forms.py ├── routes.py └── README.md
To restructure it as a package, let's first create a new folder inside
app/ named
intro_to_flask/. Then move
static/,
templates/,
forms.py and
routes.py into
intro_to_flask/. Also, delete any .pyc files that are hanging around.
flaskapp/ └── app/ ├── intro_to_flask/ │ ├── static/ │ ├── templates/ │ ├── forms.py │ ├── routes.py └── README.md
Next, create a new file named
__init__.py and place it inside
intro_to_flask/. This file is required to make Python treat the
intro_to_flask/ folder as a package.
flaskapp/ └── app/ ├── intro_to_flask/ │ ├── __init__.py │ ├── static/ │ ├── templates/ │ ├── forms.py │ ├── routes.py └── README.md
When our app was a Python module, the application-wide imports and configurations were specified in
routes.py. Now that the app is a Python package, we'll move these settings from
routes.py into
__init__.py.
app/intro_to_flask/__init__.py
from flask import Flask app = Flask(__name__) app.secret_key = 'development key' app.config["MAIL_SERVER"] = "smtp.gmail.com" app.config["MAIL_PORT"] = 465 app.config["MAIL_USE_SSL"] = True app.config["MAIL_USERNAME"] = 'contact@example.com' app.config["MAIL_PASSWORD"] = 'your-password' from routes import mail mail.init_app(app) import intro_to_flask.routes
The top of
routes.py now looks like this:
app/intro_to_flask/routes.py
from intro_to_flask import app from flask import render_template, request, flash from forms import ContactForm from flask.ext.mail import Message, Mail mail = Mail() . . . # @app.route() mappings start here
We previously had
app.run() inside of
routes.py, which allowed us to type
$ python routes.py to run the application. Since the app is now organized as a package, we need to employ a different strategy. The Flask docs recommend adding a new file named
runserver.py and placing it inside
app/. Let's do that now:
flaskapp/ └── app/ ├── intro_to_flask/ │ ├── __init__.py │ ├── static/ │ ├── templates/ │ ├── forms.py │ ├── routes.py ├── runserver.py └── README.md
Now take the
app.run() call from
routes.py and place it inside of
runserver.py.
app/runserver.py
from intro_to_flask import app app.run(debug=True)
Now you can type
$ python runserver.py and view the app in the browser. From the top, here's how you'll enter your development environment and run the app:
$ cd flaskapp/ $ . bin/activate $ cd app/ $ python runserver.py
The app is now organized as a package, we're ready to move on and install a database to manage user credentials.
—
Checkpoint: 13_packaged_app —
Flask-SQLAlchemy
We'll use MySQL for our database engine and the Flask-SQLAlchemy extension to manage all of the database interaction.
Flask-SQLAlchemy uses Python objects instead of SQL statements to query the database. For example, instead of writing
SELECT * FROM users WHERE firstname = "lalith", you would write
User.query.filter_by(username="lalith").first().
The moral of this aside is to not completely rely on, or abandon a database abstraction layer like Flask-SQLAlchemy, but to be aware of it, so that you can determine when it's useful for your needs.
But why can't we just write raw SQL statements? What's the point of using this weird syntax? As with most things, using Flask-SQLAlchemy, or any database abstraction layer, depends on your needs and preferences. Using Flask-SQLAlchemy allows you to work with your database by writing Python code instead of SQL. This way you don't have SQL statements scattered amidst your Python code, and that's a good thing, from a code quality perspective.
Also, if implemented correctly, using Flask-SQLAlchemy will help make your application to be database-agnostic. If you start building your app on top of MySQL and then decide to switch to another database engine, you shouldn't have to rewrite massive chunks of sensitive database code. You could simply switch out Flask-SQLAlchemy with your new database abstraction layer without much of an issue. Being able to easily replace components is called modularity, and it's a sign of a well designed application.
On the other hand, it might be more intuitive and readable if you write raw SQL statements instead of learning how to translate it into Flask-SQLAlchemy's Expression Language. Fortunately, it's possible to write raw SQL statements in Flask-SQLAlchemy too, if that's what you need.
The moral of this aside is to not completely rely on, or abandon a database abstraction layer like Flask-SQLAlchemy, but to be aware of it, so that you can determine when it's useful for your needs. For the database queries in this article, I'll show you both the Expression Language version and the equivalent SQL statement.
Installing MySQL
Check to see if your system already has MySQL by running the following command in your terminal:
$ mysql --version
If you see a version number, you can skip to the "Creating a Database" section. If the command was not found, you'll need to install MySQL. With the large variety of different operating systems out there, I'll defer to Google to provide installation instructions that work for your OS. The installation usually consists of running a command or an executable. For example, the Linux command is:
$ sudo apt-get install mysql-server mysql-client
Creating a Database
Once MySQL is installed, create a database for your app called '
development'. You can do this from a web interface like phpMyAdmin or from the command line, as shown below:
$ mysql -u username -p Enter password: mysql> CREATE DATABASE development;
Installing Flask-SQLAlchemy
Inside the isolated development environment, install Flask-SQLAlchemy.
$ pip install flask-sqlalchemy
When I tried to install Flask-SQLAlchemy, I received an error stating that the installation had failed. I searched the error and found that others had resolved the problem by installing
libmysqlclient15-dev, which installs MySQL's development files. If your Flask-SQLAlchemy installation fails, Google the error for solutions or leave a comment and we'll try to help you figure it out.
Configuring Flask-SQLAlchemy
Just as we did with Flask-Mail, we need to configure Flask-SQLAlchemy so that it knows where the
development database lives. First, create a new file named
models.py, along with adding in the following code
app/intro_to_flask/models.py
from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy()
Here we import the
SQLAlchemy class from Flask-SQLAlchemy (line one) and create a variable named
db, containing a usable instance of the
SQLAlchemy class (line three).
Next, open
__init__.py and add the following lines after
mail.init_app(app) and before
import intro_to_flask.routes.
app/intro_to_flask/__init__.py
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://your-username:your-password@localhost/development' from models import db db.init_app(app)
Let's go over this:
- Line one tells the Flask app to use the '
development' database. We specify this through a data URI which follows the pattern of:
mysql://username:password@server/database. The server is 'localhost' because we're developing locally. Make sure to fill in your MySQL
usernameand
db, the usable instance of the
SQLAlchemyclass we created in
models.py, still doesn't know what database to use. So we import it from
models.py(line three) and bind it to our app (line four), so that it also knows to use the '
development' database. We can now query the '
development' database through our
dbobject.
Now that our configuration is complete, let's ensure that everything works. Open
routes.py and create a temporary URL mapping so that we can perform a test query.
app/intro-to-flask/routes.py
from intro_to_flask import app from flask import Flask, render_template, request, flash, session, redirect, url_for from forms import ContactForm, SignupForm, SigninForm from flask.ext.mail import Message, Mail from models import db . . . @app.route('/testdb') def testdb(): if db.session.query("1").from_statement("SELECT 1").all(): return 'It works.' else: return 'Something is broken.'
First we import the database object (
db) from
models.py (line five). We then create a temporary URL mapping (lines 9-14) wherein we issue a test query to ensure that the Flask app is connected to the '
development' database. Now when we visit the URL
/testdb, a test query will be issued (line 11); this is equivalent to the SQL statement
SELECT 1;. If all goes well, we'll see "It works" in the browser. Otherwise, we'll see an error message stating what went wrong.
I received an error when I visited the
/testdb URL:
ImportError: No module named MySQLdb. This meant that I didn't have the mysql-python library installed, so I tried to install it by typing the following:
$ pip install mysql-python
That installation failed, too. The new error message suggested that I first run
easy_install -U distribute and then try the mysql-python installation again. So I did, just like below:
$ easy_install -U distribute $ pip install mysql-python
This time the mysql-python installation succeeded, and then I received the "It works" success message in the browser. Now the reason I'm recounting the errors I've received and what I did to solve them is because installing and connecting to databases can be a tricky process. If you get an error message, please don't get discouraged. Google the error message or leave a comment, and we'll figure it out.
Once the test query works, delete the temporary URL mapping from
routes.py. Make sure to retain the "
from models import db"" part, because we'll need it next.
—
Checkpoint: 14_db_config —
Create a User Model
It's not a good idea to store passwords in plain text, for security reasons.
Inside the '
development' database, we need to create a users table where we can store each user's information. The information we want to collect and store are the user's first name, last name, email, and password.
It's not a good idea to store passwords in plain text, for security reasons. If an attacker gains access to your database, they would be able to see each user's login credentials. One way to defend against such an attack is to encrypt passwords with a hash function and a
salt (some random data), and store that encrypted value in the database instead of the plain text password. When a user signs in again, we'll collect the password that was submitted, hash it, and check if it matches the hash in the database. Werkzeug, the utility library on which Flask is built, provides the functions
generate_password_hash and
check_password_hash for these two tasks, respectively.
With this in mind, here are the columns we'll need for the users table:
Just like before, you can create this table from a web interface such as phpMyAdmin or from the command line, as shown below:
mysql> CREATE TABLE users ( uid INT NOT NULL PRIMARY KEY AUTO_INCREMENT, firstname VARCHAR(100) NOT NULL, lastname VARCHAR(100) NOT NULL, email VARCHAR(120) NOT NULL UNIQUE, pwdhash VARCHAR(100) NOT NULL );
Next, in
models.py, let's create a class to model a user with attributes for a user's first name, last name, email, and password.
app/intro_to_flask/models.py
from flask.ext.sqlalchemy import SQLAlchemy from werkzeug import generate_password_hash, check_password_hash db = SQLAlchemy() class User(db.Model): __tablename__ = 'users' uid = db.Column(db.Integer, primary_key = True) firstname = db.Column(db.String(100)) lastname = db.Column(db.String(100)) email = db.Column(db.String(120), unique=True) pwdhash = db.Column(db.String(54)) def __init__(self, firstname, lastname, email, password): self.firstname = firstname.title() self.lastname = lastname.title() self.email = email.lower() self.set_password(password) def set_password(self, password): self.pwdhash = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.pwdhash, password)
We use the set_password() function to set a salted hash of the password, instead of using the plain text password itself.
Lines one and four already existed in
models.py, so we'll start on line two by importing the
generate_password_hash and
check_password_hash security functions from Werkzeug. Next, we create a new class named
User, inheriting from the database object
db's
Model class (line six.)
Inside of our
User class, we create attributes for the table's name, primary key, and the user's first name, last name, email, and password (lines 10-14). We then write a constructor which sets the class attributes (lines 17-20). We save names in title case and email addresses in lowercase to ensure a match regardless of how a user types in his credentials on subsequent sign ins.
We use the
set_password function (lines 22-23) to set a salted hash of the password, instead of using the plain text password itself. Lastly, we have a function named
check_password that uses
check_password_hash, to check a user's credentials on any subsequent sign ins (lines 25-26).
—
Checkpoint: 15_user_model —
Sweet! We've created a users table and a user model, thereby laying down the foundation of our authentication system. Now let's build the first user-facing component of the authentication system: the signup page.
Building a Signup Page
Planning
Take a look at
Fig. 1 below, to see how everything will fit together.
Fig. 1
Implement SSL site-wide so that passwords and session tokens cannot be intercepted.
Let's go over the figure from above:
- A user visits the URL
/signupto create a new account. The page is retrieved through an HTTP GET request and loads in the browser.
- The user fills in the form fields with his first name, last name, email, and password.
- The user clicks the "Create account" button, and the form submits to the server with an HTTP POST request.
- On the server, a function validates the form data.
- If one or more fields do not pass validation, the signup page reloads with a helpful error message, prompting the the user to try again.
- If all fields are valid, a new
Userobject will be created and saved into the database. The user will then be signed in and redirected to a profile page.
This sequence of steps should look familiar, as it's identical to the sequence of steps we took to create a contact form. Here, instead of sending an email at the end, we save a user's credentials to the database. The previous article already explained creating a form in detail, I'll move more quickly in this section so that we can get to the more exciting parts, faster.
Creating a Signup Form
We installed Flask-WTF in the previous article, so let's proceed with creating a new form inside
forms.py.
app/intro_to_flask/forms.py
from flask.ext.wtf import Form, TextField, TextAreaField, SubmitField, validators, ValidationError, PasswordField from models import db, User . . . class SignupForm(Form): firstname = TextField("First name", [validators.Required("Please enter your first name.")]) lastname = TextField("Last name", [validators.Required("Please enter your last name.")]) email = TextField("Email", [validators.Required("Please enter your email address."), validators.Email("Please enter your email address.")]) password = PasswordField('Password', [validators.Required("Please enter a password.")]) submit = SubmitField("Create account") def __init__(self, *args, **kwargs): Form.__init__(self, *args, **kwargs) def validate(self): if not Form.validate(self): return False user = User.query.filter_by(email = self.email.data.lower()).first() if user: self.email.errors.append("That email is already taken") return False else: return True
We start by importing one more Flask-WTF class named
PasswordField (line one), which is like
TextField except that it generates a password textbox. We'll need the
db database object and the
User model to handle some custom validation logic inside the
Then we create a new class named
SignupForm containing a field for each piece of user information we wish to collect (lines 7-11). There's a presence validator on each field to ensure it's filled in, and a format validator which requires that email addresses match the pattern:
user@example.com.
Next, we write a simple constructor for the class that just calls the base class' constructor (lines 13-14).
So we've added some presence and format validators to our form fields, but we need an additional validator that ensures an account does not already exist with the user's email address. To do this we hook into Flask-WTF's validation process (lines 16-25).
Now inside of the
validate() function, we first ensure the presence and format validators run by calling the base class'
validate() method; if the form is not filled in properly,
validate() returns
False (lines 16-17).
Next we define the custom validator. We start by querying the database with the email that the user submitted (line 18). If you remember from our
models.py file, the email address is converted to lowercase to ensure a match regardless of how it was typed in. This Flask-SQLAlchemy expression corresponds to the following SQL statement:
SELECT * FROM users WHERE email = self.email.data.lower() LIMIT 1
If a user record already exists with the submitted email, validation fails giving the following error message: "That email is already taken" (lines 21-22).
Using the Signup Form
Let's now create a new URL mapping and a new web template for the signup form. Open
routes.py and import the newly created signup form so that we can use it.
app/intro_to_flask/routes.py
from intro_to_flask import app from flask import render_template, request, flash from forms import ContactForm, SignupForm
Next, create a new URL mapping.
app/intro_to_flask/routes.py
@app.route('/signup', methods=['GET', 'POST']) def signup(): form = SignupForm() if request.method == 'POST': if form.validate() == False: return render_template('signup.html', form=form) else: return "[1] Create a new user [2] sign in the user [3] redirect to the user's profile" elif request.method == 'GET': return render_template('signup.html', form=form)
Inside the
form that contains a usable instance of the
SignupForm class. If a GET request has been issued, we'll return the
signup.html web template containing the signup form for the user to fill out.
Otherwise, we'll see just a temporary placeholder string. For now, the temp string lists the three actions that should take place when the form has been successfully submitted. We'll come back and replace this string with real code in "The First Signup" section below.
Now that we've created a URL mapping, the next step is to create the web template
templates/ folder.
app/intro_to_flask/templates/signup.html
{% extends "layout.html" %} {% block content %} <h2>Sign up</h2> {% for message in form.firstname.errors %} <div class="flash">{{ message }}</div> {% endfor %} {% for message in form.lastname.errors %} <div class="flash">{{ message }}</div> {% endfor %} {% for message in form.email.errors %} <div class="flash">{{ message }}</div> {% endfor %} {% for message in form.password.errors %} <div class="flash">{{ message }}</div> {% endfor %} <form action="{{ url_for('signup') }}" method=post> {{ form.hidden_tag() }} {{ form.firstname.label }} {{ form.firstname }} {{ form.lastname.label }} {{ form.lastname }} {{ form.email.label }} {{ form.email }} {{ form.password.label }} {{ form.password }} {{ form.submit }} </form> {% endblock %}
This template looks just like
contact.html. We first loop through and display any error messages if necessary. We then let Jinja2 generate most of the HTML form for us. Remember how in the
Signup form class we appended the error message "That email is already taken" to
self.email.errors? That's the same object that Jinja2 loops through in this template.
The one difference from the
contact.html template is the omission of the
if...else logic.
In this template, we want to register and sign in the user on a successful form submission. This takes place on the back-end, so the
if...else statement is not needed here.
Finally, add in these CSS rules to your
main.css file so that the signup form looks nice and pretty.
app/intro_to_flask/static/css/main.css
/* Signup form */ form input#firstname, form input#lastname, form input#password { width: 400px; background-color: #fafafa; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; border: 1px solid #cccccc; padding: 5px; font-size: 1.1em; } form input#password { margin-bottom: 10px; }
Let's check out the newly created signup page by typing:
$ cd app/ $ python runserver.py
And browse to in your favorite web browser.
Excellent! We just created a signup form from scratch, handled complex validation, and created a good looking signup page with helpful error messages.
—
Checkpoint: 16_signup_form —
If any of these steps were unclear, please take a moment to review the previous article. It covers each step in greater detail, and I followed the same steps from that article, to create this signup form.
The First Signup
Let's start by replacing the temporary placeholder string in
routes.py's
signup() function with some real code. Upon a successful form submission, we need to create a new
User object, save it to the database, sign the user in, and redirect to the user's profile page. Let's take this step by step, starting with creating a new
User object and saving it to the database.
Saving a New User Object
Add in lines five and 17-19 to
routes.py.
app/intro_to_flask/routes.py
from intro_to_flask import app from flask import render_template, request, flash, session, url_for, redirect from forms import ContactForm, SignupForm from flask.ext.mail import Message, Mail from models import db, User . . . () return "[1] Create a new user [2] sign in the user [3] redirect to the user's profile" elif request.method == 'GET': return render_template('signup.html', form=form)
First, we import the
User class from models.py so that we can use it in the
User object called
newuser and populate it with the signup form's field data (line 17).
Next, we add
newuser to the database object's session (line 18), which is Flask-SQLAlchemy's version of a regular database transaction. The
add() function generates an
INSERT statement using the
User object's attributes. The equivalent SQL for this Flask-SQLAlchemy expression is:
INSERT INTO users (firstname, lastname, email, pwdhash) VALUES (form.firstname.data, form.lastname.data, form.email.data, form.password.data)
Lastly, we update the database with the new user record by committing the transaction (line 19).
Next, we need to sign in the user. The Flask app needs to know that subsequent page requests are coming from the browser of the user who has successfully signed up. We can accomplish this by setting a cookie in the user's browser containing some sort of ID and associating that key with the user's credentials in the Flask app.
This way, the ID in the browser's cookie will be passed to the app on each subsequent page request, and the app will look up the ID to determine whether it maps to valid user credentials.
If it does, the app allows access to the parts of the website that you need to be signed in for. This combination of having a key stored on the client and a value stored on the server is called a session.
Flask has a
session object that accomplishes this functionality. It stores the session key in a secure cookie on the client and the session value in the app. Let's use it in our
app/intro_to_flask/routes.py
from flask import render_template, request, flash, session . . . "[1] Create a new user [2] sign in the user [3] redirect to the user's profile" elif request.method == 'GET': return render_template('signup.html', form=form)
We start by importing Flask's
session object on line one. Next, we associate the key '
session object will take care of hashing '
Redirecting to a Profile page
The last step is to redirect the user to a Profile page after signing in. We'll use the
url_for function (which we've seen in
layout.html and
contact.html) in conjunction with Flask's
redirect() function.
app/intro_to_flask/routes.py
from intro_to_flask import app from flask import render_template, request, flash, session, url_for, redirect . . . redirect(url_for('profile')) elif request.method == 'GET': return render_template('signup.html', form=form)
on line two, we import Flask's
url_for() and
redirect() functions. Then on line 19, we replace our temporary placeholder string with a redirect to the URL
/profile. We don't have a URL mapping for
/profile yet, so let's create that next.
app/intro_to_flask/routes.py
@app.route('/profile') def profile(): if 'email' not in session: return redirect(url_for('signin')) user = User.query.filter_by(email = session['email']).first() if user is None: return redirect(url_for('signin')) else: return render_template('profile.html')
Here we can finally see sessions in action. We start on line four by fetching the browser's cookie and checking if it contains a key named '
If the '
session['email'], and then query the database for a registered user with this same email address (line seven). The equivalent SQL for this Flask-SQLAlchemy expression is:
SELECT * FROM users WHERE email = session['email'];
If no registered user exists, we'll redirect to the signup page. Otherwise, we render the
profile.html template. Let's create
profile.html now.
app/intro_to_flask/templates/profile.html
{% extends "layout.html" %} {% block content %} <div class="jumbo"> <h2>Profile<h2> <h3>This is {{ session['email'] }}'s profile page<h3> </div> {% endblock %}
I've kept this profile template simple. If we focus in on line five — you'll see that we can use Flask's
session object inside Jinja2 templates. Here, I've used it to create a user-specific string, but you could use this ability to pull other types of user-specific information instead.
We're finally ready to see the result of all our hard work. Type the following into your terminal:
$ python runserver.py
Go to in your favorite web browser, and complete the sign up process. You should be greeted with a profile page that looks like the following screenshot:
Signing up users is a huge milestone for our app. We can adapt the code in our
/signup() function and round out our authentication system by allowing users to sign in and out of the app.
—
Checkpoint: 17_profile_page —
Building a Signin Page
Creating a signin page is similar to creating a signup page — we'll need to create a signin form, a URL mapping, and a web template. Let's start by creating the
forms.py.
app/intro_to_flask/forms.py
class SigninForm(Form): email = TextField("Email", [validators.Required("Please enter your email address."), validators.Email("Please enter your email address.")]) password = PasswordField('Password', [validators.Required("Please enter a password.")]) submit = SubmitField("Sign In") def __init__(self, *args, **kwargs): Form.__init__(self, *args, **kwargs) def validate(self): if not Form.validate(self): return False user = User.query.filter_by(email = self.email.data.lower()).first() if user and user.check_password(self.password.data): return True else: self.email.errors.append("Invalid e-mail or password") return False
The
SignupForm class. To sign a user in, we need to capture their email and password, so we create those two fields with presence and format validators (lines 2-3). Then we define our custom validator inside the
validate() function (lines 10-15). This time the validator needs to make sure the user exists in the database and has the correct password. If a record does exist with the supplied information, we check to see if the password matches (line 14). If it does, the validation check passes (line 15), otherwise they get an error message.
Next, let's create a URL mapping in
routes.py.
app/intro_to_flask/routes.py
... from forms import ContactForm, SignupForm, SigninForm . . . @app.route('/signin', methods=['GET', 'POST']) def signin(): form = SigninForm() if request.method == 'POST': if form.validate() == False: return render_template('signin.html', form=form) else: session['email'] = form.email.data return redirect(url_for('profile')) elif request.method == 'GET': return render_template('signin.html', form=form)
Once again, the
SigninForm (line two), so that we can use it in the
If the form has been POSTed and any validation check fails, the signin form reloads with a helpful error message (lines 11-12). Otherwise, we sign in the user by creating a new session and redirecting to their profile page (lines 14-15).
Lastly, let's create the web template
app/intro_to_flask/templates/signin.html
{% extends "layout.html" %} {% block content %} <h2>Sign In</h2> {% for message in form.email.errors %} <div class="flash">{{ message }}</div> {% endfor %} {% for message in form.password.errors %} <div class="flash">{{ message }}</div> {% endfor %} <form action="{{ url_for('signin') }}" method=post> {{ form.hidden_tag() }} {{ form.email.label }} {{ form.email }} {{ form.password.label }} {{ form.password }} {{ form.submit }} </form> {% endblock %}
Similar to
signup.html template, we first loop through and display any error messages, then we let Jinja2 generate the form for us.
And that does it for the signin page. Visit to check it out. Go ahead and sign in, you should get redirected to your profile page.
—
Checkpoint: 18_signin_form —
In "The First Signup" section above, we saw that "signing in" meant setting a cookie in the user's browser containing an ID and associating that ID with the user's data in the Flask app. Therefore, "signing out" means clearing the cookie in the browser and dissociating the user data.
This can be accomplished in one line:
session.pop('email', None).
We don't need a form or even a web template to sign out. All we need is a URL mapping in
routes.py, which terminates the session and redirects to the Home page. The mapping, therefore, is short and sweet:
app/intro_to_flask/routes.py
@app.route('/signout') def signout(): if 'email' not in session: return redirect(url_for('signin')) session.pop('email', None) return redirect(url_for('home'))
The user is not authenticated if the browser's cookie does not contain a key named '
You can test the sign out functionality by visiting. If you're signed in, the app will sign you out and redirect to. Once you've signed out, try visiting the profile page. You shouldn't be allowed to see the profile page if you're not signed in, and the app should redirect you back to the Signin page.
—
Checkpoint: 19_signout —
Tidying Up
Now we need to update the site header with navigation links for "Sign Up", "Sign In", "Profile", and "Sign Out". The links should change based on whether the user is signed in or not. If the user is signed out, links for "Sign Up" and "Sign In" should be visible. When the user is signed in, we want links for "Profile" and "Sign Out" to appear, while hiding the "Sign Up" and "Sign In" links.
So how can we do this? Think back to the
profile.html template where we used Flask's
session object. We can use the
session object to show navigation links based on the user's authentication status. Let's open
layout.html and make the following changes:
app/intro_to_flask/templates/layout.html
<!DOCTYPE html> <html> <head> <title>Flask App</title> <link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}"> </head> <body> <header> <div class="container"> <h1 class="logo">Flask App</h1> <nav> <ul class="menu"> <li><a href="{{ url_for('home') }}">Home</a></li> <li><a href="{{ url_for('about') }}">About</a></li> <li><a href="{{ url_for('contact') }}">Contact</a></li> {% if 'email' in session %} <li><a href="{{ url_for('profile') }}">Profile</a></li> <li><a href="{{ url_for('signout') }}">Sign Out</a></li> {% else %} <li><a href="{{ url_for('signup') }}">Sign Up</a></li> <li><a href="{{ url_for('signin') }}">Sign In</a></li> {% endif %} </ul> </nav> </div> </header> <div class="container"> {% block content %} {% endblock %} </div> </body> </html>
Starting on line 17, we use Jinja2's
if...else syntax and the
session() object to check if the browser's cookie contains the '
Now give it a try! Check out how the navigation links appear and disappear by signing in and out of the app.
The last task remaining is a similar issue: when a user is signed in, we don't want him to be able to visit the signup and signin pages. It makes no sense for a signed in user to authenticate themselves again. If signed in users try to visit these pages, they should instead be redirected to their profile page. Open
routes.py and add the following piece of code to the beginning of the
if 'email' in session: return redirect(url_for('profile'))
Here's what your
routes.py file will look like after adding in that snippet of code:
app/intro_to_flask/routes.py
@app.route('/signup', methods=['GET', 'POST']) def signup(): form = SignupForm() if 'email' in session: return redirect(url_for('profile')) . . . @app.route('/signin', methods=['GET', 'POST']) def signin(): form = SigninForm() if 'email' in session: return redirect(url_for('profile')) ...
And with that we're finished! Try visiting the the "signup" or "signin" pages while you are currently signed in, to test it out.
—
Checkpoint: 20_visibility_control —
Conclusion
We've accomplished a lot in this article. We've taken our Flask app from being a simple Python module and turned it into a well organized application, capable of handling user authentication.
There are several directions in which you can take this app from here. Here are some ideas:
- Let users sign in with an existing account, such as their Google account, by adding support for OpenID.
- Give users the ability to update their account information, as well as delete their account.
- Let users reset their password if they forget it.
- Implement an authorization system.
- Deploy to a production server. Note that when you deploy this app to production, you will need to implement SSL site-wide so that passwords and session tokens cannot be intercepted. If you deploy to Heroku, you can use their SSL certificate.
So go forth and continue to explore Flask, and build your next killer app! Thanks for reading.
| http://code.tutsplus.com/tutorials/intro-to-flask-signing-in-and-out--net-29982 | CC-MAIN-2014-52 | refinedweb | 5,782 | 57.67 |
Hello World - Java Beginners
Hello World Java Beginner - 1st day. Looked at the Hello World......){ System.out.println("Hello World!"); } } what am I doing wrong. Am I expecting too Hi friend,i saw your program. your program is correct, i think
Hello World Program
Hello World Program write a java program that continuously prints... = new DisplayMessageContinuously("Hello World ", 1000);
th.start...
Hi Friend,
Try the following code:
public class
Java Hello World code example
Java Hello World code example Hi,
Here is my code of Hello World...(String[] args) {
System.out.println("Hello, World");
}
}
Thanks
Deepak Kumar Hi,
Learn Java Java
Simple Java Program for beginners... to develop robust applications. Writing a simple Hello World program is stepwise...
HelloWorld.java - the source code for the "Hello, world!"
program
Java hello world
Java hello world
..., JavaBeans, Mobile Java. Genarally, Hello world program is the first
step.../java/beginners/hello_world.shtml
Spring Hello World prog - Spring
Spring Hello World prog I used running the helloworld prog code mentioned in
I'm...:489)
at java.lang.Thread.run(Unknown Source) Hi Friend,
Please("
hi - | http://www.roseindia.net/tutorialhelp/comment/88740 | CC-MAIN-2015-14 | refinedweb | 181 | 53.98 |
Solution for
Programming Exercise 7.8
THIS PAGE DISCUSSES ONE POSSIBLE SOLUTION to the following exercise from this on-line Java textbook.Graphics.)
Discussion
Let's start by discussing the Undo operation, since there is not much more to say about it beyond what is said in the exercise. The off-screen canvas for the undo operation, undoBuffer, is created in the setupOSI() method where OSI is created. It is filled with the background color, just like OSI. (Ordinarily, the user won't see the initial contents of the undo buffer. But if the user clicks the Undo button before drawing anything, the undo buffer will be swapped in and displayed. So, it should have some well-defined content. Since, in fact, both OSI and undoBuffer are initially filled with the background color, the user won't see any difference when they are swapped.)
In the actionPerformed method, in response to the "Undo" command, the values of OSI and undoBuffer are swapped with the statementsImage temp = OSI; OSI = undoBuffer; undoBuffer = temp; repaint();
The values stored in the variables OSI and undoBuffer are swapped. But remember that the values are only pointers to the Image objects. The Images themselves are not copied. After the swap, the Images themselves have not moved, but OSI and undoBuffer are pointing to different images. When the screen is repainted, and OSI is drawn to the screen, it's the former undo buffer that appears on the screen. The former OSI is now the new undo buffer.
In the mousePressed() routine, before a drawing operation starts, the current image is saved in the undo buffer, using the commands given in the exercise.
In the source code below, all changes having to do with the Undo command are shown in red.
In changing the program from an applet to a frame, the first line, which waspublic class KaleidaPaint extends JApplet {
is changed topublic class KaleidaPaintFrame extends JFrame {
The init() method of the applet is replace by a constructor for the frame. Since the frame will use a menu bar in place of the buttons and JComboBoxes used in the applet, the constructor is very different from the applet's init() method. Its main purpose is to create the menu bar and the menus that it contains. The design of the menu bars could be very different from the ones that I used, but techniques for setting up the menus are pretty standard and straightforward. (They do require a lot of typing, though!) The techniques are the same as those used in the ShapeDrawFrame example from Section 7. I won't discuss the set up of the menus here.
In my applet, the "Color", "Shape", and "Symmetry" menus control what type of drawing is done when the user drags the mouse. Each menu contains a group of JRadioButtonMenuItems. Java, unfortunately, doesn't have a good way of checking a group of radio buttons to see which one is selected. You have to go through and check each button. To make this possible in my applet, I have instance variables to represent each of the JRadioButtonMenuItems, and I wrote methods to check for the currently selected color, shape, and symmetry type. For example; }
The method checks the buttons in the "Symmetry" menu and returns a constant that represents the selected item in the menu. This method, along with the very similar getSelectedColor() and getSelectedShape(), are called in mousePressed() when the user begins drawing. The values they return are used to determine what to draw when the user drags the mouse.
The other menu, "Control", contains commands that will be carried out by the actionPerformed() method of the Display class. Most of this is straightforward. In order to implement custom colors, an instance variable, customColor, in the Display class holds the currently selected custom color. Initially, the color is gray. (It has to have some initial value, in case the user uses the custom color without first selecting one.) The value of this variable is changed if the user selects a new custom color with the "Select Custom Color..." command. The custom color is used for the background color by the "Fill with Custom" command in the "Control" menu, and it is used for the drawing color if "Custom" is selected in the "Color" menu. In my original solution, the "Select Custom Color..." command did nothing but change the customColor variable. To draw with this color, the user also had to select "Custom" from the color menu. After using the program, I found that this behavior didn't feel right. I wanted to be able to draw with the new color immediately after using the "Select Custom Color..." command. So, I changed the program to select "Custom" in the "Color" menu automatically. This might surprise the user, but I found it more surprising when the color wasn't changed. (There is something called the "Principle of Least Surprise" which is a valuable guideline for user interface design.)
In addition to setting up the menus, the constructor does some initialization that any frame needs, either in its constructor or elsewhere:pack(); setLocation(75,50); setResizable(false); setDefaultCloseOperation(EXIT_ON_CLOSE); show();
The pack() command sets the frame to its preferred size. Since I use the pack() command to set the size of the frame, all the components in the frame must define a reasonable preferred size. My original display class did not do this, so I added a call to setPreferredSize() method to the constructor of the display class. The default size is 450-by-450. Symmetry looks better on a square drawing area. The frame will be sized so that this is the exact size of the drawing area. As an alternative to using pack(), I could have set the size of the frame by calling its setSize() or setBounds() method.
The setResizable(false) command prevents the user from changing the size of the window. This is not usually desirable, but I decided to do it here since changing the window size will erase the current picture, and I thought that might be too surprising for the user. The default close operation tells what happens when the user clicks the close box of the window. For a stand-alone application with a single window, it's appropriate to call System.exit(), which is what I do here.
The show() command is important, since without it the frame would never appear on the screen. The show() command does not have to occur in the constructor. If the constructor does not show the frame, then the frame remains invisible until some other routine calls the frame's show() method. Sometimes it's good to be able to show and hide a frame at will.
The frame class has a main() routine that makes it possible to run the frame as a standalone program. The main() routine just needs to say "new KaleidaPaintFrame()" to create the frame:public static void main(String[] args) { new KaleidaPaintFrame(); }
Note that the main() routine ends immediately after it opens the frame. It does not wait for the window to close. The main() routine ends even while the frame continues to exist. The main() routine is, in fact, a separate thread from the user interface thread that runs the frame. The main() routine could even go on to perform other tasks independently of the frame, such as interacting with the user via TextIO.
The only other change I made was to remove the getInsets() method from the original program. The frame has its own borders anyway. In general, there is no reason to use insets on a frame
The Solution
Changes related to the Undo operation are shown in red.
Other significant changes related are shown in blue./* A nifty program where the user can sketch curves and shapes in a variety of colors on a variety of background colors. The user can draw symmetric pictures in which shapes are reflected horizontally, vertically, and diagonally. The user selects the type of symmetry from a "Symmetry" menu at the top of the frame. The user can select a color to be used for drawing from a "Color" menu. The user selects the shape to draw from a "Shape" menu at the top of the frame. The user can draw free-hand curves, straight lines, and one of six different types of shapes. A "Control" menu contains commands for filling the drawing area with various colors. It also contains commands: "Clear", "Undo", and "Quit". The "Clear" command will clear the frame to the current background color. The user can undo only the most recent operation. The user can close the window by chosing the "Quit" command or by clicking the Window's close box. Finally, there is a "Select Custom Color..." command that lets the user set a custom color for drawing or for the background. The user's drawing is saved in an off-screen image, which is used to refresh the screen when repainting. The frame is made non-resizable, since the way the program is written, the picture would be lost if the drawing area were to change size. This file defines two classes, KaleidaPaintFrame.class, and class, KaleidaPaintFrame$Display.class. */ import java.awt.*; import java.awt.event.*; import javax.swing.*; public class KaleidaPaintFrame extends JFrame { public static void main(String[] args) { // A main routine that allows this class to be run // as a stand-alone application. It just opens a frame. new KaleidaPaintFrame(); } JRadioButtonMenuItem black, red, green, blue, cyan, magenta, yellow, white, custom; // Items for the "Color" menu, which controls the drawing color. // They form a group in which only one item can be selected. // When the user starts drawing, the color is determined by // checking to see which of the items is selected. JRadioButtonMenuItem curve, straightLine, rectangle, oval, roundRect, filledRectangle, filledOval, filledRoundRect; // Items for the "Shape" menu, which determine the shape to be drawn. JRadioButtonMenuItem noSymmetry, twoWay, fourWay, eightWay; // Items for the "Symmetry" menu, which determine which // reflections of the basic figure should be drawn. public boolean standAlone = true; // If a frame is created by an applet, the applet should // set this variable to false. Otherwise, an error will // be generated when the user selects the "Quit" command, // since that command will call System.exit() if standalone // is true. The applet should also call the frame's // setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE). public KaleidaPaintFrame() { // replaces init() method. // Constructor creates a drawing area and uses it as its // content pane. It also sets up the menu bar. super("KaleidaPaint"); // Set a title for the window. Display canvas = new Display(); // The drawing area. setContentPane(canvas); // Create menu bar and menus. JMenuBar menubar = new JMenuBar(); JMenu controlMenu = new JMenu("Control",true); menubar.add(controlMenu); JMenu colorMenu = new JMenu("Color",true); menubar.add(colorMenu); JMenu shapeMenu = new JMenu("Shape",true); menubar.add(shapeMenu); JMenu symmetryMenu = new JMenu("Symmetry",true); menubar.add(symmetryMenu); setJMenuBar(menubar); // Set up the "Control" menu, and set the canvas to respond // to commands from this menu. Add accelerators for some // of the commands. controlMenu.add("Fill with Black").addActionListener(canvas); controlMenu.add("Fill with Red").addActionListener(canvas); controlMenu.add("Fill with Green").addActionListener(canvas); controlMenu.add("Fill with Blue").addActionListener(canvas); controlMenu.add("Fill with Cyan").addActionListener(canvas); controlMenu.add("Fill with Magenta").addActionListener(canvas); controlMenu.add("Fill with Yellow").addActionListener(canvas); controlMenu.add("Fill with White").addActionListener(canvas); controlMenu.add("Fill with Custom").addActionListener(canvas); controlMenu.addSeparator(); JMenuItem customItem = new JMenuItem("Set Custom Color..."); customItem.addActionListener(canvas); customItem.setAccelerator( KeyStroke.getKeyStroke("ctrl T") ); controlMenu.add(customItem); JMenuItem clearItem = new JMenuItem("Clear"); clearItem.addActionListener(canvas); clearItem.setAccelerator( KeyStroke.getKeyStroke("ctrl K") ); controlMenu.add(clearItem); JMenuItem undoItem = new JMenuItem("Undo"); undoItem.addActionListener(canvas); undoItem.setAccelerator( KeyStroke.getKeyStroke("ctrl Z") ); controlMenu.add(undoItem); JMenuItem quitItem = new JMenuItem("Quit"); quitItem.setAccelerator( KeyStroke.getKeyStroke("ctrl Q") ); quitItem.addActionListener(canvas); controlMenu.add(quitItem); // Set up the "Color" menu, with all the items in a button group. ButtonGroup colorGroup = new ButtonGroup(); black = new JRadioButtonMenuItem("Black"); colorGroup.add(black); colorMenu.add(black); red = new JRadioButtonMenuItem("Red"); colorGroup.add(red); colorMenu.add(red); green = new JRadioButtonMenuItem("Green"); colorGroup.add(green); colorMenu.add(green); blue = new JRadioButtonMenuItem("Blue"); colorGroup.add(blue); colorMenu.add(blue); cyan = new JRadioButtonMenuItem("Cyan"); colorGroup.add(cyan); colorMenu.add(cyan); magenta = new JRadioButtonMenuItem("Magenta"); colorGroup.add(magenta); colorMenu.add(magenta); yellow = new JRadioButtonMenuItem("Yellow"); colorGroup.add(yellow); colorMenu.add(yellow); white = new JRadioButtonMenuItem("White"); colorGroup.add(white); colorMenu.add(white); custom = new JRadioButtonMenuItem("Custom Color"); colorGroup.add(custom); colorMenu.add(custom); black.setSelected(true); // Set up the "Shape" menu. ButtonGroup shapeGroup = new ButtonGroup(); curve = new JRadioButtonMenuItem("Curve"); shapeGroup.add(curve); shapeMenu.add(curve); straightLine = new JRadioButtonMenuItem("Straight Line"); shapeGroup.add(straightLine); shapeMenu.add(straightLine); rectangle = new JRadioButtonMenuItem("Rectangle"); shapeGroup.add(rectangle); shapeMenu.add(rectangle); oval = new JRadioButtonMenuItem("Oval"); shapeGroup.add(oval); shapeMenu.add(oval); roundRect = new JRadioButtonMenuItem("RoundRect"); shapeGroup.add(roundRect); shapeMenu.add(roundRect); filledRectangle = new JRadioButtonMenuItem("Filled Rectangle"); shapeGroup.add(filledRectangle); shapeMenu.add(filledRectangle); filledOval = new JRadioButtonMenuItem("Filled Oval"); shapeGroup.add(filledOval); shapeMenu.add(filledOval); filledRoundRect = new JRadioButtonMenuItem("Filled RoundRect"); shapeGroup.add(filledRoundRect); shapeMenu.add(filledRoundRect); curve.setSelected(true); // Set up the "Symmetry" menu. ButtonGroup symmetryGroup = new ButtonGroup(); noSymmetry = new JRadioButtonMenuItem("None"); noSymmetry.setAccelerator( KeyStroke.getKeyStroke("ctrl 0") ); symmetryGroup.add(noSymmetry); symmetryMenu.add(noSymmetry); twoWay = new JRadioButtonMenuItem("Two-way"); twoWay.setAccelerator( KeyStroke.getKeyStroke("ctrl 2") ); symmetryGroup.add(twoWay); symmetryMenu.add(twoWay); fourWay = new JRadioButtonMenuItem("Four-way"); fourWay.setAccelerator( KeyStroke.getKeyStroke("ctrl 4") ); symmetryGroup.add(fourWay); symmetryMenu.add(fourWay); eightWay = new JRadioButtonMenuItem("Eight-way"); eightWay.setAccelerator( KeyStroke.getKeyStroke("ctrl 8") ); symmetryGroup.add(eightWay); symmetryMenu.add(eightWay); noSymmetry.setSelected(true); // Set size, etc., of frame and make it visible. pack(); setLocation(75,50); setResizable(false); setDefaultCloseOperation(EXIT_ON_CLOSE); show(); } // end constructor private class Display extends JPanel implements MouseListener, MouseMotionListener, ActionListener { // Nested class Display represents the drawing surface of the // applet. It lets the user use the mouse to draw colored curves // and shapes. The current color is specified by the pop-up menu // colorChoice. The current shape is specified by another pop-up menu, // figureChoice. (These are instance variables in the main class.) // The panel also listens for action events from buttons // named "Clear" and "Set Background". The "Clear" button fills // the panel with the current background color. The "Set Background" // button sets the background color to the current drawing color and // then clears. These buttons are set up in the main class. private final static int CURVE = 0, LINE = 1, RECT = 2, // Some constants that code OVAL = 3, // for the different types of ROUNDRECT = 4, // figure the program can draw. FILLED_RECT = 5, FILLED_OVAL = 6, FILLED_ROUNDRECT = 7; private final static int NO_SYMMETRY = 0, // Some constants that code for SYMMETRY_2 = 1, // the different symmetry styles. SYMMETRY_4 = 2, SYMMETRY_8 = 3; Color customColor = Color.gray; // The custom color that is used // when the user selects "Custom Color" // as the drawing color or "Fill with Custom" // from the "Control" menu. This color // is changed when the user selects the // "Set Custom Color..." command. /* Some variables used for backing up the contents of the panel. */ Image OSI; // The off-screen image (created in checkOSI()). int widthOfOSI, heightOfOSI; // Current width and height of OSI. These // are checked against the size of the applet, // to detect any change in the panel's size. // If the size has changed, a new OSI is created. // The picture in the off-screen image is lost // when that happens. Image undoBuffer; // An off-screen image that is used to implement // the undo operation. When the user begins // a drawing operation, the OSI is copied to // undoBuffer. If the user selects the "Undo" // command, the OSI and the undoBuffer are swapped // and the panel is repainted to show the previous image. /* The following variables are used when the user is sketching a curve while dragging a mouse. */ private int mouseX, mouseY; // The location of the mouse. private int prevX, prevY; // The previous location of the mouse. private int startX, startY; // The starting position of the mouse. // (Not used for drawing curves.) private boolean dragging; // This is set to true when the user is drawing. private int figure; // What type of figure is being drawn. This is // specified by the figureChoice menu. private int symmetry; // What type of symmetry style is being used. This is // specified by the symmetryChoice menu. private Graphics dragGraphics; // A graphics context for the off-screen image, // to be used while a drag is in progress. private Color dragColor; // The color that is used for the figure that is // being drawn. Display() { // Constructor. When this component is first created, it is set to // listen for mouse events and mouse motion events from // itself. The initial background color is white. addMouseListener(this); addMouseMotionListener(this); setBackground(Color.white); setPreferredSize( new Dimension(450,450) ); } private Color getSelectedColor() { // Check the "Color" menu and return the color // that is currently selected. if (black.isSelected()) return Color.black; else if (red.isSelected()) return Color.red; else if (green.isSelected()) return Color.green; else if (blue.isSelected()) return Color.blue; else if (cyan.isSelected()) return Color.cyan; else if (magenta.isSelected()) return Color.magenta; else if (yellow.isSelected()) return Color.yellow; else if (white.isSelected()) return Color.white; else return customColor; } private int getSelectedShape() { // Check the "Shape" menu and return the code // for the shape that is currently selected. if (curve.isSelected()) return CURVE; else if (straightLine.isSelected()) return LINE; else if (rectangle.isSelected()) return RECT; else if (oval.isSelected()) return OVAL; else if (roundRect.isSelected()) return ROUNDRECT; else if (filledRectangle.isSelected()) return FILLED_RECT; else if (filledOval.isSelected()) return FILLED_OVAL; else return FILLED_ROUNDRECT; }; } private void drawFigure(Graphics g, int shape, int x1, int y1, int x2, int y2) { // This method is called to do ALL drawing in this applet! // Draws a shape in the graphics context g. // The shape parameter tells what kind of shape to draw. This // can be LINE, RECT, OVAL, ROUNTRECT, FILLED_RECT, // FILLED_OVAL, or FILLED_ROUNDRECT. (Note that a CURVE is // drawn by drawing multiple LINES, so the shape parameter is // never equal to CURVE.) For a LINE, a line is drawn from // the point (x1,y1) to (x2,y2). For other shapes, the // points (x1,y1) and (x2,y2) give two corners of the shape // (or of a rectangle that contains the shape). if (shape == LINE) { // For a line, just draw the line between the two points. g.drawLine(x1,y1,x2,y2); return; } int x, y; // Top left corner of rectangle that contains the figure. int w, h; // Width and height of rectangle that contains the figure. if (x1 >= x2) { // x2 is left edge x = x2; w = x1 - x2; } else { // x1 is left edge x = x1; w = x2 - x1; } if (y1 >= y2) { // y2 is top edge y = y2; h = y1 - y2; } else { // y1 is top edge. y = y1; h = y2 - y1; } switch (shape) { // Draw the appropriate figure. case RECT: g.drawRect(x, y, w, h); break; case OVAL: g.drawOval(x, y, w, h); break; case ROUNDRECT: g.drawRoundRect(x, y, w, h, 20, 20); break; case FILLED_RECT: g.fillRect(x, y, w, h); break; case FILLED_OVAL: g.fillOval(x, y, w, h); break; case FILLED_ROUNDRECT: g.fillRoundRect(x, y, w, h, 20, 20); break; } } private void putMultiFigure(Graphics g, int shape, int x1, int y1, int x2, int y2) { // Draws the shape and possibly some of its reflections. // The reflections that are drawn depend on the selected // item in symmetryChoice. The shapes are drawn by calling // the drawFigure method. int width = getWidth(); int height = getHeight(); drawFigure(g,shape,x1,y1,x2,y2); // Draw the basic figure if (symmetry >= SYMMETRY_2) { // Draw the horizontal reflection. drawFigure(g, shape, width - x1, y1, width - x2, y2); } if (symmetry >= SYMMETRY_4) { // Draw the two vertical reflections. drawFigure(g, shape, x1, height - y1, x2, height - y2); drawFigure(g, shape, width - x1, height - y1, width - x2, height - y2); } if (symmetry == SYMMETRY_8) { // Draw the four diagonal reflections. int a1 = (int)( ((double)y1 / height) * width ); int b1 = (int)( ((double)x1 / width) * height ); int a2 = (int)( ((double)y2 / height) * width ); int b2 = (int)( ((double)x2 / width) * height ); drawFigure(g, shape, a1, b1, a2, b2); drawFigure(g, shape, width - a1, b1, width - a2, b2); drawFigure(g, shape, a1, height - b1, a2, height - b2); drawFigure(g, shape, width - a1, height - b1, width - a2, height - b2); } } private void repaintRect(int x1, int y1, int x2, int y2) { // Call repaint on a rectangle that contains the points (x1,y1) // and (x2,y2). (Add a 1-pixel border along right and bottom // edges to allow for the pen overhang when drawing a line.) int x, y; // top left corner of rectangle that contains the figure int w, h; // width and height of rectangle that contains the figure if (x2 >= x1) { // x1 is left edge x = x1; w = x2 - x1; } else { // x2 is left edge x = x2; w = x1 - x2; } if (y2 >= y1) { // y1 is top edge y = y1; h = y2 - y1; } else { // y2 is top edge. y = y2; h = y1 - y2; } repaint(x,y,w+1,h+1); } private void repaintMultiRect(int x1, int y1, int x2, int y2) { // Call repaint on a rectangle that contains the points (x1,y1) // and (x2,y2). Also call repaint on reflections of this // rectangle, depending on the type of symmetry. The // rects are repainted by calling repaintRect(). int width = getWidth(); int height = getHeight(); repaintRect(x1,y1,x2,y2); // repaint the original rect if (symmetry >= SYMMETRY_2) { // repaint the horizontal reflection. repaintRect(width - x1, y1, width - x2, y2); } if (symmetry >= SYMMETRY_4) { // repaint the two vertical reflections. repaintRect(x1, height - y1, x2, height - y2); repaintRect(width - x1, height - y1, width - x2, height - y2); } if (symmetry == SYMMETRY_8) { // repaint the four diagonal reflections. int a1 = (int)( ((double)y1 / height) * width ); int b1 = (int)( ((double)x1 / width) * height ); int a2 = (int)( ((double)y2 / height) * width ); int b2 = (int)( ((double)x2 / width) * height ); repaintRect(a1, b1, a2, b2); repaintRect(width - a1, b1, width - a2, b2); repaintRect(a1, height - b1, a2, height - b2); repaintRect(width - a1, height - b1, width - a2, height - b2); } } private void checkOSI() { // This method is responsible for creating the off-screen image. // It should be called before using the OSI. It will make a new OSI if // the size of the panel changes. if (OSI == null || widthOfOSI != getSize().width || heightOfOSI != getSize().height) { // Create the OSI, or make a new one if panel size has changed. OSI = null; // (If OSI already exists, this frees up the memory.) undoBuffer = null; // (Free memory.) widthOfOSI = getWidth(); heightOfOSI = getHeight(); OSI = createImage(widthOfOSI,heightOfOSI); Graphics OSG = OSI.getGraphics(); // Graphics context for drawing to OSI. OSG.setColor(getBackground()); OSG.fillRect(0, 0, widthOfOSI, heightOfOSI); OSG.dispose(); undoBuffer = createImage(widthOfOSI,heightOfOSI); OSG = undoBuffer.getGraphics(); // Graphics context for drawing to undoBuffer OSG.setColor(getBackground()); OSG.fillRect(0, 0, widthOfOSI, heightOfOSI); OSG.dispose(); } } public void paintComponent(Graphics g) { // Copy the off-screen image to the screen, // after checking to make sure it exists. Then, // if a shape other than CURVE is being drawn, // draw it on top of the image from the OSI. checkOSI(); g.drawImage(OSI, 0, 0, this); if (dragging && figure != CURVE) { g.setColor(dragColor); putMultiFigure(g,figure,startX,startY,mouseX,mouseY); } } public void actionPerformed(ActionEvent evt) { // Respond when the user selects an item from the "Control" menu. String command = evt.getActionCommand(); checkOSI(); if (command.equals("Fill with Black")) clear(Color.black); else if (command.equals("Fill with Red")) clear(Color.red); else if (command.equals("Fill with Green")) clear(Color.green); else if (command.equals("Fill with Blue")) clear(Color.blue); else if (command.equals("Fill with Cyan")) clear(Color.cyan); else if (command.equals("Fill with Magenta")) clear(Color.magenta); else if (command.equals("Fill with Yellow")) clear(Color.yellow); else if (command.equals("Fill with White")) clear(Color.white); else if (command.equals("Fill with Custom")) clear(customColor); else if (command.equals("Set Custom Color...")) { Color c = JColorChooser.showDialog(this,"Select Custom Color",customColor); if (c != null) { // Change the custom color and select it for use as // the drawing color. customColor = c; custom.setSelected(true); } } else if (command.equals("Clear")) { // Clear to current background color. Graphics g = OSI.getGraphics(); g.setColor(getBackground()); g.fillRect(0,0,getSize().width,getSize().height); g.dispose(); repaint(); } else if (command.equals("Undo")) { // Undo the most recent drawing operation // by swapping OSI with undoBuffer. Image temp = OSI; OSI = undoBuffer; undoBuffer = temp; repaint(); } else if (command.equals("Quit")) { // Close the window and exit. Note: The // exit command will cause an error when // the frame is opened from an applet. // An applet should set the frame's standAlone // variable to false after creating the frame. dispose(); if (standAlone) System.exit(0); } } private void clear(Color background) { // Fill with the specified color. If the // color is equal to the current drawing color, then // the current drawing color is changed, so that // drawing operations will not be invisible. setBackground(background); if (background.equals(getSelectedColor())) { if (background.equals(Color.black)) white.setSelected(true); // On a black background, draw in white. else black.setSelected(true); // On other backgrounds, use black. } Graphics g = OSI.getGraphics(); g.setColor(getBackground()); g.fillRect(0,0,getSize().width,getSize().height); g.dispose(); repaint(); } public void mousePressed(MouseEvent evt) { // This is called when the user presses the mouse on the // panel. This begins a draw operation in which the user // sketches a curve or draws a shape. (Note that curves // are handled differently from other shapes. For CURVE, // a new segment of the curve is drawn each time the user // moves the mouse. For the other shapes, a "rubber band // cursor" is used. That is, the figure is drawn between // the starting point and the current mouse location.) if (dragging == true) // Ignore mouse presses that occur return; // when user is already drawing a curve. // (This can happen if the user presses // two mouse buttons at the same time.) prevX = startX = evt.getX(); // Save mouse coordinates. prevY = startY = evt.getY(); figure = getSelectedShape(); // Get data from menus for drawing. symmetry = getSelectedSymmetry(); dragColor = getSelectedColor(); checkOSI(); Graphics undoGraphics = undoBuffer.getGraphics(); undoGraphics.drawImage(OSI,0,0,null); // Remember the current image, // for "Undo" operations, // before changing the image. undoGraphics.dispose(); dragGraphics = OSI.getGraphics(); dragGraphics.setColor(dragColor); dragging = true; // Start drawing. } // end mousePressed() public void mouseReleased(MouseEvent evt) { // Called whenever the user releases the mouse button. // If the user was drawing a shape, we make the shape // permanent by drawing it to the off-screen image. if (dragging == false) return; // Nothing to do because the user isn't drawing. dragging = false; mouseX = evt.getX(); mouseY = evt.getY(); if (figure == CURVE) { // A CURVE is drawn as a series of LINEs putMultiFigure(dragGraphics,LINE,prevX,prevY,mouseX,mouseY); repaintMultiRect(prevX,prevY,mouseX,mouseY); } else if (figure == LINE) { repaintMultiRect(startX,startY,prevX,prevY); if (mouseX != startX || mouseY != startY) { // Draw the line only if it has non-zero length. putMultiFigure(dragGraphics,figure,startX,startY,mouseX,mouseY); repaintMultiRect(startX,startY,mouseX,mouseY); } } else { repaintMultiRect(startX,startY,prevX,prevY); if (mouseX != startX && mouseY != startY) { // Draw the shape only if both its height // and width are both non-zero. putMultiFigure(dragGraphics,figure,startX,startY,mouseX,mouseY); repaintMultiRect(startX,startY,mouseX,mouseY); } } dragGraphics.dispose(); dragGraphics = null; } public void mouseDragged(MouseEvent evt) { // Called whenever the user moves the mouse while a mouse button // is down. If the user is drawing a curve, draw a segment of // the curve on the off-screen image, and repaint the part // of the panel that contains the new line segment. Otherwise, // just call repaint and let paintComponent() draw the shape on // top of the picture in the off-screen image. if (dragging == false) return; // Nothing to do because the user isn't drawing. mouseX = evt.getX(); // x-coordinate of mouse. mouseY = evt.getY(); // y=coordinate of mouse. if (figure == CURVE) { // A CURVE is drawn as a series of LINEs. putMultiFigure(dragGraphics,LINE,prevX,prevY,mouseX,mouseY); repaintMultiRect(prevX,prevY,mouseX,mouseY); } else { // Repaint two rectangles: The one that contains the previous // version of the figure, and the one that will contain the // new version. The first repaint is necessary to restore // the picture from the off-screen image in that rectangle. repaintMultiRect(startX,startY,prevX,prevY); repaintMultiRect(startX,startY,mouseX,mouseY); } prevX = mouseX; // Save coords for the next call to mouseDragged or mouseReleased. prevY = mouseY; } // end mouseDragged. public void mouseEntered(MouseEvent evt) { } // Some empty routines. public void mouseExited(MouseEvent evt) { } // (Required by the MouseListener public void mouseClicked(MouseEvent evt) { } // and MouseMotionListener public void mouseMoved(MouseEvent evt) { } // interfaces). } // end nested class Display } // end class KaleidaPaint
[ Exercises | Chapter Index | Main Index ] | http://math.hws.edu/eck/cs124/javanotes4/c7/ex-7-8-answer.html | CC-MAIN-2018-47 | refinedweb | 4,707 | 51.14 |
How to Run Hornet On Kubernetes
This page explains how to run IOTA mainnet Hornet nodes in a Kubernetes (K8s) environment. Kubernetes is a portable, extensible, open-source platform for managing containerized workloads and services that facilitates both declarative configuration and automation. It has a large, rapidly growing ecosystem. K8s services, support, and tools are widely available on multiple cloud providers.
If you are not familiar with K8s we recommend you to start by learning the K8s technology.
Introduction
Running Hornet mainnet nodes on K8s can enjoy all the advantages of a declarative, managed, portable and automated container-based environment. However, as Hornet is a stateful service with several persistence, configuration and peering requirements, the task can be challenging. To overcome it, the IOTA Foundation under the one-click-tangle repository umbrella is providing K8s recipes and associated scripts that intend to educate developers on how nodes can be automatically deployed, peered and load balanced in a portable way.
This script allows you to run sets of Hornet instances "in one click" in your K8s' environment of choice and also provides a blueprint with the best practices K8s administrators can leverage when deploying production-ready environments.
Deploying Using the “One Click” Script
For running the one click script you need to get access to a K8s cluster. For local development, we recommend microk8s. Instructions on how to install it can be found here. You may also need to enable the ingress add-on on micro-k8s by running
microk8s.enable ingress.
You will also need to properly configure the kubectl command-line tool to get access to your cluster.
You can pass the following parameters as variables on the command line to the one-click script:
NAMESPACE: The namespace where the one-click script will create the K8s objects.
tangleby default.
PEER: A multipeer address that will be used to peer your nodes with. If you do not provide an address, auto-peering will be configured for the set's first Hornet Node (
hornet-0).
INSTANCES: The number of Hornet instances to be deployed.
1by default.
INGRESS_CLASS: The class associated with the Ingress object that will be used to externally expose the Node API endpoint so that it can be load balanced. It can depend on the target K8s environment.
nginxby default.
You can deploy a Hornet Node using the default parameter values by running the following command:
hornet-k8s.sh deploy
After executing the script, different Kubernetes objects will be created under the
tangle namespace, as enumerated and depicted below. You can see the
kubectl instruction to get more details about them.
kubectl get namespaces
NAME STATUS AGE
default Active 81d
tangle Active 144m
kube-node-lease Active 81d
kube-public Active 81d
kube-system Active 81d
- A StatefulSet named
hornet-setthat controls the different Hornet instances and enables scaling them.
kubectl get statefulset -n tangle -o=wide
NAME READY AGE CONTAINERS IMAGES
hornet-set 1/1 20h hornet gohornet/hornet:1.1.3
- One Pod per Hornet Node bound to our StatefulSet. A pod is an artifact that executes the Hornet Docker container.
kubectl get pods -n tangle
NAME READY STATUS RESTARTS AGE
hornet-set-0 1/1 Running 0 20h
You may have noticed that the pod's name is the concatenation of the name of the Statefulset
hornet-set plus an index indicating the pod number in the set (in this case
0). If you scaled your StatefulSet to
2, you would have two pods (
hornet-set-0 and
hornet-set-1).
- One Persistent Volume Claim bound to each instance of the StatefulSet. It is used to permanently store all the files corresponding to the internal databases and snapshots of a Hornet Node.
kubectl get pvc -n tangle -o=wide
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE
hornet-ledger-hornet-set-0 Bound pvc-905fe9c7-6a10-4b29-a9fd-a405fd49a5fd 20Gi RWO standard 157m
The name of the Persistent Volume Claim is the concatenation of
hornet-ledger plus the name of the bound Pod,
hornet-set-0 in our case.
- Service objects:
- One Service Node Port object exposes the REST API of the nodes. It is a load balancer to port
14625of all the Nodes.
- One Service Node Port object per Hornet instance (in this example, just one) which exposes as a "Node Port" the gossip, dashboard, and auto-peering endpoints.
kubectl get services -n tangle -o=wide
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR
hornet-0 NodePort 10.60.4.75 <none> 15600:30744/TCP,8081:30132/TCP,14626:32083/UDP 19h statefulset.kubernetes.io/pod-name=hornet-set-0
hornet-rest NodePort 10.60.3.96 <none> 14265:31480/TCP 19h app=hornet
You can run
kubectl describe services -n tangle to get more details about the endpoints supporting the referred Services.
The name of the Services is important as it will allow you to address Hornet Nodes by DNS name within the cluster. For instance, if you want to peer a Hornet Node within the cluster, you can refer to it with the name of its bound Service, for example,
hornet-0.
- An Ingress controller intended to expose the load-balanced Hornet REST API endpoint outside the cluster, under the
/apipath. For convenience, the dashboard corresponding to the first Hornet in the StatefulSet (
hornet-0) is also exposed through the
/path.
kubectl get ingress -n tangle -o=wide
NAME CLASS HOSTS ADDRESS PORTS AGE
hornet-ingress <none> * 34.1.1.1 80 21h
In the example above, you can observe that the public IP address of the load balancer associated with the Ingress Controller is shown. This will happen when you deploy on a commercial, public cloud service.
- A ConfigMap that contains the configuration applied to each Hornet Node, including the peering configuration. Remember that your Hornet nodes, which belong to a StatefulSet, are peered among them.
kubectl get configmap -n tangle -o=wide
NAME DATA AGE
hornet-config 4 19h
kube-root-ca.crt 1 19h
Likewise, you can run
kubectl describe configmap hornet-config to obtain more details about the ConfigMap.
Secrets of the Nodes (keys, etc.). Two secrets are created:
hornet-secret: Contains secrets related to the dashboard credentials (hash and salt).
hornet-private-key: Contains the Ed25519 private keys of each node.
kubectl get secrets -n tangle -o=wide
NAME TYPE DATA AGE
default-token-fks6m kubernetes.io/service-account-token 3 20h
hornet-private-key Opaque 1 20h
hornet-secret Opaque 2 20h
This blueprint does not provide Network Policies. However, in a production environment, they should be defined so that Pods are properly restricted to perform outbound connections or receive inbound connections.
Accessing Your Hornet Node
Once you have deployed your Hornet Node on the cluster, you will want to access it from the outside. Fortunately, that is easy as you have already created K8s Services of type Node Port. This means that your Hornet Node will be accessible through certain ports published on the K8s machine (worker node in K8s terminology) where Hornet is actually running.
If you execute:
kubectl get services -n tangle
hornet-0 NodePort 10.60.4.75 <none> 15600:30744/TCP,8081:30132/TCP,14626:32083/UDP 20h
hornet-rest NodePort 10.60.3.96 <none> 14265:31480/TCP 20h
In the example above, the REST API endpoint of your Hornet Node will be accessible through the port
31480 of a K8s worker. Likewise, the Hornet dashboard will be exposed on the port
30744.
If you are running microk8s locally in your machine, you will typically have only one K8s machine running as a virtual machine. Usually, the IP address of the virtual machine is
192.168.64.2. You can double-check the IP address by displaying your
current kubectl configuration running the following command:
kubectl config view | grep server
You should receive an output similar to the endpoint of the K8s API Server.
server:
Additionally, you can get access to your Hornet Node REST API endpoint through the external load balancer defined by the Ingress Controller. If you are using a local configuration, this will not make much difference as the machine where the Ingress Controller lives is the same as the Service machine (more details at). However, in the case of a real environment provided by a public cloud provider, your Ingress controller will usually be mapped to a load balancer exposed through a public IP address. You can find more information in the commercial public cloud environment's specifics section.
Remember that it might take a while for your Hornet Pods to be running and ready
Working With Multiple Instances
If you want to work with multiple instances, you can scale your current K8s StatefulSet by running:
INSTANCES=2 hornet-k8s.sh scale
If the cluster has enough resources, a new Hornet Node will automatically be spawned and peered with your original one.
You will notice that one more Pod (
hornet-set-1) will be running:
kubectl get pods -n tangle -o=wide
NAME READY STATUS RESTARTS AGE
hornet-set-0 1/1 Running 0 24h
hornet-set-1 1/1 Running 0 24h
However, if your cluster does not have enough resources, the new POD will still be listed but its status will be
Pending:
hornet-set-1 0/1 Pending 0 2m12s
You can find more details on the reasons why the new Pod is not running by executing:
kubectl describe pods/hornet-set-1 -n tangle
If your Pod is running properly, a new Persistent Volume will be listed as well:
kubectl get pvc -n tangle -o=wide
hornet-ledger-hornet-set-0 Bound pvc-905fe9c7-6a10-4b29-a9fd-a405fd49a5fd 20Gi RWO standard 24h
hornet-ledger-hornet-set-1 Bound pvc-95b3b566-4602-4a36-8b1b-5e6bf75e5c6f 20Gi RWO standard 24h
And an additional Service
hornet-1:
kubectl get services -n tangle -o=wide
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
hornet-0 NodePort 10.60.4.75 <none> 15600:30744/TCP,8081:30132/TCP,14626:32083/UDP 24h
hornet-1 NodePort 10.60.7.44 <none> 15600:32184/TCP,8081:31776/TCP,14626:31729/UDP 24h
hornet-rest NodePort 10.60.3.96 <none> 14265:31480/TCP 24h
The REST service will be load balancing two Pods. You can verify this by running the following command:
kubectl describe services/hornet-rest -n tangle
Name: hornet-rest
Namespace: tangle
Labels: app=hornet-api
source=one-click-tangle
Selector: app=hornet
Type: NodePort
IP Family Policy: SingleStack
IP Families: IPv4
IP: 10.60.3.96
IPs: 10.60.3.96
Port: rest 14265/TCP
TargetPort: 14265/TCP
NodePort: rest 31480/TCP
Endpoints: 10.56.0.18:14265,10.56.9.32:14265
Session Affinity: None
External Traffic Policy: Cluster
If your
hornet-0 node is synced,
hornet-1 should also be synced as
hornet-0 and
hornet-1 will have peered. You can verify this by connecting to the corresponding dashboards.
Deep Dive. The "One-Click" Script Internals
In this section, you can find the internals of our blueprints for deploying Hornet Nodes on K8s. The figure below depicts the target deployment architecture behind our proposed blueprint.
The figure shows the K8s objects used and their relationships. The following sections will provide more details about them, and the K8s manifests that declare them (available at the repository). The label
source=one-click-tangle is used to mark these K8s objects that will live under a specific Namespace (named
tangle by default).
StatefulSet
hornet-set
The
hornet.yaml source file contains the definition of the StatefulSet (
hornet-set) that templates and controls the execution of the Hornet Pods. The StatefulSet is also bound to a
volumeClaimTemplate so that each Hornet Node on the set can be bound to its own K8s Persistent Volume. The StatefulSet is labeled as
source=one-click-tangle and the selector used for the Pods is
app=hornet. Additionally, the StatefulSet is bound to the Service
hornet-rest.
The template contains the Pod definition, which declares different volumes:
configurationwhich is mapped to the
hornet-configConfigMap.
private-keywhich is mapped to the
hornet-private-keySecret.
secrets-volumean
emptyDirinternal volume where the Hornet Node private key will be actually copied.
The Pod definition within the StatefulSet contains one initialization container (
create-volumes) and one regular container (
hornet). The initialization container is in charge of preparing the corresponding volumes so that the
hornet container volume mounts are ready to be used with the proper files inside and suitable permissions. The initialization container copies the Hornet Node private key and peering configuration so that each Hornet is bound to its private key and peering details.
The
hornet container declares the following volume mounts, which are key for the
hornet container to run properly within its Pod:
/app/config.jsonagainst the
configurationvolume.
app/p2p2storeagainst the
p2pstoresubfolder of the
hornet-ledgerPersistent Volume.
app/p2pstore/identity.keyagainst the transient, internal
secrets-volumeof the Pod.
app/peering.jsonagainst the
peeringsubfolder of the
hornet-ledgerPersistent Volume. This is necessary as the peering configuration is dynamic, and new peers might be added during the lifecycle of the Hornet Node.
app/mainnetdbagainst the
mainnetdbsubfolder of the
hornet-ledgerPersistent Volume to store the database files.
app/snapshots/mainnetagainst the
snapshotssubfolder of the
hornet-ledgerPersistent Volume to store snapshots.
The Pod template configuration also declares extra configuration details such as
liveness and
readiness probes, security contexts, and links to other resources such as the Secret that defines the dashboard credentials, mapped into environment variables.
Services
Two different kinds of Services are used in our blueprint:
A Node Port Service
hornet-rest(declared by the
hornet-rest-service.yamlmanifest) that is bound to the StatefulSet and the port
14265of the Hornet Nodes. Its purpose is to expose the REST API endpoint of the Hornet nodes. The endpoint Pods of such a Service are labeled as
app=hornet.
One Node Port Service (
hornet-0,
hornet-1, ...,
hornet-n) per Hornet Node, declared by the
hornet-service.yamlmanifest. These Node Port Services expose access to the individual dashboard and gossip and auto-peering endpoints of each node. Thus, it is only bound to one and only one Hornet Node. For this purpose, its configuration includes
externalTrafficPolicy
localand a selector named
statefulset.kubernetes.io/pod-name: hornet-set-xwhere
xcorresponds to the Pod number of the Hornet Node the Service is bound. Under the hood, the one-click script takes care of creating as many Services of this type as needed.
Ingress Controller
hornet-ingress
The Ingress Controller
hornet-ingress is configured so that the
hornet-rest Service can be externally load-balanced. There are two path mappings,
/api, whose backend is the
hornet-rest Service, and
/ whose backend is the dashboard of the
hornet-0 Service. The latter exists for convenience reasons of this blueprint. In the default configuration, the
kubernetes.io/ingress.class is
nginx, but you can override that for specific cloud environments (see below).
ConfigMap and Secrets
For ConfigMaps and Secrets, there are no YAML definition files as they are created on the fly through the
kubectl command line.
They are created from a
config directory automatically generated by the "one-click" script. You can see the contents of those objects by running the following command:
kubectl get configmap/hornet-config -n tangle -o=yaml
The same goes for the Hornet dashboard credentials (all the nodes share the same admin credentials).
kubectl get secrets/hornet-secret -n tangle -o=yaml
As well as for the Nodes' private keys:
kubectl get secrets/hornet-private-key -n tangle -o=yaml
Commercial Public Cloud Environments Specifics
Google Kubernetes Environment (GKE)
The deployment recipes are fully portable to the GKE public cloud environment. You will only need to ensure that the Ingress Controller is correctly annotated with
kubernetes.io/ingress.class: gce. You can do this by executing the following command:
kubectl annotate -f hornet-ingress.yaml -n $NAMESPACE --overwrite kubernetes.io/ingress.class=gce
Alternatively, if you are using the "one-click" script you can simply execute the following command and the one-click script will perform the annotation during the deployment process.:
INGRESS_CLASS=gce hornet-k8s.sh deploy
The process of deploying an external load balancer by a public cloud provider can take a while.
If you want to get access to the Service Node Ports, you will need to have a cluster with public K8s workers. You can determine the public IP addresses of your K8s workers by running:
kubectl get nodes -o=wide
Then, you can determine on which K8s worker your Hornet Pod is running by executing the following command (the default
NAMESPACE is
tangle):
kubectl get pods -n $NAMESPACE -o=wide
Once you determine the worker and its IP address, you can access each Hornet Node by knowing the Node ports declared by the corresponding service. You can do this by running the following command:
kubectl get services -n $NAMESPACE
Once you know the port, you will have to create firewall rules so that the port is reachable. That can be done using the gcloud tool. For instance, if your Hornet Node's dashboard is mapped to port
34200 and the public IP address of our K8s worker is
1.1.1.1:
gcloud compute firewall-rules create test-hornet-dashboard --allow tcp:34200
Now, you can open up a browser and load to access the Hornet Node's dashboard.
You may also have to look into encrypting Secrets when moving to a production-ready system.
Amazon Kubernetes Environment (EKS)
The deployment recipes are fully portable to the EKS commercial public cloud environment. However, there are certain preparation steps (including IAM permission grants) that have to be executed on your cluster so that the Ingress Controller is properly mapped to an AWS Application Load Balancer (ALB). Additionally, as it happens with the GKE environment, you can access your Hornet Nodes through its Service Node Port. The procedure requires a cluster with public workers and security groups configured so that traffic is enabled to the corresponding Service Node Ports.
You will need to follow several preparation steps on your cluster to map the Ingress Controller objects to AWS Application Load Balancers. Please read these documents and follow the corresponding instructions on your cluster:
- AWS Docs - Create a kubeconfig for Amazon EKS
- AWS Docs - Application load balancing on Amazon EKS
- AWS Docs - AWS Load Balancer Controller
- Kubernets Docs - AWS Load Balancer Controller
You will also need to annotate your Ingress Controller with the following:
kubernetes.io/ingress.class=alb
alb.ingress.kubernetes.io/scheme=internet-facing
alb.ingress.kubernetes.io/subnets: A comma-separated list of the IDs of the subnets that can actually host the Services being load balanced, for instance
subnet-aa1649cc, subnet-a656cffc, subnet-fdf3dcb5.
Remember that you can annotate your Ingress Controller by running
kubectl annotate.
If you have made all the preparations and annotations properly, you will be able to find the DNS name of your external load balancer when you execute the following command (Please note it can take a while for DNS servers to sync up):
kubectl get ingress -n $NAMESPACE -o=wide
NAME CLASS HOSTS ADDRESS PORTS AGE
hornet-ingress <none> * xyz.eu-west-1.elb.amazonaws.com 80 71m
Conclusion
Reference recipes are key in facilitating the deployment of IOTA mainnet Hornet nodes. The IOTA Foundation provides them as a blueprint that can be customized by developers and administrators in their journey towards production-ready deployment. The reference recipes have been designed with portability and simplicity in mind and tested successfully on some popular commercial public cloud environments. | https://wiki.iota.org/introduction/how_tos/mainnet_hornet_node_k8s | CC-MAIN-2022-33 | refinedweb | 3,255 | 51.89 |
Jim Fulton wrote:
PLease submit a collector issue at: A test would be especially helpful.
Yeehaw, I was afraid someone would ask for such a thing. I must admit I actually wasn't able to write it up to now, since I'm not too familiar with all the traversal stuff and the like and howto setup a test for that issue. Poor me - I figured out the solution by torturing our app with a bunch of simultaneous requests and provoking some ConflictErrors. Since that is not helpful at all, someone may help me on writing a formal test? greetings, Sven
Jim On Jul 18, 2006, at 4:28 AM, Sven Schomaker wrote:Hi all, the retry of a request in case of a ConflictError in Zope 3.2.1 fails with a NotFound error, while looking up the requested view in zope/app/traversing/namespace.py (line 362). It seems as the newly created request (in request.retry()) does somehow not satisfy the adapter prerequisites to successfully look up a view in zope.component.queryMultiadapter. I did not dig too deep to find out what exactly goes wrong in the old statement used to create the new request instance, but I suppose somehow not all specifications (interfaces) of the original request are set up on the new request. Nevertheless I came up with a (quick) fix in zope/publisher/http.py that circumvents the issue. I don't know whether this is already fixed in the trunk or the fix appeals to the devs with check-in permissions, but maybe someone wants to look at it and check it in (or comes up with a better/more precise one:)). greetings, Sven Schomaker Index: http.py =================================================================== --- http.py (revision 178) +++ http.py (working copy) @@ -15,6 +15,7 @@ $Id: http.py 41004 2005-12-23 21:01:20Z jim $ """ +from copy import copy import re, time, random from cStringIO import StringIO from urllib import quote, unquote, splitport @@ -435,13 +436,12 @@ 'See IPublisherRequest' count = getattr(self, '_retry_count', 0) self._retry_count = count + 1 - - new_response = self.response.retry() - request = self.__class__( + request = copy(self) + request.__init__( # Use the cache stream as the new input stream. body_instream=self._body_instream.getCacheStream(), environ=self._orig_env, - response=new_response, + response=self.response.retry(), ) request.setPublication(self.publication) request._retry_count = self._retry_count _______________________________________________ Zope3-dev mailing list Zope3-dev@zope.org Unsub:-- Jim Fulton mailto:[EMAIL PROTECTED] Python Powered! CTO (540) 361-1714 Zope Corporation
-- __________________Addressed by:_________________ Sven Holger Cochise Schomaker, Dipl.-Inf. (FH) Linie M - Metall Form Farbe - GmbH Industriestrae 8 63674 Altenstadt (Hessen) Germany Tel.: +49 (0)6047 97121 Fax: +49 (0)6047 97122 Mail: [EMAIL PROTECTED] Public Key: hkp://subkeys.pgp.net Key ID: F04D3E4FKey fingerprint: 79BD FBEB F6AE 7005 8374 320A 0D13 F202 F04D 3E4F
_______________________________________________ _______________________________________________ Zope3-dev mailing list Zope3-dev@zope.org Unsub: | https://www.mail-archive.com/zope3-dev@zope.org/msg05743.html | CC-MAIN-2018-05 | refinedweb | 473 | 57.37 |
Type: Posts; User: jopeters
Thank you for your insite
thank you Paul McKenzie, I made a silly mistake and forgot those underscores, but the program DOES run when I use "using namespace std;"
I've tried including #include <vector> at the top but it generates the same errors.
When I add namespace std it fixes the previous errors but gives me the following error on my implementation...
I'm trying to declare two vectors within the private section of a class "rover" I am working on.
#ifndef ROVER_H
#define ROVER_H
I am having problems with a series of sorting and deleting. The program is supposed to sort the names in a vector in a way that the "goose" is deleted. The "goose" is input by the user as a number...
solved the previous problem! thanks for all your help lindley you are the man.
you were right, it will compile but it crashes when the main calls the wackGoose function.
void wackGoose(const vector<string>&names, int goose)
//eliminates the gooseth entry over and over...
I thought you meant to pass them as follows:
void wackGoose(const vector<string>&names, int goose);
But when I do that I get the following compiler errors.
Error 1 error LNK2001:...
thanks a ton that info will definitely be helpful. Unfortunately I cannot use the std::swap() function for this assignment due to restrictions from my professor. At this point I am less concerned...
THE FIRST PART OF THIS IS BACKGROUND INFO ABOUT THE PROGRAM
I'm trying to write a program that inputs names from a file into a vector. The user will enter a number greater than 0 to be the...
ok thanks ill see what i can do
I'm a little confused what you mean, what are the 0, 3, 6, etc representing?
I'm trying to write a tic tac toe game and can't figure out how to check and see if someone is the winner? I'm using a 2 dimensional array thats 3 by 3 (like a tic tac toe board) and all the "blank"...
nevermind im on to something.
I need to write a function named:
int getNumAccidents()
the function is passed the names of a region within a city (north, south, east, west) The function also asks the user for the number...
i tried the forward slashes and double back slashes and still got the same output =/
also a side note, that not gunna be the full program, just that snippet.
int year;
float population;
ifstream fin;
fin.open("C:\Users\Josh\Desktop\c++\people.dat");
fin >> year >> population;
cout << year << endl << population;
the || in the first line of the if statement are actually supposed to be &&, i fixed that.
i thought my code was good but apparently not,
if (average >= 0 || average <=100)
else if (average >= 90) // <-- this is the line the error takes...
I'm trying to write a rather simple code, that allowed you to cin your name, and get something out of cout based on what you put in. Basically I want to have a response correlated to each of my... | http://forums.codeguru.com/search.php?s=c93b1cc7e4d5b485a3c34b3a1eae04fc&searchid=7208871 | CC-MAIN-2015-27 | refinedweb | 521 | 70.33 |
.
This problem might seem to call for a two-dimensional segment tree at this point, but there's a significantly easier way. We can keep two-dimensional prefix sums representing the bounds of each rectangle to quickly compute, for any grid square, how many rectangles have been drawn over that square. Once we've done so, we iterate over every grid square. If a certain color appears at that square, and we calculate that two or more rectangles have been drawn at that square, then we "invalidate" that color -- it cannot possibly have been drawn first, as it's showing up over another rectangle.
Below is Brian Dean's solution. At the top-left and bottom-right grid squares of each rectangle, he increases the value of $\texttt{P}$ at that square by 1, and at the bottom-left and top-right squares, he decreases the value of $\texttt{P}$ by 1. Then he computes the array $\texttt{A}$ as the prefix sums of that array. Each value of $\texttt{A}$ will also be equal to the number of rectangles located at that point -- if you aren't sure why this is true, it's a good exercise to work out for yourself.
#include <iostream> #include <fstream> #define MAX_N 1000 #define MAX_C (MAX_N*MAX_N) using namespace std; int upper[MAX_C+1], lower[MAX_C+1], leftside[MAX_C+1], rightside[MAX_C+1]; int N, total, art[MAX_N+1][MAX_N+1], count[MAX_C+1]; int P[MAX_N+1][MAX_N+1], A[MAX_N+1][MAX_N+1]; int main(void) { ifstream fin("art.in"); ofstream fout("art.out"); fin >> N; for (int i=0; i<N; i++) for (int j=0; j<N; j++) fin >> art[i][j]; for (int i=1; i<=N*N; i++) upper[i] = leftside[i] = N; for (int i=0; i<N; i++) for (int j=0; j<N; j++) { int c = art[i][j]; if (c > 0) { if (count[c]==0) total++; count[c]++; upper[c] = min(upper[c], i+1); lower[c] = i+1; leftside[c] = min(leftside[c], j+1); rightside[c] = max(rightside[c], j+1); } } if (total==1) fout << N*N-1 << "\n"; else { int answer = N*N-total; for (int c=1; c<=N*N; c++) if (c>0 && count[c]>0) { P[lower[c]][rightside[c]]++; P[lower[c]][leftside[c]-1]--; P[upper[c]-1][rightside[c]]--; P[upper[c]-1][leftside[c]-1]++; } for (int j=1; j<=N; j++) A[N][j] = P[N][j]; for (int i=N-1; i>=1; i--) { A[i][N] = A[i+1][N] + P[i][N]; for (int j=N-1; j>=1; j--) A[i][j] = A[i+1][j] + A[i][j+1] - A[i+1][j+1] + P[i][j]; } for (int i=1; i<=N; i++) for (int j=1; j<=N; j++) { int c = art[i-1][j-1]; if (c>0 && count[c]>0 && A[i][j]>=2) count[c] = 0; } for (int c=1; c<=N*N; c++) if (count[c]>0) answer++; fout << answer << "\n"; } return 0; } | http://usaco.org/current/data/sol_art_platinum_open17.html | CC-MAIN-2017-13 | refinedweb | 512 | 56.12 |
On Tue, Sep 8, 2020 at 7:00 PM Shantanu Jain hauntsaninja@gmail.com wrote:
I found Jukka’s referenced comment to be valuable, so here’s a direct link: Eg, I believe pyright’s narrowing to Animal corresponds in part to Jukka’s Proposal 2 (or Proposal 4), which he mentions is TypeScript’s behaviour: when narrowing a Union, narrow to a member of the Union.
My view on the invariance issue is the most natural flow is to start with:
def g(x: Foo[Union[int, str]]): ... def f() -> None: y = 1 a = Foo(y) g(a)
Then get an error (with a very clear message / suggestion) and add:
def f() -> None: y = 1 a: Foo[Union[int, str]] = Foo(y) g(a)
Which is fine in the presence of type narrowing, because obviously we shouldn’t narrow to an incompatible type. (It’s also my opinion that this is the type annotation that best helps describe what’s happening)
I don’t know that I’d be so quick to write off always narrowing (modulo Any), which I believe corresponds to Jukka’s Proposal 3. I’d be curious to know more about the significant number of false positives you’d expect; that seems contra my intuition and the results on the sample corpus Jukka described. It also feels wrong to mandate that all future type checkers can’t narrow in part because a majority of our current ones do not. It feels like if a type checker can prove something about a value, it should be fair game (and that as long as users can see that proof is possible, we’ll get bug reports).
Generally speaking, it’s surprising to me to make a usability argument for a distinction that most end users wouldn’t notice or weren’t making with intention. But maybe this is a case where if the behaviour is PEP-ed users will no longer find it surprising.
These are all good points. I remember that in Closure Compiler, we used to have the semantics where we keep the rhs type. We ran into issues occasionally where the user needed to use the value with the declared type, so they had to cast to that, which was annoying. We ended up changing the semantics to use the declared type. Unfortunately I can't remember the examples anymore though; just the generics one I already mentioned.
On Tue, 8 Sep 2020 at 09:28, dimvar--- via Typing-sig < typing-sig@python.org> wrote:
I also prefer form (1) to respect the declared type and not use the rhs type. Keeping the declared type can avoid a spurious warning in cases where type invariance matters, e.g., with generics.
T = TypeVar('T')
class Foo(Generic[T]): def __init__(self, x: T) -> None: self.attr = x
def g(x: Foo[Union[int, str]]): return x
def f(x: int): y: Union[int, str] = 1 a = Foo(y) g(a) # no warning
y = 2 b = Foo(y) reveal_type(b) g(b) # warning
Typing-sig mailing list -- typing-sig@python.org To unsubscribe send an email to typing-sig-leave@python.org Member address: hauntsaninja@gmail.com | https://mail.python.org/archives/list/typing-sig@python.org/message/WO5KWVO7AULYSDDBV3FRB33A3CAZ5QGC/ | CC-MAIN-2022-40 | refinedweb | 531 | 66.78 |
Ok I'm just going over the basic trying to sharping my skills. I was looking over this program and I was reading the "How It Works " section telling me I should add the break so the loop doesn't keep running and stuff like that. Then it said instead of wright the code like this
I should wright it like thisI should wright it like thisCode:int is_prime; is_prime = true;
and I was jw as you can see below should I also do the same forand I was jw as you can see below should I also do the same forCode:int is_prime = true
thanks. sorry for this crappy question.thanks. sorry for this crappy question.Code:is_prime = false;
Code:#include <iostream> #include <cmath> int main ( ) { int n; int i; int is_prime = true; std::cout << "Enter a number and press ENTER: "; std::cin >> n; i = 2; while ( i <= sqrt ( double ( n ) ) ) { if ( n % i == 0 ) { is_prime = false; break; } i++; } if ( is_prime ) { std::cout << "Number is prime. "; } else { std::cout << "Number is not prime. "; } std::cout << std::endl; return ( 0 ); } | https://cboard.cprogramming.com/cplusplus-programming/112772-help-if-basic-question.html | CC-MAIN-2017-13 | refinedweb | 180 | 84.2 |
RE: WSE 3.0 SOAP Router for load balancing
- From: SoGMo <AgentSmith@xxxxxxxxxxxxx>
- Date: Fri, 31 Aug 2007 12:30:00 -0700
Hi Steven,
Thanks for your reply, it answers my question.
It is not allways possible for us to go the hardware or windows based load
balancing way as it depends on customer infrastructure.
I had just understood that it was possible to do load balancing
functionallity based on configuration of the refferalCache, but unfortunately
this is not the case.
I was going to take a custom approch to "Route SOAP Messages Based Upon
Their Content", which you also describes in #2. Then I could store the
routing information in a database (or xml file), and maybe even do a mix of
load balancing and content based routing in the custom routing functionality.
It leaves an issue of a dynamic URI in the SoapActor attribute of the
recieving services.
*************
[SoapActor("")]
public class StockTraderService : System.Web.Services.WebService
{
//Web service implementation
}
*************
To make it all configurable, it would be great if this URI could be fetched
from the database as well, but as far as I know this is not possible because
this is compiled code - or is it?
Sincerely
Glenn M. Sørensen
"Steven Cheng[MSFT]" wrote:
Hi Glenn,.
For the WSE 3 loading balance, I think you can consider the following
approaches:
1. Is it possible that you use hardware or windows operating system's
loading balance feature? Thus, you can simply let a single front server
accept the requests and let the underlying loading balance framework to
redirect requests to back end service server
2. WSE 3.0's rounter feature is mainly used for hidden the backend service
server from front end client users. If you want to use it in a loading
balance model, I think you may need to write the custom SoapRouter and do
the loading balance redirect code logic in it:
#Routing SOAP Messages with WSE
#How to: Route SOAP Messages Based Upon Their Content
As in the "Route SOAP Messages Based Upon Their Content" example indicate,
you can programmatically determine the target url you want to redirect a
WSE request, and for your custom loading balance router, you may need to
give the proper target servers(from all balance servers) url.,
I've read several places and in several books, that you can implement load
balancing with WSE 3.0 and the httpHandler
Microsoft.Web.Services3.Messaging.SoapHttpRouter component (WS-Referral). I
have only been able to implement the chain and content.based routing models.
Does anyone know if and how you implement the load balancing routing model?
/Glenn
- References:
- RE: WSE 3.0 SOAP Router for load balancing
- From: Steven Cheng[MSFT]
- Prev by Date: RE: WSE 3.0 SOAP Router for load balancing
- Previous by thread: RE: WSE 3.0 SOAP Router for load balancing
- Index(es): | http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.webservices.enhancements/2007-08/msg00018.html | crawl-002 | refinedweb | 477 | 62.27 |
The LesHouchesEventHandler inherits from the general EventHandler class and administers the reading of events generated by external matrix element generator programs according to the Les Houches accord.
More...
#include <LesHouchesEventHandler.h>
HandlerGroup
The LesHouchesEventHandler inherits from the general EventHandler class and administers the reading of events generated by external matrix element generator programs according to the Les Houches accord.
The class has a list of LesHouchesReaders which typically are connected to files with event data produced by external matrix element generator programs. When an event is requested by LesHouchesEventHandler, one of the readers are chosen, an event is read in and then passed to the different StepHandler defined in the underlying EventHandler class.
LesHouchesReader
StepHandler
Definition at line 41 of file LesHouchesEventHandler.h.
Enumerate the weighting options.
All events have unit weight.
All events have wight +/- 1.
Varying positive weights.
Varying positive or negative weights.
Definition at line 58 of file LesHouchesEventHandler.h.
Make a simple clone of this object.
Reimplemented from ThePEG::EventHandler.
Finalize this object.
Called in the run phase just after a run has ended. Used eg. to write out statistics.
Initialize this object after the setup phase before saving an EventGenerator to disk.
Reimplemented from ThePEG::InterfacedBase.
Initialize this object.
Called in the run phase just before a run begins.
Make a clone of this object, possibly modifying the cloned object to make it sane.
Histogram scale.
A histogram bin which has been filled with the weights associated with the Event objects should be scaled by this factor to give the correct cross section.
Referenced by LesHouchesEventHandler().
The standard Init function used to initialize the interfaces.
Called exactly once for each class by the class description system before the main function starts or when this class is dynamically loaded.
Referenced by currentReader().
The estimated total integrated cross section of the processes generated in this run.
The estimated error in the total integrated cross section of the processes generated in this run.
The assignment operator is private and must never be called.
In fact, it should not even be implemented.
Create the Event and Collision objects.
Used by the generateEvent() function.
Function used to read in object persistently.
Function used to write out object persistently.
An event has been selected.
Signal that an event has been selected with the given weight. If unit weights are requested, the event will be accepted with that weight. This also takes care of the statistics collection of the selected reader object.
Skip some events.
To ensure a reader file is scanned an even number of times, skip a number of events for the selected reader.
Collect statistics for this event handler.
To be used for histogram scaling.
Definition at line 327 of file LesHouchesEventHandler.h.
The static object used to initialize the description of this class.
Indicates that this is a concrete class with persistent data.
Definition at line 429 of file LesHouchesEventHandler.h. | https://thepeg.hepforge.org/doxygen/classThePEG_1_1LesHouchesEventHandler.html | CC-MAIN-2018-39 | refinedweb | 483 | 52.56 |
Break
Although you have already seen the break statement in the context of switch statements (7.4 -- Switch statement basics), it deserves a fuller treatment since it can be used with other types of loops as well. The break statement causes a while loop, do-while loop, for loop, or switch statement to end, with execution continuing with the next statement after the loop or switch being broken out of.
break statement
switch statements
Breaking a switch
In the context of a switch statement, a break is typically used at the end of each case to signify the case is finished (which prevents fallthrough into subsequent cases):
switch statement
break
See lesson 7.5 -- Switch fallthrough and scoping for more information about fallthrough, along with some additional examples.
Breaking a loop
In the context of a loop, a break statement can be used to end the loop early. Execution continues with the next statement after the end of the loop.
For example:
This program allows the user to type up to 10 numbers, and displays the sum of all the numbers entered at the end. If the user enters 0, the break causes the loop to terminate early (before 10 numbers have been entered).
Here’s a sample execution of the above program:
Enter a number to add, or 0 to exit: 5
Enter a number to add, or 0 to exit: 2
Enter a number to add, or 0 to exit: 1
Enter a number to add, or 0 to exit: 0
The sum of all the numbers you entered is: 8
Break is also a common way to get out of an intentional infinite loop:
A sample run of the above program:
Enter 0 to exit or anything else to continue: 5
Enter 0 to exit or anything else to continue: 3
Enter 0 to exit or anything else to continue: 0
We're out!
Break vs return
New programmers sometimes.
return
return statement
Here are two runs of this program:
Enter 'b' to break or 'r' to return: r
Function breakOrReturn returned 1
Enter 'b' to break or 'r' to return: b
We broke out of the loop
Function breakOrReturn returned 0
Continue
The continue statement provides a convenient way to end the current iteration of a loop without terminating the entire loop.
Here’s an example of using continue:
This program prints all of the numbers from 0 to 9 that aren’t divisible by 4:
1
2
3
5
6
7
9
Continue statements work by causing the current point of execution to jump to the bottom of the current loop.
Continue statements
In the case of a for loop, the end-statement of the for loop still executes after a continue (since this happens after the end of the loop body).
Be careful when using a continue statement with while or do-while loops. These loops typically change the value of variables used in the condition inside the loop body. If use of a continue statement causes these lines to be skipped, then the loop can become infinite!
continue statement
Consider the following program:
This program is intended to print every number between 0 and 9 except 5. But it actually prints:
0 1 2 3 4
and then goes into an infinite loop. When count is 5, the if statement evaluates to true, and the continue causes the execution to jump to the bottom of the loop. The count variable is never incremented. Consequently, on the next pass, count is still 5, the if statement is still true, and the program continues to loop forever.
count
5
if statement
true
continue
Of course, you already know that if you have an obvious counter variable, you should be using a for loop, not a while or do-while loop.
for loop
while
do-while
The debate over use of break and continue
Many textbooks caution readers not to use break and continue in loops, its value is changed), an else statement, and a nested block.
else statement
Minimizing the number of variables used and keeping the number of nested blocks down both improve code comprehensibility more than a break or continue harms it. For that reason, we believe judicious use of break or continue is acceptable.
Best practice
Use break and continue when they simplify your loop logic.
The debate over use of early returns
There’s a similar argument to be made for return statements. A return statement that is not the last statement in a function is called an early return. Many programmers believe early returns should be avoided. A function that only has one return statement at the bottom of the function has a simplicity to it -- you can assume the function will take its arguments, do whatever logic it has implemented, and return a result without deviation. Having extra returns complicates the logic.
The counter-argument is that using early returns allows your function to exit as soon as it is done, which reduces having to read through unnecessary logic and minimizes the need for conditional nested blocks, which makes your code more readable.
Some developers take a middle ground, and only use early returns at the top of a function to do parameter validation (catch bad arguments passed in), and then a single return thereafter.
Our stance is that early returns are more helpful than harmful, but we recognize that there is a bit of art to the practice.
Use early returns when they simplify your function’s logic.
Maybe it could be pointed out that one of the pro of a function that has only one final return statement is related to letting the compiler use RVO return value optimization.
If I remember correctly multiple returns makes harder for the RVO to get efficiently applied, but not so sure if it's still true.
Although this is no more a significant performance issue nowadays thanks to move semantic.
On line 11 in the second to last program:
std::cin >> ch{};
Should read
std::cin >> ch;
Yet another great lesson :D
Section "Continue", first snippet, line 12:
`'\n'` should be used instead of `std::endl` to avoid unnecessary buffer flushes (as you've taught us :)).
Section "The debate over use of break and continue", second snippet, line 9:
`ch` should be initialized.
In the previous lesson, you guys provided an equivalent of the for loop using while:
Since the end-statement of a for loop executes after the loop body, should we think of it as technically NOT being apart of this following block?:
and instead being done implicitly after the body?
Yes. The end-statement is not affected by `continue`.
Unable to start program
Operation did not complete successfully because the file contain a virus or potentially unwanted software
what is wrong with this code? everytime i had compiled it and my windows antivirus detect a trojan LOL
line 5 ++i
line 8 +=
i don't known why the ++ is missing after i had posted to the comment
Today i am trying the same code, it's not showing the error from detecting virus.
when i debug step into on line 5, why it showing the value -858993460?
why the return 0 is showing <=4ms elapsed, but the other line is showing <=1ms elapsed? the longer elapsed time which showing when at debugging on step into, will it means the more slower the performance will be when we make that code into a programs?
The random number that you see when debugging on line 5 is probably garbage data that is stored at the address that is allocated for the variable "i". You ARE on line 5 (it hasn't been executed yet), once you move to the next line i.e line 6, Line 5 has been executed and your variable has been initialized.
Basically what your compiler does is that it creates the variables first thing, and then initializes them one the particular line has been executed. You can see this behavior in the following program.
You'll get warnings as we are not doing anything with the variables, but when you run this in debug mode, you'll see that even when you are on line 3, the debug window still shows all 3 variables (which are not initialized yet) now step through to the next line and "a" will be initialized..
hello i really dont understand what does the == 0 do here
if ((count % 4) == 0)
it checks if the remainder of count divided by four is equal to zero
Not sure, if this has been mentioned already, but there are 2 issues in the "Continue" section:
Second code snippet:
That comment is misleading; the statements IS executed during the first 5 iterations of the loop.
Furthermore the output of the third code snippet should be
too, since the cout line is skipped in iterations 6 to 10
> the statements IS executed during the first 5 iterations of the loop.
Comment amended, thanks!
> Furthermore the output of the third code snippet should be
The third snippet in the "continue" section? That's correct as written. The condition is `i == 5`, not `i >= 5`.
Could also include exit() which is used to skip the rest of the program
`std::exit` shouldn't be used unless normal termination of your program is not otherwise possible. `std::exit` makes the control flow harder to follow.
Summarizing:
return is used to skip the current function;
break is used to skip the current loop or switch;
continue is used to skip the rest of the current iteration.
Sir, code mentioned below is not working and it is taken from your example which is mentioned above. It is working when i am using break; instead of continue. please check!
int count(0);
while (count < 10)
{
if (count == 5)
continue; // jump to end of loop body
std::cout << count << " ";
++count;
// The continue statement jumps to here
}
The text above the example explains it.
"Be careful when using a continue statement with while or do-while loops. Because these loops typically increment the loop variables in the body of the loop, using continue can cause the loop to become infinite!"
The reason that the code is not working as the example is beacause the C++ is executed sequential, by it's nature. So, in the case when count is 5, the while condition is evaluated as true, after that if condition is evaluated as true, the continue statement is executed, witch will jump to the end of while loop (in other words will skip the rest of the body of while loop), and from this moment the loop become infinite.
When continue statement is meet end executed, the std::cout part will be skiped.
Even if you introduce continue statement of the if statement inside of {}, the result will be the same.
You will see, if you change the possition of if statement, after std::cout, the output will be 0 1 2 3 4 5 5 5 5 ....
Excuse the bad english, and correct me if I'm wrong or I misunderstood.
When I created this small bit of code to practice using continue, VS2017 required me to initialize "int count" outside of the for loop. Why? I originally wrote it in the init-statement, but I would get an error that "count" wasn't defined. **Edit: I can't seem to get the code tags to work. Not sure what I'm missing...
#include <iostream>
int main()
{
int count{ 0 };
for (; count <= 50; ++count)
{
if ((count % 2) == 0)
continue;
else
std::cout << count << std::endl;
}
}
Hi Dustin!
[-CODE]
int main()
{
...
}
[-/CODE]
without the -
The following code is working. If it doesn't work for you, please share the exact error message, including the line number(s).
smh... I don't think I actually initialized it when I included it in the init statement. You're right. It's working.
On an unrelated note, but still having to do with VS2017, while I'm going through these tutorials, I'm leaving VS up and creating small programs to experiment with what I'm learning. The other day, to mess with my son, I wrote a program in this VS2017 program window I always have open that asked the user for their name and if it matched my son's name, it would print out that he stunk. Otherwise, it would print out that the user didn't stink. (I know, it's juvenile). After I messed with him, I altered the code to say I stunk if the name input matched my name. What was odd is that even though I had deleted the code that told the program that if the string input matched my son's name the program was still recognizing when you entered his name and out put that he stunk. The program was still acting like the code was there!
Have you ever had something like this happen where VS remembered code that you had deleted and executed it? I had saved the new code and I tried "cleaning" the project. It was like that comparison bit of code was still hanging out in the memory or something. Thoughts?
If old code gets stuck:
- Make sure you restarted to program
- Make sure you saved the changes (This happens too often)
- Make sure you're building the project (VS can debug/run without re-building)
- Clean the project (Delete everything that's not a code or project file)
Some systems cache dynamic libraries. If you're developing one, disable/clean the cache or rename the library.
Thank you!
Actually, break statement should be omitted in this way without using any variables.
This was what my teacher told me.
Hi Anson!
Your teacher is wrong. Your code will compare @ch to 'e' once in line 10 and once in line 14, without @ch changing in-between. This can introduce a significant performance overhead, depending on the loop-condition. On top of that, your sample has duplicate code, which can cause additional problems when updating the code. Both of Alex' snippets should be preferred over your teacher's solution.
Your teacher has a valid point in not liking @break, because it can make understanding the control flow more difficult. You should not let this affect the efficiency or stability of your code!
In the "Break vs return" segment, there is a typo:
It should be
The output looks weird but the function name printed would be inline with the function name in the code.
Name (required)
Website
Save my name, email, and website in this browser for the next time I comment. | https://www.learncpp.com/cpp-tutorial/break-and-continue/ | CC-MAIN-2021-17 | refinedweb | 2,443 | 65.86 |
Introduction
Building a web app almost always means dealing with data from a database. There are various databases to choose from, depending on your preference.
In this article, we shall be taking a look at how to integrate one of the most popular NoSQL databases - MongoDB - with the Flask micro-framework.
There are several Flask extensions for integrating MongoDB, here we'll be using the Flask-PyMongo extension.
We will also be working on a simple Todo-List API to explore the CRUD capabilities of MongoDB.
Setup and Configuration
To follow along with this tutorial, you will need access to a MongoDB instance, You can get one from MongoDB Atlas or you could use a local instance. We will be using a local instance on our own personal machine.
To install a local instance of MongoDB, head over to their official documentation website for instructions on how to download and install it.
You will also need to have Flask installed, and if you don't, you can do so with the following command:
$ pip install flask
Next we need to set up Flask-PyMongo, which is a wrapper around the PyMongo python package.
PyMongo is a low-level wrapper around MongoDB, it uses commands similar to MongoDB CLI commands for:
- Creating data
- Accessing data
- Modifying data
It doesn't use any predefined schema so it can make full use of the schemaless nature of MongoDB.
To begin using Flask-PyMongo, we need to install it with the following command.
$ pip install Flask-PyMongo
Now that we are all set, let us get started integrating MongoDB into our Flask app.
Connecting to a MongoDB Database Instance with Flask
Before we actually perform any work, we want to connect our MongoDB instance to the Flask application. We'll start off' by importing Flask and Flask-PyMongo into our app:
from flask_pymongo import PyMongo import flask
Next we'll create a Flask app object:
app = flask.Flask(__name__)
Which we'll then use to initialize our MongoDB client. The PyMongo Constructor (imported from
flask_pymongo) accepts our Flsk app object, and a database URI string.
This ties our application to the MongoDB Instance:
mongodb_client = PyMongo(app, uri="mongodb://localhost:27017/todo_db") db = mongodb_client.db
The URI string could also be assigned to the key
MONGO_URI in
app.config
app.config["MONGO_URI"] = "mongodb://localhost:27017/todo_db" mongodb_client = PyMongo(app) db = mongodb_client.db
Once the application has a connection to the instance, we can start implementing the CRUD functionality of the application.
Create Documents - Adding New Items to the Database
MongoDB works with collections, which are analogous to the regular SQL table. Since we're making a TODO list app, we'll have a
todos collection. To reference it, we use the
db object. Each entity is a document, and a collection is really, a collection of documents.
To insert a new entry into our
todos collection, we use the
db.colection.insert_one() method. MongoDB works naturally with Python given its syntax for insertion, querying and deletion.
When inserting a document into a MongoDB collection, you'd specify a dictionary with
<field>s and
<value>s. To insert a document into a MongoDB collection using Python as the middleman, you'll pass in dictionaries that are built-in into Python.
Thus, to insert a new entity, we'll do something along the lines of:
@app.route("/add_one") def add_one(): db.todos.insert_one({'title': "todo title", 'body': "todo body"}) return flask.jsonify(message="success")
We could also add multiple entries at once using the
db.colection.insert_many() method. The
insert_many() method take a list of dictionaries and adds them to the collection:
@app.route("/add_many") def add_many(): db.todos.insert_many([ {'_id': 1, 'title': "todo title one ", 'body': "todo body one "}, {'_id': 2, 'title': "todo title two", 'body': "todo body two"}, {'_id': 3, 'title': "todo title three", 'body': "todo body three"}, {'_id': 4, 'title': "todo title four", 'body': "todo body four"}, {'_id': 5, 'title': "todo title five", 'body': "todo body five"}, {'_id': 1, 'title': "todo title six", 'body': "todo body six"}, ]) return flask.jsonify(message="success")
If we try and add a duplicate record, a
BulkWriteError will be thrown, meaning that only records up to said duplicate will be inserted, and everything after the duplicate will be lost, so keep this in mind when trying to insert many documents.
If we want to insert only valid and unique records in our list, we will have to set the
ordered parameter of the
insert_many() method to
false and then catch the
BulkWriteError exception:
from pymongo.errors import BulkWriteError @app.route("/add_many") def add_many(): try: todo_many = db.todos.insert_many([ {'_id': 1, 'title': "todo title one ", 'body': "todo body one "}, {'_id': 8, 'title': "todo title two", 'body': "todo body two"}, {'_id': 2, 'title': "todo title three", 'body': "todo body three"}, {'_id': 9, 'title': "todo title four", 'body': "todo body four"}, {'_id': 10, 'title': "todo title five", 'body': "todo body five"}, {'_id': 5, 'title': "todo title six", 'body': "todo body six"}, ], ordered=False) except BulkWriteError as e: return flask.jsonify(message="duplicates encountered and ignored", details=e.details, inserted=e.details['nInserted'], duplicates=[x['op'] for x in e.details['writeErrors']]) return flask.jsonify(message="success", insertedIds=todo_many.inserted_ids)
This approach will insert all of the valid documents into the MongoDB collection. Additionally, it'll log the details of the failed additions and print it back to the user, as a JSON message.
We've done this via Flasks'
jsonify() method, which accepts a message we'd wish to return, as well as additional parameters that let us customize it for logging purposes.
Finally, we return the successful inserts, in much the same way.
Read Documents - Retrieving Data From the Database
Flask-PyMongo provides several methods (extended from PyMongo) and some helper methods for retrieving data from the database.
To retrieve all the documents from the
todos collection, we'll use the
db.collection.find() method.
This method will return a list of all the
todos in our database. Similar to
find(), the
find_one() method returns one document, given its ID.
Let's start out with
find():
@app.route("/") def home(): todos = db.todos.find() return flask.jsonify([todo for todo in todos])
The
find() method can also take an optional filter parameter. This filter parameter is represented with a dictionary which specifies the properties we're looking for. If you've worked with MongoDB before, you'll probably be familiar with how their queries and comparators look like.
If not, here's how we can use Python's dictionary to accomodate the MongoDB query format:
# Query document where the `id` field is `3` {"id":3} # Query document where both `id` is `3` and `title` is `Special todo` {"id":3, "title":"Special todo"} # Query using special operator - Greater than Or Equal To, denoted with # the dollar sign and name ($gte) {"id" : {$gte : 5}}
Some other special operators include the
$eq,
$ne,
$gt,
$lt,
$lte and
$nin operators.
If you're unfamiliar with these, a great place to learn more about them is the official documentation.
Now that we've covered specifying MongoDB queries for filtering the
find() method, let's take a look at how to retrieve one document, given its
_id:
@app.route("/get_todo/<int:todoId>") def insert_one(todoId): todo = db.todos.find_one({"_id": todoId}) return todo
So if we we were to send a
GET request to, we'd get the following result:
{ "_id": 5, "body": "todo body six", "title": "todo title six" }
Note that
5000is the default Flask server port, but it can be easily changed while creating a Flask app object
Most times we would want to get an item or return a
404 error if the item was not found.
Flask-PyMongo provides a helper function for this, the
find_one_or_404() method which will raise a
404 error if the requested resource was not found.
Update and Replace Documents
To update entries in our database, we may use the
update_one() or the
replace_one() method to change the value of an existing entity.
replace_one() has the following arguments:
filter- A query which defines which entries will be replaced.
replacement- Entries that will be put in their place when replaced.
{}- A configuration object which has a few options, of which well be focusing on -
upsert.
upsert, when set to
true will insert
replacement as a new document if there are no filter matches in the database. And if there are matches, then it puts
replacement in its stead. If
upsert if false and you try updating a document that doesn't exist, nothing will happen.
Let's take a look at how we can update documents:
@app.route("/replace_todo/<int:todoId>") def replace_one(todoId): result = db.todos.replace_one({'_id': todoId}, {'title': "modified title"}) return {'id': result.raw_result} @app.route("/update_todo/<int:todoId>") def update_one(todoId): result = db.todos.update_one({'_id': todoId}, {"$set": {'title': "updated title"}}) return result.raw_result
So if we were to send a request to, we'd get the following result:
{ "id": { "n": 1, "nModified": 1, "ok": 1.0, "updatedExisting": true } }
Similarly, if we were too send a request to, we'd get the following result:
{ "id": { "n": 1, "nModified": 1, "ok": 1.0, "updatedExisting": true } }
The code block will return an
UpdatedResult object, which can be a tad tedious to work with. Which is why Flask-PyMongo provides more convenient methods such as
find_one_and_update() and
find_one_and_replace() - that will update an entry and return that entry:
@app.route("/replace_todo/<int:todoId>") def replace_one(todoId): todo = db.todos.find_one_and_replace({'_id': todoId}, {'title': "modified title"}) return todo @app.route("/update_todo/<int:todoId>") def update_one(todoId): result = db.todos.find_one_and_update({'_id': todoId}, {"$set": {'title': "updated title"}}) return result
So now, if we were to send a request to, we'd get the following result:
{ "_id": 5, "title": "updated title" }
Similarly, if we were too send a request to, we'd get the following result:
{ "_id": 5, "title": "modified title" }
Flask-PyMongo also allows bulk updates with the
update_many() method:
@app.route('/update_many') def update_many(): todo = db.todos.update_many({'title' : 'todo title two'}, {"$set": {'body' : 'updated body'}}) return todo.raw_result
The above code block will find and update all entries with the title "todo title two" and results in:
Sending a request to our newly-made enpoints returns the following result:
{ "n": 1, "nModified": 1, "ok": 1.0, "updatedExisting": true }
Deleting Documents
As with the others, Flask-PyMongo provides methods for deleting a single or a collection of entries using the
delete_one() and the
delete_many() methods respectively.
This method's arguments are the same as with the other methods. Let's take a look at an example:
@app.route("/delete_todo/<int:todoId>", methods=['DELETE']) def delete_todo(todoId): todo = db.todos.delete_one({'_id': todoId}) return todo.raw_result
This will search for and delete the entry with the provided ID. If we sent a
DELETE request like so to this endpoint, we would get the following result:
{ "n": 1, "ok": 1.0 }
You can alternatively use the
find_one_and_delete() method that deletes and returns the deleted item, to avoid using the unhandy result object:
@app.route("/delete_todo/<int:todoId>", methods=['DELETE']) def delete_todo(todoId): todo = db.todos.find_one_and_delete({'_id': todoId}) if todo is not None: return todo.raw_result return "ID does not exist"
Sending to our server now results in:
{ "_id": 8, "body": "todo body two", "title": "todo title two" }
Finally, you can delete in bulk, using the
delete_many() method:
@app.route('/delete_many', methods=['DELETE']) def delete_many(): todo = db.todos.delete_many({'title': 'todo title two'}) return todo.raw_result
Sending to our server will result in something similar to:
{ "n": 1, "ok": 1.0 }
Saving and Retrieving Files
MongoDB allows us to save binary data to its database using the GridFS specification.
Flask-PyMongo provides the
save_file() method for saving a file to GridFS and the
send_file() method for retrieving files from GridFS.
Let us begin with a route to upload a file to GridFS:
@app.route("/save_file", methods=['POST', 'GET']) def save_file(): <input type="file" name="file" id="file"> <br><br> <input type="submit"> </form>""" if request.method=='POST': if 'file' in request.files: file = request.files['file'] mongodb_client.save_file(file.filename, file) return {"file name": file.filename} return upload_form
In the above code block, we created a form to handle uploads and return the file name of the uploaded document.
Next let's see how to retrieve the file we just uploaded:
@app.route("/get_file/<filename>") def get_file(filename): return mongodb_client.send_file(filename)
This code block will return the file with the given filename or raise a 404 error if the file was not found.
Conclusion
The Flask-PyMongo extension provides a low-level API (very similar to the official MongoDB language) for communicating with our MongoDB instance.
The extension also provides several helper methods so we can avoid having to write too much boilerplate code.
In this article, we have seen how to integrate MongoDB with our Flask app, we have also performed some CRUD operations, and seen how to work with files with MongoDB using GridFS.
I have tried to cover a much as I can but if you have any questions and/or contributions please do leave a comment below. | https://stackabuse.com/integrating-mongodb-with-flask-using-flask-pymongo/ | CC-MAIN-2021-21 | refinedweb | 2,189 | 54.12 |
Encapsulates all options available for creating a Publisher. More...
#include <advertise_options.h>
Encapsulates all options available for creating a Publisher.
Definition at line 41 of file advertise_options.h.
Definition at line 43 of file advertise_options.h.
Definition at line 58 of file advertise_options.h.
Templated helper function for creating an AdvertiseOptions for a message type with most options.
Definition at line 148 of file advertise_options.h.
templated helper function for automatically filling out md5sum, datatype and message definition
Definition at line 84 of file advertise_options.h.
Queue to add callbacks to. If NULL, the global callback queue will be used.
Definition at line 108 of file advertise_options.h.
The function to call when a subscriber connects to this topic.
Definition at line 105 of file advertise_options.h.
The datatype of the message published on this topic (eg. "std_msgs/String")
Definition at line 102 of file advertise_options.h.
The function to call when a subscriber disconnects from this topic.
Definition at line 106 of file advertise_options.h.
Tells whether or not the message has a header. If it does, the sequence number will be written directly into the serialized bytes after the message has been serialized.
Definition at line 131 of file advertise_options.h.
Whether or not this publication should "latch". A latching publication will automatically send out the last published message to any new subscribers.
Definition at line 126 of file advertise_options.h.
The md5sum of the message datatype published on this topic.
Definition at line 101 of file advertise_options.h.
The full definition of the message published on this topic.
Definition at line 103 of file advertise_options.h.
The maximum number of outgoing messages to be queued for delivery to subscribers.
Definition at line 99 of file advertise_options.h.
The topic to publish on.
Definition at line 98 of file advertise_options.h.
An object whose destruction will prevent the callbacks associated with this advertisement from being called.
A shared pointer to an object to track for these callbacks. If set, the a weak_ptr will be created to this object, and if the reference count goes to 0 the subscriber callbacks will not get called.
Definition at line 120 of file advertise_options.h. | https://docs.ros.org/en/fuerte/api/roscpp/html/structros_1_1AdvertiseOptions.html | CC-MAIN-2021-25 | refinedweb | 363 | 52.97 |
Article For
You are currently browsing legacy 3.0 version of documentation. Click here to switch to the newest 5.2 version.
Manage Your Server: Admin Logs
Here you can connect to a server and view server logs. In order to do so, click on the
Configure Connection button, which will allow you to set the following:
- maximum log entries number determining when further logging should be banned,
- one or more namespaces for logging (Category) and the logging levels
The connection will break automatically when the maximum log entries number is reached, yet it can be also ended using the
Disconnect button. Clicking the
Export button saves all logs in JSON file.
| https://ravendb.net/docs/article-page/3.0/csharp/studio/management/admin-logs | CC-MAIN-2021-43 | refinedweb | 112 | 52.9 |
Difference between revisions of "Draft Circle"
Revision as of 02:32, 6 November 2018, a the circle will create a filled face (DATAMake Face True); if not, the circle will not make a face (DATAMake Face False).
- Press Ctrl while drawing to force snapping your point to the nearest snap location, independently of the distance.
- Press Shift while drawing to constrain your second point horizontally or vertically in relation to the first one.
- Press Esc or the Cancel button to abort the current command.
-
See also: FreeCAD Scripting Basics, Draft API, and the autogenerated API documentation..
radiuscan also be a
Part.Edge, whose
Curveobject must be a
Part.Circle
- If a
placementis given, it is used.
- If
faceis
True, the circle will make a face, that is, it will appear filled.
- If
startangleand
endangleare given (in degrees), and have different values, they are used and the object appears as a Draft Arc.
Example:
import Draft Circle1 = Draft.makeCircle(200) Circle2 = Draft.makeCircle(500) Circle3 = Draft.makeCircle(750) | https://www.freecadweb.org/wiki/index.php?title=Draft_Circle&diff=347298&oldid=347295 | CC-MAIN-2019-47 | refinedweb | 167 | 59.09 |
Download presentation
Presentation is loading. Please wait.
1
Equity analysis b Value = PV of future benefits b EIC approach b Applied Valuation Dividend based modelsDividend based models Earnings based modelsEarnings based models b Financial Statement Analysis
2
The EIC Approach b Economy - Industry - Company Performance of firm is conditioned by how its industry is expected to fare.Performance of firm is conditioned by how its industry is expected to fare. Performance of industry is conditioned by how the economy performsPerformance of industry is conditioned by how the economy performs Often called a “top-down” approachOften called a “top-down” approach Are you seeking relative or absolute performance?Are you seeking relative or absolute performance?
3
Economic Analysis b Economic growth tied to (US) Monetary and Fiscal policy as well as Business Cycle b Fed has 4 goals: Stable prices (low inflation)Stable prices (low inflation) Low unemploymentLow unemployment Sustained real growth in GDPSustained real growth in GDP Reasonable balance in international paymentsReasonable balance in international payments
4
Economic Analysis b Fed has material control over US monetary policy (reserve requirements, discount rate, open market operations) b Fed can move interest rates! b Fiscal policy: Gov’t ability to tax & spend (Deficit or surplus) b Relevance to an individual firm?
5
Business Cycles b Economy does expand and contract b Helps to know where we are within a business cycle b NBER monitors economic variables that correlate with real GDP growth Leading indicatorsLeading indicators Coincident indicatorsCoincident indicators Lagging indicatorsLagging indicators
6
Industry Analysis b Industry Life Cycle b Common considerations Nature of competitionNature of competition Market share for each firmMarket share for each firm Labor conditionsLabor conditions Regulatory environmentRegulatory environment Price elasticity of demand and supplyPrice elasticity of demand and supply Sensitivity of demand to economic conditionsSensitivity of demand to economic conditions
7
Equity Analysis b Basic inputs financial statement datafinancial statement data position in industryposition in industry international investmentinternational investment rate of growthrate of growth breakdowns by product, division, subsidiariesbreakdowns by product, division, subsidiaries R&D effortsR&D efforts Major litigationMajor litigation
8
Applied Valuation b Dividend discount model Value = PV of future DividendsValue = PV of future Dividends –need forecasts of Dividends (D), growth rate (g), and a required rate of return (k) b Example: KO D 0 = 0.68, EPS 0 = $1.25 (ttm)D 0 = 0.68, EPS 0 = $1.25 (ttm) g = 8.2% (five year div. growth)g = 8.2% (five year div. growth) g = ROE x RR =.3231 x.5440 = 17.58%g = ROE x RR =.3231 x.5440 = 17.58% k = ( ) = 11.90% (CAPM)k = ( ) = 11.90% (CAPM)
9
Valuing KO b Constant dividend growth V 0 = D 1 /(k - g)V 0 = D 1 /(k - g) V = (0.68 x 1.082)/( )V = (0.68 x 1.082)/( ) V = $19.89 < $45.90 (in July ‘01]V = $19.89 < $45.90 (in July ‘01] If dividend growth model is to work,If dividend growth model is to work, –change assumptions –modify model
10
Valuing KO b Multiple stage dividend growth Suppose growth starts at 17.58% for the first 3 years and then settles out at a long term rate of 8.2%.Suppose growth starts at 17.58% for the first 3 years and then settles out at a long term rate of 8.2%. –D 1 = 0.800, D 2 = 0.940, D 3 = 1.105, D 4 = V 3 = D 4 /(k - g) = V 3 = D 4 /(k - g) = PV of D 1, D 2, D 3, V 3 = $25.324PV of D 1, D 2, D 3, V 3 = $ Where have we gone wrong?Where have we gone wrong?
11
Valuing KO b Earnings based models P/E approachP/E approach –P/E is measured using current price and either –Trailing 12 mo. EPS (P 0 /E 0 ) –EPS forecast for the next 12 mo. (P 0 /E 1 ) –Leading P/E is considered superior, but practitioners use both ratios. –V 0 = (EPS) x (P/E) –P/E = f( growth, retention rate, inflation)
12
Valuing KO b Suppose D grows at 17.58% for 3 years and a (trailing) P/E of 40 will exist at that time D 1 = 0.800, D 2 = 0.940, D 3 = 1.105D 1 = 0.800, D 2 = 0.940, D 3 = V 3 = 1.25(1.1758) 3 (40) = (2.032)(40) = $81.28V 3 = 1.25(1.1758) 3 (40) = (2.032)(40) = $81.28 PV of D 1, D 2, D 3, V 3 = $60.26PV of D 1, D 2, D 3, V 3 = $60.26 IF you can buy KO for$60.26 or less AND you think your assumptions are plausible, BUY!IF you can buy KO for$60.26 or less AND you think your assumptions are plausible, BUY!
13
Valuing KO b KO’s actual P/E (using best data 7/3/01]: Trailing = 45.90/1.25 = 36.72Trailing = 45.90/1.25 = Leading = 45.90/1.78 = 25.79Leading = 45.90/1.78 = b Estimate of P/E may have been aggressive, but D and EPS growth may be conservative. b Forecasting EPS becomes paramount! b Other multipliers: P/S, P/B, P/CF,...
14
Forecasting EPS b Two primary approaches: Trend analysisTrend analysis Fundamental approachFundamental approach b Trend Analysis Do EPS figures exhibit a trend over time?Do EPS figures exhibit a trend over time? Is recent growth expected to continue?Is recent growth expected to continue?
15
Forecasting EPS for DELL b Forecast sales growth for DELL using trend analysis: Geometric average: 42.38%Geometric average: 42.38% b Forecast sales growth for industry! b Will DELL maintain market share? b Build a sales forecast from other data
16
Forecasting EPS for DELL b Which Income Statement items drive EPS? b Focus on ratios! basis for comparison with other firmsbasis for comparison with other firms identifies strategies, competence, deficiencies when examined over timeidentifies strategies, competence, deficiencies when examined over time b Ratio Analysis LiquidityProfitabilityLiquidityProfitability Asset UtilizationLeverageAsset UtilizationLeverage
17
Forecasting EPS for DELL b Let’s focus on Sales, NPM, and Payout. Industry Sales are forecast to increase by 15%. Assume DELL will hold their share.Industry Sales are forecast to increase by 15%. Assume DELL will hold their share. NPM? It has weakened in past years. Was 7.0% for FY01 and is 6.7% in trailing 4 quarters.NPM? It has weakened in past years. Was 7.0% for FY01 and is 6.7% in trailing 4 quarters. Dividend Payout? None paid currently. None expected in next 2 years.Dividend Payout? None paid currently. None expected in next 2 years.
18
Forecasting EPS for DELL b EPS = (S x NPM)/#sh b S 1 = ( )(1.15) = $ b EPS 1 = ( )(.07)/2604 = $1.009 b Suppose we expect DELL to sell at a P/E of 39 next year. b P 1 = $1.009 x 39 = $39.35 b P 0 = $39.35/1.2989= $30.29 (>$26.48]
19
Valuing DELL b Reality check Growth estimate?Growth estimate? Required return?Required return? P/E estimate?P/E estimate? Sensitivity analysisSensitivity analysis Qualitative adjustment of critical variablesQualitative adjustment of critical variables
Similar presentations
© 2017 SlidePlayer.com Inc. | http://slideplayer.com/slide/4230159/ | CC-MAIN-2017-04 | refinedweb | 1,207 | 59.5 |
.
in code blocks
on windoes where i compile it
this is what i get
"helloworld -).
but output screen still blink after writing these lines....
well i don't get what you mean by:
Second, add the following code at the end of the main() function (right before the return statement):
[1cin.clear();
2cin.ignore(255, 'n');
3cin.get();].
i tried to put is just right before return0;
just what ever but it shows bunch of error
and when i press ctrl and F5 together it will stay but when I click debugging it closes immediately
I see the responses here started back in 2007. It is now 2015. That's eight years... so where's the book?
:)
Thanks for the great tut.
I'd love to write a book, but life has not permitted me the luxury of time as of yet. Pity, as it would be fun." .
Would you say this tutorial would be improved if it was explicit in naming, e.g., instead of using using namespace std; using the "std::" reference? I'm just wondering because I'm being told it is OK, but better to future-proof and avoid any inherited name collisions....
Sorry but I have no idea where I'm meant to put:
cin.clear();
cin.ignore(255, '.
Can I buy these tutorials on CD or something?
Thanks for having these tutorials! I like it ;)
Nope, not at this time, unfortunately. At some point I'd like to do a book, but that's far in the future. Sorry :(
No I am not using:
cin.clear();
cin.ignore(255, 'n'); :)
I don't even know what Deviant is. :)
If your program automatically closes after running it, then add those lines and it won't any more. They should work regardless of compiler, IDE, OS, etc... 'run without debugging' but it's 'start debugging'. 'Run without debugging' has become ctrl+F5 instead.
So someone pressing F5, as is recommended in the tutorial, will start debugging, in which case, for me at least, it doesn't work. However, choosing 'run without debugging' from the debug menu does help.
Apparantly someone at miscrosoft thought that it would be more userfriendly to have debugging accessed more quickly...
I hope this helps., 'n').
I find some of these very helpful..thanks.
If you're using Dev-C++, you can put on the end of main function (before return 0;) system("PAUSE"); to don't close console window immediately. This command pause the program and wait to keypress. But I think that it works only in MS Windows. 'a' character, but "bcde" are still left in the input stream. Consequently, when the code gets to cin >> chIgnore, it reads the waiting 'b'.
In order to get the screen to pause before exiting the program, does the code:
have any advantages over just using
I have so much to learn. :).
Name (required)
Website
Save my name, email, and website in this browser for the next time I comment. | https://www.learncpp.com/cpp-tutorial/a-few-common-cpp-problems/comment-page-1/ | CC-MAIN-2021-17 | refinedweb | 497 | 75.61 |
Introduction
This article purpose is to describe how to develop a WMI provider in the .NET framework. There are several incentives for writing this article:
This article does not include the use of SNMP and does not answer to the following questions:
Nevertheless, anyone who interest in those questions can find some useful notes regarding the required steps to expose managed application to SNMP (see appendix D). nut shell, Platform Management is the means to manage and monitor the health of a system. This may fall into the following categorize:
Configuration - initialization and settings of various aspects of the platform objects such as timeout values, user count thresholds, database connection strings etc. Performance measurements - measure end to end process in regards to duration, optimization etc. Hearth beats monitoring - manage component life time. Start and stop services, receiving components state etc. Information exposing - expose platform information that might be valuable for system administrators, billing etc. Alerts mechanism informative events, errors and critical errors that happens in the platform. Corrective events mechanism As opposed to post mortem events this kind of events gives to the administrators the ability to perform actions in order to prevent up coming-in) to the Providers Manager (CIMOM).
This industry standard compliancy allows alien components to share management environment locally and remotely by using SNMP.
What is WMI provider? WMI Provider is a software component that functions as mediator between the CIM Object Manager and managed objects. Using the WMI APIs, providers supply the CIM Object Manager with data from managed objects, handle requests on behalf of management applications, and generate event notifications.
Developing WMI Provider Where to start? In order to expose software component such as a service through the WMI one need to write WMI provider.
This plug-in (provider) exposes the service to the WMI and provides the interface to receive information and to interact with the service.
Till recently WMI Providers was written as a COM component and now with the emerging of .NET framework it is easier to develop providers.
In case you arent familiar with the MOF syntax you can simply start with developing the WMI Provider(see the sample section).
When it all done and finished use the InstallUtil.exe (see appendix B) tool to enter the managed class into the CIM schema, then if you want you can generate the MOF file from the WMI CIM Studio (it is highly recommended since:
Sample project The demo includes a simple .NET service (Parachute service - Managed application ) and a WMI provider (Parachute provider). For simplicity reasons, the sample use the MSDEV IDE extension for VS.NET Server Explorer (see Appendix B) as the consumer application.
The Service code is quite simple.
Adding a reference to the ParachuteProvider and to System.Managment assemblies.
In the ExposeMeToWMI method we instantiate the provider, set some values and then publish (Instrumentation.Publish() )the provider to the WMI.
The publish call registered the provider and the managed object is mapped into the CIM schema. Events are fired when the service starts and stops.
Note: The provider instance is valid only when the service is started.
The Provider code contains the following actions:
Adding reference to the System.Management assembly.
Defining the instrumented namespace parachute_company under root: assembly:Instrumented("root/parachute_company")]Note: The managed object schema will be defined under this namespace.
Adding an instance installer in case we want to publish the provider directly via the InstallUtil tool. In this example we publish the provider through the service.
Defining events by using the InstrumentationType.Event attribute: [InstrumentationClass(InstrumentationType.Event)]. Defining WMI Provider instance using the InstrumentationType.Instance attribute:[InstrumentationClass(InstrumentationType.Instance)] Note: The provider code can be just as well written in the service.
How to use the Demo project: 1. Register the Parachute service to the SCM (Service Control Manager) with the InstallUtil tool (%systemroot%%\Microsoft.NET\Framework\<framework version&t;\InstallUtil.exe). InstallUtil.exe <service file>. 2. Open the SCM \Administrative tools\ Services 3. Log on as This account- Right click on the service name (Parachute) -> Properties -> Log on tab -> check the This account enter user name and password (the user must be under Administrator group).4. Start the service 5. Install the MSDEV IDE Management extension for VS.NET Server Explorer. 6. Open the MSDEV in Server Explorer view. 7. Add your computer to the explorer: Right click on the Servers root tree ->Add Server. 8. Add Management class to the Management Classes item. Look for the Parachute class under to the parachute_company namespace. 9. Expend the Parachute item you should see the brand new instance. Take a look at the instance properties you can see that the parachute color is exposed (red) by WMI.
10. Subscribe for events: Add Event Query to the Management Events item.
11. Check the Custom Events type. 12. Add the Landing and Jump events (situated under the parachute_company namespace). 13. Start and stop the service. The MSDEV output window will display the events data.
Known problems using wbemtest.exe).
Conclusion Well, that's it folks. Hopefully, this article will stimulate you to drill down into the WMI technology and to make advantage of it.Please send feedback, bug reports or suggestions here.
Appendix A : Definitions & Acronyms
Appendix B : WMI tools:
Appendix C : Developing steps to support SNMP:
1.: 2. Create a MIB (Management Information Base) file (check out the appendix B for some useful and easy to use MIB editors). Define classes and SNMP traps (events) that will eventually expose by the WMI Provider. 3. Compile the MIB file using the SMI2SMIR utility. This will generate a MOF file. 4. Compile the MOF file using the mofcomp.exe compiler to check the MOF file syntax correctness. 5. Create the C# classes and events with the Mgmtclassgen utility (see appendix B). Use the C# classes to create WMI provider.
©2014
C# Corner. All contents are copyright of their authors. | http://www.c-sharpcorner.com/UploadFile/falkor/WMIProviderGuide11262005021524AM/WMIProviderGuide.aspx | CC-MAIN-2014-49 | refinedweb | 981 | 58.48 |
handle_replace - replace a handle
#include <zircon/syscalls.h> zx_status_t zx_handle_replace(zx_handle_t handle, zx_rights_t rights, zx_handle_t* out);
zx_handle_replace() creates a replacement for handle, referring to the same underlying object, with new access rights rights.
handle is always invalidated.
If rights is ZX_RIGHT_SAME_RIGHTS, the replacement handle will have the same rights as the original handle. Otherwise, rights must be a subset of original handle's rights.
None.
zx_handle_replace() returns ZX_OK and the replacement handle (via out) on success.
ZX_ERR_BAD_HANDLE handle isn't a valid handle.
ZX_ERR_INVALID_ARGS The rights requested are not a subset of handle's rights or out is an invalid pointer.
ZX_ERR_NO_MEMORY Failure due to lack of memory. There is no good way for userspace to handle this (unlikely) error. In a future build this error will no longer occur.
zx_handle_close()
zx_handle_close_many()
zx_handle_duplicate() | https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/handle_replace.md | CC-MAIN-2019-04 | refinedweb | 133 | 52.26 |
26 Mar 21:49 2013
Re: Problem loading the "affxparser" dependency of the "oligo" package.
On Tue, Mar 26, 2013 at 10:20 AM, Russell Williams <russell.d.williams@...> wrote: > Hmm, since that was from a terminal and I had to retype it by hand, I might > have accidentally left out part of the path name. If that caused confusion, > I apologize. > > Here are the answers to your questions: > > All of this was done in a fresh R session. > >> system.file( >>remove.packages("affxparser") > Removing package(s) from ‘C:/Program Files/R/R-2.15.3/library’ > (as ‘lib’ is unspecified) > > Checked the file system that the folder is gone. > Then ran: > >> library("affxparser") > Error in library("affxparser") : there is no package called ‘affxparser’ > > So it's gone. > > Then, as before: >>source("") >>biocLite("affxparser") > > ... > package ‘affxparser’ successfully unpacked and MD5 sums checked > > Here I checked the file system and the folder is there: "C:\Program > Files\R\R-2.15.3\library\affxparser". > Then: >> system.file(> library("affxparser") > Error in inDL(x, as.logical(local), as.logical(now), ...) : > unable to load shared object 'C:/Program > Files/R/R-2.15.3/library/affxparser/libs/i386/affxparser.dll': > LoadLibrary failure: The specified procedure could not be found. > > Error: package/namespace load failed for ‘affxparser’ Ok. > > As an example of a working package: >> library("ggplot2") > Find out what's changed in ggplot2 with > news(Version == "0.9.3.1",> >> Hmm... the pathname in that error message indicates that something is >> really wrong. It is also *not* the same path that you had in your >> previous message. What does: >> >> system.file(> >> > [2] "C:/Program Files/RStudio/R/library" >> >> > >> >> > Is the file corrupt, or is there another solution I haven't found? >> >> > >> >> > [[alternative HTML version deleted]] >> >> > >> >> > _______________________________________________ >> >> > Bioconductor mailing list >> >> > Bioconductor@... >> >> > >> >> > Search the archives: >> >> > >> > >> > > > _______________________________________________ Bioconductor mailing list Bioconductor@... Search the archives: | http://permalink.gmane.org/gmane.science.biology.informatics.conductor/47241 | CC-MAIN-2015-22 | refinedweb | 308 | 51.55 |
18 February 2009 22:15 [Source: ICIS news]
NEW YORK (ICIS news)--The impact of biofuels on food prices is being challenged now that energy prices have come down with no reversal in food prices yet seen, industry sources said on Wednesday.
“We haven’t seen a change in food prices even though commodity and energy prices have dropped by half since their summer highs,” said Jin Chon, spokesperson for Growth Energy, a coalition of American ethanol producers.
“There are numerous global factors behind food inflation, including energy prices, increasing demand for food from a growing global population, regional droughts and commodity speculators. These are far bigger factors in increased grain prices than biofuels, which uses only 4% of world grain and has a minimal impact on food prices,” Chon added.
Indeed, Growth Energy maintains that ethanol production has had a very small impact on food prices, and this impact will not grow in the future.
“The inflation pressure from both oil and corn prices abated substantially in the second half of 2008, and that is pretty well expected to continue into 2009,” said Scott Richman, senior vice president and commercial consulting lead for Informa Economics, a commodity market analysis and management consulting firm based in the US.
Richman said several events happening around the same time contributed to the rising prices of food products in the past few years.
In autumn 2006, grain prices started to take off and oil prices had been rising steadily for a few years before that. In 2006-2007, ?xml:namespace>
In 2008, floods and wet weather in the US midwest prevented planting until as late as June, Richman said.
Crude oil prices continued to spike, reaching record levels last summer. Concurrently, corn prices reached record levels of over $7/bushel, according to Keith Wiebe, deputy director of the agricultural development economics division of the Food and Agriculture Organization (FAO) of the United Nations.
Afterwards, higher corn plantings in the
“Now oil is down 60–70% to roughly $40/bbl, and corn is down to under $4/bushel,” Wiebe said.
Meanwhile, food prices have remained high, he noted.
($1 = €0.79 | http://www.icis.com/Articles/2009/02/18/9193852/high-food-prices-persist-challenging-role-of-biofuels.html | CC-MAIN-2015-11 | refinedweb | 357 | 52.83 |
The following issue has been raised before as part of the great %TAG
debate. It was a minor point so it got lost amongst the bigger issues.
Working on the being-updated spec examples, I stumbled on it again, and
I'd like to reconsider it in the context of the current %TAG rules
(which I am explicitly _not_ reopening, thank you very much :-)
The issue is:
It is not unusual for a document to use just a single tag for the root
node - in fact, I believe this will be the most common way explicit
tagging will be used, as usually all other tags can be resolved from
the path to and/or content of the nodes. The root node's tag serves as
"the" way to associate a "schema" with the whole document - the
Archimedes point one can infinitely leverage.
However, under the current rules, this is somewhat awkward to specify.
Consider:
%TAG !handle! tag:my.domain.com,2002:/namespace/
--- !handle!document-type
# Document content here, no specified tags,
foo : bar
...
It would have been nicer to be able to simply write:
--- !tag:my.domain.com,2002:/namespace/document-type
# Document content here, no specified tags,
foo : bar
...
For this to work, the current rules need to be modified in the following
way:
- Local (private) tags may not begin with "!<word>:[^:]".
- A tag beginning with "!<word>:[^:]" is assumed to be a URI.
The "[^:]" (not ":") requirement allows languages that use "::" for
namespace separation to specify tags such as "!Date::Roman".
Anyone feel strongly against adding this rule?
Have fun,
Oren Ben-Kiki
View entire thread | http://sourceforge.net/p/yaml/mailman/message/11695550/ | CC-MAIN-2014-15 | refinedweb | 266 | 62.07 |
Lenovo Thinkpad x240
Hi everyone,
I have a brandnew Thinkpad x240 laptop (SSD included) and I want to deploy an image to it. I’m able to boot to Fog, but whatever task I choose from the menu (e.g. Quick host registration) the computer gets stuck and has to be turned off by pressing the power button.
When I try to register, it gets stuck at:
Error Unknown unclaimed register before writing to c5100
Error Timed out waiting for DP idle patterns
Error Unknown unclaimed register before writing to 64040
I registered the laptop manually and tried to deploy and debug-deploy, but it gets stuck as well:
acpi_walk_namespace failed
I use FOG 0.32 with Kernel 3.8.8 on Ubuntu Server 10.04 LTS.
I already tried Tom Elliott’s kernel, but that doesn’t work either. The laptop’s ethernet interface seems to be from “LCFC(HeFei) Electronics Technology”. The first numbers from the MAC are 28:d2:44. Maybe the correct drivers are not included in the kernels. Can anyone help? Maybe Tom?
Thanks in advance!
- Scott Lloyd last edited by
Tom,
I tried your bzImage from your Feb 11th post and it did not work on a Lenovo M93z that I have. I did download the bzImage from Chris and it does work. So it appears that something is still missing from yours. Thanks for your efforts in keeping FOG current!
Michael, not that you need to, but you can test my kernel as well. The issue you’re reporting seems more related to KMS (Kernel Mode Setting) rather than the issue that is plaguing the Lenovo’s. That’s not to say this kernel isn’t correcting the same issue you were seeing, but more just trying to get a kernel built that works across the board, as best as I can at least.
- MichaelDigital last edited by
[quote=“Chris Sodey, post: 21062, member: 1418”]Tom,
I will try to test your kernel. I finished making my custom kernel and it is working.
[URL=‘’],[/URL][/quote]
I ran into this issue with some Dell 745 and 755 with ATI cards in them. This kernel worked for me as well. Thanks!
Magnus,
While I appreciate the information, I’m not ultimately in charge the kernel’s you’ve listed here.
I have built my own kernels which can be downloaded from:
[url][/url]
I don’t know if it will work, but I’ve modified mine to work from the KS tree as Chris has done. I don’t know if it will work, but as that’s really the only change from my original Core based kernel, and that’s what Chris used, it should work. I just don’t know.
If you get a chance, please try it out and see. If it doesn’t use this kernel. I don’t know what other drivers he’s got added in though so it may not work across the board for your systems.
Chris,
Another big thanks for your kernel. I was successfully able to get my clients (Lenovo Thinkcenter m83’s) to talk to the fog server and run an inventory and upload an image with your kernel. You saved me the pain of putting together a custom kernel myself or giving up on FOG all together.
Tom,
FYI I was unable to get either the kernel that was included with 0.32 or kernel v3.8.8 to load on my m83 client. Here’s the errors I observed with both:
tps65010: no chip?
acpi_ibm: ibm_acpihp_init: acpi_walk_namespace failed
Could not find Carillo Ranch MCH device.
drm/i810 does not support SMP
Error: Driver 'mdio-gpio" is already registered, aborting…
cs89x0: request_region(0x320, 0x10) failed
Thanks,
Magnus
- Ed Hollendoner last edited by
Chris,
Thanks for the kernel. It worked great on a Lenovo X230 ThinkPad and a Lenovo M73 Mini Desktop.
Tom,
Thanks for all the work you put in on your kernels. I tried all of them. Unfortunately, I couldn’t get any of them to work with the Lenovos that I have.
Can someone please tell me what changed? Has any body had any luck with the latest kernel’s I’ve been producing?
- MCS IT Dept last edited by
Chris, you’re a lifesaver! We just got over 950 L440’s, and I’ve been trying different kernels with it all day till I finally tried your custom T440 kernel, which worked just fine.
Thanks Chris, kernel worked great! :)
Chris, thanks a lot for your kernel! it s working for me on a brand new x240
If you used kitchen sink I can get it and see the major differences. Just try my kernel and let me know if it works. If not I’ll compare the two configs.
I went back through my steps and the config I used was off of my FOG server. Location is /opt/fog-setup/fog_0.32/kernel/kitchensink.config. I copied that to the Fedora machine (/usr/src/linux-3.12.6/.config) Do you want kitchensink.config from my FOG server? I would bet you already have it.
Okay, so if I understand properly you used the fedora config?
Tom,
I would post it, but I had Fedora 20 on the T440s and after I tested the T440p with my kernel and it worked I tested the T440s. I was so excited it was working that I didn’t backup the /usr/src/linux-3.12.6 directory before I wiped it with FOG.
Chris, can you post the config file. It should be located in the root of the Linux directory with filename .config (notice the period in front.)
I have tested my kernel with both the T440p and the T440s, both working. It is based off of Linux kernel version 3.12.6.
Tom,
I will try to test your kernel. I finished making my custom kernel and it is working.
[url][/url]
Kernel is posted as:
[url][/url]
Okay,
Chances are likely that that wasn’t the issue and you’re probably right about it not containing something. My guess is the Bus information isn’t translating properly, so I’m currently rebuilding the kernel to see if adding all possible South Bridges to the system, including PIIX4 (from Intel) will work. I’m not giving up, but I don’t know what else to try.
I’ll hopefully have a kernel up for you to try shortly, if this works, I’m posting that configuration as my main config (TomElliott.config) | https://forums.fogproject.org/topic/2297/lenovo-thinkpad-x240/32 | CC-MAIN-2019-43 | refinedweb | 1,094 | 82.75 |
ASP.NET # MVC # 15 – Html Helper Class , Html Helper Method , Strongly Typed HTML Helpers.
Hi Geeks,
Today we will see very important and interesting feature provided by Microsoft for asp.net MVC called HTML Helper class,HTML Helper methods.
I) HtmlHelper Class represents support for rendering HTML controls in a view.
The ViewPage class has an HtmlHelper property named Html like follow
When you look at the methods of HtmlHelper, you’ll notice that it’s pretty sparse. This property is really an anchor point for attaching extension methods. When you import the System.Web.Mvc.Html namespace (imported by default in the default template), the Html property suddenly lights up with a bunch of helper methods.
In following screen shot u can observe it
II) HtmlHelper Methods
ASP.NET MVC 2 includes support for strongly typed HTML helpers, which allow you to specify
Model properties using a Lambda expression rather than as strings.
For example, where you would have previously used <%: Html.TextBox(“PropertyName”) %> in ASP.NET MVC 1, you can now use <%: Html.TextBoxFor(m => m.PropertyName) %>.
Replacing strings with expressions provides a number of benefits, including type checking, IntelliSense, and simpler refactoring.
We have following important strongly typed Html Helper Methods :-
- Html.Encode
- Html.TextBox
- Html.ActionLink and Html.RouteLink
- Html.BeginForm
- Html.Hidden
- Html.DropDownList and Html.ListBox
- Html.Password
- Html.RadioButton
- Html.Partial and Html.RenderPartial
- Html.Action and Html.RenderAction
- Html.TextArea
- Html.ValidationMessage
- Html.ValidationSummary
For More on ASP.NET MVC visit LEARN ASP.NET MVC IN DETAIL
Thank You. | https://microsoftmentalist.wordpress.com/2011/09/19/asp-net-mvc-15-html-helper-class-html-helper-method-strongly-typed-html-helpers/ | CC-MAIN-2018-09 | refinedweb | 257 | 52.76 |
Feb 01, 2006 06:18 PM|uswebpro|LINK
Feb 01, 2006 07:26 PM|Darmark|LINK
I'm assuming your notify.vb is a class file.
Give your class file a 'Namespace' Name, like below:
NamespaceCompanyName.ProjectName
In your code behind of your aspx page, reference your class file above like this.
DimoNY As New CompanyName.ProjectName.Notify
Put that above line of code above your Page Load Event.
Then when you want to call your Method in your notify.vb file, do this
oNY.YourMethod()
OR, if passing a parameter:
oNY.YourMethod(parameter)
Hope this helps.
Feb 01, 2006 07:27 PM|tyrus|LINK
Try this:
inherits Notify \\at the top of the page's code behind
Dim Notify as new Notify \\before you try to use it, then
Notify("123")
Try doing one of the quick tutorials on Object Oriented Programming. I'm no expert on this, but i'm working on it!
If you set up notify.vb as a class with a namespace declared in it it will appear in intellisense when you do this. (It may anyway) But then if you have a public sub in the notify.vb it will pull it up. Like say the sub is called AddNumbers
You would then have Notify.AddNumbers("123")
Good luck
Feb 01, 2006 08:13 PM|uswebpro|LINK
Feb 01, 2006 08:27 PM|uswebpro|LINK
Feb 01, 2006 08:54 PM|tyrus|LINK
Hmm. If that's all that is in that class. Then it doesn't have any functions. Is that all there is??
The file is in the right place but it needs some functionality i.e.
Public Class notifyFunction
' get record info here
Public Function Hello(ByVal vVar1 As String)
If vVar1 = "Hi" ThenReturn "Hello" Else Return "What did you say?" End If End Function
' prepare smtp notification
' send notification
' done
End Class
Then you call the function Hello("Hi") from another page that imports this class.
5 replies
Last post Feb 01, 2006 08:54 PM by tyrus | http://forums.asp.net/t/959029.aspx | CC-MAIN-2015-11 | refinedweb | 338 | 76.32 |
ENERGY 211 / CME 211. Lecture 2 September 24, 2008. Evolution. In the beginning, we all used assembly That was too tedious, so a very crude compiler for FORTRAN was built FORTRAN was still too painful to work with, so ALGOL 60 211 / CME 211
Lecture 2
September 24, 2008
// #include is a preprocessor directive that
// specifies a header file to be included in the
// program (in this case, iostream)
#include <iostream>
// When a program is run, its main function is
// invoked. It returns an integer (int) value
// indicating its status (not done here, though)
int main()
{
// std::cout denotes the “standard output”
// device, which is normally the screen. The
// << operator, in this case, is used to
// write data to this device.
std::cout << "Hello world!" << std::endl;
}
hello.cpp: (subroutine)
#include <iostream>
void say_hello() // void means “does not return a value”
{
std::cout << "Hello world!" << std::endl;
}
hellomain.cpp: (main program)
void say_hello(); // external functions must be declared
int main()
{
say_hello(); // main passes the buck to say_hello
}
Neither hello.cpp nor hellomain.cpp is a complete program, so we use –c to compile only, and not link
bramble06:~/demo211> c++ -c hello.cpp
bramble06:~/demo211> c++ -c hellomain.cpp
The previous commands created object (.o) files, which are now linked to create the executable program “hello”
bramble06:~/demo211> c++ -o hello hello.o hellomain.o
The ls command lists the current directory (like dir in Windows). The a.out is from before
bramble06:~/demo211> ls
a.out hello hello.cpp hello.o hellomain.cpp hellomain.o
The “.” is used to denote the current directory, which, by default, is not in the search path used to locate programs
bramble06:~/demo211> ./hello
Hello world!
bramble06:~/demo211>
target: prerequisites
command
where command builds target from the prerequisites
# All object files that must be linked into final executable
OBJ= hello.o hellomain.o
# Rule for building executable from object files
# $@ is shorthand for the target of the rule
hello: ${OBJ}
c++ -o $@ ${OBJ}
# Rule for compiling individual sources files into object files
# $< is shorthand for the first prerequisite
${OBJ}: %.o: %.cpp
c++ -c $<
# Rule to clean up all output files
clean:
rm -f hello ${OBJ}
With the Makefile, building executable is easy!
bramble06:~/demo211> make
c++ -c hello.cpp
c++ -c hellomain.cpp
c++ -o hello hello.o hellomain.o
Reset hello.cpp’s modified time to force recompile
bramble06:~/demo211> touch hello.cpp
Note that only hello.cpp is recompiled
bramble06:~/demo211> make
c++ -c hello.cpp
c++ -o hello hello.o hellomain.o
This removes all output files
bramble06:~/demo211> make clean
rm -f hello hello.o hellomain.o
Learning some fundamentals of C++ | http://www.slideserve.com/omer/1-cme-211 | CC-MAIN-2016-40 | refinedweb | 442 | 66.94 |
#include <someFileName>
#tells the compiler to do something before it actually compiles your code.
includeis the pre-processor command. It tells us that we are going to insert the entire contents of another file to this location here.
<>tells us that the file is located in a path included by the project. Ussually this just points to a bunch of default headers that your compiler supports (windows/linux headers, c headers, iostream, etc). The other option is to put the filename in double-quotes which will search for files in the same directory as the current file.
someFileNamethis is the file that will be included. | http://www.cplusplus.com/forum/beginner/88155/ | CC-MAIN-2014-15 | refinedweb | 105 | 65.12 |
.
# “Above the Clouds: Introducing Akka” by Jonas Bonér (Torsten)
Typesafe is a Scala company but fortunately (for me as a Java Developer) Akka can be used with both, Scala and Java.
The open source Akka framework is two and a half years old. It sits just above Scala in the Scala runtime Stack. Akka solves the problem of writing concurrent, scalable and fault tolerant systems by providing a unified programming model and a managed runtime. Basically Akka is there to manage system overload. It addresses both, scaling up (big machines) and scaling out (many machines). Akka was born in the finance sector and is mainly used for all sorts of event driven apps in the fields of batting&gaming, telecom, simulation and e-commerce.
The Akka architecture consists of a concurrency layer at the bottom, scalability and the fault tolerance layer at the top. There are also a lot of modules and add ons around akka covering topics such as management consoles, monitoring, provisioning.
The concept of Actors is the most important tool in the akka toolbox. So what is an Actor? It’s an Object with state and behaviour with strong encapsulation, even at runtime. Communicating with an Actor is done by putting a message on the Actors “inbox”. Everything is event driven, there are no blocking Threads involved.
The Akka runtime has a scheduler which puts actors on a thread and forwards messages to it. Through this separation between actors and threads it becomes very cheap to create, process and shut down actors. This makes it for example possible to have an actor for each of the millions of users of a multiplayer online game without any problem of handling them.
class Counter extends Actor { var counter = 0; def receive = { case Tick => counter += 1 println(counter) } }
Note that the receive method checks for the type of message it receives which makes Akka almost feel like a dynamic language. Although there is a counter variable defined in the Actor, the code is thread safe because concurrency is handled by the Akka runtime.
Actors are created through the AkkaApplication - it’s possible to have many Akka applications per JVM - by simply calling the actorOf method on it.
val app = AkkaApplication() val counter = app.actorOf[Counter]
The counter variable is not a reference to an Actor but an ActorRef which is a pointer to a running actor. So actors can live everywhere, on different machines, different data centers, etc. They can be killed by the runtime and recreated without the ActorRef becomming invalid. This gives Akka a lot of runtime flexibility.
To tell an actor to do something in a fire and forget manner the “!” operator is used.
counter ! Tick
To send an actor a message and consume a result the “?” operator which immediately returs a “future” is used.
val future = actor ? Mesage future onComplete { f=> f.value }
The future api includes these methods: await, onComplete, onResult, onException, onTimeout, foreeach, map, flapMap, filter. Futures can easily be composed to wait for results from multiple actors and the like. In Java futures are blocking in Akka there is a non blocking futures api.
An actor can reply to a method call by using the magic sender variable and ! on it.
sender ! ("Hi)
It’s possible to change the behaviour of actors on the fly by using the become and unbecome methods. Using this it’s very easy to implement state machines
become { case NewMessage => ... }
By binding actors to names it’s easy to implement remote actors. That’s because an actor name is virtual and decoupled from how it is deployed.
akka { actor { deployment { /path/to/my-service { router = "round-robin" nr-of-instances = 3 remote { nodes = ["wallace:2552", "grommit:2556"] } } }
In the example the service is deployed on two nodes with three instances. If two actors interact they do not know where the other actor is deployed. The ActorRef points to a “remote” actor in this case and serves as a router to the it.
Fault tolerance in Akka is inspired by the Erlang model. The classic way is to have fault tolerance implemented all over the code in try catch blocks. The actor way is onion-layered. There is an error kernel containing all critical stuff such as database failure, external system access etc. Actors delegate “scary” stuff to other actors supervise the delegates and monitor failure. Actors can also be grouped together. In case of failure these grouped actors can be killed altogether. It’s also common for supervising actors resp. supervisors to escalate failure to another actor.
That was the Akka introduction talk - very technical but very good presented. I would really like to use Akka in a real world project but I’m afraid that we will not have any projects at ConSol in the near future which fit to Akka or vice vers.
First of fall a funny note on speaker’s clothing. It’s November in Antwerp and Kevin Nilson wears some shorts! Anyway the talk about JavaFX and HTML5 was not cold at all. So HTML5 is more than just HTML, CSS and JavaScript. To get an impression on HTML5 capabilities check out this small example.
As browsers behave differently JavaScript frameworks (e.g. jQuery, Dojo, YUI) try to solve issues in order to give consistent API. If you want to check your favorite browser’s compliance with HTML5 visit. Can your browser pass the test?
According to builtwith.com 51% of the top 10,000 web sites use jQuery. So the talk strongly recommends to get known to jQuery as a web developer. If you want to try out some jQuery experience visit. Now even with JavaScript frameworks on board helping to solve cross browser differences we might need to address older browsers, especially IE6, IE7, IE8. The answer could be Chrome Frame which is running Chrome on these browsers.
The concept of Modernizr is very important for new era web development, too. Instead of user agent sniffing we use feature detection. Modernizr tells you what features are available in the browser and which of them are ready to use for you. So after this short introduction to HTML5 web era changes what ships with Java FX 2.0 in this sense?
First of all how to display HTML in JavaFX? We wanna see live coding! And we got live coding in this talk! Here is the small example on calling a browser URL in JavaFX and displaying the contents of this website in a JavaFX application.
public class WebViewTest extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { WebView webView = new WebView(); webView.getEngine().load(""); Scene scene = new Scene(webView); primaryStage.setScene(scene); primaryStage.setTitle("Hello Devoxx!!!"); primaryStage.show(); } }
We can do this in 12 lines and something about 300 characters! In addition to that plain Java code we can use GroovyFX or ScalaFX in order to code the same example. I would have typed all examples for you but I was not able to write fast enough, sorry. The important thing to notice is the fact that we now coded the example in roundabout 10 lines and 110 characters using Groovy and Scala. The Visage language does it in 8 lines and 67 characters. Pretty cool!
Now let’s move on to calling JavaScript from JavaFX.
String script = "alert ('Hello World!');"; engine.executeScript(script);
We might also have to respond to browser events in JavaFX. We are able to get callbacks for these browser events:
Last not least there was a nice idea on how to interact with JavaScript in JavaFX. So what can we do when JavaScript code needs to interact with JavaFX code? We can use the HTML page status as an event bus in order to send data from JavaScript to the JavaFX application. The JavaScript code simple sets the status with some character data and JavaFX can react to that in some event callback.
That’s it for this talk which was quite impressive on HTML5 websites running and interacting with JavaFX application. Need to find out more about that, definitely!
This talk just started right after the central Android keynote, which mostly left out all new features being supported by the new Android version 4.0 (API-version 14) aka “Ice Cream Sandwich”. This 17.11.2011 is also some kind of remarkable: By starting to sell the Google Nexus in the UK, Android 4.0 is from today on also available to customers in Europe!
As you can get all android-4.0-highlights much better on the official website, I will mention just some highlights of the talk itself.
First of all, we experienced a very vivid talk. Nick often went with his mobile just in front of the camera and demonstrated the features being listed on the presentation. Some examples: Taking pictures with face detection, taking a live face video recording with manipulation effects like popping eyes, shrinking face etc., beaming contact details from one phone to another.
Additionally we saw a whole bunch of new features, among them the new Roboto font, the beam-technology, VPN support and lots of new APIs to ease life of for developers. In the case that you want to migrate your application code from an older Android API version, Nick made you aware of testing your layouts and the new navigation bar. Also be aware of hardware acceleration being enabled now by default!
In my personal opinion, the new Android version biggest achievement is providing a smooth converged platform for both, mobiles and tablets. Layout is automatically managed by the platform in respect of the display resolution and screen orientation. Developers don’t have to care about that anymore, well done!
Performance issues seem to be a very important topic this year at Devoxx. So I decided to visit at least this one talk about a comparison of the performance of following java web application frameworks:
Using these frameworks, an example-app was written containing an overview and detail screen with input fields providing autocompletion and ajax validation. This application was deployed to an amazon cloud with 7,5GB RAM, 4 BC2 CPUs, 1GB Xmx,Xms. A database connection was simulated to avoid bottlenecks caused by the backend.
Using jMeter, each application was tested according different parameters such as throughput and max. supported users. When it came to response time, they measured the response time towards getting the HTML-page or the REST-json data.
In result, they got more than 300 Mio test-samples with more than 16GB of data and >700 hours of test-runs.
Here the ranking according to throughput:
… and with big distance …
Already at the beginning the presenters pointed on the two major classes these frameworks can be grouped:
GWTand
Spring MVC
Wicket,
JSFand
myfaces.
Unfortunately they never(!) mentioned that the server-side frameworks slowlyness is completely logical and already determined by their architecture: they have more to work and a bigger memory-footprint per session! Well, for that reason the following hosting costs calculation is not really fair in my eyes. Anyway, I don’t want to leave it out:
Hosting costs considering a web application with 10.000 concurrent users (is this realistic?) with 5 sec thinktime and a limit of 200ms response time (time unit for the costs was not mentioned).
In summary they showed that client-side-RIA are much better (factor 10) concerning performance and scalability. But in many cases the database should be the first bottleneck, so it is still a valid option to use server-side component frameworks such as JSF and Wicket. At the end just let me highlight the unique presentation style: They used one big mind-map-poster in which they zoomed into one or two levels. Very nice fonts also, so don’t miss this if you are interested into alternative presentation styles!
First is fired up a term, create a Spring sample application with Roo and used the Heroku Plugin for preparing to a deployment to the Heroku PaaS offering. Heroku uses Git for deploying. As soon Heroku receives a push, it will start a Maven build on the Heroku side which has the advantage that the world gets downloaded within the Cloud. But this is only an option, binaries can be pushed, too.
Heroku can be summarized as a Polyglot + Paas + Cloud Components. It is a cloud application platform with support for HTTP routing and load balancing.
Instances are deployed on so called Dynos, there are 750 free dyno hours per app, per month. The application server itself needs to be deployed as well. The command to start is specified in a
Procfile.
Heroku uses a Erlang based HTTP Routing. Related to load balancing, Heroku does not support sticky sessions, session state must be an external system (like MongoDB) for scalability reason. Autoscaling is provided by third party tools, but not within the platform, because Heroku has no semantic idea for when to scale.
For Scala,
sbt is the build tool of choice on which the
stage task is called on deployment. Lift is not that well supported on Heroku because it has quite some state requirements , take Play is the message. Heroku knows how to rollback a deployed release to the latest version. Very nice, one can log onto a dyno and get a bash shell ! It is also very flexible when it comes to databases. Postgres is available out of the box, but any external dababase can be used as well.
Interestingly, there are no custom API required to use Heroku. That’s different to CloudFoundry (which is on the other hand has the advantage that the PaaS stack is open source).
It was a very well structured talks with very clear and concise demos which gave me who doesn’t know yet anything specifically about Heroku a very clear impressiof what Heroku offers (and what not). BTW, it was also a quite nice introduction into Play Framework, too ;-). Very impressive, I’ll will give it a try for sure.
So let’s talk about the Java Message Service specification which is part of Java EE but also existed as standalone specification. The last maintenance update of version 1.1 was back in 2003. In March 2011 JSR 343 was launched in order to develop JMS 2.0. The target for this specification is to be part of Java EE 7 so timeline ends in Q3 2012.
The initial goals for this JMS version are:
What’s wrong with the JMS API? It’s not bad, but it could be easier to use. So one large intention is to simplify the API usage. If we have a look at a usual code for sending and receiving messages with JMS we certainly see some improvements. If you receive a JMS message in Java EE you usually have the @MessageDriven annotation along with the onMessage(Message message) method. So first of all we need to cast the message object to a TextMessage for instance in order to get the message payload. When sending a message we inject some resources with @Resource annotation (connectionFactory and destination). The sendMessage() method needs to manually create a connection, a session and a message producer. These are three objects to be created ad even worse the connection needs to be closed with some boilerplate code in a finally block. The create session method ships with two arguments: the local session true or false and secondly the acknowledgement mode. Actually in Java EE container these parameters do not have any effect! These are only for standalone Java applications managing server transactions.
A possible new API would also inject the resources via CDI, but code can be much easier. See following example on how it could look like:
@Resource(mappedName="jms/contextFactory") ContextFactory contextFactory; @Resource(mappedName="jms/outboundQueue") Queue outboundQueue; try (MessageContext mCtx = contextFactory.createContext();) { TestMessage textMessage = mCtx.createTextMessage(payload); mCtx.send(outboundQueue, textMessage) }
The ContextFactory combines connection and session creation and the AutoClosable API takes care of closing the resource in finally block. You can make it even more simple with CDI annotations.
@Resource(mappedName="jms/outboundQueue") Queue outboundQueue; @Inject @MessagingContext(lookup="jms/contextFactory") MessagingContext mCtx; @Inject TextMessage textMessage; public void senMessage(String payload) { textMessage.setText(payload); mCtx.send(outboundQueue, textMessage); }
That’s an improvement, definitely, but for me it feels not as smooth as Java APIs nowadays look like. If I have a look at the Play Java API also shown at Devoxx I feel even more comfortable. But that’s just my opinion.
Regarding durable subscriptions the JMS 2.0 API does not require a client id mandatory anymore. For MDB the container will generate a default subscription name. We also can expect some new resource annotations for JMS connection factory and destination. So we can define JMS resources in the JEE container inside our code with annotations like we do with data sources.
The new features in JMS 2.0 are:
So JMS 2.0 promises to be a version upgrade to basically simplify the API and introduce some new features. As I already set the timeline for this is Q3 2012 so stay tuned for this new version.
Allex Miller (a functional language specialist) gave a short introduction to Clojure. Clojure is a Lisp kind of language (dynamic, functional). Every thing in Clojure is immutable. Clojure separates state and identity. In Alexs words, an identity can be in different states at different times, but the state itself doesn’t change.
Clojure is a compiled language - it compiles directly to JVM bytecode, yet remains completely dynamic. Every feature supported by Clojure is supported at runtime
Clojure has almost every primitive type and all major types of collections like List, Vector, Set and Map. Clojure handles the code as data.
Defining a function:
(defn square [x] (* x x))
You can also make use of anonymous functions as below
((fn[x(* x x))
In Clojure we can write the code more compact than in Java. As an example,
with the following method we can count the number of lines in a file
(defn file-counts [file]) (count (line-seq (reader file))
This looks pretty short, or ?
Or with the following code we can do the same for all files in directory recursively
(def file-count[dir]) (map line-count filter #(. % is FIle) (file-seq (file dir)))))
How do you define a Bean class for Bear? like this.
{:name "Tremens" :brewery "Deliruim" :alcohol 85 :ibu 26}
Just imagine how many lines we have to write for this in Java. Alex explained much more Like sequences, macros, multimethods, Agents.
A good talk on Clojure. Clojure is not the easiest langauage but a very powerful language. | https://labs.consol.de/devoxx/development/2011/11/18/devoxx-2011-day-4.html | CC-MAIN-2018-22 | refinedweb | 3,117 | 64.81 |
LoRa receiving data intermittently
I am trying to receive data on a LoPy transmitted from an Adafruit Feather M0 with a RFM95 radio. The M0 transmits GPS coordinates every 1 second over the radio. At first I thought the LoPy was not working at all because I only got
'b'in the print out. However I left it on for a while and noticed that every few minutes or so I get a packet transmission with the GPS data from the M0.
Both radios are running the same default radio settings.
F = 915
Bw = 125 kHz
Cr = 4/5
Sf = 7 (128chips/symbol)
The M0 has
CRC onI am not sure where to set/verify this with the LoPy network library. I am using the RadioHead library for Arduino on the M0.
One thing I noticed on the LoPy is that the coding rate seems to be 4/6 even if I explicitly set the coding rate to
LoRa.CODING_4_5. When I retrieve the coding rate after I set it returns
1rather than the
0I should be seeing according to the docs. Not sure this is my issue but something looks off here regardless. If you don't explicitly set the coding rates it still returns
1so there does not appear to be any way to set the coding rate to
4/5.
Here's my python code, I am running firmware
1.8.0.b1. Any help would be much appreciated.
from network import LoRa import socket import machine import time lora = LoRa(mode=LoRa.LORA) lora.coding_rate(LoRa.CODING_4_5) s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) s.setblocking(False) print("LoRa Ready") print("Frequency: "+ str(lora.frequency())) print("Spreading Factor: "+ str(lora.sf())) print("Coding Rate: "+ str(lora.coding_rate())) print("Bandwidth: "+ str(lora.bandwidth())) print("MAC: "+ str(lora.mac())) while True: data = s.recv(128) print(lora.stats()) print(data) time.sleep(1)
@maelstrom
Hello,
LoRaRAW works for me between 2 LoPys both on EUR and US frequencies on the latest firmware, all the other parameters are default values.
Does anyone have a couple of LoPys running firmware
1.8.0.b1and can test out the raw LoRa mode to confirm that this isn't a firmware issue?
I got my DVB-T tuner and nothing seems out of the ordinary and 915mhz in my basement is clean of interference. Even did some additional fine tuning of the frequency that the LoPy is listening on and still got intermittent results.
I am starting to wonder if there is a bad trace or ground that is contributing to this. I did have some issues when soldering the ground pin when I put in the headers, the board has a lot of grounding copper left on the PCB which acted as a heat sink so the solder didn't flow as well... maybe I will go resolver it to be sure.
Is it possible to use FSK on the LoPy?
@ledbelly2142 Thanks for the info. Right now I would say I am getting ~99% packet loss when receiving on the LoPy from an Arduino driven RFM95. To double check that I wasn't getting interference I had another Arduino/RFM95 receiving next to the LoPy and I received 100% of the packets. I also tried the reverse (LoPy transmitting, Arduino receiving) and did not receive anything. However if I had my GPS transmitter sending at the same time the LoPy would interfere with it so something is happening around the 915 frequency. I get my DVB-T tuner today so I will keep poking around.
I have a feeling there is some default setting that is different between the Arduino and LoPy, I just cant figure out what it is and having 1% of the transmissions come across randomly is adding to the confusion.
This is what I am using
lora = LoRa(mode=LoRa.LORA, bandwidth=LoRa.BW_125KHZ, coding_rate=LoRa.CODING_4_8, sf=12, tx_iq=True) lora_sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW) lora_sock.setblocking(False)
with the 'nano-gateway' inside the office, we had a good signal up to about 1/4 mile with large buildings in the way. Still have intermittent issues and occasional corrupted messages.
Looks there is a discrepancy between docs and implementation for
coding_rate.
typedef enum { E_LORA_CODING_4_5 = 1, E_LORA_CODING_4_6 = 2, E_LORA_CODING_4_7 = 3, E_LORA_CODING_4_8 = 4 } lora_coding_rate_t;
lora.coding_rate([coding_rate])Get or set the coding rate in raw LoRa mode (LoRa.LORA). The allowed values are:
LoRa.CODING_4_5 (0), LoRa.CODING_4_6 (1), LoRa.CODING_4_7 (2) and LoRa.CODING_4_8 (3).
I think this is just a documentation issue as setting the coding rate to
0on the sx1272 would put it in FSK mode.
I am using firmware 1.8.0.b1
I am using LoRa Nano-Gateway (Raw LoRa)
Ok so I did some poking around with different frequencies and only got one hit on
908000000and it wasn't my GPS transmission from the M0. Also wanted to double check that the M0 was consistently transmitting so I fired up my other Arduino with the RFM95 and it picks up the transmissions perfectly every second. I am at a loss, this worked with very little troubleshooting using the RFM95 + Arduino.
Here's what I was using to cycle through all the ISM 915 MHz frequencies at
100000increments.
from network import LoRa import socket import machine import time lora = LoRa(mode=LoRa.LORA) frequency = 902000000 while True: if frequency <= 928000000: lora.init(frequency=frequency) s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) s.setblocking(False) time.sleep(1.2) print("Frequency: "+ str(lora.frequency())) data = s.recv(128) print(lora.stats()) print(data) frequency = frequency + 100000 else: frequency = 902000000
@bmarkus Thanks, I just ordered a tuner to do some investigation. However I have had no issues transmitting between two RFM95 modules attached to Arduinos using the RadioHead library. Should I expect much variance in terms of tuning frequency across different LoRa radios? I did try some different frequencies around 915 but didn't know how granular I should get so
I was pretty much poking around in the dark.
First I would repeat the test on different frequencies. You may have an interference from other devices. I'm not saying there is no bug in LoPy but RFI can cause issues for any properly working device.
If you are planning to work with LoRa a bit longer time, it is worth to buy a DVB-T USB stick for few bucks and use an SDR (Software Defined Radio). With this you can see noise level on the band, what is going on adjacent channels, etc.
@bmarkus no problem. I wonder if the RAW implementation has a bug where it is acting like the WAN mode and receiving on different frequencies. That's why I am seeing data come across every once and awhile.
@maelstrom Ahhhh, sorry I was not reading it carefully. Too late for working :)
@bmarkus I am the original poster, @ledbelly2142 reported similar behavior so I was wondering if his configuration was similar to mine.
@maelstrom said in LoRa receiving data intermittently:
@ledbelly2142 are you using LoRa raw or wan modes? What firmware? I wonder if there is a bug in the raw implementation for the recent 1.8.0 release.
It is in the opening post.
@ledbelly2142 are you using LoRa raw or wan modes? What firmware? I wonder if there is a bug in the raw implementation for the recent 1.8.0 release.
I have similar issues with LoRa transmission consistency. Some of the transmissions are corrupted, like the check bit got flipped mid stream. Running on a battery, it gets expensive to have to attempt to re transmit.
I'm not sure what is causing the intermittent issue. | https://forum.pycom.io/topic/1795/lora-receiving-data-intermittently/18 | CC-MAIN-2019-35 | refinedweb | 1,283 | 65.73 |
You can clone individual checks from the "Check Details" page:
The "Create a Copy..." function creates a new check in the same project and copies over the following:
The newly created check has a different ping URL, and it starts with an empty log.
It is sometimes useful to clone an entire project. For example, when recreating an existing deployment in a new region. The Healthchecks.io web interface does not have a function to clone an entire project, but you can clone all checks in the project relatively easily using the Management API calls. Below is an example using Python and the requests library:
import requests API_URL = "" SOURCE_PROJECT_READONLY_KEY = "..." TARGET_PROJECT_KEY = "..." r = requests.get(API_URL, headers={"X-Api-Key": SOURCE_PROJECT_READONLY_KEY}) for check in r.json()["checks"]: print("Cloning %s" % check["name"]) requests.post(API_URL, json=check, headers={"X-Api-Key": TARGET_PROJECT_KEY}) | https://healthchecks.io/docs/cloning_checks/ | CC-MAIN-2021-43 | refinedweb | 140 | 57.47 |
I was attending the “Microsoft patterns and practices” lectures the other day when the subject of the singleton pattern came up.
One of the questions a friend asked, which weren’t discussed at the time, was: “Why would I want to use the singleton pattern when I can simply declare all the methods and variables in my class as static?”
Well, of course you can. If you have a self contained class that doesn’t have any special initialization. Something like:
public class Test1
{
static int someValue = 100;
static public int someMethod()
{
return someValue;
}
static Test1()
System.Console.WriteLine(“Test1 static constructor”);
}
Test1 is a simple self contained class with a static constructor. The static constructor will be called right before the first use of the static class.
So if we have something like:
System.Console.WriteLine("First Line");
System.Console.WriteLine(Test1.someMethod());
The output will be:
First Line
Test1 static constructor
100
You might have already spotted the problem with static classes, copy and paste the following code into your IDE, check if you can see what the output should be before running it:
public class A
public static string staticVariableCopiedFromB = B.staticVariable;
public static string staticVariable = "Thing is a string defined in A";
public class B
public static string staticVariableCopiedFromA = A.staticVariable;
public static string staticVariable = "Thing is a string defined in B";
public class Test
static void Main(string[] args)
{
System.Console.WriteLine(A.staticVariableCopiedFromB);
System.Console.WriteLine(B.staticVariableCopiedFromA);
}
The output you should get is:
Thing is a string defined in B
Why is this happening? Lets look at what the JIT compiler is doing:
This prevents infinite circular initialization.
Changing the order so that the string assignment happens before the static assignment from the other class resolves the issue:
An even better way is to use the static constructor to explicitly initialize it in the correct order:
public static string staticVariable;
public static string staticVariableCopiedFromB;
static A()
staticVariable = "Thing is a string defined in A";
staticVariableCopiedFromB = B.staticVariable;
public static string staticVariableCopiedFromA;
static B()
staticVariable = "Thing is a string defined in B";
staticVariableCopiedFromA = A.staticVariable;
The compiler will actually generate the static constructors itself; it just feels safer to do it explicitly.
That might have been an elegant solution for a very small example, but can you see what will happen when we start working with 5 or more classes with dependencies.
This is why we can’t always depend on the order of static initialization. By explicitly initializing our singleton classes we can be sure that someone doesn’t destroy our carefully crafted static initialization bootstrap code by accidentally calling something when it shouldn’t be. As you can see, there isn’t a compile or run time error, just an unexpected result, these problems can be very difficult to track down.
Please drop a comment if I’m missing something or unaware of a dot net specific feature.
We are working on design for my current project. There is a situation where we need one and only...
This is good to know the problem with initialisation and it would be better if can give us with some more examples .
I can highlight one benefit of Singletone pattern over a class having all the variables an methods defined as static:
Static class’ methods can access only static variables.
Consider the situation in which u want to serialize your singletone class.
If u follow t the Singleton pattern then all the variables will be serialized that are defined as non static variable.
But you can’t achieve this task with Static class by using default serializable mechanism coz static variable do not participate in serialization. You will have to extend ur class from externalizable interface | http://dotnet.org.za/reyn/archive/2004/07/07/2606.aspx | crawl-002 | refinedweb | 621 | 51.48 |
I'm writing this code for one of my projects. can you please help me with line #6,#7 and #10? I'm not sure if I am writing the code for those correctly.
package waffles; import java.util.Scanner; import java.util.Stack; /** * */ public class Waffles { /** * @param args the command line arguments */ public static void main(String[] args) { #2&3 Stack<String> waffleStack= new Stack<String>(); Scanner keyboard = new Scanner(System.in); //Bonus waffles are either millk or berry. String buckwheat = "Buckwheat waffle"; // Standard waffles String blueberry = "milk waffle"; // Bonus waffles String strawberry = "berry waffle"; // Bonus waffles //Use a for loop to help the cook assemble a Stack of eight buckwheat waffles. Complete the for loop and add the missing statement so the eight waffles are placed on the stack. #4&5. for(int k = 1; k<=8; k++){ #6//Now choose some additional Special-Challenge waffles for a friend to eat. // Add as many as you want. Special Vs must be milk or berry. wafflesStack.push("milk waffles") ; wafflesStack.add("berry waffles"); } #7 // Use the customized static print method below to display the Stack of waffless your sponsoree must eat. System.out.println("\n sponsoree must eat: "+waffleStack.size()); // Let the contest begin! Start eating waffless using a while loop! // Earn $2 for each buckwheat waffles you eat, and earn $5 for each bonus waffles int numberEaten = 0; int moneyEarned = 0; String nextWaffle; boolean done = false; while(!done) { // 8. Check if the waffles stack is empty! Don't try to eat the plate!! if( WaffleStack.isEmpty()){ System.out.println("\n\nAll the waffles have been eaten! Good job!\n" );break;} nextWaffle = waffleStack.peek(); // Peek at, but to not remove the next waffle. System.out.println("\nThe next waffle is a : " + nextWaffle ); System.out.println("\nType any key to make your sponsoree eat the waffle, or type Q when done."); String newName = keyboard.next(); if(newName.equalsIgnoreCase("Q")) done = true; #9. else{waffleStack.remove(newName);//#9Eat the waffle by removing it from the stack. numberEaten++;// Great! Your sponsoree has eaten one more! What a champ! // 10. If the nextwaffles is not buckwheat, your sponsoree earns $5 else they earn $2. You must use the ! operator if(!nextWaffles.contains("Buckwheat waffle")) moneyEarned+=5; else moneyEarned +=2; } //end of else block System.out.printf("\nWow, your sponsoree has eaten %d waffles and earned %d dollars.\n", numberEaten, moneyEarned); } // end of while loop System.out.printf("\nWow, your total is %d waffless and %d dollars.\n", numberEaten, moneyEarned); } // end of main method // Custom method to print a Stack. public static void print(Stack<String> myStack ) { int count = 1, sizeOfStack = myStack.size(); System.out.println("\nYour stack has size: " + myStack.size()); for (String myString : myStack) {System.out.print(count + ". " + myString); if(count!=sizeOfStack) System.out.print( " -> "); else System.out.print( " :Last"); count++; | https://www.daniweb.com/programming/software-development/threads/475205/stacks-help-in-java | CC-MAIN-2018-13 | refinedweb | 469 | 62.04 |
Changing time zones
- Posted: Jun 02, 2010 at 6:24 AM
- 7,775 Views
- 5 Comments
Something went wrong getting user information from Channel 9
Something went wrong getting user information from MSDN
Something went wrong getting the Visual Studio Achievements location feature. Since most systems don't include GPS chipsets (yet, anyway!), you'll also need software or hardware that can figure out the current location . You can use the excellent (and free) GeoSense for Windows to make a best-guess location determination based on your current network affiliation, or buy a laptop with a GPS or cellular chipset and Windows 7 support.
The code for this project is available in both Visual Basic and Visual C# and will run in Visual Studio 2010 Express Editions. If you don't have them, download them from here.
Time zones are funny things. They're all about lining up time around the world so the sun rises and sets at roughly the same hour of the day. I've always assumed that time zones were offset by an hour as you travel along a line of latitude. This is how it works in the United States, but now I've learned that not everywhere in the world works this way. I've also learned that not only is daylight savings optional, but the dates and amount of change can vary. Finally, I've learned that it's not so easy to figure out your current time zone based on your location!
In Windows, you change your time zone by choosing from a long drop-down list. In other words, it's completely in your hands to know that you've entered a time zone and to make the appropriate change.
Since Windows 7 is location-aware, we are starting to see applications that can fetch the local weather and news headlines, or perform local map search. It seems only natural that time zone changes should be automated in the same manner.
When I started working on this project, I assumed that it would be trivial. I even naively thought that I might be able to just make a system call to map coordinates to a time zone. Not surprisingly, that didn't work. It's a pretty big task to take the entire earth and map it to time zones, though clearly it must be possible!
After doing some searching, I discovered a web service that can do exactly what I was looking for - return the time zone when given a set of coordinates. I assumed that I was done. Silly me!
It turns out that the time zone name returned from the web service doesn't map to the Windows time zone name. The web service uses a Unix format called Olson, used by the TZ utility. Previously, I had thought that time zone names were standardized because I'm used to thinking of American time zones like Pacific Standard Time or Eastern Daylight Time. It turns out that the correct name is neither Pacific Standard Time nor Pacific Daylight Time. It's not even Pacific Time. According to Windows, the name is Pacific Time (US & Canada). The Olson name is America/Los_Angeles. Fortunately, however, it's a one-to-one mapping.
Before the name even becomes a consideration, you need to subscribe to the system event for location change. You can either use the LatLongLocationProvider or the CivicAddressLocationProvider in the Windows7.Location namespace (from the Windows API Code Pack), depending on whether you need latitude/longitude coordinates, or a civic address, respectively. Create the provider, then subscribe to the LocationChanged event. As with other Windows 7 device types, you need to have permission from the user to use it. The RequestPermissions method checks for permission, and if not set, automatically prompts the user for permission.
Visual C#
gps = new LatLongLocationProvider(30000); gps.LocationChanged += new LocationChangedEventHandler(gps_LocationChanged); LocationProvider.RequestPermissions(IntPtr.Zero, true, gps);
Visual Basic
gps = New LatLongLocationProvider(30000) LocationProvider.RequestPermissions(IntPtr.Zero, True, gps)
When the location changes, the LocationChanged event fires. This provides a reference to the location provider and to the new location report. Both the provider and the report will need to be cast to the specific type, either for LatLong or CivicAddress. Once you have the address you need to determine the actual time zone. The free/public source I found to perform the lookup was the timezone web service on GeoNames.org. This service returns XML-formatted data including country, time zone name, and raw time offset values:
XML
<timezone> <countryCode>ES</countryCode> <countryName>Spain</countryName> <lat>39.5</lat> <lng>-5.97</lng> <timezoneId>Europe/Madrid</timezoneId> <dstOffset>2.0</dstOffset> <gmtOffset>1.0</gmtOffset> <rawOffset>1.0</rawOffset> <time>2009-11-02 01:31</time> </timezone>
In this example, the time zone name is "Europe/Madrid." The mapping from Olson to Windows is performed using a spreadsheet of mappings that I found on Tim Davis' blog. This spreadsheet is a great resource. In this example, the corresponding Windows time zone is "Central European Standard Time." Since .NET uses the TimeZoneInfo object to represent time zones, we need to find the right object. We do this by using the FindSystemTimeZoneById method of the TimeZoneInfo class. Once you have the right TimeZoneInfo object (the Windows time zone entry), you need to prompt the user, and then update the system.
Unfortunately, setting the system time zone isn't as easy as retrieving it. I assumed there would be a SetSystemTimeZoneById method, but once again, I was mistaken. For some reason, you can easily enumerate zones or find the current one, but changing the current zone requires dropping into unmanaged code. Considering that time zone is a per-user, non-administrative setting, I was surprised by this.
In the Win32 API's, in kernel32.dll, there are matching Set/GetDynamicTimeZoneInformation methods. You can't use the managed date/time data types though, so I created additional logic to marshall data between the managed TimeZoneInfo and unmanaged DYNAMIC_TIME_ZONE_INFORMATION Win32 types.
NOTE: Pre Vista/Win7, the Win32 functions and types were named without the "Dynamic" keyword. This was due to a less flexible layout for daylight savings. Since this application requires Windows 7 for the location awareness, I decided to use the newer Win32 calls as well.
Visual C#
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct DynamicTimeZoneInformation { [MarshalAs(UnmanagedType.I4)] public int bias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string standardName; public SystemTime standardDate; [MarshalAs(UnmanagedType.I4)] public int standardBias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string daylightName; public SystemTime daylightDate; [MarshalAs(UnmanagedType.I4)] public int daylightBias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string timeZoneKeyName; public bool dynamicDaylightTimeDisabled; }
Visual Basic
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> _ Public Structure DynamicTimeZoneInformation <MarshalAs(UnmanagedType.I4)> _ Public bias As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=32)> _ Public standardName As String Public standardDate As SystemTime <MarshalAs(UnmanagedType.I4)> _ Public standardBias As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=32)> _ Public daylightName As String Public daylightDate As SystemTime <MarshalAs(UnmanagedType.I4)> _ Public daylightBias As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=128)> _ Public timeZoneKeyName As String Public dynamicDaylightTimeDisabled As Boolean End Structure
Create an extension method of the TimeZoneInfo class to convert to the DynamicTimeZoneInformation class, and wrap the Win32 SetDynamicTimeZoneInformation function. Using an overload you can set the system time zone with either a TimeZoneInfo class or directly using DynamicTimeZoneInformation.
Setting the time zone is not quite as easy as just making the call though. Users have the right to change time zone using the SE_TIME_ZONE_NAME privilege, but it's not enabled by default. Use the system call, AdjustTokenPrivileges, to enable the privilege, make the time zone change, and then disable the privilege again. By itself, changing the time zone doesn't have any apparent effect except in new processes. In order to see the change, you need to send a system notification message. This notification is made by calling SendMessageTimeout with WM_SettingChange and a parameter of "intl". So many things to do just to change the time zone!
Visual C#
const int WM_SETTINGCHANGE = 0x1a; const int HWND_BROADCAST = (-1); const int SMTO_ABORTIFHUNG = 0x2; [DllImport("user32", EntryPoint = "SendMessageTimeoutA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] private static extern int SendMessageTimeout(int hwnd, int msg, int wParam, string lParam, int fuFlags, int uTimeout, ref int lpdwResult); public static int BroadcastSettingsChange() { int rtnValue = 0; return SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, "intl", SMTO_ABORTIFHUNG, 5000, ref rtnValue); }
Visual Basic
Const WM_SETTINGCHANGE As Integer = &H1A Const HWND_BROADCAST As Integer = (-1) Const SMTO_ABORTIFHUNG As Integer = &H2 <DllImport("user32", EntryPoint:="SendMessageTimeoutA", CharSet:=CharSet.Ansi, SetLastError:=True, ExactSpelling:=True)> _ Private Function SendMessageTimeout(ByVal hwnd As Integer, ByVal msg As Integer, ByVal wParam As Integer, _
ByVal lParam As String, ByVal fuFlags As Integer, ByVal uTimeout As Integer, _ ByRef lpdwResult As Integer) As Integer End Function Public Function BroadcastSettingsChange() As Integer Dim rtnValue As Integer = 0 Return SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, "intl", SMTO_ABORTIFHUNG, 5000, rtnValue) End Function
The Time Zone Changer is created as an addin for my MEF Utility Runner project. Recall that this project was designed to run lots of small utilities to prevent loads of icons from showing in the notification area of the task bar (by the system clock). The Visual Studio project needs a custom post-build event added in order to create the appropriate file structure:
The full command line commands should read as follows:
mkdir "$(TargetDir)Addins\MefUtil-TZChanger.util" copy /Y "$(TargetDir)$(TargetFileName)" "$(TargetDir)Addins\MefUtil-TZChanger.util" copy /Y "$(TargetDir)*.dll" "$(TargetDir)Addins\MefUtil-TZChanger.util"
In order to enable F5 debugging, set the project's Debug Start Action to Start external program to the path to the HostedWpfApp.exe executable:
When the project starts up, you'll see a notification to indicate the all was successful:
For final deployment, compress the contents of the .util folder (just the files within the folder) to a Zip file and change the extension from .zip to .util. That's it!
Though I'm pretty proud of this project, two things could still really use some enhancements. First, every location change will trigger a lookup to see if the computer is in a new time zone. If it's the same time zone, you won't really see anything. This leads to a lot of hits to the web service though. which in turn leads to the second enhancement.
If the system is offline (maybe you opened the laptop upon landing?), it may be able to get a location from a GPS chipset, but not be able to hit the location web service. Currently this will result in an error (not fatal), but it won't try again when the system is back online. This really should be fixed.
In the end, it seems like a pretty easy project: subscribe to location changes, lookup the time zone, and update the system. What lessons I learned bringing it all together! It is, however, a good example of how to leverage location in a new application. Being able to know where you are can lead to some need apps. I'm excited to see what comes of it.. I've been looking for something like this.
@ish did you install utilrunner.codeplex.com This leverages our utilrunner app.
has anyone been able to get this working
Hi. I am an absolute beginner to C# but really need to get this to work for realistic reasons.
When I open this project/solution in Vis C# Express 2010 and build it, it complains with the Windows API Code Pack dependency...so I downloaded and extracted that. But how do I reference it in this solution. I see a .sln file there as well but then it opens in its own solution... HELP please!
Thanks,
Tony.
Hi There
I did some more research and managed to get this working will put something together for the noobs like me once I finally get it working.
I enjoyed the article and being some one who travels a lot in Europe appreciate the program you wrote. I managed to follow your instructions and compile the MefUtil-TZChanger.util and load addon into MEF v2. But I have run into a problem. I get the error from MEF v2 when app is reloaded with addon.
TaskDialog feature needs to load version 6 of comctl32.dll, but a different version is currently loaded in memory.
I tried to add an app.manifest file to the project properties to set comctl32.dll to version 6 but MEF v2 doesn’t seem to have an entry point to allow for mainfests.
How do you suggest I solve this. Would really like to use this as there is nothing I have found to do the same job. Im running windows 64 bit and the version of comctl32.dll is version 5 in the system 32 and syswow64 folder.
1) Do I need to install version 6 of the Dll
2) Or how do I force windows 7 to use the verison 6 dll
Ish
Remove this comment
Remove this threadclose | http://channel9.msdn.com/coding4fun/articles/Changing-time-zones | CC-MAIN-2015-11 | refinedweb | 2,174 | 56.55 |
This article demonstrates the visualization of DICOM CT Images using Windows Presentation Foundation (WPF).
For accessing DICOM files, a parser is provided. After parsing, all the files are added to the instance tree.
The grouping is based on 'Name/Type/Study/Series'. On selection of an individual DICOM file in the instance tree, its DICOM meta information is displayed on the right-side panel.
In case the DICOM file represents a CT Image, its pixel data is displayed as bitmap in addition.
The user has the choice to open an animated 2D representation of the entire CT Image Series (similar to Apple's Cover Flow)
or to open a 3D surface representation of the entire CT Image Series (isosurface reconstruction).
In order to access the DICOM meta information of each DICOM file, a DICOM parser is provided (namespace DICOMViewer.Parsing).
The parser converts the DICOM meta information into a System.Xml.Linq.XDocument representation.
Afterwards, the XDocument tree can be queried using LINQ-queries in order to retrieve all meta information of the DICOM file.
DICOM does support many different encoding rules (DICOM Transfer Syntax).
The table below gives an overview of all possible encoding rules.
For more details on DICOM encoding, please refer to the DICOM standard (Part 5: Data Structures and Encoding).
DICOMViewer.Parsing
System.Xml.Linq.XDocument
XDocument
DICOM does specify a lot of Transfer Syntaxes which use compression. However, in all cases, the compression is only applied to one DICOM attribute: the pixel data
attribute (7FE0,0010). For all the compressed Transfer Syntaxes, the meta data information shall be encoded using Explicit VR, Little Endian.
In order to build up the instance tree, it is sufficient to access only the meta data information of each DICOM file.
Hence, the provided DICOM parser does only implement the three uncompressed transfer syntaxes:
On selection of an instance in the instance tree, the meta data information of the selected DICOM file is shown on the right-side panel.
In case the instance is of type CT Image and the pixel data is uncompressed, the pixel data is converted into a bitmap and displayed
to the user on the button of the right-side panel. The conversion is done in two steps:
For CT Images, the relationship between the stored values (SV) and the Hounsfield values is defined by the following formula:
HU = SV * RescaleSlope + RescaleIntercept
The values for RescaleSlope and RescaleIntercept are retrieved from the meta data section of the DICOM file.
The code for accessing the pixel data and the conversion into Hounsfield Units can be found in
DICOMViewer.Helper.CTSliceInfo.GetHounsfieldPixelValue().
RescaleSlope
RescaleIntercept
DICOMViewer.Helper.CTSliceInfo.GetHounsfieldPixelValue()
Once the stored values are converted into Hounsfield values (HU), the Hounsfield values have to be converted further into meaningful grayscale values.
The Hounsfield values range from -1000 (e.g., air) to several thousands (e.g., bone).
Picture is taken from: Introduction to CT
Physics
Mapping each Hounsfield value to a grayscale value would be the easiest way to display the image.
However, the human eye would not be able to distinguish gray values over such a wide range.
In order to overcome this limitation, the concept of Windowing is introduced.
Depending on the tissue being studied, the examiner of the image can set a Window corresponding to the range of Hounsfield values he is interested in.
Hounsfield values left of the window are displayed as black, Hounsfield values right of the window are displayed as white.
Below pictures show the display of the same DICOM image using different Window settings (pictures taken from: Introduction to CT
Physics):
DICOM CT image displayed with WindowCenter = +40 HU and WindowWidth = 350:
Same DICOM CT image displayed with WindowCenter = -600 HU and WindowWidth = 1500:
Most of the available DICOM viewers allow the modification of the Window settings at runtime.
However, this implementation takes the default Window setting from the meta data section of the DICOM file
(DICOM attribute WindowCenter (0028,1050) and WindowWidth (0028,1051)) and does not support any further change of the Window values at runtime.
WindowCenter
WindowWidth
The code for the grayscale conversion can be found in DICOMViewer.Helper.CTSliceInfo.GetPixelBufferAsBitmap().
DICOMViewer.Helper.CTSliceInfo.GetPixelBufferAsBitmap()
CT images belonging to the same CT Image Series can be seen as a stack of 2D images.
In order to allow the user to scroll through all CT images of the stack, a user control similar to
Apple's Cover Flow is provided.
The major design idea for the ImageFlowView control (and much of the code) has been taken from Ded's
WPF Cover Flow Tutorial.
ImageFlowView
The ImageFlowView control has to support paging. This means, only a few CT
image slices (next to the centered CT
image) are made visible at any point in time.
Displaying all CT images of an entire CT series would lead to a very high memory consumption. A CT series (e.g., a whole body scan) can sum up to 1.000
individual CT images.
The memory allocation for one single CT image can be calculated as follows:
For CT images (taken by a modern CT scanner), a typical Row/Column count is 512. This brings us to a memory consumption of 1 MB for one single CT
image.
Scrolling through the stack can be done either via Left/Right-Key, mouse wheel, or by moving the slider directly.
In case the Shift-Key is pressed, scrolling is done without animation.
A CT Image Series can be seen as a 3D scalar field of Hounsfield values.
The VolumeView class implements the well-known Marching Cubes algorithm in order to create an isosurface out of the 3D scalar field of Hounsfield values.
The Marching Cubes algorithm is described in the famous article Polygonising a scalar field from Paul Bourke.
For the C# implementation of the Marching Cubes algorithm, the proposal from Paul Bourke's article was used.
The entire surface rendering implementation can be found in the namespace DICOMViewer.Volume.
VolumeView
DICOMViewer.Volume
The DICOMViewer does allow the surface rendering for two different isovalues:
Bone rendering of the PHENIX patient (Isovalue = +500 HU):
After starting the application, select via File -> Load the directory from where you want to load the DIOCM files. The files should be of type *.dcm.
If you don't have DICOM files on hand, you can download sample DICOM images from the OsiriX internet page.
The screenshots for this article had been taken after loading the dataset for the PHENIX patient found on the OsiriX internet page.
September. | https://www.codeproject.com/Articles/466955/Medical-image-visualization-using-WPF?msg=4384386 | CC-MAIN-2017-30 | refinedweb | 1,083 | 52.29 |
CodePlexProject Hosting for Open Source Software
For which ever of the combinations bellow
'Dim dsNEW As New Microsoft.Research.Science.Data.CSV.CsvDataSet("c:\test.csv")
'Dim dsNEW As DataSet = DataSet.Create("msds:nc?file=data.nc&openMode=CreateNew")
Dim dsNew As DataSet = DataSet.Open("msds:memory")
Dim vid As Integer = dsNEW3.AddVariable(Of Single(,))("myvar").ID ' "Not supported type of data."
dsNEW3.PutData(Of Single(,))(vid, val2d)
Dim newVar As Variable = dsNEW3.Variables(vid)
I get the following two exceptions
'"Not supported type of data."
' Variables of type Single[,] are not supported in DataSet 1.0
Any ideas what should i do to correct this problem ?
Hello,
We have two version of API: object model and imperative. In the example you have mixed both APIs.
The DataSet.AddVariable<DataType> method is from object model; and the type parameter
DataType is a type of element, i.e. in your example you should specify
AddVariable<Single>() instead of AddVariable<Single[,]>().
To specify that new variable is two dimensional, you should provide two dimensions as last parameters of the method:
ds.AddVariable<Single>("var","i","j") // i,j are dimensions names
Imperative API is simpler and is file IO-like (see
documentation). It exposes extension methods defined in the assembly Microsoft.Research.Science.Data.Imperative, and its method ds.Add<D> takes a complete data type as D (i.e. Add<Single[,]> in the example):
using Microsoft.Research.Science.Data.Imperative;
...
ds.Add<Single[,]>("var"); // we may not specify dimensions names here, default names will be used
Also I would recommend you to take a look at the "Getting Started" document.
With regards,
Dmitry.
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | http://sds.codeplex.com/discussions/245607 | CC-MAIN-2017-43 | refinedweb | 308 | 52.76 |
It’s been a while since I worked on a custom component for distribution, to auto-install in the Adobe Extension Manager.
Many online tuts and official documentation assume that you want to extend the standard Flash UI Component framework. Building components without using this framework is a bit of a black art. Kudos to David Barlia’s blog post at Studio Barliesque for answering a lot of my questions regarding this approach.
When you set up a custom component and drag it to the stage from the library, it is still just a static symbol. However a component that comes from the ‘Components Panel’, (i.e. you’ve moved the FLA or SWC to the folder Adobe Flash CS6/Common/Configuration/Components ) actually runs the component when you drag it to the stage. It’s great that you can see something happen on the stage, but sometimes you don’t want it to do the same thing in authoring or compiled modes.
The common solution to handle this is to set up a separate movie which will display when you drag on the component, called the live preview. (for example this is described in this page in tutsplus)
However I was interested in the component detecting whether it was being displayed in authoring mode or compiled. Unfortunately it’s not as easy as you’d think. Capabilities.playerType thinks its running ‘External’ either way. So, I was at a road block until a few years ago David Barlia at Studio Barliesque managed to find the answer for me.
The following method can detect whether the component is running as a live preview in authoring mode, or in a compiled SWF.
protected function isLivePreview():Boolean { return (parent != null && getQualifiedClassName(parent) == "fl.livepreview::LivePreviewParent"); }
With this method you can use the same class for the component and have it work differently depending on whether it is a live preview or not. | https://craiggrummitt.com/2013/01/19/custom-component-for-distribution-live-preview-detection/ | CC-MAIN-2020-29 | refinedweb | 320 | 61.87 |
This action might not be possible to undo. Are you sure you want to continue?
MARK FISHER
The author is a senior economist in the financial section of the Atlanta Fed’s research department. He thanks Jerry Dwyer, Scott Frame, and Paula Tkac for their comments on an earlier version of the article and Christian Gilles for many helpful discussions on the subject.
he market for repurchase agreements involving Treasury securities (known as the repo market) plays a central role in the Federal Reserve’s implementation of monetary policy. Transactions involving repurchase agreements (known as repos and reverses) are used to manage the quantity of reserves in the banking system on a shortterm basis. By undertaking such transactions with primary dealers, the Fed, through the actions of the open market desk at the Federal Reserve Bank of New York, can temporarily increase or decrease bank reserves. The focus of this article, however, is not monetary policy but, rather, the repo market itself, especially the role the market plays in the financing and hedging activities of primary dealers. The main goal of the article is to provide a coherent explanation of the close relation between the price premium that newly auctioned Treasury securities command and the special repo rates on those securities. The next two paragraphs outline this relationship and introduce some basic terminology that will be used throughout the article. (Also see the box for a glossary of terms.)1 Dealers’ hedging activities create a link between the repo market and the auction cycle for newly issued (on-the-run) Treasury securities. In particular, there is a close relation between the liquidity premium for an on-the-run security and the expected future overnight repo spreads for that security (the
T
spread between the general collateral rate and the repo rate specific to the on-the-run security).. The supply of specific collateral to the repo market is not perfectly elastic; consequently, as the demand for the collateral increases, the repo rate falls to induce additional supply and equilibrate the market. The lower repo rate constitutes a rent (in the form of lower financing costs), which is capitalized into the value of the on-the-run security. The price of the on-the-run security increases so that the equilibrium return is unchanged. The rent can be captured by reinvesting the borrowed funds at the higher general collateral repo rate, thereby earning a repo dividend. When an on-the-run security is first issued, all of the expected earnings from repo dividends are capitalized into the security’s price, producing the liquidity premium. Over the course of the auction cycle, the repo dividends are “paid” and the liquidity premium declines; by the end of the cycle, when the security goes off-the-run (and the potential for additional repo dividend earnings is substantially reduced), the premium has largely disappeared.
27
Federal Reserve Bank of Atlanta E C O N O M I C R E V I E W Second Quarter 2002
BOX Glossary
Announcement date: The date on which the Treasury announces the particulars of a new security to be auctioned. When-issued (that is, forward) trading begins on the announcement date. Auction date: The date on which a security is auctioned, typically one week after the announcement date and one week before the settlement date. Fedwire: The electronic network used to transfer funds and wirable securities such as Treasury securities. Forward contract: A contract to deliver something in the future on the delivery date at a prespecified price, the forward price. Forward premium: The difference between the expected future spot price and the forward price. Forward price: The agreed-upon price for delivery in a forward contract. General collateral: The broad class of Treasury securities. General collateral rate: The repo rate on general collateral. Haircut: Margin. For example, a 1 percent haircut would allow one to borrow $99 per $100 of a bond’s price. Matched book: Paired repo and reverse trades on the same underlying collateral, perhaps mismatched in maturity. Off the run: A Treasury security that is no longer on the run (see below). Old, old-old, etc.: When a security is no longer on the run, it becomes the old security. When a security is no longer the old security, it becomes the old-old security, and so on. On special: The condition of a repo rate when it is below the general collateral rate (when R < r). On the run: The most recently issued Treasury security of a given original term to maturity—for example, the on-the-run ten-year Treasury note. Reopening: A Treasury sale of an existing bond that increases the amount outstanding.
Repo: A repurchase agreement transaction that involves using a security as collateral for a loan. At the inception of the transaction, the dealer lends the security and borrows funds. When the transaction matures, the loan is repaid and the security is returned. Repo dividend: The repo spread times the value of the security: δ = ps = p(r – R). Repo rate: The rate of interest to be paid on a repo loan, R. Repo spread: The difference between the general collateral rate and the specific collateral rate, s = r – R, where s ≥ 0. Repo squeeze: A condition that occurs when the holder of a substantial position in a bond finances a portion directly in the repo market and the remainder with “unfriendly financing” such as in a triparty repo. Reverse: A repo from the perspective of the counterparty; a transaction that involves receiving a security as collateral for a loan. Settlement date: The date on which a new security is issued (the issue date). Short squeeze: See repo squeeze. Specific collateral: Collateral that is specified— for example, an on-the-run bond instead of some other bond. Specific collateral rate: The repo rate on specific collateral. Term repo: Any repo transaction with an initial maturity longer than one business day. Triparty repo: An arrangement for facilitating an ongoing repo relationship between a dealer and a customer, where the third party is a clearing bank that provides useful services. When-issued trading: Forward trading in a security that has not yet been issued. Zero-coupon bond: A bond that makes a single payment when it matures.
28
Federal Reserve Bank of Atlanta E C O N O M I C R E V I E W Second Quarter 2002
CHART 1
The next section describes what repos and reverses are, describes the difference between onthe-run and older securities, and discusses the ways dealers use repos to finance and hedge. The article then explains the difference between general and specific collateral, defines the repo spread and dividend, presents a framework for determining the equilibrium repo spread, and describes the average pattern of overnight repo spreads over the auction cycle. The central analytical point of the article is that the rents that can be earned from special repo rates are capitalized into the price of the underlying bond so as to keep the equilibrium rate of return unchanged. The analysis derives an expression for the price premium in terms of expected future repo spreads and then computes the premium over the auction cycle from the average pattern of overnight repo spreads. Some implications of this analysis are then discussed. Finally, the article presents an analysis of a repo squeeze, in which a repo trader with market power chooses the optimal mix of funding via a triparty repo and funding directly in the repo market. Two appendixes provide additional analysis on the term structure of repo spreads and on how repo rates affect the computation of forward prices and tests of the expectations hypothesis.
A Repo and a Reverse Repo
A Repo collateral At inception: Dealer funds collateral At maturity: Dealer funds + interest
A repo (from the dealer’s perspective) finances the dealer’s long position (collateralized borrowing).
Customer
Customer
At inception:
A Reverse Repo collateral Dealer funds collateral
Customer
At maturity:
Dealer funds + interest
Customer
A reverse repo (from the dealer’s perspective) finances the dealer’s short position (collateralized lending).
Repos and Dealers
A
repurchase agreement, or repo, can be thought of as a collateralized loan. In this article, the collateral will be Treasury securities (that is, Treasury bills, notes, and bonds).2 At the inception of the agreement, the borrower turns over the collateral to the lender in exchange for funds. When the loan matures, the funds are returned to the lender along with interest at the previously agreed-upon repo rate, and the collateral is returned to the borrower. Repo agreements can have any maturity, but most are for one business day, referred to as overnight. From the perspective of the owner of the security and the borrower of funds, the transaction is referred to as a repo while from the lender’s perspective the same transaction is referred to as a reverse repo, or simply a reverse.
For concreteness, the discussion will refer to the two counterparties as the dealer and the customer even though a substantial fraction of repo transactions are among dealers themselves or between dealers and the Fed. Unless otherwise indicated, the article will adopt the dealer’s perspective in characterizing the transaction. Repo and reverse repo transactions are illustrated in Chart 1, which can be summarized by a simple mantra that expresses what happens to the collateral at inception from the dealer’s perspective: “repo out, reverse in.” Since dealers are involved with customers on both sides of transactions, it is natural for dealers to play a purely intermediary role. Chart 2 depicts a matched book transaction. In fact, the dealer may mismatch the maturities of the two transactions, borrowing funds short-term and lending them long-term (that is, reversing in collateral for a week or a month from customer 1 and repoing it out overnight first to customer 2 and then perhaps to another customer).
1. A number of sources provide additional material for anyone interested in reading more about the repo market. To read about how the repo market fits into monetary policy, see Federal Reserve Bank of New York (1998 and n.d.). For institutional details, see Federal Reserve Bank of Richmond (1993) and Stigum (1989). For some empirical results, see Cornell and Shapiro (1989), Jordan and Jordan (1997), Keane (1996), and Krishnamurthy (forthcoming). Duffie (1989) provides some theory as well as some institutional details and empirical results. 2. There is also an active repo market for other securities that primary dealers make markets in, such as mortgage-backed securities and agency securities (issued by government-sponsored enterprises such as Freddie Mac, Fannie Mae, and the Federal Home Loan Banks). In the equities markets, what is known as securities borrowing and lending plays a role analogous to the role played by repo markets, and as such much of the analysis of repo markets presented here is applicable to equities.
Federal Reserve Bank of Atlanta E C O N O M I C R E V I E W Second Quarter 2002
29
CHART 2 A Dealer’s Matched Book Transaction
collateral At inception: Customer 1 funds collateral At maturity: Customer 1 funds + interest Dealer funds + interest Dealer funds collateral Customer 2 collateral Customer 2
A dealer’s matched book transaction involves simultaneous offsetting repo and reverse transactions. From customer 1’s perspective the transaction is a repo while from customer 2’s perspective the transaction is a reverse. The dealer collects a fee for the intermediation service by keeping some of the interest that customer 1 pays.
CHART 3 Making a Market I
Told Seller bid price Dealer ask price Told Purchaser
A dealer purchases an old Treasury security (Told) and immediately finds a buyer, earning a bid-ask spread.
Typically, customer 1 is seeking financing for a leveraged position while customer 2 is seeking a safe short-term investment. On-the-run securities. The distinction between on-the-run securities and older securities is important. For example, the Treasury typically issues a new ten-year note every three months. The most recently issued ten-year Treasury security is referred to as the on-the-run issue. Once the Treasury issues another (newer) ten-year note, the previously issued note is referred to as the old tenyear note. (And the one issued before that is the old-old note, etc.) Similar nomenclature applies to other Treasury securities of a given original maturity, such as the three-year note and the thirty-year bond. Importantly, the on-the-run security is typically more actively traded than the old security in that both the number of trades per day and the average size of trades are greater for the on-the-run security. In this sense, the on-the-run security is more liquid than the old security.3 Financing and hedging. A dealer must finance, or fund, every long position and every short position it maintains. For Treasury securities, this means repoing out the long positions and reversing in the short positions. In addition to financing, the dealer must decide to what extent it will hedge the risk it is exposed to by those positions. For many positions, if not most, the dealer will want to hedge away all or most of its positions’ risk exposure. The
30
example that follows illustrates what is involved in financing and hedging a position that is generated in making a market in Treasury securities. Suppose a dealer purchases from a customer an old (or older) Treasury security. The dealer may be able to immediately resell the security at a slightly higher price, thereby earning a bid-ask spread (see Chart 3). On the other hand, since older Treasury securities are less actively traded, the dealer may have to wait some time before an appropriate purchaser arrives. In the meantime, the dealer must (1) raise the funds to pay the seller and (2) hedge the security to reduce, if not eliminate, the risk of holding the security. The funds can be raised by repoing out the security. An important way that dealers hedge such positions is by short selling an on-the-run Treasury security with a similar maturity. The price of such an on-the-run security will tend to move up and down with the old security; consequently, if the price of the old security falls, generating a loss, the price of the on-the-run security will also fall, generating an offsetting gain. Assuming the dealer does in fact sell the on-the-run security short, the dealer now has an additional short position that generates cash (from the buyer) but requires delivery of the security. The dealer uses the cash (from the short sale) to acquire the security as collateral in a reverse repurchase agreement, which is then delivered on the short sale (see Chart 4).
Federal Reserve Bank of Atlanta E C O N O M I C R E V I E W Second Quarter 2002
CHART 4 Making a Market II
Outright purchase Told Financing: Seller bid price Outright sale Tnew Hedging: Customer funds
A dealer purchases an old Treasury from a seller but has no immediate buyer.
Repo Told Dealer funds Reverse Tnew Dealer funds Customer Customer
CHART 5 Making a Market III
New repo Told Refinancing: Customer funds New reverse Tnew Rehedging: Customer funds
If no purchaser arrives (the next day), the dealer refinances and rehedges.
Unwind old repo Told Dealer funds Unwind old reverse Tnew Dealer funds Customer Customer
CHART 6 Making a Market IV
Outright sale Told Purchaser ask price New reverse Tnew Customer funds Dealer funds Dealer funds Unwind old reverse Tnew Customer Unwind old repo Told Customer
When a purchaser arrives, the dealer sells the old Treasury (to the purchaser) and buys the on-the-run Treasury to close the short position.
If a purchaser for the original security does not arrive the next day, the dealer will repo the security out again and, using the funds obtained from the repo, reverse in the on-the-run Treasury again (see Chart 5). When a purchaser arrives, the dealer sells the original security, uses the funds to unwind the
repo on the old Treasury, and purchases the on-therun Treasury outright and delivers it to unwind the reverse, using the funds to pay for the purchase (see Chart 6). If all goes well, the dealer earns a bidask spread that compensates for the cost of holding and hedging the inventory.4
3. This greater liquidity is reflected in smaller bid-ask spreads for the on-the-run security. 4. Implicitly, it is assumed that dealers can borrow the full value of a Treasury security. For interdealer transactions, this assumption is not unrealistic. In other transactions, dealers and/or customers face haircuts, which amount to margin requirements. A more accurate accounting of haircuts (larger haircuts for customers than for dealers) would complicate the story without changing the central results significantly.
Federal Reserve Bank of Atlanta E C O N O M I C R E V I E W Second Quarter 2002
31
Recall that the hedge is a short position in an on-the-run Treasury security. In the example, the hedged asset is another (older, less liquid) Treasury security. Dealers hedge a variety of fixed-income securities by taking short positions in on-the-run Treasuries. For example, dealers hedge mortgagebacked securities by selling short the on-the-run ten-year Treasury note. As noted above, on-the-run Treasuries are more liquid than older Treasuries; indeed, on-the-run Treasuries are perhaps the most liquid securities in the world. Liquidity is especially important for short sellers because of the possibility of being caught in a short squeeze. In a short squeeze,
Dealers’ hedging activities create a link between the repo market and the auction cycle for newly issued (on-the-run) Treasury securities.
it is costly to acquire the collateral for delivery on the short positions. Because the probability of being squeezed is high for large short positions, such positions are not typically established in illiquid securities; consequently, squeezes are rarely seen in illiquid securities, which is to say the unconditional probability is low. The equilibrium result is that squeezes arise most often in very liquid securities (unconditionally), because the (conditional) probability of being squeezed is low.
Repo Rates and the Repo Dividend
s noted above, repurchase agreement transactions can be thought of as collateralized loans. The loan is said to finance the collateral. For most publicly traded U.S. Treasury securities the financing rate in the repo market is the general collateral rate (which can be thought of as the risk-free interest rate). In contrast, for some Treasury securities— typically recently issued securities—the financing rate is lower than the general collateral rate. These securities are said to be on special, and their financing rates are referred to as specific collateral rates, also known as special repo rates. The difference between the general collateral rate and the specific collateral rate is the repo spread. Let r denote the current one-period general collateral rate (also referred to as the risk-free rate), and let R denote the current one-period specific
A
collateral rate, where R ≤ r.5 The repo spread is given by s = r – R. If R < r, then the repo spread is positive and the collateral is on special. Let p denote the value of the specific collateral. The repo spread allows the holder of the collateral to earn a repo dividend.6 Let δ denote the repo dividend, which equals the repo spread times the value of the bond: δ = (r – R)p = sp. A dealer holding some collateral on special (that is, for which R < r) can capture the repo dividend as follows (see Chart 7). The dealer repos out the specific collateral (borrows p at rate R) and simultaneously reverses in general collateral of the same value (lends p at rate r). The net cash flow is zero and the net change in risk is (effectively) zero. Next period the dealer unwinds both transactions, receiving the specific collateral back in exchange for paying (1 + R)p and receiving (1 + r)p in exchange for returning the general collateral. The dealer’s net cash flow is the repo dividend (r – R)p. Who would pay a repo dividend? The discussion has just shown how a dealer can obtain a repo dividend when a security it possesses is on special in the repo market. But what happens to the dealer’s counterparty in the repo transaction? The counterparty (who may be another dealer) has just lent money at less than the risk-free rate. Why would anyone do such a thing? In other words, why would anyone pay a repo dividend? If the counterparty (the party that is lending the money and acquiring the collateral) puts extra value on the specific collateral in question (above and beyond the value put on similar collateral), then that party will be willing to pay a fee for the privilege of obtaining the specific collateral. The dealer can package the fee as a repo dividend by having the counterparty accept a lower interest rate on the loan. In such a case, the specific collateral repo rate will be below the general collateral repo rate (below the risk-free rate). But this scenario begs the question, Why would anyone put extra value on some specific collateral? Why are other similar bonds not sufficiently close substitutes? The answer is simple: Anyone who sold that specific collateral short must deliver that bond and not some other bond. In other words, traders with short positions are willing to pay a repo dividend. These traders may well be dealers who have established short positions to hedge other securities acquired in the course of making markets. From their perspective, they are entering into reverse repos in order to acquire the collateral. By the same token, investors who do not hold short positions will be unwilling to pay the repo dividend. They place no special value on the specific collateral and accept collateral only at the general collateral rate.
32
Federal Reserve Bank of Atlanta E C O N O M I C R E V I E W Second Quarter 2002
CHART 7 Capturing the Repo Dividend
gen. collat. At inception: Customer 1 funds gen. collat. At maturity: Customer 1 (1 + r) × funds Dealer (1 + R) × funds Dealer funds spec. collat. Customer 2 spec. collat. Customer 2
A dealer can capture the repo dividend by repoing out the specific collateral that is on special and simultaneously reversing in general collateral. The dealer nets (r – R) times the value of the specific collateral financed in the repo market.
What determines the repo spread? One can adopt a simple model of supply and demand to analyze how the repo spread is determined. Chart 8 shows the demand for collateral by the shorts (those who want to do reverses) and the supply of collateral by the longs (those who want to do repos). The horizontal axis measures the amount of transactions, and the vertical axis measures the repo spread. The equilibrium repo spread and amount of transactions are determined by where supply and demand intersect. In the chart, the security is on special since the repo spread is positive. If instead the demand curve hit the horizontal axis to the left of Q0, then the repo spread would be zero and the security would be trading at general collateral in the repo market. Up to Q0, the supply curve is perfectly elastic at a zero spread (R = r). There is a group of holders (those who hold the collateral) who will lend their collateral to the repo market at any spread greater than or equal to zero. Beyond Q0, the supply curve slopes upward. To attract additional collateral, the marginal holders require larger and larger spreads. But why is the supply curve not infinitely elastic at all quantities? The fact that the supply curve rises at all indicates that some holders forgo repo spreads of smaller magnitudes. In fact, there are some holders who do not offer their collateral at any spread. At least for smaller spreads, transactions costs of various sorts can account for the upward slope. In addition, some holders are restricted legally or institutionally from lending their collateral. There is an important aspect of the repo market that is not explicitly modeled here: The amount of short interest may exceed the total quantity of the security issued by the Treasury. For example, there may be short positions totaling $20 billion in a given security even though the Treasury has issued only
CHART 8 An Equilibrium Repo Spread
Repo spread Supply (repo)
Demand (reverse)
r–R
Q0
Repo trans.
The supply of repos and the demand for reverse repos determine the repo spread, r – R. If the demand intersects the horizontal axis to the left of Q0, then the repo spread will be zero.
$5 billion of that security. In this situation, a given piece of collateral is used to satisfy more than one short position; this scenario demonstrates the velocity of collateral. In effect, the market expands to match the supply, at least to some extent. However, maintaining this velocity involves informational and technological costs. As the amount of short interest increases and more collateral needs to be reversed in, identifying holders who are willing to lend collateral becomes more difficult. Some who held collateral earlier in the day may no longer have it; others who did not have it earlier may be holders now. Overall, several features may contribute to the upward slope of the supply curve. The auction cycle. The supply and demand framework can be used to illustrate the average pattern of overnight repo spreads over the course of the
5. For institutional reasons, R ≥ 0 as well. 6. Unlike most of the technical terms in this article, the term repo dividend is not standard.
Federal Reserve Bank of Atlanta E C O N O M I C R E V I E W Second Quarter 2002
33
CHART 9 The Effect of a Decrease in the Repo Supply Curve
Repo spread
CHART 10 The Average Pattern of Overnight Repo Spreads
200 B a s is p o in t s p e r d a y 175 150 125 100 75 50 25 0 Q'0 Q0 Repo trans. 1 2 3 4 5 6 7 8 9 10 11 12 13
r – R'
r–R
We e ks sin c e issu a n c e
A decrease in the supply of collateral leads to an increase in the repo spread from r – R to r – R ′ or, equivalently, a fall in the special repo rate from R to R ′.
auction cycle. For example, the U.S. Treasury typically auctions a new ten-year Treasury note every three months (at the midquarter refunding in February, May, August, and November).7 There are three important periodic dates in the auction cycle: the announcement date, the auction date, and the settlement (or issuance) date. On the announcement date, the Treasury announces the particulars of the upcoming auction—in particular, the amount to be auctioned—and when-issued trading begins.8 The auction is held on the auction date and the security is issued on the settlement date. There is usually about one week from the announcement to the auction and one week from the auction to the issuance. During a typical (stylized) auction cycle, the supply of collateral available to the repo market is at its highest level when the security is issued in the sense that Q0 ≥ Q, so that the overnight repo spread is zero. As time passes, more and more of the security is purchased by holders who do not lend their collateral to the repo market. Consequently, Q0 declines over time, shifting the supply curve to the left and driving the repo spread up (see Chart 9). When forward trading in the next security begins on the announcement date, the holders of short positions roll out of the outstanding issue; the demand curve shifts rapidly to the left and drives the repo spread down. Chart 10 shows how the shifts in supply and demand described above are reflected in the average pattern of overnight repo spreads for an onthe-run security with a three-month auction cycle. Actual auction cycles display a huge variance around this average. The chart shows the average
34
The chart shows the average pattern of overnight repo spreads for an on-the-run security with a three-month (thirteen-week) auction cycle. The current on-the-run security is issued at week 0. The next security is announced at week 11 (at which point forward trading in the next security begins), auctioned at week 12, and issued at week 13. The overnight repo spreads reach a peak of 200 basis points per day at week 11. This cycle produces 0.5 × 91 × 200 = 9,100 basis-point days of repo dividend earnings (the total area under the curve).
overnight spread descending to (and presumably staying at) zero in week 13. This diagram is an adequate approximation for the three-year note but it is not a good approximation for the ten-year note, for which the overnight repo spread can average 25 to 50 basis points during the following auction cycle. In the next section, the analysis will demonstrate how the expected future overnight repo spreads are reflected in the price of the onthe-run bond.
Repo Dividends and the Price of the Underlying Bond
simple rule can be used to determine what the expected payment of a repo dividend does to the price of a bond: The expected return on the bond (which includes the repo dividend) is unchanged. The expected return is simply repackaged; whatever goes into the repo dividend yield comes out of the capital gain. In other words, the spot price will rise until the expected return on the bond is exactly the risk-free rate, r, as the following analysis demonstrates. Let p denote the current price of an n-period default-free zero-coupon bond, and let p′ denote the price of that bond next period when it becomes an (n – 1)-period bond. Recall that r is the one-period risk-free interest rate (which is the same as the general collateral rate). In this case (assuming there is no uncertainty for the time being), the current price equals the present value of next period’s price:
A
Federal Reserve Bank of Atlanta E C O N O M I C R E V I E W Second Quarter 2002
(1)
p=
p′ . 1+ r
For a one-period bond, p′ = 1 and p = 1/(1 + r). If the bond paid a dividend, δ, at the end of the period, then the current price would reflect the present value of that dividend as well: (2) p= p′+ δ . 1+ r
If the dividend is in fact a repo dividend, where δ = (r – R)p, then (3) p= p′+ ( r − R )p . 1+ r
Because both sides of equation (3) involve the current price, p, the equation can be solved as follows: (4) p= p′ . 1+ R
Note the similarity of equation (4) to equation (1). The value of a bond that pays a repo dividend equals next period’s price discounted at its own repo rate. Equation (4) reduces to equation (1) when R = r. Rearranging equation (2) produces (5) p′ − p δ + = r, p p
where the first term on the left-hand side of equation (5) is the capital gain and the second term is the (repo) dividend yield (δ/p = r – R). Neither the risk-free rate, r, nor next period’s bond price, p′, depends on the current repo dividend, δ, or the current repo rate, R. Comparing two securities with different repo rates reveals that, for the bond with the lower repo rate, (1) the repo dividend is higher, (2) the dividend yield is higher, (3) the current bond price is higher, (4) the capital gain is smaller, and (5) the expected return is the same. Uncertainty and the forward premium. When uncertainty is introduced, risk premiums must be accounted for. Risk premiums compensate investors for bearing risk by increasing the expected return. Because repo transactions are essentially forward contracts, it is convenient to introduce risk premiums through the forward premium.
A forward contract is an agreement today to deliver something on a fixed date in the future (the delivery date) in exchange for a fixed price (the forward price). A repo establishes a forward position, and the repo rate on a bond is simply a way of quoting the forward price of the bond. An n-period default-free zero-coupon bond with a face value equal to 1, by definition, pays its owner 1 after n periods. Let p denote the current (spot) price of this bond, F denote the forward price of the bond for delivery next period, and R denote the (one-period) repo rate for the bond. A long forward position is established by buying the bond for p and financing it in the repo market for one period at rate R. (The net cash flow at purchase is zero.) In the next period, one pays (1 + R)p and receives the bond.9 Therefore, the forward price is F = (1 + R)p.10 In fact, the repo rate is defined by R = F/p – 1. If current information is available, one knows the current bond price, p; the current repo rate, R; and the current risk-free rate, r. But one does not know for sure the price of the bond next period, p′ (unless it is a one-period bond, in which case p′ = 1). Assuming that one knows the probability distribution of p′, then one knows the average price (also known as the expected price). Let E[ p′] denote the expected price. The actual price of the bond next period, p′, equals its expected price plus a forecast error ε that is independent of everything currently known: (6) p′ = E[ p′] + ε.
The forward price, F, is also known today. The forward premium, p, is defined as the difference between the expected and the forward price: (7) π = E[ p′] – F.
The forward premium is a risk premium. Given p = F/(1+R) and the definition of the forward premium, (8) p= E[ p′] − π . 1+ R
7. Occasionally, instead of issuing a new security the Treasury reopens the existing on-the-run security, selling more of the same security at the next auction. See the discussion on reopenings below. 8. When-issued trading refers to forward transactions for delivery of the next issue when it is issued. 9. A short forward position is established by selling the bond short for p and financing it in the repo market (on a reverse repurchase agreement) for one period at rate R. Next period, one receives (1 + R)p and delivers the bond. 10. The forward price does not depend on the price of a one-period bond as is sometimes incorrectly assumed. See Appendix 2 for a discussion of how this miscalculation of the forward price can lead to a false rejection of the expectations hypothesis.
Federal Reserve Bank of Atlanta E C O N O M I C R E V I E W Second Quarter 2002
35
Using R = r – δ/p to eliminate R,11 equation (8) can be reexpressed as (9) E[ p′] − p δ π + =r+ , p p p
next period and its current expected price can be expressed as follows: (13a) p′ ≈ 1 + ∑ s( i) − ∑ r ( i), and
i=1 i=1 n−1 n−1
which demonstrates that the expected return (capital gains plus repo dividends, both as fractions of the investment) equals the risk-free rate plus a risk premium. Equation (9) reduces to equation (5) when there is no uncertainty. The comparison following equation (5) between two bonds with different repo rates applies just as well when there is uncertainty. Future repo rates. In order to express equation (4) in terms of future repo rates, one can assume for the moment there is no uncertainty. Recall that p is the price of an n-period zerocoupon bond. For a one-period bond, p′ = 1, and equation (4) implies that p = 1/(1 + R). For a bond with a maturity of two periods or more, let p′′ denote its price two periods hence when it becomes an (n – 2)-period bond. Similarly, let r′ and R′ denote the values next period of the shortterm interest rate and the repo rate. Then, following the same steps that led to equation (4), (10) p′ = p′′ . 1 + R′
(13b)
E[ p′] ≈ 1 + ∑ E[ s( i) ] − ∑ E[r ( i) ],
i=1 i=1
n−1
n−1
where the indexes in the sums begin at one instead of zero. Subtracting equation (13b) from (13a) yields, (14) p′ − E[ p′] ≈ 1 + ∑ (s( i) − E[ s( i)]) − ∑ ( r ( i) − E[r ( i) ]).
i=1 i=1 n−1 n−1
Using equation (10) to eliminate p′ from equation (4) yields p = p′′/(1 + R)(1 + R′). For a two-period bond, p′′ = 1 and p = 1/(1 + R)(1 + R′). An analogous expression holds for bonds of longer maturities. If p is the price of an n-period bond, then (11) p= ∏
n−1
1 , (i) i=0 1 + R
where R(0) = R, R(1) = R′, R(2) = R′′, etc. Equation (11) expresses the bond price as the present value of the final payment discounted at its current and future one-period repo rates.12 As an approximation, equation (11) can be written as (12) p = ∏
n−1 n−1 n−1 n−1 1 ≈ 1 − ∑ R( i) = 1 + ∑ s( i) − ∑ r ( i), (i) i=0 1 + R i=0 i=0 i=0
In equation (14), the uncertainty is decomposed into two components: uncertainty associated with future repo spreads and uncertainty associated with future interest rates. If a dealer is using the bond to hedge another position, then the effect of unanticipated changes in future interest rates on the bond’s price is offset by the hedged position (by assumption). However, the effect of unanticipated changes in future repo spreads is not offset. The dealer faces this very real risk when using short positions in on-the-run securities to hedge other securities. If expected future repo spreads fall while the dealer’s short position is open, the dealer may be forced to repurchase the bond at a significantly higher price when the hedge is removed, leading to possibly substantial losses. The price premium and future repo spreads. The analysis next compares the price of an n-period bond that may earn repo dividends (specific collateral) with the price of a baseline n-period bond that earns no repo dividends.13 To simplify the exposition, it is assumed there is no uncertainty. Let the price of the specific collateral be p and – the price of the baseline bond be p. The price premium of the specific collateral over the baseline – bond can be measured as ψ = log(p/p ). The price of the baseline bond can be expressed in terms of the current and future one-period risk-free interest rates (general collateral rates) (compare equation n–1 – [11]): p = Π i=0 /(1 + r(i)), where r (0) = r, r (1), r (2) = r′′, and so on. Then the price premium is given by n−1 1 ∏ i=0 1 + R( i ) n−1 (i) (i) (15) ψ = log ) = ∑ (log(1+ r ) − log(1+ R ) ∏n=−01 1 ( i ) i=0 i 1+ r ≈ ∑ ( r ( i) − R( i) ) = ∑ s( i) .
i=0 i=0 n−1 n−1
where the repo rates are expressed in terms of the risk-free (general collateral) rate and the repo spread, R(i) = r(i) – s(i). Equation (12) shows that higher repo spreads lead to higher bond prices while higher riskfree rates lead to lower bond prices. If uncertainty is introduced into future risk-free rates and repo spreads (the current risk-free rate, r, and repo spread, s, are known, of course) and if, for expositional simplicity, all uncertainty is assumed to be resolved next period, then the price of the bond
36
The relative price premium equals (to a close approximation) the sum of the current and future repo spreads. A bond may have a significant price
Federal Reserve Bank of Atlanta E C O N O M I C R E V I E W Second Quarter 2002
CHART 11
premium, even though it has no current repo dividends, as long as it has future repo dividends. This pattern can be seen in the Treasury market. When a bond is first issued, typically it has a significant price premium even though it is not on special for overnight repo transactions. Later, however, the overnight rates typically move lower than the general collateral rates, opening up a significant repo spread. Given equation (15), the price premium can be n–1 expressed as ψ ≈ s + ψ′, where ψ′ = Σ i=1 s(i) is the price premium next period. This relation between ψ and ψ′ shows that the price premium declines over time as the repo dividends are paid: ψ′ – ψ ≈ –s. The larger the repo spread, the greater the decline in the price premium; conversely, if the current repo spread is zero, then the price premium does not decline. The presence of uncertainty complicates the situation slightly. If there is uncertainty about future repo spreads, then revisions in their expectations will also affect the change in the price premium. In this case, it is the expected change in the price premium that is approximately equal to (the negative of) the current one-period repo spread: E[ψ′] – ψ ≈ –s. Chart 11 shows the price premium, π, computed from the repo spreads shown in Chart 10. Equation (15) provides the link between the two graphs. The height of the curve in Chart 11 for a given week equals the sum of the remaining repo spreads, which in turn equals the area under the curve in Chart 10 to the right of that week. Thus, the premium of 25 basis points at week 0 in Chart 10 equals the total area under the curve.14 The premium of 25 basis points is in line with that for the thirty-year bond during the late 1980s and early 1990s. During the same period the average price premium at issuance for the tenyear note was about 60 basis points while it was about 10 basis points for the three-year note. These average price premia all display the same general shape as that displayed in Chart 11. The one significant difference is that the ten-year note retained a 20 basis point premium throughout the following cycle. The huge variance around the average pattern shown in Chart 11 is consistent with the variance around the pattern of overnight repo rates shown in Chart 10.
The Average Price Premium
25 20 B a s is p o in t s 15 10 5
0
1
2
3
4
5
6
7
8
9 10 11 12 13
We e ks sin c e issu a n c e The chart shows the average price premium for an on-the-run security with a three-month (thirteen-week) auction cycle. This price premium is computed from the stylized overnight repo spreads in Chart 10. The price premium is the sum of all remaining repo spreads. When the security is issued, it has a price premium of about 25 basis points of the value of a reference bond. (The bid-ask spread for an on-the-run security is less than or equal to 1/32 per 100 = 3.125 basis points.)
Implications and Discussion
actors that determine the total specialness. One implication of the analysis is that the size of the price premium at the auction depends on the total number of basis-point days of “specialness” that the security will generate during its life. The security’s total specialness can increase either through the overnight spread increasing or by the security being on special for a longer time. For example, the main reason the price premium for the two-year note is small on average (less than 10 basis points) is that it is on a monthly cycle and therefore has only about thirty days to accumulate repo dividends versus the ninety-one days for securities with a three-month cycle. As noted above, securities that are on quarterly cycles typically have larger price premiums; the significant variation across the price premiums of such securities can be attributed to the average size of the spreads.15 Occasionally, instead of selling a new security at the next auction, the Treasury reopens the existing on-the-run security. Such a reopening extends the length of time the security is on the run. Since the
F
11. Recall that δ = (r – R)p. n–1 12. Consequently, the yield to maturity on a bond is (approximately) the average of these repo rates: –log(p)/n = Σi=0 log(1 + R(i))/n n–1 ≈ Σi=0 R(i)/n. 13. There are a sufficient number of securities that can reasonably be assumed to satisfy this condition so that the value of a baseline bond can be calculated for any specific security. 14. The repo spreads in Chart 10 are quoted in basis points per day, which must be converted to basis points per year before they can be plugged into Equation (15). The total area under the curve in Chart 10 is 1/2 × 91 × 200 = 9,100 basis-point days, which equals approximately 25 basis-point years. 15. In addition, owing to institutional details, the repo spread cannot exceed the general collateral rate, so it is possible to have larger repo spreads when short-term rates are higher.
Federal Reserve Bank of Atlanta E C O N O M I C R E V I E W Second Quarter 2002
37
supply available to the repo market is replenished by the new issuance, overnight repo rates tend to follow the same pattern on average for a reopened issue. Nevertheless, if such a reopening can be forecast ahead of time, all of the repo dividends from the next auction cycle will be capitalized into the value of the current on-the-run security, raising the premium. A number of factors that affect the total specialness came together to produce a spectacularly large price premium for one issue. In the early 1990s, the Treasury changed the auction cycle for the thirtyyear bond from quarterly to semiannually. This change effectively doubled the number of days that
An increase in expected future short selling drives up the current price of a Treasury bond because future repo dividends are capitalized while the expected return on the security is unchanged.
the new thirty-year would maintain its on-the-run status. Therefore, it was reasonable to forecast that the total amount of specialness that would accrue to the bond had increased significantly, and capitalizing those increased dividends led to a price premium that was substantially larger than usual. Once the price premium reached a certain critical amount, another factor entered the picture. Just prior to the change in the auction cycle, the Treasury had committed to reopening any security for which there appeared to be a significant “shortage.” A significant price premium was considered to be one symptom of a shortage. When the Treasury changed the auction cycle, there had not yet been an opportunity to demonstrate a willingness to follow through on the stated commitment, and it was widely believed that the Treasury would do so at the first opportunity. With the price premium on the thirtyyear bond reaching new heights, it was reasonable to forecast that the Treasury would reopen the bond at the next auction (six months hence) with the result that the bond would remain on the run for a whole year. Given this belief, it was reasonable to forecast the amount of specialness that would accrue to the thirty-year had increased significantly yet again. As a consequence, the price premium increased even more, tending to confirm the belief that the Treasury would reopen the bond, and such a reopening is of course just what occurred.
38
Not all reopenings increase the length of time a security remains on the run. In the wake of the disaster in New York City on September 11, 2001, the Treasury conducted a surprise reopening of the tenyear note in the middle of the auction cycle. This reopening had the desired effect of increasing the supply available to the repo market and raising overnight repo rates significantly. The reopening apparently also had a salutory effect on other issues as market participants recognized the Treasury’s willingness to undertake such reopenings as it saw fit. Convergence trades. The price premium that the on-the-run bond commands typically disappears by the time it goes off the run; that is, the on-therun security displays a predictable capital loss relative to the baseline security (which for practical purposes can be taken to be the old security). In other words, the price of the on-the-run security converges to the price of the baseline bond. The popular press has described a convergence trade that purports to profit from this price convergence. But, as discussed earlier, the systematic movement in relative prices is offset by the relative financing costs. Although individual episodes may have produced substantial profits for convergence trades, other episodes have produced substantial losses. On average such trades are not profitable. If uninformed speculators came to dominate the short interest in the on-the-run security in a mistaken attempt to profit from convergence, such speculators would change the dynamics of the auction cycle. Convergence occurs precisely because the shorts (who ordinarily are hedgers) roll out of the current on-the-run security and into the next issue, thereby eliminating the possibility of substantial future repo dividends for the current issue. By contrast, convergence traders (who are also short) will wait until the liquidity premium disappears before they close their short positions. But if convergence traders constitute a sufficient amount of short interest, then their short positions—by themselves—will keep the liquidity premium from disappearing. At this point, other speculators who simply observed the price premium without considering the repo market might conclude that a special profit opportunity had appeared and jump into the convergence trade, further increasing the repo spread and price premium. Those who jumped in early would find the premium has diverged instead of converged.
The Repo Squeeze
T
he analysis thus far has assumed that the repo spread is determined in a market in which no agent has (or exercises) market power. By contrast,
Federal Reserve Bank of Atlanta E C O N O M I C R E V I E W Second Quarter 2002
CHART 12
an agent with a sizable position to finance faces an interesting problem—how to finance at the cheapest possible rate given that the amount financed may affect the rate paid. In order to understand the tradeoffs a repo trader faces in choosing the optimal mix, it is necessary to be familiar with a triparty repo. Triparty repo. To obtain reliable sources of funding, dealers quite commonly establish ongoing relationships with customers seeking safe shortterm investments for their funds such as repos. To facilitate this relationship, the dealer and the customer may enter into a triparty repo agreement in which the third party is a clearing bank. Both the dealer and the customer must have clearing accounts with the bank. The bank provides a number of services, including verifying that the collateral posted by the dealer meets the prespecified requirements of the customer. An important aspect of a triparty repo is that the transfer of collateral and funds between the dealer and the customer occurs entirely within the books of the clearing bank and does not require access to Fedwire. This feature is convenient because it allows for repo transactions to be consummated late in the day after Fedwire is closed for securities transfers, which typically is midafternoon. The repo squeeze. Suppose a repo trader has a sizable (long) position in a Treasury security to finance. The position may have been acquired outright by the dealer’s Treasury desk or it may have been acquired by the repo trader himself via reverse repos for some term to maturity. The collateral can be financed either directly in the market at rate R or via a triparty repo at the general collateral rate, r.16 What makes this choice interesting is that the amount the trader finances directly in the market may affect the repo rate itself. If the trader’s position is substantial, then as more and more collateral is lent directly in the repo market, the special repo rate will rise. In this case, the traders must take care to compute the financing mix that minimizes the total financing cost. Let Q denote the total amount of collateral to be financed and q denote the amount financed directly in the market so that Q – q is the amount financed via a triparty repo. Therefore, the cost of financing the collateral is Rq + r(Q – q). This financing cost can be rewritten as rQ – (r – R)q, which expresses the financing cost as the general collateral rate
Maximizing the Repo Dividend
Repo spread
D
S Net demand
r – R* S* q* Repo MR trans. q*
In the left panel, the demand curve for collateral by the shorts is labeled D, and the supply curve of collateral by others is labeled S. In the right panel, the difference between D and S is the net demand facing the trader, and the diagonal dashed line is marginal revenue. The arrow indicates the profit-maximizing (or cost-minimizing) quantity of collateral to supply directly to the market, q*. The area of the rectangle is the maximized repo dividend, (r – R*)q*. If the trader’s total amount to be financed, Q, is greater than q*, then the difference, Q – q*, is financed via a triparty repo. The amount supplied by others is S*.
applied to the total amount of collateral, rQ, less the repo dividend on the amount financed directly in the market, (r – R)q. Thus, minimizing the finance cost is the same as maximizing the repo dividend. The problem for a trader with a large position is that an increase in q leads to an increase in R, decreasing the spread, r – R. Whether the repo dividend goes up or down when q increases depends on just how responsive the special repo rate is to the amount of collateral lent directly to the market. In effect, the trader has the same problem as a monopolist: The amount “produced” (q) affects the price (r – R). The trader faces a downward-sloping demand curve. In this case, the demand curve facing the trader is a net demand curve, in which the supply of collateral by others is subtracted from the demand for collateral by the holders of short positions.17 This situation is depicted in Chart 12. The quantity that maximizes the repo dividend (q*) is determined by the condition that marginal revenue be zero. If Q ≤ q*, then all the collateral is financed directly in the market. On the other hand, if Q > q*, then q* is financed directly in the market and Q – q* is financed via a triparty repo at the higher rate, r. This situation (that is, when Q > q*) is known as a repo squeeze. There are two essential ingredients for a repo squeeze. First, there must be outstanding short positions; otherwise, the security could not go on special. Second, the trader must have possession of the collateral, by having acquired it outright or
16. The dealer’s counterparty on a triparty agreement has no interest in whether any of the collateral in its triparty repo account at its clearing bank is on special, and it will not accept less than the general collateral rate on its loans to the dealer secured by that collateral. 17. The trader plays the role of the dominant firm among a competitive fringe of other suppliers.
Federal Reserve Bank of Atlanta E C O N O M I C R E V I E W Second Quarter 2002
39
via term reverse repos. (For collateral acquired via reverse repo, the term of the repo limits the duration of the repo squeeze; when the reverses mature, the collateral must be returned.) One should recognize that the “profits” from a repo squeeze come from driving the repo spread up and earning a larger repo dividend than otherwise. While it is true that a repo squeeze drives the price of the security higher than it otherwise would be, this feature is a side effect. Since a squeeze can be maintained only by one who controls the collateral, selling the security is counterproductive. Note that if the repo squeeze is fully anticipated, the shorts bear no cost since they establish their short positions at appropriately high prices. By the same token, the trader earns no profits from a fully anticipated squeeze since the prices at which he acquired the security fully reflected his actions. Thus, a repo squeeze is profitable only if it is not fully anticipated.
Conclusion
his article has presented the somewhat surprising proposition that an increase in expected future short selling drives up the current price of a Treasury bond because future repo dividends are capitalized while the expected return on the security is unchanged. The repo dividends arise when a bond goes on special—that is, when the bond’s repo rate falls below the risk-free rate. The liquidity premium for an on-the-run Treasury security can be attributed to this effect. The premium goes away when the bond goes off the run because the holders of short positions roll out of the current issue and into the new issue, thereby eliminating the possibility of significant future repo earnings. The on-the-run security’s predictable capital loss relative to other bonds is offset by its financing cost relative to other bonds. Consequently, there are no profits to be made from so-called convergence trades on average.
T
40
Federal Reserve Bank of Atlanta E C O N O M I C R E V I E W Second Quarter 2002
APPENDIX 1 Term Structure of Repo Spreads
hus far, the discussion has considered only oneperiod repo transactions, that is, those in which the securities have been repoed (or reversed) for one period only. However, term repo transactions are quite common. In a term repo, a single, fixed repo rate is agreed to at the inception of the transaction. Perhaps the best way to think about term repo rates is as a way of quoting forward prices for delivery more than one period in the future. Consider an n-period bond that has a current price of p. To establish a long forward position in the bond for delivery in two periods, one buys the bond and repos it in the term repo market for two periods at the rate of R2 per period. The current cash flow is zero. At time two, one pays (1 + R2)2p and receives the bond. Thus, F2 = (1 + R2)2p, where F2 is the forward price of a given bond for delivery in two periods. In general, the forward price for delivery in m periods is F = (1 + Rm)mp, where Rm m is the m-period repo rate (per period) and Fm is the forward price for delivery in m periods. Compare the cost of financing a bond for m periods with a term repo versus rolling over oneperiod financing. In the first case the cost is (1 + m–1 Rm)m while in the second case the cost is Π i=0(1 (1) + R ). When there is no uncertainty, these two costs must be the same, implying an expectations m–1 hypothesis for repo rates: Rm ≈ Σ i=0 R(i)/m. – Consider again the price premium, ψ = log(p/p). – = 1/(1 + r )n, For the baseline n-period bond, p n where rn is the yield to maturity of the baseline bond (which earns no repo dividends). The price premium can be reexpressed as
T
s(i)/n, which shows that the term repo spread is (approximately) the average of the one-period repo spreads. Moreover, the term structure of repo spreads can be used to forecast the dynamics of the price premium. In particular, the n-period change in the price premium is approximately equal to (the negative of) the n-period term repo spread, ψ(n) – ψ ≈ –sn, where ψ(n) is the price premium n periods later. Uncertainty, of course, complicates matters a bit: E[ψ(n)] – ψ ≈ –sn. The chart displays the average pattern of three term repo spreads over the course of a three-month auction cycle. The term spreads are computed in accordance with the expectations hypothesis from the average pattern of overnight spreads shown in Chart 10. These term repo spreads are in line with those observed on the market.
CHART The Term Structure of Repo Spreads
200 Ba sis p o in ts p e r d a y 175 150 125 100 75 50 25 0 1 2 3 4 5 6 7 8 9 10 11 12 13 We e ks sin c e issu a n c e
(A1.1)
1/(1 + Rn )n ψ = log ≈ n( rn − Rn ) = nsn , n 1/(1 + rn )
where sn = rn – Rn is the term repo spread. Comparing the expression for ψ in equation n–1 (A1.1) with that in equation (15) yields sn ≈ Σi=0
Term repo spreads are computed from the stylized overnight repo spreads in Chart 10: thirty-day (solid), sixty-day (dashed), and ninety-day (dotted). When the security is issued at week 0, the term structure slopes upward, anticipating the rise in overnight rates; the thirty-day spread is about 39 basis points while the ninety-day spread is about 100 basis points. By week 8, the term structure slopes steeply downward; the thirty-day spread is about 160 basis points while the ninety-day spread is about 56 basis points.
Federal Reserve Bank of Atlanta E C O N O M I C R E V I E W Second Quarter 2002
41
APPENDIX 2 Forward Prices and the Expectations Hypothesis
he forward rate, F, can be used to forecast the bond price next period, p′. A linear forecast has the form p′ = α + βF, where p′ is the forecast. ˆ ˆ The coefficients α and β are constants that can be chosen to produce unbiased forecasts and to minimize the variance of the forecast error, p′ – p′. ˆ The slope coefficient, β, is computed as
T
Finally, if π is constant, then equation (A2.3) reduces to β= Var[ E[ p′]] = 1. Var[ E[ p′]]
(A2.1)
β=
Cov[ p′, F ] , Var[ F ]
where Cov[p′, F] is the covariance between p′ and F and Var[F] is the variance of F.1 If the expectations hypothesis holds, then β = 1, in which case p′ = α + F and changes in the foreˆ cast (∆p′) correspond to changes in the forward ˆ price (∆ F).2 The forward risk premium plays a central role in determining whether the expectations hypothesis holds. It will be shown that if π is constant (that is, if π is the same in every period), then β = 1. The strategy is to write both F and p′ in terms of E[p′] by using the definition of the forward premium in equation (7) and the relation between next period’s price and its current expectation in equation (6). Substituting these expressions for F and p′ into equation (A2.1) produces Cov[ E[ p′ ] + ε, E[ p′] − π] . Var[ E[ p′] − π]
(A2.2)
β=
In the numerator of equation (A2.2), the properties of covariances and the independence of ε imply 3 Cov[ E[ p′] + ε, E[ p′] − π] = Cov[ E[2],E[ p′]] 144 p′443
=Var[ E [ p′ ]]
− Cov[E[ p′], π] + Cov[ε, E[ p′]] − Cov[ε, π] 14 24 3 1 24 4 4 4 3
=0 =0
= Var[ E[ p′]] − Cov[ E[ p′], π].
The regression coefficient can now be reexpressed: Var[ E[ p′]] − Cov[ E[ p′], π] . Var[ E[ p′] − π]
A number of empirical studies have purported to estimate β for U.S. data. These estimates typically reject the hypothesis that β = 1 and conclude therefore that π is not constant. The following discussion illustrates how these studies may have incorrectly computed forward rates. Consequently, the slope coefficient that was estimated involves additional factors that were ignored. Pseudo forward rates. The way of computing forward prices that has been used in many empirical studies is incorrect and can lead to spurious rejections of the expectations hypothesis. As before, let p denote the current price of an n-period bond (where in this case n ≥ 2). Define ˜ the pseudo forward price of the bond as F = p/p1, where p1 is the current price of a one-period bond. The price of the one-period bond can be written in terms of its own one-period repo rate: p1 = 1/(1 + R1), where R1 is the one-period repo rate for the one-period bond. Thus, the pseudo ˜ forward price can be expressed as F = (1 + R1)p. ˜ Comparing this expression for F with the expression for the true forward price, F = (1 + R)p, ˜ shows that F uses the wrong repo rate. The definition of the pseudo forward price implicitly assumes one can finance the n-period bond at R1 rather than at its own repo rate R. Defining the pseudo forward premium, π = ˜ ˜ ˜ E[p′] – F, note that π = (E[p′] – F) + (F – F) = π + ˜ (R – R1)p. In other words, the pseudo forward premium equals the true forward premium plus another term that reflects the difference between the two repo rates. Even if the true forward premium were identically zero, the pseudo forward premium would equal (R – R1)p. Suppose the pseudo forward price (instead of the true forward price) is used to forecast the price of the bond next period. Let the linear forecast be given by α + ˜ F, where the coefficients α ˜ β˜ ˜ and ˜ are chosen to minimize the forecast error. β The slope coefficient is ˜ ˜ Cov[ p′, F ]. β= ˜ Var[ F ]
(A2.3)
β=
(A2.4)
42
Federal Reserve Bank of Atlanta E C O N O M I C R E V I E W Second Quarter 2002
A P P E N D I X 2 (continued)
If π is constant but R1 – R is random, then ˜ ≠ 1. β Following the steps above that lead from equation (A2.1) to equation (A2.3), but replacing F and π ˜ with F and π, leads from equation (A2.3) to ˜ ˜ ˜ Var[ E[ p′]] − Cov[ E[ p′], π]. β= ˜ Var[ E[ p′] − π]
By the properties of variance,4 equation (A2.5) can be expressed as (A2.6) ˜ β= A , A+ B
(A2.5)
where A = Var[E[ p′]] – Cov[E[ p′], π] and B = Var[π] ˜ ˜ – Cov[E[p′], π]. If B = 0, then ˜ = 1. If π is constant, ˜ β then π = (R – R1)p and B = Var[(R – R1)p] – ˜ Cov[E[ p′], (R – R1)p]. In general, B ≠ 0.
1. Conditionally (that is, given the information available at the beginning of the current period), F and E[ p′] are known constants. However, over time F and E[ p′] vary from period to period. Therefore, unconditionally, they are random variables with nonzero variances and covariances. 2. Strictly speaking, by itself β = 1 characterizes the weak form of the expectations hypothesis. The strong form also requires α = 0. 3. (i) Cov[a + b, c + d] = Cov[a,c] + Cov[a,d] + Cov[b,c] + Cov[b,d] and (ii) Cov[a,a] = Var[a]. If a is independent of b, then Cov[a,b] = 0. 4. Var[a – b] = (Var[a] – Cov[a,b]) + (Var[b] – Cov[a,b]).
REFERENCES
Cornell, Bradford, and Alan C. Shapiro. 1989. The mispricing of U.S. Treasury bonds: A case study. Review of Financial Studies 2, no. 3:297–310. Duffie, Darrell. 1989. Special repo rates. Journal of Finance 2, no. 3:493–526. Federal Reserve Bank of New York. 1998. U.S. monetary policy and financial markets. < addpub/monpol> (May 29, 2002). ———. n.d. Understanding open market operations. <> (May 29, 2002). Federal Reserve Bank of Richmond. 1993. Instruments of the money market. <> (May 29, 2002). Jordan, B.D., and Susan Jordan. 1997. Special repo rates: An empirical analysis. Journal of Finance 52 (December): 2051–72. Keane, Frank. 1996. Repo rate patterns for new Treasury notes. Current Issues in Economics and Finance (Federal Reserve Bank of New York) 2, no. 10:2–6. Krishnamurthy, Arvind. Forthcoming. The bond/old-bond spread. Journal of Financial Economics. Stigum, Marcia. 1989. The money market. 3d ed. Homewood, Ill.: Dow Jones-Irwin.
Federal Reserve Bank of Atlanta E C O N O M I C R E V I E W Second Quarter 2002
43 | https://www.scribd.com/doc/40181609/Fisher-2q02 | CC-MAIN-2017-13 | refinedweb | 11,628 | 50.36 |
04 May 2011 16:41 [Source: ICIS news]
By: Helen Yan
?xml:namespace>
Non-oil grade 1502 SBR prices in Asia have doubled since August last year, increasing by a staggering $2,000/tonne, driven by a combination of factors including strong demand from the automotive sector, tight supply and soaring natural rubber (NR) prices.
By the end of April, non-oil grade 1502 SBR prices had shot to near $4,000/tonne (€2,680/tonne) CIF (cost, insurance and freight) China, according to ICIS data.
Non-oil grade 1502 SBR is the most actively traded grade of synthetic rubber and widely used in tyre and footwear manufacturer.
But, have SBR prices peaked? And will they tumble in the third quarter?
A key concern is that China’s tightened monetary policy will dampen sentiment and slow down SBR demand in Asia. In such circumstances, can the automotive industry in China keep up its sizzling pace of growth?
Total auto sales rose 32% in 2010 to 18.1m vehicles, following growth of 46% in 2009, according to the China Association of Automobile Manufacturers (CAAM).
Chinese auto-makers have forecast that car sales in
The broad market slowdown in
Not suprisingly, SBR producers in Asia are keeping a close watch on
Indeed, the Chinese government’s monetary policy of incessantly raising interest rates to combat inflation has started to bite.
It has raised interest rates four times in the past six months and rumours of another interest rate hike in May has sent shivers down traders’ spines.
“It is getting more and more difficult to get credit and trades will only slow down further if there is another interest rate increase,” one Chinese trader said.
Chinese SBR imports fell 20% in the first quarter of 2011, compared with the same period last year, as it has become more difficult for businesses to borrow money.
“
Falling natural rubber prices is another factor that may exert further downward pressure on the SBR price. NR prices futures have fallen by $700/tonne during the past month.
The products are interchangeable in the tyre market with manufacturers adjusting formulations to take one product or the other as prices and avalability change. NR and SBR prices tend to move in tandem and impact each other.
NR futures for September delivery at the Singapore Commodity Exchange fell to about $4,500/tonne in late April, from around $5,200/tonne in the early part of the month.
“Natural rubber prices have fallen sharply and are likely to continue falling. So we expect to see a corresponding correction in SBR prices soon,” one tyre producer said.
($1 = €0.67, CNY6.50). | http://www.icis.com/Articles/2011/05/04/9455967/insight-asia-sbr-market-shivers-as-pressure-mounts-on-china-autos.html | CC-MAIN-2013-20 | refinedweb | 442 | 59.64 |
Hi Chris,On 04/12/2010 08:49 PM, Chris Mason wrote:> /*> + * when a semaphore is modified, we want to retry the series of operations> + * for anyone that was blocking on that semaphore. This breaks down into> + * a few different common operations:> + *> + * 1) One modification releases one or more waiters for zero.> + * 2) Many waiters are trying to get a single lock, only one will get it.> + * 3) Many modifications to the count will succeed.> + *> Have you thought about odd corner cases:Nick noticed the last time that it is possible to wait for arbitrary values:in one semop: - decrease semaphore 5 by 10 - wait until semaphore 5 is 0 - increase semaphore 5 by 10.> SYSCALL_DEFINE4(semtimedop, int, semid, struct sembuf __user *, tsops,> unsigned, nsops, const struct timespec __user *, timeout)> {> @@ -1129,6 +1306,8 @@ SYSCALL_DEFINE4(semtimedop, int, semid, struct sembuf __user *, tsops,> struct sem_queue queue;> unsigned long jiffies_left = 0;> struct ipc_namespace *ns;> + struct sem *blocker = NULL;> + LIST_HEAD(pending);>> ns = current->nsproxy->ipc_ns;>> @@ -1168,6 +1347,14 @@ SYSCALL_DEFINE4(semtimedop, int, semid, struct sembuf __user *, tsops,> alter = 1;> }>> + /*> + * try_atomic_semop takes all the locks of all the semaphores in> + * the sops array. We have to make sure we don't deadlock if userland> + * happens to send them out of order, so we sort them by semnum.> + */> + if (nsops> 1)> + sort(sops, nsops, sizeof(*sops), sembuf_compare, NULL);> +> Does sorting preserve the behavior? | https://lkml.org/lkml/2010/4/13/243 | CC-MAIN-2017-13 | refinedweb | 228 | 53.44 |
- Variables are locations where the data is stored when program execute.
- It refers to memory location.
- You should follow the variable naming rules before type a name, Go to Java naming standards post.
- There are two major types of variables in java.
Primitive
- Numeric (integer and floating point)
- Single character
- Boolean (true/false)
- Strings
- Dates
- Everything else
Another types of declaration of variables1. Instance variables (Non-static variable)
2. Class variables (Static variables)
3. Local variables
public class Apple{ int x = 10; // Instance variable static int y = 20; // static variables public static void main(String args[]){ byte z=5; // local variables } }
Instance variable
- This variables are declared in a class, but outside of any block.
- These are visible for all method, constructor and any block in the class.
- If you are using instance variable in non-static field, you have to call it through object.
- We will learn how to create objects in next posts. Here is a example.
- Value is depend on the object which is created.
class Apple{ int x = 10; // Instance variable public static void main(String args[]){ Apple obj = new Apple(); // create obj object System.out.println(obj.x); /*System.out.println(x); this will give a compile time error */ } }
Class variables (Static variables)
- This variable declared with a ‘static’ keyword.
- This variables are start with program start and destroy when program stops.
- Can be accessed with class name.
- Values depend on the class.
class Apple{ static float x = 10.5f; static String s = "ryjskyline"; public static void main(String args[]){ System.out.println(Apple.x); System.out.println("-------------------"); System.out.println(x); System.out.println("-------------------"); System.out.println(s); // Apple.s is also correct } }
Local variable
- Local variable are declared in method, constructors of any other block.
- This type of variable destroy once it exits the method, constructor or block.
- Access modifiers can’t be used for local variables.
- This variable does not initialize to default values.
- Local variables should be explicitly assigning value.
public class Apple{ public static void main(String args[]){ int x =10; System.out.println(x); } }
Java variables
Reviewed by Ravi Yasas
on
2:41 AM
Rating:
| https://www.javafoundation.xyz/2013/09/java-variables.html | CC-MAIN-2021-43 | refinedweb | 356 | 59.4 |
Hierarchical clustering is a type of unsupervised machine learning algorithm used to cluster unlabeled data points. Like K-means clustering, hierarchical clustering also groups together the data points with similar characteristics. In some cases the result of hierarchical and K-Means clustering can be similar. Before implementing hierarchical clustering using Scikit-Learn, let's first understand the theory behind hierarchical clustering.
Theory of Hierarchical Clustering
There are two types of hierarchical clustering: Agglomerative and Divisive. In the former, data points are clustered using a bottom-up approach starting with individual data points, while in the latter top-down approach is followed where all the data points are treated as one big cluster and the clustering process involves dividing the one big cluster into several small clusters.
In this article we will focus on agglomerative clustering that involves the bottom-up approach.
Steps to Perform Hierarchical Clustering
Following are the steps involved in agglomerative clustering:
- At the start, treat each data point as one cluster. Therefore, the number of clusters at the start will be K, while K is an integer representing the number of data points.
- Form a cluster by joining the two closest data points resulting in K-1 clusters.
- Form more clusters by joining the two closest clusters resulting in K-2 clusters.
- Repeat the above three steps until one big cluster is formed.
- Once single cluster is formed, dendrograms are used to divide into multiple clusters depending upon the problem. We will study the concept of dendrogram in detail in an upcoming section.
There are different ways to find distance between the clusters. The distance itself can be Euclidean or Manhattan distance. Following are some of the options to measure distance between two clusters:
- Measure the distance between the closes points of two clusters.
- Measure the distance between the farthest points of two clusters.
- Measure the distance between the centroids of two clusters.
- Measure the distance between all possible combination of points between the two clusters and take the mean.
Role of Dendrograms for Hierarchical Clustering
In the last section, we said that once one large cluster is formed by the combination of small clusters, dendrograms of the cluster are used to actually split the cluster into multiple clusters of related data points. Let's see how it's actually done.
Suppose we have a collection of data points represented by a
numpy array as follows:
import numpy as np X = np.array([[5,3], [10,15], [15,12], [24,10], [30,30], [85,70], [71,80], [60,78], [70,55], [80,91],])
Let's plot the above data points. To do so, execute the following code:
import matplotlib.pyplot as plt labels = range(1, 11) plt.figure(figsize=(10, 7)) plt.subplots_adjust(bottom=0.1) plt.scatter(X[:,0],X[:,1], label='True Position') for label, x, y in zip(labels, X[:, 0], X[:, 1]): plt.annotate( label, xy=(x, y), xytext=(-3, 3), textcoords='offset points', ha='right', va='bottom') plt.show()
The script above draws the data points in the
X
numpy array and label data points from 1 to 10. In the image below you'll see that the plot that is generated from this code:
Let's name the above plot as Graph1. It can be seen from the naked eye that the data points form two clusters: first at the bottom left consisting of points 1-5 while second at the top right consisting of points 6-10.
However, in the real world, we may have thousands of data points in many more than 2 dimensions. In that case it would not be possible to spot clusters with the naked eye. This is why clustering algorithms have been developed.
Coming back to use of dendrograms in hierarchical clustering, let's draw the dendrograms for our data points. We will use the scipy library for that purpose. Execute the following script:
from scipy.cluster.hierarchy import dendrogram, linkage from matplotlib import pyplot as plt linked = linkage(X, 'single') labelList = range(1, 11) plt.figure(figsize=(10, 7)) dendrogram(linked, orientation='top', labels=labelList, distance_sort='descending', show_leaf_counts=True) plt.show()
The output graph looks like the one below. Let's name this plot Graph2.
The algorithm starts by finding the two points that are closest to each other on the basis of Euclidean distance. If we look back at Graph1, we can see that points 2 and 3 are closest to each other while points 7 and 8 are closes to each other. Therefore a cluster will be formed between these two points first. In Graph2, you can see that the dendograms have been created joining points 2 with 3, and 8 with 7. The vertical height of the dendogram shows the Euclidean distances between points. From Graph2, it can be seen that Euclidean distance between points 8 and 7 is greater than the distance between point 2 and 3.
The next step is to join the cluster formed by joining two points to the next nearest cluster or point which in turn results in another cluster. If you look at Graph1, point 4 is closest to cluster of point 2 and 3, therefore in Graph2 dendrogram is generated by joining point 4 with dendrogram of point 2 and 3. This process continues until all the points are joined together to form one big cluster.
Once one big cluster is formed, the longest vertical distance without any horizontal line passing through it is selected and a horizontal line is drawn through it. The number of vertical lines this newly created horizontal line passes is equal to number of clusters. Take a look at the following plot:
We can see that the largest vertical distance without any horizontal line passing through it is represented by blue line. So we draw a new horizontal red line that passes through the blue line. Since it crosses the blue line at two points, therefore the number of clusters will be 2.
Basically the horizontal line is a threshold, which defines the minimum distance required to be a separate cluster. If we draw a line further down, the threshold required to be a new cluster will be decreased and more clusters will be formed as see in the image below:
In the above plot, the horizontal line passes through four vertical lines resulting in four clusters: cluster of points 6,7,8 and 10, cluster of points 3,2,4 and points 9 and 5 will be treated as single point clusters.
Hierarchical Clustering via Scikit-Learn
Enough of the theory, now let's implement hierarchical clustering using Python's Scikit-Learn library.
Example 1
In our first example we will cluster the
X
numpy array of data points that we created in the previous section.
The process of clustering is similar to any other unsupervised machine learning algorithm. We start by importing the required libraries:
import matplotlib.pyplot as plt import pandas as pd %matplotlib inline import numpy as np
The next step is to import or create the dataset. In this example, we'll use the following example data:
X = np.array([[5,3], [10,15], [15,12], [24,10], [30,30], [85,70], [71,80], [60,78], [70,55], [80,91],])
The next step is to import the class for clustering and call its
fit_predict method to predict the clusters that each data point belongs to.
Take a look at the following script:
from sklearn.cluster import AgglomerativeClustering cluster = AgglomerativeClustering(n_clusters=2, affinity='euclidean', linkage='ward') cluster.fit_predict(X)
In the code above we import the
AgglomerativeClustering class from the "sklearn.cluster" library. The number of parameters is set to 2 using the
n_clusters parameter while the
affinity is set to "euclidean" (distance between the datapoints). Finally
linkage parameter is set to "ward", which minimizes the variant between the clusters.
Next we call the
fit_predict method from the
AgglomerativeClustering class variable
cluster. This method returns the names of the clusters that each data point belongs to. Execute the following script to see how the data points have been clustered.
print(cluster.labels_)
The output is a one-dimensional array of 10 elements corresponding to the clusters assigned to our 10 data points.
[1 1 1 1 1 0 0 0 0]
As expected the first five points have been clustered together while the last five points have been clustered together. It is important to mention here that these ones and zeros are merely labels assigned to the clusters and have no mathematical implications.
Finally, let's plot our clusters. To do so, execute the following code:
plt.scatter(X[:,0],X[:,1], c=cluster.labels_, cmap='rainbow')
You can see points in two clusters where the first five points clustered together and the last five points clustered together.
Example 2
In the last section we performed hierarchical clustering on dummy data. In this example, we will perform hierarchical clustering on real-world data and see how it can be used to solve an actual problem.
The problem that we are going to solve in this section is to segment customers into different groups based on their shopping trends.
The dataset for this problem can be downloaded from the following link:
Place the downloaded "shopping-data.csv" file into the "Datasets" folder of the "D" directory. To cluster this data into groups we will follow the same steps that we performed in the previous section.
Execute the following script to import the desired libraries:
import matplotlib.pyplot as plt import pandas as pd %matplotlib inline import numpy as np
Next, to import the dataset for this example, run the following code:
customer_data = pd.read_csv('D:\Datasets\shopping-data.csv')
Let's explore our dataset a bit. To check the number of records and attributes, execute the following script:
customer_data.shape
The script above will return
(200, 5) which means that the dataset contains 200 records and 5 attributes.
To eyeball the dataset, execute the
head() function of the data frame. Take a look at the following script:
customer_data.head()
The output will look like this:
Our dataset has five columns: CustomerID, Genre, Age, Annual Income, and Spending Score. To view the results in two-dimensional feature space, we will retain only two of these five columns. We can remove CustomerID column, Genre, and Age column. We will retain the Annual Income (in thousands of dollars) and Spending Score (1-100) columns. The Spending Score column signifies how often a person spends money in a mall on a scale of 1 to 100 with 100 being the highest spender. Execute the following script to filter the first three columns from our dataset:
data = customer_data.iloc[:, 3:5].values
Next, we need to know the clusters that we want our data to be split to. We will again use the
scipy library to create the dendrograms for our dataset. Execute the following script to do so:
import scipy.cluster.hierarchy as shc plt.figure(figsize=(10, 7)) plt.title("Customer Dendograms") dend = shc.dendrogram(shc.linkage(data, method='ward'))
In the script above we import the hierarchy class of the
scipy.cluster library as
shc. The hierarchy class has a
dendrogram method which takes the value returned by the
linkage method of the same class. The
linkage method takes the dataset and the method to minimize distances as parameters. We use 'ward' as the
method since it minimizes then variants of distances between the clusters.
The output of the script above looks like this:
If we draw a horizontal line that passes through longest distance without a horizontal line, we get 5 clusters as shown in the following figure:
Now we know the number of clusters for our dataset, the next step is to group the data points into these five clusters. To do so we will again use the
AgglomerativeClustering class of the
sklearn.cluster library. Take a look at the following script:
from sklearn.cluster import AgglomerativeClustering cluster = AgglomerativeClustering(n_clusters=5, affinity='euclidean', linkage='ward') cluster.fit_predict(data)
The output of the script above looks like this:, 1, 2, 0, 2, 0, 2, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2], dtype=int64)
You can see the cluster labels from all of your data points. Since we had five clusters, we have five labels in the output i.e. 0 to 4.
As a final step, let's plot the clusters to see how actually our data has been clustered:
plt.figure(figsize=(10, 7)) plt.scatter(data[:,0], data[:,1], c=cluster.labels_, cmap='rainbow')
The output of the code above looks like this:
You can see the data points in the form of five clusters. The data points in the bottom right belong to the customers with high salaries but low spending. These are the customers that spend their money carefully. Similarly, the customers at top right (green data points), these are the customers with high salaries and high spending. These are the type of customers that companies target. The customers in the middle (blue data points) are the ones with average income and average salaries. The highest numbers of customers belong to this category. Companies can also target these customers given the fact that they are in huge numbers, etc.
Resources
Between all of the different Python packages (
pandas,
matplotlib,
numpy, and
sklearn) there is a lot of info in this article that might be hard to follow, and for that reason we recommend checking out some more detailed resources on doing data science tasks with Python, such as an online course:
- Data Science in Python, Pandas, Scikit-learn, Numpy, Matplotlib
- Python for Data Science and Machine Learning Bootcamp
- Machine Learning A-Z: Hands-On Python & R In Data Science
We've found that these resources are good enough that you'll come away with a solid understanding of how to use them in your own work.
Conclusion
The clustering technique can be very handy when it comes to unlabeled data. Since most of the data in the real-world is unlabeled and annotating the data has higher costs, clustering techniques can be used to label unlabeled data.
In this article we explained hierarchical clustering with help of two examples. For more machine learning and data science articles, keep visiting this site. Happy Coding! | https://stackabuse.com/hierarchical-clustering-with-python-and-scikit-learn/ | CC-MAIN-2020-05 | refinedweb | 2,413 | 62.68 |
This required a feature to first be activated in SharePoint. How could we activate the feature? That’s when Keenan Newton wrote his blog post, Defining content in Host Web from an App for SharePoint. The idea was so simple: use the App Installed event.
This post follows the same pattern. I am going to take a pretty long path to do something that can be accomplished pretty quickly because there are a few confusing elements to this pattern:
- Handle the app installed event.
- When the app installed event occurs, an event is sent to our service. We use the client side object model to attach an event receiver to a list in the host web.
- When an item is added to the list, an ItemAdded event is sent to our service.
Visually, it looks like this:
Once you understand this pattern, you’ll use it for all sorts of things such as activating features, creating subsites, applying themes, all kinds of stuff.
If you don’t care about how it all works, just skip to the end to the section “Show Me The Code!”
Remote Event Receivers
A remote event receiver is just like a traditional event receiver in SharePoint. Your code registers itself with SharePoint to be called whenever an event occurs, such as a list is being deleted or a list item is being added. With full trust code solutions, you would register your code by giving SharePoint an assembly name and type name. Server side code for apps isn’t installed on SharePoint, but rather on your own web server, so how would you register a remote endpoint? Provide a URL to a service.
If you aren’t familiar with remote event receivers, go check out the Developer training for Office, SharePoint, Project, Visio, and Access Services which includes a module on remote event receivers.
The point that I want to highlight here is that you tell SharePoint what WCF service endpoint to call when a specific event occurs. That means that SharePoint needs to be able to resolve the address to that endpoint.
Handle App Installed and App Uninstalling
To perform this step, I assume you already have an Office 365 Developer Site Collection. If you don’t, you can sign up for a free 30-day trial. Even better, as an MSDN subscriber you get an Office 365 developer tenant as part of your MSDN benefits.
In Visual Studio 2013, create a new provider-hosted app.
Provide the URL for your Office 365 developer site, used for debugging, and leave the host type as Provider-hosted.
The next screen asks if you want to use the traditional Web Forms model for your app, or if you prefer ASP.NET MVC. I really love ASP.NET MVC, so I’ll use that option.
Finally, you are asked about how your app will authenticate. We are using Office 365, so leave the default option, “Use Windows Azure Access Control Service”. Click Finish.
Once your project is created, click on the app project (not the web project) and change its Handle App Installed and HandleAppUninstalling properties to True.
That will create a WCF service for you in the project where you can now handle an event for when the app is installed.
There are two methods, ProcessEvent and ProcessOneWayEvent, and sample code exists in the ProcessEvent method to show you how to get started with a remote event receiver.
We are going to use the ProcessEvent method to register an event receiver on a list in the host web. We will also use the ProcessEvent method to unregister the remote event receiver when the app is uninstalled. Clean up after yourself!
Add a breakpoint in the ProcessEvent method, but don’t hit F5 just yet.
Debugging Remote Event Receivers
Let me restate that last part if you didn’t catch it: SharePoint needs to be able to resolve the address to your WCF endpoint. Let me change that picture just a bit:
See the difference? Here we have Office 365 calling our web service. If we told O365 that our WCF service was available at, that server would try to make an HTTP call to localhost… the HTTP call would never leave that server. There’s no way that SharePoint can figure out that what you really meant was to traverse your corporate firewall and get past the Windows Firewall on your laptop to call an HTTP endpoint in IIS Express.
Thankfully, someone incredibly smart on the Visual Studio team (hat’s off, Chaks!) figured out how to use Windows Azure Service Bus to debug remote events. That means that SharePoint now has an endpoint that it can deliver messages to, and your app can then connect to service bus to receive those messages.
Even better, you really don’t have to know much about this to make it all work. If you don’t have an Azure subscription already, you can sign up for a free trial. If you have MSDN, you get an Azure subscription as part of your MSDN benefits that includes monthly credits! If you are worried about the cost here, don’t be: as of today, you are charged $0.10 for every 100 relay hours, $0.01 for every 10,000 messages. I seriously doubt anyone is leaving their machine debugging for that long.
Once you have an Azure subscription, log into the Windows Azure Management Portal. Go to the Service Bus extension on the left of the screen.
On the bottom of the screen, click Create to add a new namespace.
Give it a unique name and provide a location near you.
Once the namespace is created, click the Connection Information button, you will see your connection string. Copy it into your clipboard buffer.
Go back to Visual Studio. In the Solution Explorer, click the app project (not the web project) in Visual Studio’s Solution Explorer pane, then go to Project / AttachEventsInHostWeb Properties…
Go to the SharePoint tab and check the checkbox to enable debugging via Windows Service Bus and paste your connection string.
Now, let’s test our app so far. Press F5 in Visual Studio to start debugging.
Our breakpoint is then hit. Let’s inspect where the WCF message was sent to. In the Watch window in Visual Studio, add the value System.ServiceModel.OperationContext.Current.RequestContext.RequestMessage.Headers.To
You can see that SharePoint Online sent the message to:
This is the service bus endpoint used during debugging. This solves our earlier problem of SharePoint not being able to send messages to. The messages are relayed from Service Bus to our local endpoint.
Ask for Permission
The last bit of setup that we need to do is to ask for permission. We are going to add a remote event receiver to a list in the host web, which means we need to ask for permission to manage the list. We don’t need Full Control for this operation, we just need Manage. Further, we only need Manage permission for a list, not the whole web, site collection, or tenant.
The list we will work with is an Announcements list, which has a template ID of 104. Adding the BaseTemplateId=104 property in a list permission request significantly reduces the number and type of lists that a user chooses from when granting permission.
Notice the app-only permission request? That’s added when we handle the App Installed and App Uninstalling events, because when those happen we want to execute operations that the current user may not have permission to.
Show Me The Code!
Finally, we’re here. First, let’s define the name of the event handler and implement the required ProcessEvent method.
private const string ReceiverName = "ItemAddedEvent"; private const string ListName = "Announcements";Added: HandleItemAdded(properties); break; } return result; }
Those methods (HandleAppInstalled, HandleAppUninstalling, HandleItemAdded) are methods that we will define.
1: private void HandleAppInstalled: bool rerExists = false;
13:
14: foreach (var rer in myList.EventReceivers)
15: {
16: if (rer.ReceiverName == ReceiverName)
17: {
18: rerExists = true;
19: System.Diagnostics.Trace.WriteLine("Found existing ItemAdded receiver at "
20: + rer.ReceiverUrl);
21: }
22: }
23:
24: if (!rerExists)
25: {
26: EventReceiverDefinitionCreationInformation receiver =
27: new EventReceiverDefinitionCreationInformation();
28: receiver.EventType = EventReceiverType.ItemAdded;
29:
30: //Get WCF URL where this message was handled
31: OperationContext op = OperationContext.Current;
32: Message msg = op.RequestContext.RequestMessage;
33:
34: receiver.ReceiverUrl = msg.Headers.To.ToString();
35:
36: receiver.ReceiverName = ReceiverName;
37: receiver.Synchronization = EventReceiverSynchronization.Synchronous;
38: myList.EventReceivers.Add(receiver);
39:
40: clientContext.ExecuteQuery();
41:
42: System.Diagnostics.Trace.WriteLine("Added ItemAdded receiver at "
43: + msg.Headers.To.ToString());
44: }
45: }
46: }
47: }
Lines 8-10 just get the list and the event receivers for the list using the client side object model. The real work is in lines 24-38 where we obtain the WCF address of where the message was originally sent to and use that URL for our new event receiver. This is how we add a remote event receiver to a list in the host web.
We need to clean up after ourselves, otherwise we may continue to receive messages after someone has uninstalled the app.
1: private void HandleAppUninstalling: var rer = myList.EventReceivers.Where(
13: e => e.ReceiverName == ReceiverName).FirstOrDefault();
14:
15: try
16: {
17: System.Diagnostics.Trace.WriteLine("Removing ItemAdded receiver at "
18: + rer.ReceiverUrl);
19:
20: //This will fail when deploying via F5, but works
21: //when deployed to production
22: rer.DeleteObject();
23: clientContext.ExecuteQuery();
24:
25: }
26: catch (Exception oops)
27: {
28: System.Diagnostics.Trace.WriteLine(oops.Message);
29: }
30:
31: }
32: }
33: }
Now let’s handle the ItemAdded event.
1: private void HandleItemAdded(SPRemoteEventProperties properties)
2: {
3: using (ClientContext clientContext =
4: TokenHelper.CreateRemoteEventReceiverClientContext(properties))
5: {
6: if (clientContext != null)
7: {
8: try
9: {
10: List photos = clientContext.Web.Lists.GetById(
11: properties.ItemEventProperties.ListId);
12: ListItem item = photos.GetItemById(
13: properties.ItemEventProperties.ListItemId);
14: clientContext.Load(item);
15: clientContext.ExecuteQuery();
16:
17: item["Title"] += "\nUpdated by RER " +
18: System.DateTime.Now.ToLongTimeString();
19: item.Update();
20: clientContext.ExecuteQuery();
21: }
22: catch (Exception oops)
23: {
24: System.Diagnostics.Trace.WriteLine(oops.Message);
25: }
26: }
27:
28: }
29:
30: }
I need to point out line 4. TokenHelper has two different methods for creating a client context for an event. The first is CreateAppEventClientContext, which is used for app events such as AppInstalled or AppUninstalling. The second is CreateRemoteEventReceiverClientContext, which is used for all other events. This has tripped me up on more than one occasion, make sure to use the CreateRemoteEventReceiverClientContext method for handling item events.
That’s really all there is to it… we use the AppInstalled event to register an event on a list in the host web, use the same WCF service to handle the event. These operations require Manage permission on the object where the event is being added.
Testing it Out
We’ve gone through the steps of creating the app and adding the service bus connection string, let’s see the code work! Add breakpoints to each of your private methods in the WCF service and press F5 to see it work.
We are prompted to trust the app. Notice that only the announcements lists in the host web show in the drop-down.
Click Trust It. A short time later, the breakpoint in the HandleAppInstalled method fires. We continue debugging, and then O365 prompts us to log in.
Your app’s main entry point is then shown.
Without closing the browser (which would stop your debugging session), go back to your SharePoint site. Go to the Announcements list and add a new announcement.
W00t! Our breakpoint for the ItemAdded event is then hit!
If you want to inspect the properties of the remote event receiver that was attached, you can use Chris O’Brien’s scripts from his post, Add/delete and list Remote Event Receivers with PowerShell/CSOM:
Debugging and the Handle App Uninstalling Event
Recall that we will be using the App Installed event to register a remote event receiver on a list in the host web. We want to also remove the remote event receiver from the list. If we try to use the AppUninstalling event and unregister the event using DeleteObject(), it doesn’t work. You will consistently receive an error saying you don’t have permissions. This only happens when side-loading the app, which is what happens when you use F5 to deploy the solution with Visual Studio.
Unfortunately, that means that the receivers that are registered for the list hang around. The only way to get rid of them is to delete the list. Again, this only occurs when side-loading the apps, it doesn’t happen when the app is deployed.
To see the App Uninstalling event work, we are going to need to deploy our app.
Deploy to Azure and App Catalog
In my previous post, Creating a SharePoint 2013 App With Azure Web Sites, I showed how to create an Azure web site, go to AppRegNew.aspx to create a client ID, and a client secret. I then showed how to publish the app to an Azure web site, and package the app to generate the .app package. I did the same here, deploying the web application to an Azure web site called “rerdemo”.
Instead of copying the .app package to a Developer Site Collection, we are instead going to copy the .app package to our App Catalog for our tenant. Just go to the Apps for SharePoint library and upload the .app package.
Now go to a SharePoint site that you want to deploy the app to. Make sure to create an Announcements list. Our app could have done this in the App Installed event, but c’mon, this post is long enough as it is. I’ll leave that as an exercise to the reader.
Before we add the app to the site, let’s see something incredibly cool. Go to the Azure web site in Visual Studio, right-click and choose Settings, and turn up logging for everything.
Click save.
Right-click the Azure web site and choose View Streaming Logs in Output Window. You’ll be greeted with a friendly message.
Now go back to your SharePoint site and choose add an app. You should now see your app as one of the apps that can be installed.
Click Trust It.
Your app will show that it is installing.
Go back to Visual Studio and look at the streaming output logs.
OMG. I don’t know about you, but I nearly wet myself when I saw that. That is so unbelievably cool. Let’s keep playing to see what other messages show up. Go to the Announcements list and add an item.
Shortly after clicking OK, you’ll see the Title has changed.
Finally, uninstall the app to test our HandleAppUninstalling method.
We see a new message that the remote event receiver is being removed.
And we can again use Chris O’Brien’s PowerShell script to check if there are any remote event receivers still attached to the Announcements list.
Now, go back to Visual Studio. Right-click on the Azure web site and choose Settings. Go to the Logs tab and choose Download Logs.
A file is now in my Downloads folder.
I can double-click on the zip file to navigate into it. Go to LogFiles / http / RawLogs and see the log file that is sitting there. Double-click it. You can see the IIS logs for your site!
For More Information
Developer training for Office, SharePoint, Project, Visio, and Access Services
Defining content in Host Web from an App for SharePoint
Add/delete and list Remote Event Receivers with PowerShell/CSOM
Streaming Diagnostics Trace Logging from the Azure Command Line (plus Glimpse!)
Creating a SharePoint 2013 App With Azure Web Sites
Hi Kirk,
I'm quite new to all of this SharePoint development, but this is great. I've followed the process and have it working fine.
The only problem is that when an item is added to my Custom List I want to add the functionality to start a workflow already associated with the list.
Lots of other examples on the web utilize Client.WorkflowServices however this doesnt seem to be available in my project.
Have you any idea how that can be incorporated into your example above?
Best regards
Hi Kirk,
I'm struggling with similar scenario.
I have a local machine with local installation of SharePoint 2013. I create a SharePoint hosted app. Within that I created a Remote Event Handler which further created another web project. I also added the App Install event into the same web project.
Now I hosted (Published Web Project) Remote Event Handler and App Install Handler in local IIS with Anonymous login. Also I generated .app file and uploaded to app catalog.
Now when I try to install my app, I attach my code to the w3p process and it breaks into my App Event Handler however TokenHelper.CreateAppEventClientContext(properties, false) is returning null. I further debugged to find that ContextTokenString is empty…I'm not sure however I feel this is happening due to anonymous login?
Any help really appreciated..
Thanks
Manu
Manu – most often I've seen this issue when the app endpoint is incorrectly using HTTP instead of HTTPS. SSL is required.
Hi Kirk,
I've essentially followed your example to create remote event receivers. I'm able to debug them fine. The new event receivers also fire fine…..only during the first debug session that they are attached to the list in. On subsequent debugs, the list event receivers have already been added, but they don't fire. The App Installed event receivers still fire fine. Its just that the list receivers do not.
Do you have any idea as to why this may happen?
Cheers,
Sam
Hi Kirk,
I am having the same issue as Sam above me is having. It seems that the event receiver only fires for the first debug session after being attached to the list in the host web. Any input on why this might be happening would be appreciated.
Thanks,
Jordan
Jordan and Sam – I believe it has to do with the way that Visual Studio installs the app when you press F5. Try installing the app using an app catalog instead and verify that it works. If you are working with an on-premises farm, then you can check the ULS logs to see if there is any indication of what might have failed.
Hi Kirk & Jordan,
I can confirm that this is the case. Frustrating, but i'm glad now that we've uncovered the reason. I guess the cause is the next thing to find out, hopefully it can be fed back to the VS team.
So essentially, i packaged the app, installed to the app catalog, installed the app on the relevant site, and the event receivers registered nicely and have fired every time they were supposed to.
Thanks Kirk!
Guys,
I have the breakpoint in my AppInstall event firing, but all other events (itemadded / itemupdated) on a list are not fired :-(.
I verified that the remote event receiver is attached on the list with the "azure service bus service url". (dont know how else to call it). The url is siteprovisioningdev.servicebus.windows.net/…/SiteProvisioningService.svc
If I browse to the url I get the following text, so I'm assuming it's ok.
<feed xmlns="…/Atom"><subtitle type="text">This is the list of publicly-listed services currently available.</subtitle><id>uuid:41725493-b0cb-4272-9f4e-c385a285e844;id=46931</id><updated>2014-06-25T09:47:25Z</updated><generator>Service Bus 1.1</generator></feed>
Any ideas why my breakpoints don't get hit when I (for example) update an item?
What is point of returning SPRemoteEventResult result = new SPRemoteEventResult(); if there is no change in the object?
First of all, thanks for this wonderful post!! You have been a great help through out my short journey through Azure and SharePoint online 🙂
I followed the same steps you mentioned here and got the Remote event receiver working. it's adding the RER to the list when App is getting installed. its firing on item added. But I couldn't get the appuninstalling event to work. It's not firing when I tried from apps in testing and also after adding it ti the apps for SharePoint in the app store. It's not firing the process even when I tested using tracing.
Here is my part of my appmanifest-
<Properties>
<StartPage>~remoteAppUrl/?{StandardTokens}</StartPage>
<UninstallingEventEndpoint>~remoteAppUrl/Services/AppEventReceiver.svc</UninstallingEventEndpoint>
<InstalledEventEndpoint>~remoteAppUrl/Services/AppEventReceiver.svc</InstalledEventEndpoint>
</Properties>
It would be a great help if you can recollect any issues you faced while creating this. I tried installing the app in my test office 365 dev site and enterprise site too.. But no luck!!
@Libin – see the section of the post titled "Debugging and the Handle App Uninstalling Event", it doesn't work for side-loaded apps, but works when deployed using an app catalog.
Thanks. But I deployed using app catalog and uninstalled the app and didn't work. I put below line
System.Diagnostics.Trace.WriteLine("Entering ProcessEvent" + Convert.ToString(properties.EventType
));
in the ProcessEvent method and it didn't execute when I uninstalled the app from the site (I checked using view streaming logs which you explained). But it executed when I installed the app (using add an app from browser) for the first time and also when I added items to the announcements list.
Altogether, for me ProcessEvent is not firing when I uninstall the app from the site.
Hi Evans,
The above article really helped me a lot for host web. Currently i am facing an issue where i am unable to fetch the current item values while deleting it.
like: properties.ItemEventProperties.BeforeProperties["Title"].ToString();
is not able to get the values before deleting the item in a custom list.
Is there any way we can achieve it.
Thanks
Prashant
Great post – very helpful for what I was trying to accomplish. I did notice (at least in my tenant) if you are using the developer template and running this in debug mode, I was able to get the uninstall to work successfully by leaving the debugging session open, clicking the "…" on the appropriate item in the "Apps in Testing" web part and clicking "Remove" from that menu. It fired the "AppUninstalling" event and successfully removed the event receiver. I was able to verify by looking at the event receivers for the list in SharePoint 2013 Client Browser.
Hi Evans,
Is there hard and fast rule for deploying and packaging the RER's in host web on sharepoint premises. As we are struggling to move the RER app to different environment. In dev the RER works fine as we debug the solution and things goes fine.
Can you please help me on this.
Prashant
Hi Evans,
I am not able to deploy the RER as an .app file to the App catalog . It keeps on installing but never installs
Can you help me on this.
Thanks
Hi Kirk,
I'm experiencing exactly same issue as Libin – AppUninstalling event is not firing. I've published my site as an Azure Website, installed the app using App Catalog and tested the event in a production environment on different tenants (not debugging). Would could be a root cause of this? the App, Website or Visual Studio? I'm using VS 2013, Update 3.
Thanks in advance!
I too cannot get the UninstallingEventEndpoint to work when publishing the app to the app catalog.
Attaching Remote Event Receiver(s)
Assuming many will want to be able to have more than one RER per SharePoint App.
I have a Solution with an RER project working with 2 Remote Event Receivers.
I am handing this by moving the methods for the "Handling" events to separate .cs files.
One for each RER.
Question: Is this an acceptable pattern?
I have a college who is concerned, as this pattern handles the ItemUpdated event in the Service, that means "all the attached RERs fire"…
Should I move handling of the ItemUpdated event into the .cs file for each RER?
See Example:
Service Endpoint for APP (AppInstalled, AppUnintalling)
AppEventReceiver.svcUpdated:
HandleItemUpdated(properties);
break;
}
return result;
}
…
AppInstalled Event
private void HandleAppInstalled(SPRemoteEventProperties properties)
{
using (ClientContext clientContext =
TokenHelper.CreateAppEventClientContext(properties, false))
{
if (clientContext != null)
{
new SalesRemoteEventReceiverManager().AssociateRemoteEventsToHostWeb(clientContext);
new ChangeRemoteEventReceiverManager().AssociateRemoteEventsToHostWeb(clientContext);
}
}
}
…
ItemUpdated Event
private void HandleItemUpdated(SPRemoteEventProperties properties)
{
using (ClientContext clientContext =
TokenHelper.CreateRemoteEventReceiverClientContext(properties))
{
if (clientContext != null)
{
if (properties.ItemEventProperties.ListTitle == "Sales Pipeline")
{
new SalesRemoteEventReceiverManager().ItemUpdatedListEventHandler(clientContext, properties.ItemEventProperties.ListId, properties.ItemEventProperties.ListItemId);
}
if (properties.ItemEventProperties.ListTitle == "Project Change Request")
{
new ChangeRemoteEventReceiverManager().ItemUpdatedListEventHandler(clientContext, properties.ItemEventProperties.ListId, properties.ItemEventProperties.ListItemId);
}
}
}
} Kirk,
I tried your above example and it works fine. I would now like to copy the item updated in the annoucements list by the event receiver to an announcements list on another site collection.
Here is a piece of your code with my code added:
using (ClientContext clientContext =
TokenHelper.CreateRemoteEventReceiverClientContext(properties))
{
if (clientContext != null)
{
using (ClientContext otherContext = new ClientContext(""))
{
List otherList = otherContext.Site.RootWeb.Lists.GetByTitle("Announcements");
otherContext.Load(otherList);
otherContext.ExecuteQuery();–>I get a 403 Forbidden error
…
I added the app trust in the other site collection (manage site collection permissions) but doesn't work.
Any tips?
Best regards
@Kristoff – try requesting Tenant/Write permission (because you are crossing site collections and need permission to Read from one and Write to the other). This level of permission is not allowed in the Store, in case you wanted to sell this solution.
Hi Kirk,
Thanks for pointing that out! I'll look into it.
Best regards
I have struggled to get events to fire for both RemoteEventReceiver and AppEventReceiver until i stumbled on your blog. Thanks for sharing. Microsoft support told me i have to close the browser to get the app install and then debug . this was very disturbing to me and i told them until they can find me a good explnation why i have to close the browser to debug am leaving the ticket open.
Anyways, i was able to your your steps and it going if i deploy my app and install it on office 365. Side-loding debug hasn't work for me. Secondly, i noticed that AppUninstall was not firing when i looked at the console log.
Once again thanks.
I'm wondering if there are other ways to "hook" the event receivers other than AppInstall.
I'm trying to do this after I provision a newly created site. When I combine the Provisioning app with this receiver app, the "hook" gets applied to the parent site and not the newly provisioned site.
Thanks!
Ken
Hi Kirks,
Thanks a lot for explaining on how to attach to a list in Hostweb. This blog has really helped me a lot!!
Hi Evans – I ran above sample code and Itemadded event is not getting fired. I added a Itemadding event and it worked but not the Itemadded event. I guess reason for it , in above code it is treated as Synchronous event. I am able to recall that earlier also i tried using itemadded as synchronous and it didnt worked for me.
Can you please guess what can be the reason behind the same?
Thanks,
Vipin
When I write blog posts I try to give you the information to understand how things work and to troubleshoot them yourself. While I try to answer follow-up questions when I can, there are many situations (like this one) where I provided all the information that I know and unfortunately cannot provide any more insight. Please post questions to StackOverflow.com (stackoverflow.com/…/sharepoint) for additional help from the community.
Great article, thanks!
But how do I register an event receiver for all lists in the host web of type document library, for example?
I have added an event receiver for a given list, that works fine. An event receiver with listTemplateType=101 in the SharePoint app project does not work. Does this event receiver only run for lists in the app web? Can I switch this behaviour to the host web?
Regards,
Thorsten | https://blogs.msdn.microsoft.com/kaevans/2014/02/26/attaching-remote-event-receivers-to-lists-in-the-host-web/ | CC-MAIN-2017-47 | refinedweb | 4,710 | 66.13 |
Examples of programs benefiting from linear types fall into three categories.
Enforcement of protocolEnforcement of protocol
Linear types can be used to encode protocols, in a way very similar to 'session types'. Linearity checks ensure that the protocol is respected (so one does not backtrack or drops out).
type a ⊗ b = ... {- see proposal -} type a ⊸ b = ... {- see proposal -} type Effect = IO () -- for example pr :: Double -> Effect -- "prints" a number type N a = a ⊸ Effect data Client = Mul Double Double (N (Double ⊗ Server)) -- Client sends two 'Double' and -- expects a double and a new server -- session. | Terminate type Server = N Client exampleClient :: N (N Client) exampleClient server = server $ Mul 12 34 $ \(product,server') -> -- do something with the product pr product >> server' Terminate exampleServer :: Server exampleServer client = case client of Mul x y k -> k (x*y,exampleServer) Terminate -> return ()
Correctness of optimized codeCorrectness of optimized code
Writing programs in the polarized style shown above is very useful to write efficient programs.
In general, fusion in GHC relies on the rewrite rules and the inliner.
- Rewrite rules transform code using general recursion into a representation with no recursion (eg. church encodings)
- The inliner kicks in and 'fuses' composition of non-recursive functions
- Unfused code may be reverted to the original representation.
The problem with this scheme is that it involves two phases of heuristics (rules and inliner), and in practice programmers have difficulties to predict the performance of any given program.
A partial remedy to this solution is to stop relying on rewrite rules, and use directly non-recursive representations. For example the following representation from Lippmeier et al.:
data Sources i m e = Sources -- 'i' is the array's index type, 'e' the type of elements and 'm' the effects { arity :: i , pull :: i -> (e -> m ()) -> m () -> m () } -- 'pull' is an iterator to apply to every elements of the array (like 'traverse') data Sinks i m e = Sinks { arity :: i , push :: i -> e -> m () , eject :: i -> m () }
Such representations are typically functionals, and thus do not consume memory. One eventually gets code which is guaranteed to be 'fused'. For instance, in the following example from Lippmeier et al., neither the source nor the sink represent data in memory.
copySetP :: [FilePath] -> [FilePath] -> IO () copySetP srcs dsts = do ss <- sourceFs srcs sk <- sinkFs dsts drainP ss sk
One then faces two classes of new problems.
First, any non-linear (precisely non-affine) use of such a representation will duplicate work. For example:
example srcs dsts = do ss <- expensiveComputation <$> sourceFs srcs sk <- sinkFs dsts drainP ss sk drainP ss sk -- expensiveComputation is run a second time here.
If one is not careful, one may end up with a program which does not use any intermediate memory, but duplicates a lot of intermediate computations. Linear types solve the problem by preventing such duplications. (Combinators may be still provided to duplicate computation explicitly or store intermediate results explicitly.)
Second, such representations may contain effects. In this situation, non-linear uses may produce an incorrect program. If one takes the example of a non-recursive representation of files, one may have two processes writing simultaneously in the same file (potentially corrupting data), or one may forget to close the file.
Quoting Lippmeier et al.:
In general an object of type Sources is an abstract producer of data, and it may not even be possible to rewind it to a previous state — suppose it was connected to a stream of sensor readings. Alas the Haskell type system does not check linearity so we rely on the programmer to enforce it manually.
Literature on this style of non-recursive representations includes additionally:
- Push and Pull arrays in Feldspar
- On the duality of streams
- Composable Efficient Array Computations using Linear Types
Diminishing GC pressureDiminishing GC pressure
Because linear values cannot be shared, they should in principle not be subject to GC. Indeed, the consumer of the value (pattern matching) may very well perform de-allocation of the spot. Thus linear values can be stored in a heap outside of GC control. Alone, this strategy will diminish GC usage, but may increase the total running time of the program (if only because allocation in the GC heap is so efficient that it beats manual memory management for short-lived object) [Wakeling and Runciman have experienced this effect]. Yet, the tradeoff may be worth the trouble if long-tail in latencies is a bigger problem than absolute runtime.
There is however an improvement to be had on top of the simple strategy. Namely, to always fuse composition of linear functions. This strategy removes many short-lived objects. Fusing always is safe performance wise thanks to linearity. It is a good idea because it allows the programmer to predict accurately the behavior of the generated code.
A consequence of this choice is that linear data will only exist when pointed to by non-linear data structures.
Controlling sharing (full laziness)Controlling sharing (full laziness)
According to de Vries ():
[...] memory leak, in practice the resulting code is too brittle and writing code like this is just too difficult.
[...]
Full laziness can be disabled using
-fno-full-laziness, but sadly this throws out the baby with the bathwater. In many cases, full laziness is a useful optimization.
Linearity offers a solution to the problem. Indeed, linearly-typed values are used once only. Thus, linearity implies that no sharing is intended by the programmer. In turn, the full laziness optimization cannot apply to expressions in a linear context.
Consider now a simple example which exhibits the problem, also provided by de Vries:
ni_mapM_ :: (a -> IO b) -> [a] -> IO () {-# NOINLINE ni_mapM_ #-} ni_mapM_ = mapM_ main2 :: IO () main2 = forM_ [1..5] $ \_ -> ni_mapM_ print [1 .. N]
One would expect that the above programs uses constant space (because
the list
[1..N] is produced lazily). However, if one compiles the
above program with full laziness and runs it, one observes a memory
residency proportional to N. This happens because GHC shares the
intermediate list
[1..N] between runs of
ni_mapM_ print [1 .. N].
Let us now consider an equivalent program, be written using our proposed extension for linear types. (To transpose the example with minimal changes we have to redefine several basic types and functions --- in a practical application this would not happen because we would actually be using a custom streaming library, as de Vries does).
data [a] where [] :: [a] (:) :: a ⊸ [a] ⊸ [a] discard :: Int ⊸ IO () ni_mapM_ :: (a ⊸ IO b) → List a ⊸ IO () forM_ :: List a ⊸ (a ⊸ IO ()) → IO () main2 ::1 IO () main2 = forM_ [1..5] $ \i -> do discard i ni_mapM_ print [1 .. N]
In the above example, it is incorrect to share the intermediate list. Indeed, performing full laziness would amount to transform the program into the following form, which is not well-typed:
main2 ::1 IO () main2 = let xs ::1 [a] xs = [1 .. N] in forM_ [1..5] $ \i -> do discard i ni_mapM_ print xs
Indeed, the above definition attempts to use
xs several times, while
it is bound only once.
In our proposed extension, one could still write the following type-correct program, which introduces explicit sharing:
main2 ::1 IO () main2 = let xs ::ω [a] xs = [1 .. N] in forM_ [1..5] $ \i -> do discard i ni_mapM_ print xs
Yet, thanks to linearity annotations, the programmer intentionally marked the expressions which are not supposed to be shared, in effect precisely controlling where (not) to apply full-laziness. Moreover, the user of a library written for streams would never have to worry about inadvertent sharing, because the types of the library functions would specify exactly the right behavior. See for how such a library may look like. | https://gitlab.haskell.org/ghc/ghc/wikis/linear-types/examples | CC-MAIN-2019-30 | refinedweb | 1,270 | 52.9 |
import the following:
import play.api.libs.ws._(...) .withTimeout(...) .withQueryString(...)
You end by calling a method corresponding to the HTTP method you want to use. This ends the chain, and uses all the options defined on the built request in the
WSRequestHolder.
val futureResponse : Future[Response] = complexHolder.get()
This returns a
Future[Response] where the Response contains the data returned from the server.
§Request with authentication
If you need to use HTTP authentication, you can specify it in the builder, using a username, password, and an AuthScheme. Options for the AuthScheme are
BASIC,
DIGEST,
KERBEROS,
NONE,
NTLM, and
SPNEGO.
import com.ning.http.client.Realm.AuthScheme WS.url(url).withAuth(user, password, Auth" -> "text-xml").post(xmlString)
§Request with virtual host
A virtual host can be specified as a string.
WS.url(url).withVirtualHost("192.168.1.1").get()
§Request with time out
If you need to give a server more time to process, you can use
withTimeout to set a value in milliseconds. You may want to use this for extremely large files.
WS.url(url).withTimeout(1000)[Response] =[Response] = WS.url(url).post(data)
§Processing the Response
Working with the Response is easily done by mapping inside the Future.
The examples given below have some common dependencies that will be shown once here for brevity.
An execution context, required for Future.map:
implicit val context = scala.concurrent.ExecutionContext.Implicits.global
and a case class that will be used._ import play.api.libs.functional.syntax._ implicit val personReads: Reads[Person] = ( (__ \ "name").read[String] and (__ \ "age").read[Int] ).
import play.api.libs.iteratee._ def fromStream(stream: OutputStream): Iteratee[Array[Byte], Unit] = Cont { case [email protected] => stream.close() Done((), e) case Input.El(data) => stream.write(data) fromStream(stream) case Input.Empty => fromStream(stream) } val outputStream: OutputStream = new BufferedOutputStream(new FileOutputStream(file)) val futureResponse: Future[Unit] = WS.url(url).withTimeout(3000).get { headers => fromStream(outputStream) }.flatMap(_.run)
This is an iteratee that will receive a portion of the file as an array of bytes, write those bytes to an OutputStream, and close the stream when it receives the
EOF signal. Until it receives an
EOF signal, the iteratee will keep running.
WS doesn’t send
EOF to the iteratee when it’s finished – instead, it redeems the returned future.
In fact,
WS has no right to feed
EOF, since it doesn’t control the input. You may want to feed the result of multiple WS calls into that iteratee (maybe you’re building a tar file on the fly), and if
WS feeds
EOF, the stream will close unexpectedly. Sending
EOF to the stream is the caller’s responsibility.
We do this by calling Iteratee.run which will push an
EOF into the iteratee when the future is redeemed.
PUT calls use a slightly different API than
GET calls: instead of
post(), you call
WS.url(url).postAndRetrieveStream(body) { headers => Iteratee.foreach { bytes => logger.info("Received bytes: " + bytes.length) } }
§Common Patterns and Use Cases
§Chaining WS calls
Using for comprehensions is a good way to chain WS calls in a trusted environment. You should use for comprehensions together with Future.recover to handle possible failure.
val futureResponse: Future[Response] =
You can compose several promises and end with a
Future[Result] that can be handled directly by the Play server, using the
Action.async builder defined in Handling Asynchronous Results.
def feedTitle(feedUrl: String) = Action.async { WS.url(feedUrl).get().map { response => Ok("Feed title: " + (response.json \ "title").as[String]) } }
§Advanced Usage
You can also get access to the underlying async client.
import com.ning.http.client.AsyncHttpClient val client:AsyncHttpClient = WS.client
This is important in a couple of cases. WS has a couple of limitations that require access to the client:
WSdoes not support multi part form upload directly. You can use the underlying client with RequestBuilder.addBodyPart.
WSdoes not support client certificates (aka mutual TLS / MTLS / client authentication). You should set the
SSLContextdirectly in an instance of AsyncHttpClientConfig and set up the appropriate KeyStore and TrustStore.
§Configuring WS false to use the default SSLContext
§Timeouts
There are 3 different timeouts in WS. Reaching a timeout causes the WS request to interrupt.
- Connection Timeout: The maximum time to wait when connecting to the remote host (default is 120 seconds).
- Connection Idle Timeout: The maximum time the request can stay idle (connexion is established but waiting for more data) (default is 120 seconds).
- Request Timeout: The total time you accept a request to take (it will be interrupted, whatever if the remote host is still sending data) (default is none, to allow stream consuming).
You can define each timeout in
application.conf with respectively:
ws.timeout.connection,
ws.timeout.idle,
ws.timeout.request.
Alternatively,
ws.timeout can be defined to target both Connection Timeout and Connection Idle Timeout.
The request timeout can be specified for a given connection with
withRequestTimeout.
Example:
WS.url("").withRequestTimeout(10000 /* in milliseconds */)
Next: OpenID Support in Play
Found an error in this documentation? The source code for this page can be found here. After reading the documentation guidelines, please feel free to contribute a pull request. | https://www.playframework.com/documentation/2.2.x/ScalaWS | CC-MAIN-2018-22 | refinedweb | 857 | 51.24 |
Jest — How To Mock a Function Call Inside a Module
Mocking function calls within a module
Let’s say you have the file:
// f.jsexport function b(){
return 'b';
}export function a(){
return b();
}
If you want to mock
b to test a, well… It is not as easy as it seems to be.
The Naive Approach.
Solution 1 — Splitting The Module Into Different Files
If you move
b to its own file:
// b.jsexport function b(){
return 'b';
}// f.jsimport {b} from './b';export function a(){
return b();
}
Then the test will pass:
test('a', () => {
const b = require('./b');
const f = require('./f'); jest.spyOn(b, 'b').mockReturnValue('c'); expect(f.a()).toBe('c');
//PASSED!
})
This looks like the cleanest solution, but what if you want to keep your functions in the same file?
Solution 2 — Calling The Mocked Function Using Exports
Add
exports. before calling the function
// f.jsexport function b(){
return 'b';
}export function a(){
return exports.b();
}
And then the test will just pass:
test('a', () => {
const f = require('./f'); jest.spyOn(f, 'b').mockReturnValue('c'); expect(f.a()).toBe('c');
//PASSED!
})
I really like this solution because you change only something insignificant in the tested file. Moreover, even this small change can be avoided:
You can use the library
babel-plugin-explicit-exports-references to add
exports. to all functions within the same module programmatically.
Notice that the library is very fresh and has a very small audience.
Use it with caution in terms of security.
A Sub-Optimal Solution Worth Mentioning — Exporting a Namespace Object
You can create a namespace that you export as the default object and call
b using the namespace.
This way, when you call
jest.mock it will replace the
b function on the namespace object.
// f.jsconst f = {
b(){
return 'b';
}, a(){
return f.b();
}
};export default f;
And then the test will pass:
test('a', () => {
const f = require('./f'); jest.spyOn(f, 'b').mockReturnValue('c'); expect(f.a()).toBe('c');
//PASSED!
})
But then you will need to import it as a
default import without being able to break it into named exports.
// won't work:
// import {a} from './f';import f from './f';...f.a();
Which is kinda ugly.
Another Sub-Optimal Solution— Using a Re-Wire Library
The library babel-plugin-rewire is an intrusive library that changes what’s inside modules.
It doesn’t seem to be a very maintained library and it actually didn’t work for me because it doesn’t support TypeScript, but here is roughly how it is supposed to work —
You don’t need to change anything on the file that you are testing.
// f.jsexport function b(){
return 'b';
}export function a(){
return b();
}
Rewire the
b function in the test:
import {a, __set__} from './f';test('a', () => {
const f = require('./f'); // This rewires b to return 'c'
__set__('b', () => 'c'); expect(f.a()).toBe('c');
// PASSED!})
Happy Testing :) | https://medium.com/welldone-software/jest-how-to-mock-a-function-call-inside-a-module-21c05c57a39f | CC-MAIN-2022-27 | refinedweb | 489 | 66.54 |
In ye olde barbaric days, one thing was handy: templates and python
scripts reloaded just fine in debug mode and a
refresh.txt in your
product went a long way to not having to restart your zope too often.
Zcml only loads on startup, so a change there means a zope restart, probably nothing to be done about that. But I seem to be restarting zope for just about every single little python change.
So I asked around on the mailinglist last month: on the current strategies for preventing too many zope restarts during development? I was bound to miss a few tips and tricks otherwise :-) So here's a summary.
=instead of
==, head-slapping stuff like that. Catch it before restarting zope :-)
Martin Aspeli provided the full list of rules on what requires a restart:
Those plone mailing lists sure are):
/@@code_reload didn't work for me for a portlet renderer, but moving the renderer class definition to a separate file and importing the renderer in the file referenced by the zcml worked.
I guess it has to do with ZCA registration.
But in most cases it works well (and saves time).
bin/zeo_client_2 debug < mytest.py
where mytest.py might be:
from mysite.theme.setuphandlers import SiteSetup
cp = SiteSetup()
cp.MyMethodToTest(app.plonesite)
... then maybe evolve it into a more formal unit or doc test later ...
Luckily I like to do it :-)
I've recently made the decision to increase the frequency with which I blog (and not only on plone, so not all of it will show up on planet.plone.org). Your positive feedback helps a lot in strengthening that resolve.
It also means that I'm also inviting negative (or "improvement-oriented") feedback in order to improve myself. I really really want to learn.
mailing lists are really helpful, and all the plone people is kicking ass, but you rule, and i propose you as one of the best plone reporter out there!
hope you'll have a great 2008 and to meet you soon!
Maurizio | http://reinout.vanrees.org/weblog/2008/01/15/restarting-zope-for-plone-development.html | CC-MAIN-2015-40 | refinedweb | 341 | 72.76 |
Accurately render even the largest data
New to Datashader? Check out this quick video introduction to what it does and how it works! ordinary Python but transparently compiled to machine code using Numba and flexibly distributed across CPU cores and processors using Dask or GPUs using CUDA. This approach provides a highly optimized rendering pipeline that makes it practical to work with extremely large datasets even on standard hardware, while exploiting distributed and GPU systems when available.
For concreteness, here’s an example of what Datashader code looks like:
import datashader as ds, pandas as pd, colorcet df = pd.read_csv('census.csv') cvs = ds.Canvas(plot_width=850, plot_height=500) agg = cvs.points(df, 'longitude', 'latitude') img = ds.tf.shade(agg, cmap=colorcet.fire, how='log')
This code reads a data file into a Pandas dataframe
df, and then projects the fields
longitude and
latitude onto the x and y dimensions of an 850x500 grid, aggregating it by count. The results are rendered into an image where the minimum count will be plotted in black, the maximum in white, and with brighter colors ranging logarithmically in between.
With code just like the above, you can plot 300 million points of data (one per person in the USA) from the 2010 census without any parameter tuning:
Or you can plot attractors with 10 million points each, using random colormaps:
See the topics page for these and many other examples.
Installation#
Please follow the instructions on Getting Started if you want to reproduce the specific examples on this website, or follow the instructions at HoloViz.org if you want to try out Datashader together with related plotting tools.
Other resources#
You can see Datashader in action in the 2019 HoloViz SciPy tutorial (3 hours!), listen to the Open Source Directions episode from July 2019, or see how it is used in many of the projects at examples.pyviz.org.
Some of the original ideas for Datashader were developed under the name Abstract Rendering, which is described in a 2014 SPIE VDA paper.
The source code for datashader is maintained on Github, and is documented using the API link on this page.
We recommend the Getting Started Guide to learn the basic concepts and start using Datashader as quickly as possible.
The User Guide covers specific topics in more detail.
The API is the definitive guide to each part of
Datashader, but the same information is available more conveniently via
the
help() command as needed when using each component.
Please feel free to report issues or contribute code. You are also welcome to chat with the developers on gitter, but please use the official channels for reporting issues or making feature requests so that they are captured appropriately. | https://datashader.org/ | CC-MAIN-2022-40 | refinedweb | 454 | 59.84 |
Saylor.org's C++ Programming text will also cover the topics of namespaces, exception handling, and preprocessor directives. In the last part of the text, we will learn some slightly more sophisticated programming techniques that deal with data structures such as linked lists and binary trees.
Global Learning Outcomes
Upon successful completion of this course, students will be able to:
- Compile and execute code written in C++ language.
- Work with the elementary data types and conditional and iteration structures.
- Define and use functions, pointers, arrays, struct, unions, and enumerations.
- Write C++ using principles of object-oriented programming.
- Write templates and manipulate the files.
- Code and use namespaces, exceptions, and preprocessor instructions.
- Write a code that represents linked lists and binary trees.
- Translate simple word problems into C++ language.
Contents
Introduction and Set Up[edit]
Upon successful completion of this unit, students will be able to:
- Describe the basic history of C++.
- Set up a NetBeans IDE for a simple C++ project.
- Create and compile a simple C++ program.
- Use cout and cin objects effectively.
- Declare and use variables.
- Use conditional and iteration structures in C++.
- Define and use simple functions.
- 1.1 History of C++: Origins and Examples
- 1.2 How to Compile and Run a C++ Program
- 1.2.1 Linux Way
- 1.2.2 Other Ways with NetBeans
- 1.3 Basics of C++
- 1.3.1 Structure of a Program
- 1.3.2 Variables, Data Types, and Constants
- 1.3.3 Basic Input and Output
- 1.3.4 Control Structures
- 1.3.5 Simple Functions
- 1.4 C++ Reference
- 1.5 C++ Coding Practice
Dealing with Data and Compound Types[edit]
Upon successful completion of this unit, students will be able to:
- List the operators in C++ language.
- Define and use arrays, struct, unions, and enumerations.
- Use pointers.
- Use the functions of string class.
- 2.1 Arithmetic Operators
- 2.2 Basic Data Structures
- 2.2.1 Arrays and Strings
- 2.2.2 Pointers
- 2.2.3 Struct, Unions, and Enumerations
- 2.3 C++ Coding Practice: String Class
Object-Oriented Programming[edit]
Upon successful completion of this unit, students will be able to:
- Define and compare/contrast constructors and deconstructors.
- Design pointers to the class and create overloading operators.
- Define and use the keyword “this” and use the static members appropriately.
- Design and appropriately use friend functions and classes.
- Use the class inheritance for better code design.
- Explain how polymorphism is achieved through C++ code.
- 3.1 Class Design
- 3.1.1 Constructors and Destructors
- 3.1.2 Overloading Constructors and Pointers to Classes
- 3.1.3 Overloading Operators
- 3.1.4 The Keyword “This”
- 3.1.5 Static Members
- 3.2 Inheritance Between Classes
- 3.2.1 Friend Functions
- 3.2.2 Friend Classes
- 3.2.3 Inheritance Between Classes
- 3.2.4 Multiple Inheritance
- 3.3 Polymorphism
- 3.3.1 Pointers to Base Class
- 3.3.2 Virtual Members
- 3.3.3 Abstract Base Classes
- 3.4 Coding Drills
Advanced Concepts[edit]
Upon successful completion of this unit, students will be able to:
- Write class and function templates.
- Code with a class that manipulates the files.
- Use namespaces and exceptions in C++ code.
- Write preprocessor instructions.
- 4.1 Templates
- 4.1.1 Function Templates
- 4.1.2 Class Templates
- 4.1.3 Template Specialization
- 4.1.4 Non-type Parameters for Templates
- 4.1.5 Templates and Multiple-file Projects
- 4.2 Input/Output With Files
- 4.2.1 Open and Close a File
- 4.2.2 Text Files
- 4.2.3 Binary Files
- 4.3 Namespaces
- 4.4 Exceptions
- 4.5 Preprocessor Directives
Useful Examples[edit]
Upon successful completion of this unit, students will be able to:
- Describe and code the binary tree structure.
- Code special data structures by combining linked lists and binary trees. | https://en.wikibooks.org/wiki/Saylor.org's_C%2B%2B_Programming | CC-MAIN-2015-14 | refinedweb | 629 | 55.71 |
import "github.com/dgraph-io/badger"
Package badger implements an embeddable, simple and fast key-value database, written in pure Go. It is designed to be highly performant for both reads and writes simultaneously. Badger uses Multi-Version Concurrency Control (MVCC), and supports transactions. It runs transactions concurrently, with serializable snapshot isolation guarantees.
Badger uses an LSM tree along with a value log to separate keys from values, hence reducing both write amplification and the size of the LSM tree. This allows LSM tree to be served entirely from RAM, while the values are served from SSD.
Badger has the following main types: DB, Txn, Item and Iterator. DB contains keys that are associated with values. It must be opened with the appropriate options before it can be accessed.
All operations happen inside a Txn. Txn represents a transaction, which can be read-only or read-write. Read-only transactions can read values for a given key (which are returned inside an Item), or iterate over a set of key-value pairs using an Iterator (which are returned as Item type values as well). Read-write transactions can also update and delete keys from the DB.
See the examples for more usage details.
backup.go batch.go compaction.go db.go dir_unix.go doc.go errors.go histogram.go iterator.go key_registry.go level_handler.go levels.go logger.go managed_db.go manifest.go merge.go options.go publisher.go stream.go stream_writer.go structs.go txn.go util.go value.go
const ( // KeyRegistryFileName is the file name for the key registry file. KeyRegistryFileName = "KEYREGISTRY" // KeyRegistryRewriteFileName is the file name for the rewrite key registry file. KeyRegistryRewriteFileName = "REWRITE-KEYREGISTRY" )
const ( // ValueThresholdLimit is the maximum permissible value of opt.ValueThreshold. ValueThresholdLimit = math.MaxUint16 - 16 + 1 )
var ( // ErrValueLogSize is returned when opt.ValueLogFileSize option is not within the valid // range. ErrValueLogSize = errors.New("Invalid ValueLogFileSize, must be between 1MB and 2GB") // ErrKeyNotFound is returned when key isn't found on a txn.Get. ErrKeyNotFound = errors.New("Key not found") // ErrTxnTooBig is returned if too many writes are fit into a single transaction. ErrTxnTooBig = errors.New("Txn is too big to fit into one request") // ErrConflict is returned when a transaction conflicts with another transaction. This can // happen if the read rows had been updated concurrently by another transaction. ErrConflict = errors.New("Transaction Conflict. Please retry") // ErrReadOnlyTxn is returned if an update function is called on a read-only transaction. ErrReadOnlyTxn = errors.New("No sets or deletes are allowed in a read-only transaction") // ErrDiscardedTxn is returned if a previously discarded transaction is re-used. ErrDiscardedTxn = errors.New("This transaction has been discarded. Create a new one") // ErrEmptyKey is returned if an empty key is passed on an update function. ErrEmptyKey = errors.New("Key cannot be empty") // ErrInvalidKey is returned if the key has a special !badger! prefix, // reserved for internal usage. ErrInvalidKey = errors.New("Key is using a reserved !badger! prefix") // ErrRetry is returned when a log file containing the value is not found. // This usually indicates that it may have been garbage collected, and the // operation needs to be retried. ErrRetry = errors.New("Unable to find log file. Please retry") // ErrThresholdZero is returned if threshold is set to zero, and value log GC is called. // In such a case, GC can't be run. ErrThresholdZero = errors.New( "Value log GC can't run because threshold is set to zero") // ErrNoRewrite is returned if a call for value log GC doesn't result in a log file rewrite. ErrNoRewrite = errors.New( "Value log GC attempt didn't result in any cleanup") // ErrRejected is returned if a value log GC is called either while another GC is running, or // after DB::Close has been called. ErrRejected = errors.New("Value log GC request rejected") // ErrInvalidRequest is returned if the user request is invalid. ErrInvalidRequest = errors.New("Invalid request") // ErrManagedTxn is returned if the user tries to use an API which isn't // allowed due to external management of transactions, when using ManagedDB. ErrManagedTxn = errors.New( "Invalid API request. Not allowed to perform this action using ManagedDB") // ErrInvalidDump if a data dump made previously cannot be loaded into the database. ErrInvalidDump = errors.New("Data dump cannot be read") // ErrZeroBandwidth is returned if the user passes in zero bandwidth for sequence. ErrZeroBandwidth = errors.New("Bandwidth must be greater than zero") // ErrInvalidLoadingMode is returned when opt.ValueLogLoadingMode option is not // within the valid range ErrInvalidLoadingMode = errors.New("Invalid ValueLogLoadingMode, must be FileIO or MemoryMap") // ErrReplayNeeded is returned when opt.ReadOnly is set but the // database requires a value log replay. ErrReplayNeeded = errors.New("Database was not properly closed, cannot open read-only") // ErrWindowsNotSupported is returned when opt.ReadOnly is used on Windows ErrWindowsNotSupported = errors.New("Read-only mode is not supported on Windows") // ErrPlan9NotSupported is returned when opt.ReadOnly is used on Plan 9 ErrPlan9NotSupported = errors.New("Read-only mode is not supported on Plan 9") // ErrTruncateNeeded is returned when the value log gets corrupt, and requires truncation of // corrupt data to allow Badger to run properly. ErrTruncateNeeded = errors.New( "Value log truncate required to run DB. This might result in data loss") // ErrBlockedWrites is returned if the user called DropAll. During the process of dropping all // data from Badger, we stop accepting new writes, by returning this error. ErrBlockedWrites = errors.New("Writes are blocked, possibly due to DropAll or Close") // ErrNilCallback is returned when subscriber's callback is nil. ErrNilCallback = errors.New("Callback cannot be nil") // ErrEncryptionKeyMismatch is returned when the storage key is not // matched with the key previously given. ErrEncryptionKeyMismatch = errors.New("Encryption key mismatch") // ErrInvalidDataKeyID is returned if the datakey id is invalid. ErrInvalidDataKeyID = errors.New("Invalid datakey id") // ErrInvalidEncryptionKey is returned if length of encryption keys is invalid. ErrInvalidEncryptionKey = errors.New("Encryption key's length should be" + "either 16, 24, or 32 bytes") // ErrGCInMemoryMode is returned when db.RunValueLogGC is called in in-memory mode. ErrGCInMemoryMode = errors.New("Cannot run value log GC when DB is opened in InMemory mode") // ErrDBClosed is returned when a get operation is performed after closing the DB. ErrDBClosed = errors.New("DB Closed") )
var DefaultIteratorOptions = IteratorOptions{ PrefetchValues: true, PrefetchSize: 100, Reverse: false, AllVersions: false, }
DefaultIteratorOptions contains default options when iterating over Badger key-value stores.
func WriteKeyRegistry(reg *KeyRegistry, opt KeyRegistryOptions) error
WriteKeyRegistry will rewrite the existing key registry file with new one. It is okay to give closed key registry. Since, it's using only the datakey.
type DB struct { sync.RWMutex // Guards list of inmemory tables, not individual reads and writes. // contains filtered or unexported fields }
DB provides the various functions required to interact with Badger. DB is thread-safe.
Open returns a new DB object.
Code:
dir, err := ioutil.TempDir("", "badger-test") if err != nil { panic(err) } defer removeDir(dir) db, err := Open(DefaultOptions(dir)) if err != nil { panic(err) } defer db.Close() err = db.View(func(txn *Txn) error { _, err := txn.Get([]byte("key")) // We expect ErrKeyNotFound fmt.Println(err) return nil }) if err != nil { panic(err) } txn := db.NewTransaction(true) // Read-write txn err = txn.SetEntry(NewEntry([]byte("key"), []byte("value"))) if err != nil { panic(err) } err = txn.Commit() if err != nil { panic(err) } err = db.View(func(txn *Txn) error { item, err := txn.Get([]byte("key")) if err != nil { return err } val, err := item.ValueCopy(nil) if err != nil { return err } fmt.Printf("%s\n", string(val)) return nil }) if err != nil { panic(err) }
Output:
Key not found value
OpenManaged returns a new DB, which allows more control over setting transaction timestamps, aka managed mode.
This is only useful for databases built on top of Badger (like Dgraph), and can be ignored by most users.
Backup dumps a protobuf-encoded list of all entries in the database into the given writer, that are newer than or equal to the specified version. It returns a timestamp (version) indicating the version of last entry that is dumped, which after incrementing by 1 can be passed into later invocation to generate incremental backup of entries that have been added/modified since the last invocation of DB.Backup(). DB.Backup is a wrapper function over Stream.Backup to generate full and incremental backups of the DB. For more control over how many goroutines are used to generate the backup, or if you wish to backup only a certain range of keys, use Stream.Backup directly.
BlockCacheMetrics returns the metrics for the underlying block cache.
Close closes a DB. It's crucial to call it to ensure all the pending updates make their way to disk. Calling DB.Close() multiple times would still only close the DB once.
DropAll would drop all the data stored in Badger. It does this in the following way. - Stop accepting new writes. - Pause memtable flushes and compactions. - Pick all tables from all levels, create a changeset to delete all these tables and apply it to manifest. - Pick all log files from value log, and delete all of them. Restart value log files from zero. - Resume memtable flushes and compactions.
NOTE: DropAll is resilient to concurrent writes, but not to reads. It is up to the user to not do any reads while DropAll is going on, otherwise they may result in panics. Ideally, both reads and writes are paused before running DropAll, and resumed after it is finished.
DropPrefix would drop all the keys with the provided prefix. It does this in the following way: - Stop accepting new writes. - Stop memtable flushes before acquiring lock. Because we're acquring lock here
and memtable flush stalls for lock, which leads to deadlock
- Flush out all memtables, skipping over keys with the given prefix, Kp. - Write out the value log header to memtables when flushing, so we don't accidentally bring Kp
back after a restart.
- Stop compaction. - Compact L0->L1, skipping over Kp. - Compact rest of the levels, Li->Li, picking tables which have Kp. - Resume memtable flushes, compactions and writes.
Flatten can be used to force compactions on the LSM tree so all the tables fall on the same level. This ensures that all the versions of keys are colocated and not split across multiple levels, which is necessary after a restore from backup. During Flatten, live compactions are stopped. Ideally, no writes are going on during Flatten. Otherwise, it would create competition between flattening the tree and new tables being created at level zero.
GetMergeOperator creates a new MergeOperator for a given key and returns a pointer to it. It also fires off a goroutine that performs a compaction using the merge function that runs periodically, as specified by dur.
GetSequence would initiate a new sequence object, generating it from the stored lease, if available, in the database. Sequence can be used to get a list of monotonically increasing integers. Multiple sequences can be created by providing different keys. Bandwidth sets the size of the lease, determining how many Next() requests can be served from memory.
GetSequence is not supported on ManagedDB. Calling this would result in a panic.
IndexCacheMetrics returns the metrics for the underlying index cache.
IsClosed denotes if the badger DB is closed or not. A DB instance should not be used after closing it.
KeySplits can be used to get rough key ranges to divide up iteration over the DB.
Load reads a protobuf-encoded list of all entries from a reader and writes them to the database. This can be used to restore the database from a backup made by calling DB.Backup(). If more complex logic is needed to restore a badger backup, the KVLoader interface should be used instead.
DB.Load() should be called on a database that is not running any other concurrent transactions while it is running.
MaxBatchCount returns max possible entries in batch
MaxBatchSize returns max possible batch size
NewKVLoader returns a new instance of KVLoader.
func (db *DB) NewManagedWriteBatch() *WriteBatch
NewStream creates a new Stream.
NewStreamAt creates a new Stream at a particular timestamp. Should only be used with managed DB.
func (db *DB) NewStreamWriter() *StreamWriter
NewStreamWriter creates a StreamWriter. Right after creating StreamWriter, Prepare must be called. The memory usage of a StreamWriter is directly proportional to the number of streams possible. So, efforts must be made to keep the number of streams low. Stream framework would typically use 16 goroutines and hence create 16 streams.
NewTransaction creates a new transaction. Badger supports concurrent execution of transactions, providing serializable snapshot isolation, avoiding write skews. Badger achieves this by tracking the keys read and at Commit time, ensuring that these read keys weren't concurrently modified by another transaction.
For read-only transactions, set update to false. In this mode, we don't track the rows read for any changes. Thus, any long running iterations done in this mode wouldn't pay this overhead.
Running transactions concurrently is OK. However, a transaction itself isn't thread safe, and should only be run serially. It doesn't matter if a transaction is created by one goroutine and passed down to other, as long as the Txn APIs are called serially.
When you create a new transaction, it is absolutely essential to call Discard(). This should be done irrespective of what the update param is set to. Commit API internally runs Discard, but running it twice wouldn't cause any issues.
txn := db.NewTransaction(false) defer txn.Discard() // Call various APIs.
NewTransactionAt follows the same logic as DB.NewTransaction(), but uses the provided read timestamp.
This is only useful for databases built on top of Badger (like Dgraph), and can be ignored by most users.
func (db *DB) NewWriteBatch() *WriteBatch
NewWriteBatch creates a new WriteBatch. This provides a way to conveniently do a lot of writes, batching them up as tightly as possible in a single transaction and using callbacks to avoid waiting for them to commit, thus achieving good performance. This API hides away the logic of creating and committing transactions. Due to the nature of SSI guaratees provided by Badger, blind writes can never encounter transaction conflicts (ErrConflict).
func (db *DB) NewWriteBatchAt(commitTs uint64) *WriteBatch
NewWriteBatchAt is similar to NewWriteBatch but it allows user to set the commit timestamp. NewWriteBatchAt is supposed to be used only in the managed mode.
Opts returns a copy of the DB options.
PrintHistogram builds and displays the key-value size histogram. When keyPrefix is set, only the keys that have prefix "keyPrefix" are considered for creating the histogram
RunValueLogGC triggers a value log garbage collection.
It picks value log files to perform GC based on statistics that are collected during compactions. If no such statistics are available, then log files are picked in random order. The process stops as soon as the first log file is encountered which does not result in garbage collection.
When a log file is picked, it is first sampled. If the sample shows that we can discard at least discardRatio space of that file, it would be rewritten.
If a call to RunValueLogGC results in no rewrites, then an ErrNoRewrite is thrown indicating that the call resulted in no file rewrites.
We recommend setting discardRatio to 0.5, thus indicating that a file be rewritten if half the space can be discarded. This results in a lifetime value log write amplification of 2 (1 from original write + 0.5 rewrite + 0.25 + 0.125 + ... = 2). Setting it to higher value would result in fewer space reclaims, while setting it to a lower value would result in more space reclaims at the cost of increased activity on the LSM tree. discardRatio must be in the range (0.0, 1.0), both endpoints excluded, otherwise an ErrInvalidRequest is returned.
Only one GC is allowed at a time. If another value log GC is running, or DB has been closed, this would return an ErrRejected.
Note: Every time GC is run, it would produce a spike of activity on the LSM tree.
SetDiscardTs sets a timestamp at or below which, any invalid or deleted versions can be discarded from the LSM tree, and thence from the value log to reclaim disk space. Can only be used with managed transactions.
Size returns the size of lsm and value log files in bytes. It can be used to decide how often to call RunValueLogGC.
Stream the contents of this DB to a new DB with options outOptions that will be created in outDir.
Subscribe can be used to watch key changes for the given key prefixes. At least one prefix should be passed, or an error will be returned. You can use an empty prefix to monitor all changes to the DB. This function blocks until the given context is done or an error occurs. The given function will be called with a new KVList containing the modified keys and the corresponding values.
Sync syncs database content to disk. This function provides more control to user to sync data whenever required.
Tables gets the TableInfo objects from the level controller. If withKeysCount is true, TableInfo objects also contain counts of keys for the tables.
Update executes a function, creating and managing a read-write transaction for the user. Error returned by the function is relayed by the Update method. Update cannot be used with managed transactions.
VerifyChecksum verifies checksum for all tables on all levels. This method can be used to verify checksum, if opt.ChecksumVerificationMode is NoVerification.
View executes a function creating and managing a read-only transaction for the user. Error returned by the function is relayed by the View method. If View is used with managed transactions, it would assume a read timestamp of MaxUint64.
type Entry struct { Key []byte Value []byte UserMeta byte ExpiresAt uint64 // time.Unix // contains filtered or unexported fields }
Entry provides Key, Value, UserMeta and ExpiresAt. This struct can be used by the user to set data.
NewEntry creates a new entry with key and value passed in args. This newly created entry can be set in a transaction by calling txn.SetEntry(). All other properties of Entry can be set by calling WithMeta, WithDiscard, WithTTL methods on it. This function uses key and value reference, hence users must not modify key and value until the end of transaction.
WithDiscard adds a marker to Entry e. This means all the previous versions of the key (of the Entry) will be eligible for garbage collection. This method is only useful if you have set a higher limit for options.NumVersionsToKeep. The default setting is 1, in which case, this function doesn't add any more benefit. If however, you have a higher setting for NumVersionsToKeep (in Dgraph, we set it to infinity), you can use this method to indicate that all the older versions can be discarded and removed during compactions.
WithMeta adds meta data to Entry e. This byte is stored alongside the key and can be used as an aid to interpret the value or store other contextual bits corresponding to the key-value pair of entry.
WithTTL adds time to live duration to Entry e. Entry stored with a TTL would automatically expire after the time has elapsed, and will be eligible for garbage collection.
Item is returned during iteration. Both the Key() and Value() output is only valid until iterator.Next() is called.
DiscardEarlierVersions returns whether the item was created with the option to discard earlier versions of a key when multiple are available.
EstimatedSize returns the approximate size of the key-value pair.
This can be called while iterating through a store to quickly estimate the size of a range of key-value pairs (without fetching the corresponding values).
ExpiresAt returns a Unix time value indicating when the item will be considered expired. 0 indicates that the item will never expire.
IsDeletedOrExpired returns true if item contains deleted or expired value.
Key returns the key.
Key is only valid as long as item is valid, or transaction is valid. If you need to use it outside its validity, please use KeyCopy.
KeyCopy returns a copy of the key of the item, writing it to dst slice. If nil is passed, or capacity of dst isn't sufficient, a new slice would be allocated and returned.
KeySize returns the size of the key. Exact size of the key is key + 8 bytes of timestamp
String returns a string representation of Item
UserMeta returns the userMeta set by the user. Typically, this byte, optionally set by the user is used to interpret the value.
Value retrieves the value of the item from the value log.
This method must be called within a transaction. Calling it outside a transaction is considered undefined behavior. If an iterator is being used, then Item.Value() is defined in the current iteration only, because items are reused.
If you need to use a value outside a transaction, please use Item.ValueCopy instead, or copy it yourself. Value might change once discard or commit is called. Use ValueCopy if you want to do a Set after Get.
ValueCopy returns a copy of the value of the item from the value log, writing it to dst slice. If nil is passed, or capacity of dst isn't sufficient, a new slice would be allocated and returned. Tip: It might make sense to reuse the returned slice as dst argument for the next call.
This function is useful in long running iterate/update transactions to avoid a write deadlock. See Github issue:
ValueSize returns the approximate size of the value.
This can be called to quickly estimate the size of a value without fetching it.
Version returns the commit timestamp of the item.
type Iterator struct { // ThreadId is an optional value that can be set to identify which goroutine created // the iterator. It can be used, for example, to uniquely identify each of the // iterators created by the stream interface ThreadId int // contains filtered or unexported fields }
Iterator helps iterating over the KV pairs in a lexicographically sorted order.
Close would close the iterator. It is important to call this when you're done with iteration.
Item returns pointer to the current key-value pair. This item is only valid until it.Next() gets called.
Next would advance the iterator by one. Always check it.Valid() after a Next() to ensure you have access to a valid it.Item().
Rewind would rewind the iterator cursor all the way to zero-th position, which would be the smallest key if iterating forward, and largest if iterating backward. It does not keep track of whether the cursor started with a Seek().
Seek would seek to the provided key if present. If absent, it would seek to the next smallest key greater than the provided key if iterating in the forward direction. Behavior would be reversed if iterating backwards.
Valid returns false when iteration is done.
ValidForPrefix returns false when iteration is done or when the current key is not prefixed by the specified prefix.
type IteratorOptions struct { // Indicates whether we should prefetch values during iteration and store them. PrefetchValues bool // How many KV pairs to prefetch while iterating. Valid only if PrefetchValues is true. PrefetchSize int Reverse bool // Direction of iteration. False is forward, true is backward. AllVersions bool // Fetch all valid versions of the same key. // The following option is used to narrow down the SSTables that iterator picks up. If // Prefix is specified, only tables which could have this prefix are picked based on their range // of keys. Prefix []byte // Only iterate over this given prefix. InternalAccess bool // Used to allow internal access to badger keys. // contains filtered or unexported fields }
IteratorOptions is used to set options when iterating over Badger key-value stores.
This package provides DefaultIteratorOptions which contains options that should work for most applications. Consider using that as a starting point before customizing it for your own needs.
KVList contains a list of key-value pairs.
KVLoader is used to write KVList objects in to badger. It can be used to restore a backup.
Finish is meant to be called after all the key-value pairs have been loaded.
Set writes the key-value pair to the database.
KeyRegistry used to maintain all the data keys.
func OpenKeyRegistry(opt KeyRegistryOptions) (*KeyRegistry, error)
OpenKeyRegistry opens key registry if it exists, otherwise it'll create key registry and returns key registry.
func (kr *KeyRegistry) Close() error
Close closes the key registry.
type KeyRegistryOptions struct { Dir string ReadOnly bool EncryptionKey []byte EncryptionKeyRotationDuration time.Duration InMemory bool }
type Logger interface { Errorf(string, ...interface{}) Warningf(string, ...interface{}) Infof(string, ...interface{}) Debugf(string, ...interface{}) }
Logger is implemented by any logging system that is used for standard logs.
type Manifest struct { Levels []levelManifest Tables map[uint64]TableManifest // Contains total number of creation and deletion changes in the manifest -- used to compute // whether it'd be useful to rewrite the manifest. Creations int Deletions int }
Manifest represents the contents of the MANIFEST file in a Badger store.
The MANIFEST file describes the startup state of the db -- all LSM files and what level they're at.
It consists of a sequence of ManifestChangeSet objects. Each of these is treated atomically, and contains a sequence of ManifestChange's (file creations/deletions) which we use to reconstruct the manifest at startup.
ReplayManifestFile reads the manifest file and constructs two manifest objects. (We need one immutable copy and one mutable copy of the manifest. Easiest way is to construct two of them.) Also, returns the last offset after a completely read manifest entry -- the file must be truncated at that point before further appends are made (if there is a partial entry after that). In normal conditions, truncOffset is the file size.
MergeFunc accepts two byte slices, one representing an existing value, and another representing a new value that needs to be ‘merged’ into it. MergeFunc contains the logic to perform the ‘merge’ and return an updated value. MergeFunc could perform operations like integer addition, list appends etc. Note that the ordering of the operands is maintained.
MergeOperator represents a Badger merge operator.
func (op *MergeOperator) Add(val []byte) error
Add records a value in Badger which will eventually be merged by a background routine into the values that were recorded by previous invocations to Add().
func (op *MergeOperator) Get() ([]byte, error)
Get returns the latest value for the merge operator, which is derived by applying the merge function to all the values added so far.
If Add has not been called even once, Get will return ErrKeyNotFound.
func (op *MergeOperator) Stop()
Stop waits for any pending merge to complete and then stops the background goroutine.
type Options struct { Dir string ValueDir string SyncWrites bool TableLoadingMode options.FileLoadingMode ValueLogLoadingMode options.FileLoadingMode NumVersionsToKeep int ReadOnly bool Truncate bool Logger Logger Compression options.CompressionType InMemory bool MaxTableSize int64 LevelSizeMultiplier int MaxLevels int ValueThreshold int NumMemtables int // Changing BlockSize across DB runs will not break badger. The block size is // read from the block index stored at the end of the table. BlockSize int BloomFalsePositive float64 KeepL0InMemory bool BlockCacheSize int64 IndexCacheSize int64 LoadBloomsOnOpen bool NumLevelZeroTables int NumLevelZeroTablesStall int LevelOneSize int64 ValueLogFileSize int64 ValueLogMaxEntries uint32 NumCompactors int CompactL0OnClose bool LogRotatesToFlush int32 ZSTDCompressionLevel int // When set, checksum will be validated for each entry read from the value log file. VerifyValueChecksum bool // Encryption related options. EncryptionKey []byte // encryption key EncryptionKeyRotationDuration time.Duration // key rotation duration // BypassLockGaurd will bypass the lock guard on badger. Bypassing lock // guard can cause data corruption if multiple badger instances are using // the same directory. Use this options with caution. BypassLockGuard bool // ChecksumVerificationMode decides when db should verify checksums for SSTable blocks. ChecksumVerificationMode options.ChecksumVerificationMode // DetectConflicts determines whether the transactions would be checked for // conflicts. The transactions can be processed at a higher rate when // conflict detection is disabled. DetectConflicts bool // contains filtered or unexported fields }
Options are params for creating DB object.
This package provides DefaultOptions which contains options that should work for most applications. Consider using that as a starting point before customizing it for your own needs.
Each option X is documented on the WithX method.
DefaultOptions sets a list of recommended options for good performance. Feel free to modify these to suit your needs with the WithX methods.
LSMOnlyOptions follows from DefaultOptions, but sets a higher ValueThreshold so values would be collocated with the LSM tree, with value log largely acting as a write-ahead log only. These options would reduce the disk usage of value log, and make Badger act more like a typical LSM tree.
Debugf logs a DEBUG message to the logger specified in opts.
Errorf logs an ERROR log message to the logger specified in opts or to the global logger if no logger is specified in opts.
Infof logs an INFO message to the logger specified in opts.
Warningf logs a WARNING message to the logger specified in opts.
WithBlockCacheSize returns a new Options value with BlockCacheSize set to the given value.
This value specifies how much data cache should hold in memory. A small size of cache means lower memory consumption and lookups/iterations would take longer. It is recommended to use a cache if you're using compression or encryption. If compression and encryption both are disabled, adding a cache will lead to unnecessary overhead which will affect the read performance. Setting size to zero disables the cache altogether.
Default value of BlockCacheSize is zero.
WithBlockSize returns a new Options value with BlockSize set to the given value.
BlockSize sets the size of any block in SSTable. SSTable is divided into multiple blocks internally. Each block is compressed using prefix diff encoding.
The default value of BlockSize is 4KB.
WithBloomFalsePositive returns a new Options value with BloomFalsePositive set to the given value.
BloomFalsePositive sets the false positive probability of the bloom filter in any SSTable. Before reading a key from table, the bloom filter is checked for key existence. BloomFalsePositive might impact read performance of DB. Lower BloomFalsePositive value might consume more memory.
The default value of BloomFalsePositive is 0.01.
Setting this to 0 disables the bloom filter completely.
WithBypassLockGuard returns a new Options value with BypassLockGuard set to the given value.
When BypassLockGuard option is set, badger will not acquire a lock on the directory. This could lead to data corruption if multiple badger instances write to the same data directory. Use this option with caution.
The default value of BypassLockGuard is false.
func (opt Options) WithChecksumVerificationMode(cvMode options.ChecksumVerificationMode) Options
WithChecksumVerificationMode returns a new Options value with ChecksumVerificationMode set to the given value.
ChecksumVerificationMode indicates when the db should verify checksums for SSTable blocks.
The default value of VerifyValueChecksum is options.NoVerification.
WithCompactL0OnClose returns a new Options value with CompactL0OnClose set to the given value.
CompactL0OnClose determines whether Level 0 should be compacted before closing the DB. This ensures that both reads and writes are efficient when the DB is opened later. CompactL0OnClose is set to true if KeepL0InMemory is set to true.
The default value of CompactL0OnClose is true.
func (opt Options) WithCompression(cType options.CompressionType) Options
WithCompression returns a new Options value with Compression set to the given value.
When compression is enabled, every block will be compressed using the specified algorithm. This option doesn't affect existing tables. Only the newly created tables will be compressed.
The default compression algorithm used is zstd when built with Cgo. Without Cgo, the default is snappy. Compression is enabled by default.
WithDetectConflicts returns a new Options value with DetectConflicts set to the given value.
Detect conflicts options determines if the transactions would be checked for conflicts before committing them. When this option is set to false (detectConflicts=false) badger can process transactions at a higher rate. Setting this options to false might be useful when the user application deals with conflict detection and resolution.
The default value of Detect conflicts is True.
WithDir returns a new Options value with Dir set to the given value.
Dir is the path of the directory where key data will be stored in. If it doesn't exist, Badger will try to create it for you. This is set automatically to be the path given to `DefaultOptions`.
WithEncryptionKey return a new Options value with EncryptionKey set to the given value.
EncryptionKey is used to encrypt the data with AES. Type of AES is used based on the key size. For example 16 bytes will use AES-128. 24 bytes will use AES-192. 32 bytes will use AES-256.
WithEncryptionKeyRotationDuration returns new Options value with the duration set to the given value.
Key Registry will use this duration to create new keys. If the previous generated key exceed the given duration. Then the key registry will create new key.
WithInMemory returns a new Options value with Inmemory mode set to the given value.
When badger is running in InMemory mode, everything is stored in memory. No value/sst files are created. In case of a crash all data will be lost.
WithIndexCacheSize returns a new Options value with IndexCacheSize set to the given value.
This value specifies how much memory should be used by table indices. These indices include the block offsets and the bloomfilters. Badger uses bloom filters to speed up lookups. Each table has its own bloom filter and each bloom filter is approximately of 5 MB.
Zero value for IndexCacheSize means all the indices will be kept in memory and the cache is disabled.
The default value of IndexCacheSize is 0 which means all indices are kept in memory.
WithKeepL0InMemory returns a new Options value with KeepL0InMemory set to the given value.
When KeepL0InMemory is set to true we will keep all Level 0 tables in memory. This leads to better performance in writes as well as compactions. In case of DB crash, the value log replay will take longer to complete since memtables and all level 0 tables will have to be recreated. This option also sets CompactL0OnClose option to true.
The default value of KeepL0InMemory is false.
WithLevelOneSize returns a new Options value with LevelOneSize set to the given value.
LevelOneSize sets the maximum total size for Level 1.
The default value of LevelOneSize is 20MB.
WithLevelSizeMultiplier returns a new Options value with LevelSizeMultiplier set to the given value.
LevelSizeMultiplier sets the ratio between the maximum sizes of contiguous levels in the LSM. Once a level grows to be larger than this ratio allowed, the compaction process will be
triggered.
The default value of LevelSizeMultiplier is 15.
WithLoadBloomsOnOpen returns a new Options value with LoadBloomsOnOpen set to the given value.
Badger uses bloom filters to speed up key lookups. When LoadBloomsOnOpen is set to false, bloom filters will be loaded lazily and not on DB open. Set this option to false to reduce the time taken to open the DB.
The default value of LoadBloomsOnOpen is true.
WithLogRotatesToFlush returns a new Options value with LogRotatesToFlush set to the given value.
LogRotatesToFlush sets the number of value log file rotates after which the Memtables are flushed to disk. This is useful in write loads with fewer keys and larger values. This work load would fill up the value logs quickly, while not filling up the Memtables. Thus, on a crash and restart, the value log head could cause the replay of a good number of value log files which can slow things on start.
The default value of LogRotatesToFlush is 2.
WithLogger returns a new Options value with Logger set to the given value.
Logger provides a way to configure what logger each value of badger.DB uses.
The default value of Logger writes to stderr using the log package from the Go standard library.
WithLoggingLevel returns a new Options value with logging level of the default logger set to the given value. LoggingLevel sets the level of logging. It should be one of DEBUG, INFO, WARNING or ERROR levels.
The default value of LoggingLevel is INFO.
WithMaxLevels returns a new Options value with MaxLevels set to the given value.
Maximum number of levels of compaction allowed in the LSM.
The default value of MaxLevels is 7.
WithMaxTableSize returns a new Options value with MaxTableSize set to the given value.
MaxTableSize sets the maximum size in bytes for each LSM table or file.
The default value of MaxTableSize is 64MB.
WithNumCompactors returns a new Options value with NumCompactors set to the given value.
NumCompactors sets the number of compaction workers to run concurrently. Setting this to zero stops compactions, which could eventually cause writes to block forever.
The default value of NumCompactors is 2. One is dedicated just for L0 and L1.
WithNumLevelZeroTables returns a new Options value with NumLevelZeroTables set to the given value.
NumLevelZeroTables sets the maximum number of Level 0 tables before compaction starts.
The default value of NumLevelZeroTables is 5.
WithNumLevelZeroTablesStall returns a new Options value with NumLevelZeroTablesStall set to the given value.
NumLevelZeroTablesStall sets the number of Level 0 tables that once reached causes the DB to stall until compaction succeeds.
The default value of NumLevelZeroTablesStall is 10.
WithNumMemtables returns a new Options value with NumMemtables set to the given value.
NumMemtables sets the maximum number of tables to keep in memory before stalling.
The default value of NumMemtables is 5.
WithNumVersionsToKeep returns a new Options value with NumVersionsToKeep set to the given value.
NumVersionsToKeep sets how many versions to keep per key at most.
The default value of NumVersionsToKeep is 1.
WithReadOnly returns a new Options value with ReadOnly set to the given value.
When ReadOnly is true the DB will be opened on read-only mode. Multiple processes can open the same Badger DB. Note: if the DB being opened had crashed before and has vlog data to be replayed, ReadOnly will cause Open to fail with an appropriate message.
The default value of ReadOnly is false.
WithSyncWrites returns a new Options value with SyncWrites set to the given value.
When SyncWrites is true all writes are synced to disk. Setting this to false would achieve better performance, but may cause data loss in case of crash.
The default value of SyncWrites is true.
func (opt Options) WithTableLoadingMode(val options.FileLoadingMode) Options
WithTableLoadingMode returns a new Options value with TableLoadingMode set to the given value.
TableLoadingMode indicates which file loading mode should be used for the LSM tree data files.
The default value of TableLoadingMode is options.MemoryMap.
WithTruncate returns a new Options value with Truncate set to the given value.
Truncate indicates whether value log files should be truncated to delete corrupt data, if any. This option is ignored when ReadOnly is true.
The default value of Truncate is false.
WithValueDir returns a new Options value with ValueDir set to the given value.
ValueDir is the path of the directory where value data will be stored in. If it doesn't exist, Badger will try to create it for you. This is set automatically to be the path given to `DefaultOptions`.
WithValueLogFileSize returns a new Options value with ValueLogFileSize set to the given value.
ValueLogFileSize sets the maximum size of a single value log file.
The default value of ValueLogFileSize is 1GB.
func (opt Options) WithValueLogLoadingMode(val options.FileLoadingMode) Options
WithValueLogLoadingMode returns a new Options value with ValueLogLoadingMode set to the given value.
ValueLogLoadingMode indicates which file loading mode should be used for the value log data files.
The default value of ValueLogLoadingMode is options.MemoryMap.
WithValueLogMaxEntries returns a new Options value with ValueLogMaxEntries set to the given value.
ValueLogMaxEntries sets the maximum number of entries a value log file can hold approximately. A actual size limit of a value log file is the minimum of ValueLogFileSize and ValueLogMaxEntries.
The default value of ValueLogMaxEntries is one million (1000000).
WithValueThreshold returns a new Options value with ValueThreshold set to the given value.
ValueThreshold sets the threshold used to decide whether a value is stored directly in the LSM tree or separately in the log value files.
The default value of ValueThreshold is 1 KB, but LSMOnlyOptions sets it to maxValueThreshold.
WithVerifyValueChecksum returns a new Options value with VerifyValueChecksum set to the given value.
When VerifyValueChecksum is set to true, checksum will be verified for every entry read from the value log. If the value is stored in SST (value size less than value threshold) then the checksum validation will not be done.
The default value of VerifyValueChecksum is False.
WithZSTDCompressionLevel returns a new Options value with ZSTDCompressionLevel set to the given value.
The ZSTD compression algorithm supports 20 compression levels. The higher the compression level, the better is the compression ratio but lower is the performance. Lower levels have better performance and higher levels have better compression ratios. We recommend using level 1 ZSTD Compression Level. Any level higher than 1 seems to deteriorate badger's performance. The following benchmarks were done on a 4 KB block size (default block size). The compression is ratio supposed to increase with increasing compression level but since the input for compression algorithm is small (4 KB), we don't get significant benefit at level 3. It is advised to write your own benchmarks before choosing a compression algorithm or level.
no_compression-16 10 502848865 ns/op 165.46 MB/s - zstd_compression/level_1-16 7 739037966 ns/op 112.58 MB/s 2.93 zstd_compression/level_3-16 7 756950250 ns/op 109.91 MB/s 2.72 zstd_compression/level_15-16 1 11135686219 ns/op 7.47 MB/s 4.38 Benchmark code can be found in table/builder_test.go file
Sequence represents a Badger sequence.
Next would return the next integer in the sequence, updating the lease by running a transaction if needed.
Release the leased sequence to avoid wasted integers. This should be done right before closing the associated DB. However it is valid to use the sequence after it was released, causing a new lease with full bandwidth.
type Stream struct { // Prefix to only iterate over certain range of keys. If set to nil (default), Stream would // iterate over the entire DB. Prefix []byte // Number of goroutines to use for iterating over key ranges. Defaults to 16. NumGo int // Badger would produce log entries in Infof to indicate the progress of Stream. LogPrefix can // be used to help differentiate them from other activities. Default is "Badger.Stream". LogPrefix string // ChooseKey is invoked each time a new key is encountered. Note that this is not called // on every version of the value, only the first encountered version (i.e. the highest version // of the value a key has). ChooseKey can be left nil to select all keys. // // Note: Calls to ChooseKey are concurrent. ChooseKey func(item *Item) bool // KeyToList, similar to ChooseKey, is only invoked on the highest version of the value. It // is upto the caller to iterate over the versions and generate zero, one or more KVs. It // is expected that the user would advance the iterator to go through the versions of the // values. However, the user MUST immediately return from this function on the first encounter // with a mismatching key. See example usage in ToList function. Can be left nil to use ToList // function by default. // // Note: Calls to KeyToList are concurrent. KeyToList func(key []byte, itr *Iterator) (*pb.KVList, error) // This is the method where Stream sends the final output. All calls to Send are done by a // single goroutine, i.e. logic within Send method can expect single threaded execution. Send func(*pb.KVList) error // contains filtered or unexported fields }
Stream provides a framework to concurrently iterate over a snapshot of Badger, pick up key-values, batch them up and call Send. Stream does concurrent iteration over many smaller key ranges. It does NOT send keys in lexicographical sorted order. To get keys in sorted order, use Iterator.
Backup dumps a protobuf-encoded list of all entries in the database into the given writer, that are newer than or equal to the specified version. It returns a timestamp(version) indicating the version of last entry that was dumped, which after incrementing by 1 can be passed into a later invocation to generate an incremental dump of entries that have been added/modified since the last invocation of Stream.Backup().
This can be used to backup the data in a database at a given point in time.
Orchestrate runs Stream. It picks up ranges from the SSTables, then runs NumGo number of goroutines to iterate over these ranges and batch up KVs in lists. It concurrently runs a single goroutine to pick these lists, batch them up further and send to Output.Send. Orchestrate also spits logs out to Infof, using provided LogPrefix. Note that all calls to Output.Send are serial. In case any of these steps encounter an error, Orchestrate would stop execution and return that error. Orchestrate can be called multiple times, but in serial order.
ToList is a default implementation of KeyToList. It picks up all valid versions of the key, skipping over deleted or expired keys.
StreamWriter is used to write data coming from multiple streams. The streams must not have any overlapping key ranges. Within each stream, the keys must be sorted. Badger Stream framework is capable of generating such an output. So, this StreamWriter can be used at the other end to build BadgerDB at a much faster pace by writing SSTables (and value logs) directly to LSM tree levels without causing any compactions at all. This is way faster than using batched writer or using transactions, but only applicable in situations where the keys are pre-sorted and the DB is being bootstrapped. Existing data would get deleted when using this writer. So, this is only useful when restoring from backup or replicating DB across servers.
StreamWriter should not be called on in-use DB instances. It is designed only to bootstrap new DBs.
func (sw *StreamWriter) Flush() error
Flush is called once we are done writing all the entries. It syncs DB directories. It also updates Oracle with maxVersion found in all entries (if DB is not managed).
func (sw *StreamWriter) Prepare() error
Prepare should be called before writing any entry to StreamWriter. It deletes all data present in existing DB, stops compactions and any writes being done by other means. Be very careful when calling Prepare, because it could result in permanent data loss. Not calling Prepare would result in a corrupt Badger instance.
func (sw *StreamWriter) Write(kvs *pb.KVList) error
Write writes KVList to DB. Each KV within the list contains the stream id which StreamWriter would use to demux the writes. Write is thread safe and can be called concurrently by multiple goroutines.
type TableInfo struct { ID uint64 Level int Left []byte Right []byte KeyCount uint64 // Number of keys in the table EstimatedSz uint64 IndexSz int }
TableInfo represents the information about a table.
type TableManifest struct { Level uint8 KeyID uint64 Compression options.CompressionType }
TableManifest contains information about a specific table in the LSM tree.
Txn represents a Badger transaction.
Commit commits the transaction, following these steps:
1. If there are no writes, return immediately.
2. Check if read rows were updated since txn started. If so, return ErrConflict.
3. If no conflict, generate a commit timestamp and update written rows' commit ts.
4. Batch up all writes, write them to value log and LSM tree.
5. If callback is provided, Badger will return immediately after checking for conflicts. Writes to the database will happen in the background. If there is a conflict, an error will be returned and the callback will not run. If there are no conflicts, the callback will be called in the background upon successful completion of writes or any error during write.
If error is nil, the transaction is successfully committed. In case of a non-nil error, the LSM tree won't be updated, so there's no need for any rollback.
CommitAt commits the transaction, following the same logic as Commit(), but at the given commit timestamp. This will panic if not used with managed transactions.
This is only useful for databases built on top of Badger (like Dgraph), and can be ignored by most users.
CommitWith acts like Commit, but takes a callback, which gets run via a goroutine to avoid blocking this function. The callback is guaranteed to run, so it is safe to increment sync.WaitGroup before calling CommitWith, and decrementing it in the callback; to block until all callbacks are run.
Delete deletes a key.
This is done by adding a delete marker for the key at commit timestamp. Any reads happening before this timestamp would be unaffected. Any reads after this commit would see the deletion.
The current transaction keeps a reference to the key byte slice argument. Users must not modify the key until the end of the transaction.
Discard discards a created transaction. This method is very important and must be called. Commit method calls this internally, however, calling this multiple times doesn't cause any issues. So, this can safely be called via a defer right when transaction is created.
NOTE: If any operations are run on a discarded transaction, ErrDiscardedTxn is returned.
Get looks for key and returns corresponding Item. If key is not found, ErrKeyNotFound is returned.
func (txn *Txn) NewIterator(opt IteratorOptions) *Iterator
NewIterator returns a new iterator. Depending upon the options, either only keys, or both key-value pairs would be fetched. The keys are returned in lexicographically sorted order. Using prefetch is recommended if you're doing a long running iteration, for performance.
Multiple Iterators: For a read-only txn, multiple iterators can be running simultaneously. However, for a read-write txn, iterators have the nuance of being a snapshot of the writes for the transaction at the time iterator was created. If writes are performed after an iterator is created, then that iterator will not be able to see those writes. Only writes performed before an iterator was created can be viewed.
Code:
dir, err := ioutil.TempDir("", "badger-test") if err != nil { panic(err) } defer removeDir(dir) db, err := Open(DefaultOptions(dir)) if err != nil { panic(err) } defer db.Close() bkey := func(i int) []byte { return []byte(fmt.Sprintf("%09d", i)) } bval := func(i int) []byte { return []byte(fmt.Sprintf("%025d", i)) } txn := db.NewTransaction(true) // Fill in 1000 items n := 1000 for i := 0; i < n; i++ { err := txn.SetEntry(NewEntry(bkey(i), bval(i))) if err != nil { panic(err) } } err = txn.Commit() if err != nil { panic(err) } opt := DefaultIteratorOptions opt.PrefetchSize = 10 // Iterate over 1000 items var count int err = db.View(func(txn *Txn) error { it := txn.NewIterator(opt) defer it.Close() for it.Rewind(); it.Valid(); it.Next() { count++ } return nil }) if err != nil { panic(err) } fmt.Printf("Counted %d elements", count)
Output:
Counted 1000 elements
func (txn *Txn) NewKeyIterator(key []byte, opt IteratorOptions) *Iterator
NewKeyIterator is just like NewIterator, but allows the user to iterate over all versions of a single key. Internally, it sets the Prefix option in provided opt, and uses that prefix to additionally run bloom filter lookups before picking tables from the LSM tree.
ReadTs returns the read timestamp of the transaction.
Set adds a key-value pair to the database. It will return ErrReadOnlyTxn if update flag was set to false when creating the transaction.
The current transaction keeps a reference to the key and val byte slice arguments. Users must not modify key and val until the end of the transaction.
SetEntry takes an Entry struct and adds the key-value pair in the struct, along with other metadata to the database.
The current transaction keeps a reference to the entry passed in argument. Users must not modify the entry until the end of the transaction.
WriteBatch holds the necessary info to perform batched writes.
func (wb *WriteBatch) Cancel()
Cancel function must be called if there's a chance that Flush might not get called. If neither Flush or Cancel is called, the transaction oracle would never get a chance to clear out the row commit timestamp map, thus causing an unbounded memory consumption. Typically, you can call Cancel as a defer statement right after NewWriteBatch is called.
Note that any committed writes would still go through despite calling Cancel.
func (wb *WriteBatch) Delete(k []byte) error
Delete is equivalent of Txn.Delete.
func (wb *WriteBatch) DeleteAt(k []byte, ts uint64) error
DeleteAt is equivalent of Txn.Delete but accepts a delete timestamp.
func (wb *WriteBatch) Error() error
Error returns any errors encountered so far. No commits would be run once an error is detected.
func (wb *WriteBatch) Flush() error
Flush must be called at the end to ensure that any pending writes get committed to Badger. Flush returns any error stored by WriteBatch.
func (wb *WriteBatch) Set(k, v []byte) error
Set is equivalent of Txn.Set().
func (wb *WriteBatch) SetEntry(e *Entry) error
SetEntry is the equivalent of Txn.SetEntry.
func (wb *WriteBatch) SetEntryAt(e *Entry, ts uint64) error
SetEntryAt is the equivalent of Txn.SetEntry but it also allows setting version for the entry. SetEntryAt can be used only in managed mode.
func (wb *WriteBatch) SetMaxPendingTxns(max int)
SetMaxPendingTxns sets a limit on maximum number of pending transactions while writing batches. This function should be called before using WriteBatch. Default value of MaxPendingTxns is 16 to minimise memory usage.
func (wb *WriteBatch) Write(kvList *pb.KVList) error
Package badger imports 40 packages (graph) and is imported by 507 packages. Updated 2020-09-18. Refresh now. Tools for package owners. | https://godoc.org/github.com/dgraph-io/badger | CC-MAIN-2020-40 | refinedweb | 8,878 | 58.99 |
21 November 2008 14:56 [Source: ICIS news]
TORONTO (ICIS news)--Citigroup has slashed target prices and profit estimates for five US chemicals majors due to massive global destocking in the chemical supply chain, it said on Friday.
?xml:namespace>
“We think inventory liquidation is most pronounced in ?xml:namespace>
“This is now followed by announcements [to cut production] from LyondellBasell and BASF,” it said.
Citigroup believed that other large-cap global chemical companies would face similar headwinds, given the sharp deterioration in already weakened markets such as autos, construction and textiles, it said.
“We had previously forecasted a 10% ‘base case’ earnings decline for bellwether chemical companies such as DuPont, but are now moving to a 20-25% assumption,” the bank said.
Analysts cut Celanese’s target price to $9 from $28, their 2008 earnings per share (EPS) estimate to $3.14 from $3.53 and their 2009 EPS estimate to $1.78 from $2.98.
The bank also was downgraded the shares to “hold” from “buy”.
DuPont’s target price was cut to $23 from $36, its 2008 EPS estimate to $3.18 from $3.33 and the 2009 estimate to $2.51 from $3.01.
Citigroup’s target price for Dow Chemical’s target prices is now $17, down from $26. The 2008 EPS estimate was cut to $2.65 from $2.82, and the 2009 estimate to $2.09 from $2.40.
Eastman’s target price was cut to $30 from $42, but Citigroup retained its EPS estimates at $5.26 and $4.18 for 2008 and 2009 respectively.
Analysts cut PPG Industries’ target price to $39 from $54. They reduced their 2008 EPS estimate to $5.00 from $5.14 and their 2009 estimate to $4.00 from $4.90.
For more on BASF, Celanese, Dupont, Dow Chemical, Eastman Chemical, LyondellBasell and PPG | http://www.icis.com/Articles/2008/11/21/9173776/destocking-prompts-citi-to-slash-us-chems-targets.html | CC-MAIN-2014-35 | refinedweb | 308 | 69.79 |
Java Exercises: Test whether there are two integers x and y
Java Basic: Exercise-191 with Solution
Write a Java program to test whether there are two integers x and y such that x^2 + y^2 is equal to a given positive number.
Pictorial Presentation:
Sample Solution:
Java Code:
import java.util.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Input a positive integer: "); int n = in.nextInt(); if (n>0) { System.out.print("Is "+n+" sum of two square numbers? "+sum_of_square_numbers(n)); } } public static boolean sum_of_square_numbers(int n) { int left_num = 0, right_num = (int) Math.sqrt(n); while (left_num <= right_num) { if (left_num * left_num + right_num * right_num == n) { return true; } else if (left_num * left_num + right_num * right_num < n) { left_num++; } else { right_num--; } } return false; } }
Sample Output:
Input a positive integer: 25 Is 25 sum of two square numbers? true
Flowchart:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to find the missing string from two given strings.
Next: Write a Java program to find the kth smallest and largest element in a given array. Elements in the array can be in any order.
What is the difficulty level of this exercise?
New Content: Composer: Dependency manager for PHP, R Programming | https://www.w3resource.com/java-exercises/basic/java-basic-exercise-191.php | CC-MAIN-2019-18 | refinedweb | 214 | 57.37 |
JPA.next - Thinking about the Future
By Linda DeMichiel on Mar 29, 2010
JPA 2.0 was strongly influenced by input that we received from the Java developer community, and many of the new features and improvements in JPA 2.0 were added and prioritized in response to developer feedback.
These include all of the following (and more!):
- collections of basic types
- collections of embeddables
- nested embeddables
- persistently ordered lists
- orphan removal
- pessimistic locking
- foreign key mappings for unidirectional one-to-many relationships
- improved support for maps
- criteria query API
- improvements to JPQL, including collection-valued in-expressions, more generalized support for operators and functions, and restrictions on query polymorphism
- further standardization of configuration properties and hints
Feedback from the community is very important to us, so please share your thoughts on where you think we should go next. What features do you think are most important to add in JPA 2.1?
Feel free to comment here, and please also share your input by posting
to the JPA 2.0 feedback list,
jsr
Thanks!
I know I won't be the last but manual flush mode please. I know we all clamored for it with JPA2, but not sure what the argument against it was.
Posted by Jason Porter on March 29, 2010 at 08:49 AM PDT #
it would be nice to have the equivalent of hibernate's FlushMode.MANUAL
Posted by Xavier Dury on March 29, 2010 at 07:52 PM PDT #
Hi Linda,
First of all thanks a lot for the great work on JPA 2.0!
Here is one of my wishes for JPA 2.1:
What I'm really missing on JPA is access to the change set the provider creates before an update. Today it's not possible to get a list of changes made on the entities.
That's one of the only point where I always need direct access to Hibernates PostUpdateEventListener and where I can't use JPA EntityListeners mechanism.
It would be great to have a standardized way of accessing the change set and more information on the currently running transaction.
Kind Regards,
Simon
Posted by Simon Martinelli on March 29, 2010 at 10:15 PM PDT #
Isn't FlushMode.COMMIT the equivalent of FlushModel.MANUAL? It defers the flush until commit, or until you call Flush. Seems like the same thing.
Suggestions:
Standard set of test cases to ship with spec. (Why wait for 2.1? Do it now!)
Posted by Pierce Wetter on April 13, 2010 at 02:52 AM PDT #
@Pierce
Commit is not the same unfortunately. I may have an entity manager that stays open longer than a transaction, and I may not want to persist to the database at commit as well.
Imagine I have a wizard like form that takes you through a series of steps. You can cancel the wizard at any time. If you cancel and don't complete the process either the records that were persisted need to be removed, or with a manual flush option I can flush once at the end of the wizard (keeping state in a conversation or a session) and just write to the database once. That's the power of having a manual flush. I'm not done with my unit of work, so don't write anything until I tell you to, when I'm done with the unit of work.
It would be the same in a desktop / fat client application, why commit things to the database and have to possibly clean it out if I don't need to?
Posted by Jason Porter on April 13, 2010 at 03:09 AM PDT #
Both Hibernate (Envers) and EclipseLink support an audit trail/versioning API.
Seems like a natural thing to standardize.
Posted by Pierce Wetter on April 14, 2010 at 04:15 AM PDT #
+1 on audit trail / versioning API
Posted by Jason Porter on April 14, 2010 at 04:23 AM PDT #
Read only entities would be good enhancement.
If the data comes from a view or from an other system in most cases this data is not updatable.
Posted by Simon Martinelli on April 14, 2010 at 07:34 PM PDT #
+1 for changed set. You will finally be able to execute some triggers logic.
The possibility to use EntityManager in entity life-cycle (EntityListeners) events like @PrePersist is also something I miss.
Posted by Radu B on April 16, 2010 at 01:44 AM PDT #
My wishes (more likely for JPA 3.0 ;-):
\* fetch- and merge-plans
\* declaring relationships as optional/mandatory so that the query-engine can choose on its own whether to use inner-joins or left-outer-joins
\* Down-casts in joins: select employee e join (MaintenanceProject)e.projects p where p.propertyOnylInMaintenanceProject = 'value'
\* metamodell with more information at runtime: length/type of corresponding column, all declared (proprietary) annotations, etc.
Posted by Frank Schwarz on April 16, 2010 at 04:36 PM PDT #
One more wish for JPA 2.1:
It would be great if there were more sensible column-naming rules for embeddables: This one for example is impossible without @AttributeOverrides:
public class Car {
@Embedded private Weight basicWeight;
@Embedded private Weight maxWeight;
}
public class Weight {
private BigDecimal value;
@Enumerated WeightUnit unit;
}
Why not generating column-names like basicweight_value, basicweight_unit, etc. by default?
Posted by Frank Schwarz on April 16, 2010 at 04:50 PM PDT #
- Enhanced sorting/ordering support (e.g. using comparators), see Hibernate's @Sort
- Native query elements within Criteria API
Posted by Adrian Hummel on April 18, 2010 at 09:31 PM PDT #
- persitence-test.xml configuration file for unit testing with maven
Posted by Stan Svec on April 19, 2010 at 10:19 PM PDT #
It would be great to include support for queries by example. I understand OpenJPA offers this as extension to CriteriaBuilder API.
Posted by Jaro Kuruc on April 29, 2010 at 07:14 AM PDT #
I would like nonproprietary enum support for legacy databases where column values are ordinals that are not sequential. This is common in some industries, such as pharmaceuticals where data providers use discontinuous integers to represent various states. Right now, this requires me to use <object-type-converter> in EclipseLink. To quote an EclipseLink bug, we need something like this:
// EXAMPLE USE:
@Entity
public class Order {
...
public enum Status {
@EnumValue(value="N")
NEW,
@EnumValue(value="S")
SHIPPED,
@EnumValue(value="C")
CLOSED
}
}
but in this case, we also need ordinal support as well.
Posted by Edward Rayl on May 06, 2010 at 03:30 AM PDT #
+1 on audit trail / versioning API
Posted by Reto on May 14, 2010 at 02:50 AM PDT #
Is there any implementation available, which is fully JPA 2.0 compatible? 'til now I haven't found any :(
Posted by Jens Elkner on June 19, 2010 at 03:13 AM PDT #
+1 on audit trail / versioning API
Posted by Duncan Carter on July 15, 2010 at 01:57 AM PDT #
+1 on audit trail / versioning API
Posted by Hansi Müller on July 21, 2010 at 03:30 PM PDT #
+1 on:
- audit trail / versioning API,
- FlushModel.MANUAL,
- enum support for legacy databases,
- more sensible column-naming rules for embeddables,
- queries by example and changed set
all these are situations where I use hibernate on a day-to-day
Posted by Gilliard Cordeiro on July 27, 2010 at 01:24 AM PDT #
+1 on:
audit trail / versioning API;
FlushMode.MANUAL;
more sensible column-naming for embeddables;
access to the change set the provider creates before an update.
Posted by Geraldo Luiz on August 25, 2010 at 10:30 PM PDT #
I would like to have custom converterts to do the conversion of the content of the database field to any Java type.
Posted by Simon Martinelli on August 25, 2010 at 11:06 PM PDT #
Hi Linda,
One of my biggest requests is remote Criteria. This is for use within Java client applications. This was missed out in JAP 2.0. As a reference look at Hibernate's DetachedCriteria.
We could use the MetaModel on the client to create remote criteria instances as no EntityManager would be available.
What are the chances of this?
regards,
--
Darren
Posted by Darren Bell on September 09, 2010 at 03:12 AM PDT #
+1 on
- DetachedCriteria support in JPA 2.1
Posted by Zuber Saiyed on September 15, 2010 at 06:47 AM PDT #
We need outer joins with conditions in an ON clause.
Let's say you want a list of car dealers and how many new vehicles they're selling.
In SQL you can say:
SELECT d.name, count( v.id ) FROM dealer d LEFT OUTER JOIN vehicle v ON v.dealer_id = d.dealer_id AND v.type = 'New' GROUP BY d.name
In JPQL, you only have the WHERE clause which limits your results, making the outer join useless:
SELECT d.name, count( v.id ) FROM dealer d LEFT OUTER JOIN d.vehicleList v WHERE v.type = 'New' GROUP BY d.name
This is so basic. Let's not forget why we have JPA. Back to reality please.
Posted by Bernard on September 15, 2010 at 08:43 AM PDT #
+1 on outer joins with conditions in an ON (WITH) clause. :-)
Posted by Peter Levart on October 11, 2010 at 05:22 PM PDT #."
What's the reason for this? Could this limitation be overcomed?
I'll find also useful some way to ask for loading some/all lazy fields when you know that the entity is going to be detached. I find kind of ugly calling something on the fields just to load them.
+1 on:
- query by example
- standard set of test cases to ship with spec
Posted by Xavier Sanchez on October 13, 2010 at 04:06 AM PDT #
I would like to have integration with dependency injection jsrs(330,299).
An standard response to things like Spring @Configurable annotation.
Posted by Ali Ebrahimi on December 01, 2010 at 06:40 PM PST #
+1 on:
- outer joins with conditions in an ON (WITH) clause
- enum support for legacy databases
Please let javax.persistence.criteria.Fetch be a javax.persistence.criteria.Join otherwise we are not able to express the following query with the criteria-api:
select distinct xx from Currency xx
left join fetch xx.companies comp
where comp=:comp
Posted by Valentino on December 06, 2010 at 12:38 AM PST #
What about API to check whether a collection is initialized or not in the case of lazy loading?.
Currently I need to duplicate a lot of named queries when I only need to add a single small condition. Defining them from the start as a criteria query would be an option, but this not as nice for readability as JPQL is.
Posted by henk on December 20, 2010 at 06:32 AM PST #
Public TCK.
Fetch groups.
Fluent typesafe API like QueryDSL.
In fact many things that JDO already offers.
Posted by Neil on December 22, 2010 at 04:59 PM PST #
- transactional like spring. Annotating a method would mean that transactions could be taken care of.
- auditing like envers
-.
- push back to change java as a core language to help the development of jpa.
..
-option to put named queries in a separate file from entity with default name entityql. This should include the criteria too. Named criteria should sit alongside names queries in the same class.
.
- ability of the jpa to deal with stored procedures and functions at they are always needed/used in projects whether we like it or not.
Posted by Alan B on January 12, 2011 at 07:35 PM PST #
+1 on:
Native SQL queries within Criteria queries
Fetch groups
Full metamodel information (all annotation information)
Posted by Gerald Glocker on March 02, 2011 at 08:08 AM PST #
Remove the constraint that Entities must have a field that represents the primary key of the database table. This can be completely transparent to the developer. It could be generated by the persistence provider or the persistence provider could manage it in another way.
In addition the persistence provider should handle the correct working of equals and hashCode. It is clearly defined by database semantic which entities should be equal. Why does the developer has to implement equals and hashCode again and again for every new entity.
Every existing persistence provider uses encapsulation of entities either by proxying or by byte-code-enhancement. It should be no problem to add id-field-handling and proper handling of equals and hashCode...
Posted by Arne Limburg on March 16, 2011 at 11:48 PM PDT #
Native Queries mapping for non-entity class
class Test{
Integer id;
String name;
}
em.createNativeQuery("select new id,name from test_table",Test.class) <-but not entity required
What do you think. This is in case when we have a special native queries and no entities for it ?
Posted by Tomasz Bożek on March 18, 2011 at 06:21 PM PDT #
Update.
I've just read the spec for 2.1
Improved support for the result type mapping of native queries
Maybe this is my request ?
Posted by Tomasz Bożek on March 18, 2011 at 06:26 PM PDT #
Not sure if this would fall under JPA or EJB but I'd like to see a way of specifying a default PU in the persistence.xml. eg:
<persistence ...>
<persistence-unit name="foo" ... />
<persistence-unit name="bar" ... />
<default-unit>bar</default-unit>
</persistence>
Then anytime a @PersistenceContext is injected without specifying a unitname the value of default-unit would be used. That would nicely solve this and make switching into a test context much simpler then it currently is.
Posted by NW on March 21, 2011 at 07:34 AM PDT #.
Rather than having annotated named queries a new jpql type should be created. The query should not be a string eg
Jpql findAddesses = select a from Address a;
This would mean the jpql would use the object to compile at compile time of the object.
Annotations are useful for hibernate but with the JPA core things like a Jpql type can be created in the language itself.
Posted by Alan B on March 29, 2011 at 09:18 PM PDT #
Please make sure, that method-validation (Bean-Validation 1.1) will be available for Entity-Beans out of the box.
Posted by Arne Limburg on April 09, 2011 at 05:13 PM PDT #
The biggest issue I have is real usable events; this means that in before update or insert event, or maybe even in the post events, it is possible to make changes to other entities..
Posted by Tbee on April 14, 2011 at 03:49 AM PDT #:
public interface IDAO {
public Object findById(Class<?> clazz, Object id,
FetchConfig[] fetchConfigs, LockMode lockMode);
public Object findById(Class<?> clazz, Object id);
public Object findByValue(Class<?> clazz, Restrictions[] restrictions,
FetchConfig[] fetchConfigs, LockMode lockMode);
public Object findByExample(Object exampleObject, String[] excludes,
LockMode lockMode);
public List<?> listByExample(Object example, FetchConfig[] fetchConfigs,
Restrictions[] restrictions, Order[] orders, int firstResult,
int maxResult);
public List<?> list(Class<?> clazz, FetchConfig[] fetchConfigs,
Restrictions[] restrictions, Order[] orders, int firstResult,
int maxResult);
}
public class FetchConfig {
private String table;
private FetchMode fetchmode;
public FetchConfig(String table, FetchMode fetchMode){
this.table = table;
this.fetchmode = fetchMode;
}
public String getTable() {
return table;
}
public void setTable(String table) {
this.table = table;
}
public FetchMode getFetchmode() {
return fetchmode;
}
public void setFetchmode(FetchMode fetchmode) {
this.fetchmode = fetchmode;
}
}
Posted by Albert Timel on April 15, 2011 at 01:11 PM PDT #
add EntityManagerFactory.getCurrentEntityManager() which retrieves the current transaction-scoped EntityManager (à la Hibernate SessionFactory.getCurrentSession()).
Posted by Xavier Dury on April 20, 2011 at 05:19 AM PDT #
Annotation for defining db index on fields (columns);
Posted by Ali Ebrahimi on April 23, 2011 at 04:58 PM PDT # | https://blogs.oracle.com/ldemichiel/entry/jpa_next_thinking_about_the | CC-MAIN-2015-27 | refinedweb | 2,628 | 62.58 |
Adobe Flash Professional version MX and higher
Adobe Flex
This technique relates to:
See User Agent Support for Flash for general information on user agent support.
The objective of this technique is to demonstrate how to invoke a scripting function in a way that is keyboard accessible by attaching it to keyboard-accessible, standard Flash components provided by the Adobe Flash Profressional authoring tool. In order to ensure that scripted actions can be invoked from the keyboard, they are associated with standard Flash components such as the Button component. The click event of these components is device independent. While the "CLICK" event is a mouse event, it is actually mapped to the default action of a button. The default action occurs when the user clicks the element with a mouse, but it also occurs when the user focuses the element and hits the space key, and when the element is triggered via the accessibility API.
This example shows a button that uses the MouseEvent.CLICK event to change its label. This event will fire both on mouse click and when the space key is pressed
Example Code:
import fl.controls.Button; import fl.accessibility.ButtonAccImpl; ButtonAccImpl.enableAccessibility(); var testBtn = new Button(); testBtn.label = "click me"; testBtn.addEventListener(MouseEvent.CLICK, clickHandler, false); addChild(testBtn); testBtn.x = testBtn.y = 10; function clickHandler(e) { e.target.label = "Thanks"; }
This approach is demonstrated in the working version of click event on a button. The source of click event on a button is available.
When a Flash Movie contains interactive controls, confirm that:
Standard Flash components are used for the controls
The controls use the "click". | http://www.w3.org/TR/2010/NOTE-WCAG20-TECHS-20101014/FLASH16 | CC-MAIN-2014-35 | refinedweb | 271 | 56.35 |
makes it even easier for you so you don’t even have to create an
EntityManager by yourself, this was usually the stuff that made my head spin when I just started Java development, but no more!
Project setup
Like every Spring boot project we start at start.spring.io. Enter the group ID and artifact ID you like and as dependencies I’m going to select the following:
- JPA: Dependency to use Spring Data JPA
- MySQL: MySQL JDBC driver for connecting to a database (you could choose another driver as well if you know what you’re doing!)
- Web: Dependency for creating web applications
- Thymeleaf: Template engine
Press the big Generate project button, unzip the archive and open the project in your favourite IDE. You’re now set to create some cool projects with Spring Boot!
Database
In this example I will be using a local MySQL database. In case you don’t have one, you’ll have to install it by yourself. What you also have to do is to create a MySQL database, if you’re on the MySQL CLI, you could use the following command:
CREATE DATABASE test;
To select the created database you use the following command:
USE test
Now the next step is that we’re going to create a table called superhero:
CREATE TABLE IF NOT EXISTS `superhero` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(32) NOT NULL, `first_name` VARCHAR(32), `last_name` VARCHAR(32), `good` bit(1), PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
And finally we’re going to insert some records:
INSERT INTO `superhero` (`name`, `first_name`, `last_name`, `good`) VALUES ('Superman', 'Clark', 'Kent', 1), ('Silver Banshee', 'Siobhan', 'McDougal', 0);
With the database up and running it’s time to write some code!
Entity
If you import the generated project into your IDE, you can immediately start adding classes and stuff, without having to do a lot of setup first.
The first thing I’m going to do is to create an entity that resembles the table I just created:
; } }
At first sight this class is a simple POJO with some fields and getters/setters for every field except for the ID. We don’t want people to allow updating the ID, so if you leave out the setter, there is no way you can edit the field. Obviously for instantiation you’ll have to find another mechanism, being either a builder or a constructor with the possibility to add the ID. Or in this case we have an auto-generated ID, so in theory you don’t need any way to set the field, though for testing you still might want to keep a constructor or a builder.
Anyways, next to the fields themselves there are also some JPA annotations. Above the class we can find two of them, called
@Entity and
@Table. With the first annotation we tell JPA that this class is an entity, while with the second one you tell which table it resembles. If the table name is the same as the class name, you could leave this one away.
Now, for each field we have the
@Column annotation to tell what column the field resembles. For the ID we also have the
@Id annotation and the
@GeneratedValue annotation which tells JPA how the ID is created.
Repository
In the early days you now had to create a DAO class which has methods for creating, updating, deleting and reading data from the table. With Spring Data on the other hand all you need is an interface that extends another interface. For example:
public interface SuperheroRepository extends JpaRepository<Superhero, Long> { }
So in this case we created an interface called
SuperheroRepository, extending Spring’s
JpaRepository, providing some generics for the entity and the type of the ID, being
Superhero and
Long. The reason we have these generics is so the return type and parameter types of the methods can be determined. For example, the
findOne() method should accept a parameter of type
Long and should return an entity of type
Superhero.
Controller
Now the final piece of code is to write a controller that retrieves all entities and returns a
ModelAndView to render those superheroes (and villains):
@Controller @RequestMapping("/superhero") public class SuperheroController { @Autowired private SuperheroRepository repository; @RequestMapping public ModelAndView getSuperheroes() { return new ModelAndView("superheroes", "superheroes", repository.findAll()); } }
All we have to do when we want to use the repository is to autowire it. By extending from
JpaRepository we already have some predefined methods. One of them being
findAll(). Now we can simply use that in our controller.
The view
If you followed my last tutorial you know that, if we use
ModelAndView in the way we did, the first argument is the name of the view (
"superheroes"), the second argument is the name of the model (
"superheroes" as well), and the third one is the model.
To create a view called superheroes, we have to go to the src/main/resources/templates folder and create a file called superheroes.html. Inside the file you can provide any HTML template you want, enriched with Thymeleaf syntax.
For our application I’m going to be using the following template:
<>
If you look at it, you would htink this is a normal HTML file. But if you look closely, you’ll see some special attributes starting with
th:. These attributes are part of Thymeleaf and allow you to provide an HTML template.
In this case we have the attribute
th:each to loop over all superheroes in the
${superheroes} model. Every time we loop over it we use the
hero model to contain the specific superhero and
status to contain metadata about the loop itself.
Now, for each table row, we show four cells. The first one contains a number that increases on each loop cycle. We can use the
${status.count} property for that.
For the other properties we will be using the
${hero.name} to retrieve the data of the name property of the
Superhero object, and for the other column we will be using the full name of the superhero, being
${hero.firstName + ' ' + hero.lastName}, concatenating both the
firstName and
lastName properties.
For the final column we’re using the
th:if and
th:unless attributes to show (or hide )data depending on a boolean condition. In this case we use the
good property of the
Superhero object to show a tick or a cross if the hero is actually good or evil (villain).
To show the tick or cross symbol we use the Glyphicons set, which is included in Bootstrap by default.
Setting some properties
Before we run our application we have to configure our application to be using the given database, and provide the credentials to connect to it. To do that you can open the application.properties filed inside the src/main/resources folder, or if you prefer using YAML, you can delete the properties file and create a file called application.yml in stead.
I prefer YAML because it shows how the properties are linked together hierarchically:
spring: datasource: url: jdbc:mysql://localhost:3306/demo username: root password: 123456 jpa: database-platform: org.hibernate.dialect.MySQLDialect
Using properties it would be:
spring.datasource.url=jdbc:mysql://localhost:3306/demo spring.datasource.username=root spring.datasource.password=123456 spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
Make sure you replace the properties to the correct details.
Testing it out
If you run the application now, and you visit, you should see the application in its full glory.
The entries we stored inside the database are displayed like they should be:
With that we made a simple application that connects to a database and shows you the data in a simple table. | http://g00glen00b.be/spring-data-jpa/ | CC-MAIN-2017-26 | refinedweb | 1,287 | 58.01 |
)
This does pretty much what
push does in a normal context,
it adds a singular version
$singular of a object to the plural object that the method is used on.
Grep($pattern, $field)
Somewhat similar to the usual
grep function,
but takes as argument a pattern to search for,
but not enclosed in slashes,
and which data field to look in.
Will return an object of the same class with the records that matched,
or
undef if there were no matches.
_load(%args)
As the underscore implies this is for internal use only!
It can do the hard work for subclasses of this class.,
these will be combined by logical AND.
By default,
exact matches of the
limit arguments will be used,
but you may also supply a
regex argument with an array containing the fields that should be fetched using case sensitive POSIX regular expressions. return an arrayref containing the data from the storage.
write_xml($doc, $parent)
To avoid bloating the parent class too much, this takes care of some specifics for plurals, but leaves most of the job to the parent class. Has a completely identical interface as the parent class, and can be called like it without further ado.
If an object of this class has had its element and/or namespace set with
xmlelement()/
xmlns()/
xmlprefix() respectively,
the individual entries will have the same element and/or namespace.
The save method is not yet reimplemented and may not work.
See AxKit::App::TABOO. | http://search.cpan.org/~kjetilk/AxKit-App-TABOO-0.52/lib/AxKit/App/TABOO/Data/Plurals.pm | CC-MAIN-2014-35 | refinedweb | 247 | 59.64 |
#include <row_iterator.h>
Ends performance schema batch mode, if started.
It's always safe to call this.
Iterators that have children (composite iterators) must forward the EndPSIBatchModeIfStarted() call to every iterator they could conceivably have called StartPSIBatchMode() on. This ensures that after such a call to on the root iterator, all handlers are out of batch mode.
Reimplemented from.
Start performance schema batch mode, if supported (otherwise ignored).
PFS batch mode is a mitigation to reduce the overhead of performance schema, typically applied at the innermost table of the entire join. If you start it before scanning the table and then end it afterwards, the entire set of handler calls will be timed only once, as a group, and the costs will be distributed evenly out. This reduces timer overhead.
If you start PFS batch mode, you must also take care to end it at the end of the scan, one way or the other. Do note that this is true even if the query ends abruptly (LIMIT is reached, or an error happens). The easiest workaround for this is to simply call EndPSIBatchModeIfStarted() on the root iterator at the end of the scan. See the PFSBatchMode class for a useful helper.
The rules for starting batch and ending mode are:
The upshot of this is that when scanning a single table, batch mode will typically be activated for that table (since we call StartPSIBatchMode() on the root iterator, and it will trickle all the way down to the table iterator), but for a join, the call will be ignored and the join iterator will activate batch mode by itself as needed.
Reimplemented from RowIterator.
The default implementation of unlock-row method of RowIterator, used in all access methods except EQRefIterator.
Implements RowIterator.
Reimplemented in SortFileIterator< false >, SortFileIterator< true >, SortBufferIterator< false >, and SortBufferIterator< true >. | https://dev.mysql.com/doc/dev/mysql-server/latest/classTableRowIterator.html | CC-MAIN-2020-24 | refinedweb | 304 | 52.39 |
2D games using Silverlight - implementing the game loop
This article shows how to create a games loop in a Microsoft Silverlight application, which once created on Windows Phone 7, should be able to run with minimal modification on Windows Phone 8 and Windows 8 devices. It is the first article in a series which will show how to create a complete working game (a clone of the classic Arkanoid game).
Windows Phone 7.5
Introduction
The recommendation for Windows 8 and Windows Phone 8 is that new apps be written in the new Metro style app so they can run largely unchanged across both platforms, while games should be written using DirectX and C++ to minimize the porting effort. However if you want also to target Windows Phone 7 with your application then using DirectX and C++ is not an option.
This article outlines an option to allow you to create games that are capable to run on all three platforms using Microsoft Silverlight. Silverlight is not a game framework but it is suitable for game creation since it is Rich Internet Application framework. This might be appropriate for simple games where you need to target all three platforms and investing in both XNA and DirectX/C++ is more costly than maintaining a single codeline.
Microsoft Silverlight does not guarantee the frame rate (in the same way that XNA does) and hence for some games and on some platforms the performance may differ; there may also be other limitations. However for the game used in this example we haven't run into any issues on any current Windows Phone 7 devices, including those with reduced memory and CPU.
For any game we need :
- Game loop
- Sprite animation
- Collision detection
This article explores the first part of the problem - creating a game project application skeleton with a game loop. The second article in the series will extend the application with more objects and explain object collision detection.
Game project
The game project contains source code and some related information or this article. Unfortunately the project does not contain installation package for a quick demo because Windows Phone does not allow application side loading. Please check supplementary application project to how to build and run the application on your device.
If you don't have a device and Microsoft developer id you can still test the code using the device emulator in the SDK. Note however that the emulator cannot simulate accelerometer changing for users to play the game. You can emulate device shaking only, but this is not a good mechanism for game control.
Note: Good news for students - you can get developer id for free of charge!
Please check this on how to obtain Microsoft developer id and setup development environment. Also Useful links: Windows Phone development
Implementation & design
Game rendering loop
The game rendering loop needs to be run in such a way that the app remains responsive to user input. In this example we hook into the CompositionTarget.Rendering . event inside Windows Presentation Framework's (WPF) rendering loop. This event is fired once each time WPF decides to render a frame. This is by far the simplest solution, and appropriate for this case where we have fast moving objects with little position calculation (accelerometer data).
Other alternatives that were considered were to use timer tick animation or a completely separate thread. Timer tick animation would work, but results in "jerky" (non-smooth) movement (see StoryBoard class for more information on timer based animation). Using a separate thread is also a good approach, but the complexity is not justified in this case because the amount of calculation required is trivial.
When creating the game physics engine (covered in the next article) we will consider using a worker thread or StoryBoard class.
Target device constraints
We are targeting the Windows Phone device with the poorest specification: Lumia 610. This device lacks most of sensors and has memory limit of 256 Mb. As a result we cannot use the Motion class, but instead must use the accelerometer sensor. The accelerometer works badly in all directions except when device is in portrait mode.
Code walkthrough
Examine the following structure in the project source code:
- Main application (MainPage.xml, MainPage.xaml.cs)
- Game board container (BoardControl.xml, BoardControl.xaml.cs. Also it contains components below)
- Game loop (function void gameLoopHandler(object sender, EventArgs e) )
- Controlled object (BoardControl.xml, XAML definition <Rectangle Name="bouncer" ...../>)
- in BoardControl container find line that register rendering handler:
- Then find the handler implementation:
void gameLoopHandler(object sender, EventArgs e)
{
if (state != STATE.RUNNING)
return;
handleAccelerometer(sender, e);
}
- Note, function handleAccelerometer(sender, e) only reads the class member variable Vector3 acceleration for accelerometer reading. This variable is written in separate thread via void accelerometerDataChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e) handler.
- Again to subscribe for accelerometer's data reading there is line:
- all the rest of the code implementation is related to the application auxiliary supporting as suspending gameplay when control is out of the screen (note we use Pivot control as the main page) and resuming it when it is visible again.
- the last thing that may look wierd to you is suppression possible exceptions in onLoad handler. That is for WPF Designer. WPF Designer panel appears on the right side of XAML document opened in Visual Studio. The panel displays live-view of your page by running virtual machine. WPF Designer can through exception while your User Control instantiation even your code will work fine on device or emulator. There is a guide from Microsoft about Troubleshooting WPF and Silverlight Designer Load Failures. The main rule is: not place anything that might throw an exception into class constructor. And that is onLoad handler for. But still my preview is broken on accelerometer instantiation - that is why exception handling is here.
Try it. Type accelerometer.CurrentValueChanged + and when you start typing = sign to assign a handler, see pop-up hint allows you to generate the handler code
Profiling performance
The approach outlined in this article hooks into the CompositionTarget.Rendering event, which provides no guarantee on the frame refresh rate. To measure the impact of platform on refresh rate we've added a refresh rate measurement in the upper-right corner (displays milliseconds between frames).
Measurements using this approach show that the screen refresh rate on a PC desktop browser is about 16 milliseconds, while on Nokia Lumia 610 the rate is about 48 milliseconds. As result if you do not adjust object movement to current screen refresh rate, movement is considerably slow on Lumia 610.
The screen rate measurement is a part of the physics engine implementation that we explain in our next wiki article.
Running the game in a browser
Microsoft Silverlight apps can run on Windows Phone 7.X device and on a PC desktop browser with minimal modifications. However there is no sensor support in a PC desktop browser so you should implement different user input control when the application is to be run embedded in a browser.
You will also have to modify code to exclude .NET assemblies that exist on Windows Phone 7 but do not exist for Silverlight desktop applications. Fortunately .NET supports conditional compilation so you can target at least two platforms, Windows Phone 7 and desktop application with single code base. Please check supplementary application project for details.
Porting to Microsoft Visual Studio 2012
Microsoft Visual Studio 2012 development tool does not include Windows Phone 7 or (Zune Phone) target. However you can run your WP7 Silverlight application on Windows 8 device with minimal modification -- only renaming namespaces and the project rebuilding is required. To build your project for desktop browser you need to install Microsoft Visual Studio Express 2012 for WEB. After installation Microsoft Visual Studio Express 2012 for WEB, original Microsoft Visual Studio Express 2010 for Windows Phone may get broken but you can use Microsoft Expression Blend 4 without debugging facilities though. Microsoft Expression Blend 4 comes with Windows Phone 7 SDK for free.
Summary
This article has shown how to create a games loop by hooking into the CompositionTarget.Rendering event. The next wiki article in the series is 2D games using Silverlight - Collision detection implementation. | http://developer.nokia.com/community/wiki/index.php?title=2D_games_using_Silverlight_-_implementing_the_game_loop&oldid=178445 | CC-MAIN-2014-10 | refinedweb | 1,369 | 52.09 |
In order to explore object marshalling and unmarshalling possibilities in the context of distributed semantic web services in which various RDF-based and non-RDF SOAP solutions may proliferate, an example web services architecture is shown in this report.
The architecture aims to demonstrate how an RDF-based web service (in this case we happen to use Sesame for the RDF service 'backend') might be combined with SOAP (in this case we happen to use Apache Axis for the RDF service's SOAP 'frontend') in order to serialise object data. In the examples, the service's WSDL is used in order to auto-generate client-side stubs so that we may demonstrate the ease with which some client on the network (whether it be "RDF-savvy" or otherwise) may consume such a service.
We also show how soap-encoded data may be transformed (via an XSL stylesheet) to RDF data and suggest scenarios where this may be useful.
The example dataset we use is very small and chosen merely to demonstrate how object data may be serialised as SOAP encoded data, for exchange on the network. We example how SOAP encoded data may be transformed 'back' to RDF data (the "round trip") in order to show the relationship between the two data models. However, we do not attempt a full comparison of the data models: we do not provide a transformation from RDF to SOAP for example, hence we do not consider the serialisation of arbitrary RDF data via the soap data encoding syntax. Instead we aim to demonstrate some potential for using the SOAP data encoding for standardised data exchange in a network environment in which both semantic web services and more traditional web services reside.
We note that at the time of writing this report, Document/Literal message styled SOAP Web Services have gained industry support over RPC/Encoded services (or any other combination). We give a brief outline of the impact of this document/literal versus RPC/Encoded debate for SOAP services at the end of Section 1.
In Section 1 of this report we give an overview of our chosen hypothetical illustration of a semantic web service scenario. We present a diagram of this example web service architecture. Then, in section 2 we explain our example architecture for a Semantic Web Service at a more technical level. In section 3 we explain how we have opted for a generic approach with which to integrate Apache Axis and Sesame software, in order to run trials. We give our example data and configurations used and and we hope to make the given sample implementation downloadable via a link on this page by the close of the project. In section 4 we briefly discuss the Soap data model and the RDF data model - transforming from the former to the latter.
Please note that in following the explanation of the above diagram, the reader is referred to the Web Services Architecture, W3C Working Draft (August 2003) for certain equivalent concepts - for example the client side view we discuss here corresponds to the Requestor Agent in that report, the Server side view we discuss corresponds to the Provider Agent.
We have adopted Apache Axis as the software for both the client and server sides. Axis is Java software (with a C++ implementation also under development at the time of writing), designed around handler chains which are configurable and allow the developer to write any handlers needed in order to process the incoming and outgoing SOAP messages. A special sort of Axis handler is a "provider" - a pivot handler representing the handling of data at the point at which Axis actually interacts with the service itself. In the example service described below we use the Java:RPC provider that is built in to Axis. This provider aids the marshalling and unmarshalling of objects between Java and the SOAP encoded data model. So long as it is possible/required to derive object-oriented data from RDF graphs (we transform tabulated result sets into java beans in our examples) then this standard Axis Java:RPC provider may be used 'out of the box', meaning that no custom handler has to be written. Specifically, we demonstrate that a simple Axis configuration is possible in order to implement an RDF-based SOAP web service quickly - no custom serialisers need be written, Axis' own "bean serialisers" are sufficient.
The Axis handlers on the client side (left hand side in above diagram) can be thought of as the mirror image of the ones on the server side. The client side initiates RPC transactions in order to consume some web service on the network - the service is represented on the right hand side in the above diagram. The service itself is a queryable data store - where the data is stored as RDF. We happen to have used Sesame as the RDF database. The fact that the service uses an RDF database is 'invisible' in terms of its exposure on the network - it is fronted by a SOAP server which can handle the marshalling of objects via a simple Axis<->Sesame bridging class (which we discuss further on).
Data returned by the SOAP server is encoded according to the Soap Encoding specification (see). On the client side, it is very simple to use the service's WSDL in order to configure the built-in Axis handlers to unmarshal soap-encoded objects returned from the service in response to RPC requests.
What happens to these objects next is dependent on what the client side application requires them for. For example, as Axis can unmarshal complex objects (it can generate javabeans from a service's WSDL and uses these to map from elements in XML or SOAP encoding format), these can immediately be used within some java application for example (which is the case for 'e.g. B' in the diagram above). Where there are non-java (or non-C++) API's on either the client or server sides, software other than Apache Axis is required, but the principles remain the same in terms of marshalling and unmarshalling objects.
In a scenario where perhaps the client side is being used as part of some aggregator (semantic) web service, it is possible to directly transform the soap encoded data to RDF (via XSLT) in order to add it to an RDF datastore, say ('e.g. A' in the diagram above). Scenarios where this can be useful are discussed further below. We give a sample XSLT transformation in section 3.
We note that the scenarios consider here are within the context of stateless connections only.
We give here an example high-level scenario to illustrate the potential of using the SOAP data encoding syntax for a web services architecture as outlined above.
Suppose I wish to purchase a house in the South West of the UK. I may be interested in various data sets: houses for sale in the area (obviously), according to price band and location, plus environmental information (such as pollution factors, tendency for landslides, flooding and so on), plus also schools information on which I can base decisions regarding my children's education (government Offsted reports, or schools' own web sites for example). It currently tends to be the case that no single online service will provide such information. So these data repositories exist in the closed worlds sense.
However, if that information is available via the network via SOAP services then I can use a SOAP client to query these sources. I should be able to aggregate the results using the unique identifiers these sets of information have in common - postcodes. I may well use RDF-based tools to assist aggregation at my end, with inferencing capabilities to support querying over the aggregated data (perhaps using OWL for example in order to link equivalent terms for the cases where various data providers have used different terms for "number of bedrooms" and so on).
In a perhaps more globablly "highly evolved" - semantically - version of the same context, a data provider on the web - an estate agent's online service for example - might in fact choose to use an "intelligent RDF backend" to aggregate objects in order to centralise access to some of these resources. By doing this, a data provider thereby enhances its business services by allowing end users (or other services - maybe an online jobs recruitment service) a central point to access distributed information, rather than having to develop their own aggregator clients.
The main advantage of using RDF to store the data in the backend database is that, whilst a range of content providers may publish data all related to a similar domain, their choice of data modelling will naturally vary from provider to provider. The RDF standard (plus OWL for example) makes it simpler to aggregate such related but heterogeneous data. It provides the basis for a simple inferencing layer, meaning that for example my aggregated data store can be simply designed to 'know' that a "semi-detached bungalow" and a "detached bungalow" are both sub-classes of a type called "bungalow", which itself is a sub-class of a type called "residential property" and so it may continue. Or that resources which one content provider may classify as "flats/apartments" are the same as what another content provider classifies as "apartments or flats". And so on, this system being fully extensible and flexible in RDF, meaning that not only is it quite 'clever' in terms of the sorts of questions that can be asked of and answered by it, but it also may be maintained with less overheads in terms of human effort than when using, say, a traditional relational database approach. It will also be the case that even if a data provider should add new attributes to the objects that they are modelling, when the objects are unmarshalled at the client end they will not break the service's model used for aggregating the data (RDF resources are allowed arbitrary, non-reserved properties).
The main advantage of using SOAP as the transportation protocol for such objects is that the SOAP specification supports the SOAP encoding data model which promotes the standardised serialisation of arbitrarily complex objects (allowing multi-reference and cyclic data structures). And this remains consistent in either an RDF-aware or RDF-non-aware context.
Industry support for SOAP messaging styles has recently - over the lifetime of the SWAD-e project - swung in favour of Document/Literal. In this section we take a brief look at the place of SOAP encoding in the Soap 1.2 specification and also its absence in the WS-I Basic Profile. We consider some of the arguments against using SOAP encoding for Web Services and note the potential for using document/literal styled SOAP Web Services for the Semantic Web.
The place of SOAP Encoding in Soap 1.2
Having been in section 5 of the Soap 1.1 specification, the SOAP encoding is revised and moved to an adjunct section in the SOAP 1.2 specification (see). Here it states "This encoding MAY be used to transmit data in SOAP header blocks and/or SOAP bodies. Other data models, alternate encodings of the SOAP Data Model as well as unencoded data MAY also be used in SOAP messages".
The WS-I Basic Profile The Web Services Interoperability Organization, formed in February 2002 (and led by Microsoft and IBM), published the Basic Profile 1.0 specification in August 2003. The specifications covered by the Basic Profile include SOAP 1.1, WSDL 1.1, UDDI 2.0, XML 1.0 and XML Schema, with the aim of promoting Web services interoperability. With regards to soap encoding, the specification says ." And it goes on to specify that this attribute must not be used.
It appears that the argument against using soap encoding is "why bring another sort of encoding into the arena when we already have XML and XML namespaces?". However, semantic web initiatives frequently point to the clear gap left by XML in a context where it is important to maximise semantic coherence at machine-to-machine level across distributed web services. In contrast to XML, the SOAP data encoding allows for multi-referencing on a grand scale and, when augmented with RDF, RDFS and OWL, opens up the space occupied by web services such that the links between large repositories of related but heterogenous data may be exploited in an extensively automated and arguably efficient fashion. It is hard to see how such links can be managed sensibly using the XML tree structure (see also a recent article from a non-semantic web context that also discusses this issue - "RPC/encoded, RPC/literal, document/literal? Which one?" ). A directed graph structure such as specified by the SOAP data encoding offers plenty in terms of managing the way information may be merged on the network - with RDF-based layers making it usefully 'meaningful'.
None-the-less, RDF has its own RDF/XML syntax and parallel SWADE work is reviewing the relationship of RDF/XML to XML, for example looking at the development of a normalised RDF/XML. This means that, should a SOAP-based web service require to be document/literal based, it might then be configured to offer SOAP message responses where the SOAP message content is encoded in RDF/XML. Schemas - both RDF and XML schemas - might then be associated with this same content (via namespaces) to permit either or both of the XML processing and RDF processing alternatives on the client side. Again, this promotes a relaxed situation in which both RDF-aware and non RDF-aware services may share out data to RDF-aware and non RDF-aware consumer applications equally.
It is recommended that work that follows on from this workpackage look more closely at just this sort Document/Literal option. In the example architecture described below, scenarios are limited by the sort of data structures that can be handed over from Sesame (the RDF database) to the Axis server software (for creating SOAP data encoded SOAP body content). Only Sesame's tabulated data structures for result sets can be very easily mapped to Java beans for straight forward consumption by Axis' bean and array serialisers. RDF result sets encoded in RDF/XML would require a custom serialiser to be written for Axis - one that would handle a complete RDF to SOAP mapping. We have not conducted full investigations in this respect, but such a feature would be required to handle arbitrary RDF structures. At this point the utility of a Document/Literal options becomes apparent again.
This section takes a quick look at the data being exchanged over the network in the specific scenario we have produced for this report: how that data originates, how objects are "preserved" during transportation, and what can be done with the data on the receiving end as it were.
The exampled web service architecture is obviously not intended to be representative of the scale and capabilities of current or future web services, but simply to illustrate the extent to which SOAP-to-RDF mappings are possible, and indeed useful in the context of web services. In other words, this is merely a proof-of-concept demonstration.We begin with another diagram, similar to the more general overview diagram above, but specifically labelled with the java classes and stylesheets used in our example scenario.
In our example scenario the SOAP, RPC-Encoded style service that we have called "rubysoapservices", happens to hold a small amount of data about Ruby software products. These software products are encapsulated as what we have named "rubyinfo" objects which essentially are objects that have "product", "owner", "update" and "category" properties - themselves objects, with further properties such as "category_major", "category_minor" etc. This is best explained quickly with the diagram from this workpackage's first report:
Please take a look at the WSDL we have for our example (localhost) Ruby Soap Service. You will see that the "request" message name is rubyQueryRequest and that it contains one part, (not named - we could have more sensibly given this a generic name such as "query_expresssion", say) of type "xsd:string".
<wsdl:message <wsdl:part </wsdl:message>
Here is an example request message in which we see that the single string part to the RPC message body is in fact an RQL query (for information on the RQL language as interpreted for Sesame, see). This soap message specifies the encoding style to be used (soapenv:encodingStyle=""). And the RQL query effectively says:
"give me all objects that have PRODUCT_NAME, VERSION etc properties, using the namespace ruby =.
We have permitted the request message to contain a single string parameter deliberately so as to allow the testing of different query expressions on the remote service. We could of course specify several seperate queries (for e.g. asking all ruby information objects with product_name value is so-and-so) in the WSDL . Normally we would deploy the service so as the parameter would be more informatively named than simply "arg1" (the Axis default).
This response message effectively shows that the soap service (i.e. where Axis "talked" to Sesame) returned an array of 3 RubyInfo objects ("rubyQueryReturn xsi:type="soapenc:Array" soapenc:arrayType="ns1:RubyInfo[3]" xmlns:soapenc="").
Each of these objects is referenced by id's and contain further properties, ruby_category, ruby_owner, ruby_product and update. Each of these reference further objects (except in the case of update which is just a string value). You will see that these objects correspond to the types given in the service's WSDL, which also indicates that the response message will contain an array of ruby info objects:
<wsdl:message <wsdl:part </wsdl:message>
For more information, see also an analysis by Marc Hadley (who works for XML Technology Centre at Sun Microsystems, and is co-editor of the SOAP 1.2 specification) at
We provide a Stylesheet for transforming soap encodings from the SOAP 1.1 specification to that of the 1.2 specification (Author: Max Froumentin). After transformation, the body of the above response message looks like this:
The stylesheet we have developed (Max Froumentin and Nikki Rogers) for this transformation is soap_to_rdf.xsl. It is not completely generic - the first element in the soap body to be treated as an 'edge' has to be identified as noted in the stylesheet. Also the choice of name for SOAP accessors that have 'id' attributes is arbitrary and for Axis is "multiRef". Therefore these multiref accessors are matched as part of the transformation in order to be mapped to RDF typed elements.
When applied to the above response body data, it produces:
You may run both the original data uploaded to sesame and the above RDF (obtained from a transformation of the SOAP response body's data) through the online RDF validator at to compare triples that both graphs produce. They are simliar with a couple of differences.
Installation of axis and sesame is quite a lengthy process, and we hope to wrap up what we have put together for this report as a downloadable war. file with an ant build to assist installation and configuration. In the meantime, we provide a summary and some more detailed instructions to supplement those available from the Axis and Sesame websites. We also refer the reader to outputs emerging from related work conducted under SWAD-Europe workpackage 8 which includes a continued exploration of architectures for a semantic web service.
Obtaining Sesame
See the Sesame server installation instructions which describe how the downloads for a sesame installation. Briefly they are:
Sesame and the servlet container
As described in the sesame installation instructions, you will need to place the extracted sesame.war file in a directory (called, say 'sesame') in your [TOMCAT_DIR]/webapps/ directory. And you will need to place the appropriate jar files (the jdbc jar and xerces.jar, soap.jar, icu4j.jar and jena.jar that are found in the sesame distribution) in [SESAME_DIR]/WEB-INF/lib/ (see.)
To configure a fresh installation of Sesame you can copy the example sesame configuration file at [SESAME_DIR]/WEB-INF/system.conf.example. to [SESAME_DIR]/WEB-INF/system.conf. Then you will need to edit this file for the correct path to the directory where Sesame is installed on your machine, and for a new SESAME_PASSWORD. Again, this is all detailed in the Sesame installation instructions.
Uploading the Ruby test data to Sesame
Similarly to as described in the Sesame installation instructions, you can:
C:\mysql\bin>mysql -u sesame -p Enter password: ****** Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 74 to server version: 3.23.54-max-nt Type 'help;' or '\h' for help. Type '\c' to clear the buffer. mysql> CREATE DATABASE rubyinfodb -> ; Query OK, 1 row affected (0.01 sec) mysql> GRANT ALL ON rubyinfodb.* TO sesame; Query OK, 0 rows affected (0.01 sec) mysql> QUIT Bye C:\mysql\bin>
<repository id="mysql-rubyInfo"> <title>MySQL Ruby Products Information DB</title> <sailstack> <!-- SyncRdfSchemaRepository prevents multiple concurrent transactions and reads during a transaction --> <sail class="nl.aidministrator.rdf.sail.sync.SyncRdfSchemaRepository"/> <sail class="nl.aidministrator.rdf.sail.sql92.MySQLSail"> <param name="jdbcDriver" value="com.mysql.jdbc.Driver"/> <param name="jdbcUrl" value="jdbc:mysql://localhost:3306/rubyinfodb"/> <param name="user" value="sesame"/> <param name="password" value="sesame"/> </sail> </sailstack> <!--Access Control List can contain zero or more 'user' elements--> <acl worldReadable="true" worldWritable="true"> <user login="testuser" readAccess="true" writeAccess="true"/> </acl> </repository>
A standalone test of Sesame over http
It is possible to do command-line testing of Sesame (over http) via the SesameClient.java file ( SESAME_SOURCE_DIRECTORY\nl\aidministrator\rdf\client\SesameClient.java). We have adapted this client to form the "bridge" between Axis and Sesame as described below. The adapted file is SesameTestStandalone.java. Call this class from the commandline
It issues a hardcoded query against the sesame database "RubyInfodb" in which we uploaded data in order to test we can soap<->rdf roundtrip. All matching RubyInfo "Objects" are returned using Sesame's tabulated form for result sets. The result set is then mapped to javabeans in a proprietary way.
The query is String query = "select X, PRODUCT_NAME, VERSION, STATUS, HOMEPAGE, DOWNLOAD, LICENSE, DESC, EMAIL,OWNER_NAME, OWNER_ID, CATEGORY_MAJOR, CATEGORY_MINOR from {X} ruby:ruby_product . ruby:product_name {PRODUCT_NAME} , {X} ruby:ruby_product . ruby:version {VERSION} ,{X} ruby:ruby_product . ruby:status {STATUS}, {X} ruby:ruby_product . ruby:homepage {HOMEPAGE}, {X} ruby:ruby_product . ruby:download {DOWNLOAD}, {X} ruby:ruby_product . ruby:license {LICENSE}, {X} ruby:ruby_product . ruby:desc {DESC}, {X} ruby:ruby_owner . ruby:email {EMAIL} , {X} ruby:ruby_owner . ruby:owner_name {OWNER_NAME} , {X} ruby:ruby_owner . ruby:owner_id {OWNER_ID} , {X} ruby:ruby_category . ruby:category_major {CATEGORY_MAJOR} , {X} ruby:ruby_category . ruby:category_minor {CATEGORY_MINOR} using namespace ruby =";
The query string can be adapted according to RQL conventions. The beans required are RubyInfo.java, Category.java, Owner.java Product.java.
Obtaining Axis
We installed Axis as described in Axis' installation instructions and also in the README that comes with the Axis download. REQUIRE: We used Ant Version 1.5.1 in order to use the build for Axis. We placed the Axis classes from the build in TOMCAT_DIR]/webapps/ in a directory we have called 'swadWP4". We performed the "validate" and testing tasks as required for an Axis installation.
WSDD
The appropriate classes for the service (RubySoapServiceTest.java, RubyInfo.java, Category.java, Owner.java Product.java) are placed in the TOMCAT_DIR/webapps/swadWP4/WEB-INF/classes directory, and the appropriate jar files (example for sesame and the sesame client) in the lib directory for this webapp.
A WSDL file for the service can be authored "by hand", or it can be auto-generated by the Axis java2wsdl tool if run in the same webapp directory. For example:
java org.apache.axis.wsdl.Java2WSDL -o semwebserv.wsdl -l"" -n "urn:semwebservices" -p"semwebservices" "urn:semwebservices" semwebservices.SesameServiceTest
Where:
In order to deploy a service via Axis it is necessary to create a WSDD file as mentioned earlier. This can be authored "by hand", or from a temporary folder we can now run the Axis wsdl2java tool - with the server-side switch - on the service's classes. This will generate the deploy.wsdd and undeploy.wsdd files (and also server-side skeletons which in fact we do not use in this example). The wsdd generated will look something like this
!-- Use this file to deploy some handlers/chains and services --> <!-- Two ways to do this: --> <!-- java org.apache.axis.client.AdminClient deploy.wsdd --> <!-- after the axis server is running --> <!-- or --> <!-- java org.apache.axis.utils.Admin client|server deploy.wsdd --> <!-- from the same directory that the Axis engine runs --> <deployment xmlns="" xmlns: <!-- Services from RubySoapServiceTestService WSDL service --> <service name="RubySoapServiceTest" provider="java:RPC" style="rpc" use="encoded"> <parameter name="wsdlTargetNamespace" value="urn:rubysoapservices"/> <parameter name="className" value="rubysoapservices.RubySoapServiceTest"/> <operation name="rubyQuery" qname="operNS:rubyQuery" xmlns: <parameter name="in0" type="tns:string" xmlns: </operation> <parameter name="allowedMethods" value="rubyQuery"/> <parameter name="scope" value="Session"/> <typeMapping xmlns: <typeMapping xmlns: <typeMapping xmlns: <typeMapping xmlns: <typeMapping xmlns: </service> </deployment>
As you can see from this file, we use the Axis built in RPC provider, with a SOAP data-encoded format for the response message body. The deploy and undeploy.wsdd files in the servlet container (i.e. tomcat in our case) with the service's java class files. In the same directory it is now possible to deploy the service using Axis' AdminClient tool from the command line, like this:
java org.apache.axis.client.AdminClient -l deploy.wsdd
Having deployed the service it should now be possible to access the WSDL for the service from the localhost machine, say, thus:
You can access the service:
In the above examples for a semantic web service we give an XSLT transformation - soap_to_rdf. This transformation may be used in the implementation of a Semantic Web Service which follows the design outlined in the previous sections of this report. Whilst in Section 1 we provide a discussion of the merits of the soap data encoding syntax in providing a serialisation option for RDF data over SOAP, we conclude that more research in this area is required.
In particular we highlight the following issues for further discussion:
The architectures for a SOAP-based "Semantic Web Service" considered here are revisited and extended in the work under SWAD-Europe workpackage 8 which includes the development of a prototype Thesaurus Web Service for the Semantic Web.
1. Sesame from openRDF.org
2. Apache Axis for WebServices.
3. Web Services Architecture, W3C Working Draft (August 2003)
4. Web Services Interoperability Organization and the Basic Profile.
5. Article: "RPC/encoded, RPC/literal, document/literal? Which one?", Russell Butek Software Engineer, IBM, 31 October 2003
6. SOAP 1.1 Specification.
7. Resource Description Framework (RDF), Model Primer and Syntax Specification. | http://www.w3.org/2001/sw/Europe/reports/sw_soap_design_report/ | CC-MAIN-2016-07 | refinedweb | 4,467 | 51.18 |
Graphs are defined in XML files, then imported into MEM. The new custom graph is displayed in the Graphing category on the Advisors page.
For an example of how to create a graph, see Section 30.1.9, “Creating a New Graph: An Example”.
The XML elements for creating a graph are as follows:
version
The version number of the graph. Generally only important with the bundled graphs, and is only used internally.
uuid
The unique id of the graph. Each revision (version) requires a new uuid, which is only used internally.
name
The visible graph name, which is displayed within the graph listing. Note: graphs are sorted alphabetically.
frequency
Optionally define the frequency for the graph, which defaults to 1 minute. May use seconds, minutes, hours, and days.
rangeLabel
The Y-axis range label. For example, a graph about disk space usage may use
MB.
series
Each series contains a label and an expression. The label is the visible name of the series, and the simple expression defines it.
variables
Each variables definition contains a name, instance, and dcItem element. The instance defines what data the graph displays, and each dcItem element contains a nameSpace, className, and attribName:
nameSpace
Namespace (type) of the data collection item.
className
Class (namespace type) of the data collection item.
attribName
Attribute name of the data collection item. | https://dev.mysql.com/doc/mysql-monitor/8.0/en/mem-creating-graphs-overview.html | CC-MAIN-2019-22 | refinedweb | 224 | 60.21 |
I'm trying to come up with changes for the "default" emails that come from the help desk. I want to add thins like "Your ticket has been assigned to xxxxxxxxxx, he will contact you soon to go over the details of your issue" instead of "Your ticket has been assigned to xxxxxxxxxx" - seems kind of dry.
My problem is that I see the email templates...I've customized that nicely, now I need to find the conditional email messages (ticket assigned, ticket closed, etc.)
Where do I find that? I've looked in as many hiding places as I can find...
Thanks,
Tom
May 11, 2012 at 8:46 UTC
You're so close!
All actions are in the same email template. Please scroll through the text until you find the response conditions and the verbiage is right next to it.
6 Replies
May 11, 2012 at 8:46 UTC
You're so close!
All actions are in the same email template. Please scroll through the text until you find the response conditions and the verbiage is right next to it.
May 11, 2012 at 8:52 UTC
Yep, all the actions are done using the single template. You just need to add in the appropriate logic for Spiceworks to create the message.
More information can be found here: http:/
May 11, 2012 at 10:01 UTC
OK - I'm stuck. I see the email template, but there is only one template. I don't see anywhere in the code where something like "if event = ticket-closed" and there isn't multiple choices for the templates that are being generated...
May 11, 2012 at 10:15 UTC
There is only on template to edit (actually, two... one for HTML and one for Plain Text, but this is swtiched via the tab at the top).
Within the template is where you build the logic for what you are looking for it to do. So for your example of the closed ticket reply, the block would be:
{% if event == 'ticket-assigned' %}
Your ticket has been assigned to {{ticket.assignee.full_name}}., he will contact you soon to go over the details of your issue.
{% endif %}
I would copy/paste the code from the SW editor to something with more formatting and find capabilities, like Notepad++. Then you can search for that block and edit it there.
May 11, 2012 at 10:21 UTC
I've been looking for the code in the HTML only...there are no % if event... language in the .html. I checked the plain text and that is where it's all located.
Finally! Whew.
May 11, 2012 at 10:28 UTC
There should be some %if...% events in the HTML version, unless you eliminated them while modifying. You can certainly add them back in as you need though. Having them just in the Plain Text won't help for messages received as HTML. | https://community.spiceworks.com/topic/224486-help-desk-email-responses | CC-MAIN-2017-13 | refinedweb | 485 | 82.24 |
It's a simple program. You first type your favorite movie, then your favorite game,
if your favorite game and movie matches with the programmer's favorites,
you then see a message "Wow! It seems we have so many things in common.".
It works fine, but I'd like to know if i coded this correctly, or if there's anything
that should be done to make the code cleaner.
Code:#include <iostream> #include <cstring> using namespace std; int main() { char fvrtMovie[100]; char fvrtGame[100]; int points = 0; cout<<"Type your favorite movie: "; cin.getline(fvrtMovie,100); cout<<"\n\n"; if(strcmp(fvrtMovie,"Godfather") == 0 || strcmp(fvrtMovie,"The Godfather") == 0) { cout<<"Really? That's my favorite movie, too!"; points++; } else { cout<<"Hmmm, I see..." ; } cin.get(); cout<<"\n\nNow, what's your favorite game? "; cin.getline(fvrtGame,100); if(strcmp(fvrtGame,"Street Fighter") == 0) { cout<<"\n\nThat's your favorite game, too?"; points++; } else { cout<<"\n\nOh, "<<fvrtGame<<". I see..."; } if(points >= 2) { cin.get(); cout<<"Wow! It seems we have so many things in common."; } cin.get(); return 0; } | http://cboard.cprogramming.com/cplusplus-programming/128907-my-first-program.html | CC-MAIN-2014-41 | refinedweb | 181 | 78.14 |
...one of the most highly
regarded and expertly designed C++ library projects in the
world. — Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
Distributed under the Boost Software License, Version 1.0.
Table of Contents
bind(f, ...)and
bind<R>(f, ...)?
bind(f, ...)
bind<R>(f, ...)
constin signatures
using boost::bind;
...in signatures treated as type
bind
__stdcall,
__cdecl,
__fastcall, and
pascalSupport
visit_eachsupport
boost::bind is a generalization of the standard
functions
std::bind1st and
std::bind2nd.
It supports arbitrary function objects, functions, function pointers, and member
function pointers, and is able to bind any argument to a specific value or
route input arguments into arbitrary positions.
bind
does not place any requirements on the function object; in particular, it does
not need the
result_type,
first_argument_type and
second_argument_type standard typedefs.
Given these definitions:
int f(int a, int b) { return a + b; } int g(int a, int b, int c) { return a + b + c; }
bind(f, 1, 2)
will produce a "nullary" function object that takes no arguments
and returns
f(1, 2). Similarly,
bind(g,
1, 2, 3)() is equivalent
to
g(1, 2, 3).
It is possible to selectively bind only some of the arguments.
bind(f, _1,
5)(x) is equivalent
to
f(x, 5); here
_1
is a placeholder argument that means "substitute
with the first input argument."
For comparison, here is the same operation expressed with the standard library primitives:
std::bind2nd(std::ptr_fun(f), 5)(x);
bind covers the functionality
of
std::bind1st as well:
std::bind1st(std::ptr_fun(f), 5)(x); // f(5, x) bind(f, 5, _1)(x); // f(5, x)
bind can handle functions
with more than two arguments, and its argument substitution mechanism is
more general:
bind(f, _2, _1)(x, y); // f(y, x) bind(g, _1, 9, _1)(x); // g(x, 9, x) bind(g, _3, _3, _3)(x, y, z); // g(z, z, z) bind(g, _1, _1, _1)(x, y, z); // g(x, x, x)
Note that, in the last example, the function object produced by
bind(g, _1,
_1, _1) does
not contain references to any arguments beyond the first, but it can still
be used with more than one argument. Any extra arguments are silently ignored,
just like the first and the second argument are ignored in the third example.
The arguments that
bind takes
are copied and held internally by the returned function object. For example,
in the following code:
int i = 5; bind(f, i, _1);
a copy of the value of
i
is stored into the function object.
boost::ref and
boost::cref can be used to make the function
object store a reference to an object, rather than a copy:
int i = 5; bind(f, ref(i), _1); bind(f, cref(i), _1);
bind is not limited to functions;
it accepts arbitrary function objects. In the general case, the return type
of the generated function object's
operator() has to be specified explicitly (without
a
typeof operator the return
type cannot be inferred):
struct F { int operator()(int a, int b) { return a - b; } bool operator()(long a, long b) { return a == b; } }; F f; int x = 104; bind<int>(f, _1, _1)(x); // f(x, x), i.e. zero
Some compilers have trouble with the
bind<R>(f, ...)
syntax. For portability reasons, an alternative way to express the above
is supported:
boost::bind(boost::type<int>(), f, _1, _1)(x);
Note, however, that the alternative syntax is provided only as a workaround. It is not part of the interface.
When the function object exposes a nested type named
result_type,
the explicit return type can be omitted:
int x = 8; bind(std::less<int>(), _1, 9)(x); // x < 9
[Note: the ability to omit the return type is not available on all compilers.]
By default,
bind makes a
copy of the provided function object.
boost::ref and
boost::cref can be used to make it store a reference
to the function object, rather than a copy. This can be useful when the function
object is non-copyable, expensive to copy, or contains state; of course,
in this case the programmer is expected to ensure that the function object
is not destroyed while it's still being used.
struct F2 { int s; typedef void result_type; void operator()(int x) { s += x; } }; F2 f2 = { 0 }; int a[] = { 1, 2, 3 }; std::for_each(a, a+3, bind(ref(f2), _1)); assert(f2.s == 6);
Pointers to member functions and pointers to data members are not function
objects, because they do not support
operator(). For convenience,
bind
accepts member pointers as its first argument, and the behavior is as if
boost::mem_fn
has been used to convert the member pointer into a function object. In other
words, the expression
bind(&X::f, args)
is equivalent to
bind<R>(
mem_fn(&X::f), args)
where
R is the return type
of
X::f (for member functions) or the type of
the member (for data members.)
[Note:
mem_fn
creates function objects that are able to accept a pointer, a reference,
or a smart pointer to an object as its first argument; for additional information,
see the
mem_fn documentation.]
Example:
struct X { bool f(int a); }; X x; shared_ptr<X> p(new X); int i = 5; bind(&X::f, ref(x), _1)(i); // x.f(i) bind(&X::f, &x, _1)(i); // (&x)->f(i) bind(&X::f, x, _1)(i); // (internal copy of x).f(i) bind(&X::f, p, _1)(i); // (internal copy of p)->f(i)
The last two examples are interesting in that they produce "self-contained"
function objects.
bind(&X::f, x,
_1)
stores a copy of
x.
bind(&X::f, p,
_1)
stores a copy of
p, and since
p is a
boost::shared_ptr, the function object
retains a reference to its instance of
X
and will remain valid even when
p
goes out of scope or is
reset().
Some of the arguments passed to
bind
may be nested bind expressions themselves:
bind(f, bind(g, _1))(x); // f(g(x))
The inner bind expressions are evaluated, in unspecified
order, before the outer
bind
when the function object is called; the results of the evaluation are then
substituted in their place when the outer
bind
is evaluated. In the example above, when the function object is called with
the argument list
(x),
bind(g,
_1)(x) is evaluated
first, yielding
g(x), and
then
bind(f, g(x))(x) is evaluated,
yielding the final result
f(g(x)).
This feature of
bind can
be used to perform function composition. See bind_as_compose.cpp
for an example that demonstrates how to use
bind
to achieve similar functionality to Boost.Compose.
Note that the first argument - the bound function object - is not evaluated,
even when it's a function object that is produced by
bind
or a placeholder argument, so the example below does
not work as expected:
typedef void (*pf)(int); std::vector<pf> v; std::for_each(v.begin(), v.end(), bind(_1, 5));
The desired effect can be achieved via a helper function object
apply that applies its first argument,
as a function object, to the rest of its argument list. For convenience,
an implementation of
apply
is provided in the apply.hpp
header file. Here is how the modified version of the previous example looks
like:
typedef void (*pf)(int); std::vector<pf> v; std::for_each(v.begin(), v.end(), bind(apply<void>(), _1, 5));
Although the first argument is, by default, not evaluated, all other arguments
are. Sometimes it is necessary not to evaluate arguments subsequent to the
first, even when they are nested bind subexpressions.
This can be achieved with the help of another function object,
protect, that masks the type so that
bind does not recognize and evaluate it.
When called, protect simply forwards the argument list to the other function
object unmodified.
The header protect.hpp
contains an implementation of
protect.
To
protect a bind function
object from evaluation, use
protect(bind(f, ...)).
For convenience, the function objects produced by
bind
overload the logical not operator
!
and the relational and logical operators
==,
!=, <,
<=, >,
>=, &&,
||.
!bind(f,
...) is equivalent to
bind(logical_not(), bind(f,
...)), where
logical_not
is a function object that takes one argument
x
and returns
!x.
bind(f, ...)
op x,
where op is a relational or logical
operator, is equivalent to
bind(relation(), bind(f,
...), x), where
relation
is a function object that takes two arguments
a
and
b and returns
a op b.
What this means in practice is that you can conveniently negate the result
of
bind:
std::remove_if(first, last, !bind(&X::visible, _1)); // remove invisible objects
and compare the result of
bind
against a value:
std::find_if(first, last, bind(&X::name, _1) == "Peter"); std::find_if(first, last, bind(&X::name, _1) == "Peter" || bind(&X::name, _1) == "Paul");
against a placeholder:
bind(&X::name, _1) == _2
or against another bind expression:
std::sort(first, last, bind(&X::name, _1) < bind(&X::name, _2)); // sort by name
class image; class animation { public: void advance(int ms); bool inactive() const; void render(image & target) const; }; std::vector<animation> anims; template<class C, class P> void erase_if(C & c, P pred) { c.erase(std::remove_if(c.begin(), c.end(), pred), c.end()); } void update(int ms) { std::for_each(anims.begin(), anims.end(), boost::bind(&animation::advance, _1, ms)); erase_if(anims, boost::mem_fn(&animation::inactive)); } void render(image & target) { std::for_each(anims.begin(), anims.end(), boost::bind(&animation::render, _1, boost::ref(target))); }
class button { public:
boost::function<void()> onClick; }; class player { public: void play(); void stop(); }; button playButton, stopButton; player thePlayer; void connect() { playButton.onClick = boost::bind(&player::play, &thePlayer); stopButton.onClick = boost::bind(&player::stop, &thePlayer); }
As a general rule, the function objects generated by
bind
take their arguments by reference and cannot, therefore, accept non-const temporaries
or literal constants. This is an inherent limitation of the C++ language in
its current (2003) incarnation, known as the forwarding
problem. (It will be fixed in the next standard, usually called C++0x.)
The library uses signatures of the form
template<class T> void f(T & t);
to accept arguments of arbitrary types and pass them on unmodified. As noted, this does not work with non-const r-values.
On compilers that support partial ordering of function templates, a possible solution is to add an overload:
template<class T> void f(T & t); template<class T> void f(T const & t);
Unfortunately, this requires providing 512 overloads for nine arguments, which is impractical. The library chooses a small subset: for up to two arguments, it provides the const overloads in full, for arities of three and more it provides a single additional overload with all of the arguments taken by const reference. This covers a reasonable portion of the use cases.
See the dedicated Troubleshooting section.
Probably because you used the general
bind<R>(f, ...)
syntax, thereby instructing
bind
to not "inspect" f to detect arity and return type errors.
The first form instructs
bind
to inspect the type of
f
in order to determine its arity (number of arguments) and return type. Arity
errors will be detected at "bind time". This syntax, of course,
places some requirements on
f.
It must be a function, function pointer, member function pointer, or a function
object that defines a nested type named
result_type;
in short, it must be something that
bind
can recognize.
The second form instructs
bind
to not attempt to recognize the type of
f.
It is generally used with function objects that do not, or cannot, expose
result_type, but it can also
be used with nonstandard functions. For example, the current implementation
does not automatically recognize variable-argument functions like
printf, so you will have to use
bind<int>(printf, ...). Note
that an alternative
bind(type<R>(), f, ...)
syntax is supported for portability reasons.
Another important factor to consider is that compilers without partial template
specialization or function template partial ordering support cannot handle
the first form when
f is
a function object, and in most cases will not handle the second form when
f is a function (pointer)
or a member function pointer.
Yes, if you
#define
BOOST_BIND_ENABLE_STDCALL.
An alternative is to treat the function as a generic
function object and use the
bind<R>(f, ...)
syntax.
Yes, if you
#define
BOOST_BIND_ENABLE_PASCAL.
An alternative is to treat the function as a generic
function object and use the
bind<R>(f, ...)
syntax.
Sometimes. On some platforms, pointers to extern "C" functions
are equivalent to "ordinary" function pointers, so they work fine.
Other platforms treat them as different types. A platform-specific implementation
of
bind is expected to handle
the problem transparently; this implementation does not. As usual, the workaround
is to treat the function as a generic
function object and use the
bind<R>(f, ...)
syntax.
Non-portable extensions, in general, should default to off to prevent vendor
lock-in. Had the appropriate
macros been defined automatically, you could have accidentally taken
advantage of them without realizing that your code is, perhaps, no longer
portable. In addition, some compilers have the option to make
__stdcall (
__fastcall)
their default calling convention, in which case no separate support would
be necessary.
In a
bind(f, a1, a2,
..., aN) expression, the function object
f must be able to take exactly N arguments.
This error is normally detected at "bind time"; in other words,
the compilation error is reported on the line where
bind() is invoked:
int f(int, int); int main() { boost::bind(f, 1); // error, f takes two arguments boost::bind(f, 1, 2); // OK }
A common variation of this error is to forget that member functions have an implicit "this" argument:
struct X { int f(int); } int main() { boost::bind(&X::f, 1); // error, X::f takes two arguments boost::bind(&X::f, _1, 1); // OK }
As in normal function calls, the function object that is bound must be compatible
with the argument list. The incompatibility will usually be detected by the
compiler at "call time" and the result is typically an error in
bind.hpp on a line that looks like:
return f(a[a1_], a[a2_]);
An example of this kind of error:
int f(int); int main() { boost::bind(f, "incompatible"); // OK so far, no call boost::bind(f, "incompatible")(); // error, "incompatible" is not an int boost::bind(f, _1); // OK boost::bind(f, _1)("incompatible"); // error, "incompatible" is not an int }
The placeholder
_N selects
the argument at position
N
from the argument list passed at "call time." Naturally, it is
an error to attempt to access beyond the end of this list:
int f(int); int main() { boost::bind(f, _1); // OK boost::bind(f, _1)(); // error, there is no argument number 1 }
The error is usually reported in
bind.hpp, at
a line similar to:
return f(a[a1_]);
When emulating
std::bind1st(f, a), a common mistake of this category is to
type
bind(f, a, _2)
instead of the correct
bind(f,
a, _1).
The
bind(f, a1, a2,
..., aN) form
causes automatic recognition of the type of
f.
It will not work with arbitrary function objects;
f
must be a function or a member function pointer.
It is possible to use this form with function objects that define
result_type, but only on compilers that
support partial specialization and partial ordering. In particular, MSVC
up to version 7.0 does not support this syntax for function objects.
The
bind<R>(f, a1, a2,
..., aN) form
supports arbitrary function objects.
It is possible (but not recommended) to use this form with functions or member function pointers, but only on compilers that support partial ordering. In particular, MSVC up to version 7.0 does not fully support this syntax for functions and member function pointers.
By default, the
bind(f, a1, a2,
..., aN) form
recognizes "ordinary" C++ functions and function pointers. Functions that use a different calling
convention, or variable-argument functions such as
std::printf,
do not work. The general
bind<R>(f, a1, a2,
..., aN) form
works with nonstandard functions.
On some platforms, extern "C" functions, like
std::strcmp,
are not recognized by the short form of
bind.
See also
__stdcall
and
pascal Support.
An attempt to bind an overloaded function usually results in an error, as there is no way to tell which overload was meant to be bound. This is a common problem with member functions with two overloads, const and non-const, as in this simplified example:
struct X { int& get(); int const& get() const; }; int main() { boost::bind(&X::get, _1); }
The ambiguity can be resolved manually by casting the (member) function pointer to the desired type:
int main() { boost::bind(static_cast< int const& (X::*) () const >(&X::get), _1); }
Another, arguably more readable, alternative is to introduce a temporary variable:
int main() { int const& (X::*get) () const = &X::get; boost::bind(get, _1); }
The function objects that are produced by
bind
do not model the STL Unary
Function or Binary
Function concepts, even when the function objects are
unary or binary operations, because the function object types are missing
public typedefs
result_type
and
argument_type or
first_argument_type and
second_argument_type.
In cases where these typedefs are desirable, however, the utility function
make_adaptable can be used
to adapt unary and binary function objects to these concepts. This allows
unary and binary function objects resulting from
bind
to be combined with STL templates such as
std::unary_negate
and
std::binary_negate.
The
make_adaptable function
is defined in
<boost/bind/make_adaptable.hpp>,
which must be included explicitly in addition to
<boost/bind/bind.hpp>:
#include <boost/bind/make_adaptable.hpp> template <class R, class F> unspecified-type make_adaptable(F f); template<class R, class A1, class F> unspecified-unary-functional-type make_adaptable(F f); template<class R, class A1, class A2, class F> unspecified-binary-functional-type make_adaptable(F f); template<class R, class A1, class A2, class A3, class F> unspecified-ternary-functional-type make_adaptable(F f); template<class R, class A1, class A2, class A3, class A4, class F> unspecified-4-ary-functional-type make_adaptable(F f);
This example shows how to use
make_adaptable
to make a predicate for "is not a space":
typedef char char_t; std::locale loc(""); const std::ctype<char_t>& ct = std::use_facet<std::ctype<char_t> >(loc); auto isntspace = std::not1(boost::make_adaptable<bool, char_t>(boost::bind(&std::ctype<char_t>::is, &ct, std::ctype_base::space, _1)));
In this example,
bind creates
the "is a space" (unary) predicate. It is then passed to
make_adaptable so that a function object
modeling the Unary Function concept can be created,
serving as the argument to
std::not1.
Some compilers, including MSVC 6.0 and Borland C++ 5.5.1, have problems with
the top-level
const in function
signatures:
int f(int const); int main() { boost::bind(f, 1); // error }
Workaround: remove the
const
qualifier from the argument.
On MSVC (up to version 7.0), when
boost::bind
is brought into scope with an using declaration:
using boost::bind;
the syntax
bind<R>(f, ...)
does not work. Workaround: either use the qualified name,
boost::bind,
or use an using directive instead:
using namespace boost;
On MSVC (up to version 7.0), a nested class template named
bind will shadow the function template
boost::bind, breaking the
bind<R>(f, ...)syntax.
Unfortunately, some libraries contain nested class templates named
bind (ironically, such code is often an
MSVC specific workaround.)
The workaround is to use the alternative
bind(type<R>(), f, ...)
syntax.
MSVC (up to version 7.0) treats the ellipsis in a variable argument function
(such as
std::printf) as a type. Therefore, it will accept
the (incorrect in the current implementation) form:
bind(printf, "%s\n", _1);
and will reject the correct version:
bind<int>(printf, "%s\n", _1);
namespace boost { // no arguments template<class R, class F> unspecified-1
bind(F f); template<class F> unspecified-1-1
bind(F f); template<class R> unspecified-2
bind(R (*f) ()); // one argument template<class R, class F, class A1> unspecified-3
bind(F f, A1 a1); template<class F, class A1> unspecified-3-1
bind(F f, A1 a1); template<class R, class B1, class A1> unspecified-4
bind(R (*f) (B1), A1 a1);); // two arguments template<class R, class F, class A1, class A2> unspecified-7
bind(F f, A1 a1, A2 a2); template<class F, class A1, class A2> unspecified-7-1
bind(F f, A1 a1, A2 a2); template<class R, class B1, class B2, class A1, class A2> unspecified-8
bind(R (*f) (B1, B2), A1 a1, A2 a2); template<class R, class T, class B1, class A1, class A2> unspecified-9
bind(R (T::*f) (B1), A1 a1, A2 a2); template<class R, class T, class B1, class A1, class A2> unspecified-10
bind(R (T::*f) (B1) const, A1 a1, A2 a2); // implementation defined number of additional overloads for more arguments } namespace { unspecified-placeholder-type-1 _1; unspecified-placeholder-type-2 _2; unspecified-placeholder-type-3 _3; // implementation defined number of additional placeholder definitions }
All unspecified-N types returned by
bind
are CopyConstructible. unspecified-N
::result_type
is defined as the return type of unspecified-N
::operator().
All unspecified-placeholder-N types are CopyConstructible. Their copy constructors do not throw exceptions.
The function μ
(x, v1,
v2, ..., vm), where
m
is a nonnegative integer, is defined as:
x.get(), when
xis of type
boost::reference_wrapper
<T>for some type
T;
vk, when
xis (a copy of) the placeholder _k for some positive integer k;
x(v1, v2, ..., vm)when
xis (a copy of) a function object returned by
bind;
xotherwise.
template<class R, class F> unspecified-1 bind(F f)
(v1, v2, ..., vm)is equivalent to
f(), implicitly converted to
R.
Fthrows an exception.
template<class F> unspecified-1-1 bind(F f)
bind<typename F::result_type, F>(f).
fvia other means as an extension, without relying on the
result_typemember.
template<class R> unspecified-2 bind(R (*f) ())
(v1, v2, ..., vm)is equivalent to
f().
template<class R, class F, class A1> unspecified-3 bind(F f, A1 a1)
(v1, v2, ..., vm)is equivalent to
f(μ
(a1, v1, v2, ..., vm)), implicitly converted to
R.
For
A1throw an exception.
template<class F, class A1> unspecified-3-1 bind(F f, A1 a1)
bind<typename F::result_type, F, A1>(f, a1).
fvia other means as an extension, without relying on the
result_typemember.
template<class R, class B1, class A1> unspecified-4 bind(R (*f) (B1), A1 a1)
(v1, v2, ..., vm)is equivalent to
f(μ
(a1, v1, v2, ..., vm)).
A1throws an exception.)
template<class R, class F, class A1, class A2> unspecified-7 bind(F f, A1 a1, A2 a2)
(v1, v2, ..., vm)is equivalent to
f(μ
(a1, v1, v2, ..., vm),μ
(a2, v1, v2, ..., vm)), implicitly converted to
R.
F,
A1or
A2throw an exception.
template<class F, class A1, class A2> unspecified-7-1 bind(F f, A1 a1, A2 a2)
bind<typename F::result_type, F, A1, A2>(f, a1, a2).
fvia other means as an extension, without relying on the
result_typemember.
template<class R, class B1, class B2, class A1, class A2> unspecified-8 bind(R (*f) (B1, B2), A1 a1, A2 a2)
(v1, v2, ..., vm)is equivalent to
f(μ
(a1, v1, v2, ..., vm),μ
(a2, v1, v2, ..., vm)).
A1or
A2throw an exception.
template<class R, class T, class B1, class A1, class A2> unspecified-9 bind(R (T::*f) (B1), A1 a1, A2 a2)
bind<R>(
boost::mem_fn
(f), a1, a2).
template<class R, class T, class B1, class A1, class A2> unspecified-10 bind(R (T::*f) (B1) const, A1 a1, A2 a2)
bind<R>(
boost::mem_fn
(f), a1, a2).
Implementations are allowed to provide additional
bind
overloads in order to support more arguments or different function pointer
variations.
bind.hpp, do not include directly)
bind.hpp, do not include directly)
bind.hpp, do not include directly)
_1,
_2, ...
_9placeholders)
applyhelper function object)
protecthelper function)
make_adaptablehelper function)
__stdcallfunctions)
__stdcallmember functions)
__fastcallfunctions)
__fastcallmember functions)
This implementation supports function objects with up to nine arguments. This is an implementation detail, not an inherent limitation of the design.
Some platforms allow several types of (member) functions that differ by their calling convention (the rules by which the function is invoked: how are arguments passed, how is the return value handled, and who cleans up the stack - if any.)
For example, Windows API functions and COM interface member functions use
a calling convention known as
__stdcall.
Borland VCL components use
__fastcall.
Mac toolbox functions use a
pascal
calling convention.
To use
bind with
__stdcall functions,
#define
the macro
BOOST_BIND_ENABLE_STDCALL
before including
<boost/bind/bind.hpp>.
To use
bind with
__stdcall member functions,
#define the macro
BOOST_MEM_FN_ENABLE_STDCALL
before including
<boost/bind/bind.hpp>.
To use
bind with
__fastcall functions,
#define
the macro
BOOST_BIND_ENABLE_FASTCALL
before including
<boost/bind/bind.hpp>.
To use
bind with
__fastcall member functions,
#define the macro
BOOST_MEM_FN_ENABLE_FASTCALL
before including
<boost/bind/bind.hpp>.
To use
bind with
pascal functions,
#define
the macro
BOOST_BIND_ENABLE_PASCAL
before including
<boost/bind/bind.hpp>.
To use
bind with
__cdecl member functions,
#define the macro
BOOST_MEM_FN_ENABLE_CDECL
before including
<boost/bind/bind.hpp>.
It is best to define these macros in the project options,
via
-D
on the command line, or as the first line in the translation unit (.cpp file)
where
bind is used.
Not following this rule can lead to obscure errors when a header includes
bind.hpp before the macro has been defined.
[Note: this is a non-portable extension. It is not part of the interface.]
[Note: Some compilers provide only minimal support for
the
__stdcall keyword.]
Function objects returned by
bind
support the experimental and undocumented, as of yet,
visit_each
enumeration interface.
See bind_visitor.cpp for an example.
Earlier efforts that have influenced the library design:
Doug Gregor suggested that a visitor mechanism would allow
bind
to interoperate with a signal/slot library.
John Maddock fixed a MSVC-specific conflict between
bind
and the type traits library.
Numerous improvements were suggested during the formal review period by Ross Smith, Richard Crossley, Jens Maurer, Ed Brey, and others. Review manager was Darin Adler.
The precise semantics of
bind
were refined in discussions with Jaakko Järvi.
Dave Abrahams fixed a MSVC-specific conflict between
bind
and the iterator adaptors
library.
Dave Abrahams modified
bind
and
mem_fn to support
void returns on deficient compilers.
Mac Murrett contributed the "pascal" support enabled by
BOOST_BIND_ENABLE_PASCAL.
The alternative
bind(type<R>(), f, ...)
syntax was inspired by a discussion with Dave Abrahams and Joel de Guzman.
This documentation was ported to Quickbook by Agustín Bergé. | https://www.boost.org/doc/libs/1_73_0/libs/bind/doc/html/bind.html | CC-MAIN-2020-29 | refinedweb | 4,432 | 53.1 |
import "github.com/cyberdelia/statsd"
Statsd client
Supports counting, sampling, timing, gauges, sets and multi-metrics packet.
Using the client to increment a counter:
client, err := statsd.Dial("127.0.0.1:8125") if err != nil { // handle error } defer client.Close() err = client.Increment("buckets", 1, 1)
Client is statsd client representing a connection to a statsd server.
Dial connects to the given address on the given network using net.Dial and then returns a new Client for the connection.
DialSize acts like Dial but takes a packet size. By default, the packet size is 512, see for guidelines.
DialTimeout acts like Dial but takes a timeout. The timeout includes name resolution, if required.
Close closes the connection.
Decrement decrements the counter for the given bucket.
DecrementGauge decrements the value of the gauge.
Duration records time spent for the given bucket with time.Duration.
Flush flushes writes any buffered data to the network.
Gauge records arbitrary values for the given bucket.
Increment increments the counter for the given bucket.
IncrementGauge increments the value of the gauge.
Time calculates time spent in given function and send it.
Timing records time spent for the given bucket in milliseconds.
Unique records unique occurences of events.
Package statsd imports 6 packages (graph) and is imported by 3 packages. Updated 2016-07-17. Refresh now. Tools for package owners. | https://godoc.org/github.com/cyberdelia/statsd | CC-MAIN-2018-26 | refinedweb | 224 | 63.05 |
Add Remove Theme Files
RadThemeManager cannot load the theme if it is saved as package (tssp file). This is shown in the following article: using custom themes
To edit the list of themes loaded into a Theme Manager, follow these steps:
Select the RadThemeManager control, and then open its Smart Tag menu.
Select Edit Themes to open the ThemeSource Collection Editor.
Click OK when you are finished working in the editor.
To Add a New Theme to the Theme Manager
Click Add.
Choose the StorageType for the theme. Select Resource or File.
Set the ThemeLocation (resource name or file location).
To Remove a Theme from the Resource Manager
Select the theme that you wish to remove.
Click Remove.
To Change the Properties for an Existing Theme
Select the theme that you wish to edit.
Set the StorageType and ThemeLocation properties to your desired values.
When setting the ThemeLocation for a Resource storage type be sure to include the project namespace. The naming convention for ThemeManager to find the resource is <my project namespace>.<theme name>.xml. In project "MyProject" with theme resource file "MyTheme.xml", the fully qualified resource name should be entered as "MyProject.MyTheme.XML". | https://docs.telerik.com/devtools/winforms/tools/theme-manager/editing-themes | CC-MAIN-2018-34 | refinedweb | 197 | 66.94 |
Log messages and report errors to MarkLogic Server. You do not need to subclass this class. More...
#include <MarkLogic.h>
Log messages and report errors to MarkLogic Server. You do not need to subclass this class.
Messages logged by Reporter::log are written to the MarkLogic Server log. For example, to marklogic_dir/Logs/ErrorLog.txt.
Rather than throwing exceptions, your AggregateUDF implementation should report errors by calling Reporter::error. Errors reported this way write a message to the log file, cancel the current job, and raise a MarkLogic Server exception to the calling application.
Log an error and cancel the current job.
The task that calls this function stops immediately. That is, control does not return to your code. In-progress tasks for the same job may still run to completion.
Determine the current log level.
Only messages at this level and above appear in the log. | http://docs.marklogic.com/cpp/udf/classmarklogic_1_1Reporter.html | CC-MAIN-2018-09 | refinedweb | 147 | 61.33 |
Type: Posts; User: confused93
Thanks, it working.. but i need to solve this in my way, can anybody help me?
I have no errors, program only dont do, what i want
#include <iostream>
using namespace std;
int main(){
const int N = 26;
char abeceda[N] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',...
Hello i need exchange strings in field, but i have no more ideas how to do that.
For example:
{"Hi", "Hello", "Goodbye", "Morning"};
to
{"Hello", "Hi", "Goodbye", "Morning"};
i tried this, but...
I solved it. Thank you.
Yes, i have function.cpp, function.h and main.cpp but all what i need is logical condition into for cycle
void pyramida(int N, char symbol){
cout << symbol << endl;
for(int i=0;...
i need to find right logical condition into for
I need program which draw this nice pyramid with for cycle, N=number of lines...
i need only content of for cycle
Yes it is homework, but i really don't know how to solve it. I spend with it about hour.:/
Hello, i'm totally beginer, can somebody help me solve this (for cycle)?
31193
Thanks in advance. :) | http://forums.codeguru.com/search.php?s=6f29854d87dc7e7419dd10b288f92787&searchid=2757771 | CC-MAIN-2014-15 | refinedweb | 193 | 83.56 |
One day while browsing the Code Project, I found an excellent article by Tony Selke 'Wrapper Class for Parsing Fixed-Width or Delimited Text Files'. I decided that I would port the code to C# because that is my language of choice. While doing this, I also added a couple of features:
DataTable
This is my first article submitted to the Code Project, so be gentle.
The library can import delimited or fixed width files while the developer decides what to do with each record by subscribing to the RecordFound event. The library can import delimited or fixed width files directly into a DataTable.
RecordFound
The developer sets up a schema either with code or in an XML schema file. This determines the data types that will be used in the DataTable. Based on the schema, the text values are parsed and converted to the respective data types and either put in a DataTable or simply passed to the calling object as an event.
The first thing to do is, add a reference to the library. Then add the using statement at the top of your source file.
using
using WhaysSoftware.Utilities.FileParsers;
Create an instance of the TextFieldParser object.
TextFieldParser
TextFieldParser tfp = new TextFieldParser(filePath);
If you will be using an XML schema file, use the constructor that has the 'schemaFile' parameter.
schemaFile
TextFieldParser tfp = new TextFieldParser(filePath, schemaPath);
If using an XML schema file, the following is an example of how the XML schema file would look:
<TABLE Name="TEST" FileFormat="Delimited" ID="Table1">
<FIELD Name="LineNumber" DataType="Int32" />
<FIELD Name="Quoted String" DataType="String" Quoted="true" />
<FIELD Name="Unquoted String" DataType="String" Quoted="false" />
<FIELD Name="Double" DataType="Double" />
<FIELD Name="Boolean" DataType="Boolean" />
<FIELD Name="Decimal" DataType="Decimal" />
<FIELD Name="DateTime" DataType="DateTime" />
<FIELD Name="Int16" DataType="Int16" />
</TABLE>
I have included with the source code a complete description of the schema file attributes. Here is an example of the same thing, but done in code.
TextFieldCollection fields = new TextFieldCollection();
fields.Add(new TextField("Line Number", TypeCode.Int32));
fields.Add(new TextField("Quoted String", TypeCode.String, true));
fields.Add(new TextField("Unquoted String", TypeCode.String, false));
fields.Add(new TextField("Double", TypeCode.Double));
fields.Add(new TextField("Boolean", TypeCode.Boolean));
fields.Add(new TextField("Decimal", TypeCode.Decimal));
fields.Add(new TextField("DateTime", TypeCode.DateTime));
fields.Add(new TextField("Int16", TypeCode.Int16));
tfp.TextFields = fields;
Now you can either subscribe to the RecordFound event if you want to do something custom with the records...
tfp.RecordFound += new RecordFoundHandler(tfp_RecordFound);
tfp.ParseFile();
...
private void tfp_RecordFound(ref int CurrentLineNumber,
TextFieldCollection TextFields)
{
//Do something with the TextFields parameter
}
or you can call ParseToDataTable to get the results in a DataTable.
ParseToDataTable
DataTable dt = tfp.ParseToDataTable();
Note: Even when calling ParseToDataTable, the RecordFound event is still fired.
You can also subscribe to the RecordFailed event to get notification of when a record fails to parse. In the event handler, you can decide if you can continue or not.
RecordFailed
tfp.RecordFailed += new RecordFailedHandler(tfp_RecordFailed);
...
private void tfp_RecordFailed(ref int CurrentLineNumber,
string LineText, string ErrorMessage, ref bool Continue)
{
MessageBox.Show("Error: " + ErrorMessage + Environment.NewLine +
"Line: " + LineText);
}
That's it. I look forward to comments, suggestions from you all.. | https://www.codeproject.com/articles/9696/a-modified-c-implementation-of-tony-selke-s-textfi?fid=157716&df=90&mpp=25&sort=position&spc=relaxed&select=4433585&tid=4433585 | CC-MAIN-2016-50 | refinedweb | 536 | 50.63 |
Try following the tutorial at
Quote from: floresta on Mar 28, 2011, 04:33 amTry following the tutorial at was the one I followed, got up and running with it in no time.Then once I knew it all worked, I got a little more daring with the second schematic in this one so I could get 3 of those pins back.
#include <ShiftRegLCD.h>ShiftRegLCD objectName(Datapin, Clockpin, Enablepin or TWO_WIRE [, Lines [, Font]]) where Lines and Font are optional. * Enablepin: can be replaced by constant TWO_WIRE, if using only 2 wires. * Lines: 1 or 2 lines (also 4-line LCD's must be set as 2). * Font : 0 or 1, small or big font (8 or 10 pixel tall font, if available).
You will have to change...
Are you really in need of three pins? Have you used the analog pins as digital pins?
Quote from: liudr on Mar 28, 2011, 11:55 pmYou will have to change...Already done Quote from: liudr on Mar 28, 2011, 11:55 pmAre you really in need of three pins? Have you used the analog pins as digital pins?Yup, need the pins, I'm now down from using 11 to using 8, and I still have 2 servo motors and a stepper (and maybe another 4x20 LCD) that I'll need to hook up to this. But let's not hijack this fella's thread. I was simply commenting that Ladyada's tutorial helped me, and informed me that the LCD was working before moving on to what I really wanted to do. | http://forum.arduino.cc/index.php?topic=56722.msg408496 | CC-MAIN-2015-27 | refinedweb | 262 | 80.21 |
GETC(3) BSD Programmer's Manual GETC(3)
fgetc, getc, getchar, getw - get next character or word from input stream
#include <stdio.h> int fgetc(FILE *stream); int getc(FILE *stream); int getchar(void); int getw(FILE *stream);w() function obtains the next int (if present) from the stream pointed at by stream.
If successful, these routines return the next requested object from the stream. If the stream is at end-of-file or a read error occurs, the rou- tines return EOF. The routines feof(3) and ferror(3) must be used to dis- tinguish between end-of-file and error. If an error occurs, the global variable errno is set to indicate the error. The end-of-file condition is remembered, even on a terminal, and all subsequent attempts to read will return EOF until the condition is cleared with clearerr(3).
ferror(3),w() is not recommended for portable applications.. | https://www.mirbsd.org/htman/i386/man3/getc.htm | CC-MAIN-2019-18 | refinedweb | 153 | 63.09 |
So why do we need Freeglut?
Freeglut is an open source toolkit that abstracts all the OS specific code that every OpenGL program requires. This prevents us from having to learn Win32 API or GLX if you use Linux. If you don't already know OpenGL, it saves you from having to write a lot of boiler plate code just to get started. Once you have the basics of OpenGL, using a toolkit is entirely optional and can be dropped if you don't want the extra dependencies. For simple tutorials and demos, Freeglut is the way to go to get started.
What is Gl3w?
Gl3w is a utility that loads all the core OpenGL 4.2 functions and extensions for us. (You could also use Glew, but it loads deprecated functions as well as the core ones, so you have to be more careful when you use it.)The alternative is to spend time manipulating function pointers and loading extensions by hand which can get tedious very quick. Again, later you can drop the Gl3w utility if you prefer and load in everything by hand, but for now we will use the library.
Installing Freeglut
So now we can get started. The first thing to do is download, compile, and install Freeglut. Why do we compile Freeglut when we can get the binaries? We compile it because we are programmers and because we can. Further, Freeglut is open source so it defeats the purpose if all we do is use pre-built binaries. Download Freeglut from
Next, open a command window and navigate to the Freeglut source code. I assume that Mingw is on the path. Type the following compiler commands:
gcc -O2 -c -DFREEGLUT_EXPORTS *.c -I../include gcc -shared -o freeglut32.dll *.o -Wl,--enable-stdcall-fixup,--out-implib,libfreeglut32.a -lopengl32 -lglu32 -lgdi32 -lwinmm gcc -O2 -c -DFREEGLUT_STATIC *.c -I../include ar rcs libfreeglut32_static.a *.o
Freeglut should compile without any problem. Next, find the newly built files freeglut32.dll, libfreeglut32.a, libfreeglut32_static.a and the include directory. Copy the header files from the include directory to the ..\Mingw\include\GL directory. The path ..\Mingw is the install location of Mingw on disk. Put freeglut32.dll into ..\Mingw\bin and put libfreeglut32.a and libfreeglut32_static.a into ..\Mingw\lib. Make sure that ..\Mingw\bin is on the path. That takes care of the installation of Freeglut.
Installing Gl3w
For Gl3w, you should have Python 2.XX installed. Download the Python script located at Run the Python script and it will download the core header files from opengl.org and it will create a source file that can be compiled. Copy the downloaded header files to ..\Mingw\include\GL3 directory. The source file gl3w.c we will link with our application. I renamed it to gl3w.cpp and modified it to compile with g++, but it should work just the same.
The Code
Now we can write a minimal program to check that we can run OpenGL 4.2 core profile programs. The following is a simple program that creates a window and paints it black. I named it test.cpp:
#include <iostream> #include <GL3/gl3w.h> #include <GL/freeglut.h> // display callback void display() { glClear(GL_COLOR_BUFFER_BIT); glutSwapBuffers(); } int main(int argc, char **argv) { glutInit(&argc, argv); // request version 4.2 glutInitContextVersion(4, 2); // core profile glutInitContextFlags(GLUT_FORWARD_COMPATIBLE); glutInitContextProfile(GLUT_CORE_PROFILE); // double buffered, depth, color w/ alpha glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE); glutInitWindowSize(640, 480); glutCreateWindow("OpenGL Test"); if (gl3wInit()) { std::cerr << "Failed to initialize." << std::endl; return -1; } if (!gl3wIsSupported(4, 2)) { std::cerr << "OpenGL 4.2 not supported" << std::endl; return -1; } std::cout << "OpenGL " << glGetString(GL_VERSION) << "\nGLSL " << glGetString(GL_SHADING_LANGUAGE_VERSION); glClearColor(0,0,0,0); glutDisplayFunc(display); glutMainLoop(); return 0; }
Compiling and Executing
The program creates a 640 x 480 window and prints out the GL version and GLSL version. It's straightforward to compile:
g++ -Wall -c test.cpp gl3w.cpp g++ -o test.exe test.o gl3w.o -lfreeglut32 -lopengl32
Finally, we can run the executable test.exe:
| http://www.dreamincode.net/forums/topic/282014-getting-started-with-modern-opengl-42/page__pid__1639796__st__0 | CC-MAIN-2013-20 | refinedweb | 672 | 68.87 |
A Django app to generate a simple and automatic api documentation with Tastypie
Project description
A Django app to generate a simple and automatic api documentation with Tastypie.
Installation
pip install django-tastypie-simple-api-doc
Usage
First, add this to installed app and django_markup (we use this package to format classes docstrings).
INSTALLED_APPS = ( 'tastypie_api_doc', 'django_markup', )
Then you need to tell me where is your Tastypie Api object that will be documented. Put it’s path in settings.py like this:
API_OBJECT_LOCATION = "app.module.object_name"
In my test project was like this:
API_OBJECT_LOCATION = "project.urls.v1_api"
Got it? Now go to your urls module and goes like this:
from tastypie_api_doc.views import build_doc urlpatterns = [ ... url(r'^choose_your_url', build_doc), ]
And….We are almost there. Now, you need to “collect your static” if you know what I mean. :P
python manage.py collectstatic
And this is it. :)
This is a work in progress but it can be already used in your projects. So, stay tuned. Feel free to contribute to get this app way more better. =D
Project details
Release history Release notifications | RSS feed
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/django-tastypie-simple-api-doc/ | CC-MAIN-2022-27 | refinedweb | 204 | 61.43 |
Ian Huff, Software Design EngineerMicrosoft Corporation
Included in Visual Studio Team System is a useful new code coverage tool. Code coverage can tell you exactly what percent of your code is being exercised by your test methods. We have taken the time to integrate this functionality with the testing framework included in Visual Studio Team System and this is the recommended way to collect code coverage information, but the IDE and the testing framework is not the only way to collect code coverage information. We have also provided command line tools and APIs that will allow you to integrate code coverage information collection into your own custom test harnesses or build events. This TechNote will cover how to collect and view code coverage information without having to go through the Visual Studio Team System IDE.
The first main step to collecting code coverage information is to instrument the assemblies that you are interested it. Instrumentation will insert code into the assemblies so that when they are run, code coverage information will be collected. You can instrument both managed and native dll files, exe files and assemblies. The tool that you use to instrument is called VsInstr.exe and it is found in the following directory:
Microsoft Visual Studio 8\Team Tools\Performance Tools
Instrumenting the assembly is done by passing the –coverage option to the VsInstr.exe tool:
vsinstr –coverage MyAssembly.exe
When you instrument the assembly you are modifying it permanently, so the VsInstr tool automatically makes a backup of the file you instrument. In this case the backup will be called MyAssembly.orig.exe.
The next step in collecting code coverage information is to make sure that the collection monitor is running so that our collected coverage data gets written somewhere. The coverage monitor is called VsPerfMon.exe and is located in the same location as VsInstr.exe was located. To start it up for code coverage collection just use the following command:
start vsperfmon –coverage –output:mytestrun.coverage
Now the command shell will be running your monitor, waiting for some data to collect and write to the output file. Now is the time where you run your test suites or exercise your instrumented code in whatever manner you want to collect coverage information for. The command window will wait until the instrumented code has exited before it will close down and create the coverage file. Once it has, you will now have a code coverage file called mytestrun.coverage that details what code you exercised in your instrumented assembly while the monitor was running. You can open this file directly from Visual Studio to see a code coverage results window that will give you a breakdown of what percent of the code in your instrumented assembly was covered.
The above sample shows the basics of collecting command line code coverage information, but we didn’t stop with just providing command line tools. We also provide assemblies that you can use to build code coverage functionality into your own projects.
First off, we provide a controller dll that performs all the instrumentation and collection functions that we detailed above. This dll is called:
Microsoft.VisualStudio.Coverage.Monitor.dll
Below is some simple example code that uses some of the functions provided by the above dll to collect code coverage information:); } }}
The code above will do essentially the same thing as we did from the command line. First we instrument the assembly, then we start up the monitor, exercise the code (you have to fill in this part) and finally shut down the monitor. Like from the command line, we will end up with a mytestrun.coverage file at the end of the program execution.
The other assembly that we provide for code coverage is:
Microsoft.VisualStudio.Coverage.Analysis.dll
This assembly provides the smarts to extract the data from a .coverage file and display it in some useful fashion. Below is an example that uses this assembly to dump out the coverage information as XML.
using System;using System.Collections.Generic;using System.Text;using Microsoft.VisualStudio.CodeCoverage; // You must"); } }}
After running this you will generate a mylines.xml file that contains the coverage information. Instead of outputting as XML you could also perform your own visualizations with the DataSet at this point.
So as you can see, not only did we provide solid integration of code coverage with the testing framework, but we also provided all the tools and APIs needed to work with code coverage on your own terms. I would like to suggest that the best way to start with code coverage is to work thought the unit testing framework, but hopefully this TechNote will help you if you want to dig in deeper. | http://msdn.microsoft.com/en-us/teamsystem/aa718858.aspx | crawl-002 | refinedweb | 789 | 53.21 |
IRC log of lld on 2011-04-28
Timestamps are in UTC.
03:52:22 [RRSAgent]
RRSAgent has joined #lld
03:52:22 [RRSAgent]
logging to
03:52:34 [emma]
zakim, this wil be LLD
03:52:34 [Zakim]
I don't understand 'this wil be LLD', emma
03:52:42 [emma]
zakim, this will be LLD
03:52:42 [Zakim]
ok, emma, I see INC_LLDXG()12:00AM already started
03:53:55 [hideaki]
hideaki has joined #lld
03:54:03 [antoine]
antoine has joined #lld
03:55:33 [Zakim]
+[IPcaller]
03:55:46 [Zakim]
+??P2
03:56:00 [TomB]
TomB has joined #lld
03:56:03 [antoine]
zakim, IPcaller is me
03:56:03 [Zakim]
+antoine; got it
03:56:29 [antoine]
zakim, ??P2 is TomB
03:56:29 [Zakim]
+TomB; got it
03:56:39 [Zakim]
+??P3
03:56:56 [TomB]
zakim, who is on the call?
03:56:56 [Zakim]
On the phone I see ??P0, antoine, TomB, ??P3
03:57:02 [Zakim]
+??P5
03:57:24 [antoine]
zakim, ??P5 is kcoyle
03:57:24 [Zakim]
+kcoyle; got it
03:57:40 [ikki]
ikki has joined #lld
03:57:51 [TomB]
Meeting: LLD XG
03:57:53 [TomB]
Chair: Tom
03:58:01 [TomB]
rrsagent, please make record public
03:58:19 [emma]
zakim, ??P3 is maybe me
03:58:19 [Zakim]
I don't understand '??P3 is maybe me', emma
03:58:20 [Zakim]
+??P6
03:58:26 [TomB]
Agenda:
03:58:34 [emma]
zakim, ??P3 is probably me
03:58:34 [Zakim]
+emma?; got it
03:58:36 [TomB]
zakim, who is on the call?
03:58:36 [Zakim]
On the phone I see ??P0, antoine, TomB, emma?, kcoyle, ??P6
03:58:40 [antoine]
zakim, ??P6 is jeff_
03:58:40 [Zakim]
+jeff_; got it
03:58:53 [Zakim]
+Marcia
03:58:59 [fumi]
fumi has joined #lld
03:59:16 [jeff_]
jeff_ has joined #lld
03:59:36 [jeff_]
zakim, unmute me
03:59:36 [Zakim]
jeff_ was not muted, jeff_
03:59:43 [jeff_]
zakim, mute me
03:59:43 [Zakim]
jeff_ should now be muted
03:59:48 [marcia]
zakim, mute me
03:59:48 [Zakim]
Marcia should now be muted
04:00:45 [kosuke]
kosuke has joined #lld
04:01:37 [emma]
rrsagent, please draft minutes
04:01:37 [RRSAgent]
I have made the request to generate
emma
04:02:10 [Zakim]
+[IPcaller]
04:02:28 [edsu]
Zakim, [IPcaller] is edsu
04:02:28 [Zakim]
+edsu; got it
04:02:56 [antoine]
zakim, please mute me
04:02:56 [Zakim]
antoine should now be muted
04:03:00 [Zakim]
+??P10
04:03:37 [marcia]
me too, when needed
04:04:08 [edsu]
scribenick: edsu
04:04:11 [TomB]
zakim, who is on the call?
04:04:11 [Zakim]
On the phone I see hideaki, antoine (muted), TomB, emma?, kcoyle, jeff_ (muted), Marcia (muted), edsu, ??P10
04:04:13 [Zakim]
hideaki has fumi, ikki, kosuke
04:05:15 [TomB]
zakim, ??P10 is DanChudnov
04:05:15 [Zakim]
+DanChudnov; got it
04:05:20 [dchud]
thanks TomB
04:05:47 [edsu]
Topic: Reports on the status of the main deliverable
04:06:00 [edsu]
04:06:36 [kcoyle]
Benefits section:
04:07:03 [kcoyle]
emma: it is important to start the report with a section of benefits that illustrates the value of linked data for libraries
04:07:14 [kcoyle]
... started this with a review of the 42 use cases
04:07:33 [emma]
04:08:08 [kcoyle]
... started with a bullet point list, then organized in terms of 'benefits for whom?" -- everyone, librarians, developers, organizations
04:08:31 [emma]
04:08:45 [kcoyle]
... then wrote summarizing text
04:09:15 [kcoyle]
... main benefit is that everything will have a URI so it can be referenced and de-referenced
04:09:30 [kcoyle]
... and will make it possible to pull together data
04:10:01 [kcoyle]
... then benefits for different users, like researchers, etc.
04:10:57 [edsu]
scribenick: edsu
04:11:01 [edsu]
Topic: Issues
04:11:21 [edsu]
kcoyle: we began with the use cases, and extracted from them all the issues and problems that were identified
04:12:08 [edsu]
kcoyle: we brought these together and came up w/ 3 different categories: management, collaboration and extending of standards, library standards themselves
04:12:11 [edsu]
04:13:09 [edsu]
kcoyle: libraries by their nature work in a stable and somewhat unchanging environment, and how this effects making changes to linked data: price, rights ... and how libraries have large amounts of data already, and how this needs to get translated into this new format
04:13:15 [edsu]
kcoyle: that's the high level
04:13:54 [edsu]
TomB: to elborate on this point of translation: we want to make reference to different design decisions that can be made in transation, but we don't want to go into too much detail
04:14:10 [jeff_]
zakim, unmute me
04:14:10 [Zakim]
jeff_ should no longer be muted
04:14:17 [edsu]
Topic: Relevant Technologies
04:14:21 [lukose]
lukose has joined #lld
04:14:35 [edsu]
TomB: this is a good lead in to the next topic
04:14:35 [jeff_]
04:14:53 [jeff_]
zakim, unmute me
04:14:53 [Zakim]
jeff_ was not muted, jeff_
04:14:53 [TomB]
ack jeff_
04:15:05 [jeff_]
can't hear me?
04:15:09 [antoine]
no
04:15:12 [edsu]
jeff_: not yet :-)
04:15:13 [marcia]
ok
04:15:15 [emma]
zakim, unmute antoine
04:15:15 [Zakim]
antoine should no longer be muted
04:15:23 [jeff_]
sorry
04:15:25 [marcia]
Antoine, yes I can speak about our part
04:15:31 [antoine]
zakim, who is here?
04:15:31 [Zakim]
On the phone I see hideaki, antoine, TomB, emma?, kcoyle, jeff_, Marcia (muted), edsu, DanChudnov
04:15:32 [emma]
zakim, unmute marcia
04:15:33 [Zakim]
hideaki has fumi, ikki, kosuke
04:15:33 [Zakim]
Marcia should no longer be muted
04:15:41 [marcia]
about the vocabulary?
04:15:55 [emma]
zakim, who's here ?
04:15:55 [Zakim]
On the phone I see hideaki, antoine, TomB, emma?, kcoyle, jeff_, Marcia, edsu, DanChudnov
04:15:57 [Zakim]
hideaki has fumi, ikki, kosuke
04:16:07 [edsu]
marcia: i can talk about vocabulary and dataset deliverable
04:16:28 [jeff_]
I may have fixed my problem
04:16:39 [jeff_]
zakim, mute me
04:16:39 [Zakim]
jeff_ should now be muted
04:16:46 [edsu]
Topic: Available data: vocabularies and datasets
04:17:12 [edsu]
marcia: in general we have two main parts
04:17:19 [emma]
zakim, mute antoine
04:17:19 [Zakim]
antoine should now be muted
04:17:20 [TomB]
Jeff, you can pick up after Marcia and Antoine have presented
04:17:48 [edsu]
marcia: metadata element sets (rdf schemas, owl ontologies)
04:18:10 [TomB]
04:18:11 [edsu]
marcia: there is a plan that antoine will draw a picture of how metadata terms are reused by each other
04:18:25 [edsu]
marcia: the 2nd major part includes the value-vocabularies and datasets
04:18:47 [edsu]
marcia: the idea is to use the linked-open-data registered in the ckan to show what is relevant for library linked data
04:19:10 [edsu]
marcia: value vocabularies can be used to cover entities and subject vocabularies
04:19:26 [edsu]
marcia: most of the vocabularies are mentioned in the use cases
04:19:45 [edsu]
... the part we haven't finished yet is on published datasets
04:19:46 [emma]
LLD on CKAN :
04:19:55 [edsu]
04:20:04 [emma]
zakim, unmute antoine
04:20:04 [Zakim]
antoine should no longer be muted
04:20:30 [edsu]
kind of interesting too:
04:21:00 [edsu]
antoine: that's the work of william
04:21:18 [marcia]
04:21:19 [edsu]
... we plan on having a specific section on vocabulary datasets, but we have not yet made progress on it
04:21:46 [edsu]
... the idea would be start with a summary, to start with the most representative vocabularies/ontologies and value vocabularies
04:22:09 [edsu]
s/be start/be to start/
04:22:50 [edsu]
... e.g. for frbr there are several ones, we would identify the issues: when there are more than one, and when there aren't any
04:23:30 [jeff_]
zakim, unmute me
04:23:30 [Zakim]
jeff_ should no longer be muted
04:23:32 [edsu]
... we have been working on the side deliverable to help us identify the issue first
04:23:41 [jeff_]
04:23:48 [edsu]
scribenick: kcoyle
04:23:51 [Zakim]
+??P11
04:24:06 [kcoyle]
oops, we've got static
04:24:08 [TomB]
zakim, ??P11 is lukose
04:24:08 [Zakim]
+lukose; got it
04:24:52 [marcia]
zakim, mute me
04:24:52 [Zakim]
Marcia should now be muted
04:25:30 [kcoyle]
trying to explain linked data is a challenge -- i've written a few paragraphs to try to explain the relevant technologies
04:25:50 [kcoyle]
... but it's not just a question of having new tools; have to use domain-specific technologies, etc.
04:26:21 [kcoyle]
... the relevant technologies are allowing us to create the infrastructure; it's not tools, but it's about taking the data we have today
04:26:33 [emma]
s/trying/Jeff: Trying
04:26:39 [kcoyle]
... and mapping to these new technologies; leaving our current infrastructure in place
04:27:19 [kcoyle]
... sees 3-4 different categories of things happening; like take existing relational databases and map those to technologies
04:28:03 [kcoyle]
... can store new data in new ways that aren't as hard to map as our old schemas
04:28:34 [kcoyle]
... use OWL-based designed technologies; there are tools to help us do that development
04:28:54 [kcoyle]
s/designed/design
04:29:35 [kcoyle]
... then there is the controlled vocabulary level, such as SKOS; not classes or properties, but usable vocabularies
04:29:49 [RRSAgent]
I have made the request to generate
antoine
04:30:18 [kcoyle]
... modeling question between what things are best described in OWL and what in SKOS
04:30:40 [kcoyle]
... much of this gets off-loaded to W3C as the keeper of RDF / Semantic Web standards
04:30:52 [edsu]
q+ to ask about using web frameworks and rdfa
04:30:58 [jeff_]
zakim, mute me
04:30:58 [Zakim]
jeff_ should now be muted
04:31:17 [TomB]
ack edsu
04:31:17 [Zakim]
edsu, you wanted to ask about using web frameworks and rdfa
04:31:24 [jeff_]
zakim, unmute me
04:31:24 [Zakim]
jeff_ should no longer be muted
04:32:18 [TomB]
Edsu: A-ha moment for me: Django tools made it easy to create a Website with URIs - that I could use that for publishing RDF too.
04:32:42 [kosuke_]
kosuke_ has joined #lld
04:32:47 [keven]
is there any tech (or policy guidelines) can be used to keep the linkage in linked data (esp. the which used in the name spaces) more sustainable, like cache technology. For the maintainance of the links in linked data is quite fatal.
04:32:57 [TomB]
...Cobble together some RDF/XML. Karen in Open Library: Web publishing framework - created templates that would generate RDF.
04:33:36 [emma]
zakim, mute tomeB
04:33:36 [Zakim]
sorry, emma, I do not know which phone connection belongs to tomeB
04:33:39 [TomB]
...Seems overwhelming when people discuss SW tech stack - "convert all your data", "you need a SPARQL endpoint" - developers tune out.
04:34:10 [TomB]
...Legacy systems that we have. Do not have to discard to do something useful.
04:34:50 [antoine]
@keven: sthg like that?
04:35:02 [TomB]
Jeff: In my case, played with Rails - still doing domain models - object-oriented classes - variables get mapped to database. Tried hard. Could produce RDF that way, but frustrating.
04:35:24 [keven]
ok thanks to antonie. i'll look into that
04:35:29 [TomB]
...That's why I like ?DVRQ database - do in two days what I spent six months doing with Rails.
04:35:39 [TomB]
Edsu: Opposite experience.
04:36:20 [TomB]
Jeff: Maybe walk thru the steps I took. Compare scaffolding languages. Important that we be able to do with data we have. Chance to start to migrate.
04:37:00 [TomB]
Edsu: RDFa. Rails and Django.
04:37:25 [TomB]
Jeff: But Grails has default URI pattern. Now you're stuck. URIs a huge problem - designing good ones.
04:38:15 [TomB]
Edsu: Haven't had any trouble - optimized for defining URI spaces. Get you thinking about resources and how am I naming them. Web developers looking at this section would want to see this.
04:38:20 [TomB]
Jeff: Compare approaches.
04:38:30 [edsu]
scribenick: edsu
04:39:16 [edsu]
keven: are there any policies for keeping the linkage in linked data, e.g. which namespaces are used, using cache technologies to help maintain links
04:40:02 [edsu]
jeff_: caching is normally for network efficiency ; the domain not being supported anymore is a bit different
04:40:17 [edsu]
jeff_: imagine dbpedia going away ... i don't know what the answer is
04:40:27 [edsu]
jeff_: publishing the information in bulk can help
04:40:30 [keven]
thx anyway
04:40:42 [edsu]
q+ to mention 301
04:40:57 [edsu]
TomB: any more questions can be typed into IRC
04:41:03 [TomB]
ack edsu
04:41:03 [Zakim]
edsu, you wanted to mention 301
04:41:09 [keven]
do you have any comments on drupal used for linked data application?
04:41:36 [marcia]
ed: big search engines look at things that moves
04:41:39 [keven]
we plan to have a try on drupal to publish some exprimental biblio data
04:41:45 [jeff_]
The PURL server can help too. Somebody could step in.
04:41:50 [jeff_]
zakim, mute me
04:41:50 [Zakim]
jeff_ should now be muted
04:42:23 [marcia]
ed: this is the architecture of the Web issue
04:42:34 [TomB]
Edsu: Do a 301 redirect when a site moves permanently to another location. People who care about link integrity - don't want to serve up dead links - part of the architecture. Link rot. Identifiers break. They do not give the URI enough respect.
04:42:42 [lukose]
are there any guideline for representing and linking the "DataSet" and the "Model" used in producing the results outlined in a scientific publication, to the "meta-data" of the publication?
04:43:22 [lukose]
yes
04:43:25 [edsu]
kcoyle: is this about the underlying data?
04:43:47 [kosuke_]
@keven are you using this module?
04:43:48 [lukose]
absolutely correct!
04:43:50 [edsu]
TomB: so linking a scientific publication with the data used
04:43:51 [marcia]
tom: this is about linking sci publication with the data used to describe the publication
04:44:03 [edsu]
04:44:09 [marcia]
... is there a standard way to link the two?
04:44:09 [keven]
@kosuke: yes
04:44:39 [edsu]
04:44:45 [marcia]
ed: someone sent a link to this article
04:44:47 [emma]
suggest to look at
04:45:21 [TomB]
Edsu: Link to D-lib article in January - looking at this problem. Looking at LD approaches to linking data to publications. A consortium that started in 2009.
04:45:51 [jeff_]
zakim, unmute me
04:45:51 [Zakim]
jeff_ should no longer be muted
04:45:56 [TomB]
...Herbert van de Sompel - OAI-ORE.
04:46:02 [emma]
zakim, mute me
04:46:02 [Zakim]
emma? should now be muted
04:46:23 [TomB]
Jeff: Hard time understanding OAI-ORE - aggregations nice, but what are its boundaries? How do you draw those boundaries.
04:46:25 [edsu]
jeff_: hard to imagine what the boundaries of aggregations are in oai-ore and how to draw those boundaries
04:46:42 [edsu]
antoine: i think ore could be used, but there is no standard way to use it to link articles to datasets
04:46:52 [jeff_]
zakim, mute me
04:46:52 [Zakim]
jeff_ should now be muted
04:46:52 [edsu]
antoine: i think it's still an active topic of research
04:47:10 [TomB]
Antoine: ORE could be used but there is no standard way to use it for linking articles to datasets. Still a topic of research. Alot of activitity about scientific data. Have not heard about standard ways.
04:47:14 [edsu]
... i've not heard of standard ways, but there are lots of things happening
04:47:28 [emma]
zakim, unmute me
04:47:28 [Zakim]
emma? should no longer be muted
04:47:31 [edsu]
lukose: good question :)
04:47:32 [kcoyle]
just found this:
04:47:36 [lukose]
ok, thanks guys.... this is an interesting challange...
04:47:53 [antoine]
could be interesting to mention in report!
04:48:00 [edsu]
antoine++
04:48:28 [edsu]
TomB: perhaps you could consider mentioning it in your section?
04:48:47 [jeff_]
The Dryad project at UNC Chapel Hill is working on relating scientific publications with scientific data sets
04:48:49 [marcia]
D-Lib article:
04:49:19 [marcia]
D-Lib: isCitedBy: A Metadata Scheme for DataCite
04:49:46 [edsu]
antoine: i think it's more of a research area
04:50:09 [jeff_]
04:50:46 [edsu]
edsu: might make sense to capture it as a possible vocabulary gap
04:51:03 [marcia]
D-Lib issue on research data:
04:51:29 [edsu]
TomB: we need to have a good elevator pitch, or top-level story
04:51:45 [edsu]
... one problem we have is that libraries have changed technologies many times
04:51:54 [jeff_]
zakim, mute me
04:51:54 [Zakim]
jeff_ was already muted, jeff_
04:52:02 [edsu]
... the movement to linked data could look like another one
04:52:12 [marcia]
TomB: * antoine, maybe we need to add that metadata scheme even though no use case
04:52:52 [edsu]
... we want to convey that there is a paradigm shift between record based data with statement based data
04:53:23 [marcia]
*/TomB/Antoine
04:53:26 [edsu]
... the report is targeted at decision makers, who will be in a position to set policy within their organisations
04:53:45 [edsu]
TomB: any final questions in the 7 minutes remaining?
04:54:15 [emma]
rrsagent, please draft minutes
04:54:15 [RRSAgent]
I have made the request to generate
emma
04:54:32 [edsu]
TomB: any comments from malaysia, china and japan on how the linked data idea is being perceived, and what sort of arguments do we need to put into place in order to convince decision makers that this is something they should devote some resources to
04:54:39 [marcia]
Tom: do you want to talk: Recommendations (Karen, Tom)
04:55:35 [edsu]
hideaki: is it for leaders of libraries and museums?
04:55:35 [kcoyle]
and top level managers, no?
04:55:41 [edsu]
TomB: yes
04:56:44 [TomB]
Hideaki: in Japan. To decision-makers, we often have to explain benefits of RDF. Prefer to have simple explanations.
04:56:56 [edsu]
TomB++
04:57:05 [lukose]
my challange is in creating awareness of the LOD developments arround the world, to our local lib (national archive, national lib, etc....), so I am conducting workshops...the next challange is the benefits of this to the organization.
04:58:01 [marcia]
TomB: that is exactly what we are trying to summarize just 3-4 pages
04:58:11 [antoine]
q+ on reviewing or contrib to recs
04:58:16 [marcia]
.. the benifits for different categories
04:58:17 [TomB]
ack antoine
04:58:17 [Zakim]
antoine, you wanted to comment on reviewing or contrib to recs
04:58:19 [edsu]
TomB: that's why we're trying to boil down the high level benefits for different groups
04:58:20 [keven]
usually decision makers in library circle used to adopt turn-key solutions for them. they don't care about the linked data technology. so the benefit for them is important to get conciousness. for the techie people they need tools, tools, tools.
04:58:26 [marcia]
.. for librarians, developers
04:58:54 [lukose]
yes, I would very much like to help....
04:59:10 [edsu]
antoine: could hideaki and keven play a more formal role in reviewing the benefits? since they have to talk to decision makers it would be great to have them look at it
04:59:22 [edsu]
s/keven/lukose/
04:59:43 [kcoyle]
I also suspect that benefits may vary by country or region... so there may be benefits that we haven't identified?
04:59:54 [edsu]
TomB: currently the benefits secition is about 2 pages, it still has some rough edges, but it should be ready to be reviewed by the teleconference next tuesday
05:00:14 [keven]
i'd love to take a review on this
05:00:20 [marcia]
TomB: the benifit section is very important and to be discussed next week
05:00:29 [edsu]
... since it is so crucial, it would be great if we had your help
05:00:42 [kosuke]
kosuke has joined #lld
05:00:45 [marcia]
.. is any of you can volunteer to review, it will be very helpful.
05:01:00 [marcia]
.. we may sign reviewers on the May 5th
05:01:11 [antoine]
q+ on workshops
05:01:29 [edsu]
TomB: if you could comment on the mailing list which ones work and which ones don't ; also a review of the recommendations would be helpful
05:01:40 [TomB]
ack antoine
05:01:40 [Zakim]
antoine, you wanted to comment on workshops
05:02:43 [edsu]
antoine: one specific point about workshops and education, if there is any experience available in the kind of topic that should be mentioned in such workshops, what sort of targets, it would be really nice, it turns out gunter may not be able to contribute
05:02:45 [marcia]
Antoine: workshops on education, if anyone can jump in to make recommendations that will be helpful
05:02:59 [marcia]
.. especailly if there are expereince
05:03:10 [lukose]
I can make some contribution on my experience in doing these lectures and workshops...
05:03:21 [antoine]
lukose++
05:03:32 [marcia]
*no, ed, I could not see
05:03:35 [kosuke]
@antoine excuse me, does "linking articles to datasets" in ORE mean "citation" in this topic?
05:03:45 [marcia]
*just try to duplicate
05:04:00 [edsu]
kosuke: yes we did look at that in the context of citation
05:04:06 [antoine]
@kosuke: not sure, maybe we could discuss that by email
05:04:14 [edsu]
kosuke: did you run across that wiki page?
05:04:15 [keven]
thanks for having me here
05:04:16 [lukose]
tq
05:04:22 [Zakim]
-jeff_
05:04:22 [emma]
thx !
05:04:23 [Zakim]
-kcoyle
05:04:25 [Zakim]
-Marcia
05:04:28 [dchud]
thank you!
05:04:32 [Zakim]
-edsu
05:04:33 [emma]
rrsagent, please draft minutes
05:04:33 [RRSAgent]
I have made the request to generate
emma
05:04:37 [Zakim]
-DanChudnov
05:04:40 [Zakim]
-hideaki
05:04:41 [antoine]
zakim, please list attendees
05:04:41 [Zakim]
As of this point the attendees have been antoine, TomB, kcoyle, emma?, jeff_, Marcia, fumi, ikki, kosuke, edsu, DanChudnov, lukose
05:04:51 [antoine]
rrsagent, please draft minutes
05:04:51 [RRSAgent]
I have made the request to generate
antoine
05:04:57 [jeff_]
jeff_ has left #lld
05:05:01 [Zakim]
-lukose
05:05:25 [edsu]
kosuke: here were our notes:
05:05:54 [Zakim]
-antoine
05:05:56 [Zakim]
-TomB
05:06:02 [Zakim]
-emma?
05:06:03 [Zakim]
INC_LLDXG()12:00AM has ended
05:06:04 [Zakim]
Attendees were antoine, TomB, kcoyle, emma?, jeff_, Marcia, fumi, ikki, kosuke, edsu, DanChudnov, lukose
05:06:12 [edsu]
kosuke: that's actually how datacite came to my attention, when i was working on those notes w/ kai
05:06:48 [antoine]
rrsagent, bye
05:06:48 [RRSAgent]
I see no action items | http://www.w3.org/2011/04/28-lld-irc | CC-MAIN-2015-14 | refinedweb | 4,082 | 65.86 |
* Peter Zijlstra (a.p.zijlstra@chello.nl) wrote:> On Sat, 2008-09-20 at 05:03 -0400, Steven Rostedt wrote:> > > Oh, and all commands should start with the namespace.> > > > ring_buffer_alloc()> > ring_buffer_free()> > ring_buffer_record_event()> > I really think we should separate the ringbuffer management from the> event stuff.> Sure, I am strongly in favor of separating those two, given theyrepresent two different things. However, the requirement I have heard atKS2008 was to provide - Unified buffering mechanism- Timestamps synchronized across all buffers- Unified event IDs management, so events from various sources could be shared between tools.- As of my understanding, unified event structure, which can be exported to userspace and be shared across different tools.- Unified buffer control/management mechanism.These all represent different infrastructure parts, but are all neededif we want tools to be able to share the data exported through thosebuffers.Relay is a good example of having only a _single_ of these layers incommon : there is currently no way the different relay users can sharethe data they collect because they have simply no idea how othersstructure their data.Mathieu-- Mathieu DesnoyersOpenPGP key fingerprint: 8CD5 52C3 8E3C 4140 715F BA06 3F25 A8FE 3BAE 9A68 | https://lkml.org/lkml/2008/9/22/455 | CC-MAIN-2015-22 | refinedweb | 192 | 53.1 |
Persistent Objects and InterSystems IRIS SQL
A key feature in InterSystems IRIS® is its combination of object technology and SQL. You can use the most convenient access mode for any given scenario. This chapter describes how InterSystems IRIS provides this feature and gives an overview of your options for working with stored data.
The samples shown in this chapter are from the Samples-Data sample (). InterSystems recommends that you create a dedicated namespace called SAMPLES (for example) and load samples into that namespace. For the general process, see Downloading Samples for Use with InterSystems IRIS.
Introduction
InterSystems IRIS provides what is sometimes called an object database: a database combined with an object-oriented programming language. As a result, you can write flexible code that does all of the following:
Perform a bulk insert of data via SQL.
Open an object, modify it, and save it, thus changing the data in one or more tables without using SQL.
Create and save new objects, adding rows to one or more tables without using SQL.
Use SQL to retrieve values from a record that matches your given criteria, rather than iterating through a large set of objects.
Delete an object, removing records from one or more tables without using SQL.
That is, you can choose the access mode that suits your needs at any given time.
Internally, all access is done via direct global access, and you can access your data that way as well when appropriate. (If you have a class definition, it is not recommended to use direct global access to make changes to the data.)
InterSystems SQL
InterSystems IRIS provides an implementation of SQL, known as InterSystems SQL.
InterSystems SQL supports the complete entry-level SQL-92 standard with a few exceptions and several special extensions. InterSystems SQL also supports indices, triggers, BLOBs, and stored procedures (these are typical RDBMS features but are not part of the SQL-92 standard). For a complete list, see Using InterSystems SQL.
Where You Can Use InterSystems SQL
You can use InterSystems SQL within routines and within methods. To use SQL in these contexts, you can use either or both of the following tools:
Embedded SQL, as in the following example:
&sql(SELECT COUNT(*) INTO :myvar FROM Sample.Person) Write myvarCopy code to clipboard
You can use embedded SQL in ObjectScript routines and in methods written in ObjectScript.
Dynamic SQL (the %SQL.Statement and %SQL.StatementResult classes), as in the following example:
SET myquery = "SELECT TOP 5 Name,DOB FROM Sample.Person" SET tStatement = ##class(%SQL.Statement).%New() SET tStatus = tStatement.%Prepare(myquery) SET rset = tStatement.%Execute() //now use proprties of rset objectCopy code to clipboard
You can use dynamic SQL in any context.
Also, you can execute InterSystems SQL directly within the SQL Shell (in the Terminal) and in the Management Portal. Each of these includes an option to view the query plan, which can help you identify ways to make a query more efficient.
Object Extensions to SQL
To make it easier to use SQL within object applications, InterSystems IRIS includes a number of object extensions to SQL.
One of the most interesting of these extensions is ability to follow object references using the reference (“–>”) operator. For example, suppose you have a Vendor class that refers to two other classes: Contact and Region. You can refer to properties of the related classes using the reference operator:
SELECT ID,Name,ContactInfo->Name FROM Vendor WHERE Vendor->Region->Name = 'Antarctica'
Of course, you can also express the same query using SQL JOIN syntax. The advantage of the reference operator syntax is that it is succinct and easy to understand at a glance.
Special Options for Persistent Classes
In InterSystems IRIS, all persistent classes extend %Library.Persistent (also referred to as %Persistent). This class provides much of the framework for the object-SQL correspondence in InterSystems IRIS. Within persistent classes, you have options like the following:
Methods to open, save, and delete objects.
When you open a persistent object, you specify the degree of concurrency locking, because a persistent object could potentially be used by multiple users or multiple processes.
When you open an object instance and you refer to an object-valued property, the system automatically opens that object as well. This process is referred to as swizzling (also known as lazy loading). Then you can work with that object as well. For example:
Set person=##class(Sample.Person).%OpenId(10) Set person.Name="Andrew Park" Set person.Address.City="Birmingham" Do person.%Save()Copy code to clipboard
Similarly, when you save an object, the system automatically saves all its object-valued properties as well; this is known as a deep save. There is an option to perform a shallow save instead.
Default query (the Extent query) that is an SQL result set that contains the data for the objects of this class.
In this class (or in other classes), you can define additional queries; see “Class Queries,” earlier in this book.
Ability to define relationships between classes that are projected to SQL as foreign keys.
A relationship is a special type of object-valued property that defines how two or more object instances are associated with each other. Every relationship is two-sided: for every relationship definition, there is a corresponding inverse relationship that defines the other side. InterSystems IRIS automatically enforces referential integrity of the data, and any operation on one side is immediately visible on the other side. Relationships automatically manage their in-memory and on-disk behavior. They also provide superior scaling and concurrency over object collections (see “Collection Classes” in the previous chapter).
Ability to define foreign keys. In practice, you add foreign keys to add referential integrity constraints to an existing application. For a new application, it is simpler to define relationships instead.
Ability to define indices in these classes.
Indices provide a mechanism for optimizing searches across the instances of a persistent class; they define a specific sorted subset of commonly requested data associated with a class. They are very helpful in reducing overhead for performance-critical searches..
Ability to define triggers in these classes to control what occurs when rows are inserted, modified, or deleted.
Ability to project methods and class queries as SQL stored procedures.
Ability to fine-tune the projection to SQL (for example, specifying the table and column names as seen in SQL queries).
Ability to fine-tune the structure of the globals that store the data for the objects.
SQL Projection of Persistent Classes
For any persistent class, each instance of the class is available as a row in a table that you can query and manipulate via SQL. To demonstrate this, this section uses the Management Portal and the Terminal, which are introduced later in this book.
Demonstration of the Object-SQL Projection
Consider the Sample.Person class in SAMPLES. If we use the Management Portal to display the contents of the table that corresponds to this class, we see something like the following:
(This is not the same data that you see, because this sample is repopulated at each release.) Note the following points:
The values shown here are the display values, not the logical values as stored on disk.
The first column (#) is the row number in this displayed page.
The second column (ID) is the unique identifier for a row in this table; this is the identifier to use when opening objects of this class. (In this class, these identifiers are integers, but that is not always true.)
These numbers happen to be the same in this case because this table is freshly populated each time the SAMPLES database is built. In a real application, it is possible that some records have been deleted, so that there are gaps in the ID values and these values do not match the row numbers.
In the Terminal, we can use a series of commands to look at the first person:
SAMPLES>set person=##class(Sample.Person).%OpenId(1) SAMPLES>write person.Name Van De Griek,Charlotte M. SAMPLES>write person.FavoriteColors.Count() 1 SAMPLES>write person.FavoriteColors.GetAt(1) Red SAMPLES>write person.SSN 571-15-2479
These are the same values that we see via SQL.
Basics of the Object-SQL Projection
Because inheritance is not part of the relational model, the class compiler projects a “flattened” representation of a persistent class as a relational table. The following table lists how some of the various object elements are projected to SQL:
The projected table contains all the appropriate fields for the class, including those that are inherited.
Classes and Extents
InterSystems IRIS uses an unconventional and powerful interpretation of the object-table mapping.
All the stored instances of a persistent class compose what is known as the extent of the class, and an instance belongs to the extent of each class of which it is an instance. Therefore:
If the persistent class Person has the subclass Student, the Person extent includes all instances of Person and all instances of Student.
For any given instance of class Student, that instance is included in the Person extent and in the Student extent.
Indices automatically span the entire extent of the class in which they are defined. The indices defined in Person contain both Person instances and Student instances. Indices defined in the Student extent contain only Student instances.
The subclass can define additional properties not defined in its superclass. These are available in the extent of the subclass, but not in the extent of the superclass. For example, the Student extent might include the FacultyAdvisor field, which is not included in the Person extent.
The preceding points mean that it is comparatively easy in InterSystems IRIS to write a query that retrieves all records of the same type. For example, if you want to count people of all types, you can run a query against the Person table. If you want to count only students, run the same query against the Student table. In contrast, with other object databases, to count people of all types, it would be necessary to write a more complex query that combined the tables, and it would be necessary to update this query whenever another subclass was added.
Object IDs
Each object has a unique ID within each extent to which it belongs. In most cases, you use this ID to work with the object. This ID is the argument to the following commonly used methods of the %Persistent class:
%DeleteId()
%ExistsId()
%OpenId()
The class has other methods that use the ID, as well.
How an ID Is Determined
InterSystems IRIS assigns the ID value when you first save an object. The assignment is permanent; you cannot change the ID for an object. Objects are not assigned new IDs when other objects are deleted or changed.
Any ID is unique within its extent.
The ID for an object is determined as follows:
For most classes, by default, IDs are integers that are assigned sequentially as objects of that class are saved.
For a class that is used as the child in a parent-child relationship, the ID is formed as follows:
parentID||childIDCopy code to clipboard
Where parentID is the ID of the parent object and childID is the ID that the child object would receive if it were not being used in a parent-child relationship. Example:
104||3Copy code to clipboard
This ID is the third child that has been saved, and its parent has the ID 104 in its own extent.
If the class has an index of type IdKey and the index is on a specific property, then that property value is used as the ID.
SKU-447Copy code to clipboard
Also, the property value cannot be changed.
If the class has an index of type IdKey and that index is on multiple properties, then those property values are concatenated to form the ID. For example:
CATEGORY12||SUBCATEGORYACopy code to clipboard
Also, these property values cannot be changed.
Accessing an ID
To access the ID value of an object, you use the %Id() instance method that the object inherits from %Persistent.
In SQL, the ID value of an object is available as a pseudo-field called %Id. Note that when you browse tables in the Management Portal, the %Id pseudo-field is displayed with the caption ID:
Despite this caption, the name of the pseudo-field is %Id.
Storage
Each persistent class definition includes information that describes how the class properties are to be mapped to the globals in which they are actually stored. The class compiler generates this information for the class and updates it as you modify and recompile.
A Look at a Storage Definition
It can be useful to look at this information, and on rare occasions you might want to change some of the details (very carefully). For a persistent class, Studio displays something like the following as part of your class definition:
<Storage name="Default"> <Data name="PersonDefaultData"><Value name="1"> <Value>%%CLASSNAME</Value> </Value> <Value name="2"> <Value>Name</Value> </Value> <Value name="3"> <Value>SSN</Value> </Value> <Value name="4"> <Value>DOB</Value> </Value> ... </Storage>
Globals Used by a Persistent Class
The storage definition includes several elements that specify the globals in which the data is stored:
<DataLocation>^Sample.PersonD</DataLocation> <IdLocation>^Sample.PersonD</IdLocation> <IndexLocation>^Sample.PersonI</IndexLocation> ... <StreamLocation>^Sample.PersonS</StreamLocation>
By default, with default storage:
The class data is stored in the data global for the class. Its name starts with the complete class name (including package name). A “D” is appended to the name. For example: Sample.PersonD
The index data is stored in the index global for the class. Its name starts with the class name and ends with an “I”. For example: Sample.PersonI
Any saved stream properties are stored in the stream global for the class. Its name starts with the class name and ends with an “S”. For example: Sample.PersonS
If the complete class name is long, the system automatically uses a hashed form of the class name instead. So when you view a storage definition, you might sometimes see global names like ^package1.pC347.VeryLongCla4F4AD. If you plan to work directly with the data global for a class for any reason, make sure to examine the storage definition so that you know the actual name of the global.
Informally, these globals are sometimes called the class globals, but this can be a misleading phrase. The class definitions are not stored in these globals.
For more information on how global names are determined, see “Globals” in Defining and using Classes.
Default Structure for a Stored Object
For a typical class, most data is contained in the data global, which includes nodes as follows:
For an example, see “A Look at Stored Data,” later in this chapter.
Notes
Note the following points:
Never redefine or delete storage for a class that has stored data. If you do so, you will have to recreate the storage manually, because the new default storage created when you next compile the class might not match the required storage for the class.
During development, you may want to reset the storage definition for a class. You can do this if you also delete the data and later reload or regenerate it.
By default, as you add and remove properties during development, the system automatically updates the storage definition, via a process known as schema evolution.
The exception is if you use a non-default storage class for the <Type> element. The default is %Storage.Persistent; if you do not use this storage class, InterSystems IRIS does not update the storage definition.
Options for Creating Persistent Classes and Tables
To create a persistent class and its corresponding SQL table, you can do any of the following:
Use Atelier to define a class based on %Persistent. When you compile the class, the system creates the table.
In the Management Portal, you can use the Data Migration Wizard, which reads an external table, prompts you for some details, generates a class based on %Persistent, and then loads records into the corresponding SQL table.
You can run the wizard again later to load more records, without redefining the class.
In the Management Portal, you can use the Link Table Wizard, which reads an external table, prompts you for some details, and generates a class that is linked to the external table. The class retrieves data at runtime from the external table.
This is a special case and is not discussed further in this book.
In InterSystems SQL, use CREATE TABLE or other DDL statements. This also creates a class.
In the Terminal (or in code), use the CSVTOCLASS() method of %SQL.Util.Procedures. For details, see the Class Reference for %SQL.Util.Procedures.
Accessing Data
To access, modify, and delete data associated with a persistent class, your code can do any or all of the following:
Open instances of persistent classes, modify them, and save them.
Delete instances of persistent classes.
Use embedded SQL.
Use dynamic SQL (the SQL statement and result set interfaces).
Use low-level commands and functions for direct global access. Note that this technique is not recommended except for retrieving stored values, because it bypasses the logic defined by the object and SQL interfaces.
InterSystems SQL is suitable in situations like the following:
You do not initially know the IDs of the instances to open but will instead select an instance or instances based on input criteria.
You want to perform a bulk load or make bulk changes.
You want to view data but not open object instances.
(Note, however, that when you use object access, you can control the degree of concurrency locking. If you know that you do not intend to change the data, you can use minimal concurrency locking.)
You are fluent in SQL.
Object access is suitable in situations like the following:
You are creating a new object.
You know the ID of the instance to open.
You find it more intuitive to set values of properties than to use SQL.
A Look at Stored Data
This section demonstrates that for any persistent object, the same values are visible via object access, SQL access, and direct global access.
In Atelier, if we view the Sample.Person class, we see the following property definitions:
/// Person's name. Property Name As %String(POPSPEC = "Name()") [ Required ]; ... /// Person's age.<br> /// This is a calculated field whose value is derived from <property>DOB</property>. Property Age As %Integer [ details removed for this example ]; /// Person's Date of Birth. Property DOB As %Date(POPSPEC = "Date()");
In the Terminal, we can open a stored object and write its property values:
SAMPLES>set person=##class(Sample.Person).%OpenId(1) SAMPLES>w person.Name Newton,Dave R. SAMPLES>w person.Age 14 SAMPLES>w person.DOB 58153
Note that here we see the literal, stored value of the DOB property. We could instead call a method to return the display value of this property:
SAMPLES>write person.DOBLogicalToDisplay(person.DOB) 03/20/2000
In the Management Portal, we can browse the stored data for this class, which looks as follows:
Notice that in this case, we see the display value for the DOB property. (In the Portal, there is another option to execute queries, and with that option you can control whether to use logical or display mode for the results.)
In the Portal, we can also browse the global that contains the data for this class:
Or, in the Terminal, we can write the value of the global node that contains this instance:
zw ^Sample.PersonD("1") ^Sample.PersonD(1)=$lb("","Newton,Dave R.","384-10-6538",58153,$lb("6977 First Street","Pueblo","AK",63163), $lb("9984 Second Blvd","Washington","MN",42829),"",$lb("Red"))
For reasons of space, the last example contains an added line break.
Storage of Generated Code for InterSystems SQL
For InterSystems SQL (except when used as embedded SQL), the system generates reusable code to access the data.
When you first execute an SQL statement, InterSystems IRIS optimizes the query and generates and stores code that retrieves the data. It stores the code in the query cache, along with the optimized query text. Note that this cache is a cache of code, not of data.
Later when you execute an SQL statement, InterSystems IRIS optimizes it and then compares the text of that query to the items in the query cache. If InterSystems IRIS finds a stored query that matches the given one (apart from minor differences such as whitespace), it uses the code stored for that query.
You can view the query cache and delete any items in it.
For More Information
For more information on the topics covered in this chapter, see the following:
Defining and Using Classes describes how to define classes and class members in InterSystems IRIS.
Class Definition Reference provides reference information for the compiler keywords that you use in class definitions.
Using InterSystems SQL describes how to use InterSystems SQL and where you can use it.
InterSystems SQL Reference provides reference information on InterSystems SQL.
Using Globals provides details on how InterSystems IRIS stores persistent objects in globals.
The InterSystems Class Reference has information on all non-internal classes provided by InterSystems IRIS. | https://docs.intersystems.com/irislatest/csp/docbook/Doc.View.cls?KEY=GORIENT_ch_persistence | CC-MAIN-2020-45 | refinedweb | 3,547 | 54.63 |
How to get Users of Windows/Linux Systems using Python?
Hello Geek! In this article, we will use Python to get the current users on the Windows and Linux Systems.
The method that we are going to use to get the current users is users(). It is defined in the psutil Library. Therefore syntax of the function will be
syntax: psutil.users()
The function psutil.users() returns all the users that are connected to the System. It returns the users as a list of named tuples.
Each tuple has the name, terminal, host, started and pid as its attributes. The attribute name gives us the username.
PROGRAM
First, import the psutil Python Library to access the users() method.
import psutil
Now, use the method psutil.users() method to get the list of users as a named tuple and assign to the variable user_list.
Implement a print statement to display that we are going to print the usernames of the users associated with the System.
Iterate over the list of users using a for a statement as the variable user.
Now, under the for loop, we can get the username from the named tuple as user.name and assign it to the variable username.
Now, print the variable username using a print statement.
user_list = psutil.users() print("Users associated with this System are :") for user in user_list: username = user.name print(username)
Output
Users associated with this System are : Guthas
Hurrah! We have successfully obtained the username of all the users associated with the System using simple lines of code in Python.
Thank you for reading this article. I hope this article helped you in some way. Also do check out our other related articles below:
- How to Find and List All Running Processes in Python
- Python Program to get IP Address of your Computer | https://www.codespeedy.com/get-users-of-windows-linux-systems-using-python/ | CC-MAIN-2021-43 | refinedweb | 304 | 75.91 |
C++ <cstdlib> - mblen() Function
The C++ <cstdlib> mblen() function returns the size (in bytes) of the multibyte character whose first byte is pointed to by str and examining at most n bytes.
This function has its own internal shift state, which is altered as necessary only by calling it. If str is a null pointer, it resets its internal conversion state to represent the initial shift state and returns whether multibyte encoding is state-dependent.
Syntax
int mblen(const char *str, size_t n)
Parameters
Return Value
When str is not a null pointer, it returns the number of bytes that are contained in the multibyte character or -1 if the first bytes pointed to by str do not form a valid multibyte character or 0 if str is pointing at the null charcter '\0'.
When str is a null pointer, it returns 0 if the current multibyte encoding is not state-dependent or a non-zero value if the current multibyte encoding is state-dependent.
Example:
In the example below, mblen() and mbtowc() functions are used in the user-defined function printbuffer(), which prints a multibyte string character by character.
#include <cstdio> #include <cstdlib> void printbuffer (char* str, size_t n){ int length; wchar_t dest; mblen (NULL, 0); //reset mblen mbtowc (NULL, NULL, 0); //reset mbtowc while (n > 0) { length = mblen(str, n); if (length < 1) break; mbtowc(&dest, str, length); printf("[%lc]", dest); str = str + length; n = n - length; } } int main (){ char str [] = "Hello World!"; printbuffer (str, sizeof(str)); return 0; }
The output of the above code will be:
[H][e][l][l][o][ ][W][o][r][l][d][!]
❮ C++ <cstdlib> Library | https://www.alphacodingskills.com/cpp/notes/cpp-cstdlib-mblen.php | CC-MAIN-2021-43 | refinedweb | 272 | 59.77 |
"Getting an issue fixed" and "QHash result intersection performance"
There is a Qt bug (or a missing improvement) that starts killing one of my algorithms due to complexity. Actually there a probably some ways of doing special optimizations case-by-case to improve this... but this time I don't want to bother you with the technical side of the problem.
My actual issue now exists for 14 months. And it still is a big problem for me, making me creating horrible workarounds. And it even isn't evaluated! I can only guess if it can be done at all (and when).
So my actual question is much simpler (and maybe stupid): Is there a way to make a Qt issue rising in priority?
There is voting. But even if the issue is a showstopper (or its very critical) you will not get a lot of votes if there are few people doing the same thing.
I could buy commercial support. But I can not affort it (actually I do not know current prices but back to Trolltech times it was far too expensive for me).
Unfortunately I do not have time to work into the processes and code that would allow me to contribute directly.
So finally I am stuck wondering if there is a way to get more attention to a Qt Bug Tracker issue. Or at least getting a kind evaluation of the issue so I know what I am dealing with.
Is there some e-mail? Is there some special forum I could beg for votes? Can issues be resubmitted? Is there some way of motivating someone from the community fixing a specific issue? I surely could not compensate the actual effort so my few bucks would probably be not enough making Digia or someone else fixing a specific issue.
EDIT: Changed the title since the thread is more of a technical discussion now
Hi,
You can also post the link to the bug report here
- JKSH Moderators
There's the "development mailing list": which you can subscribe to to send emails. Emails there are more visible to Qt engineers than bug reports (which only alert the assignee, I think). If the bug is bad enough, someone will escalate it.
Note that they are currently preparing for the Qt 5.2 release which is scheduled for release in December. If you email now and the fix is straightforward enough, there's a chance it might be fixed for Qt 5.2. From 11 November 2013 onwards, only issues deemed "blockers" will be fixed. Others will have to wait until Qt 5.2.1 or later.
If you know what the issue is, you could patch your copy of Qt (I remember you've compiled your own version?). You can also submit your patch to fix Qt (patches are reviewed far quicker than bug reports).
@SGaist: I intentionally avoided posting the link here. Imagine more people would do this and would flood the forum with copies of bug tracker issues.
Anyway if you think it's the right place, here it is:
It is about an algorithm I use that calls QHash::values(key) on multiple related QHash objects and intersects the results. The latter is not possible in accetable speed because QHash::values(key) returns an unordered QList<value> instead of QSet<value> which does not provide a fast intersect() method. QList::toSet() is my current workaround but slows down the code significantly. I have no idea why they preferred QList<value> for this since the data is unordered anyway.
@JKSH: No, actually I decided not to use self-build Qt. I instead invested some time into testing ANGLE on VMs and decided to switch to the ANGLE builds (which are provided in both x86 and x64 for VS2012).
The mailing list is a good idea. I will subscribe to it.
I wonder if there is any website collecting bounties for missing Qt features or bugs?!
Are you thinking of something like:
@
QHash<int, QString> myHash;
QSet<QString> valuesSet = myHash.valuesSet(myKey);
@
?
Edit:Indeed it was QString I had in mind
Yes (providing you intended to write "QSet<QString> valuesSet"). That's exactly what I need. But I suppose there are a few more functions that could be improved in the same way.
Do you think that bounty idea is a good one?
bq. QList::toSet() is my current workaround but slows down the code significantly
if you investigated so much the issue tbh I wonder why you have not done your own "maptoset" or "hashtoset" templated functions? with the code similar like in toList qt's src a code as bellow is better than your workaround:
@template <class Key, class T>
QSet<T> maptoset(QMap<Key,T> map)
{
QSet<T> res; res.reserve(map.size()); typename QMap<Key,T>::const_iterator i = map.begin(); while (i != map.end()) { res.insert(i.value()); ++i; } return res;
}
template <class Key, class T>
QSet<T> hashtoset(QHash<Key,T> map)
{
QSet<T> res; res.reserve(map.size()); typename QHash<Key,T>::const_iterator i = map.begin(); while (i != map.end()) { res.insert(i.value()); ++i; } return res;
}
...
QHash<int,QString> myHash1;
QHash<int,QString> myHash2;
QHash<int,QString> myHash3;
myHash1[1] = "one"; myHash1[2] = "two"; myHash1[3] = "three"; myHash2[1] = "one"; myHash2[2] = "three"; myHash2[3] = "two"; myHash3[1] = "one"; myHash3[2] = "two"; myHash3[3] = "five"; QSet<QString> set1 = hashtoset(myHash1); QSet<QString> set2 = hashtoset(myHash2); QSet<QString> set3 = hashtoset(myHash3); QSet<QString> setIntersect = set1.intersect(set2.intersect(set3)); qDebug()<<"interesection"<<setIntersect;
@
@NicuPopescu: Thanks for you suggestion. But that's not what I want to do. I am afraid you missed the point.
Could you show an example of what you want to do ?
it was an answer to the unhappy workaround :) ... as regarding the main topic I let the other advanced people here to respond
QMap::values() and QHash::values() can only sensibly return a QList. Both functions return all the values associated with the key specified in reverse insertion order (or all keys if no key is given). This list can, and in the general case will, contain duplicates. What you are proposing would have values() return a QSet where the values are the keys: this cannot contain duplicates. Your proposal might fit your particular data set but not the general case.
Your problem is how to efficiently find the intersection of several unordered lists. You convert each list to a QSet and then use intersect(), but that involves hashing every value several times. Have you tried the generic std::set_intersection approach?
@
#include <algorithm>
QList<int> first;
first << 35 << 10 << 15 << 20 << 15 << 35 << 30 << 35;
QList<int> second;
second << 10 << 45 << 35 << 35 << 35 << 35;
QList<int>::iterator it;
std::sort(first.begin(), first.end());
it = std::unique(first.begin(), first.end());
first.erase(it, first.end());
std::sort(second.begin(), second.end());
it = std::unique(second.begin(), second.end());
second.erase(it, second.end());
QList<int> result;
std::set_intersection (
first.begin(), first.end(),
second.begin(), second.end(),
std::back_inserter(result));
qDebug() <<"Result =" << result;
@
@ChrisW67: Your algorithm is much better than my workaround. It's about twice as fast. I will use it instead. Thank you very much!
But unfortunately it still is too slow for my application.
I would like to discuss my proposal. I think it would give this kind of data analysis a major speedup and is worth being considered. Additionally, using QHash::valuesSet(key) + QSet::intersect() would be much more easy to use and to understand.
I think having a QHash (or a QMultiHash in my case) with n:1 relation isn't unusual. Actually that is what was QMultiHash made for. There are a lot of applications where a fast n:1 lookup is needed. Simply most application that process large data amounts without involving a fully featured database. In these applications, valuesSet(key) would VERY useful. And even for a 1:n hash it could be useful to get a set of unique values. So I see no reason why valuesSet(key) (or similar) would be a bad idea. Specifically I don't think it is too specialized. Actually it would be probably more useful than the QList variant since getting the values in reverse insertion order is needed not very often on a QHash. But speed is a neck-breaker, especially for QHash
You say that creating a set involves expensive hashing. You are right. This is probably killing my code. But that hashing is only necessary using my workaround. QHash and QSet use the same hashing algorithm (I think QSet internally is a QHash), right? A Q(Multi)Hash::valuesSet(key) method could simply copy the found hashes from the source QHash to the result QSet. This would be surely quick. Then that would allow doing the desired fast QSet::intersect() without separate (expensive) std:unique and sort calls. I suppose that would be even much faster than your algorithm.
Are there any technical facts I am missing why this wouldn't work?
Hashes are designed for rapid retrieval by key, i.e, 1 to n lookup. The keys are hashed to achieve the speed on large data sets (for small key counts it's not worth the effort). Whether there is one or many values for a given key is largely irrelevant: the values are simply stored in the correct hash bucket.
While QSet is based on a QHash what you are expecting as a result is a set built from the values for a given key in the source hash. The values are not hashed in the source QHash, so they will have to hashed in order to become the keys in the QSet internal hash table. Whether you do it internally or externally to QHash will make little performance difference.
The problem you described is finding all the values that are common to all the keys you started with. This tells you nothing about the keys to which these values belong that you did not already know at the outset. You are not determining the keys that contain a certain value, a task for a which a second, reversed hash would be suitable. Perhaps I do not have a grasp on the problem.
If you only ever need this structure for this query, or need the multiple values to be unique, then you could make the structure a map from key to QSet<valueType> so you build and store the sets as you go. You still have to hash all the values, but you move the cost from query to insertion time.
You are right, those are the wrong hashes. They would need to be calculated from the scratch. This would not work.
Actually the entire data structures used by me are pretty much optimized to speed up read accesses by moving the cost to insertion. This is ok and desired. So your map-of-sets idea is pretty good. I will definitely try this! I am not sure if it would be better to first merge those sub-sets to intersect that with the main result or to immediately intersect each of the sub-sets with the main result.
I think this solves my problem. But please allow me explore one more thought.
The problem with my intersection idea is the fact that QSet needs hashes for data storage. This is expensive. But QMap does not suffer from this drawback. What if someone would build something like a tree-based set, lets call it QTree. How would such a tree perform on my cascaded lookup-and-intersect problem? QMap and QHash do not replace each other - they both have their drawbacks and so they both exist. I would expect the same for QSet and something like QTree. Why does no such a container exist?
Hi,
first I missed your point, then I thought how to do hash tables as hash lists (sets with duplicates) from one key's multiple values and then a fast intersect function on them:
@template <class Key, class T>
QHash<T,T> HashToHashList(QHash<Key,T> hash)
{
QHash<T,T> res; res.reserve(hash.size()); typename QHash<Key,T>::const_iterator i = hash.begin(); while (i != hash.end()) { res.insertMulti(i.value(),i.value());//difference from QSet which uses
//insert() ... now res is equivalent to QSet with duplicate values!
++i;
}
return res;
}
template <class T>
QHash<T,T> intersectHashLists(const QHash<T,T> &hash1,const QHash<T,T> &hash2)
{
QHash<T,T> copy1(hash1);
QHash<T,T> copy2(hash2);
typename QHash<T,T>::const_iterator i = hash1.constEnd();
while (i != hash1.constBegin()) {
--i;
if (!copy2.contains(*i))//fast look up by hash function
copy1.remove(*i);
}
return copy1;
}
...
QHash<int,QString> myHash1;
QHash<int,QString> myHash2;
QHash<int,QString> myHash3;
myHash1[1] = "one"; myHash1[1] = "one"; myHash1[2] = "two"; myHash1[3] = "three"; myHash1.insertMulti(1,"four"); myHash1.insertMulti(1,"eight"); myHash1.insertMulti(1,"five"); myHash1.insertMulti(1,"six"); myHash1.insertMulti(1,"one"); qDebug()<<"myHash1"<<myHash1; myHash2[1] = "one"; myHash2[2] = "three"; myHash2[3] = "two"; myHash2.insertMulti(1,"four"); myHash2.insertMulti(1,"seven"); myHash2.insertMulti(1,"five"); myHash2.insertMulti(1,"six"); QHash<QString,QString> hashList1 = HashToHashList(myHash1); QHash<QString,QString> hashList2 = HashToHashList(myHash2); qDebug()<<"hashList1"<<hashList1; qDebug()<<"hashList2"<<hashList2; QHash<QString,QString> intersectionHashLists = intersectHashLists(hashList1,hashList2); qDebug()<<"intersectionHashLists"<<intersectionHashLists;
...
@
QSet intert() source:
@ inline iterator insert(const T &value)
{ return static_cast<typename Hash::iterator>(q_hash.insert(value, QHashDummyValue()));//does not allow duplicates@
hope I have not missed the point again :)
L.E. brr ... I missed the key finding again but I'll follow up :)
@NicuPopescu: I think your new algorithm is more or less the same as I requested in my issue. The line "res.insertMulti(i.value(),i.value());" does pretty much the same as set.insert() since it also calculates a hash for each value (which is the responsible for making my requested algorithm slow too).
EDIT: And I missed your edit :-)
except that for copying from source to QHash or QSet involves calls to qhash function, there is an important difference in my approach: you can have duplicates, entire source will be found in new copy; I think the solution works well if you don't need to filter by a key which I missed to address in pursuing how to convert a container(I used QHash with mulitple values but it could be other) to a hash table for fast intersections ... edit: I was so sure that I found a possible solution and I realized after posting that I forgot to treat finding values by a key
to filter by a key is not so big deal with little condition: either to have access to hash data or at least to have access to hash iterator encapsulated QHashNode
now I have other wonder: since templated code in general is placed in headers, as it is the case for stl or qt container classes, why it couldn't be a solution to work with a local/project working copy slightly modified to meet your needs or even to do changes directly in qt sources, no need of qt rebuild ... all my efforts so far was to find a solution keeping qt source untouched
I slightly modified ..\Qt5.1.1\5.1.1\mingw48_32\include\QtCore\qhash.h
@template <class Key, class T>
Q_OUTOFLINE_TEMPLATE QHash<T,T> QHash<Key, T>::valuesHash(const Key &akey) const
{
QHash<T,T> res;
Node *node = *findNode(akey);
if (node != e) {
do {
res.insertMulti(node->value,node->value);
} while ((node = node->next) != e && node->key == akey);
}
return res;
}@
and added as member in QHash class and it works as expected ... hope so :) | https://forum.qt.io/topic/33837/getting-an-issue-fixed-and-qhash-result-intersection-performance | CC-MAIN-2018-39 | refinedweb | 2,604 | 65.12 |
#include <CglTreeInfo.hpp>
Inheritance diagram for CglTreeInfo:
Definition at line 13 of file CglTreeInfo.hpp.
Default constructor.
Copy constructor.
Destructor.
Clone.
Reimplemented in CglTreeProbingInfo.
Assignment operator.
Take action if cut generator can fix a variable (toValue -1 for down, +1 for up).
Reimplemented in CglTreeProbingInfo.
Definition at line 55 of file CglTreeInfo.hpp.
Initalizes fixing arrays etc - returns >0 if we want to save info 0 if we don't and -1 if is to be used.
Reimplemented in CglTreeProbingInfo.
Definition at line 58 of file CglTreeInfo.hpp.
The level of the search tree node.
Definition at line 16 of file CglTreeInfo.hpp.
How many times the cut generator was already invoked in this search tree node.
Definition at line 19 of file CglTreeInfo.hpp.
The number of rows in the original formulation.
Some generators may not want to consider already generated rows when generating new ones.
Definition at line 22 of file CglTreeInfo.hpp.
Set true if in tree (to avoid ambiguity at first branch).
Definition at line 24 of file CglTreeInfo.hpp.
Replacement array.
Before Branch and Cut it may be beneficial to strengthen rows rather than adding cuts. If this array is not NULL then the cut generator can place a pointer to the stronger cut in this array which is number of rows in size.
A null (i.e. zero elements and free rhs) cut indicates that the row is useless and can be removed.
The calling function can then replace those rows.
Definition at line 34 of file CglTreeInfo.hpp.
Optional pointer to thread specific random number generator.
Definition at line 36 of file CglTreeInfo.hpp. | http://www.coin-or.org/Doxygen/Smi/class_cgl_tree_info.html | crawl-003 | refinedweb | 271 | 52.46 |
0
So, I wrote some code for appending to an array, and I thought to myself, would be cool to make the method more generic using an interface. I keep getting this error though that basically says that the compiler's best overloaded method that can match this is _____, and it does not like how I am passing it. So I am getting the distinct impression that interfaces cannot be passed by reference. Here is the code:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Test2 { class Program { static void Main(string[] args) { MyClass[] mine = new MyClass[5]; for (int i = 0; i < mine.Length; i++) mine[i] = new MyClass(i); foreach (MyClass temp in mine) Console.WriteLine(temp.ToString()); appendIComparable(ref mine, ref new MyClass(8) ); foreach(MyClass temp in mine) Console.WriteLine(temp.ToString()); pause(); } public static void pause() { Console.Write("Press any key to continue... "); Console.ReadLine(); } public class MyClass : IComparable { public int i; public MyClass(int i) { this.i = i; } public int CompareTo(object obj) { if (obj == null) return 1; MyClass otherClass = obj as MyClass; if (otherClass != null) return this.i.CompareTo(otherClass.i); else throw new ArgumentException("Object is not my class... "); } public override string ToString() { return i.ToString(); } } public static void appendIComparable(ref IComparable[] original, ref IComparable append) { //move original from one array to the other int j = 0; IComparable[] newArray = new IComparable[original.Length + 1]; for (; j < original.Length; j++) { if (original[j].CompareTo(append) > 0) {//if the append customer is larger than the current customer in the first list j++; break; } else newArray[j] = original[j]; } newArray[j] = append;//then add the append customer to the list for (; j < original.Length; j++)//and then finish up appending the customers from the first list to the end list newArray[j] = original[j - 1]; append = null; original = newArray; }//end method }//end class }//end namespace
So am I wrong, or is this just not possible. Also, was for a customer comparison method before, so comments don't quite match up.
Edited by overwraith | https://www.daniweb.com/programming/software-development/threads/471176/passing-an-interface-type-by-reference | CC-MAIN-2017-34 | refinedweb | 344 | 58.38 |
This is part of a series I started in March 2008 - you may want to go back and look at older parts if you're new to this series.
As mentioned last time, over the previous parts I at some point brutally broke our built in operators. I did so by actually implementing proper method calls.
It also made the compiler largely unusuable, and went unnoticed because, well, the compiler is still largely unusable.
So this time we'll add the built in operators back in. At the same time, we'll start the process of getting rid of that obnoxious vestige of C:
runtime.c
I originally hoped to cover this in one part, but it grew and grew, and you're going to have to endure 4 parts of this.
On the upside it represents a return to the low level / code generation focus, along with "threading" the changes through to the Ruby end, and actually adding tests (!).
There are a few things we need to do:
Originally, when we started out, anything the compiler didn't recognize was turned into a call to a function expected to exist and follow C calling convention.
This was convenient, as it allowed adding stuff like simple addition like this:
signed int add(signed int a, signed int b) { return a + b; }
rather than having to figure out the code required to inline the addition directly.
However, Ruby has strange expectations of numbers: They are objects (well, this is not a strange expectation per se - everything is an object in Ruby), and you can add methods to their classes (but really, please, don't do that).
MRI ("Matz Ruby Interpreter" - the disambiguating nickname for the original Ruby, though if you've followed this series this far, you probably knew that) handles integers in part by type tagging, rather than turning them into "proper" objects.
That might be a good route for us to take too, eventually, but there's a ton of caveats to consider (not least that it means you can never just dereference an object pointer).
But for now, lets do the bare minimum (you haven't forgot I'm lazy, have you? defer elegance and finesse in favour of getting something working as quickly as possible).
What classes matter? Let's break out IRB:
$ irb >> 1.class => Fixnum >> Fixnum.superclass => Integer >> Integer.superclass => Numeric >> Numeric.superclass => Object
Essentially we want to implement
Numeric,
Integer and
FixNum and not much more. Eventually that will burn us as our
integers will overflow and act weirdly, or someone tries
to use a
Float, but it's a distinct step up from what
we have now.
So we will implement small bits of
Numeric and
Integer
and
FixNum in terms of a small number of s-expression operators,
which we will then need to figure out how to compile.
We will blatantly disregard overflow issues and expect everyone to behave nicely and stay within the confines of a 32 bit signed integer for now... We will also implement just the bare minimum set of operators.
And we will add some simple test programs.
Our current
runtime.c implements
add,
sub,
div,
mul,
ne,
eq,
not,
and,
gt,
ge,
lt,
le.
(Note that the "and" and "not" above are logical, not bitwise)
Numeric,
Integer and
Fixnum have quite a lot of methods,
but we will for now implement only those which aids us in
removing these.
Lets stub it out:
class Numeric end class Integer < Numeric end class Fixnum < Integer def + other ... end def - other ... end def <= other ... end def == other ... end def < other ... end def > other ... end def >= other ... end def div other end def mul other end # These two definitions are only acceptable temporarily, # because we will for now only deal with integers def * other mul(other) end def / other div(other) end end
We will expand on these with others that can be implemented in terms of the basics later, as well as consider which others might be worthwhile implementing as primitives.
So to recap: For now, we will
otherbeing anything but a Fixnum
That's the first thing to verify, as we need to ensure the method names get suitably mangled to 1) pass through the C compiler, and 2) not clash with other potentially legal method names.
The first problem I ran into was that the test suite has gotten quite broken due to some cucumber change in the last couple of years, so that's fixed in 679ab6a, and I won't go over that change as it's simple to follow.
Secondly, while updating the tests I ran into a minor parser bug in (lack of) handling ';' as a expression terminator. That is fixed (at least to the extent of passing the currently relevant tests) in 0a8b33a.
And the answer is still 'no', so lets take a detour into debugging the parser.
# ruby compiler.rb --norequire lib/core/fixnum.rb reading from file: lib/core/fixnum.rb Missing value in expression / op: #<Oper:0xb74e4334 @pri=6, @assoc=:right, @arity=2, @minarity=2, @type=:infix, @sym=:assign> / vstack: [] / rightv: :other Failed at line 16 / col -1 before: end def < other end
The error messages can clearly need some love, but here's line 16 in lib/core/fixnum.rb at this stage:
def == other
The output from the operator precedence part of the parser indicates it's processing an assignment operator, which it obviously isn't, so this looks superficially like a tokenizer bug. As good a time as any to update our test suite.
To faciliate this I first updated the Rakefile to include a new target 'failing' that only outputs the failing features (in 48d1382)
I then added a basic test or '==' in e347ce4, but this passed so the problem does not appear to be in the operator precedence parser.
In 840262f I then added a basic test for '==' as a method name, and it fails as expected. Instrumenting
parse_fname which is used to parse the
name of a definition, reveals that the offender actually appears to be the operator tokenizer, that actually does not recognize '=='
Before going on to add tests, looking at the code reveals a fairly obvious problem:
# fname ::= name | "[]" def parse_fname name = expect("[]") || expect(Methodname) || expect(Oper) name.is_a?(String) ? name.to_sym : name end
expect(Oper) leads us to this code in
operators.rb:
def self.expect(s) # expect any of the defined operators # if operator found, return it's symbol (e.g. "*" -> :*) # otherwise simply return nil, # as no operator was found by scanner Operators.keys.each do |op| if s.expect(op) return op.to_sym end end return nil end
Spotted the problem yet? How about with this excerpt from the Operators hash:
"=" => Oper.new( 6, :assign, :infix), ... "==" => Oper.new( 9, :eq, :infix),
Oops.
Oper.expect scans the operators linearly, without taking into account length. It is
both horribly inefficient, and flat out broken since any cases where a short token gets inserted
prior to a longer token with the shorter token as a prefix will fail.
This is one of those instances where laziness and lack of tests does come back to bite us later.
So lets add some tests (added in 6198c0a):
Feature: Tokenizers In order to tokenize programs, a series of tokenizer classes provides components that can tokenize various subsets of Ruby tokens. @operators Scenario Outline: Operators Given the expression <expr> When I tokenize it with the Oper tokenizer Then the result should be <result> Examples: | expr | result | | "=" | :"=" | | "==" | :"==" |
You know what? This test passes... Lets check something manually:
# ruby -roperators -e 'p Operators.keys' ["do", "..", "::", "+", "==", "<<", "||", "&&", ",", "!", "<=", "=>", "and", "#index#", "#call#", "-", ".", "or", "/", ":", "#,#", "#flatten#", "{", "[", "-=", "!=", "<", "&", "}", "]", "<=>", "+=", "||=", "=", "#block#", "(", ">", ")", "#hash#", ">=", "?", "return", "*"]
So the code in Oper.expect is almost certainly broken, but it's not actually the problem tripping
us up in this case. Lets add some more cases to the new
tokenizer.feature anyway. In c2360cf I've
added a couple more test cases, including one for "+=" which illustrates the problem with
Oper.expect
perfectly. We'll leave actually fixing it for later, since it's not what's breaking our other test
case.
Some more instrumenting to print out the result of
@scanner.get in
parse_fname reveals the real
source of the problem:
Methodname.expect does not correctly rewind the scanner state, and/or reads
the wrong thing. (Arguably it would also be cleaner if
Methodname did what it says on the tin and
actually tokenized method names fully rather than only handle parts of them...)
So lets add some more test cases (added in 767de38 and 95addac)
@methodname Scenario Outline: Method names Given the expression <expr> When I tokenize it with the Tokens::Methodname tokenizer Then the result should be <result> Examples: | expr | result | | "=" | nil | | "==" | nil |
We expect
nil because despite the comment above we don't handle operators in this tokenizer class.
So why does it return
:"=" in both cases?
Turns out
MethodName.expect checks for valid method name suffixes, including
= without checking
that they occur after a valid
Atom:
pre_name = s.expect(Atom) suff_name = MethodEndings.select{ |me| s.expect(me) }.first
This is fixed in 6906426.
And that concludes our detour into bug fixing for now, you might think. Not so. Rerunning the parser:
Missing value in expression / op: #<Oper:0xb7481388 @pri=6, @assoc=:right, @arity=2, @minarity=2, @type=:infix, @sym=:assign> / vstack: [] / rightv: :other Failed at line 28 / col -1 before:
This time, though, we have an easier time. It is
>= it chokes on this time, so we add it to the
tokenizer tests in 053052b. Unsurprisingly, this is now
Oper.expect coming back to bite us. So it's good news, bad news: We've already tracked down the problem, but we actually have to fix it.
The naive/trivial fix is to simply sort the keys in
Oper.expect:
--- a/operators.rb +++ b/operators.rb @@ -36,7 +36,7 @@ class Oper # if operator found, return it's symbol (e.g. "*" -> :*) # otherwise simply return nil, # as no operator was found by scanner - Operators.keys.each do |op| + Operators.keys.sort_by {|op| -op.to_s.length}.each do |op| if s.expect(op) return op.to_sym end
This works and passes the tests, and gets us to a state where we can parse the Fixnum stub. It's obviously not very efficient, but then again linearly checking the operators hash was never efficient to begin with. So let's go with that for now, but add a suitable "FIXME" to explain the rationale (in 4fdd8d4)
While the code now parses, we face a second problem: The method names causes the output to become invalid. E.g:
__method_Fixnum_==: .stabn 68,0,16,.LM20 -.LFBB8 .LM20: .LFBB8: pushl %ebp movl %esp, %ebp subl $20, %esp addl $20, %esp leave ret .size __method_Fixnum_==, .-__method_Fixnum_==
Let's just say that
gas and most other sane assemblers would take issue with labels that include "==" and other operators. Even my syntax highlighting chokes.
For robustness we should do some general escaping of method names with symbols. So far we've gotten away with just these very specific fixups:
#") return cleaned end
Lets make this more generic:
First we formulate a test (in df6ae1a - oops, forgot to commit it until after I actually fixed the method, but I did write it first, I promise). You will find it in test/compiler.rb. I like Cucumber a lot for the tests that require long tables of examples, or complex scenarios of reusable steps, but for tests like these that are very specialized and one-off, I prefer rspec:
require 'compiler' describe Compiler do describe "#clean_method_name" do it "should escape all characters outside [a-zA-Z0-9_]" do input = (0..255).collect.pack("c*") output = Compiler.new.clean_method_name(input) expect(output.match("([0-9a-zA-Z_])+")[0]).to eq(output) end end end
This test simply state that we expect the output string matched against [0-9a-zA-Z_]+ to be equal to the input string. The regexp capture will exclude any characters outside our desired range, so if any nasty characters are left, they'll fail. We don't nail down the actual specific format beyond that.
This simple change will accommodate that:
#") cleaned = cleaned.split(//).collect do |c| if c.match(/[a-zA-Z0-9_]/) c else "__#{c[0].to_s(16)}" end end.join return cleaned end
Though this is suboptimal for debugging, so I'm adding a small array of exceptions (in 656921a):
def clean_method_name(name) dict = { "?" => "__Q", "!" => "__X", "[]" => "__NDX", "==" => "__eq", ">=" => "__ge", "<=" => "__le", "<" => "__lt", ">" => "__gt", "/" => "__div", "*" => "__mul", "+" => "__plus", "-" => "__minus"} cleaned = name.to_s.gsub />=|<=|==|[\?!=<>+\-\/\*]/ do |match| dict[match.to_s] end cleaned = cleaned.split(//).collect do |c| if c.match(/[a-zA-Z0-9_]/) c else "__#{c[0].to_s(16)}" end end.join return cleaned end
(This could be done more cleanly with Ruby 1.9+
#gsub, but I'm being a luddite
and still support 1.8.x since I have it installed all over the place, so sue me)
This finally gives us acceptable labels.
The next problem we run across is that numeric constants in our compiler so far have not been objects, but actual numbers. There are two problems here:
String's or
Symbol's.
Like with String, rather than try to copy MRI's type-tagging, we will create an action class
We'll tackle that in the next part. | https://hokstad.com/compiler/27-the-operators | CC-MAIN-2021-21 | refinedweb | 2,220 | 63.8 |
Brandeburg, Jesse <jesse.brandeburg@intel.com> wrote:> > I say 'upgrade' because now S3 sleep and wakeup often take 60> > seconds. I've also noticed ACPI errors in the 'dmesg'. Once I have> > something reproducible I'll file a bugzilla report.>> ick, it would be nice if the system vendors actually tested their acpi> implementations on multiple OSes.They do: XP, Vista, NT, ... Are there any other OS's?!Good news for 2.6.27.3: With the latest stable kernel, thesuspend/resume is quick again, and the ACPI dmesg errors are gone!So I'll keep running it and wait for the e1000e problem to return (orvanish). I'll hurry it along by doing suspend/resume/dhcp lots oftimes.-Sanjoy`Until lions have their historians, tales of the hunt shall always glorify the hunters.' --African Proverb | http://lkml.org/lkml/2008/10/24/346 | CC-MAIN-2013-20 | refinedweb | 136 | 69.99 |
MySQL Shell 8.0 (part of MySQL 8.0)
MySQL Shell's instance dump utility
util.dumpInstance() and schema dump utility
util.dumpSchemas(), introduced in MySQL Shell
8.0.21, support the export of all schemas or a selected schema
from an on-premise MySQL instance into an Oracle Cloud
Infrastructure Object Storage bucket or a set of local files. The
table dump utility
util.dumpTables(),
introduced in MySQL Shell 8.0.22, supports the same operations
for a selection of tables or views from a schema. The exported
items can then be imported into a MySQL Database Service DB System
(a MySQL DB System, for short) or a MySQL Server instance using
MySQL Shell's Section 7.6, “Dump Loading Utility”
util.loadDump().
MySQL Shell's instance dump utility, schema dump utility, and table dump utility provide Oracle Cloud Infrastructure Object Storage streaming, MySQL Database Service compatibility checks and modifications, parallel dumping with multiple threads, and file compression, which are not provided by mysqldump. Progress information is displayed during the dump. You can carry out a dry run with your chosen set of dump options to show information about what actions would be performed, what items would be dumped, and (for the instance dump utility and schema dump utility) what MySQL Database Service compatibility issues would need to be fixed, when you run the utility for real with those options.
When choosing a destination for the dump files, note that for import into a MySQL DB System, the MySQL Shell instance where you run the dump loading utility must be installed on an Oracle Cloud Infrastructure Compute instance that has access to the MySQL DB System. If you dump the instance, schema, or tables to an Object Storage bucket, you can access the Object Storage bucket from the Compute instance. If you create the dump files on your local system, you need to transfer them to the Oracle Cloud Infrastructure Compute instance using using the copy utility of your choice, depending on the operating system you chose for your Compute instance.
The dumps created by MySQL Shell's instance dump utility, schema
dump utility, and table dump utility comprise DDL files specifying
the schema structure, and tab-separated
.tsv
files containing the data. You can also choose to produce the DDL
files only or the data files only, if you want to set up the
exported schema as a separate exercise from populating it with the
exported data. You can choose whether or not to lock the instance
for backup during the dump for data consistency. By default, the
dump utilities chunk table data into multiple data files and
compress the files.
If you need to dump the majority of the schemas in a MySQL
instance, as an alternative strategy, you can use the instance
dump utility rather than the schema dump utility, and specify the
excludeSchemas option to list those schemas
that are not to be dumped. Similarly, if you need to dump the
majority of the tables in a schema, you can use the schema dump
utility with the
excludeTables option rather
than the table dump utility. The
information_schema,
mysql,
ndbinfo,
performance_schema,
and
sys schemas are always excluded from an
instance dump. The data for the
mysql.apply_status,
mysql.general_log,
mysql.schema, and
mysql.slow_log tables is always excluded from a
schema dump, although their DDL statements are included. You can
also choose to include or exclude users and their roles and
grants, events, routines, and triggers.
By default, the time zone is standardized to UTC in all the
timestamp data in the dump output, which facilitates moving data
between servers with different time zones and handling data that
has multiple time zones. You can use the
tzUtc:
false option to keep the original timestamps if
preferred.
From MySQL Shell 8.0.22, when you export instances or schemas to
an Oracle Cloud Infrastructure Object Storage bucket, during the
dump you can generate a pre-authenticated request URL for every
item. The user account that runs MySQL Shell's dump loading
utility
util.loadDump() uses these to load the
dump files without additional access permissions. By default, if
the
ocimds option is set to
true and an Object Storage bucket name is
supplied using the
osBucketName option,
MySQL Shell's instance dump utility and schema dump utility
generate pre-authenticated request URLs for the dump files and
list them in a single manifest file. The dump loading utility
references the manifest file to obtain the URLs and load the dump
files. For instructions to generate or deactivate
pre-authenticated request URLs, see the description for the
ociParManifest option.
The following requirements apply to dumps using the instance dump utility, schema dump utility, and table dump utility:
MySQL 5.7 or later is required for both the source MySQL instance and the destination MySQL instance.
Object names in the instance or schema must be in the
latin1 or
utf8
characterset.
Data consistency is guaranteed only for tables that use the
InnoDB storage engine.
The minimum required set of privileges that the user account
used to run the utility must have on all the schemas involved
is as follows:
BACKUP_ADMIN,
EVENT,
RELOAD,
SHOW VIEW, and
TRIGGER. If the
consistent option is set to
false, the
BACKUP_ADMIN and
RELOAD privileges are not
required. If the
consistent option is set
to
true, which is the default, the
LOCK TABLES privilege on all
dumped tables can substitute for the
RELOAD privilege if the latter
is not available.
The upload method used.
The utilities convert columns with data types that are not
safe to be stored in text form (such as
BLOB) to Base64. The size of these columns
therefore must not exceed approximately 0.74 times the value
of the
max_allowed_packet
system variable (in bytes) that is configured on the target
MySQL instance.
For the table dump utility, exported views and triggers must not use qualified names to reference other views or tables.
For the instance dump utility and schema dump utility, for
import into a MySQL DB System, set the
ocimds option to
true,
to ensure compatibility with MySQL Database Service.
For compatibility with MySQL Database Service, all tables must
use the
InnoDB storage engine. If
you are using the instance dump utility or schema dump
utility, the
ocimds option checks for any
exceptions found in the dump, and the
compatibility option alters the dump files
to replace other storage engines with
InnoDB.
For the instance dump utility and schema dump utility, for
compatibility with MySQL Database Service, all tables in the
instance or schema must be located in the MySQL data directory
and must use the default schema encryption. The
ocimds option alters the dump files to
apply these requirements.
A number of other security related restrictions and
requirements apply to items such as tablespaces and privileges
for compatibility with MySQL Database Service. The
ocimds option checks for any exceptions
found during the dump, and the
compatibility option automatically alters
the dump files to resolve some of the compatibility issues.
You might need (or prefer) to make some changes manually. For
more details, see the description for the
compatibility option.
The instance dump utility, schema dump utility, and table dump utility use the MySQL Shell global session to obtain the connection details of the target MySQL server from which the export is carried out. You must open the global session (which can have an X Protocol connection or a classic MySQL protocol connection) before running one of the utilities. The utilities open their own sessions for each thread, copying options such as connection compression and SSL options from the global session, and do not make any further use of the global session.
In the MySQL Shell API, the instance dump utility, schema dump
utility, and table dump utility are functions of the
util global object, and have the following
signatures:
util.dumpInstance(outputUrl[, options]) util.dumpSchemas(schemas, outputUrl[, options]) util.dumpTables(schema, tables, outputUrl[, options])
For the schema dump utility,
schemas specifies
a list of one or more schemas to be dumped from the MySQL
instance.
For the table dump utility,
schema specifies
the schema that contains the items to be dumped, and
tables is an array of strings specifying the
tables or views to be dumped. Note that the information required
to set up the specified schema is not exported, so the dump files
produced by this utility must be loaded into an existing target
schema.
If you are dumping to the local filesystem,
outputUrl is a string specifying the path to a
local directory where the dump files are to be placed. You can
specify an absolute path or a path relative to the current working
directory. You can prefix a local directory path with the
file:// schema. In this example, the connected
MySQL instance is dumped to a local directory, with some
modifications made in the dump files for compatibility with MySQL
Database Service. The user first carries out a dry run to inspect
the schemas and view the compatibility issues, then runs the dump
with the appropriate compatibility options applied to remove the
issues:
shell-js> util.dumpInstance("C:/Users/hanna/worlddump", {dryRun: true, ocimds: true}) Checking for compatibility with MySQL Database Service 8.0.21 ... Compatibility issues with MySQL Database Service 8.0.21 were found. Please use the 'compatibility' option to apply compatibility adaptations to the dumped DDL. Util.dumpInstance: Compatibility issues were found (RuntimeError) shell-js> util.dumpInstance("C:/Users/hanna/worlddump", { > ocimds: true, compatibility: ["strip_definers", "strip_restricted_grants"]})
The target directory must be empty before the export takes place.
If the directory does not yet exist in its parent directory, the
utility creates it. For an export to a local directory, the
directories created during the dump are created with the access
permissions
rwxr-x---, and the files are
created with the access permissions
rw-r-----
(on operating systems where these are supported). The owner of the
files and directories is the user account that is running
MySQL Shell.
The table dump utility can be used to select individual tables
from a schema, for example if you want to transfer tables between
schemas. In this example, the tables
employees
and
salaries from the
hr
schema are exported to the local directory
emp,
which the utility creates in the current working directory:
shell-js> util.dumpTables("hr", [ "employees", "salaries" ], "emp")
If you are dumping to an Oracle Cloud Infrastructure Object
Storage bucket,
outputUrl is a path that will
be used to prefix the dump files in the bucket, to simulate a
directory structure. Use the
osBucketName
option to provide the name of the Object Storage bucket, and the
osNamespace option to identify the namespace
for the bucket. In this example, the user dumps the
world schema from the connected MySQL instance
to an Object Storage bucket, with the same compatibility
modifications as in the previous example:
shell-py> util.dump_schemas(["world"], "worlddump", { > "osBucketName": "hanna-bucket", "osNamespace": "idx28w1ckztq", > "ocimds": "true", "compatibility": ["strip_definers", "strip_restricted_grants"]})
In the Object Storage bucket, the dump files all appear with the
prefix
worlddump, for example:
worlddump/@.done.json worlddump/@.json worlddump/@.post.sql worlddump/@.sql worlddump/world.json worlddump/world.sql worlddump/world@city.json worlddump/world@city.sql worlddump/world@city@@0.tsv.zst worlddump/world@city@@0.tsv.zst.idx ...
The namespace for an Object Storage bucket is displayed in the
Bucket Information tab of the bucket details
page in the Oracle Cloud Infrastructure console, or can be
obtained using the Oracle Cloud Infrastructure command line
interface. A connection is established to the Object Storage
bucket using the default profile in the default Oracle Cloud
Infrastructure CLI configuration file, or alternative details that
you specify using the
ociConfigFile and
ociProfile options. For instructions to set up
a CLI configuration file, see
SDK
and CLI Configuration File
options is a dictionary of options that can be
omitted if it is empty. The following options are available for
the instance dump utility, the schema dump utility, and the table
dump utility, unless otherwise indicated:
dryRun: [ true | false ]
Display information about what would be dumped with the
specified set of options, and about the results of MySQL
Database Service compatibility checks (if the
ocimds option is specified), but do not
proceed with the dump. Setting this option enables you to
list out all of the compatibility issues before starting the
dump. The default is
false.
osBucketName: "
string"
The name of the Oracle Cloud Infrastructure Object Storage
bucket to which the dump is to be written. By default, the
[DEFAULT] profile in the Oracle Cloud
Infrastructure CLI configuration file located at
~/.oci/config is used to establish a
connection to the bucket. You can substitute an alternative
profile to be used for the connection with the
ociConfigFile and
ociProfile options. For instructions to
set up a CLI configuration file, see
SDK
and CLI Configuration File.
osNamespace: "
string"
The Oracle Cloud Infrastructure namespace where the Object
Storage bucket named by
osBucketName is
located. The namespace for an Object Storage bucket is
displayed in the Bucket Information tab of the bucket
details page in the Oracle Cloud Infrastructure console, or
can be obtained using the Oracle Cloud Infrastructure
command line interface.
ociConfigFile: "
string"
An Oracle Cloud Infrastructure CLI configuration file that
contains the profile to use for the connection, instead of
the one in the default location
~/.oci/config.
ociProfile: "
string"
The profile name of the Oracle Cloud Infrastructure profile
to use for the connection, instead of the
[DEFAULT] profile in the Oracle Cloud
Infrastructure CLI configuration file used for the
connection.
threads:
int
The number of parallel threads to use to dump chunks of data from the MySQL instance. Each thread has its own connection to the MySQL instance. The default is 4.
maxRate: "
string"
The maximum number of bytes per second per thread for data
read throughput during the dump. The unit suffixes
k for kilobytes,
M for
megabytes, and
G for gigabytes can be
used (for example, setting
100M limits
throughput to 100 megabytes per second per thread). Setting
0 (which is the default value), or
setting the option to an empty string, means no limit is
set.
showProgress: [ true | false ]
Display (
true) or hide
(
false) progress information for the
dump. The default is
true if
stdout is a terminal
(
tty), such as when MySQL Shell is in
interactive mode, and
false otherwise.
The progress information includes the estimated total number
of rows to be dumped, the number of rows dumped so far, the
percentage complete, and the throughput in rows and bytes
per second.
compression: "
string"
The compression type to use when writing data files for the
dump. The default is to use zstd compression
(
zstd). The alternatives are to use gzip
compression (
gzip) or no compression
(
none).
excludeSchemas:
array of strings
(Instance dump utility
only) Exclude the named schemas from the dump.
Note that the
information_schema,
mysql,
ndbinfo,
performance_schema, and
sys schemas are always excluded from an
instance dump. If a named schema does not exist or is
excluded anyway, the utility ignores the item.
excludeTables:
array of strings
(Instance dump utility and schema dump utility only) Exclude
the named tables from the dump. Table names must be
qualified with a valid schema name, and quoted with the
backtick character if needed. Note that the data for the
mysql.apply_status,
mysql.general_log,
mysql.schema, and
mysql.slow_log
tables is always excluded from a schema dump,
although their DDL statements are included. Tables named by
the
excludeTables option do not have DDL
files or data files in the dump. If a named table does not
exist in the schema or the schema is not included in the
dump, the utility ignores the item.
all: [ true | false ]
(Table dump utility only) Setting this option to
true includes all views and tables from
the specified schema in the dump. When you use this option,
set the
tables parameter to an empty
array. The default is
false.
users: [ true | false ]
(Instance dump utility
only) Include (
true) or
exclude (
false) users and their roles and
grants in the dump. The default is
true,
so users are included by default. The schema dump utility
and table dump utility do not include users, roles, and
grants in a dump. From MySQL Shell 8.0.22, you can use the
excludeUsers or
includeUsers option to specify individual
user accounts to be excluded or included in the dump files.
These options can also be used with MySQL Shell's dump
util.loadDump() to
exclude or include individual user accounts at the point of
import, depending on the requirements of the target MySQL
instance.
In MySQL Shell 8.0.21, attempting to import users to a
MySQL DB System causes the import to fail if the
root user account or another
restricted user account name is present in the dump
files, so the import of users to a MySQL DB System is
not supported in that release.
excludeUsers:
array of strings
(Instance dump
utility only) Exclude the named user accounts
from the dump files. This option is available from
MySQL Shell 8.0.22, and you can use it to exclude user
accounts that are not accepted for import to a MySQL DB
System, or that already exist or are not wanted on the
target MySQL instance. Specify each user account string in
the format
"'
for an account that is defined with a user name and host
name, or
user_name'@'
host_name'"
"'
for an account that is defined with a user name only (which
is equivalent to
user_name'"
"').
If a named user account does not exist, the utility ignores
the item.
user_name'@'
%'"
includeUsers:
array of strings
(Instance dump utility
only) Include only the named user accounts in the
dump files. Specify each user account string as for the
excludeUsers option. This option is
available from MySQL Shell 8.0.22, and you can use it as an
alternative to
excludeUsers if only a few
user accounts are required in the dump. You can also specify
both options, in which case a user account matched by both
an
includeUsers string and an
excludeUsers string is excluded.
events: [ true | false ]
(Instance dump utility and schema dump
utility only) Include (
true)
or exclude (
false) events for each schema
in the dump. The default is
true.
routines: [ true | false ]
(Instance dump utility and schema dump
utility only) Include (
true)
or exclude (
false) functions and stored
procedures for each schema in the dump. The default is
true. Note that user-defined functions
are not included, even when
routines is
set to
true.
triggers: [ true | false ]
Include (
true) or exclude
(
false) triggers for each table in the
dump. The default is
true.
defaultCharacterSet: "
string"
The character set to be used during the session connections
that are opened by MySQL Shell to the server for the dump.
The default is
utf8mb4. The session value
of the system variables
character_set_client,
character_set_connection,
and
character_set_results
are set to this value for each connection. The character set
must be permitted by the
character_set_client system
variable and supported by the MySQL instance.
tzUtc: [ true | false ]
Include a statement at the start of the dump to set the time
zone to UTC. All timestamp data in the dump output is
converted to this time zone. The default is
true, so timestamp data is converted by
default. Setting the time zone to UTC facilitates moving
data between servers with different time zones, or handling
a set of data that has multiple time zones. Set this option
to
false to keep the original timestamps
if preferred.
consistent: [ true | false ]
Enable (
true) or disable
(
false) consistent data dumps by locking
the instance for backup during the dump. The default is
true. When
true is
set, the utility sets a global read lock using the
FLUSH TABLES WITH READ LOCK statement.
The transaction for each thread is started using the
statements
SET SESSION TRANSACTION ISOLATION LEVEL
REPEATABLE READ and
START TRANSACTION
WITH CONSISTENT SNAPSHOT. When all threads have
started their transactions, the instance is locked for
backup and the global read lock is released.
ddlOnly: [ true | false ]
Setting this option to
true includes only
the DDL files for the dumped items in the dump, and does not
dump the data. The default is
false.
dataOnly: [ true | false ]
Setting this option to
true includes only
the data files for the dumped items in the dump, and does
not include DDL files. The default is
false.
chunking: [ true | false ]
Enable (
true) or disable
(
false) chunking for table data, which
splits the data for each table into multiple files. The
default is
true, so chunking is enabled
by default. Use
bytesPerChunk to specify
the chunk size. In order to chunk table data into separate
files, a primary key or unique index must be defined for the
table, which the utility uses to select an index column to
order and chunk the data. If a table does not contain either
of these, a warning is displayed and the table data is
written to a single file. If you set the chunking option to
false, chunking does not take place and
the utility creates one data file for each table.
bytesPerChunk: "
string"
Sets the approximate number of bytes to be written to each
data file when chunking is enabled. The unit suffixes
k for kilobytes,
M for
megabytes, and
G for gigabytes can be
used. The default is 64 MB (
64M) from
MySQL Shell 8.0.22 (32 MB in MySQL Shell 8.0.21), and the
minimum is 128 KB (
128k). Specifying this
option sets
chunking to
true implicitly. The utility aims to
chunk the data for each table into files each containing
this amount of data before compression is applied. The chunk
size is an average and is calculated based on table
statistics and explain plan estimates.
ocimds: [ true | false ]
(Instance dump utility and schema dump
utility only) Setting this option to
true enables checks and modifications for
compatibility with MySQL Database Service. The default is
false.
When this option is set to
true,
DATA DICTIONARY,
INDEX
DICTIONARY, and
ENCRYPTION
options in
CREATE TABLE
statements are commented out in the DDL files, to ensure
that all tables are located in the MySQL data directory and
use the default schema encryption. Checks are carried out
for any storage engines in
CREATE TABLE
statements other than
InnoDB, for grants
of unsuitable privileges to users or roles, and for other
compatibility issues. If any non-conforming SQL statement is
found, an exception is raised and the dump is halted. Use
the
dryRun option to list out all of the
issues with the items in the dump before the dumping process
is started. Use the
compatibility option
to automatically fix the issues in the dump output.
From MySQL Shell 8.0.22, when this option is set to
true and an Object Storage bucket name is
supplied using the
osBucketName option,
the
ociParManifest option also defaults
to
true, meaning that pre-authenticated
requests are generated for every item in the dump, and the
dump files can only be accessed using these request URLs.
compatibility:
array of strings
(Instance dump utility and schema dump utility only) Apply the specified requirements for compatibility with MySQL Database Service for all tables in the dump output, altering the dump files as necessary. The following modifications can be specified as a comma-separated list:
force_innodb
Change
CREATE TABLE
statements to use the
InnoDB storage engine for
any tables that do not already use it.
strip_definers
Remove the
DEFINER clause from
views, routines, events, and triggers, so these
objects are created with the default definer (the user
invoking the schema), and change the
SQL
SECURITY clause for views and routines to
specify
INVOKER instead of
DEFINER. MySQL Database Service
requires special privileges to create these objects
with a definer other than the user loading the schema.
If your security model requires that views and
routines have more privileges than the account
querying or calling them, you must manually modify the
schema before loading it.
strip_restricted_grants
Remove specific privileges that are restricted by
MySQL Database Service from
GRANT statements, so
users and their roles cannot be given these privileges
(which would cause user creation to fail). From
MySQL Shell 8.0.22, this option also removes
REVOKE statements for
system schemas (
mysql and
sys) if the administrative user
account on an Oracle Cloud Infrastructure Compute
instance does not itself have the relevant privileges,
so cannot remove them.
strip_role_admin
Remove the
ROLE_ADMIN
privilege from
GRANT
statements. This privilege can be restricted by MySQL
Database Service.
strip_tablespaces
Remove the
TABLESPACE clause from
GRANT statements, so
all tables are created in their default tablespaces.
MySQL Database Service has some restrictions on
tablespaces.
ociParManifest: [ true | false ]
(Instance dump utility
and schema dump utility only) Setting this option
to
true generates a pre-authenticated
request for read access (an Object Read PAR) for every item
in the dump, and a manifest file listing all the
pre-authenticated request URLs. The pre-authenticated
requests expire after a week by default, which you can
change using the
ociParExpireTime option.
This option is available from MySQL Shell 8.0.22, and can
only be used when exporting to an Object Storage bucket (so
with the
osBucketName option set). When
the
ocimds option is set to
true and an Object Storage bucket name is
supplied using the
osBucketName option,
ociParManifest is set to
true by default, otherwise it is set to
false by default.
The user named in the Oracle Cloud Infrastructure profile
that is used for the connection to the Object Storage bucket
(the
DEFAULT user or another user as
named by the
ociProfile option) is the
creator for the pre-authenticated requests. This user must
have
PAR_MANAGE permissions and
appropriate permissions for interacting with the objects in
the bucket, as described in
Using
Pre-Authenticated Requests. If there is an issue
with creating the pre-authenticated request URL for any
object, the associated file is deleted and the dump is
stopped.
To enable the resulting dump files to be loaded, create a
pre-authenticated read request for the manifest file object
(
@.manifest.json) following the
instructions in
Using
Pre-Authenticated Requests. You can do this while
the dump is still in progress if you want to start loading
the dump before it completes. You can create this
pre-authenticated read request using any user account that
has the required permissions. The pre-authenticated request
URL must then be used by the dump loading utility to access
the dump files through the manifest file. The URL is only
displayed at the time of creation, so copy it to durable
storage.
Before using this access method, assess the business requirement for and the security ramifications of pre-authenticated access to a bucket or objects.
A pre-authenticated request URL gives anyone who has the URL access to the targets identified in the request. Carefully manage the distribution of the pre-authenticated URL you create for the manifest file, and of the pre-authenticated URLs for exported items in the manifest file.
ociParExpireTime: "
string"
(Instance dump utility
and schema dump utility only) The expiry time for
the pre-authenticated request URLs that are generated when
the
ociParManifest option is set to true.
The default is the current time plus one week, in UTC
format. The expiry time must be formatted as an RFC 3339
timestamp, as required by Oracle Cloud Infrastructure when
creating a pre-authenticated request. The format is
YYYY-MM-DDTHH-MM-SS immediately followed
by either the letter Z (for UTC time), or the UTC offset for
the local time expressed as
[+|-]hh:mm,
for example
2020-10-01T00:09:51.000+02:00.
MySQL Shell does not validate the expiry time, but any
formatting error causes the pre-authenticated request
creation to fail for the first file in the dump, which stops
the dump. This option is available from MySQL Shell 8.0.22. | https://docs.oracle.com/cd/E17952_01/mysql-shell-8.0-en/mysql-shell-utilities-dump-instance-schema.html | CC-MAIN-2020-45 | refinedweb | 4,645 | 51.68 |
syslog - read and/or clear kernel message ring buffer; set console_loglevel
#include <unistd.h>
#include <linux/unistd.h>
_syscall3(int, syslog, int, type, char *, bufp, int, len);
int syslog(int type, char *bufp, int len);
This is probably not the function you are interested in. Look at sys-
log(3) for the C library interface. This page only documents the bare
kernel system call interface.
The type argument determines the action taken by syslog.
*/
Only function 3 is allowed to non-root processes.
The kernel log buffer [Toc] [Back]
The kernel has a cyclic buffer of length LOG_BUF_LEN (4096, since
1.3.54: 8192, since 2.1.113: 16384) [Toc] [Back]
The kernel routine printk() will only print a message on the console,
if it has a loglevel less than the value of the variable con-
sole_loglevel (initially DEFAULT_CONSOLE_LOGLEVEL (7), but set to 10 if
the kernel commandline. [Toc] [Back]
System call was interrupted by a signal - nothing was read.
This system call is Linux specific and should not be used in programs
intended to be portable.
syslog(3)
Linux 1.2.9 1995-06-11 SYSLOG(2) | https://nixdoc.net/man-pages/Linux/man2/syslog.2.html | CC-MAIN-2022-27 | refinedweb | 188 | 67.65 |
Contents
The easiest way to upgrade TurboGears itself is to download the latest tgsetup.py and run it! This will update all of the parts of the TurboGears installation that need updating.
Backwards incompatible changes in new TurboGears versions might make it necessary to update your existing TurboGears applications, so that they work correctly with the new TurboGears version. These necessary changes are addressed in the remainder of this guide.
Here is a list of changes in the 1.0.8 release which might affect existing applications. For a detailed list of changes, see the 1.0.9 changelog.
No incompatible changes are known to exist in 1.0.9.
Here is a list of changes in the 1.0.8 release which might affect existing applications. For a detailed list of changes, see the 1.0.8 changelog.
In TG 1.0.7 XHTML templates were delivered with a content type of "application/xhtml+xml". In TG 1.0.8 this was changed back to "text/html" due to compatibility issues with the Internet Explorer.
Here is a list of changes in the 1.0.7 release which might affect existing applications. For a detailed list of changes, see the. 1.0.7 changelog.
The standard controller method Root.login handling the URl given by identity.failure_url (/login) now returns the proper HTTP status code "401 Unauthorized" instead of "403 Forbidden". Please note that this change is reverted in TG 1.1 so that in case of an IdentityFailure exception the 401 status is only returned if HTTP Basic Authentication is enabled, in which case a WWW-Authenticate header is sent along with the 401 response. otherwise a 403 response code is sent again.
These changes might especially affect any AJAX error callbacks in your JavaScript code, e.g. when using the MochiKit loadJSONDoc function.
Here is a list of changes in the 1.0.6 release which might affect existing applications. For a detailed list of changes, see the 1.0.6 changelog.
Here is a list of changes in 1.0.5 which might affect existing applications. For a detailed list of changes, see the 1.0.5 changelog.
Release 1.0.4 is only a minor release, so there are no incompatible changes.
There is however a change that affects only the start script of newly quickstarted projects, old projects will still work as they are with 1.0.4. If you still want to update an old project to the new behavior, do the following.
Quickstart a new project with the same name and settings as your old project somewhere in a temporary directory. Substitute <project> and <package> with your actual project resp. package name below.
From the new project, copy the file <project>/<package>/commands.py to the corresponding location in your old project.
From the new project, copy the file <project>/start-<project>.py to the corresponding location in your old project, overwriting the existing start script.
Open the setup.py file in your old project with an editor and change the following (again substituting <package> with the actual package name):
-
Delete the following line:scripts = ["start-<package>.py"],
-
Add the following to the end of the parameters of the setup() call:entry_points = { 'console_scripts': [ 'start-<package> = <package>.commands:start', ], },
Other things you should do when upgrading:
For more information, please see the 1.0.4 changelog.
A new setting identity.saprovider.model.visit resp. identity.soprovider.model.visit has been added to the config. You may want to include this in the app.cfg file of your existing projects to make sure the identity provider picks up the class from your model file. Otherwise it will use a default class which may not match the one in your model file.
When your project uses SQLAlchemy and you want to upgrade from version 0.3.x to 0.4.x, you need to change a few import statements. There are no TurboGears specific changes.
Add the following line to model.py:
from sqlalchemy.orm import mapper, relation, create_session
(Leaving from sqlalchemy import * as is should also work.)
To controllers.py:
from sqlalchemy.exceptions import SQLError
These instructions cover updating existing TurboGears projects that were started with TurboGears versions 0.9a6-1.0b2 to work with TurboGears version 1.0.x, up to and including the latest release 1.0.4.
To be done...
i18n.runTemplateFilter in the config file has been renamed i18n.run_template_filter (#796)
For people using FastData (experimental): get_add_url, get_edit_url and get_delete_url all are passed the row instead of the ID now, allowing you to use something other than the ID if desired.
In widgets, if you were using a dictionary as params be aware that now the dictionary is not updated at construction or display/render time but simply replaced with the new one. If you were using it to provide default attributes for your widget, take a look at how the TableForm does that.
QUICKSTART: quickstart projects that used identity would generate a table called user, which is invalid for some databases. The new quickstart model.py generates tables called tg_user. (#805
If you have an old project with a model.py generated by a previous version, change the table name of the User object to tg_user by adding the following in the class definition:
class sqlmeta: table="tg_user"
for SQLObject models. The SQLAlchemy model structure has changed several times since then, so you should probably just generate a new project and copy the identity classes from there."
There are a number of changes that will need to be made to your project in order to upgrade to TurboGears 0.9. ‘Y.
CherryPy 2.2 requires that paths to static files be absolute. While you might think this would prevent projects from being deployed on different machines, TurboGears provides a function ‘absfile’ to help maintain portability. If your package name is ‘big.
In order to prevent accidentally exposing information that perhaps everyone shouldn’t see, exposed methods no longer automatically provide JSON output when the url contains ‘tg."}
The std object that appears in your template namespace that holds useful values and functions has been renamed tg. You should be able to do a search and replace in your template files to swap std. with tg..
There are a couple other changes that probably won’t impact most projects, but will cause things to not work if you are using them.
The following items will work in 0.9, but will be changing in the future. You should migrate away from any usage of these items as you are able to.. | http://www.turbogears.org/1.0/docs/Install/Upgrade.html | CC-MAIN-2014-35 | refinedweb | 1,101 | 67.86 |
It is much more convenient and cleaner to use a single statement like
import java.awt.*;
import java.awt.Panel;
import java.awt.Graphics;
import java.awt.Canvas;
...
import
The only problem with it is that it clutters your local namespace. For example, let's say that you're writing a Swing app, and so need
java.awt.Event, and are also interfacing with the company's calendaring system, which has
com.mycompany.calendar.Event. If you import both using the wildcard method, one of these three things happens:
java.awt.Eventand
com.mycompany.calendar.Event, and so you can't even compile.
.*), but it's the wrong one, and you struggle to figure out why your code is claiming the type is wrong.
com.mycompany.calendar.Event, but when they later add one your previously valid code suddenly stops compiling.
The advantage of explicitly listing all imports is that I can tell at a glance which class you meant to use, which simply makes reading the code that much easier. If you're just doing a quick one-off thing, there's nothing explicitly wrong, but future maintainers will thank you for your clarity otherwise. | https://codedump.io/share/jcIlxjIN9KrQ/1/why-is-using-a-wild-card-with-a-java-import-statement-bad | CC-MAIN-2017-43 | refinedweb | 196 | 57.27 |
A long-standing joke about the Hadoop ecosystem is that if you don't like an API for a particular system, wait five minutes and two new Apache projects will spring up with shiny new APIs to learn.
It's a lot to keep up with. Worse, it leads to a lot of work migrating to different projects merely to keep current. "We've implemented our streaming solution in Storm! Now we've redone it in Spark! We're currently undergoing a rewrite of the core in Apache Flink (or Apex)! … and we've forgotten what business case we were attempting to solve in the first place."
Enter Apache Beam, a new project that attempts to unify data processing frameworks with a core API, allowing easy portability between execution engines.
Now, I know what you're thinking about the idea of throwing another API into the mix. But Beam has a strong heritage. It comes from Google and its research on the Millwheel and FlumeJava papers, as well as operational experience in the years following their publication. It defines a somewhat familiar directed acyclic graph data processing engine with the capability of handling unbounded streams of data where out-of-order delivery is the norm rather than the exception.
But wait, I hear some of you cry. Isn’t that Google Cloud Dataflow? Yes! And no. Google Cloud Dataflow is a fully managed service where you write applications using the Dataflow SDK and submit them to run on Google’s servers. Apache Beam, on the other hand, is simply the Dataflow SDK and a set of "runners" that map the SDK primitives to a particular execution engine. Yes, you can run Apache Beam applications on Google Cloud Dataflow, but you can also use Apache Spark or Apache Flink with little to no changes in your code.
Ride with Apache Beam
There are four principal concepts of the Apache Beam SDK:
- Pipeline: If you've worked with Spark, this is somewhat analogous to the SparkContext. All your operations will begin with the pipeline object, and you'll use it to build up data streams from input sources, apply transformations, and write the results out to an output sink.
- PCollection: PCollections are similar to Spark's Resilient Distributed Dataset (RDD) primitive, in that they contain a potentially unbounded stream of data. These are built from pulling information from the input sources, then applying transformations.
- Transforms: A processing step that operates on a PCollection to perform data manipulation. A typical pipeline will likely have multiple transforms operating on an input source (for example, converting a set of incoming strings of log entries into a key/value pair, where the key is an IP address and the value is the log message). The Beam SDK comes with a series of standard aggregations built in, and of course, you can define your own for your own processing needs.
- I/O sources and sinks: Lastly, sources and sinks provide input and output endpoints for your data.
Let’s look at a complete Beam program. For this, we’ll use the still-quite-experimental Python SDK and the complete text of Shakespeare’s "King Lear":
import re
import google.cloud.dataflow as df
p = df.Pipeline('DirectPipelineRunner')
(p
| df.Read('read',
df.io.TextFileSource(
'gs://dataflow-samples/shakespeare/kinglear.txt'))
| df.FlatMap('split', lambda x: re.findall(r'\w+', x))
| df.combiners.Count.PerElement('count words')
| df.Write('write', df.io.TextFileSink('./results')))
p.run()
After importing the regular expression and Dataflow libraries, we construct a Pipeline object and pass it the runner that we wish to use (in this case, we're using
DirectPipelineRunner, which is the local test runner).
From there, we read from a text file (with a location pointing to a Google Cloud Storage bucket) and perform two transformations. The first is
flatMap, which we pass a regular expression into in order to break each string up into words -- and return a
PCollection of all the separate words in "King Lear." Then we apply the built-in
Count operation to do our word count.
The final part of the pipeline writes the results of the
Count operation to disk. Once the pipeline is defined, it is invoked with the
run() method. In this case, the pipeline is submitted to the local test runner, but by changing the runner type, we could submit to Google Cloud Dataflow, Flink, Spark, or any other runner available to Apache Beam.
Runners dial zero
Once we have the application ready, it can be submitted to run on Google Cloud Dataflow with no trouble, as it is simply using the Dataflow SDK.
The idea is that runners will be provided for other execution engines. Beam currently includes runners supplied by DataArtisans and Cloudera for Apache Flink and Apache Spark. This is where some of the current wrinkles of Beam come into play because the Dataflow model does not always map easily onto other platforms.
A capability matrix available on the Beam website shows you which features are and are not supported by the runners. In particular, there are extra hoops you need to jump through in your code to get the application working on the Spark runner. It’s only a few lines of extra code, but it isn’t a seamless transition.
It's also interesting to note that the Spark runner is currently implemented using Spark's RDD primitive rather than DataFrames. As this bypasses Spark's Catalyst optimizer, it's almost certain right now that a Beam job running on Spark will be slower than running a DataFrame version. I imagine this will change when Spark 2.0 is released, but it's definitely a limitation of the Spark runner over and above what's presented in the capability matrix.
At the moment, Beam only includes runners for Google Cloud Dataflow, Apache Spark, Apache Flink, and a local runner for testing purposes -- but there's talk of creating runners for frameworks like Storm and MapReduce. In the case of MapReduce, any eventual runner will be able to support a subset of the what Apache Beam provides, as it can work only with what the underlying system provides. (No streaming for you, MapReduce!)
Grand ambitions
Apache Beam is an incredibly ambitious project. Its ultimate goal is to unify all the data processing engines under one API -- and make it trivially easy to migrate, say, your Beam application running on a self-hosted Flink cluster over to Google Cloud Dataflow.
As somebody who has to develop these applications, this is great. It's clear that Google has spent years refining the Beam model to cover most of the data processing patterns that many of us will need to implement. Note, however, that Beam is currently an "incubating" Apache project, so you'll want to exercise caution before putting it into production. But it's worth keeping a close eye on Beam as it incorporates more runners -- and ports the Beam SDK to more languages. | https://www.infoworld.com/article/3056172/apache-beam-wants-to-be-uber-api-for-big-data.html | CC-MAIN-2021-39 | refinedweb | 1,166 | 61.06 |
For my school project ' if this, then that ' I had to make something Interactive with the use of an arduino. I chose to create this automatic dice tower. In this project I'll show you how I put it together.
The tower itself is simple, its just a wooden case with an extra tray to catch the dice. On top of the tower are 6 different cases to put the dice, all closed by a hatch controlled by a servo motor.
The six buttons on the tower each controll a different hatch. The tray has leds underneath it that light up different colours when the buttons are pressed.
Teacher Notes
Teachers! Did you use this instructable in your classroom?
Add a Teacher Note to share how you incorporated it into your lesson.
Step 1: Things You'll Need
The things I used for this project:
- Arduino Uno
- WS2812B LED STRIP
- SG90 Analog Servo
- 6 tactile led button white
- Four battery clips
- Four 9 volt batteries
- Any set of clear polydice. I used Chessex Borealis purple/white
- printed wiring board
- Mahogany Planks
- Plexiglass, I used one that isn't entirely see through
- Any clear ballpoint pen.
- Any kind of thin MDF wood
- A phone charger
Ofcourse you can switch a lot of the materials to something else of your liking, These are just the specifics for what I used.
Step 2: The Case
Creating the case is a fairly straight forward process.
- For the sides and the back: cut 3 planks of your desired wood, 320 cm tall and 150 wide. To fit it together nicely in the end I cut the sides diagonally.
- For the front: You'll have to create an entrance of your desired height. Keep in mind that you have to fit in the buttons, servos and the arduino itself so make sure you don't run out of space.
- For the tray: Cut the side pieces 160 cm wide and cut the sides diagonally like the tower. This way you can easily slot it into the tower without necessarily having to attach it, Cut out two slits on each piece. One in the middle for the plexiglass, and one on the bottom so you can slot in the piece of wood with your ledstrip.
- For the buttons: Drill 6 holes justr above the entrance, make sure its spaced like you'll space your buttons because they'll be put behind them on the inside.
- For your charger : This is something I completely forget to do but I can absolutely recommend you do. Take out a little bit of wood on the botton of the backpiece, you can let your charger wire for the leds feed through this so your tower doesnt rest on it and wobble.
- Putting it together: Lay your pieces in the right order with the right side up. Apply tape diagonally along the seams and a few horizontal pieces for support. Then turn it around and apply generous amounts of glue. Fold them together and apply enough clamps to keep it all together. Dry overnight
Step 3: The Buttons
For this project I wanted the buttons to resemble the dice that were going to fall out when pressed. Because the buttons light up I thought it would be cool for the dice to be translucent.
I considered a few options here:
3d print them:
pros:
- Fairly cheap
- If you have knowledge of 3d programs it would be fairly easy to make
Cons:
- If you don't have knowledge of 3d programms, its not that easy to model a set of dice
- 3d printing takes a while
- 3d printers are not accessible for everyone
- The result often is fairly rough
Resin Print them:
Pros:
- Clear and pretty result
- If you have knowledge of 3d programs it would be fairly easy to make
Cons:
- Resin printing takes a while
- Is even less accesible then 3d printing
Buy a set of dice , get the chainsaw:
Pros:
- You have to model nothing yourself
- Great range of colours, glitters , finish.
- Quick and easily obtainable
Cons:
- Fairly expensive
- Cutting them in half is quite the project
- Chance of breaking whilst cutting
- If you're a dice fanatic like me , it hurts a little to buy a set only to destroy it
In the end I went for buying a set of dice because I did not have that much time left and I did like the thought of having a pretty colour.
Cutting them:
The nasty part about cutting these in half is that they conduct heat...extremeeely well. So if you go too quick you get a dice melted to your saw which is incredibly inconvenient to get off. What I did was take two pieces of scrap wood, drill a partial hole in them and wedge the dice inbetween. Then I took a handsaw and just slowly and steadily started to half them. Once I got through I got a fairly rough sandpaperblock and sanded the underside evenly. This worked for all dice except the d4, Its fairly thin and small and I just didn't do it carefully enough, it ended up melting/breaking away. I replaced it with the d100 for aesthetic reasons but I can recommend just putting it on the button as a whole.
Assembeling the button:
Because the actual buttons are on the inside of the tower you'll need something that reaches through the drilled holes and portrudes a little on the outside so you can press it. Because light needs to travel through it needs to be translucent aswell. To do this I simply took the barrel of a ballpoint pen, cut it in six equal pieces long enough to go through the holes and glued the halved dice on the other side. I didnt permanently attach mine to the buttons on the inside because this way I can take them out when travellling with the tower.
(I used the other half of the dice to put next to the hatches of the tower so you know in which one to put the corrosponding dice)
Step 4: The Button/Led/Battery Printplate
Get ready for an unholy amount of wires.
The printplate:
I completely forgot to take a clear picture of the printplate with all wires soldered to so these two have to do. Cut two pieces of printplate, drill 4 holes at the corners for each and attach your buttons. Put appropriate resistors for both the button and the led on it (treat the led on it like you'd treat a seperate normal one). Then solder a wire for each button and led.
Attach all the volt wires of the buttons and leds together, and add a wire that leads back to the 5v input on the arduino.
Attach all the ground wires of the buttons and leds together, then add a wire that leads back to the ground on the arduino.
This is also where I attached my battery clips and male connector to plug into the arduino.
Step 5: The Servos
To make the little dice compartments:
- Cut out two different pieces of wood, that fit perfectly in the width of the tower. Glue 3 servos on each, make sure they can be put opposite each other later (see first and second picture)m drill a hole where the turning part of the servo fits in.
- Put little dividers between them so you have the dice compartments
- Cut a piece of wood fo rthe middle , then put each piece of wood on a side.
- cut 6 hatches (make sure they're not too heavy, the servos arent that strong) drill a tiny tiny hole in the side and put an equally smale nail in. Glue(be sure to use strong glue and let it dry appropriately) that into the moving part of the servo
- Tada, you got your compartments.
Wiring:
Now put all the ground wires of your servos together, solder them and lead one wire from there into a ground pin on the arduino.
Now put all the power wires of your servos together, solder them and lead one wire from there to the printplate with the buttons and attach it there so they can take energy from the batteries.
attach all the signal pins into your arduino
Step 6: The LEDS
I used 15 leds for this project, I divided them in 3 pieces and glued them to a piece of mdf. Then slotted them into the dice tray. I attached this to a wire with an usb end so I can just use a phone charger because these ledstrips take a lot of energy to run.
You'll need two ground wires for this one , one goes into the charger and the other goes to the arduino. Also lead the signal wire to the arduino.
Step 7: Putting It All Together
This will sound so much easier then it actually is. Cause I wanted a fairly sleek tower I absolutely sacrificed a bit of comfort. Putting it in is a lot of fumbling and cursing and I absolutely reccomend a second pair of hands for this.
If you want this all to be a bit easier, size up your tower.
- Start with wedging your servos into the top of the tower. I made it such
a tight fit I just had to push it in , no need for glue or anything. I then glued the other halves of the dice to the top so I know what slot needs what dice.
- Turn the tower around.
- Put the printplate of the buttons behind the drilled holes. Screw tiny screws into the 8 drilled holes you got. Take extra care to make sure the buttons are pressable and there are no wires accidentally infront of it!
- Screw in your arduino opposite of that printplate, all the wires are now in the middle of the tower. (I don't think this the most professional way of doing this but I was so afraid of wires popping out I put a layer of hotglue on them once they were all plugged inside the arduino. Its easibly peelable so you dont destroy your arduino. )
- Wire manage, tie them together, keep them in the middle (this is the worst I'm sorry)
- Make a ramp, put it infront of your arduino so its hidden and the dice can roll off it.Make it overlap the outside of the tower slightly so you can slot in your dice tray. (picture) Make sure your ramp is prettier then mine.
I'm sorry I don't have more picturees for refrence, I was too busy crying whilst putting it together.
Step 8: The Coding
#include <servo.h> //include servo library<br>#include <fastled.h> //include fastled library</fastled.h></servo.h>
#define LED_PIN 19 //define the LEDSTRIP pins #define NUM_LEDS 24 //define the amount of leds you use, your first one counts as 0
CRGB leds[NUM_LEDS];
const int ledPin1 = 2; //define which pins you'll use for the button LEDS const int ledPin2 = 3; const int ledPin3 = 4; const int ledPin4 = 5; const int ledPin5 = 6; const int ledPin6 = 7;
const int buttonPin1 = A0; //define which pins you'll use for your buttons const int buttonPin2 = A1; const int buttonPin3 = A2; const int buttonPin4 = A3; const int buttonPin5 = A4; const int buttonPin6 = A5;
int servoPin1 = 8; //define which pins you'll use for your Servo's int servoPin2 = 9; int servoPin3 = 10; int servoPin4 = 11; int servoPin5 = 12; int servoPin6 = 13;
int buttonState1 = 0; //create a variable for your buttonstate int buttonState2 = 0; int buttonState3 = 0; int buttonState4 = 0; int buttonState5 = 0; int buttonState6 = 0;
Servo Servo1; Servo Servo2; Servo Servo3; Servo Servo4; Servo Servo5; Servo Servo6;
void setup() {
Serial.begin(9600);
FastLED.addLeds<ws2812, led_pin,="" grb="">(leds, NUM_LEDS); </ws2812,>
pinMode(ledPin1, OUTPUT); //set led pins as output pinMode(ledPin2, OUTPUT); pinMode(ledPin3, OUTPUT); pinMode(ledPin4, OUTPUT); pinMode(ledPin5, OUTPUT); pinMode(ledPin6, OUTPUT);
Servo1.attach(8); //attach your servos Servo2.attach(9); Servo3.attach(10); Servo4.attach(11); Servo5.attach(12); Servo6.attach(13);
}
void loop() //Servo 1 { Servo1.write(0); //automatically puts the servo to 0 at the begin buttonState1 = digitalRead(buttonPin1); //the state of the button gets saved as buttonstate1 if (buttonState1 == HIGH) { //if you press the button digitalWrite(ledPin1, HIGH); //turns led on Servo1.write(90); //servo turns 90 degrees for(int i=0;i<6;i++){ //leds 0-5 turn your defined colour leds[i].setRGB(131, 7, 247); } for(int i=5;i<11;i++){ //leds 6-10 turn your defined colour leds[i].setRGB(255, 13, 93); } for(int i=11;i<16;i++){ //leds 11-15 turn your defined colour leds[i].setRGB(253, 185, 155); } FastLED.show(); Serial.println("Servo1 ON"); //prints that the servo is on delay(5000); //waits 5 seconds Servo1.write(0); //servo turns back to 0 degrees }
else {
digitalWrite(ledPin1, LOW); Serial.println("Servo1 OFF");
} //repeat x6
//Servo 2
Servo2.write(0); buttonState2 = digitalRead(buttonPin2); if (buttonState2 == HIGH) { digitalWrite(ledPin2, HIGH); Servo2.write(90); for(int i=0;i<6;i++){ leds[i].setRGB(131, 7, 247); } for(int i=5;i<11;i++){ leds[i].setRGB(255, 255, 93); } for(int i=11;i<16;i++){ leds[i].setRGB(253, 185, 155); } FastLED.show(); Serial.println("Servo2 ON"); delay(5000); Servo2.write(0); }
else {
digitalWrite(ledPin2, LOW); Serial.println("Servo2 OFF");
}
//Servo 3
Servo3.write(0); buttonState3 = digitalRead(buttonPin3); if (buttonState3 == HIGH) { digitalWrite(ledPin3, HIGH); Servo3.write(90); Serial.println("Servo3 ON"); delay(5000); Servo3.write(0); }
else {
digitalWrite(ledPin3, LOW);
Serial.println("Servo3 OFF");
}
//Servo 4
Servo4.write (0); buttonState4 = digitalRead(buttonPin4); if (buttonState4 == HIGH) { digitalWrite(ledPin4, HIGH); Servo4.write(90); for(int i=0;i<6;i++){ leds[i].setRGB(131, 7, 247); } for(int i=5;i<11;i++){ leds[i].setRGB(255, 13, 93); } for(int i=11;i<16;i++){ leds[i].setRGB(253, 185, 155); } FastLED.show(); Serial.println("Servo4 ON"); delay(5000); Servo4.write(0); }
else {
digitalWrite(ledPin4, LOW);
Serial.println("Servo4 OFF"); }
//Servo 5
Servo5.write (0); buttonState5 = digitalRead(buttonPin5); if (buttonState5 == HIGH) { digitalWrite(ledPin5, HIGH); Servo5.write(90); Serial.println("Servo5 ON"); delay(5000); Servo5.write(0); }
else {
digitalWrite(ledPin5, LOW);
Serial.println("Servo5 OFF");
}
//Servo 6
Servo6.write (0); buttonState6 = digitalRead(buttonPin6);
if (buttonState6 == HIGH) {
digitalWrite(ledPin6, HIGH); Servo6.write(90); Serial.println("Servo6 ON"); delay(5000); Servo6.write(0); }
else {
digitalWrite(ledPin6, LOW);
Serial.println("Servo6 OFF");
} }
2 Discussions
2 months ago
this is awesome, i am actually looking for a way to make something like this, but where it is possible to load multiple dice of each kind and drop one at a time when you push the corresponding button
7 months ago
Nice. I like how the dice are also the buttons. | https://www.instructables.com/id/Arduino-Automatic-Dice-Tower/ | CC-MAIN-2019-35 | refinedweb | 2,467 | 70.13 |
Change Log
This section describes major changes that have been made to the spec since it was released.
March 6
- Updated information about grading (to link to Piazza).
March 3
- Added an extra page with some tips about how to use JavaFX's
ScrollBarclass, linked from the scroll bar section.
March 1
- Added another video on data structure selection and analysis.
- Added basics autograder.
February 29
- Added FAQ about removing nodes
- Added a note that the scroll bar should never result in non-integral window positions (these positions should be rounded, like text positions).
February 27
Added more FAQs to address common questions about the mysterious JavaFX Nodes, Groups, and special root Group.
February 25
- Added a clarification to the runtimes: Using arrow keys or clicking should be resolved in constant time: but the length of each line is a constant, since the window can only be so wide.
- Added links to Project 2 slide and video.
February 23
- Added a requirement that shortcut+p prints the current cursor position, and removed the "cursor" option for the 2nd command line argument.
- Updated
CopyFile.javaexample to show how to check if a file exists before attempting to read from it.
- Added a hint for how to display the cursor.
February 21
Clarified description of time requirements to explicitly separate the timing requirements for storing document data from the timing requirements for rendering.
Table of Contents
- Introduction
- Overview
- Getting the Skeleton Files
- Detailed Spec
- JavaFX and KeyEvents
- Window size and margins
- Command line arguments
- Data structures and time requirements
- Shortcut keys
- Font and spacing
- Newlines
- Cursor
- Word wrap
- Open and Save
- Scroll Bar
- Undo and redo
- Optional Beautification
- Gold points
- Selection (3 points)
- Copy / Paste (2 points)
- Frequently Asked Questions
- Acknowledgements
Introduction
Project 2 is the largest project you will do in this class, and the goal of the project is to teach you how to handle a larger code base than you have (likely) ever worked with before. It is a solo project, so while you can discuss ideas with others, all of the code you submit will be your own. This project is designed to be similar to the coding experience you might have at a summer internship or job: you'll write a large amount of code, and you'll need to interact with some external libraries that you've never used before. By the time you're done with this project, you will have written approximately 1000 lines of code. This may sound like a lot of lines of code, and it is! Here are some tips to avoid being crushed by complexity:
- Start early This project has some tricky data structures, so we recommend you start thinking about how to implement the project as soon as possible so that you have some time to mull over your design. Also, you'll be more efficient at writing code if you're not stressed by an impending deadline!
- Design first Before writing any code, spend some time designing. By "design", we mean think about what data structures you're going to use for each part of the project. We recommend thinking about all of the features and how each one might be implemented with your data structures, and do this before writing any code. You don't need to know exactly how every feature will be implemented before you write any code, but it's a good idea to have a rough idea and a sense of potential problem areas. This will help you avoid a situation where you start implementing a feature later in the assignment and realize a massive re-write is necessary!
- Code small Constantly ask yourself "what's the minimum amount of code I can write before testing this new functionality?" Testing doesn't necessarily mean writing a unit test; it can mean sometime much simpler, like opening your program and trying some new input, or seeing if a feature of an external library works as expected. The fewer lines of code that you write in between testing, the fewer lines you will need to debug when something goes wrong! "HelloWorlding", a technique described in lab 5, is an example of the "code small" mentality.
- Modularize To mimimize how much complexity you need to consider at any one time, divide your program into modules with clear simple interfaces. Ideally, these interfaces should hide complexity in their implementations. For example, the ArrayDeque you wrote in Project 1 hid the complexity of the re-sizing operation from a user of the class. Similarly, in this project, you should write classes that hide complexity from the code that calls them, which will reduce how much complexity you need to consider at a time.
- Modularize This is so important that it is here again. Having a hierarchy of classes (or interfaces) with an easy to understand API will make your life so much easier than otherwise. Modular code that hides details is easier to understand, plan, develop, debug, and improve. And if you later decide you don't like a piece of your program, a modular design means you can cleanly replace only that piece.
- Bounce ideas off of each other While you should write all of the code for the project on your own, you're welcome to discuss design ideas with others in the class. After you've thought about your design, we strongly recommend finding someone else in the class and discussing each of your approaches. The other person likely thought of a few things you didn't consider, and vice versa.
- Look at examples We have written examples (in the
examplesdirectory) that show how to use most of the functionality in JavaFX that you'll need to use for this project. Starting from these examples will be much easier than starting from scratch!
This project will be long, arduous, and at times frustrating. However, we hope that you will find it a rewarding experience by the time you are done!
This is a brand new project, so bear with us as we work out kinks! There is a chance we will make some of the currently required features gold points instead as the project progresses.
If you run into problems, be sure to check out the FAQ section before posting to Piazza. We'll keep this section updated as questions arise during the assignment.
For some additional tips on the project, see:
- Project 2 Design Guide Video: Link
- Project 2 Slides (video content and more): Link
- Project 2 Design Analyis Worksheet (make a copy): Link
- Example Project 2 Design Analysis Worksheet, using String as data structure: Link
3/1/2016. For even more tips, see:
- Project 2 Video #2, More on Data Structures: Link
- Project 2 Design Analysis Worksheet, using FastLinkedList as data structure: Link
Overview
In this project, you will build a text editor from scratch. You are probably, you'll implement a basic text editor that can be used to open, edit, and save plain text files.
In the overview here and the text below, we'll refer to the "Shortcut" key. By "shortcut key", we mean the control key on Windows and Linux, and the command key on Mac. Handling these special key presses is described in the shortcut keys section.
Your text editor should support the following features. Most of these features are described in more detail in the Detailed Spec section.
- Cursor The current position of the cursor should be marked with a flashing vertical line.
- Text input Each time the user types a letter on the keyboard, that letter should appear on the screen after the current cursor position, and the cursor should advance to be after the last letter that was typed.
- Word wrapping Your text editor should break text into lines such that it fits the width of the text editor window without requiring the user to scroll horizontally. When possible, your editor should break lines between words rather than within words. Lines should only be broken in the middle of a word when the word does not fit on its own line.
- Newlines When the user presses the Enter or Return key, your text editor should advance the cursor to the beginning of the next line.
- Backspace Pressing the backspace key should cause the character before the current cursor position to be deleted.
- Open and save Your editor should accept a single command line argument describing the location of the file to edit. If that file exists, your editor should display the contents of that file. Pressing shortcut+s should save the current contents of the editor to that file.
- Arrow keys Pressing any of the four arrow keys (up, down, left, right) should cause the cursor to move accordingly (e.g., the up key should move the cursor to be on the previous line at the horizontal position closest to the horizontal position of the cursor before the arrow was pressed).
- Mouse input When the user clicks somewhere on the screen, the cursor should move to the place in the text closest to that location.
- Window re-sizing When the user re-sizes the window, the text should be re-displayed so that it fits in the new window (e.g., if the new window is narrower or wider, the line breaks should be adjusted accordingly).
- Vertical scrolling Your text editor should have a vertical scroll bar on the right side of the editor that allows the user to vertically navigate through the file. Moving the scroll bar should change the positioning of the file (but not the cursor position), and if the cursor is moved (e.g., using the arrow keys) so that it's not visible, the scroll bar and window position should be updated so that the cursor is visible.
- Undo and redo Pressing shortcut+z should undo the most recent action (either inserting a character or removing a character), and pressing shortcut+y should redo. Your editor should be able to undo up to 100 actions, but no more.
- Changing font size Pressing shortcut+"+" (the shortcut key and the "+" key at the same time) should increase the font size by 4 points and pressing shortcut+"-" should decrease the font size by 4 points.
- Printing the current position To facilitate grading, pressing shortcut+p should print the top left coordinate of the current cursor position.
If you're unsure what some of these features mean, we suggest experimenting with Notepad, Microsoft Word, Google Docs, or TextEdit. Those text editors all use a flashing vertical cursor, implement line wrap, react to arrow keys, scroll vertically, and accept mouse input in the way we expect you to for this assignment. Some of these editors (e.g., Microsoft Word) assume documents have a fixed with (e.g., 8.5", to match the width of letter paper), so sometimes show a horizontal scroll bar. For this assignment, you should always word-wrap the text to fit in the width of the current window, so you will never need to show a horizontal scroll bar. Also note that up/down arrows are a bit more sophisticated in some editors than what we require in this assignment, as described in more detail in the detailed spec below.
For obvious reasons, the spec leaves some room for interpretation. Most reasonable interpretations will be given full credit. See the FAQ for more.
Getting the Skeleton Files
As with all previous projects, pull the skeleton using the command
git pull skeleton master. Make sure to reimport the project in IntelliJ.
Detailed Spec
The skeleton provides a single file named
Editor.java that you should modify. You may create as many additonal classes and files as you like.
JavaFX and KeyEvents
For this project, you'll be using the JavaFX libary to create your application, display text, etc. JavaFX is included in Java 1.8, so you do not need to download any additional libraries for this project. JavaFX is a massive library that's designed to support a wide variety of Java applications; as a result, it is significantly more complicated than the
StdDraw library you used in project 0. You will likely find JavaFX overwhelming when you first start writing code! One of the goals of this project is to help you get comfortable with using external libraries. To help you get started, we have written few example applications (described in
examples/README); we highly recommend that you use one of these examples as a starting point for your editor. There will be cases where our example is incomplete and you need to look up functionality on your own; the official documentation is a good starting point.
Much of the functionality you'll implement in this project will be initiated by
KeyEvents. There are two kinds of
KeyEvents:
KEY_TYPED events and
KEY_PRESSED events.
KEY_TYPED events are generated when a Unicode chracter is entered; you should use these to find out about character input for your text editor. The
KEY_TYPED events automatically handle capitalization (e.g., if you press the shift key and the "a" key, you'll get a single
KEY_TYPED event with a character of "A"). You can ignore
KEY_TYPED events that have 0-length (keys like the arrow key will result in a
KEY_TYPED event with 0-length), that have a charater equal to 8 (which represents the backspace), and that have
isShortcutDown() set to true (it's easier to handle the shortcuts using the
KEY_PRESSED events).
Every time a key is pressed, a
KEY_PRESSED event will be generated. The
KEY_PRESSED events often duplicate the
KEY_TYPED events. For example, in the example we gave above where the user presses shift and the "a" key, JavaFX generates three events: one
KEY_PRESSED event for the shift key, one
KEY_PRESSED event for the "a" key, and one
KEY_TYPED event with a character of "A". These
KEY_PRESSED events aren't very useful for normal text input, because they don't handle capitalization; however, they are useful for control keys, because each
KEY_PRESSED event has an associated
KeyCode that's useful for finding out about special keys (e.g., the code will be
KeyCode.BACK_SPACE for the backspace key). If you're unsure about how
KeyEvents work, make sure to see the
KeyPressPrinter.java example.
There are a few JavaFX classes that you may not use as part of this project. You should only display text using the
Text class, and you should be determining where to place text (and how to word wrap) yourself. You cannot use the
TextFlow,
FlowPane,
TextArea,
TextInputControl, or
HTMLEditor. If in doubt about whether you can use a particular class or function, ask on Piazza.
Window size and margins
You should display the text in a window with a top and bottom margin of 0 (the bottom margin is only relevant when there is enough text to reach the bottom of the window) and a left and right margin of 5 pixels.
When your editor first opens, the window size should be 500 by 500 pixels (including the scroll bar).
Command line arguments
Your
Editor program should accept one required command line argument representing the name of the file to edit (see the Open and Save section for more information about how to handle the filename). If no filename is provided, your editor should print a message stating that no filename was provided, and exit (see
CopyFile.java for an example of how to check the number of command line arguments provided).
Editor should accept a second optional command line argument that controls the output of your program as follows:
- If the second command line argument is blank, your program should not print any output.
- If the second command line argument is "debug", you can print any output you like to facilitate debugging.
TIP: One way to control when output is printed is to create a
print(String toPrint) method. The
Data structures and time requirements
One of the most important decisions you'll make in this project is what data structures to use. As you think about how to efficiently implement the functionality required by this project, we'd like you to consider two things separately:
Storing the contents of the document
First, consider how to store the contents of your document. Here, we mean the information about what characters are in the document (either because the user added them to the document, or because they were in the original file that was opened). You can think of this as being all of the information that's needed to save the text. This data should be stored in a data structure such that characters can be added to or deleted from the current cursor position in constant time (even if the cursor is somewhere in the middle of the document).
TIP: As in project 1a, sentinel nodes will make your life much easier!
Storing rendering information
You'll also need to store information about how the text is displayed on the screen. This may include data like where each character is placed on the screen, where word wraps occur, etc. None of this data is needed to save the file; it's only needed to display the contents of the file to the user.
Updates to these data structure(s) can take linear time (i.e., the time can be proportional to the number of characters in the document). In fact, we recommend an approach where you recompute all of the rendering information after each operation. This makes word wrap much easier, because it's easier to determine where word wraps occur if you start from the beginning of the file.
Moving the cursor (e.g., with a mouse click) should take time constant time. However, since each line has a constant length (since the window can only be so wide), this means your runtime may be proportional to the number of characters in the line where the new cursor position is located. Moving the cursor should not take time proportional to the length of the file (so, for example, you should not need to look at all of the characters in the file to determine the new cursor position). Keep in mind that it is possible that someone might use the scroll bars before clicking, so even if your cursor is at the beginning of the file, a click might come at the end.
Why?
You may be wondering why we require one part of operations like inserting a new character to be constant time (updating the data structure storing the character data), while the other part of inserting a new character is allowed to take linear time (re-rendering the document). We'd like you to implement some things efficiently to give you some practice thinking about efficiency. Your efficient data structure for storing character data paves the way for optimizations to rendering; however, these optimizations are tricky, so we're not requiring them in this assignment. If you're interested, think about how you might do rendering more efficiently!
A hidden side-effect of this constraint is that it prevents you from attempting designs that are overally complicated.
Non-requirements
If you read about text editors online, there are many nifty data structures (gap buffers! balanced trees! etc.) that can be used to efficiently represent text for a text editor. For the purposes of this assignment, you do not need to use any such sophisticated data structures. With appropriate use of the data structures we've learned about so far in this class, you can satisfy the requirements described above.
Shortcut keys
Your editor should do various behaviors in response the user typing a "shortcut" key in addition to a letter. For example, as described in more detail below, pressing the shortcut key and the letter "s" should cause the editor to save the current file. The "shortcut key" should be the control key on Linux and Windows, and the command key on Mac (for consistency with other applications you've used on these operating systems). Luckily you don't need to deal with determining which operating system your program is running on; JavaFX has a nifty
isShortcutDown() function that you can call on any
KEY_PRESSED
KeyEvent to determine whether the shortcut key is pressed. Check out the
ShortcutKeyPrinter program for an example of how this function can be used.
Font and spacing
By default, your editor should display all text in size 12 Verdana font. Verdana is not a fixed-width font, so you will need to calculate the width of each letter to determine where the next letter should begin, and you will need to calculate the height of the font to determine where new lines should begin. You can calculate the height of the font by checking the height of any character (JavaFX considers the height of a letter like "a" or even a space " " to be the same as the height of a letter like "Q" or "j"). The only exception is newlines, which JavaFX considers to have twice the height of other characters. Check out the example applications to see how to calculate the width and height of letters. For this assignment, we suggest that you display each letter as a separate
Text object. See the section in lab 5 labeled
Our First Blind Alley.
JavaFX will report that letters have non-integral heights and widths (e.g., JavaFX reports that the letter "H" in the example below has a width of 9.02). However, JavaFX displays characters on pixel boundaries, and chops off any decimal values that you pass in. For example, if you tell JavaFX to display a letter at position 5.8, the letter will be displayed at pixel 5. As a result, you need to round all width and height values from JavaFX to integral values. If you don't do this, you'll notice that your text ends up spaced in un-appealing ways. The example below gets up-close-and-personal with some text in our solution editor to illustrate the width values reported by JavaFX and how they should be rounded to integral values. The blue boxes show pixel boundaries, and the grey bar at the top is the top of the editor window.
For many fonts, the height of the font includes some whitespace at the top, even above tall characters. You can see this in the example above: there is whitespace above the "H" even though the top margin is 0.
If you take a screenshot of your own text editor and zoom in, yours may look like it has twice as many pixels as the screen shot above:
Fear not! This is because you have a fancy retina display, so your display uses 4 pixels for each 1 pixel that JavaFX knows about. This isn't something you need to handle in your code; just something to be aware of if you're taking screenshots to understand what's going on.
We strongly recommend that you change the "origin" of your text by calling
setOrigin(VPos.TOP) on each of your
Text objects. For an example of this, see
SingleLetterDisplay.java. If you don't do this, when you assign the text a y-position, that position will be the position of the bottom of letters like the "H" and "u" in the example above. This is very inconvenient, because some of the text ends up below this position (e.g., the bottom of the "g") above, so you'll need to adjust for this offset. Setting the origin to
VPos.TOP means that the y-colordinate you assign the
Text object will be the top of all letters (in the example above, all of the letters have
VPos.TOP set as the origin, and they have an assigned y-position of 0).
Changing the font size
When the user presses the shortcut key and the key with the "+" on it, the font should increase by 4 points, and when the user presses the shortcut key and the "-" key, the font should decrease by 4 points (but the font should never decrease to be size 0 or below, so when the font size is 4, pressing the shortcut key and the "-" key should have no effect). You should detect the minus key using
KeyCode.MINUS. You should consider both
KeyCode.PLUS and
KeyCode.EQUALS to be the plus key (since on most keyboards, "+" and "=" are on the same key, and this behavior is consistent with other applications).
Newlines
To detect if the user has pressed the "return" or "enter" key, check if the character in a
KEY_TYPED event is equal to "\r" (also known as the "carriage return", or 0x0D in hex). Please let us know if you have trouble with this; we have tried this on a few different operating systems, but there's a chance that we'll discover new inconsistenies with how how the "enter" key works on different systems. One way to debug what's happening if you run into trouble is to set a breakpoint inside your EventHandler, and then use IntelliJ's debugger to look at the character code in the KeyEvent. This is often easier than printing out the KeyEvent, since characters like "\r" don't print nicely.
When you're writing a file, you should never write "\r"; instead, you should use "\n" for all newlines (this is the UNIX style of handling newlines).
When you're reading a file, you should treat "\n" as a newline, and you should also treat "\r\n" as a single newline. You can assume that anytime you see a "\r" in a file you're reading, it will be followed by a "\n". Windows operating systems use "\r\n" to represent a newline character, which is why we're asking you to handle this second kind of newline character (this will also make it easier for you to test your editor if you're on Windows, because you can create a file with a different program and then open it with your editor). We've included two example files in the
examples/example_files directory to help you test these two different types of newlines (these two files should appear the same when opened in your editor).
Cursor
The cursor should be shown as a vertical line with width 1 pixel and height equal to the height of each letter (see the figure above). The cursor should blink for a period of 0.5 seconds: it should be black for 0.5 seconds, then disappear for 0.5 seconds, and so on. The cursor should always be shown after a letter; for example, in the "Hug" example above, if the cursor were after the "u", it would cover the first vertical line of pixels in "g" (and not the last vertical line of "u").
TIP: If you can't figure out how to display the cursor, take a look at
SingleLetterDisplay.java. Think about whether there's anything in that example that would be useful for making a blinking cursor!
What happens when the cursor is between lines?
One tricky part is handling where to place the cursor when the cursor is at the end of a line. If you experiment with Google Docs, you'll notice that when the cursor's logical position is in between two lines, it is sometimes displayed at the end of the earlier line, but other times it is displayed at the beginning of the later line. For example, consider the text below:
There is a space after the word "very", and the editor word-wrapped the line between "very" and "long". When the cursor is after the space after "very" and before "long", it will sometimes appear at the end of the 2nd line, after the space after "very", and it will sometimes appear at the beginning of the 3rd line, before "long". When the cursor position is ambibugous because it is between lines, the positioning should obey the following rules:
- When the user is navigating with the left and right arrow keys, the cursor should always appear at the beginning of the later line.
- When the user is navigating with the up and down arrow keys or using the mouse, the cursor may appear in either position, as appropriate. For example, if the user clicks to the right of "very ", the cursor should appear at the end of the 2nd line, after the space after "very". If the user clicks to the left of "Here", the later line, the cursor should instead appear before the "H". For a more detailed explanation of how the arrow keys should move the cursor, see the Moving the Cursor with Arrows section.
- When the most recent action was to add text, the cursor should appear at the end of the earlier line, except if the most recent action added a newline character, in which case the cursor should appear on the new line (consider this a hint: it's easier if you put newline characters at the end of the line before the newline!).
- When the most recent action was to delete text and the cursor position is ambiguous, it should appear on the line where the deleted text was.
Note that these rules only apply when the cursor position is ambiguous because it is between lines. If you have questions about how the cursor position should work, try experimenting with Google Docs or your editor of choice. We have observed that editors are consistent on all but the last requirement (about what to do when text is deleted), which different editors handle in different ways.
Moving the cursor with arrows
There are a few different ways that you should handle moving the cursor. First, you should support the arrow keys. If the user presses the left arrow key, the cursor should move to the left one character (unless the cursor is at the beginning of the file, in which case pressing the left arrow key should have no effect). Consider the example from above again:
When the cursor is on the 3rd line, after the "l" in "long", pressing the left arrow should move the cursor to before the "l" in "long". At this point, the cursor's logical position is after the space after "very" and before "long". Pressing the left arrow again should move the cursor to after the "y" in "very" (and before the space after "very").
As a second example, if the cursor is after the "H" in "Here", pressing the left arrow key should move the cursor to immediately before the "H" key. Pressing the left arrow key again should move the cursor to after the ")" on the first line (so the cursor has moved back one character, which in this case was a newline character).
The right arrow key should work in a similar way: pressing the right arrow key should advance the cursor one character to the right (unless the cursor is at the end of the file, in which case the right arrow key should have no effect).
The up and down arrows should move the cursor up one line and down one line, respectively. The cursor's horizontal position on the new line should be as close as possible to the horizontal position on the current line, with the constraint that the cursor should always appear between characters (it cannot be in the middle of a character).
When pressing the up and down arrows, you do not need to maintain a notion of the original position, which is a behavior implemented by many other text editors. For example, consider a case where the cursor is at the end of a long line, and you press the up arrow to position the cursor at the end of the previous line, which is shorter. If you press the down arrow again, the cursor does not need to re-appear at the end of the long line; it can re-appear at the horizontal position closet to the end of the previous, shorter line.
Moving the cursor with a mouse click
When the cursor is moved as a result a mouse click, the cursor's new vertical position should be on the line corresponding to the vertical position of the mouse click. If the mouse click is below the end of the file or above the beginning of the file, the new vertical position should be the last line or the first line, respectively. The cursor's horizontal position should be the closest position to the x-coordinate of the mouse click. Keep in mind that this means that clicking on a letter may cause the cursor to appear before or after the letter, depending on whether the mouse position was closer to the left or right side of the letter!
Printing the Cursor Position
To facilitate grading, when the user presses shortcut+p, you should print the top left coordinate of the current cursor position. The cursor position should be printed in the format "x, y" where the x and y positions describe the cursor position relative to the top left corner of the window (note that the y position may be negative when the cursor is above the window and out of view). The cursor position should be followed by a newline. For example, suppose you open the file, type a letter that is 7 pixels wide, type a second letter that is 4 pixels wide, press shortcut+p, move the cursor by pressing the left arrow once, and then press shortcut+p again, your program should print:
16, 0 12, 0
The cursor position should be printed as an integer because the cursor should always be at an integer, as described in Font and spacing.
The coordinates of the cursor that you print should be relative to the window. For example, if the cursor is at the beginning of the first line of visible text, the position printed should be "5, 0", even if there's more text above that isn't visible. We will be using your printed cursor positions for grading.
Non-requirements
As you experiment with other text editors for this project, you may notice that other editors stop the blinking of the cursor while text is being typed (so the cursor is shown as a solid line while text is typed). You do not need to implement this feature for this project.
Word wrap
When the user types more text than will fit horizontally on the screen, your editor should wrap the line. We have provided a detailed explanation of how word wrap should work below, but before reading this, we suggest that you do some of your own experimentation in your editor of choice (e.g., Google Docs). Experimenting yourself will give you a better intuition for the feature, and is more fun than reading the text below!
Breaking a line between words
When possible, lines should be broken between words (i.e., when there is a space or a newline).
You should implement word wrap greedily: fit as many words as possible on the current line before starting a new line. As a user is typing, you should wrap the current word onto a new line as soon as the word is too long to fit onto the current line. For example, consider the text below.
When the user types the next letter, "e", the "e" won't fit onto the current line (taking the 5 pixel margin into account). As soon as the user types "e", the entire word should be moved to the next line
You should also greedily word-wrap when inserting characters into the middle of a line or even into the middle of a word! Remember that when inserting characters into the middle of a word, the new character might fit on the current line, but the characters in the rest of the word might add too much width for the entire word to fit on the current line.
Finally, you should greedily wrap words when deleting. If a user deletes characters from a word such that the word would fit on the previous line, the word and cursor should both move back to the previous line. For example, in the example above, if the user deleted the "e", the "ev" should be moved back to the previous line, where they were before the "e" was added. Similarly, if a user deletes text in the middle of a line such that the first word on the next line would fit on the current line, that word should be moved back to the current line. For example, if the user started deleting "and longer" from the text in the example, the "eve" should be moved back to the first line as soon as it fits:
Whitespace characters should be treated specially when wrapping lines: whitespace characters at the end of a line should never be wrapped onto the next line, even if they do not fit on the current line. If the user types whitespace at the end of a line that extends beyond the allowed text area, the cursor should stop at the edge of allowed text area (i.e., the edge of the screen, minus 5 pixels for the margin), even as the user continues to type more whitespace. The line should only wrap when non-whitespace characters are typed. Your editor must keep track of that whitespace, so that if the word before the whitespace wraps onto a new line, the correct amount of whitespace is displayed after that word. If you're confused about this, we suggest experimenting with Microsoft Word, Google Docs, or TextEdit. Note that the only type of whitespace that you need to handle is spaces resulting from the user pressing the space bar.
Breaking a line in the middle of a word
You should only break a line in the middle of a word when the word is too long to fit in its own line. Consder the following example, where the user starts typing a long word:
First, the long word will get wrapped onto its own line:
Eventually, the word will be too long to fit on one line, so the line should break in the middle of the word:
If the word keeps getting longer, line breaks should keep being added as necessary:
TIP: Implementing word wrap is easiest if you do it from the very beginning of a file. Each time a letter is added at the end of a word, you can check to see if that word needs to move to the next line. Always starting from the beginning of the file is much easier than figuring out how to adjust the word wrapping when characters are added or deleted mid-word or mid-line.
Open and Save
As mentioned in the command line arguments section, the first command line argument passed to
Editor must be the name of a file to edit, and this argument is required. If that file already exists,
Editor should open it and display its contents (with the starting cursor position at the beginning of the file); otherwise,
Editor should begin with an empty file. Presing shortcut+s should save the text in your editor to the given file, replacing any existing text in the file. If you encounter an exception when opening or writing to the file (e.g., because the user gave the name of a directory as the first command line argument), your editor should exit and print an error message that includes the filename (for example, "Unable to open file nameThatIsADirectory"). Beware that if you attempt to read from a file that doesn't exist, Java will throw a
FileNotFoundException, which is the same kind of exception you'll get if you try to read from a directory. Check out
CopyFile.java for an example of how to determine if a file exists before attempting to read from it.
Opening a file should take time proportional to the length of the file, not to the length of the file squared. As a reference point, in our example text editor, opening a file with about 2000 characters took less than one second. If your editor takes, for example, a little over a second for a similarly sized file, that is fine, but it should not take a lot more than a second (e.g., it should not take 30 seconds).
You can assume text files are represented as ASCII. This means that if you read from the file, e.g., using a
BufferedReader called
myReader, you can cast the result to a char:
char readChar = (char) myReader.read()
For more about
BufferedReaders, checkout the
CopyFile.java example, or the official documentation.
TIP: Implement save and open as early as possible! These make it much easier to test other features like word wrap and handling mouse clicks.
Scroll bar
Your editor should include a scroll bar on the right side of the screen that can be used to scroll through a document that doesn't all fit on the screen at once. When the scroll bar is at the top position, the top line of text should be at the top of the screen; when the scroll bar is at the bottom position, the bottom line of text should be at the bottom of the screen. You do not need to implement optimizations to avoid rendering text that is not currently visible on the screen.
TIP: If you're struggling with the scroll bar, after reading the writeup below, take a look at this page for some extra tips on how it works.
The scroll bar and the cursor
Moving the scroll bar should not move the cursor. So, it's possible for the user to move the scroll bar such that the cursor is currently off of the screen (because it's at a position that's not currently visible). However, if the cursor is off of the screen and then the user starts typing (e.g., typing a new letter), the window should "snap" back to a location where the cursor is visible (you can play around with other editors like Google Docs to see this functionality in action). When you're "snapping" the window back so that the cursor is visible, you should perform the minimum adjustment so that the cursor is visible. If the cursor is below the currently visible text, the scroll bar and window position should adjust so that the cursor is on the bottom line of visible text. If the cursor is above the visible text, the scroll bar should adjust so that the cursor is on the top line of visible text. Note that you should only do this adjustment if the user starts typing; if the user is just scrolling with the scroll bar, it's fine for the cursor to be off of the screen.
If the user moves the cursor (e.g., with the arrow keys) such that it is off of the visible screen, the scroll bar and window position should automatically adjust so that the cursor stays visible. As above, your editor should use the minimum adjustment that maintains visibility of the cursor.
TIP: When the scroll bar moves, you need to move all of the text in the document. You could move each text object individually, but your life will be much easier if you create a new
Group (e.g., called
textRoot) that's a child of your application's root
Group and a parent of all of the
Text nodes. To do this, you can add
textRoot as a child of your application's root:
Group textRoot = new Group(); root.getChildren().add(textRoot);
And then add all of your
Text nodes (and the cursor) as children of
textRoot rather than as children of
root. (JavaFX will display all
Nodes that are children of the root, children of the root's children, and so on.) When you want to move all of the text, you can just move the
textRoot object. For example, to shift the text position up by 10 pixels (so that 10 pixels are hidden above the window), you would do:
textRoot.setLayoutY(-10);
If you're not sure how this works, do some HelloWorlding to experiment!
Rounding
As with text positions, you should always round the position of the window (when adjusted with the scroll bar) to be an integral number of pixels. For example, if the scroll bar's position dictates that the window should be shown so that 8.2 pixels are hidden at the top (i.e., so the window begins 8.2 pixels down into the document), you should round this to 8 pixels.
Non-requirements
You only need to handle changes to the scroll bar that are initiated by clicking somewhere on the scroll bar, as in the
ScrollBarExample code. You do not need to move the scroll position as a result of mouse wheel events.
You may notice that the default scroll speed is very slow. You're not required to fix this, but if you're interested, take a look at the
setUnitIncrement and
setBlockIncrement methods in the
ScrollBar class.
Undo and Redo
Your editor should support undo (when the user presses the shortcut key and the "z" key simultaneously) and redo (when the user presses the shortcut key and the "y" key simultaneously. You should keep a stack of up to 100 undo events, but you should not store any more undo events than this (if you never deleted old undo events, your stack of events to undo could grow to be unbounded!). Your editor should also support re-doing any events that have been un-done. For example, suppose the user does the following actions:
- Types "a" (editor should show "a")
- Types "d" (editor should show "ad")
- Deletes "d" (editor should show "a")
- Types "b" (editor should show "ab")
Now, undo / redo should work as follows:
- Undo (editor should show "a")
- Undo (editor should show "ad")
- Undo (editor should show "a")
- Redo (editor should show "ad")
- Undo (editor should show "a")
And so on. As soon as a user does a new action that is not an undo or redo, redos should no longer be possible. For example, after the sequence above, if the user adds a new letter like "z", pressing redo should have no effect. You do not need to explicitly limit the number of redo events that you store, because it is implicitly capped by the limit on the number of undos (try some examples in your text editor of choice if this doesn't make sense).
Cursor movements are not considered actions that need to be undone / redone, and when you undo or redo, the cursor should be moved back to the position it was when the action originally took place. If necessary, the scroll position should be updated so that the cursor is visible.
Font re-sizings and window re-sizings are also not considered actions that need to be undone / redone (since these don't affect the contents of the document; they only affect how the document is shown to the user).
Non-requirements
If you experiment with undo on other text editors, you may notice that they do coarser-grained undo (e.g., undo will undo the entire last word or last line typed). You do not need to implement this in your text editor.
Optional Beautification
If you like, you can change the appearance of the mouse in your text editor to be a text icon, like you've seen in other text editors. You can do this by calling the setCursor() method on your root
Group object. If you do this, you'll probably also want to call
setCursor to override the cursor on your
ScrollBar to be the default cursor, because it looks a little funny if the cursor is the text cursor when it's over the scroll bar. This functionality is optional because we have found that JavaFX's implementation of this is buggy, and the cursor changes back to the default when you re-enter the window, even if you register an event to change the cursor to the text cursor every time the mouse enters the window again (if you figure out how to get this to reliably work, let us know!). There are no additional points associated with implementing this functionality; the only reward is the joy you'll feel at seeing the fancy cursor!
Gold Points
There are two features you can implement for gold points. The features build on each other, so you must do them in order (i.e., you can't just do copy / paste, because it requires selection first, to select the text to copy).
Selection (3 points)
Add a feature to your text editor to support selection: if the user presses down on the mouse, drags it across some text, and releases the mouse, the text between the start and end position should be highlighted. Selection should work while the user is dragging (so the text should appear selected instantaneously as the user drags, before the mouse is released). You should use
Color.LIGHTBLUE as the background for highlighted text. When the highlighted text spans multiple lines, the highlighted background should extend to the margin on all but the last line (even if the line didn't extend to the right side of the window), as in the example below:
When text is selected, the cursor should disappear, and where you'd normally print the cursor position, you should print the position of the leading edge of the selected text (in other words, the position the cursor would have printed, had the cursor been immediately before the selected text).
You should also handle the case where a character is input or the delete key is pressed while text is selected. If a character is input, the selected text should all be deleted, and the character should be inserted where the selected text was. If the delete key is pressed while text is selected, all of the selected text shoud be eliminated from the document.
If the user presses the left arrow key while text is selected, the cursor should appear at the beginning of the selection; pressing the right arrow key should cause the cursor to appear at the end of the selection. If the up arrow key is pressed, the cursor should move up from the beginning of the selection (so it should appear one line higher than the beginning of the selection, at the closest horizontal position to the horizontal position of the beginning of the selection). Similarly, if the down arrow is pressed, the cursor should move one line down from the end of the selection, to the horizontal position closest to the horizontal position of the end of the selection.
Undo and redo should still work after you've implemented selection. Pressing undo should undo one action from the perspective of the user. For example, if the user had some text selected and then pressed "a" to replace the selected text, and then presses undo, the "a" should be eliminated and the text should appear selected again.
Copy / Paste (2 points)
Add copy/paste functionality to your editor: when the user presses shortcut+c, any selected text should be saved to the system clipboard, and when the user presses shortcut+v, the text on the system clipboard should be added to the editor at the current location. Because you're adding things to the system's clipboard, pressing shortcut+v should paste any text copied in a different application into your text editor, and similarly, if you copy something in your editor, you should be able to paste it in a different application. Take a look at
ClipboardExample to see how to interact with the system clipboard.
Undo and redo should work for pasting: if the user pastes some text into the document, and then presses shortcut+z, all of the pasted text should be removed.
Extra Credit Autograder
A basic autograder is available that tests that your printed cursor position is correct under the following circumstances:
- At program startup (AGInitialCursorTest).
- After typing text that fits on one line (AGSimpleTextTest).
- After typing text and backspacing (AGBackspaceTest).
- After typing text and using left and right arrow keys (AGArrowKeyTest).
- After typing text that involves newlines (AGNewlineTest).
To get the autograder, pull from skeleton using
git pull skeleton master. To run one of the five autograder tests, just run the class file, e.g.:
$ java editorTester.AGInitialCursorTest
These tests will only work correctly if:
- Your code prints the current cursor position when shortcut+p is pressed.
- Your code does not print anything else to the screen, other than the cursor position when shortcut+p is pressed.
Of course, you're welcome to print anything you'd like so long as you specify "debug" as the second command line argument. Our test files will not use this argument, so such print statements will not interfere with the grader.
Completing these tests by 3/2/16 at 11:59 PM will yield 0.2 bonus points per test.
Submission for Basic Autograder
To get credit for passing the tests, run the editorTester tests with the optional command line argument "gradescope". For example:
$ java editorTester.AGInitialCursorTest gradescope
You will be prompted to enter your gradescope email address. If you are not prompted, repull from skeleton since you have the old version of the autograder. Enter it exactly like your account from gradescope. If your test is successful, a file called TokenAGInitialCursorTest.java will be generated.
Run this for each of the five tests, and if you pass all of them you'll generate 5 distinct tokens.
Simply upload these to gradescope for credit. Warning: Do not provide tokens for other students in the class. If we happen to catch you, this will be considered a failing grade in the course, as per our course plagiarism policy.
5:00 PM: At present the test will only work if you submit all 5 tokens, but I'll be fixing this very soon.
Tokens are due 3/2/2016 at 11:59 PM, barring any infrastructural issues that I am unable to fix due to travel.
Submissions
For information about submitting your assignment, see this Piazza post. For a rough point breakdown and information about how your project will be graded, see this Piazza post.
Frequently Asked Questions
Does my editor need to support any non-text keys not mentioned in the spec (e.g., the tab key)?
No, you do not need to support any additional key presses beyond the ones mentioned in the spec.
What about the delete key, which deletes the character in front of the cursor on some operating systems?
You do not need to handle this special delete functionality; you only need to handle the backspace key (which removes the character behind the cursor).
How can I efficiently append to a String?
You shouldn't need to append to a String for this assignment! If you're just curious, Strings are immutable, so if you want to efficiently construct a string by appending substrings to it, you can use a
StringBuilder (but to reiterate, you should not be appending to Strings or using StringBuilders for this assignment!).
My Text / Rectangle / other Node isn't appearing on the screen!
Make sure you've added the new Node to the scene graph; e.g.,
root.getChildren().add(<new thing>).
What is this mysterious root and why do I need to change its children? (or: what are Groups?)
Before talking about
root, it's helpful to describe JavaFX
Nodes. JavaFX uses the
Node abstract class to represent, essentially, "something that should be displayed on the screen." All of the things you display — Rectangles, Text, Groups, etc. — are subclasses of Node. Checkout the Node documentation here:
root is a special
Node that JavaFX uses to determine what to display in the window. Each JavaFX application has exactly one Scene (you can think of the Scene as a container for all of the JavaFX "stuff"), and each Scene has exactly one "root" node ("root" is just a naming convention used for this special
Node). JavaFX uses the root node to determine what do display: JavaFX displays the root node, and all of the children of the root node, and all of the children of the children, and so on. This is why when you add a new Node (e.g., a Text object), you need to do this funny "root.getChildren.add(..)" call: this call adds your new Node as a child of "root" so that it will be displayed. This page talks in extensive detail about the scene graph; just looking at figure 1 is probably most useful.
A Group is a special kind of Node that can have children. Usual nodes (e.g., Text nodes) can't have any children. You'll notice that the
root is actually a
Group (in the examples, we create it with something like
Group root = new Group()). It can be useful to create a Group if you want to style a bunch of nodes together. For example, you can make a Group called "thingsIWantToMove", and when you adjust the layout position of "thingsIWantToMove", it will change the layout of all of the children of the "thingsIWantToMove" Group. For example:
Group thingsIWantToMove = new Group(); root.getChildren().add(thingsIWantToMove); Rectangle rectangleToMove = new Rectangle(10, 10, 10, 10); Rectangle secondRectangleToMove = new Rectangle(20, 20, 20, 20); thingsIWantToMove.getChildren().add(rectangleToMove); thingsIWantToMove.getChildren().add(secondRectangleToMove);
Notice that
rectangleToMove and
secondRectangleToMove were both added as children of
thingsIWantToMove rather than as children of
root. Since
thingsIWantToMove is a child of root, these rectangles wil still be displayed on the screen. Now, you can change the position of
thingsIWantToMove, e.g.,
thingsIWantToMove.setLayoutX(30);
This call will change all of the children of
thingsIWantToMove to be shifted to the right by 30 pixels. Note that
rectangleToMove.getX() will still return 10 (the original value it was set to be), but
rectangleToMove will be displayed at an x-position of 10 relative to the position of its parent. Since its parent is at an x-position of 30,
rectangleToMove will be displayed at an absolute x-position of 40 (i.e., it will be 40 pixels to the right of the edge of the window). It will likely be helpful to do some "hello worlding" to understand how groups and layout positions work, where you make a simple example (much simpler than your editor!) just to experiment with.
Groups may be useful when you're implementing the scroll bar, as hinted at in that section of the spec.
What do you mean by "render"? How do I re-render things?
By "render", we mean draw all of the text on the screen. As described above, in JavaFX, to display a
Node on the screen, it needs to be added as a child of
root (or one of
root's children, or one of the children of one of
root's children, and so on). JavaFX displays all of the children, grandchildren, etc. of
root automatically; you don't need to call any special functions to make this happen. You may be wondering how to change something once it's already been placed on the screen. For example, suppose you add a rectangle to the screen:
// Make a 5x5 rectangle at position 0, 0. Rectange funGrowingRectangle = new Rectangle(0, 0, 5, 5); root.getChildren().add(funGrowingRectangle);
And then later, you decide you'd like to make the rectangle larger. One way to do this is to remove the rectangle from the children of root and then re-add a new one:
root.getChildren().remove(funGrowingRectangle); // Make a 10x10 rectangle as position 0, 0. Rectangle biggerFunnerGrowingRectangle = new Rectangle(0, 0, 10, 10); root.getChildren().add(biggerFunnerGrowingRectangle);
However, you can also change the attributes of the existing
Node. For example, after running the previous code, you could change the size of
biggerFunnerGrowingRectangle with:
biggerFunnerGrowingRectangle.setWidth(30); biggerFunnerGrowingRectangle.setHeight(30);
And voila, you will see a rectangle with a width and height of 30! The call
getChildren().add(biggerFunnerGrowingRectangle) added a pointer to
biggerFunnerGrowingRectangle to the children, so changing properties of
biggerFunnerGrowingRectangle means that the
Rectangle shown on the screen will change accordingly (JavaFX will always display all nodes reachable from root, using the current properties of those nodes). When we say that rendering should take linear time, we mean that updating all of the JavaFX objects (e.g., their positions, the font size, etc.) should take linear time.
How can I remove Nodes from the screen? Is it ok to remove all of the children of root and re-add them each time?
You can remove Nodes from the screen with the
remove function. For example, suppose you have added the letters "H", "u", and "g" to the screen, and then want to remove the "u". You could do that as follows:
Text letterOnLeft = new Text("H"); root.getChildren().add(letterOnLeft); Text letterInMiddle = new Text("u"); root.getChildren().add(letterInMiddle); Text letterOnRight = new Text("g"); root.getChildren().add(letterOnRight); // ... sometime later, delete the middle letter. root.getChildren().remove(letterInMiddle);
You should not remove things by clearing all of the children of root and re-adding them each time, for example, with code like this:
// Do not do this! root.getChildren().clear(); root.getChildren().add(letterOnLeft); root.getChildren().add(letterOnRight);
This strategy will be prohibitively slow when editing a large file.
I want to add something as a child of
root but I can't get access to
root in the location where I want it!
If you worked off of one of our examples, you probably created root with a call like:
Group root = new Group();
in your
Editor class's
start() function. You may later have some other function in
Editor where you want to use
root:
public void drawCow() { Cow myCow = new Cow("Clover"); root.getChildren().add(myCow); }
If you haven't changed anything else in your
Editor, this code will cause a compile-time error because
root cannot be found. This error may seem vexing because
root and the
start() method are these mysterious JavaFX constructs, but remember your old friend the instance variable! You can use an instance variable in your
Editor class to save the value of root, if you like, just like you've used instance variables in the past to save variables that are needed in many places in your class (e.g., the array that you used to store data in
ArrayDeque). For example, you could add something at the top of your
Editor class like:
public class Editor extends Application { Group root; ...
and then in your
start method, you can set the
root instance variable rather than creating a new
root variable:
root = new Group();
If you'd like, you can also create a no-argument constructor for your
Editor class where you initialize
root:
public Editor() { root = new Group(); }
Then, in
start(), you can use the
root instance variable (e.g., when you're making a
Scene) rather than creating a new
root variable. JavaFX will call the no-argument constructor of your application for you (before
start() is called). For an example, checkout
SingleLetterDisplay.java, which uses a no-argument constructor to set up some instance variables.
Maybe you want to use
root in a different class, e.g., the
CowDrawer class:
public class CowDrawer { // The cow to draw. Cow cow; public CowDrawer() { cow = new Cow("Bluebell"); root.getChildren().add(cow); } }
Again, you'll get a compiler warning. Remember that
root is just like any other variable, and if you want to let other classes have access to it, you'll need to explicitly tell those classes about it, e.g., by making it a constructor variable:
public class CowDrawer { // The cow to draw. Cow cow; public CowDrawer(Group root) { cow = new Cow("Bluebell"); root.getChildren().add(cow); } }
This new code will compile, and the code that creates
CowDrawer will need to pass the
root variable into the constructor.
What does this error mean? "Caused by: java.lang.NullPointerException: Children: child node is null: parent = Group@4490e1f7[styleClass=root]""
This typically means you’re trying to add a Node to the scene graph (e.g., using something like
group.getChildren().add(<new node>)) that’s null or not completely initialized.
Can I use methods from the swing or awt or \
?
No.
Can I use Java Libraries?
You're welcome to use Java libraries for data structures like Lists, Queues, etc. You can also use Java libraries for reading from and writing to files. As mentioned in the previous question, you should not use any graphics libraries other than JavaFX.
Can I use code that I found online and that's not from a Java library?
In general, no; other than the Java libraries, all of the code used for this project should be your own. If you have a specific use case that seems questionable, feel free to post on Piazza.
Can I use functionality from earlier projects, even though I worked with a partner on those projects?
Yes.
I added a
ChangeListener to ScrollBar to listen for when the user scrolls, but this listener gets called even when my code initiates a change to the value of the scroll bar! How do I avoid this?
When you add a listener that listens for changes to the value of the scroll bar, that listener's
handle function will be called even when your code (and not the user) initiated a change to the value. One way to avoid this to store the value that your code has set the scroll position to be. Then, in
handle(), you can check whether the new value is the same value that your code already set.
I'm carefully placing the scroll bar at the edge of the window, but there is this ugly border of a few pixels to the right of the scroll bar. HALP.
This seems to be a bug with JavaFX; this happened for us too (you'll notice this border in all of the examples above). Sometimes the border magically goes away when the window is re-sized. Don't worry about this.
Can I use JavaFX's
ScrollPane instead of
ScrollBar?
No. We did some experimenting with
ScrollPane and found that it was easier to implement the editor using a
ScrollBar. We realize you may not agree, but allowing people to use different kinds of scrolling functionality makes it difficult to grade the assignments, because the different scroll functionalities take up different amounts of horizontal space on the screen. Sorry!
The bar (sometimes called the "thumb") in my scroll bar seems really small. Is this normal?
Yes. JavaFX creates a scroll bar that's always the same wee size by default. If you'd like, you can set the size of the scroll bar using the
setVisibleAmount method, but this is not required, and it is tricky to get right.
As an aside, if you get really excited about scroll bars (who wouldn't be?), you can write your own scroll bar using one of Java FX's rectangles, and setting the arc properties on the rectangle to get rounded corners. You can use this functionality to create a fancy minimalist scroll bar (just a dark-grey rounded rectangle on the right side of the screen), and register mouse properties so that dragging the scroll bar changes the position of the text. This is entirely a fun experiment, and not something you should turn in with your assignment, because it will break the grading of your assignment.
I'm getting an error from JavaFX that says duplicate children were added. What does this mean?
This error is happening because you're adding the same Node object to the root twice. For example, suppose you do something like:
Text t1 = new Text("h"); root.getChildren().add(t1);
Now, if you change t1 and try to add it again:
t1.setText("hi"); root.getChildren().add(t1);
The second call will throw an error, because JavaFX recognizes that t1 is already in children. JavaFX displays all of the nodes that are children of root, or children of children of root, and so on. If you change a node that is already reachable from root (e.g., in the example above, if you change the string stored in t1), JavaFX will update the displayed text automatically. If you want to add another piece of text to root, you should do something like:
Text t2 = new Text("my new text"); root.getChildren().add(t2);
Pressing command+equals (or command+minus) causes three events to happen, so my font increases (or decreases) by 12 rather than 4. What's going on?
This seems to be a bug issue with the way some keyboards / operating systems interact with JavaFX. Try running
KeyPressPrinter to see what happens when you press shortcut and the offending key (some folks have had this problem with the equals/plus key, and others have had this problem with the minus key). For example, if you're having this problem with equals, run
KeyPressPrinter and press shortcut+equals. If you see output that your keyboard is working correctly, and there's an issue in your code that you should debug. This output has one
KEY_PRESSED event for when the command key was first pressed, a second
KEY_PRESSED event for when the equals key was pressed (note that
shortcutDown is set in the key event, meaning the command key was also down), and a final
KEY_TYPED event for the "=" key, which should be ignored in your editor because
shortcutDown is set.
On the other hand, if the output you have the keyboard bug issue. In this output, the key pressed and key typed events for the equals key are duplicated three time. If this happens to you, then don't worry about the font-increasing-by-three (or decreasing by three) issue; this is an issue specific to your machine that won't occur when we grade your assignment.
Acknowledgements
Inifinite thanks to Akhil Batra and Matt Mussomele, who completed this project before it had a spec or any examples! | http://sp16.datastructur.es/materials/proj/proj2/proj2.html | CC-MAIN-2020-50 | refinedweb | 11,721 | 67.38 |
On occasion, your regular author, Peter Shaw, requires rest from the daily strife of the I.T. world. As much as a ghost in the machine as he is, even he needs such rest. Therefore, from time to time, I shall pop my head up and fill in with a few articles, making up for any gaps. Given that Shawty's articles are .NET/C# focused, I will be following his lead.
For my first article, I'd like to share with you a very nice combination of technologies, which is: Entity Framework Core 1.0, SQLite, and—for the sake of this article—something on the desktop, such as a console application.
Entity Framework Core
Before we start, where does EF Core come from? As its name suggests, it spun out from the .NET Core camp of development. EF Core is an extensible version of Entity Framework, which may be complied against the full .NET Framework, or .NET Core for cross platform development. It's worth keeping in mind that the original Entity Framework is still in development, but can only be complied against the full .NET Framework. You can find the GitHub repositories for both .NET Core and EF Core below…
The next question one might ask is: If I'm building a desktop application with the full framework .NET, will pieces of code from .NET Core world work with something such as WPF or Win Forms? The answer to that is simply yes, although the more recent versions of .NET are recommended and needed in some cases. And, this is one of the great things about .NET Core. You may have heard the words light-weight being throw around a lot when .NET Core is in conversation. Well, that light-weightiness refers not immediately to size, but to modularity.
One of the guiding principles of its development was strong modularity. And this principle, echoed throughout all the projects spun from .NET Core, is something we can take great advantage of. And in this article, this is exactly what we'll be doing.
Building the Application
To give you a basic overview, this application will be a .NET console application, for which we'll bring in the needed components for EF Core for SQLite.
Once you have your full framework .NET Console application created, you'll need to open your NuGet package manager, tick the 'include prerelease' option on—which is required at the time of this writing—and grab the following packages:
- EntityFramework.SQLite: This will install everything you need if you don't want to create migrations.
- EntityFramework.Commands: This will give you the commands you'll need to create a migration from the package manager console.
When you install the EF SQLite package, you will see quite a few libraries of code being installed. Don't worry about this. Remember, as we've already talked about, .NET Core has a strong emphasis on modularity. There are a few libraries that come down with EF Core you may find are worthy of further investigation. I've used a number of them on recent projects for various needs.
And that's it. That's everything you need to get started with some coding. If you've used Entity Framework before, you'll have probably jumped ahead and created your db context class already; but if you haven't, mine looks something like this…
public class DataContext : DbContext { public DataContext() { Database.Migrate(); } public DbSet<Beer> Beers { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { string connectionStringBuilder = new SqliteConnectionStringBuilder() { DataSource = "beer.db" } .ToString(); var connection = new SqliteConnection(connectionStringBuilder); optionsBuilder.UseSqlite(connection); } }
If we examine the preceding code a little, we first need to look at the override we have in place for the 'OnConfuguring' method. In our override, we are creating a connection string using the SqliteConnectionStringBuilder class. We can give a name to our db by passing a string to the 'DataSource' property. I've named my database 'beer.db,' but you can give this database whatever name suits you best. Keep in mind the name of my database reflects that I'll be storing information about my favourite beers in this db.
If you are familiar with EntityFramework already, you'll recognise the property of type DbSet<T>, where T in my case is 'Beer.' If you are not familiar with EntityFramework, this property represents a table in your database. It might be recommended you dive a little more into Entity Framework for more details, but you can probably get to the end of this article without that knowledge and just play a little.
You'll also see a line of code in the constructor for our db context; but we'll cover this in a moment.
If you haven't created a class to quell the voices of Intellisense—which at this point will be given you and an error saying it can't find Beer. This is what I have in my Beer class.
public class Beer { public int Id { get; set; } public string Name { get; set; } }
Migrations
We'll be going into the code to add an item to our database at runtime in a moment. Before we do, we need to talk about creating our SQLite database file. For this writing, I'm using migrations because of how easy it is to use in EF Core and I want to show you this. This is apparent when you look at the 'DataContext' class above, which includes the line…
Database.Migrate();
There is another option you can use here, which is…
Database.EnsureCreated();
I'll leave it to your good self to explore the various options, but EnsureCreated pretty much does what it says on the box. It ensures that when you new the context up, the database has been created; and if it hasn't, it will create it. However, because we are using Migrate(), we won't need to use EnsureCreated() for this application.
And, as we are going down this path. we need to create our migration. Being sure we installed the package 'EntityFramework.Commands,' open your Package Manager Console and use this command…
Add-Migration
It will ask you for your migration name. Put what you like here; I used 'Initial-Migration' myself. Press Enter, and away it will go, creating your migration. And that is it. You do not need to update your database through the package manager console—if you are used to doing this—because the line of code 'Database.Migrate()' will do this for you at runtime. And, at the same time, it will ensure the database has been created, and create it if it does not exist.
The Program
And the final piece of this application… The program.cs.
Mine is quite simple. It asks for a beer name, creates a beer object, and enters this into the database. My code looks something like this…
class Program { static void Main(string[] args) { Console.WriteLine("Enter a beer name"); string beerName = Console.ReadLine(); Beer beer = new Beer() { Name = beerName, }; DataContext db = new DataContext(); db.Beers.Add(beer); db.SaveChanges(); } }
And that is it. The complete application, which if you run it, you can enter a beer name and store that in your SQLite db. Further expansion on the application might include the strength of the beer, and possibly a personal rating for said beer. Possibly even some notes, allowing you to expand a little on taste and quality.
When you have entered a few beers, you might want to have a peek into the db file. You will find your db file in the root of your application. If the application was run from VS in DEBUG, this would be -> bin -> Debug -> beer.db. Unless, of course, you named your db something else. To look at the Sqlite db file, I like to use sqlitebrowser, which can be found here.
One you've downloaded the required exe for your platform, run the browser and open the db file. For me, I can now see something like this…
Figure 1: The program in action
If you feel like exploring a little, you can see various pieces of information through each of the tabs; such as your 'Migrations History' by selecting the table under Browse Data, and 'Database Structure.'
If you want to see the application, as I have put it together, running, you can find the code in GitHub at. Also, if you have any questions, you can find me on Twitter as @GLanata.
There are no comments yet. Be the first to comment! | https://www.codeguru.com/columns/dotnet/using-the-entity-framework-core-with-sqlite.html | CC-MAIN-2018-43 | refinedweb | 1,427 | 74.08 |
Here is the final patch I'm committing. I've fixed my previous change of msg_target, and restricted the variable_defined check to user-targets. 2002-09-13 Alexandre Duret-Lutz <address@hidden> Diagnose target clashes, for PR automake/344: * automake.in (%targets): Record conditionals for definitions. (%target_conditional): Remove (obsoleted by %targets). (%target_source, %target_owner): New hashes. (TARGET_AUTOMAKE, TARGET_USER): New constants. (initialize_per_input): Adjust to reset new variables. (err_cond_target, msg_cond_target): New functions. (msg_target): Adjust usage of %targets. (conditional_ambiguous_p): Take a list of conditional to check as a third parameter, so this can be used for other things that variables. (handle_lib_objects_cond): Adjust conditional_ambiguous_p usage. (variable_defined): Restrict the target-with-same-name check to user targets. (rule_define): Add the $SOURCE argument, and take $OWNER instead of $IS_AM. Diagnose target clashes (including ambugious conditionals). Return a list of conditions where the rule should be defined instead of a boolean. Fill %target_source and %target_owner. (target_define): Use `exists', not `defined'. (read_am_file): Adjust the call to rule_define. (file_contents_internal): Add more FIXMEs. Simplify my moving and documenting the "define rules in undefined conditions" to rule_define. * tests/Makefile.am (XFAIL_TESTS): Add specflags7.test and specflags8.test. Index: automake.in =================================================================== RCS file: /cvs/automake/automake/automake.in,v retrieving revision 1.1347 diff -u -r1.1347 automake.in --- automake.in 10 Sep 2002 20:45:57 -0000 1.1347 +++ automake.in 13 Sep 2002 16:33:04 -0000 @@ -517,11 +517,19 @@ my %content_seen; # This holds the names which are targets. These also appear in -# %contents. +# %contents. $targets{TARGET}{COND} is the location of the definition +# of TARGET for condition COND. my %targets; -# Same as %VAR_VALUE, but for targets. -my %target_conditional; +# $target_source{TARGET}{COND} is the filename where TARGET +# were defined for condition COND. Note this must be a +# filename, *without* any line number. +my %target_source; + +# $target_owner{TARGET}{COND} the owner of TARGET in condition COND. +my %target_owner; +use constant TARGET_AUTOMAKE => 0; # Target defined by Automake. +use constant TARGET_USER => 1; # Target defined in the user's Makefile.am. # This is the conditional stack. my @cond_stack; @@ -721,8 +729,8 @@ %content_seen = (); %targets = (); - - %target_conditional = (); + %target_source = (); + %target_owner = (); @cond_stack = (); @@ -1186,6 +1194,14 @@ msg_target ('error', @_); } +# err_cond_target ($COND, $TARGETNAME, $MESSAGE, [%OPTIONS]) +# ---------------------------------------------------------- +# Uncategorized errors about conditional targets. +sub err_cond_target ($$$;%) +{ + msg_cond_target ('error', @_); +} + # err_am ($MESSAGE, [%OPTIONS]) # ----------------------------- # Uncategorized errors about the current Makefile.am. @@ -1211,13 +1227,24 @@ msg $channel, $var_location{$macro}, $msg, %opts; } +# msg_cond_target ($CHANNEL, $COND, $TARGETNAME, $MESSAGE, [%OPTIONS]) +# -------------------------------------------------------------------- +# Messages about conditional targets. +sub msg_cond_target ($$$$;%) +{ + my ($channel, $cond, $target, $msg, %opts) = @_; + msg $channel, $targets{$target}{$cond}, $msg, %opts; +} + # msg_target ($CHANNEL, $TARGETNAME, $MESSAGE, [%OPTIONS]) # -------------------------------------------------------- # Messages about targets. sub msg_target ($$$;%) { my ($channel, $target, $msg, %opts) = @_; - msg $channel, $targets{$target}, $msg, %opts; + # Don't know which condition is concerned. Pick any. + my $cond = (keys %{$targets{$target}})[0]; + msg_cond_target ($channel, $cond, $target, $msg, %opts); } # msg_am ($CHANNEL, $MESSAGE, [%OPTIONS]) @@ -2913,21 +2940,22 @@ } } - if ($xname ne '') + if ($xname ne '') { - if (conditional_ambiguous_p ($xname . '_DEPENDENCIES', $cond) ne '') + my $depvar = $xname . '_DEPENDENCIES'; + if ((conditional_ambiguous_p ($depvar, $cond, + keys %{$var_value{$depvar}}))[0] ne '') { - # Note that we've examined this. - &examine_variable ($xname . '_DEPENDENCIES'); + # Note that we've examined this. + &examine_variable ($depvar); } - else + else { - define_pretty_variable ($xname . '_DEPENDENCIES', $cond, - @dep_list); + define_pretty_variable ($depvar, $cond, @dep_list); } } - return $seen_libobjs; + return $seen_libobjs; } # Canonicalize the input parameter @@ -6034,51 +6062,54 @@ sub check_ambiguous_conditional ($$) { my ($var, $cond) = @_; - my $message = conditional_ambiguous_p ($var, $cond); + my ($message, $ambig_cond) = + conditional_ambiguous_p ($var, $cond, keys %{$var_value{$var}}); err_var $var, "$message\n" . macro_dump ($var) if $message; } -# $STRING -# conditional_ambiguous_p ($VAR, $COND) -# ------------------------------------- -# Check for an ambiguous conditional. Return an error message if we -# have one, the empty string otherwise. -sub conditional_ambiguous_p ($$) +# $STRING, $AMBIG_COND +# conditional_ambiguous_p ($WHAT, $COND, @CONDS) +# ---------------------------------------------- +# Check for an ambiguous conditional. Return an error message and +# the other condition involved if we have one, two empty strings otherwise. +# WHAT: the thing being defined +# COND: the condition under which is is being defined +# CONDS: the conditons under which is had already been defined +sub conditional_ambiguous_p ($$@) { - my ($var, $cond) = @_; - foreach my $vcond (keys %{$var_value{$var}}) + my ($var, $cond, @conds) = @_; + foreach my $vcond (@conds) { - #"; - } - elsif (&conditional_true_when ($vcond, $cond)) - { - return ("$var was already defined in condition $vcond, " - . "which implies condition $cond"); - } - elsif (&conditional_true_when ($cond, $vcond)) - { - return ("$var was already defined in condition $vcond, " - . "which is implied by condition $cond"); - } - } - - return ''; + #", $vcond); + } + elsif (&conditional_true_when ($vcond, $cond)) + { + return ("$var was already defined in condition $vcond, " + . "which implies condition $cond", $vcond); + } + elsif (&conditional_true_when ($cond, $vcond)) + { + return ("$var was already defined in condition $vcond, " + . "which is implied by condition $cond", $vcond); + } + } + return ('', ''); } # @MISSING_CONDS @@ -6458,21 +6489,47 @@ { my ($var, $cond) = @_; - # Unfortunately we can't just check for $var_value{VAR}{COND} - # as this would make perl create $condition{VAR}, which we - # don't want. - if (!exists $var_value{$var}) + if (! exists $var_value{$var} + && (! defined $cond || ! exists $var_value{$var}{$cond})) { - err_target $var, "`$var' is a target; expected a variable" - if defined $targets{$var}; - # The variable is not defined + # VAR is not defined. + + # Check there is no target defined with the name of the + # variable we check. + + # adl> I'm wondering if this error still makes any sense today. I + # adl> guess it was because targets and variables used to share + # adl> the same namespace in older versions of Automake? + # tom> While what you say is definitely part of it, I think it + # tom> might also have been due to someone making a "spelling error" + # tom> -- writing "foo:..." instead of "foo = ...". + # tom> I'm not sure whether it is really worth diagnosing + # tom> this sort of problem. In the old days I used to add warnings + # tom> and errors like this pretty randomly, based on bug reports I + # tom> got. But there's a plausible argument that I was trying + # tom> too hard to prevent people from making mistakes. + if (exists $targets{$var} + && (! defined $cond || exists $targets{$var}{$cond})) + { + for my $tcond ($cond || keys %{$targets{$var}}) + { + prog_error ("\$targets{$var}{$tcond} exists but " + . "\$target_owner doesn't") + unless exists $target_owner{$var}{$tcond}; + # Diagnose the first user target encountered, if any. + # Restricting this test to user targets allows Automake + # to create rules for things like `bin_PROGRAMS = LDADD'. + if ($target_owner{$var}{$tcond} == TARGET_USER) + { + err_cond_target ($tcond, $var, "`$var' is a target; " + . "expected a variable"); + return 0; + } + } + } return 0; } - # The variable is not defined for the given condition. - return 0 - if $cond && !exists $var_value{$var}{$cond}; - # Even a var_value examination is good enough for us. FIXME: # really should maintain examined status on a per-condition basis. $content_seen{$var} = 1; @@ -7287,22 +7344,27 @@ } } -# $BOOL -# rule_define ($TARGET, $IS_AM, $COND, $WHERE) -# -------------------------------------------- -# Define a new rule. $TARGET is the rule name. $IS_AM is a boolean -# which is true if the new rule is defined by the user. $COND is the -# condition under which the rule is defined. $WHERE is where the rule -# is defined (file name or line number). Returns true if it is ok to -# define the rule, false otherwise. -sub rule_define ($$$$) +# @CONDS +# rule_define ($TARGET, $SOURCE, $OWNER, $COND, $WHERE) +# ----------------------------------------------------- +# Define a new rule. $TARGET is the rule name. $SOURCE +# si the filename the rule comes from. $OWNER is the +# owener of the rule (TARGET_AUTOMAKE or TARGET_USER). +# $COND is the condition string under which the rule is defined. +# $WHERE is where the rule is defined (file name and/or line number). +# Returns a (possibly empty) list of conditions where the rule +# should be defined. +sub rule_define ($$$$$) { - my ($target, $rule_is_am, $cond, $where) = @_; + my ($target, $source, $owner, $cond, $where) = @_; + + # Don't even think about defining a rule in condition FALSE. + return () if $cond eq 'FALSE'; # For now `foo:' will override `foo$(EXEEXT):'. This is temporary, # though, so we emit a warning. (my $noexe = $target) =~ s,\$\(EXEEXT\)$,,; - if ($noexe ne $target && defined $targets{$noexe}) + if ($noexe ne $target && exists $targets{$noexe}{$cond}) { # The no-exeext option enables this feature. if (! defined $options{'no-exeext'}) @@ -7312,29 +7374,141 @@ . "change your target to read `$noexe\$(EXEEXT)'"); } # Don't define. - return 0; + return (); } - reject_target ($target, - "$target defined both conditionally and unconditionally") - if ($cond - ? ! exists $target_conditional{$target} - : exists $target_conditional{$target}); + $target = $noexe; + + # Diagnose target redefinitions. + if (exists $target_source{$target}{$cond}) + { + # Sanity checks. + prog_error ("\$target_source{$target}{$cond} exists, but \$target_owner" + . " doesn't.") + unless exists $target_owner{$target}{$cond}; + prog_error ("\$target_source{$target}{$cond} exists, but \$targets" + . " doesn't.") + unless exists $targets{$target}{$cond}; + + my $oldowner = $target_owner{$target}{$cond}; + + # Don't mention true conditions in diagnostics. + my $condmsg = $cond ne 'TRUE' ? " in condition `$cond'" : ''; + + if ($owner == TARGET_USER) + { + if ($oldowner eq TARGET_USER) + { + err ($where, "redefinition of `$target'$condmsg..."); + err_cond_target ($cond, $target, + "... `$target' previously defined here."); + return (); + } + else + { + # Since we parse the user Makefile.am before reading + # the Automake fragments, this condition should never happen. + prog_error ("user target `$target' seen after Automake's " + . "definition\nfrom `$targets{$target}$condmsg'"); + } + } + else # $owner == TARGET_AUTOMAKE + { + if ($oldowner == TARGET_USER) + { + # Don't overwrite the user definition of TARGET. + return (); + } + else # $oldowner == TARGET_AUTOMAKE + { + # Automake should ignore redefinitions of its own + # rules if they came from the same file. This makes + # it easier to process a Makefile fragment several times. + # Hower it's an error if the target is defined in many + # files. E.g., the user might be using bin_PROGRAMS = ctags + # which clashes with our `ctags' rule. + # (It would be more accurate if we had a way to compare + # the *content* of both rules. Then $targets_source would + # be useless.) + my $oldsource = $target_source{$target}{$cond}; + return () if $source eq $oldsource; + + err ($where, "redefinition of `$target'$condmsg..."); + err_cond_target ($cond, $target, + "... `$target' previously defined here."); + return (); + } + } + # Never reached. + prog_error ("Unreachable place reached."); + } # A GNU make-style pattern rule has a single "%" in the target name. msg ('portability', $where, "`%'-style pattern rules are a GNU make extension") if $target =~ /^[^%]*%[^%]*$/; - # Value here doesn't matter; for targets we only note existence. - $targets{$target} = $where; - if ($cond) - { - if ($target_conditional{$target}) + # Conditions for which the rule should be defined. + my @conds = $cond; + + # Check ambiguous conditional definitions. + my ($message, $ambig_cond) = + conditional_ambiguous_p ($target, $cond, keys %{$targets{$target}}); + if ($message) # We have an ambiguty. + { + if ($owner == TARGET_USER) + { + # For user rules, just diagnose the ambiguity. + err $where, "$message ..."; + err_cond_target ($ambig_cond, $target, + "... `$target' previously defined here."); + return (); + } + else { - &check_ambiguous_conditional ($target, $cond); + # FIXME: for Automake rules, we can't diagnose ambiguities yet. + # The point is that Automake doesn't propagate conditionals + # everywhere. For instance &handle_PROGRAMS doesn't care if + # bin_PROGRAMS was defined conditionally or not. + # On the following input + # if COND1 + # foo: + # ... + # else + # bin_PROGRAMS = foo + # endif + # &handle_PROGRAMS will attempt to define a `foo:' rule + # in condition TRUE (which conflicts with COND1). Fixing + # this in &handle_PROGRAMS and siblings seems hard: you'd + # have to explain &file_contents what to do with a + # conditional. So for now we do our best *here*. If `foo:' + # was already defined in condition COND1 and we want to define + # it in condition TRUE, then define it only in condition !COND1. + # (See cond14.test and cond15.test for some test cases.) + my @defined_conds = keys %{$targets{$target}}; + @conds = (); + for my $undefined_cond (invert_conditions(@defined_conds)) + { + push @conds, make_condition ($cond, $undefined_cond); + } + # No conditions left to define the rule. + # Warn, because our workaround is meaningless in this case. + if (scalar @conds == 0) + { + err $where, "$message ..."; + err_cond_target ($ambig_cond, $target, + "... `$target' previously defined here."); + return (); + } } - $target_conditional{$target}{$cond} = $where; + } + + # Finally define this rule. + for my $c (@conds) + { + $targets{$target}{$c} = $where; + $target_source{$target}{$c} = $source; + $target_owner{$target}{$c} = $owner; } # Check the rule for being a suffix rule. If so, store in a hash. @@ -7350,7 +7524,10 @@ register_suffix_rule ($where, $1, $2); } - return 1; + # Return "" instead of TRUE so it can be used with make_paragraphs + # directly. + return "" if 1 == @conds && $conds[0] eq 'TRUE'; + return @conds; } @@ -7358,7 +7535,7 @@ sub target_defined { my ($target) = @_; - return defined $targets{$target}; + return exists $targets{$target}; } @@ -7538,7 +7715,11 @@ # Found a rule. $prev_state = IN_RULE_DEF; - rule_define ($1, 0, $cond, $here); + # For TARGET_USER rules, rule_define won't reject a rule + # without diagnosic an error. So we go on and ignore the + # return value. + rule_define ($1, $amfile, TARGET_USER, $cond || 'TRUE', $here); + check_variable_expansions ($_, $here); $output_trailer .= $comment . $spacing; @@ -7896,7 +8077,7 @@ foreach (split (' ' , $targets)) { - # FIXME: We are not robust to people defining several targets + # FIXME: 1. We are not robust to people defining several targets # at once, only some of them being in %dependencies. The # actions from the targets in %dependencies are usually generated # from the content of %actions, but if some targets in $targets @@ -7904,13 +8085,16 @@ # a rule for all $targets (i.e. the targets which are both # in %dependencies and $targets will have two rules). - # FIXME: The logic here is not able to output a + # FIXME: 2. The logic here is not able to output a # multi-paragraph rule several time (e.g. for each conditional # it is defined for) because it only knows the first paragraph. + # FIXME: 3. We are not robust to people defining a subset + # of a previously defined "multiple-target" rule. E.g. + # `foo:' after `foo bar:'. + # Output only if not in FALSE. - if (defined $dependencies{$_} - && $cond ne 'FALSE') + if (defined $dependencies{$_} && $cond ne 'FALSE') { &depend ($_, @deps); $actions{$_} .= $actions; @@ -7919,55 +8103,22 @@ { # Free-lance dependency. Output the rule for all the # targets instead of one by one. - - # Work out all the conditions for which the target hasn't - # been defined - my @undefined_conds; - if (defined $target_conditional{$targets}) + my @undefined_conds = + rule_define ($targets, $file, + $is_am ? TARGET_AUTOMAKE : TARGET_USER, + $cond || 'TRUE', $file); + for my $undefined_cond (@undefined_conds) { - my @defined_conds = keys %{$target_conditional{$targets}}; - @undefined_conds = invert_conditions(@defined_conds); + my $condparagraph = $paragraph; + $condparagraph =~ s/^/$undefined_cond/gm; + $result_rules .= "$spacing$comment$condparagraph\n"; } - else - { - if (defined $targets{$targets}) - { - # No conditions for which target hasn't been defined - @undefined_conds = (); - } - else - { - # Target hasn't been defined for any conditions - @undefined_conds = (""); - } - } - - if ($cond ne 'FALSE') + if (scalar @undefined_conds == 0) { - for my $undefined_cond (@undefined_conds) - { - my $condparagraph = $paragraph; - $condparagraph =~ s/^/make_condition (@cond_stack, $undefined_cond)/gme; - if (rule_define ($targets, $is_am, - "$cond $undefined_cond", $file)) - { - $result_rules .= - "$spacing$comment$condparagraph\n" - } - else - { - # Remember to discard next paragraphs - # if they belong to this rule. - $discard_rule = 1; - } - } - if ($#undefined_conds == -1) - { - # This target has already been defined, the rule - # has not been defined. Remember to discard next - # paragraphs if they belong to this rule. - $discard_rule = 1; - } + # Remember to discard next paragraphs + # if they belong to this rule. + # (but see also FIXME: #2 above.) + $discard_rule = 1; } $comment = $spacing = ''; last; Index: tests/Makefile.am =================================================================== RCS file: /cvs/automake/automake/tests/Makefile.am,v retrieving revision 1.435 diff -u -r1.435 Makefile.am --- tests/Makefile.am 10 Sep 2002 09:50:23 -0000 1.435 +++ tests/Makefile.am 13 Sep 2002 16:33:05 -0000 @@ -1,6 +1,7 @@ ## Process this file with automake to create Makefile.in -XFAIL_TESTS = subdir5.test auxdir2.test cond17.test +XFAIL_TESTS = subdir5.test auxdir2.test cond17.test \ + specflags7.test specflags8.test TESTS = \ acinclude.test \ Index: tests/Makefile.in =================================================================== RCS file: /cvs/automake/automake/tests/Makefile.in,v retrieving revision 1.560 diff -u -r1.560 Makefile.in --- tests/Makefile.in 10 Sep 2002 09:50:23 -0000 1.560 +++ tests/Makefile.in 13 Sep 2002 16:33:06 -0000 @@ -91,7 +91,9 @@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ -XFAIL_TESTS = subdir5.test auxdir2.test cond17.test +XFAIL_TESTS = subdir5.test auxdir2.test cond17.test \ + specflags7.test specflags8.test + TESTS = \ acinclude.test \ @@ -521,7 +523,7 @@ mkinstalldirs = $(SHELL) $(top_srcdir)/lib/mkinstalldirs CONFIG_CLEAN_FILES = defs DIST_SOURCES = -DIST_COMMON = Makefile.am Makefile.in defs.in +DIST_COMMON = Makefile.am Makefile.in configure.in defs.in all: all-am .SUFFIXES: -- Alexandre Duret-Lutz | http://lists.gnu.org/archive/html/automake-patches/2002-09/msg00024.html | CC-MAIN-2013-20 | refinedweb | 2,493 | 51.44 |
Hello!
I am using an M5stack (esp32) with 520kb RAM. I have successfully ported lvgl and I am able to render things like buttons etc.
Now I am trying to render an image (a logo when the device boots for the first time) but I am not able to do it, every time ( no matter the image size) I end up with MemoryError: memory allocation failed and it doesn’t seem to be connected with the image size. I already tried images with 100kb and with 2kb.
Right now I am following the example in
My code is:
import ustruct as struct import lodepng as png import lvgl as lv import lvesp32 lv.init() lv.log_register_print_cb(lambda level,path,line,msg: print('%s(%d): %s' % (path, line, msg))) from ili9341 import ili9341 from imagetools import get_png_info, open_png disp = ili9341() # Register PNG image decoder decoder = lv.img.decoder_create() decoder.info_cb = get_png_info decoder.open_cb = open_png # Create a screen with a draggable image with open('logo320240.png','rb') as f: png_data = f.read() png_img_dsc = lv.img_dsc_t({ 'data_size': len(png_data), 'data': png_data }) scr = lv.scr_act() # Create an image on the left using the decoder # lv.img.cache_set_size(2) img1 = lv.img(scr) img1.align(scr, lv.ALIGN.IN_TOP_LEFT, 0, 0) img1.set_src(png_img_dsc)
I am quiet new to this and I am finding a bit difficult to find info about lvgl micropython usage, so let me know if I have done something wrong.
PS: Running gc.mem_free() before running anything else gives me ± 90000 bytes available. | https://forum.lvgl.io/t/memory-error-png-image/1639 | CC-MAIN-2020-24 | refinedweb | 252 | 66.84 |
2016 Round 1A
The Last Word
We must place the last occurrence of the largest letter in front, and all following letters on the back. Recursively applying this principle leads to the solution:
import Data.List import Jam main = jam $ f <$> gets f "" = "" f xs = (a:f (reverse as)) ++ reverse bs where (bs, a:as) = span (< maximum xs) $ reverse xs
The awkward reverse calls could be eliminated if spanEnd existed, though we would then call init and last instead of decomposing a list into its head and tail. By spanEnd we mean a function that is to span as dropWhileEnd is to dropWhile.
The first time I tried this problem I split the list at the first maximum instead of the last. Luckily the small input exposed my mistake, so I had a chance to redeem myself.
Rank and File
If we had all the papers, then each height appears twice: once for its row, and once for its column. Thus each number should appear an even number of times.
The missing numbers are distinct, so we can just look for the numbers that appear an odd number of times and sort them.
import Data.List import Jam main = jam $ do [n] <- getints ns <- concat <$> getintsn (2*n - 1) pure $ unwords $ map (show . head) $ filter (odd . length) $ group $ sort ns
BFFs
Data.List makes brute force a breeze:
import Data.List import Jam smallMain = jam $ do [n] <- getints ns <- getints pure $ show $ maximum $ map length $ filter (f ns) $ concatMap permutations $ subsequences [1..n] f _ [] = False f _ [x] = True f ns xs = and $ zipWith (||) (zipWith bff xs ys) (zipWith bff xs zs) where bff x y = ns!!(x - 1) == y ys = tail xs ++ [head xs] zs = last xs:init xs
The smarter approach is finicky to describe, so we’ll skim over details. We’ll use graph theory terminology. Let each node represent a kid, and draw a directed edge from A to B if A’s BFF is B.
Since no kid is their own BFF, the circle contains a cycle of length 2 or more.
We find if the circle contains a cycle of length 3 or greater, then the circle must consist of only that cycle.
Otherwise, all cycles in the circle have length 2, and not only can the circle contain an arbitrary number of 2-cycles, but it can also contain all nodes along a path to a node in a 2-cycle.
Thus the biggest circle is either the longest cycle of length 3 or more, or all the cycles of length 2 plus the nodes in the longest paths reaching these nodes, whichever is biggest.
import Data.List import Data.Map ((!)) import qualified Data.Map as M import Jam main = jam $ do [n] <- getints ns <- getints let m = M.fromList $ zip [1..] ns rm = M.fromListWith (++) $ zip ns (map pure [1..]) ++ zip [1..n] (repeat []) f a = long [a] where long [] = 0 long xs = 1 + maximum [long $ (rm!x) \\ [a, m!a] | x <- xs] -- Inefficient, but good enough. maxCycle = maximum $ cyc . pure <$> [1..n] cyc xs@(x:_) | y `notElem` xs = cyc (y:xs) | y == last xs = length xs | otherwise = 0 where y = m!x pure $ show $ max maxCycle $ sum $ f <$> [x | x <- [1..n], m!(m!x) == x]
Above, m is a Data.Map that stores the edges, and rm is its inverse, so we can quickly follow the BFF relationships in either direction. Over all nodes in a 2-cycle, we sum a function that measures the longest path to that node, excluding nodes in its 2-cycle.
Unfortunately, I was so excited when I successfully characterized the largest circle that I stupidly downloaded the large input before optimizing my code enough to handle it. It’s trivial to generate a large test case to verify the program is sufficiently fast. | http://crypto.stanford.edu/~blynn/haskell/2016-1a.html | CC-MAIN-2018-09 | refinedweb | 641 | 81.12 |
One class controller instead of multiple command
My question is simple: Is it possible to combine in one class-controller instead of multiple command?
Let me explain
I have the general application (tens of services, loadable modules and other). And I have the hundreds of commands. And I need to accumulate these commands on several classes (divided by the business logic).
For example:
In my Context I describe my Class-Controller:
injector.mapSingleton( WebServiceController,'WebServiceController' );
After that I start the my first View/Mediator (loading page) and in the Mediator I initialize my controller:
[Inject (name='WebServiceController')] public var wC : WebServiceController;
override public function onRegister() : void {
// init authorization service and start initialization activity in system wC.Init(); ...
In Controller->Init() :
public function Init() : void {
eventDispatcher.addEventListener(
UIStateEvents.AUTHORIZATION_INIT_OK,
AuthorizatonInitOkHandler
); }
What can I get in this variant?
1) I accumulate all my command for web service in one place
2) I don’t need to write for every command : create new command class, don’t forget to map this command in context...
3) I have simple navigation in my source code : list of controllers without commands-commands-commands files
General activity: split the business logic in list of controllers, describe commands as functions in these classes and map to listener list of events.
Could you please criticize this variant and point out possible problems?
Comments are currently closed for this discussion. You can start a new one.
Keyboard shortcuts
Generic
Comment Form
You can use
Command ⌘ instead of
Control ^ on Mac
1 Posted by Stray on 18 May, 2011 07:35 PM
Hi Oleg,
the Commands vs Controllers debate is a long running one.
Personally I love the Command pattern - I find it to be easier to test, easier to refactor and easier to find what I need at a later date.
The weak points of the Command pattern are:
1) Logic is distributed, this means that if your Commands aren't very well named then it can be hard to find what you are looking for.
2) You can end up with repeated-code in some Commands.
I think 1) is solved by naming Commands well and 2) is solved using composition and helper classes in your Comands (even a class that just does one logic step can be useful as far as I am concerned).
But - in addition, I'd just suggest reading up on Controllers vs Commands. Google it. The debates rage :)
A simple way to achieve the Controller approach in Robotlegs is to use an Actor as a 'Controller Mediator'. This Actor (which would be created as a Singleton using the injector) would listen for events on the eventMap and then call functions on the Controller. Personally I don't like Controllers, so I wouldn't use this approach, but it certainly works.
But you should really consider helper classes for your commands first...
Stray
Support Staff 2 Posted by Till Schneidere... on 18 May, 2011 07:37 PM
I tend to see the list of command classes as a great way to get a
quick overview of a module's functionality. The list, if done
properly, contains all "gestures" the module can perform. "Module",
though, can be as fine-grained as you like: It can be the entire
application, a (Flex-)module, or specific area of functionality in an
application as in your webservice example. In fact, I'd recommend
using packages to organize your source in much the same way as you
propose using fat controller classes.
That being said, your approach has a couple of down-sides:
- Instead of simply informing the application about something that
happened in the view without caring about how, or even if, the
application is going to react to it, it tells the controller what to
do. That causes a lot of coupling you don't get when using the
CommandMap
- The controller being a singleton means that you can never have
multiple "commands" running side-by-side. That only gets problematic
when using asynchronous commands, of course, so it might not be a
problem for you at all
Here's how I go about organizing an application's wiring:
- implement each area of functionality in its own sub-package
- in each of these sub-packages, have a command that contains
instructions for how to configure and wire that area: Mapping commands
and mediators, setting up models and services, etc.
- when your application uses the functionality, include this setup
command in your startup sequence
There's been lots of discussion about the "right" structure in the
support forum. One good such discussion is:
but I recommend searching through the discussions and seeing if
there's something you like.
On another note, is there a specific reason why you've named your
singleton mapping? It looks to me like you're simply repeating the
class name. Named injections are only ever required if you want to
inject multiple unique values of one type. For example, people use
them to map different strings for configuration purposes. If that's
not what you're doing, just get rid of the second parameter in your
mapping and the "name" parameter in your [Inject] tag.
3 Posted by Oleg Borisov on 18 May, 2011 08:19 PM
Thanks all...
Stray,
I need to understand, should I use my idea (class-controller + mapping commands as functions in this controller) in Robotlegs environment and what potential problem will I have...
My opinion, I don't broke the general idea of Robotleg. I create the up-domain for group of commands and restructure my code over small part of big-controllers.
And I need to select the correct/flexible/supportable variant for the future. Now I have to create new command - generate new file + additional code (inject of event class, inject of target model/service, rewrite execute function)...
If I use the one controller for group of activity, I can create the list of functions + map this functions to events. It's all...
For example:
public class AuthorizationInitOkCommand extends Command {
and for another authorization command, and another...
And I can change it: one controller class, and 10-20-... functions.
I think, I don't corrupt the general idea of framework + I will use all possibilities, include general event mechanism and other...
4 Posted by Stray on 18 May, 2011 08:28 PM
Writing code is less than 10% of your effort.
If you think making a Command is 'work' then you need a better IDE, not a different architecture :)
5 Posted by Oleg Borisov on 18 May, 2011 08:34 PM
tschneidereit,
About "named singleton". I should use it for resolve the potential 'cicle' problem.
For example, I have 2 classes:
injector.mapSingleton( Class1);
injector.mapSingleton( Class2);
And I use in the Class1 injection to Class2, and in Class2 I can have the Injection to Class1. If I use no-name specification, I have the following collision:
Robot calls the Class1 initialization, has found the injection to Class2, try to create it, found the injection to Class1, ... and I have the recursion error.
About modules/commands and my general question.
Me inconvenient to keep a large number of files, classes, each of which can carry a tiny operation. At the same time - I need to describe it and generate a large piece of code to create this class, describe the links to the common commands for this group of models and services, etc.
I realize this is more convenient in the form of Controller-class, which collect a piece of business logic in one place.
And I try to understand - is it correct in range of Robotlegs or not.
My mediators send events, mapped Controller gets this information and executes the functions-commands and manipulates to models and services. If you see the class diagramm, I will create the block of controller (top of image) as one class, not folder/subfolder + many separated files...
6 Posted by Oleg Borisov on 18 May, 2011 08:49 PM
Stray,
Sure, coding is not general problem. My general problem is to understand - can I accumulate group of commands as one singleton-controller or not, and what problems in the future I will have, if I use this variant of event-command activity.
7 Posted by Stray on 18 May, 2011 08:57 PM
Hi Oleg, technically you won't have problems, but many of us who have used controllers in the past find Commands to be a better way of doing things.
As I said already - you can read in many many places about the Controllers vs Commands arguments. For example, this thread from Flex Coders:
Stray
8 Posted by Oleg Borisov on 18 May, 2011 09:06 PM
Hi Stray,
Thanks,
I created this topic for one point: understand the general question... Can I accumulate part of command in controller + map command as function, or Robotleg framework doesn't support / recommend it in the general practice.
Ok, I try to create mixed activity: some code include in my Controllers, and some code use in the 'pure' commands interface. And will have the final decision after real work and support the big project...
Thanks, mate.
9 Posted by Oleg Borisov on 18 May, 2011 09:12 PM
Stray, small question after all.
If I have the 100 commands and map all commands in the Content.
What is the optimum variant to organize this list of mapping? Map all commands in one base content for all project, or create some contents, etc?
10 Posted by Stray on 18 May, 2011 09:16 PM
Search for "Bootstrap" in the existing list of questions - that'll help you out :)
I'm off to bed here - but I think that'll explain how others do it.
Stray
11 Posted by Oleg Borisov on 18 May, 2011 09:43 PM
Thank you very much, go to study :)
Stray closed this discussion on 25 May, 2011 08:27 AM. | http://robotlegs.tenderapp.com/discussions/suggestions/57-one-class-controller-instead-of-multiple-command | CC-MAIN-2020-29 | refinedweb | 1,653 | 59.13 |
This document lists the document formats that will be used by the Java Persistence API XML descriptors. The Java Persistence API requires that its XML descriptors be validated with respect to the XML Schema listed by this document.
Starting with the 2.1 version,
the Java Persistence API Schemas share the namespace,.
Previous versions used the namespace. Each schema
document contains a version attribute that contains the version of the
Java Persistence specification. This pertains to the specific version
of the specification as well as the schema document itself. 2.1.
This table contains the XML Schema components for Java Persistence 2.0.
This table contains the XML Schema components for Java Persistence 1.0. | http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/persistence/index.html | CC-MAIN-2017-22 | refinedweb | 115 | 58.99 |
How to write a utility program that lists all contents of directory irrespective of Operating System.
Most of the C/C++ compilers, define macros which can be used to detect operating system. For example, in GCC, following are common macros.
_WIN32 : Defined for both 32 bit and 64 bit windows OS. _WIN64 : Defined for 64 bit windows OS. unix, __unix, __unix__ : Defined in UNIX OS __APPLE__, __MACH__ : Defined in Mac OS Source : StackOverflow
In Windows, we us dir call to list all directories and in most of the other Operating Systems “ls” is used. Below is simple C++ implementation to list directories of folder irrespective of OS.
// C++ program to list all directories. #include <bits/stdc++.h> using namespace std; int main() { #ifdef _WIN32 system("dir"); #else system("ls"); #endif return 0; }
The above OS independent code is totally different from Java’s platform independence. In Java, there is intermediate byte code that is very clean way of handling platform dependencies. Here we have to remember compiler specific macros and write code in using clumsy #ifdef and #else, and the most important, we need to recompile the code for every OS.
This article is contrubuted by Shubham Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Recommended Posts:
- Database Connectivity using C/C++
- C++ bitset and its application
- Writing C/C++ code efficiently in Competitive programming
- std::fill() and fill_n() in C++ STL
- nextafter() and nexttoward(). | https://www.geeksforgeeks.org/writing-os-independent-code-cc/ | CC-MAIN-2018-13 | refinedweb | 248 | 52.8 |
Here is a compilation of basic interview questions for python programmers:
1. What is Python?
Fundamentally focused on code readability and usage of whitespace, Python can be described as an interpreted, high-level, and general-purpose programming language. The language is simple and comes with easy to learn syntax and readability, thus, making it easier to maintain in terms of costs. The language enables code reuse, program modularity, and supports modules and packages. It is an easy language for beginners level programmers, too.
2. How do lists and tuples differ in Python?
Lists are the mutable components of Python, which means that programmers can edit them. But tuples are the components that are immutable or can be considered as lists that can not be edited. While lists are slower in Python, tuples are faster.
Here is an example of List and tuples syntax:
Syntax: list_1 = [10, ‘Chelsea’, 20] Syntax: tup_1 = (10, ‘Chelsea’ , 20)
3. List down a few key features of Python
- By Python being an interpreted language, it means that Python need not be compiled before running it, unlike some other language like C, C++, etc.
- The language is dynamically typed. Hence, programmers do not need to state the types of variables upon declaration, and the code will be executed without error.
- Although Python code writing is quite a fast task, running it can take a lot of time. Hence, Python allows for the inclusion of C based extensions for easy execution of bottlenecks.
- The language is optimal for object-oriented programming and enables the definition of classes, composition, and inheritance. But Python does not come with access specifiers such as public and private, unlike C++.
- Functions are termed as the first-class objects in Python. Hence, they can be easily returned from and passed into other functions and assigned to other variables. Classes are also listed under first-class objects in Python.
4. Is Python a programming or scripting language?
Though Python is actually a scripting language, commonly, it is considered as a general-purpose language.
5. What is PYTHONPATH?
PYTHONPATH is an environmental variable. The variable is used when a module is imported. Also, upon the importing of a module, the PYTHONPATH variable is deployed for checking other imported modules in the various directories. Hence, it becomes easy for the interpreter to see and interpret the module that needs to be loaded.
6. What are Python modules and list down a few commonly used built-in modules in Python?
Files containing Python code are known as Python modules. The code can be anything from functions, classes to variables. The Python module can be seen as a .py file with executable code.
A few commonly used built-in modules in Python are as below:
- os
- sys
- math
- random
- data time
- JSON
7. What are core default modules and list down a few of the core default modules available in Python?
These codes are written in C and are part of the core. They are integrated with the Python interpreter. The built-in modules contain resources for system-specific functions.
- email: the module is used to parse, handle, and generate email messages.
- string: the module is used to contain functions that help to process standard Python strings.
- XML: the module is used to enable XML support.
- sqlite3: the module is used to employ the work of SQLite database.
- traceback: the module is used to enable extraction and print of stack trace details.
- logging: it is used to allow the support for log classes and methods.
8. How long can an identifier be in Python?
An identifier can be of any length according to the Python documentation. But as the readability of the code is a major factor of consideration in Python as per PEP 20 and PEP 8, too, limits the identifiers to be 79 characters per line. Though a longer code can be allowed, it will result in the violation of PEP 20 and PEP 8.
It is important to remember that Python is case sensitive, and the same goes for identifiers. The identifier can only begin with A-Z or a-z, while the rest can contain any letters or numbers. Also, keywords can not be used as identifiers.
9. What are local and global variables in Python?
In Python, the variables declared outside a function or in global space are called the global variables. You can access these variables from any function in the program.
On the other hand, variables declared inside functions are known as local variables. It is because the variable is present in local space and not in global space. If an attempt is made to access a local variable outside the function, an error will be shown.
10. What are generators in Python?
The generators in Python are a way to implement iterators. A generator function is mostly like normal functions themselves. The only difference is that the generator function contains yield expression in the function.
11. Does Python require indentation?
Indentation is compulsory in Python and is used to specify a block of code. An indented block is used to determine all code within loops, classes, functions, etc. The indentation is usually done using four space characters.
12. What are the functions in Python?
A block of code that is executed only when called for is known as a function in Python. It is defined by a def keyword.
Example:
def Newfunc(): print("Hi, hello world") Newfunc(); #calling the function
13. What is Self in Python?
Self can be defined as an instance of an object of a class in Python and is included as the first language parameter.
In the init method, a Self variable points to a newly created object, while in other methods, it is used to refer to an object whose method is called.
14. How are comments written in Python?
To write a comment in a Python program, you need to begin with a # character. Comments can also be written by enclosing the strings in triple quotes known as docstrings.
Example:
#This is an example of a comment print("This is an example of a comment")
15. What is pickling and unpickling in Python?
A pickle module in Python pickling is used to convert a Python object into a string, which can then be dumped into a file using the dump function. The process is known as pickling.
Unpickling refers to the vice versa of this process. The retrieval of an original Python object from a string is called unpickling. | https://pdf.co/blog/interview-questions-for-python-programmers-beginners | CC-MAIN-2021-17 | refinedweb | 1,084 | 66.54 |
Microsoft Office Tutorials and References
In Depth Information
Chapter 7: Importing Data into Excel
Importing Data
into Excel
A vast amount of data exists in the world,
and most of it resides in some kind of
non-workbook format. Some data exists
in simple text files, perhaps as comma-
separated lists of items. Other data resides
in tables, either in Word documents or,
more likely, in Access databases. There is
also an increasing amount of data that
resides in Web pages and in XML files.
Depending on your needs and on the type
of data, you can either import the data
directly into a PivotTable report, or store
the data on a worksheet. In most cases,
Excel also enables you to refresh the data
so that you are always working with the
most up-to-date version of the data.
Excel can access a wide variety of external
data types. However, this chapter focuses
on the six most common types: data source
files, Access tables, Word tables, text files,
Web pages, and XML files.
By definition, all this data is not directly
available to you in Excel. However, Excel
offers a number of tools that enable you to
import external data into the program.
Search JabSto ::
Custom Search | http://jabsto.com/Tutorial/topic-6/Microsoft-Excel-2010-192.html | CC-MAIN-2018-09 | refinedweb | 208 | 52.6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.