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 |
|---|---|---|---|---|---|
You can subscribe to this list here.
Showing
2
results of 2
David,
Now you've really got me confused. Can you tell me what you're running on
your machine, so that I can try to replicate it? I need versions of
Windows, Apache, mod_python, Python, Spyce; the spyce install directory;
and the appropriate pieces of your httpd.conf file for starters. Let's try
that.
To figure out whether spyce is running via mod_python, have a look at
examples/info.spy. It will tell you. Alternatively, run a benchmark. CGI
can't do any better than 1-5 requests per second. Once the server is
warmed up, spyce via mod_python will do >50 and usually in the 100's,
depending on your machine and request complexity.
All the best,
Rimon.
On Fri, 13 Dec 2002, dave neel wrote:
>I've already tried putting the quotes around the sys.path thing but all
>that does is when i try to execute .spy scripts, my browser tries to
>download the file. Switching the quotes does that too. I have tried a lot
>of different variations, quoting, playing around with the slashes and the
>only way that I got Apache to properly restart was with the following
>modifications:
>
>I double slached the following line in the mod_python section of
>httpd.conf into:
>
><Directory "C://Program Files//Apache Group//Apache//htdocs//server">
>
>and I quoted and double slashed the PythonPath line like this:
>
>PythonPath "sys.path+[r'C:\\Program Files\\Python\\spyce']"
>
>now what happens is that mod_python files like mptest.py will no longer
>work but spyce files work. Now I could care less about the mod_python
>files as long as spyce is actually running on mod_python. I doubt that
>spyce really is running on mod_python but if it is, then that's all I
>want.
>Rimon,
>First of all, I would like to do some ego boosting. I think Python is
>one the most attractive languages I have seen. With Python you can write
>console programs and gui programs. The only type of programming left I
>do is html programming. I love PHP, but what makes Spyce better is it
>uses Python. Now all the programming I do can be in Python. I think the
>job you have done with Spyce is wonderful. Keep up the good work!
>
>With that said, I have some concerns, at the very least, I would like you
>to be aware of and at most a solution for. I asked you sometime ago
>about when Spyce has an error that it display what line had the problem
>in your web browser. You told me that you added it to the latest version
>of Spyce and you did. But the line number it displays does not match the
>line number in my .spy file. It is in the ballpark though, so it is
>useful.
I know about this problem... (I think!) Are you using multi-line strings?
Those offset the line numbers, by the number of 'extra' lines per string.
It's a problem that is caused by the transformation into Python. It's not
at the top of my list of issues, but I will eventually get to it. Are
there other cases? If you could narrow it down to the basic syntactic
construct that offsets numbers, with an error in it, that would help. i.e.
Can you send me a file with a the most basic version of the problem? The
only one that I currently know about is the 'multi-line strings' case. If
you'd like to work on it, search for the 'rimtodo' comment in the
spyceCompile.py file. That's the point that needs the work. Otherwise, I
will get to it eventually.
>Another concern I have is .py files. I import .py files that I wrote in
>my .spy files. This works great except when I make a change to my .py
>file, the .spy file does not see that change. The only way I have found
>to force the .spy file to see my change is to restart the apache web
>server. Is there a better way?
Yes... It's called debug mode. When you're running a production server,
you don't want the engine to check the timestamp of so many files. It's a
major slowdown, and so debug is off by default. But, you do want this for
when you are prototyping. Check out:
and look at the 'debug' option.
This will recompile the Spyce file on every hit, and reload all the Spyce
modules. I'm not sure about Python modules. Get back to me on that one if
it does not work. I think that I can fix that too. Python usually checks
the system cache for Python modules that are already loaded, for
performance. I'm thinking that we can run the entire file in a restricted
execution environment that intercepts imports and reloads the module if
necessary (or something like that). We'll see... Another really simple fix
is to run in plain CGI mode. You'll get a fresh copy of the engine on each
invocation! That might do the trick for you as well.
>One last concern is using MySQLdb. I'm not sure if this is a problem
>with Spyce or MySQLdb. When I lock a table using this import and Spyce
>gets an error before the database close, the table stays locked until I
>restart apache. It's like Spyce never cleaned up my MySQLdb object.
Tiberius reported a simlar problem. I'm not sure what this is, but it
seems to be related to Python garbage collection. I think we resolved it
back then, but I can't remember how. I don't think it was something
related to Spyce in the end, but I could be mistaken. It could be that the
MySQLdb object is not properly written. I'm not sure, as I have not used
it. I would, however, recommend that you trace the garbage collection
calls, and see what's going on. Try the following spyce file
[[\
class foo:
def __init__(self):
print 'created'
def __del__(self):
print 'destroyed'
x = foo()
print 'hello'
]]
The output should be:
created
hello
destroyed
This indicates that the garbage collection is working, at least in this
simple example. The destroyed gets printed when x goes out of scope at the
end of spyceProcess function. This decrements the ref-count on the foo
object, and it gets collected, since its ref-count is zero. If you are
creating a MySQLdb object, it should be cleaning up after itself.
Perhaps you can look at the MySQLdb implementation, and understand why the
state of the database is remaining locked. Again, this could be unrelated
to Spyce and really be a MySQLdb issue; that's what I am hoping. Could you
give me a pointer to the code you are using? Does anyone else have
experience using this library?
All the best,
Rimon. | http://sourceforge.net/p/spyce/mailman/spyce-users/?viewmonth=200212&viewday=14 | CC-MAIN-2014-15 | refinedweb | 1,165 | 84.17 |
:
set variable = [value]
Value is in brackets --
[] -- as it is optional. This syntax is specific to the C and tcsh shells.
If you wish to change your prompt, the name of the C or tcsh shell
variable is
prompt. You can set as many values as you want for the
prompt variable, as long as they are enclosed within quotation marks. The actual values differ slightly for the C shells and the tcsh shells; if you are using FreeBSD 4.0 or earlier, follow the instructions for the C
shell. If you are using FreeBSD 4.1, follow the instructions for the tcsh
shell.
Let's try a very simple prompt that works in both the C and tcsh
shells. Using your favorite text editor, open up the .cshrc file in your
test user's home directory. Add the following line at the very end of the
file, just before the
endif line.
set prompt = "${USER}% "
Save the file and log out. When you log back in as the test user, your prompt should show your user name, followed by a % followed by a space, and then your cursor. Let's pick apart the string of characters we assigned to the prompt shell variable.
First off, we enclosed the entire value in quotation marks. It is good practice to always do this; it is mandatory if you have any spaces anywhere in your string of characters.
The
${USER} is actually an environment variable. While shell variables are specific to a shell, environment variables are read by all programs (including shells). You can recognize variables as they always start with a
$ and are usually enclosed in curly braces --
{}. By convention, environment variables are named in upper case characters, while shell variables are in lower case. If you wish to see your other environment variables, type the following at your command prompt:
env
If you wish to see your shell variables, type:
set
The
${USER} environment variable contains your login name. We can tell the shell prompt variable to read this value when it sets your prompt.
Finally, we put a
% after the login name to remind ourselves we are still in the C shell. I like a space between the
% and the cursor, so I included one before the last quotation mark.
This prompt is useful as you will always be able to tell at a glance who you are logged in as at a virtual terminal.
I'm a very forgetful person and was forever using the
pwd command to figure out where I was in the directory structure. Fortunately, this information can be included in the prompt. To do this in the C shell, replace your
set prompt line with the following text:
alias cd 'chdir \!* && set prompt="`dirs`% "'
If you've typed the above without any typos, when you log off and back on,
you'll get the regular % prompt. However, after you type
cd, your prompt will always tell you what directory you are in, with your home directory shortened to the ~ symbol.
We actually had to do a bit of C programming to get this prompt to work. The C shell understands the
${cwd} or current working directory variable; unfortunately, this will only show what your current directory was when you logged in. We had to create an alias to the
cd command if we wanted our prompt to continue to change as we changed directories.
We also had to use the backquote, or
` -- this is on the same key as the
~ symbol. Don't confuse it with this quote --
', which is on the same key as
". Back quotes are used for command substitution. We used it around the
dirs command that tells the C shell to print out the name of the current directory. If you forget the
` quotes, your prompt will literally display the word
dirs, instead of the result of the
dirs command.
The other new characters we used were
&&. This tells your shell that "I want you to do one thing, and when that successfully finishes, I want you to do this next". In summary, we told the shell that when we use the
cd command, not only did we want it to change our directory, we also wanted it to set our prompt to show the name of the directory we changed to.. | http://www.linuxdevcenter.com/lpt/a/378 | CC-MAIN-2015-11 | refinedweb | 722 | 71.14 |
C API: BreakIterator. More...
#include "unicode/utypes.h"
#include "unicode/uloc.h"
#include "unicode/utext.h"
#include "unicode/localpointer.h"
#include "unicode/parseerr.h"
Go to the source code of this file.
C API: BreakIterator.
A text-break iterator. For usage in C programs.
The BreakIterator C API defines methods for finding the location of boundaries in text. Pointer to a UBreak.
Title boundary analysis locates all positions, typically starts of words, that should be set to Title Case when title casing the text.
The text boundary positions are found according to the rules described in Unicode Standard Annex #29, Text Boundaries, and Unicode Standard Annex #14, Line Breaking Properties. These are available at and.
In addition to the plain C API defined in this header file, an object oriented C++ API with equivalent functionality is defined in the file brkiter.h.
Code snippets illustrating the use of the Break Iterator APIs are available in the ICU User Guide, and in the sample program icu/source/samples/break/break.cpp
Definition in file ubrk.h. | http://icu.sourcearchive.com/documentation/4.8.1.1-1/ubrk_8h.html | CC-MAIN-2017-39 | refinedweb | 175 | 53.68 |
An Introduction to Poetry
Maximilian Burszley
・7 min read
In this post, I am using
Windows 10/
Windows Terminal/
PowerShell 7 with
Python 3.8.1. Adjust examples according to your environment.
If you don't care about the logic and reasoning behind "why Poetry?", skip to Getting Started where we build a simple Flask app using Poetry as our package manager.
§ History ↑
Python has existed for almost 30 years now and many revolutions have occurred in the software arena since its inception. Paradigms have shifted around OOP and functional, design patterns have come and gone, but one issue every language sees, and has varying success in tackling, is dependency management.
For the first half of its life thus far, Python did not have a dedicated way to handle packaging or dependencies. It was the wild west: relying on what's in the standard library or figuring it out yourself. It wasn't until Python 1.6 that the
distutils package was added to the standard library in a first attempt to handle the problem in 2000. Here are some more milestones according to PyPA (Python Packaging Authority):
- 2003: PyPI was operational but wouldn't have "packages" hosted until 2005.
- 2004:
setuptoolsis created and is the present packaging go-to.
- 2007:
virtualenvpackage is created to segregate packages per-project.
- 2008:
pipsupersedes
easy_install(from the
setuptoolspackage).
- 2011: PyPA is created to take over
pipand
virtualenvmaintenance.
- 2013: PEP 425 and PEP 427 accepted which define the built-package (binary) format,
wheel.
- 2016: PEP 518 accepted for the
pyproject.tomlformat for static build dependency declarations.
- 2017: PEP 517 accepted for
setup.py-independent (from
setuptools) build system backends.
There is a lot of history when it comes to Python packaging and decisions, but I tried to highlight the milestones. The last two are the most relevant to this post as they enabled the
Poetry project to take off as it is today and move away from the history of
distutils/
setuptools.
§ Problems ↑
When you start most Python projects, there isn't really guidance on how to start. Most guides used to give you a
requirements.txt file to define your dependencies that you install using
pip:
PS ~/> pip install --user --requirement requirements.txt
You would probably install those in your user site-packages (indicated by
--user which could cause some chaos with changing versions, conflicting packages, etc.) and off you go. This was hard to scale and deploy, however, which is why
virtualenv came along to ease that development process by keeping your dependencies contained per-project and "activating" the environment when you're using it:
PS ~/> python -m venv .venv PS ~/> .venv/Scripts/Activate.ps1
Another problem with this approach is that the requirements file is rather simple. It's typically a newline-separated plaintext file with a package name and some version indicator that a person writes or generates using:
PS ~/> pip freeze > requirements.txt
But using this approach has its own problems. It locks all the versions with exact specifiers and their dependencies:
PS ~/> pip install flask==1.1.1 # ... PS ~/> pip freeze click==7.1.1 Flask==1.1.1 itsdangerous==1.1.0 Jinja2==2.11.1 MarkupSafe==1.1.1 Werkzeug==1.0.0
This creates a lot of manual work to audit your dependencies and bring them up-to-date when needed.
A route some people go with is using
setuptools to manage their project as an installable package. This is particularly effective when your project has tests and sub-packages, but adds another layer to the stinky onion.
setuptools uses a
setup.py script to control the installation of your package. This file has one requirement when called: to execute
setuptools.setup().
import setuptools setuptools.setup() # barebones
Normally this function takes arguments to imperatively install the package, but a nice, declarative way to set these arguments is using a
setup.cfg file.
# ... [options] install_requires = Flask==1.1.1 # ...
This file is also used by many packages for configuration, so it's a neat way to centralize your configuration, but it has the same problems as it uses the same format for dependencies. More information on this method of setup can be found here.
This leaves us with the following problems:
- How do we isolate our project?
virtualenvis nice, but can be forgotten
- How do we manage our dependencies and their versions? Locking everything that gets installed is a management nightmare.
One last issue that deserves a little blurb: how do we install our own project/package and use it? Depending on
PYTHONPATH is fraught with complications especially when you start talking about testing your code and many a solution has been created to mangle it to fit a use-case perhaps unnecessarily.
§ Installation ↑
Poetry's tagline is "Python packaging and dependency management made easy." It accomplishes this by using features introduced by PEP 517 and PEP 518 introducing independent build system backends and new dependency declaration (away from
pip and
setuptools; they're still there, but abstracted away from the user).
What this looks like in action is something that resembles JavaScript's
yarn tool. There is the
pyproject.toml similar to
package.json and a
poetry.lock like
yarn.lock. There is also configuration of the tool itself kept in
poetry.toml (again, like
.yarnrc.yml).
Poetry is available on PyPI, but they recommend using their alternative installer to avoid polluting your Python packages.
# bash curl -sSL | python # PowerShell (Invoke-WebRequest -Uri -UseBasicParsing).Content | python # python pip install --user poetry
§ Getting Started ↑
To the meat and potatoes- using the tool! Here, the tool creates our project scaffold so the package is installable in a virtual environment:
PS ~/> poetry new --name app --src poetry-intro Created package app in poetry-intro
Now that we have a project, I go a step further to create the virtual environment local to the project for easier editor integration:
PS ~/> Set-Location -Path poetry-intro PS ~/poetry-intro/> poetry config --local virtualenvs.in-project true
With the configuration set, we're ready to initialize the environment, install our package, and add some dependencies:
PS ~/poetry-intro/> poetry install Creating virtualenv app in ~/poetry-intro/.venv Updating dependencies Resolving dependencies... Writing lock file Package operations: 11 installs, 0 updates, 0 removals - Installing pyparsing (2.4.6) - Installing six (1.14.0) - Installing atomicwrites (1.3.0) - Installing attrs (19.3.0) - Installing colorama (0.4.3) - Installing more-itertools (8.2.0) - Installing packaging (20.3) - Installing pluggy (0.13.1) - Installing py (1.8.1) - Installing wcwidth (0.1.9) - Installing pytest (5.4.1) - Installing app (0.1.0) PS ~/poetry-intro/> poetry add flask Using version ^1.1.1 for flask Updating dependencies Resolving dependencies... Writing lock file Package operations: 6 installs, 0 updates, 0 removals - Installing markupsafe (1.1.1) - Installing click (7.1.1) - Installing itsdangerous (1.1.0) - Installing jinja2 (2.11.1) - Installing werkzeug (1.0.1) - Installing flask (1.1.1)
If you're in an environment with private registries, add them according to the docs (I could not get them to work when specifying them in
poetry.toml):
~/poetry-intro/pyproject.toml
[[tool.poetry.source]] name = "private-repo" url = "" default = true [[tool.poetry.source]] name = "private-repo2" url = ""
The
default tells Poetry to ignore the public
PyPI registry.
Now we'll get to writing code:
~/poetry-intro/src/app/__init__.py
from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'Hello, World!'
To execute our new app, we take advantage of the
run command which executes commands in the context of the virtual environment:
PS ~/poetry-intro/> $Env:FLASK_ENV = 'development' PS ~/poetry-intro/> poetry run flask run * Environment: development * Debug mode: on * Running on (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 000-000-000
If you want to work in your environment for an extended period, you may want to use
poetry shell to spawn a new shell according to
$SHELL with the environment activated.
I usually have some linters and formatters to integrate into intellij/vscode for consistency, so let's add them here as developer dependencies:
PS ~/poetry-intro/> poetry add --dev yapf flake8 Using version ^0.29.0 for yapf Using version ^3.7.9 for flake8 Updating dependencies Resolving dependencies... Writing lock file Package operations: 6 installs, 0 updates, 0 removals - Installing entrypoints (0.3) - Installing mccabe (0.6.1) - Installing pycodestyle (2.5.0) - Installing pyflakes (2.1.1) - Installing flake8 (3.7.9) - Installing yapf (0.29.0)
You may notice a lack of test runner, but that was already included in the
pyproject.toml dependencies when using
poetry new. Speaking of which, no project is complete without some tests:
~/poetry-intro/tests/test_app.py
from app import app app.testing = True client = app.test_client() def test_index(): response = client.get('/') assert b"Hello, World!" in response.data
PS ~/poetry-intro/> poetry run pytest ======================== test session starts ======================== platform win32 -- Python 3.8.1, pytest-5.4.1, py-1.8.1, pluggy-0.13.1 rootdir: ~/poetry-intro collected 1 item tests\test_app.py . [100%] ========================= 1 passed in 0.30s =========================
§ Conclusion ↑
This post is starting to get a bit long, but I feel like I've covered the bases to get started. There is a lot more to Poetry, such as building packages, deployment to registries, etc., but the docs are a great location to dig deeper.
In our sample project, we:
- showcased using Poetry for all interactions with the project which made forgetting our virtual environment an impossibility
- saw the lockfile in action which enables repeatable builds and avoids dependency nightmares
- avoided the overhead of
setuptools/
setup.pyto install our package/module in our environment
I hope this project grows into further maturity and sees more adoption because it could be the catalyst to make
pip better and/or become the standard like
yarn has for many JavaScript devs.
Did you find this article helpful?
🎩 JavaScript Enhanced Scss mixins! 🎩 concepts explained
In the next post we are going to explore CSS @apply to supercharge what we talk about here....
Great article! I would love to share two python boilerplates that are using
poetryas the package manager:
Bleeding edge cookiecutter template to create new python packages
wemake-python-package
Bleeding edge cookiecutter template to create new python packages.
Purpose
This project is used to scaffold a
pythonproject structure. Just like
poetry newbut better.
Features
python3.7+
flake8and wemake-python-styleguide for linting
travisor
Github Actionsas the default CI
Installation
Firstly, you will need to install dependencies:
Then, create a project itself:
Projects using it
Here's a nice list of real-life open-source usages of this template.
License
MIT. See LICENSE for more details. | https://practicaldev-herokuapp-com.global.ssl.fastly.net/mburszley/an-introduction-to-poetry-2b6n | CC-MAIN-2020-24 | refinedweb | 1,788 | 50.02 |
Hierarchical Clustering in Python
Want to share your content on python-bloggers? click here.
We have provided an example of K-means clustering and now we will provide an example of Hierarchical Clustering. We will work with the famous
Iris Dataset.
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline from sklearn import datasets iris = datasets.load_iris() df=pd.DataFrame(iris['data']) print(df.head())
0 1 2 3 0 5.1 3.5 1.4 0.2 1 4.9 3.0 1.4 0.2 2 4.7 3.2 1.3 0.2 3 4.6 3.1 1.5 0.2 4 5.0 3.6 1.4 0.2
Let’s see the number of targets that the Iris dataset has and their frequency:
np.unique(iris.target,return_counts=True)
(array([0, 1, 2]), array([50, 50, 50], dtype=int64))
As we can see there are three targets of 50 observations each. If we want to see the names of the target:
iris.target_names
array(['setosa', 'versicolor', 'virginica'], dtype='<U10')
Data Preparation for Cluster Analysis
When we apply Cluster Analysis we need to scale our data. There are many different approaches like standardizing or normalizing the values etc. Also, we can
whiten the values which is a process of rescaling data to a standard deviation of 1:
\(x_{new} = x/std\_dev(x)\)
Let’s scaled the iris dataset.
# Import the whiten function from scipy.cluster.vq import whiten scaled_data = whiten(df.to_numpy())
Let’s check if the variance of every feature is close to 1 now:
pd.DataFrame(scaled_data).describe()
Creat the Distance Matrix based on linkage
Look at the documentation of the `linkage` function to see the available methods and metrics.
# Import the fcluster and linkage functions from scipy.cluster.hierarchy import fcluster, linkage # Use the linkage() function distance_matrix = linkage(scaled_data, method = 'ward', metric = 'euclidean')
How many Clusters – Introduction to dendrograms
Dendrograms help in showing progressions as clusters are merged. It is a branching diagram that demonstrates how each cluster is composed by branching out into its child nodes.
# Import the dendrogram function from scipy.cluster.hierarchy import dendrogram # Create a dendrogram dn = dendrogram(distance_matrix) # Display the dendogram plt.show()
From the dendrogram we can realize that a good candidate for the number of Clusters is 3 and that 2 clusters are closer (the red ones) compared to the green one.
Run the Hierarchical Clustering
# Assign cluster labels df['cluster_labels'] = fcluster(distance_matrix, 3, criterion='maxclust')
Notice that we can define clusters based on the linkage distance by changing the criterion to
distance in the
fcluster function!
Hierarchical vs Actual for n_clusters=3
df['target'] = iris.target fig, axes = plt.subplots(1, 2, figsize=(16,8)) axes[0].scatter(df[0], df[1], c=df['target']) axes[1].scatter(df[0], df[1], c=df['cluster_labels'], cmap=plt.cm.Set1) axes[0].set_title('Actual', fontsize=18) axes[1].set_title('Hierarchical', fontsize=18)
Want to share your content on python-bloggers? click here. | https://python-bloggers.com/2020/08/hierarchical-clustering-in-python/ | CC-MAIN-2021-10 | refinedweb | 508 | 50.73 |
Ppl pls have a look at the performance test results
under:
--Dasarath
--- Aleksander Slominski <aslom@cs.indiana.edu> wrote:
> Eran Chinthaka wrote:
>
> >>>start with no collection and allocate collection
> only if any attribute
> >>>is added and have initial size 1 or 2 with
> increment of 4.
> >>>
> >>>
> >
> > [Chinthaka] This is what I also have done.
> >Initially there is no collection and if there is an
> attribute only I create
> >the ArrayList.
> >
> >
> >I just looked in to the JDom way of implementing
> Namespaces and Attributes.
> >As far as the namespaces are concerned they have
> done the same thing, we
> >did. They have an ArrayList of 5 to hold
> namespaces, within the Element.
> >
> >
> i would guess that if you have 4 or more elements
> than ArrayList is more
> efficient than any linked list implementation
> linked list: N * (size of object) + 2 * N * (size of
> pointer for next/prev)
> array list: N * (size of object) + size filed + N *
> (size of pointer -
> actual array)
> and access is faster as you can read directly
> elements form array no
> need to walk linked list to find elements
>
> however without tests i could not say and moreover i
> think when compared
> to other operations in OM or in Engine this will be
> unnoticeable
>
> alek
>
> >And the same mechanism is there for attributes, but
> with some more
> >complexity.
> >So I think our approach is not so bad. And I know
> very well that, JDom is
> >very good in performance wise also, as I used JDom
> to bench mark our OM.
> >
> >So my opinion is to leave the things as it is,
> until we find some better way
> >of implementing that.
> >
> >
> >Thankx and regards,
> >-- Eran Chinthaka
> >
> >
> >
> >
>
>
> --
> The best way to predict the future is to invent it -
> Alan Kay
>
>
__________________________________
Do you Yahoo!?
Jazz up your holiday email with celebrity designs. Learn more. | http://mail-archives.apache.org/mod_mbox/axis-java-dev/200412.mbox/%3C20041231161129.23440.qmail@web11608.mail.yahoo.com%3E | CC-MAIN-2018-05 | refinedweb | 303 | 65.05 |
26 October, 2018
Apex allows us to use the following modifiers
Privat. we want to make something public like it is in Java,.
Note:We recommend using the global access modifier rarely, if at all. Cross-application dependencies are difficult to maintain.
With Sharing: Use the with sharing keywords when declaring a class to enforce the sharing rules that apply to the current user.
Without Sharing: Use the without sharing keywords when declaring a class to ensure that the sharing rules for the current user are notenforced..
Abstract
The abstract definition modifier declares that this class contains abstract methods, that is, methods that only have their signature declared and no body defined.
Extends
Inheritance concept
Final
Final variables can only be assigned a value once, either when we declare a variable or in initialization code
Virtual
The virtual definition modifier declares that this class allows extension and overrides.
This
There are two different ways of using the this keyword. We can use the this keyword in dot notation, without parenthesis, to represent the current instance of the class in which it appears. Use this form of the this keyword to access instance variables and methods. For example:
Public class myTestThis { string s; { this.s = 'TestString'; } }
In the above example, the class myTestThis declares an instance variable s. The initialization code populates the variable using the this keyword. Or we can use the this keyword to do constructor chaining, that is, in one constructor, call another constructor. In this format, use the this keyword with parentheses.
For example:
public class testThis { // First constructor for the class. It requires a string parameter. public testThis(string s2) { } // Second constructor for the class. It does not require a parameter. // This constructor calls the first constructor using the this keyword. public testThis() { this('None'); } }
Super
The super keyword.can be used by classes that are extended from virtual or abstract classes. By using super, we can override constructors and methods from the parent class. The following are special types of keywords that aren't reserved words and can be used as identifiers.
Count: count() returns the number of rows that match the filtering conditions and count() returns the number of rows that match the filtering conditions and have a non-null value for . This syntax is newer than COUNT() and is available in API version 18.0 and later.
Enthusiastic about exploring the skill set of Salesforce?Then, have a look at the Salesforce Training Online to gather additional knowledge.
Apex supports the following OOPS concepts given below
Acquiring the properties of parents by children is what we call as. We can make use of the same principle under object oriented language and consume the members of one class under multiple classes by establishing Parent-Child relationship between classes. This basically provides us
Changing the behavior of entities depending upon input they receive is known as Polymorphism. This can be implemented in object oriented language using different approaches like
This is all about Hiding the complexity of a program and providing with a set of interface to consume the functionalities. Functions and Methods are examples for Abstraction we never know the logic behind them, what we are is only how to consume them.
Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of
It is all about hiding the code to secure the contents of a program. To hide the code we enclose the members of a program under a container or wrapper known as class.
A wrapper or container class is a class, a data structure, or an abstract data type whose instances are collections of other objects. In Apex and Visual force this type of class can be extremely useful
A function or Method in general referred as Subprogram is a named block of code which can be reused, when and where is called its get executed It is also an action that has to be performed A method can be either value returning or non value returning, use *- to tell the method non value returning and if it value returning specify the type (primitive or Sobject data type) of value it was returning using keyword.
Some Other key words are
- Excludes,first,includes,last,order,after . | https://tekslate.com/access-modifier-and-oops-concepts | CC-MAIN-2022-21 | refinedweb | 731 | 53.81 |
Top 50 question and answer asked in Phone interview
Abhishek
・20 min read
Hello There!! Hope you all doing great.
Today i'm going to share about what I read in a article "Top 50 Programming Language, Data Structure & Algorithms Phone Interview Questions with Answers" on HOB's blog post by Kimberly Cook.
As article's heading explain more about the article so let's get started.
As you can see from last few years companies started a new way to take interview is Phone interview and it's also known as telephonic round. Telephonic round is the single most popular way to screen candidates in a programming language job interview. It's easy for both parties to gauge each other, candidate doesn't need to travel to perspective Employer's premises and Interviewer also doesn't need to make any necessary arrangement.In order to clear telephonic round and proceed to next round, you must be good enough to answer all the questions related to your Job description.
In most of the phone interviews for Java or C++ developer, you will not only find questions from respective programming language but also from other technology e.g. SQL, XML, UNIX, General Programming, Object-oriented programming, Data Structure, and Algorithm, Networking, Coding and other areas of work. Because of this vast nature of phone round of programming job interview, you need to come up with a special strategy to present yourself in a manner Interviewer is expecting.
One of the most important things to remember, while answering questions on phone interview is to mention key points early and always give to the point answer. Since most interviewers like to cover lots of topics to screen the candidate, they usually like to the point answers rather than blah blah and OK I know the stuff, you will get your chance to explain things in deep in the face to face interview. BTW, this is not the hard and fast rule and you can actually understand what interviewer is expecting from you by noting his response to your answers. If he asks follow-up or expects you to speak more than go ahead, but it quickly jumps to the next question then be clear and concise.
In this article, I am sharing you some popular and interesting programming questions especially tailored for phone interviews. Most of them are actually from the telephonic round of various tech companies including banks like Barclays, Citi, Nomura, and various service-based companies like Infosys, TCS, CTS, Tech Mahindra, and HCL.
As I mentioned before questions are randomly picked from various topic but mostly based on fundamentals because that is what Interviewer test on phone interviews. Though these questions mostly for less experienced developer e.g. 2 to 5 years, Senior and experienced programmers can also use these for their interview purpose.
If you are seriously preparing for Job interviews, I also suggest you take a look at either Programming Interviews Exposed by Wrox or Cracking the code Interview, two of the good books I have found for preparing any programming job interviews. First one is my favorite and I have read it almost 7 years back, but still, it's quite relevant because of an excellent explanation of data structure and algorithm questions.
If you are an interviewer, you can also use these question to quickly screen candidate for development positions. I have provided the short answer here and pointer for the more detailed answer.
Top 50 Programming Language Questions for Telephonic Interviews
Here is a list of almost 50 questions from phone round of programming job interviews. These questions are good for any programmers, developers, software engineer, QA and support engineer because they are based on fundamentals of programming, but most suited for programmers and developers. BTW, If you are Java developer and looking for Java Questions for Phone interviews, check out that list. This list is more general and applicable for all programmers including Python, Ruby, Perl, and C# developers.
1. How much time does it take to retrieve an element if stored in HashMap, Binary tree, and a Linked list? how it changes if you have millions of records?
In HashMap it takes O(1) time, in the binary tree it takes O(logN) where N is a number of nodes in the tree and in linked list it takes O(n) time where n is a number of element in the list. Millions of records don't affect the performance if the data structure is working as expected e.g. HashMap has no or relatively less number of collision or binary tree is balanced. If that's not the case then their performance degrades as a number of records grow.
2. What is the difference between Overriding and Overloading? (detailed answer)
Overriding is resolved at runtime while overloading is compiled time. Also, rules of overriding and overloading are different, for example in Java, method signature of the overloaded method must be different than original method, but in the case of overriding, it must be exactly same as an overriding method.
3. What is the difference between forking a process and spawning a thread?
When you fork a process, the new process will run the same code as parent process but in different memory space, but when you spawn a new thread in the existing process, it just creates another independent path of execution but share same memory space.
4. What is a critical section? (answer)
A critical section is the part of a code, which is very important and in multi-threading must be exclusively modified by any thread. Semaphore or mutex is used to protect a critical section. In Java, you can use synchronized keyword or ReentrantLock to protect a critical section.
5. What is the difference between a value type and a reference type? (answer)
A value type is a more optimized type and always immutable e.g. primitive int, long, double and float in Java while a reference type points to an object, which can be mutable or Immutable. You can also say that value type points to a value while reference type points to an object.
6. What is heap and stack in a process? (detailed answer)
They are two separate areas of memory in the same process. Talking about Java, the stack is used to store primitive values and reference type to object but actual object is always created in heap. One critical difference between heap and stack is that heap memory is shared by all threads but each thread has their own stack
7. What is revision/version control? (answer)
Version control is software which is used to store code and manages versions of codebase e.g. SVN, CVS, Git, Perforce, and ClearCase. They are very effective while comparing code, reviewing code and creating a build from the previous stable version. All professional development use some sort of revision or version control tool, without them, you cannot manage code effectively, especially if 20 developers are working on same code base at the same time. Version control tool plays a very important role to keep codebase consistent and resolving code conflicts.
8. What is a strongly typed programming language? (answer)
In a strongly typed language compiler ensure type correctness, for example, you can not store the number in String or vice-versa. Java is a strongly typed language, that's why you have different data types e.g. int, float, String, char, boolean etc. You can only store compatible values in respective types. On the other hand, weakly typed language doesn't enforce type checking at compile time and they tree values based upon context. Python and Perl are two popular example of weakly typed programming language, where you can store a numeric string in number type.
9. Can you describe the difference between valid and well-formed XML?
A well-formed XML is the one which has root element and all tags are closed properly, attributes are defined properly, their value is also quoted properly. On another hand, a valid XML is the one which can be validated against an XSD file or schema. So it's possible for an XML to be well-formed but not valid because they contain tags which may not be allowed by their schema.
10. What is the difference between DOM and SAX parser?(detailed answer)
DOM parser is an in-memory parser so it loads a whole XML file in memory and creates a DOM tree to parse. SAX parser is an event-based parser, so it parses XML document based on the event received e.g. opening tag, closing tag, the start of attribute or end of the attribute. Because of their working methodology, DOM parser is not suitable for large XML file as they will take a lot of space in memory and your process may run out of memory, SAX is the one which should be used to parse large files. For small files, DOM is usually much faster than SAX.
11. What is the relationship between threads and processes? (detailed answer)
A process can have multiple threads but a thread always belongs to a single process. Two processes cannot share memory space until they are purposefully doing inter-process communication via shared memory but two threads from the same process always share the same memory.
12. What is Immutable class mean?(detailed answer) the new object. An immutable object is very useful for concurrent programming because they can be shared between multiple threads without worrying about synchronization. In fact, the whole model of functional programming is built on top of Immutable objects.
13. Why would you ever want to create a mock object?(answer)
A mock object is very useful to test an individual unit in your Software, in fact, stub and mocks a is a powerful tool for creating automated unit tests. Suppose you write a program to display currency conversion rates but you don't have a URL to connect to, now if you want to test your code, you can use mock objects. In the Java world, there are a lot of frameworks which can create powerful mock objects for you e.g. Mockito and PowerMock.
14. What is SQL injection?
SQL injection is a security vulnerability which allows an intruder to steal data from the system. Any system which takes input from the user and creates a SQL query without validating or sanitizing that input is vulnerable to SQL injection. In such system, an intruder can inject SQL code instead of data to retrieve more than expected data. There are many instances on which sensitive information e.g. user id, password, and personal details are stolen by exploiting this vulnerability. In Java, you can avoid SQL injection by using a Prepared statement.
15. What is the difference between an inner join and a left join in SQL? (answer)
In SQL, there are mainly two types of joins, inner join, an outer join. Again outer joins can be two types right and left outer join. The main difference between inner join and left join is that in the case of former only matching records from both tables are selected while in the case of left join, all records from left table are selected in addition to matching records from both tables. Always watch out for queries which have "all" in it, they usually require left join e.g. to write SQL query to find all departments and a number of employees on it. If you use inner join to solve this query, you will miss empty departments where no one works.
16. What does the V in MVC stand for, and what does it signify?(answer)
V stands for View in MVC pattern. The view is what user sees e.g. web pages. This is a very important design pattern of web development which is based upon segregation of concern so that each area can be modified without impacting other areas. In the Java world, there are lots of open source framework which provides an implementation of MVC pattern e.g. Struts 2 and Spring MVC. By the way, M stands the for model and C stands the for the controller. Modes are actual business objects e.g. User, Employee, Order; while the controller is used for the routing request to correct processor.
17. What is the difference between a class and an object?(detailed answer)
A class is a blueprint on which objects are created. A class has code and behavior but an object has both the state and behavior. You cannot create an object without creating a class to represent its structure. The class is also used to map an object in memory, in Java, JVM does that for you.
18. What is loose-coupling?
Loose coupling is a desirable quality of software, which allows one part of the software to modify without affecting another part of the software. For example, in a loosely coupled software, a change in UI layout should not affect the back-end class structure.
19. What is the difference between composition, aggregation, and association?(detailed answer)
Association means two objects are related to each other but can exist without each other, Composition is a form of association where one object is composed of multiple objects, but they only exist together e.g. human body is the composition of organs, individual organs cannot live they only useful in the body. Aggregation is a collection of object e.g. city is an aggregation of citizens.
20. What is the difference between an interface and an abstract class? (detailed answer)
This is the most classical question of all programming interviews. An interface is the purest form of abstraction with nothing concrete in place while an abstract class is a combination of some abstraction and concrete things. The difference may vary depending upon language e.g. in Java you can extend multiple interfaces but you can only extend on the abstract class. For a more comprehensive discussion see the detailed answer.
21. What is unit testing? (answer)
Unit testing is a way to test individual unit for their functionality instead of testing whole application. There are a lot of tools to do the unit testing in different programming language e.g. in Java, you can use JUnit or TestNG to write unit tests. It is often run automatically during the build process or in a continuous environment like Jenkins.
22. Can you describe three different kinds of testing that might be performed on an application before it goes live?
unit testing, integration testing, and smoke testing.. in a flight booking website, you should be able to book, cancel or change flights.
23. What is the difference between iteration and recursion? (detailed answer)
Iteration uses a loop to perform the same step again and again while recursion calls the function itself to do the repetitive task. Many times recursion results in a clear and concise solution to complex problem e.g. tower of Hanoi, reversing a linked list or reversing a String itself. One drawback of recursion is depth since recursion stores intermediate result in the stack you can only go up to a certain depth, after that your program will die with StackOverFlowError, this is why iteration is preferred over recursion in production code.
24. What is the difference between & and && operator? (detailed answer)
& is a bitwise operator while && is a logical operator. One difference between & and && is that bitwise operator (&) can be applied to both integer and boolean but logical operator (&&) can only be applied to boolean variables. When you do a & b then AND operator is applied to each bit of both integer number, while in the case of a && b, the second argument may or may not be evaluated, that's why it is also known as short circuit operator, at least in Java. I like this question and often asked it to junior or developer and college graduates.
25. What is the result of 1 XOR 1?
The answer is zero because XOR returns 1 if two operands are distinct and zero if two operands are same, for example, 0 XOR 0 is also zero, but 0 XOR 1 or 1 XOR 0 is always 1.
26. How do you get the last digit of an integer?(detailed answer)
By using the modulus operator, number % 10 returns the last digit of the number, for example, 2345%10 will return 5 and 567%10 will return 7. Similarly, division operator can be used to get rid of the last digit of a number e.g. 2345/10 will give 234 and 567/10 will return 56. This is an important technique to know and use to solve problems like number palindrome or reversing numbers.
27. What is test-driven development?
Test-driven is one of the popular development methodologies in which tests are written before writing any function code. In fact, test drives the structure of your program. Purists never wrote a single line of application code without writing a test for that. It greatly improves code quality and often attributed to a quality of rockstar developers.
28. What is the Liskov substitution principle? (detailed answer)
Liskov substitution principle is one of the five principles introduced by Uncle Bob as SOLID design principles. It's the 'L' in SOLID. Liskov substitution principle asserts that every subtype should be able to work as the proxy for parent type. For example, if a method except for the object of the Parent class then it should work as expected if you pass an object of the Child class. Any class which cannot stand in place of its parent violate LSP or Liskov substitution principle. This is actually a tough question to answer and if you do that you end up with creating a good impression on interviewers mind.
29. What is the Open closed design principle?(answer)
Open closed is another principle from SOLID, which asserts that a system should be open for extension but closes for modification. Which means if a new functionality is required in a stable system then your tried and tested code should not be touched and new functionality should be provided by adding new classes only.
30. What is the difference between a binary tree and a binary search tree?
The binary search tree is an ordered binary tree, where the value of all nodes in the left tree is less than or equal to node and values of all nodes in right subtree is greater than or equal to the node (e.g. root). It's an important data structure and can be used to represent a sorted structure.
31. Can you give a practical example of a recursive algorithm?(example)
There are lots of places where the recursive algorithm fits e.g. algorithm related to the binary and linked list. A couple of examples of a recursive algorithm is reversing String and calculating Fibonacci series. Other examples include reversing a linked list, tree traversal, and quicksort algorithm.
32. What is the time complexity of an algorithm?
Time complexity specifies the ratio of time to the input. It shows how much time an algorithm will take to complete for a given number of input. It's approximated valued but enough to give you an indication that how your algorithm will perform if the number of input is increased from 10 to 10 million?
33. What are some important differences between a linked list and an array? (detailed answer)
linked list and array are two of the most important data structure in the programming world. The most significant difference between them is that array stores its element at the contiguous location while linked list stores its data anywhere in memory. This gives linked list enormous flexibility to expand itself because memory is always scattered. It's always possible that you wouldn't be able to create an array to store 1M integers but can do by using linked list because space is available but not as contiguous chunk. All other differences are the result of this fact. For example, you can search an element in array with O(1) time if you know the index but searching will take O(n) time in linked list. For more differences see the detailed answer.
34. What is a couple of ways to resolve collision in the hash table?
linear probing, double hashing, and chaining. In linear probing, if the bucket is already occupied then function check next bucket linearly until it finds an empty one, while in chaining, multiple elements are stored in same bucket location.
35. What is a regular expression? (answer)
A regular expression is a way to perform pattern matching on text data. It's a very powerful tool to find something e.g. some character in a long string e.g. finding if a book contains some word or not. Almost all major programming language supports regular expression but Perl has been renowned for its enormous capability. Java also supports Perl-like regular expression using java.util.regex package. You can use the regular expression to check if an email is valid or not, if a phone number is valid, or if a zip code is valid, or even an SSN number is valid or not. One of the simplest examples of the regular expression is to check if a String is a number or not.
36. What is a stateless system?
A stateless system is a system which doesn't maintain any internal state. Such a system will produce the same output for the same input at any point in time. It's always easier to code and optimize a stateless system, so you should always strive for one if possible.
37. Write SQL query to find second highest salary in the employee table?(solution)
This is one of the classic questions from SQL interviews, the event it's quite old it is still interesting and has lots of follow-ups you can use to check the depth of a candidate's knowledge. You can find second highest salary by using the correlated and non-correlated subquery. You can also use keyword's like TOP or LIMIT if you are using SQL Server or MySQL, given Interviewer allows you. The simplest way to find the 2nd highest salary is following:
SELECT MAX(Salary) FROM Employee WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee)
This query first finds maximum salary and then exclude that from the list and again finds maximum salary. Obviously second time, it would be the second highest salary.
38. Can you describe the difference between correlated and non-correlated subquery?(answer)
In correlated sub-query, inner query depends upon the outer query and executes for each row in the outer query. While non-correlated subquery doesn't depend upon the outer query and can be executed independently. Due to this reason, the former is slow and later is fast. BTW, correlated subquery has some nice application, one of them is finding Nth highest salary in Employee table, as seen on previous SQL question as well.
39. How do you find if a number is a power of two, without using arithmetic operator?(solution)
Assume it's a question of using the bitwise operator as soon as you hear restriction about not allowed to use arithmetic operator. If that restriction is not in place then you can easily check if a number is a power of two by using modulus and division operator. By the using bitwise operator, there is a nice trick to do this. You can use the following code to check if a number if the power of two or not
public static boolean powerOfTwo(int x) {
return (x & (x - 1)) == 0;
}
x & (x-1) is a nice trick to convert right a most bit to zero if it's on, I learned from hackers delight book.
40. How do you find a running Java process on UNIX? (command)
You can use the combination of 'ps' and 'grep' command to find any process running on UNIX machine. Suppose your Java process has a name or any text which you can use to match against just use following command.
ps -ef | grep "myJavaApp"
ps -e will list every process i.e. process from all user, not just you and ps -f will give you full details including PID, which will be required if you want to investigate more or would like to kill this process using kill command.
41. How do you find large files in UNIX e.g. more than 1GB?(command)
You can easily find big files by using find command because it provides an option to search files based upon their size. Use this if your file system is full and your Java process is crashing with no more space. This command will list all files which are more than 1GB. You can tweak the size easily e.g. to find all files with more than 100 MB just use +100M.
find . - type f -size +1G -print
42. What is the shell script?
A shell script is a set of shell commands with some programming constructs e.g. if and for loop, which allows you to automate some repetitive task. For example, you can write a shell script to the daily cleanup of logs files, for backing up data for historical use and for other housekeeping jobs, releases, and monitoring.
That's all in this list of programming questions for phone interviews. You might have noticed that there are only 42 questions but title mentioned about 50 questions, where is remaining 8 questions? Well Instead of sharing 8 questions I am sharing with you guys 8 more articles where you can find remaining programming questions. here you go:
20 String Coding Questions for Programmers ( read here)
15 Data Structure and Algorithm questions for Software developers (see here)
10 Interview Questions Every Developer Should Know (read more)
20 Core Java Question from Programmers for 2 to 3 years experienced (check here)
21 SQL Query Interview Questions with Answers (read more)
23 Tricky Questions for Java Programmers (read here)
10 XML Interview Questions for Programmers (see here)
50 Multithreading and Concurrency Questions from Java Interviews (check here)
20 Software design Questions from Programming Interviews (read more)
18 Java Design Pattern Interview questions. (see here)
Uhh that's a long list . So that's it for this article guys .See you in next one and thanks for reading.
Good luck and happy coding. | https://practicaldev-herokuapp-com.global.ssl.fastly.net/abhishekalbert/top-50-question-and-answer-asked-in-phone-interview--3pkc | CC-MAIN-2020-10 | refinedweb | 4,426 | 62.07 |
This tutorial is designed to help technical artists or developers learn to extend Blender. An understanding of the basics of Python is expected for those working through this tutorial.
Before going through the tutorial you should...
Suggested reading before starting this tutorial.
To best troubleshoot any error message Python prints while writing scripts you run blender with from a terminal, see Use The Terminal.
While going through the tutorial you may want to look into our reference documentation.
An addon is simply a Python module with some additional requirements so Blender can display it in a list with useful information.
To give an example, here is the simplest possible addon.
bl_info = {"name": "My Test Addon", "category": "Object"} def register(): print("Hello World") def unregister(): print("Goodbye World")
Notice this addon does not do anything related to Blender, (the bpy module is not imported for example).
This is a contrived example of an addon that serves to illustrate the point that the base requirements of an addon are simple.
An addon will typically register operators, panels, menu items etc, but its worth noting that _any_ script can do this, when executed from the text editor or even the interactive console - there is nothing inherently different about an addon that allows it to integrate with Blender, such functionality is just provided by the bpy module for any script to access.
So an addon is just a way to encapsulate a Python module in a way a user can easily utilize.
Note
Running this script within the text editor won’t print anything, to see the output it must be installed through the user preferences. Messages will be printed when enabling and disabling.
The simplest possible addon above was useful as an example but not much else. This next addon is simple but shows how to integrate a script into Blender using an Operator which is the typical way to define a tool accessed from menus, buttons and keyboard shortcuts.
For the first example we’ll make a script that simply moves all objects in a scene.
Add the following script to the text editor in Blender.
import bpy scene = bpy.context.scene for obj in scene.objects: obj.location.x += 1.0
Click the Run Script button, all objects in the active scene are moved by 1.0 Blender unit. Next we’ll make this script into an addon.
This addon takes the body of the script above, and adds them to an operator’s execute() function.
bl_info = { "name": "Move X Axis", "category": "Object", } import bpy class ObjectMoveX(bpy.types.Operator): """My Object Moving Script""" # blender will use this as a tooltip for menu items and buttons. bl_idname = "object.move_x" # unique identifier for buttons and menu items to reference. bl_label = "Move X by One" # display name in the interface. bl_options = {'REGISTER', 'UNDO'} # enable undo for the operator. def execute(self, context): # execute() is called by blender when running the operator. # The original script scene = context.scene for obj in scene.objects: obj.location.x += 1.0 return {'FINISHED'} # this lets blender know the operator finished successfully. def register(): bpy.utils.register_class(ObjectMoveX) def unregister(): bpy.utils.unregister_class(ObjectMoveX) # This allows you to run the script directly from blenders text editor # to test the addon without having to install it. if __name__ == "__main__": register()
Note
bl_info is split across multiple lines, this is just a style convention used to more easily add items.
Note
Rather than using bpy.context.scene, we use the context.scene argument passed to execute(). In most cases these will be the same however in some cases operators will be passed a custom context so script authors should prefer the context argument passed to operators.
To test the script you can copy and paste this into Blender text editor and run it, this will execute the script directly and call register immediately.
However running the script wont move any objects, for this you need to execute the newly registered operator.
Do this by pressing SpaceBar to bring up the operator search dialog and type in “Move X by One” (the bl_label), then press Enter.
The objects should move as before.
Keep this addon open in Blender for the next step - Installing.
Once you have your addon within in Blender’s text editor, you will want to be able to install it so it can be enabled in the user preferences to load on startup.
Even though the addon above is a test, lets go through the steps anyway so you know how to do it for later.
To install the Blender text as an addon you will first have to save it to disk, take care to obey the naming restrictions that apply to Python modules and end with a .py extension.
Once the file is on disk, you can install it as you would for an addon downloaded online.
Open the user File -> User Preferences, Select the Addon section, press Install Addon... and select the file.
Now the addon will be listed and you can enable it by pressing the check-box, if you want it to be enabled on restart, press Save as Default.
Note
The destination of the addon depends on your Blender configuration. When installing an addon the source and destination path are printed in the console. You can also find addon path locations by running this in the Python console.
import addon_utils print(addon_utils.paths())
More is written on this topic here: Directory Layout
For our second addon, we will focus on object instancing - this is - to make linked copies of an object in a similar way to what you may have seen with the array modifier.
As before, first we will start with a script, develop it, then convert into an addon..objects.link(obj_new) # Now we can place the object obj_new.location = cursor
Now try copy this script into Blender and run it on the default cube. Make sure you click to move the 3D cursor before running as the duplicate will appear at the cursor’s location.
... go off and test ...
After running, notice that when you go into edit-mode to change the cube - all of the copies change, in Blender this is known as Linked-Duplicates.
Next, we’re going to do this in a loop, to make an array of objects between the active object and the cursor.
import bpy from bpy import context scene = context.scene cursor = scene.cursor_location obj = scene.objects.active # Use a fixed value for now, eventually make this user adjustable total = 10 # Add 'total' objects into the scene for i in range(total): obj_new = obj.copy() scene.objects.link(obj_new) # Now place the object in between the cursor # and the active object based on 'i' factor = i / total obj_new.location = (obj.location * factor) + (cursor * (1.0 - factor))
Try run this script with with the active object and the cursor spaced apart to see the result.
With this script you’ll notice we’re doing some math with the object location and cursor, this works because both are 3D mathutils.Vector instances, a convenient class provided by the mathutils module and allows vectors to be multiplied by numbers and matrices.
If you are interested in this area, read into mathutils.Vector - there are many handy utility functions such as getting the angle between vectors, cross product, dot products as well as more advanced functions in mathutils.geometry such as bezier spline interpolation and ray-triangle intersection.
For now we’ll focus on making this script an addon, but its good to know that this 3D math module is available and can help you with more advanced functionality later on.
The first step is to convert the script as-is into an addon..objects.link(obj_new) factor = i / total obj_new.location = (obj.location * factor) + (cursor * (1.0 - factor)) return {'FINISHED'} def register(): bpy.utils.register_class(ObjectCursorArray) def unregister(): bpy.utils.unregister_class(ObjectCursorArray) if __name__ == "__main__": register()
Everything here has been covered in the previous steps, you may want to try run the addon still and consider what could be done to make it more useful.
... go off and test ...
The two of the most obvious missing things are - having the total fixed at 10, and having to access the operator from space-bar is not very convenient.
Both these additions are explained next, with the final script afterwards.
There are a variety of property types that are used for tool settings, common property types include: int, float, vector, color, boolean and string.
These properties are handled differently to typical Python class attributes because Blender needs to be display them in the interface, store their settings in key-maps and keep settings for re-use.
While this is handled in a fairly Pythonic way, be mindful that you are in fact defining tool settings that are loaded into Blender and accessed by other parts of Blender, outside of Python.
To get rid of the literal 10 for total, we’ll us an operator property. Operator properties are defined via bpy.props module, this is added to the class body.
# moved assignment from execute() to the body of the class... total = bpy.props.IntProperty(name="Steps", default=2, min=1, max=100) # and this is accessed on the class # instance within the execute() function as... self.total
These properties from.
In Blender addons have their own key-maps so as not to interfere with Blenders built in key-maps.
In the example below, a new object-mode bpy.types.KeyMap is added, then a bpy.types.KeyMapItem is added to the key-map which references our newly added operator, using Ctrl-Shift-Space as the key shortcut to activate it.
# store keymaps here to access after registration addon_keymaps = [] def register(): #(): # handle the keymap for km, kmi in addon_keymaps: km.keymap_items.remove(kmi) addon_keymaps.clear()
Notice how the key-map item can have a different total setting then the default set by the operator, this allows you to have multiple keys accessing the same operator with different settings.
Note
While Ctrl-Shift-Space isn’t a default Blender key shortcut, its hard to make sure addons won’t overwrite each others keymaps, At least take care when assigning keys that they don’t conflict with important functionality within Blender.
For API documentation on the functions listed above, see: bpy.types.KeyMaps.new, bpy.types.KeyMap, bpy.types.KeyMapItems.new, bpy.types.KeyMapItem.
bl_info = { "name": "Cursor Array", "category": "Object", } import bpy class ObjectCursorArray(bpy.types.Operator): """Object Cursor Array""" bl_idname = "object.cursor_array" bl_label = "Cursor Array" bl_options = {'REGISTER', 'UNDO'} total = bpy.props.IntProperty(name="Steps", default=2, min=1, max=100) def execute(self, context): scene = context.scene cursor = scene.cursor_location obj = scene.objects.active for i in range(self.total): obj_new = obj.copy() scene.objects.link(obj_new) factor = i / self.total obj_new.location = (obj.location * factor) + (cursor * (1.0 - factor)) return {'FINISHED'} def menu_func(self, context): self.layout.operator(ObjectCursorArray.bl_idname) # store keymaps here to access after registration addon_keymaps = [] def register(): bpy.utils.register_class(ObjectCursorArray) bpy.types.VIEW3D_MT_object.append(menu_func) #(): bpy.utils.unregister_class(ObjectCursorArray) bpy.types.VIEW3D_MT_object.remove(menu_func) # handle the keymap for km, kmi in addon_keymaps: km.keymap_items.remove(kmi) addon_keymaps.clear() if __name__ == "__main__": register()
Run the script (or save it and add it through the Preferences like before) and it will appear in the menu.
After selecting it from the menu, you can choose how many instance of the cube you want created.
Note
Directly executing the script multiple times will add the menu each time too. While not useful behavior, theres nothing to worry about since addons won’t register them selves multiple times when enabled through the user preferences.
Addons can encapsulate certain functionality neatly for writing tools to improve your work-flow or for writing utilities for others to use.
While there are limits to what Python can do within Blender, there is certainly a lot that can be achieved without having to dive into Blender’s C/C++ code.
The example given in the tutorial is limited, but shows the Blender API used for common tasks that you can expand on to write your own tools.
Blender comes commented templates which are accessible from the text editor header, if you have specific areas you want to see example code for, this is a good place to start.
Here are some sites you might like to check on after completing this tutorial. | http://www.blender.org/documentation/blender_python_api_2_67_1/info_tutorial_addon.html | CC-MAIN-2014-15 | refinedweb | 2,069 | 56.15 |
Altair - Remove margin/padding on discrete X axis
One of the Altair charts on my Covid Vaccine Dashboards Streamlit app shows the % of first doses, but when I first created it there was some padding on the X axis that I wanted to remove. In this blog post we’ll learn how to do that.
Pre requisites
Let’s start by installing the following libraries:
pip install pandas altair altair_viewer
Next let’s import them, as shown below:
import pandas as pd import altair as alt
Visualising % of first doses
Now we’re going to create a DataFrame that contains two columns - one contains the year and week number, the other the percentage of 1st doses administered.
df = pd.DataFrame({ 'dateWeek': ['2021-02', '2021-03', '2021-04', '2021-05', '2021-06', '2021-07', '2021-08', '2021-09', '2021-10', '2021-11', '2021-12', '2021-13'], 'percentageFirstDose': [95.53223579198118, 99.05357715009595, 99.29015227195728, 99.3040526396809, 99.17822125167659, 97.17701207004448, 93.13782375333588, 86.52577108509273, 80.75997640077365, 84.62332165884469, 67.53684465759456, 46.83433617577248] }) df
Next we’ll create a line chart using the Altair visualisation libray:
chart = (alt.Chart(df, padding={"left": 10, "top": 10, "right": 10, "bottom": 10}) .mark_line(point=True) .encode( x=alt.X("dateWeek"), y=alt.Y('percentageFirstDose', axis=alt.Axis(title='% first dose'))) .properties(title="% of first doses by week")) chart.show()
As we can see, this diagram has a padding/margin on either side of the X axis that I wanted to remove.
After trying out a lot of things that didn’t solve the problem, I came across a suggestion by Eitan Lees to set the
Scale of the X axis.
We can remove all padding by setting that value to 0, as shown below:
chart = (alt.Chart(df, padding={"left": 10, "top": 10, "right": 10, "bottom": 10}) .mark_line(point=True) .encode( x=alt.X("dateWeek", scale=alt.Scale(padding=0)), y=alt.Y('percentageFirstDose', axis=alt.Axis(title='% first dose'))) .properties(title="% of first doses by week")) chart.show()
Job. | https://www.markhneedham.com/blog/2021/04/02/altair-discrete-x-axis-margin-padding/ | CC-MAIN-2021-21 | refinedweb | 334 | 60.75 |
Created on 2017-06-07 15:21 by pitrou, last changed 2017-06-30 08:37 by pitrou. This issue is now closed.
The documentation for multiprocessing.exitcode says:
"""
The child’s exit code. This will be None if the process has not yet terminated. A negative value -N indicates that the child was terminated by signal N.
"""
This is true for the "fork" method, but not "forkserver" where a child terminated by a signal will get an exitcode of 255. This is because forkserver relies on the child writing its own exit code in a pipe, which obviously doesn't work if it was killed (255 is simply a fallback value).
See forkserver's Popen.poll():
def poll(self, flag=os.WNOHANG):
if self.returncode is None:
from multiprocessing.connection import wait
timeout = 0 if flag == os.WNOHANG else None
if not wait([self.sentinel], timeout):
return None
try:
self.returncode = forkserver.read_unsigned(self.sentinel)
except (OSError, EOFError):
# The process ended abnormally perhaps because of a signal
self.returncode = 255
return self.returncode
New changeset dfd5f34634f9c505945e9348b4b799544680a7cf by Antoine Pitrou in branch 'master':
Fix bpo-30589: improve Process.exitcode with forkserver (#1989)
I've merged a fix for Python 3.7. Since the fix is a bit delicate, I don't want to risk regression by merging it into 3.6 and 3.5. Closing now.
In the end, I'm glad I added a stress test (test_many_processes) as part of this issue.
It helper uncover a serious reliability issues in CPython's delivery of signals () and then triggered the discovery of a more minor bug in our setitimer() wrapper ().
Hopefully signal processing is more reliable in Python now! | https://bugs.python.org/issue30589 | CC-MAIN-2018-13 | refinedweb | 279 | 61.12 |
NAME
Allocate a new subregion.
SYNOPSIS
#include <zircon/syscalls.h> zx_status_t zx_vmar_allocate(zx_handle_t parent_vmar, zx_vm_option_t options, size_t offset, size_t size, zx_handle_t* child_vmar, zx_vaddr_t* child_addr);
DESCRIPTION
Creates a new VMAR within the one specified by parent_vmar.
options is a bit vector that contains one more of the following:
- ZX_VM_COMPACT A hint to the kernel that allocations and mappings within the newly created subregion should be kept close together. See the NOTES section below for discussion.
- ZX_VM_SPECIFIC Use the offset to place the mapping, invalid if vmar does not have the ZX_VM_CAN_MAP_SPECIFIC permission. offset is an offset relative to the base address of the parent region. It is an error to specify an address range that overlaps with another VMAR or mapping.
- ZX_VM_CAN_MAP_SPECIFIC The new VMAR can have subregions/mappings created with ZX_VM_SPECIFIC. It is NOT an error if the parent does not have ZX_VM_CAN_MAP_SPECIFIC permissions.
- ZX_VM_CAN_MAP_READ The new VMAR can contain readable mappings. It is an error if the parent does not have ZX_VM_CAN_MAP_READ permissions.
- ZX_VM_CAN_MAP_WRITE The new VMAR can contain writable mappings. It is an error if the parent does not have ZX_VM_CAN_MAP_WRITE permissions.
- ZX_VM_CAN_MAP_EXECUTE The new VMAR can contain executable mappings. It is an error if the parent does not have ZX_VM_CAN_MAP_EXECUTE permissions.
offset must be 0 if options does not have ZX_VM_SPECIFIC set.
In addition, the following power-of-two alignment flags can added:
- ZX_VM_ALIGN_1KB aligns child_addr to a power-of-2 at least 1K bytes.
- ZX_VM_ALIGN_2KB aligns child_addr to a power-of-2 at least 2K bytes.
- ZX_VM_ALIGN_4KB aligns child_addr to a power-of-2 at least 4K bytes.
- ZX_VM_ALIGN_8KB aligns child_addr to a power-of-2 at least 8K bytes.
and continues up to
- ZX_VM_ALIGN_4GB aligns child_addr to a power-of-2 at least 4G bytes.
TODO(ZX-3978): Currently, alignment flags greater than 4KB cannot be used when allocating a new VMAR within a compact VMAR.
Using ZX_VM_ALIGN flags with ZX_VM_SPECIFIC will fail if the parent_vmar base address + offset are not aligned to the requested value.
RIGHTS
If options & ZX_VM_CAN_MAP_READ, parent_vmar must be of type ZX_OBJ_TYPE_VMAR and have ZX_RIGHT_READ.
If options & ZX_VM_CAN_MAP_WRITE, parent_vmar must be of type ZX_OBJ_TYPE_VMAR and have ZX_RIGHT_WRITE.
If options & ZX_VM_CAN_MAP_EXECUTE, parent_vmar must be of type ZX_OBJ_TYPE_VMAR and have ZX_RIGHT_EXECUTE.
RETURN VALUE
zx_vmar_allocate() returns ZX_OK, the absolute base address of the
subregion (via child_addr), and a handle to the new subregion (via
child_vmar) on success. The base address will be page-aligned and non-zero.
In the event of failure, a negative error value is returned.
ERRORS
ZX_ERR_BAD_HANDLE parent_vmar is not a valid handle.
ZX_ERR_WRONG_TYPE parent_vmar is not a VMAR handle.
ZX_ERR_BAD_STATE parent_vmar refers to a destroyed VMAR.
ZX_ERR_INVALID_ARGS child_vmar or child_addr are not valid, offset is non-zero when ZX_VM_SPECIFIC is not given, offset and size describe an unsatisfiable allocation due to exceeding the region bounds, offset or size is not page-aligned, or size is 0.
ZX_ERR_NO_MEMORY This may be due to the following:
- A free address range of the requested size is not available within parent_vmar.
- The system is out of memory resources.
ZX_ERR_ACCESS_DENIED Insufficient privileges to make the requested allocation.
NOTES
Deallocation
The address space occupied by a VMAR will remain allocated (within its
parent VMAR) until the VMAR is destroyed by calling
zx_vmar_destroy().
Note that just closing the VMAR's handle does not deallocate the address space occupied by the VMAR.
The COMPACT flag
The kernel interprets this flag as a request to reduce sprawl in allocations. While this does not necessitate reducing the absolute entropy of the allocated addresses, there will potentially be a very high correlation between allocations. This is a trade-off that the developer can make to increase locality of allocations and reduce the number of page tables necessary, if they are willing to have certain addresses be more correlated. | https://fuchsia.dev/fuchsia-src/reference/syscalls/vmar_allocate | CC-MAIN-2020-29 | refinedweb | 627 | 56.86 |
.
Could someone tell me what the below means?
localhost /usr/lib/gdm3/gdm-x-session[2965]: (II) SYN_DROPPED event
from "HID 1241:1166" - some input events have been lost.
Hello list,
i'im using that lines in a Makefile.am for my new project:
# AppData
@INTLTOOL_XML_RULE@
@APPSTREAM_XML_RULES@
appdatadir = $(datadir)/appdata
appdata_in_files = org.gnome.Publisher.appdata.xml.in
appstream_XML = $(appstream_in_files:.appdata.xml.in=.appdata.xml)
The created Makefile looks like:
# AppData
%.xml: %.xml.in $(INTLTOOL_MERGE) $(wildcard
$(top_srcdir)/po/*.po) ; $(INTLTOOL_V_MERGE)LC_ALL=C $(INTLTOOL_MERGE)
$(INTLTOOL_V_MERGE_OPTIONS) -x -u -c
$(top_builddir)/po/.intltool-merge-cache $(top_srcdir)/po $< $@
@APPSTREAM_XML_RULES@
org.gnome.Publisher.gresour
All,
I don't know where this should be asked or directed, but within the past
week or so, MinGW update its gcc from 5.x to 6.3. As a result, when building
gtk apps on windows using the old binaries from:
<a href="" title=""></a>
gobject/gparam.h now generates warnings about using '1 << 31` not being a
integer value (and it isn't as it exceeds INT_MAX by 1).
Hi
I login to session with GDM. I then open gedit. Documents I save all have rw-r--r--.
I have tried setting umask to 077 at /etc/login.defs, ~/.profile, ~/.gnomerc, ~/.xsessionrc. None of these have any effect.
It appears systemd now manages umask in gnome 3.22. Can someone please describe how I can change the default umask setting?
Hello,
opensuse 42.3
linux 4.4.76-1-default x86_64
gnome 3.20.2
After upgrading from 42.2 to 42.3 the system now has Inkscape set as
the default PDF viewer, a poor choice.
At one time ISTR the apps were set using the Tweak Tool. Not so any
longer.
Where might I find the assignment of default applications?
Hello everyone!
Nautilus file manager (currently ver. 3.22.3-1 in Debian 9 with Gnome
desktop) offers the Recent files list.
As a user who is used to the recent files feature in some popular
applications (e.g. LibreOffice, MS Office, MS Windows Explorer) I
would expect it to work as a FIFO (first in, first out) structure: the
most recently opened document goes on top of the list and pushes the
previous list members downwards.
opensuse 42.2
linux 4.4.74-18.20-default x86_64
gnome 3.20.2
Whenever I connect a camera (a Nikon) with a USB port, two camera
icons appear on the desktop. They are mirrors; whatever is done with one
icon is shadowed with the other.
Is there a way to have only one icon for cameras?
Hello,
I'm using GNOME 3.22.2 as shipped with Debian 9. I find that the old
Character Map (gucharmap, I assume), which was the default character map
application in GNOME 2 has been replaced with a new generation JavaScript
one.
It looks cool, but doesn't show any non-English letter unless you
explicitly search for it. What was the cause for this replacement?
I didn't find anything related to the character map application on
gnome.org to file a bug, and that's why I'm using this list. Should I use
some other list?
Could someone explain to me what this is about.
<a href="" title=""></a>
It intermittently keeps getting written multiple times to my syslog.
System is Ubuntu 16.04.2 LTS Gnome Shell
apt-cache policy gnome-shell
gnome-shell:
Installed: 3.18.5-0ubuntu0.2
Candidate: 3.18.5-0ubuntu0.2
Version table:
*** 3.18.5-0ubuntu0.2 500
500 <a href="" title=""></a> xenial-updates/universe
amd64 Packages
100 /var/lib/dpkg/status
3.18.4-0ubuntu3 500
500 <a href="" title=""></a> xenial/universe amd64
Packages
I am using the en_US locale. I need LC_CURRENCY, LC_NUMERIC, AND
LC_PAPER to be formatted per the en_US locale. But I need LC_TIME and
LC_MEASUREMENT set to international standards (e.g., en_DK). I can set
this in Debian, but the GNOME DE overrides it and prevents it within the
GNOME DE. So why does GNOME not allow the changing of formats within a
locale? Settings > Region & Language only allows changing the locale.
Different locales give different formats but do not allow using U.S.
locale with Denmark's date format (for example). Why not?
I
I currently have GIMP 2.6.11 installed on a Dell D600 running WinXP, but
would like to update to the latest possible version. How do I do that?
Thanks!!
Dear.
Hi to all the gnome-dev and to all the member of this mailing list,
I want to emit some critics about gnome, for enhancing this wonderful
desktop, which will be the default desktop For Ubuntu next, Unity is out !
"All was OK in Gnome 3.18"
Then comes the problems as I update with the ppa gnome3-staging
1. The functionality for compressing a folder only propose 3 compressing
algorithms.
Before you get a combo box where you can choose from plenty of algorithms.
2..
<a href="" title="">...</a>
My syslog is filling up with these lines:
localhost org.gnome.Shell.desktop[3485]: (gnome-shell:3485): GLib-
GObject-CRITICAL **: g_object_set: assertion 'G_IS_OBJECT (object)'
failed
localhost org.gnome.Shell.desktop[3485]: (gnome-shell:3485): GLib-
GObject-CRITICAL **: g_object_set: assertion 'G_IS_OBJECT (object)'
failed
localhost org.gnome.Shell.desktop[3485]: (gnome-shell:3485): Clutter-
CRITICAL **: clutter_layout_manager_get_child_meta: assertion
'CLUTTER_IS_LAYOUT_MANAGER (manager)' failed
My system is:
Distributor ID: Ubuntu
Description: Ubuntu 16.04.2 LTS
Release: 16.04
Codename:
Hello Gnome list,
I have a CentOS 7.3 OS with gnome 3.14.0 desktop.
Everything works perfectly, except my dualdisplay setup...
Displays work, I'm happy, but then when I don't use them for X min, they go
in suspend, and only the primary display comes back after typing/using the
mouse.
When I go to gnome settings->display I see my primary display active and my
secondary switched off. When I switch it on all works again...
How can I trigger this change on wake-up of display one?
Or maybe accomplish the same in some other way...
Thanks!
Best regards,
Geert
(sorry if it's not the correct mailing-list for this kind of discussions)
For the last few years, I've been the main developer of a program
called Paperwork ( <a href="" title=""></a> ;
<a href="" title=""></a> ).
I'm currently wondering, could Paperwork become part of the Gnome project ?
Quick presentation:
Paperwork is a personal document manager. It manages scanned documents
and PDFs. It's designed to be easy and fast to use.
opensuse 42.2
linux 4.4.49-16-default x86_64
gnome 3.20.2
firefox 52.0.0
I went to check for an extension update (OpenWeather) and was told to
install an extension (Gnome Shell Integration 8.2) and a program (GNOME
Shell integration for Chrome).
Since I am interested only in Firefox, I did not install the connector
for Chrome.
When I go to the Gnome extensions page, the following is displayed:
"An unexpected error occurred"
Gee. An "unexpected" error. The worst kind.
There is no further information. No log entries. Nothing.
Is there a fix for this?
First of all I am sorry if I am emailing this to a wrong address but I
could not find any other way to get my feature request out.
Iam sure that a lot people use gnome screenshot application for making
presentations or sending instructions. I would be nice to have way of
taking multiple screenshots without having to close and reopen
application itself.
What I would like to see is an option of going back to main screenshot
screen after pressing "copy to clipboard " right now application closes
and I have to reopen it to create another screenshot.
The entire syslog entry
Mar 6 18:59:44 localhost systemd[1]: Started CUPS Scheduler.
Mar 6 18:59:44 localhost gnome-settings-daemon.desktop[2530]: (gnome-
settings-daemon:2530): color-plugin-WARNING **: failed to connect to
device: Failed to connect to missing device
/org/freedesktop/ColorManager/devices/cups_HP_LaserJet_1020
Mar 6 18:59:44 localhost gnome-settings-daemon.desktop[2530]: (gnome-
settings-daemon:2530): color-plugin-WARNING **: failed to connect to
device: Failed to connect to missing device
/org/freedesktop/ColorManager/devices/cups_PDF
I have filed bug
The entire warning is below. This happens every seven minutes.
This e-mailing list looks like a graveyard of desperate GNOME questions.
Alexey.
Hello List,
is there any way to import bookmarks in epiphany from a file?
I'll checked the menu, but it looks like, that i just can save one url
as bookmark at a time. But now way to import more from a file.
Greetings
Sascha
--
Sascha Manns
Email: <a href="mailto:Sascha. ... at mailbox dot org">Sascha. ... at mailbox dot org</a> | Blog: <a href="" title=""></a>
GPG: 0x168428cdb1f20ab1
The complete notation in my syslog that is written about every two
minutes throughout an hour is:
Feb 24 15:02:03 localhost tracker-extract.desktop[3603]: (tracker-
extract:3603): dconf-CRITICAL **: unable to create file
'/run/user/1000/dconf/user': Permission denied. dconf will not work
properly.
Feb 24 15:04:05 localhost tracker-extract.desktop[3603]: (tracker-
extract:3603): dconf-CRITICAL **: unable to create file
'/run/user/1000/dconf/user': Permission denied. dconf will not work
properly.
I submitted this bug in Jan of this year on Ubuntu Launchpad - https://
bugs.launchpad.net/ubunt
Hi,
I'm having a hard time to configure the keyboard shortcuts of my new
gnome-shell 3.22 session.
I would like:
1- To bind "Emacs" to "Shift+Enter". For some reason it seemes to be
impossible to use Shift+enter for a shortcut. Is there a workaround ?
2- I used to have volume down and volume up in Ctrl+PageDown and
Ctrl+PageUp. I tried to use "amixer -q set Master 5%+ unmute" and
"amixer -q set Master 5%- unmute" for this (my config in Xfce) but both
cut the audio (while working from a terminal).
3- I am using ncmpcpp (mpd client) for music.
sorry for the encrypted mail. Used the false button.
Here the original message:
just now i'm a little bit irritated.
In that article <a href="" title=""></a>
it is proposed to remove all intltool stuff in the configs. Also it
should removed @INTLTOOL_DESKTOP_RULE@ and @INTLTOOL_XML_RULE@.
In this article <a href="" title=""></a>
omeSoftware it is mentioned to use that rules for managing the appdata
file.
But now, what to do?
just now i'm a little bit irritated.
In that article <a href="" title=""></a>
it is proposed to remove all intltool stuff in the configs. Also it
should removed @INTLTOOL_DESKTOP_RULE@ and @INTLTOOL_XML_RULE@.
But now, what to do? Is there any newer handling for the appdata files?
And is this the right list?
hi,
i'm trying to install a new login theme from gnome-look.org,
let us say this one for example:
i've followed this tutorial and succeed to change the background of the login page
<a href="" title="">...</a>
the tutorial states to decompile the gresource file at /usr/share/gnome-shell/gnome-shell-theme.gresource
then add an xml file with the <gresources> tag and all the other files in the new theme dir in a <file> tag,,, i was able to change the background
but my question is how to install t
This does not work, editing or creating a custom shortcut are for assigning
keyboard shortcuts to executable commands.
What i want to do is modify an hardcoded shortcut to an internal behaviour
Hi all,
After upgrading and got last version of Gnome+Wayland, it kind of mostly
broke Autokey (even login with Gnome3 on Xorg). After so much time spent
trying to get Command+c to copy instead of Control+c (i use a Mac keyboard
and frequently switch computers), i am at a point where i am about to get
rid of Gnome 3 altogether, just because it does not allow me to redefine
Cut Copy and Paste keyboard shortcuts.
hi,
i've recently updated my opensuse linux distro from leap 42.1 to 42.2
which come with gnome ver 3.20.2 (the prev came with 3.16.2)
my problem is the fonts in the new distro looks small, dense and blurry and really hearts my eyes
as i spend all of my time looking at the computer screen
if you look at the following pics you will see the different between the two versions:
<a href="" title=""></a>
<a href="" title=""></a>
the gnome-tweak-tool shows fonts are the same in both versions which isn't true(i think):
<a href="" title=""></a>
my question is
1-how can
When I have a lot of projects going concurrently, I try to set up
different things on different workspaces. One particular project or
activity may have 3 to 5 workspaces.
Is there a way to group the workspaces and have the workspace switcher
emphasize workspaces in the group that I'm currently interested in?
Is there also a way to put labels on the workspaces in the switcher, or
to colour-code them, e.g.
In the bottom bar within gnome I have a lot of apps open and running.
There are so many that, unfortunately, the buttons aren't very wide and
consequently there are displayed only the icons for the and I can't see
the relevant file names.
Distro is Ubuntu 16.04.1 LTS Gnome version info:
Installed: 3.20.1-1ubuntu2~ubuntu16.04.1
Candidate: 3.20.1-1ubuntu2~ubuntu16.04.1
Version table:
*** 3.20.1-1ubuntu2~ubuntu16.04.1 500
500 <a href="" title=""></a>
xenial/main amd64 Packages
100 /var/lib/dpkg/status
3.18.3-0ubuntu2 500
500 <a href="" title=""></a> xenial/universe amd64
Packages
What I get in syslog is:
Nov 21 03:33:26 localhost systemd[1]: Started CUPS Scheduler.
Nov 21 03:33:27 localhost gnome-settings-daemon.desktop[2456]: (gnome-
settings-daemon
Dear gnome-list mailing list subscribers,
I would like to say that the name for the Yelp help viewer for GNOME may
have came, if not from a passage of similar lineage, from the following
passage from the television cartoon film short based on Dr. Seuss'
"Horton Hears a Who!":
"He was splashing, enjoying the jungle's great joys,
When Horton, the elephant, heard a small noise.
. .
opensuse 42.1
gnome 3.16.2
A lot of these errors are logged in /var/log/messages. What are the
consequences of the error? Is there anything to do?
2016-11-14T15:30:35.060434-07:00 sma-station14l gnome-session[3448]:
(gnome-shell:3521): Clutter-CRITICAL **: clutter_text_get_editable:
assertion 'CLUTTER_IS_TEXT (self)' failed
i have encountered a strange problem after upgrading NixOS from 16.03 to
16.09, which upgraded gnome-shell from 3.18.3 to 3.20.3: i cannot log in
with GNOME anymore.
I can still log in from console or with other graphical desktop
managers.
What is strange is that i have a second test account, and i still can
log into that account with GNOME.
What could be a cause for this behavior?
I'm using GNOME 3 on a Debian jessie laptop system
I've observed that when I connect and disconnect an external monitor
(either on VGA or DisplayPort), all the workspaces/virtual desktops are
merged into one and it becomes impossible to move windows to other
workspaces
When I move the mouse over the "Activities" button at the top of the
screen, I can still see the workspace switcher on the right hand side,
it only shows two workspaces, one with all the windows and a second one
that has an empty desktop background.
Dear gnome-list,
Here are two questions about the Permissions tab of folder Properties:
1. Why does the 'Other' group have 'Access files' permission?
2. Why is the 'Security context' listed as 'unknown'?
Please see screenshot: <a href="" title=""></a>
This is from Debian 8.6, newly installed and accepting all defaults.
Hello,
opensuse 42.1
gnome 3.16.2
I occasionally get a burst of the error below in </var/log/messages>.
At some point is the near future, when opening a program, Gnome freezes
solid.
The OS itself continues to function normally; there is no GUI making
the OS's functioning useless. A reboot is required. (well, I could go to
another computer, remotely log in, kill the Gnome process, return to my
workstation, log in again.
Wayland has supported mixed DPI for a good while, but requires the window manager (compositor?) to support it as well. Could someone tell me whether does current Gnome 3 support it or not? There is some, mainly quite old information available on the net. The best I could find was a Phoronix article earlier this year (1) that claimed that Gnome 3.22 was to contain some improvements.
1) <a href="" title="">...</a> (<a href="" title="">...</a>)
Fedora 25 is AFAIK going to ship Gnome 3.23.
Hi,
While HiDPI works a lot better nowadays, there are still some parts
that needs a bit more polish. I use a ThinkPad X1 Carbon 4th gen, with
a 1440p 14" screen which gives about 210 PPI. To get reasonable UI
that isn't too big or too small I use Window scaling of 1, and a
Scaling Factor of 0.5, with fonts in Gnome, Emacs and RXVT set to
16px.
When I get to work and connect my Dell 28" 3840x2160 monitor at about
160 PPI, I've configured my setup to disable the laptop monitor as I
only use that external screen. What I get to now is the need-of-polish
part.
Folks;
as I just discovered getpocket.com for keeping reading lists in sync, I also found out I can add a
Pocket account to my GNOME Online Accounts. Fine... but how can I actually use it, then, in GNOME?
How to add links to it, or how to access any resources stored there?
TIA and all the best,
Kristian
Long story short, I setup KDE plasma mobile in lxc with a cyanogenmod back end on my nexus, and it worked. Still wishing for some gnome love, I said hey, let's install gnome into that lxc container too. Added it to the display manager, and low and behold, gnome 3.20 worked with little effort. Yes, a good amount of tweaking is necessary to make it useable on the screen, it is not perfect out of the box by any means.
Question now is, since gnome will run similar to how KDE plasma mobile is doing it, was any discussion ever held on pushing into the mobile space?
In previous versions of gnome-shell it was possible to do a lot of
tweaking through the .js files.
I've noticed that the following script
from PyQt4.QtGui import QDialog, QVBoxLayout, QApplication, QLabel
import sys
class DateDialog(QDialog):
def __init__(self, parent = None):
super(DateDialog, self).__init__(parent)
layout = QVBoxLayout(self)
self.mlabel = QLabel(self)
self.mlabel.setText("a"*2000)
layout.addWidget(self.mlabel)
def main():
app = QApplication(sys.argv)
w = DateDialog()
w.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Hi GNOME team!!
Hello, I am ASML engineer and found your e-mail address through panel help document..
We are suffered from panel for MSC(=2, Master System Controller, one of our PC). We can`t see panel for MSC..
As you can see, We use both DAS(=1) and MSC(=2). DAS(=1) show panel correctly.
*Hi,*
*We have a corba based server application developed on Orbitcpp built on
linux, currently we are facing issue with inter process communication where
the behavior is the parent to wait for the child process to complete the
execution and then the parent continues.
Folks,
using GNOME calendar, is it possible to add people to a scheduled event
and send out invites? I know that evolution manages to do this but I'd
prefer using the calendar app for that as it seems a bit more usable
"just" for calendaring tasks. ;)
TIA,
Kristian | http://www.devheads.net/desktop/gnome | CC-MAIN-2017-47 | refinedweb | 3,350 | 67.15 |
Welcome to Dynamic Tracing in the Solaris Operating System! If you have ever wanted to understand the behavior of your system, DTrace is the tool for you. DTrace is a comprehensive dynamic tracing facility that is built into. from?:
It might take some time to display all of the output. To count up all your probes, you can type the command:.
When you write traditional programs in JavaTM.
Our next example program makes use of the DTrace profile provider to implement a simple time-based counter. The profile provider is able to create new probes based on the descriptions found in your D program. If you create a probe named profile:::tick-nsec for some integer n, the profile provider will create Control-C, and then prints the total at the Chapter 2, Chapter 2, Chapter.
System call tracing is a powerful way to observe the behavior of most user processes. If you've used the:
syscall::read:entry, syscall::write:entry /pid == $1/ { printf("%s(%d, 0x%x, %4d)", probefunc, arg0, arg1, arg2); } syscall::read:return, syscall::write:return /pid == $1/ { printf("\t\t = %d\n", 12, Chapter\t = %d kernel, so in addition to accessing special DTrace variables and probe arguments, you can also access kernel data structures, symbols, and types. These capabilities enable advanced DTrace users, administrators, service personnel, and driver developers to examine low-level behavior of the operating system kernel and device drivers. The reading list at the start of this book includes books that can help you learn more about more information about kmem_flags. This tunable is declared in C in the kernel source code as follows:
int kmem_flags;
To trace the value of this variable in a D program, you can write the D statement:
trace(`kmem_flags);
DTrace associates each kernel symbol with the type used for it in the corresponding operating system C code, providing easy source-based access to the native operating system data structures. Kernel symbol names are kept in a separate namespace from D variable and function identifiers, so you never need to worry about these names conflicting with your D variables.
You have now completed a whirlwind tour of DTrace and you've learned many of the basic DTrace building blocks necessary to build larger and more complex D programs. The following chapters describe the complete set of rules for D and demonstrate how DTrace can make complex performance measurements and functional analysis of the system easy. Later, you'll see how to use DTrace to connect user application behavior to system behavior, giving you the capability to analyze your entire software stack.
You've only just begun! | http://docs.oracle.com/cd/E19082-01/819-3620/6n5r1fv90/index.html | CC-MAIN-2014-23 | refinedweb | 440 | 57.81 |
RDF::Trine::Parser::Turtle - Turtle RDF Parser
This document describes RDF::Trine::Parser::Turtle version 1.019
use RDF::Trine::Parser; my $parser = RDF::Trine::Parser->new( 'turtle' ); $parser->parse_into_model( $base_uri, $data, $model );
This module implements a parser for the Turtle RDF format.
Beyond the methods documented below, this class inherits methods from the RDF::Trine::Parser class.
new ( [ namespaces => $map ] )
Returns a new Turtle parser.
parse ( $base_uri, $rdf, \&handler )
Parses the bytes in
$data, using the given
$base_uri. Calls the
triple method for each RDF triple parsed. This method does nothing by default, but can be set by using one of the default
parse_* methods.
parse_file ( $base_uri, $fh, $handler )
Parses all data read from the filehandle or file
$fh, using the given
$base_uri. If
$fh is a filename, this method can guess the associated parse. For each RDF statement parses
$handler is called.
parse_node ( $string, $base, [ token => \$token ] )
Returns the RDF::Trine::Node object corresponding to the node whose N-Triples serialization is found at the beginning of
$string. If a reference to
$token is given, it is dereferenced and set to the RDF::Trine::Parser::Turtle::Token tokenizer object, allowing access to information such as the token's position in the input. | http://search.cpan.org/dist/RDF-Trine/lib/RDF/Trine/Parser/Turtle.pm | CC-MAIN-2018-09 | refinedweb | 204 | 56.15 |
yt_analysis is sharing code with you
Bitbucket is a code hosting site. Unlimited public and private repositories. Free for small teams.Don't show this again
- Overview
- Downloads (0)
- Pull requests (2)
- Source
- Commits
- Wiki
- Issues (39) »
Commit 9f8fb27e2fc1 Raw commit »
- commit
- 9f8fb27e2fc1
- parent
- a332a51c273f
- branch
- yt
Fixes to Gadget data from the GDF format. Mostly stylistic, but also set the
particle fields to be recognized as such, which means they can be accessed
directly. This script should now work:
import yt.frontends.gadget.data_structures as gds
file='decay_100.gyt.hdf5'
gf = gds.GadgetStaticOutput(file)
dd = gf.h.all_data()
px = dd["particle_position_x"]
Log in to comment » | http://hg.yt-project.org/yt/changeset/9f8fb27e2fc1 | crawl-003 | refinedweb | 106 | 53.58 |
Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Comparing and Combining Dice5:41 with Kenneth Love
Dice are great but we need to be able to find ones that fit certain criteria, like being greater than four. It'd also be handy to be able to add dice together. We can do both of these things using magic methods!
If you want to get a lot of magic method goodies easily, check out
attrs. It's a solid library and makes a lot of common usages much easier.
Or, to stick with the standard library, check out the docs for
functools.total_ordering. You need to define
__eq__ and then one of the other operations and Python will figure out the rest.
Before you ask
Yes, I could have done something like:
def __le__(self, other): return int(self) <= other
Either format (long or short) is fine and produces the same result.
- 0:00
That's a great basic dye class, but we need to be able to do a lot more with it.
- 0:04
We've already added our D6 class to always have six sided dice.
- 0:07
If we're playing a lot of dice games, though, we need the sum total of our dice.
- 0:10
We really want to be able to compare dice to each other, or to another number too,
- 0:14
so we can find all the dice that have a value over four, or something.
- 0:18
We can accomplish all of these tasks with a few magic methods.
- 0:21
Great, let's get to it.
- 0:23
Okay, I wanna start with our equality comparison.
- 0:26
We can do an equality comparison, so double equals, stuff like that, with just
- 0:31
one magic method, but I'd like to be able to compare with greater than, less than,
- 0:34
and all of their friends, that means we'll have to add a few more things in.
- 0:39
First, let's start with turning an instance of our die into an integer.
- 0:43
So, we'll say int self, and we'll return self.value.
- 0:48
Okay?
- 0:49
Because we always have an int there, simple, easy enough.
- 0:52
Okay, so now to do the equality stuff.
- 0:56
We need to define six different magic methods.
- 0:59
I like to do them in alternating pairs, so let's start with equals and not equals.
- 1:03
So def __eq__(self): return
- 1:07
int(self) == other, and I need to take other in here as well.
- 1:13
Okay, and then def __ne__ for not equals.
- 1:17
We take self and other, and let's just return not int(self) == other.
- 1:26
We can also do return int(self) != other.
- 1:31
Either one of those that you want to do.
- 1:37
All right?
- 1:38
Both of these, we turn this instance into an int, compare it to the other value.
- 1:41
I don't think we need to test this right off quick,
- 1:43
you can see what's going on here.
- 1:44
All right, so let's move on to greater than and less than.
- 1:48
So def __gt__, we take (self, other): and we return int(self) > other or
- 1:54
def __ lt__ for less than, return int self less than the other thing.
- 2:00
Again, turning our instance into an int and then comparing it to the other value.
- 2:07
And again, these are opposites of each other both in usage and
- 2:13
in their actual code, right?
- 2:15
We use greater than on one and we use less than on the other.
- 2:19
Okay one more pair to do which is the greater than or equal to and less than or
- 2:23
equal to.
- 2:25
So we define ge self and other.
- 2:30
Return int self greater than the other or int self is equal to the other.
- 2:37
And then def __le(self, other): return
- 2:42
int(self) < other or int(self) == other.
- 2:48
I kind of wish these were named gte and
- 2:52
lte instead of ge and le, but we can't always have everything we want, can we?
- 2:59
All right so let's test our operator methods.
- 3:04
All right let's get over here, we'll go into Python.
- 3:07
And say from dice import D6.
- 3:11
And we'll say d6 = D6().
- 3:15
And let's see what our d6 is.
- 3:18
I get 6 to the 6, great, all right, so d6 is less than 2.
- 3:24
False, that's right, it's not less than 2.
- 3:26
Our d6 is less than or equal to 2.
- 3:29
Nope, okay.
- 3:32
What about our d6 is greater than 1, that's true.
- 3:36
Is our d6 not equal to 4, that's also true.
- 3:39
And finally is our d6 equal to 6.
- 3:42
It is.
- 3:43
Okay.
- 3:44
Awesome.
- 3:44
Now you can add these to any class that you create.
- 3:47
They don't have to be related to numbers.
- 3:50
They can be strings or whatever.
- 3:52
But since ours is based on a number let's add in the ability to add them together.
- 3:57
Now I don't wanna do this in like in place of addition.
- 4:00
Because, well we wouldn't ever implace increment the value of a die,
- 4:06
but I do want to have add and r add.
- 4:11
So let's come down here def __add__(self,
- 4:17
other), return int(self) + other and
- 4:22
def __radd__(self, other).
- 4:27
And we could again just return self + other, or
- 4:31
we can do what we've been doing and say int (self) + other.
- 4:38
Those are exactly the same code, but that's what we need right there, right?
- 4:42
So no matter which some of the plus sign our die is on,
- 4:44
it should just add its value to the other objects value.
- 4:48
Okay.
- 4:48
So, we've got time to do one last test on this.
- 4:52
And then we'll move on to something more interesting.
- 4:56
From dice import d6.
- 4:59
And let's say d1 = D6 () and d2 = D6 ().
- 5:04
Int(d1) is 6 and int(d2) Is 4,
- 5:10
d1 + d2 is 10, d1 + 12, cuz I got a bonus, is 18.
- 5:15
And it works, so that's great.
- 5:18
Works just like we want it to,
- 5:19
and now I think we can do a lot more interesting things with our dice.
- 5:23
It can be a bit of a pain to declare all of those comparison methods.
- 5:27
If you think you need all of them, check out the ATTR's or
- 5:30
Atters package, which I've linked in the teacher's notes.
- 5:33
It makes things a bit easier at the expense of having another package to
- 5:35
install and use.
- 5:37
All right, let's look at creating a class to auto roll a set of dice for us. | https://teamtreehouse.com/library/comparing-and-combining-dice | CC-MAIN-2019-04 | refinedweb | 1,266 | 90.39 |
Log in to like this post! Using NetAdvantage jQuery Grid in ASP.NET MVC [Infragistics] Murtaza Abdeali / Monday, May 09, 2011 The NetAdvantage for jQuery product contains a client-side jQuery grid with an ASP.NET MVC Html Helper. The Helper makes it easy to new up the grid within your MVC views connecting to data form your model. In this blog, you will learn how to create a simple grid using the Razor syntax in your ASP.NET MVC view and connect to the data source. Setting up the project In order to get the grid to show up you will need the necessary JavaScript and CSS file on the client so that when the MVC helper generates the jQuery grid initialization code on the client, everything needed for the grid to display is available. When you create a new ASP.NET MVC 3 project it comes with Scripts and a Content folders where all the default JavaScript files and CSS contents are located respectively. We will use the same folder and insert the Infragistics Scripts & CSS. Note: These Scripts & CSS can be found under the Install location of NetAdvantage for jQuery. Next you want the project to be able to consume these references. You have two choices, use _Layout.cshtml and put everything there, or add reference on every page that uses an Infragistics control. I prefer to use the _Layout.cshtml because that way, I can just put this code at one place and don’t have to worry about it anymore in any other views I create that use Infragistics controls. The following code in the head section of _Layout.cshtml will be needed: <script src="" type="text/javascript"></script> <script src="" type="text/javascript"></script> <script type="text/javascript" src=""></script> <script src="@Url.Content("~/Scripts/IG/ig.ui.min.js")" type="text/javascript"></script> <link href="@Url.Content("~/Content/themes/base/jquery.ui.all.css")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("~/Content/IGStyles/base/ig.ui.editors.css")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("~/Content/IGStyles/base/ig.ui.grid.css")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("~/Content/IGStyles/ig/jquery.ui.custom.css")" rel="stylesheet" type="text/css" /> You will also have to add reference to the Infragistics.Web.Mvc assembly that contains the Html Helper we will use in our Razor view. This contains definitions for all the MVC helpers, so once you have added this to your project, you will be able to work with all the controls throughout the project. The project is now setup and we can build out MVC view with any Infragistics controls using the appropriate HTML Helper. For this blog, we will be using the Helper for the grid and have it display data coming from our Model. Model The ASP.NET MVC project has a default Model class called AccountModel.cs. In the same Model class, we will add a BankAccount object with some properties and a new AccountModels class that has a GetAccountList method which creates a list of BankAccout objects and returns them as a list of IQueryable objects. Using IQueryable object, the grid is able to natively perform operations like sorting, filtering and paging on the collection. You can use any type of collections, even web services to connect data and operate on the grid. The code we will add to AccountModel.cs class would be: public class BankAccount { public int AccountNumber { get; set; } public string AccountName { get; set; } public DateTime AccountDate { get; set; } public string AccountType { get; set; } public decimal AccountBalance { get; set; } } public class AccountModels { public static IQueryable<BankAccount> GetAccountList() { List<BankAccount> accountList = new List<BankAccount>(); DateTime date = DateTime.Now; for (int i = 1; i < 1001; i++) { accountList.Add(new BankAccount() { AccountNumber = i, AccountName = "Test" + i.ToString(), AccountDate = date, AccountType = "chk", AccountBalance = 12345678.90M } ); } return accountList.AsQueryable<BankAccount>(); } } View We have already referenced the JavaScript & CSS in _Layout.cshtml, so now we can get directly to writing our view code. We will be using the Razor syntax to create the grid in the Index.cshtml page that gets generated when you create a new ASP.NET MVC 3 project, and binding it to the BankAccount object collection in the model. In order to be able to do that, we will need to insert the following lines right at the top of our view. @using Infragistics.Web.Mvc; @using Mvc3WebApp.Models; Once we have these lines, we also get Visual Studtio intellisense that will make it easy to work with the helper and create views with the Infragistics jQuery grid or any other control. We can use the Html Helper to define grid properties, enable features and setup up the initial layout. We will begin with setting up column object, and setting some properties on it, enable paging, sorting & selection feature of the grid and use the “DataSourceUrl” property to connect it to the GetAccountList method which returns the list of BankAccount object. Finally we will call databind & render which is needed so that the grid can bind to its data source and render on the page. With all that, the helper will look like the following: @( Html.Infragistics().Grid<BankAccount>() .ID("igGrid1") .Columns(column => { column.For(x => x.AccountNumber).DataType("int").HeaderText("Account Number"); column.For(x => x.AccountName).DataType("string").HeaderText("Account Name"); column.For(x => x.AccountDate).DataType("date").HeaderText("Account Date"); column.For(x => x.AccountType).DataType("string").HeaderText("Account Type"); column.For(x => x.AccountBalance).DataType("number").HeaderText("Account Balance"); }) ); }) .ClientDataSourceType(ClientDataSourceType.JSON) .DataSourceUrl(Url.Action("GetAccountList")) .Width("100%") .Height("350") .LocalSchemaTransform(true) .DataBind() .Render() ) Controller The grid MVC helper above will call the GetAccountList() method in the controller to get the data to display in the grid. We can setup the method, make the call to the GetAccountList in our Model and return the view back to the grid, so that it has what it needs. The Controller method do so will be: [GridDataSourceAction] public ActionResult GetAccountList() { return View(Models.AccountModels.GetAccountList()); } That is it. You can run the project and it will show the Infragistics jQuery grid control, connected to the data coming from our Model. You can perform operations like paging, sorting and selection, and the grid will function as expected. Summary In this article, you learned how to get started with the Infragistics ASP.NET MVC Html Helper for the jQuery grid control. Add project references, use the new Razor syntax for the MVC view, you can connect the grid to the data in the model and have it perform paging and sorting operations on that data. You can download the sample code from here. If you have any questions on this blog, or questions in general about the Netadvantage for jQuery product, feel free to reach out to me. murtazaa@infragistics.com | https://www.infragistics.com/community/blogs/b/taz_abdeali/posts/using-netadvantage-jquery-grid-in-asp-net-mvc | CC-MAIN-2018-05 | refinedweb | 1,140 | 56.25 |
Preserving a linebuffer type in assignment
Having one other struggle here that I am hoping I could get some guidance on.
I have an indicator that I am porting that needs to track a min() value over a rolling window of 10 floats.
In the next() method for the indicator, I have a series of linebuffer values that I am updating from a PandasData feed.
The following bit of code is converting the type of linebuffer for this variable to float as soon as I assign the value to it as follows:
def __init__(self): self.dval1 = bt.linebuffer.LineBuffer() super(IND, self).__init__() def next(self): self.dval1 = min(self.data.low.get(size=10))
As soon as the min assignment happens, the self.dval1 is now type 'float'
How do I preserve that to allow me to get "slices" of these linebuffers for other calcs in next()?
- backtrader administrators last edited by backtrader
This is a non-expected usage pattern and for sure one which is not going to work.
LineBufferis an internal object which is not meant for user consumption. And of course
self.dval1is turning into a float, you are assigning a float to the member attribute you created yourself.
This is not the same as
self.lines.xxx = yyyduring the
__init__phase, because in that case
self.linesis an object, and
xxxis constructed by means of
Descriptors, which allows controlling things like assignment (via
__set__). But assignment cannot be controlled on a member attribute you have created.
The use case is actually a lot easier:
def __init__(self): self.dval1 = bt.ind.Lowest(self.data.low, period=10) # or bt.ind.MinN(self.data.low, period=10) def next(self): print('the current lowest value is:', self.dval1[0])
The indicator family is big and tries to cover all possible aspects | https://community.backtrader.com/topic/13/preserving-a-linebuffer-type-in-assignment/1 | CC-MAIN-2021-43 | refinedweb | 305 | 57.87 |
When i last time tried to add vectors i got nasty error (in dev-c++) that opens another file .cpp and cite the error, a line that has some iterator.
this is the code
Code:#include <iostream> #include <vector> using namespace std; int main() { //Making vectors vector<string> my; my.push_back("Car"); my.push_back("Boat"); my.push_back("Plane"); vector<string> yours; yours.push_back("Jet"); yours.push_back("Parachute"); yours.push_back("Wings"); vector<string> ours(my, yours); return 0; }
plz tell me how to add more than one vector (for example 5 vectors) in one vector ? do i have to specify the size of the vector that is having all the vectors ?? | http://cboard.cprogramming.com/cplusplus-programming/85522-adding-vectors.html | CC-MAIN-2014-41 | refinedweb | 110 | 64.41 |
Hello all, I am a maya user and I am trying to create a python script to generate cubes which represent the object space bounding boxes of objects.
For example, if I create random objects (sphere, cube, pyramid, cone, and etc) in Maya, I want to replace those selected objects with a cube which has the dimensions of that object's bounding box.
so if I create 3 different objects,
for instance , a cone, a sphere, and a pyramid, there should be three individual cubes that has bounding box of a cone, a sphere, and a pyramid.
I have to make cubes that has bounding box of the objects. just by executing the script.
here is the script that I tried to build, but I am stuck right after this
Steps that I followed:
1) create a sphere. (Manually by clicking the 'generate sphere button' on Maya program)
2) after step 1, this is the python script that I tried to build on
import maya.cmds as cmds
sel=cmds.ls(sl=True)
print sel
bbox = cmds.exactWorldBoundingBox(sel)
print bbox
cmds.polyCube() | http://forums.devshed.com/python-programming/955371-maya-python-help-asap-replacing-object-cube-last-post.html | CC-MAIN-2018-22 | refinedweb | 183 | 70.73 |
RxJS: Reactive Extensions For JavaScript
The Roadmap from RxJS 7 to 8The Roadmap from RxJS 7 to 8
Curious what's next for RxJS? Follow along with Issue 6367.
RxJS 7RxJS 7
THE 6.x BRANCHFOR 6.X PLEASE GO TO.
Versions In This RepositoryVersions In This Repository
- master - This is all of the current work, which is against v7 of RxJS right now
- 6.x - This is the branch for version 6.X
Most PRs should be made to master.
It's recommended to pull in the Observable creation methods you need directly from
'rxjs' as shown below with
range.
If you're using RxJS version 7.2 or above, you can pull in any operator you need from the same spot,
'rxjs'.
import { range, filter, map } from 'rxjs'; range(1, 200) .pipe( filter(x => x % 2 === 1), map(x => x + x) ) .subscribe(x => console.log(x));
If you're using RxJS version below 7.2, you can pull in any operator you need from one spot, under
'rxjs/operators'.
import { range } from 'rxjs'; import { filter, map } from 'rxjs/operators'; range(1, 200) .pipe( filter(x => x % 2 === 1), map(x => x + x) ) .subscribe(x => console.log(x));
CDNCDN
For CDN, you can use unpkg:^7/dist/bundles/rxjs.umd.min.js
The global namespace for rxjs is
rxjs:
const { range } = rxjs; const { filter, map } = rxjs.operators; range(1, 200) .pipe( filter(x => x % 2 === 1), map(x => x + x) ) .subscribe(x => console.log(x));
GoalsGoals
-Building/Testing
npm run compilebuild everything
npm testrun tests
npm run dtslintrun dtslint tests
Adding documentationAdding documentation
We appreciate all contributions to the documentation of any type. All of the information needed to get the docs app up and running locally as well as how to contribute can be found in the documentation directory. | https://www.npmjs.com/package/rxjs?ref=pkgstats.com | CC-MAIN-2022-33 | refinedweb | 301 | 68.36 |
In the previous post, we looked at loading in texture data from a PNG file and uploading it to an OpenGL texture, and then displaying that on the screen in Android. To do that, we used libpng and loaded in the data from our platform-independent C code.
In this post, we’ll add supporting files to our iOS project so we can do the same from there.
Prerequisites
To complete this lesson, you’ll need to have completed Loading a PNG into Memory and Displaying It as a Texture with OpenGL ES 2, Using (Almost) the Same Code on iOS, Android, and Emscripten. The previous iOS post, Calling OpenGL from C on iOS, Sharing Common Code with Android, covers setup of the Xcode project and environment.
You can also just download the completed project for this part of the series from GitHub and check out the code from there.
Adding the common platform code
The first thing we’ll do is add new supporting files to the common platform code, as we’ll need them for both iOS and emscripten. These new files should go in /airhockey/src/platform/common:
platform_file_utils.c
#include "platform_file_utils.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> FileData get_file_data(const char* path) { assert(path != NULL); FILE* stream = fopen(path, "r"); assert (stream != NULL); fseek(stream, 0, SEEK_END); long stream_size = ftell(stream); fseek(stream, 0, SEEK_SET); void* buffer = malloc(stream_size); fread(buffer, stream_size, 1, stream); assert(ferror(stream) == 0); fclose(stream); return (FileData) {stream_size, buffer, NULL}; } void release_file_data(const FileData* file_data) { assert(file_data != NULL); assert(file_data->data != NULL); free((void*)file_data->data); }
We’ll use these two functions to read data from a file and return it in a memory buffer, and release that buffer when we no longer need to keep it around. For iOS & emscripten, our asset loading code will wrap these file loading functions.
platform_log.c
#include "platform_log.h" #include <stdarg.h> #include <stdlib.h> #include <stdio.h> #define LOG_VPRINTF(priority) printf("(" priority ") %s: ", tag); \ va_list arg_ptr; \ va_start(arg_ptr, fmt); \ vprintf(fmt, arg_ptr); \ va_end(arg_ptr); \ printf("\n"); void _debug_log_v(const char *tag, const char *fmt, ...) { LOG_VPRINTF("VERBOSE"); } void _debug_log_d(const char *tag, const char *fmt, ...) { LOG_VPRINTF("DEBUG"); } void _debug_log_w(const char *tag, const char *fmt, ...) { LOG_VPRINTF("WARN"); } void _debug_log_e(const char *tag, const char *fmt, ...) { LOG_VPRINTF("ERROR"); }
For iOS and emscripten, our platform logging code just wraps around
printf.
Updating the iOS code
There’s just one new file that we we need to add to the ios group in our Xcode project, platform_asset_utils.m:
#include "platform_asset_utils.h" #include "platform_file_utils.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> FileData get_asset_data(const char* relative_path) { assert(relative_path != NULL); NSMutableString* adjusted_relative_path = [[NSMutableString alloc] initWithString:@"/assets/"]; [adjusted_relative_path appendString: [[NSString alloc] initWithCString:relative_path encoding:NSASCIIStringEncoding]]; return get_file_data( [[[NSBundle mainBundle] pathForResource:adjusted_relative_path ofType:nil] cStringUsingEncoding:NSASCIIStringEncoding]); } void release_asset_data(const FileData* file_data) { assert(file_data != NULL); release_file_data(file_data); }
To load in an asset that’s been bundled with the application, we first prefix the path with ‘/assets/’, and then we use the
mainBundle of the application to get the path for the resource. Once we’ve done that, we can use the regular file reading code that we’ve defined in platform_file_utils.c.
iOS experts: When I was researching how to do this, I wasn’t sure if this was the best way or even the right way, but it does seem to work. I’d love to know if there’s another way to do this that is more appropriate, perhaps just by grabbing the path of the application and concatenating that with the relative path?
Aside from adding this new file, we just need to add some references to the project and then we’ll be able to compile & run the app.
Adding the libpng files
Right-click the project and select Add Files to “Air Hockey”…. Add the following C files from the libpng folder, and add them as a new folder group:
Remove the common folder group that may be left there from the last lesson, and then add all of the files from the core folder as a new folder group. Do the same for all of the files in /platform/common. Finally, add the assets folder as a folder reference, not as a folder group. That will link the assets folder directly into the project and package those files with the application.
We’ll also need to link to libz.dylib. To do this, click on the ‘airhockey’ target, select Build Phases, expand Link Binary With Libraries, and add a reference to ‘libz.dylib’.
The Xcode Project Navigator should look similar to the below:
It might make more sense to link in the libpng sources as a static library somehow, but I found that this compiled very fast even from a clean build. Once you run the application in the simulator, it should look similar to the following image:
Now the same code that we used in Android is running on iOS to load in a texture, with very little work required to customize it for iOS! One of the advantages of this approach is that we can also take advantage of the vastly superior debugging and profiling capabilities of Xcode (as compared to what you get in Eclipse with the NDK!), and Xcode can also build the project far faster than the Android tools can, leading to quicker iteration times.
Exploring further
The full source code for this lesson can be found at the GitHub project. In the next post, we’ll also cover an Emscripten target, and we’ll see that it also won’t take much work to support. As always, let me know your feedback.
.
4 thoughts on “Loading a PNG into Memory and Displaying It as a Texture with OpenGL ES 2: Adding Support for iOS” | http://www.learnopengles.com/loading-a-png-into-memory-and-displaying-it-as-a-texture-with-opengl-es-2-adding-support-for-ios/ | CC-MAIN-2015-27 | refinedweb | 971 | 63.29 |
Hide Forgot
Description of problem:
Mar 19 15:36:30 grampi avahi-daemon[17498]: chroot.c: fork() failed: Resource temporarily unavailable
Mar 19 15:36:30 grampi avahi-daemon[17498]: failed to start chroot() helper daemon.
Adjusting rlimit-nproc=2 to higher number in /etc/avahi/avahi-daemon.conf
fixes this issue.
Version-Release number of selected component (if applicable):
avahi-0.6.31-30.fc21.x86_64
How reproducible:
Always
To reproduce start LXC container and try running avahi-daemon along with avahi-daemon running on host.
If there are avahi-daemons running in LXC then it even prevents starting of avahi-daemon on host.
I don't think there is anything which can be done about this in avahi. In struct_user in kernel there is a field,
atomic_t processes; /* How many processes does this user have? */
Setting rlimit_nproc will set this field to two. Since avahi service by default spawns two processes then once you start it in container which *does not* use user namespace then you are screwed because you exhausted your limit which is per user. Then you can't start avahi on the host nor in any other container you might have.
To prevent this unfortunate behavior you can of course use user_ns. However once you go this road note that you are entering another realm of pain with current user_ns implementation.
I'd say you'll be better off setting rlimit-nproc to higher number. | https://bugzilla.redhat.com/show_bug.cgi?id=1203731 | CC-MAIN-2019-39 | refinedweb | 240 | 65.83 |
STREET RAILROADS OF NEW OR
LEANS.
RAILWAIY GUIDE TO PLACE. OP IN
TERFNT.
We take the following from Hardee'4 inap of
thIs (tity:
The Clay Statue, situated on Canal street, at
the junction of St. Charles a;d teoyal, is the
grand central landmark of Nhw Orleans.
From this point and its vicinity radiate all
the lines of street railroads.
CANAL BTREET LINK.
The horse ears on the Lake side of the Clay
Statue marked "tidge Cemeteries" convey
aessengers out Canal street to the Half- Way
House, a distance of about three and a hell
miles. This Half-Way House is so called from
being about one-hrlf way between the octy and
the Lake End of the Now canal, on the route of
the various shellroad drives which toseoontrate
at that point. Fnd is a famous pliain for rest
and refreshmnut.
In the vicinlty of the Half-Way yTouse are
situated the various Ridge OmiUnlt",res s, called
from being located on the Metalirf hldg,. n
plateau of ground eloevativ some six or eight
feet above the stirrou it tnt sRalwnmt.
In the'treenwosl ('Cemetery will be found the
celebrated Confedorat ou M nlllmat. built by an
association of New Ol leans liadi.pn in honoro
the Confederate dead. nd is none of the most
chaste and bea.tiful ml.0llnuments in tile rounit r.
Just beyond the Ialf.\Way House is the ne1e
Metalrle Ct'ellerry. luid iru eCl the spot of tl.
old and famous MBlatlril Rlite (Course.
These various e'I,, -ternes are beautifully InRd
out and emblnelilspel. anud .'troi the poetulli
manner in which intlrments are malne in
tombs above grourud aflfrT a curious attrec
tion to strangers. A doiluh) track on this line
enable es saoenlors to return by sanme route.
'The steam ears on tib line start from the
same point near Clay St.a.s, fllow the same
track as the horen ears to the Half-Way House-
then by a dothle-irnak railway loated on th;
east bank of tk ''"Nw O.nal" to tile Lake Pont
chartrain, a dittanec from Clany Statue of nearli
seven miles. At the Lake terrnilus Is the cpl.n
brated lievotmelnt j.er.o, whilhi affords a fini
drive and ,rornmlnadl .
Famous restaurallts are located at this point
MAGAZINE AND PYTANIA STREET LINES
The cars of these lines start on the river slde
of Clay Statue. Both IthIse lines pass in com
mon uip C(amp strect by it single track to the
junction of l'rytana. At this point thePrytanis
street ears proceed up that street to the depot or
terminus at Toledano street; and the Magnsine
cars continue up Camp by old Camp street
into Magazine., at lih ylagazino Market. and
thus along Maga.lne to th tte rminus at Joseph
street. 'there is a chnllige of ears on Magazine
street beyond the market, at a depot on Hiar
mony street.
In passing up Camp street by either of these
lines there will be seen on the right Lafayette
Sqluarn in the centre of which is a statue of
Franklin, by the celebrated sculptor. Hiram
Powers5, Fronting this square, on Camp sO reet
will be seen to to the Inft the Odd Fellows' Iall
and the new St. Patrick's Hail, and fronting the
equare, also on the upper side, Is Dr. Palmer's
Presbyterian Churllh. Ju-rt beyond Lafayette
Square, and to thle bit, will be seen St. Patritk's
Oathollic Church.
On Prytan liastreet there are some of the hand
somest private resildenles in New Orleans.
In returning, the Magazine aurs pass entirely
down Magazine street by ia double track to its
Intersection with UCunal, amid thence to tile start
ing point near the Clay 8tatue. In returnlling by
the Prylania line rornu the terminus at Toleda
no street, thi ears pass down l'rytanla by a
parallel double track to its intersection with
Uamp, where tile turn is made through Pocy
farre street into MagI.leine, and thenuce followilng
the return of the Mliagaine carse, resume their
places at the starting point.
CARROLLTON AND JACIKSON STREET
LINES.
The cars of this line start on Baronne
street at its junctlon with Canal, which
is two squares on the Lake side of
the Clay Stalue, and in front of Grunewald
Hall. It has a double track all the way to Car
rollton via Baronne street, Tivoli Circle and St.
Charles Avenue. Fronting on Tivoli Circle and
at the corner to the rluht as you enter St.
Oharles Avenue is the site of tile new Masonic
Temple. the foundation of which is laid. In
Tivoll C(ircle is the spot selected for the Lee
Monument.
At Napoleon Avenue there is a station where
a change is made. and you there enter a car
which is propelled by a fireless engine, a great
curiosity, and you are transported in a
novel and delightful manner to the station
at Carrollton, which is opposite the celebrated
Carrollton Gardens, a great place for pleasure
The distance from Canal street to Carrollton
via this route is about seven miles, and the
journey out St. Charles Avenue affords one of
the finest suburban sights in the Southern
country.
At Louisiana Avenue and at Napoleon Ave
nue each there are branch lines running out to
the river.
A oar also marked Jnekenn street starts from
the same place opposite Grunewald Hall. and
follows the same track out Baronne street and
t. Charles Avenue to Jackson street.. and
thence via Jackson street by a double track to
the river, and return.
ESPLANADE AND BAYOU BRIDGE LINE.
The cars of this line start on the Lake
side of the Clay Statue and go out Canal
street to Rampart, thence out Rampart to
Esplanade. and out Esplanado to the Bayou
Brdge, a distance of about three miles. It has
a parallel double track, so that a passenger can
return by the same route.
On Rampart street, between St. Peter and St.
Ann. will be seen Congo Square or PIlce
D'Armes, and on the further side of this square
is located the P'arish Prison.
Both Rampart and Esplanade are two of the
widest and most attractive streets in New
Orleans.
At a point near the Bayou Ilridge sl a station
leading to the Fair Grou inds, Thoee grounds
are also used as the race course of the Loulsi
ana .Jockey Clb.
Just beyond the Fair Ground station is the
club-houseO , whli'h, together with its garden
lnd sullrroundings. is one of the handsomest
establlshments of the kind in the \nuntry.
If It is not desirei to retulrn by the same
route, a passenger caRn cron the Barou Bridge
and take a car whichi will convey aim to the
IRalf.Way House, and thence by the C(anal
street line bnak to the Clay Statue. or, o'ri. rsa1,
the same tolr can be performed by the Canal
street lille to the Hlilf-Way House, and thencn
via Bayou Bnrilge aid Esplanade street back to
the starting point.
On the roulte btween the Bayou Bridge andi
tie lIalf.-Wy House can b" seen the Cify Park.
whih is faimouts for its muagnifeent live oak
trees, and h1s h1oeen celehlrateid as a great duel
ing ground under thile hlmliar nalme of the
akas.
Opposite the ear station at thel Bayou Bridgn
will tbe found the Magnolia Garden, a groat
pleasure resort.
RAMPART AND DAUIPHINE STREET LINE
These cars start on the Like side of Clay
Statue, proceed out Canal to Rampart. oit
Rampart to Esplanade in common with the
layou Bridg. line, thence down Esplanade to
allhiune. dolwn Dauphine to Poland, and out
P'oland to the station. liRturning, thoee cars
start from the station, and follow Rampart
stre.r all the way to Canal and back to the in
itlll oint near the Clay Statue.
At bte car stn tn. ' corner of I'olnnd and Rim
Lart. a change is made. and, without additional
fare, a I)iLsseLnger is conveyed down to the
United States itlrracks and Slaugllrter-lo ouse
by the Levee and Btarracks line.
LEVEE AND lARIRACKS LINE.
The ears of this linle start on the river site of
Clay Sttatue, opposite the Custom Rloueo. A
turn is made from Canald into Peters street
aroundt the Custom- Ist use, arnd thn+,t tih rougt
Old Levee back Inlto Peters street, thnIlll atlonlr
lafayette Avenue or Eughoin streot to (Jhatrtro-.
out Chart r.a to Polan 1, and througtih I'oland to
the station at th~ corner of 'ohlan and Love
streets. At thitts station1 a chlange is inmle into
another car. which convoys youtt to the aullgr
ter-ollonse, located( oln the Missisettnpi river, a
few hundred yards beyond the Unitted Statles
i-arracks.
From the initial point, opposite the Cmustom
Ilouse, there is a doluinhtrck as far as Chartres
street, andt a singlI track outgoing On ('Chartres
street, and ia single track incoming on Royal.
From the station up Poland street down to
the Itarracks and Slaughter-. ouse. there is at
double track nearly all the way, so that a pas
sener can returtl by Ihe salme general route.
In leaving Canllal sttreet this line passese ill
front of the Jacks-n Square, which is a most
beautiful public garden, and has in the centre
a magntflIelt eqnuestrian stratue of Andrew
Jackson. Around this square are located the
St. Louts OCathedral. the coulrt rooms and the
Poutalba Buildings. and the whole forms one of
the most plctures me sights to be seen in the
Crescent t ity. The editlc's are built after a
qauaint old French style of architecture, and,
with tihe entire surrilndtilgs, no Dpieture within
the limits of New Orleans offers such a field of
interest and sight pleasure to the American
stranger.
Just beyond the Jackson Square thoecar passes
through tlhe Fr nricll Market. which is one of the
celebra'ed ins'ritutions of New Orleans, and no
stranger should leave without visiting It.
A little lurther or, and to the left, at the cor
nor of Esplanade streeo', is located the United
W ates Mint.
On the rApte from the Poland street station
h B. ,as.hter-House can be seen, to the right.
h Jonvent of the Ursulilne nun-. which is the
.'.est religaous organisation in Louislana.
In returning by this line from the station at
Poland street, the cars pass from roland into
Royal, thence by a single track to its junction
with Enahein street or Lafayette Avenue,
thence to the corner of Chartres. where they
reach toe parallel double track, and return to
the starting point on Canal street.
ANNUNCIATION RTItEET LINE.
The ears of this line start on the river tide of
the Clay Statute, between Camp and Magazine
streets, thence out Tehoupitoul s to the junc
tion of Delord and Annunciation, thence br
Annunciation street and to the right around
Annunciation Square back into Annunelation
strest, and out Anutnclation street to the sta
tion on LouislaIna Avenue.
In returning the ears enter Chippewa, and
follow that street to Annunoiation Mquare.
thence around that seqiar to Annunciation'
street, and down that street to Delord. thnettc by
Doelord to-Peters street, and via Peters street to
Canal and baca to the starting point.
_- 0
THE TOHOUPITOUILAS LINE.
The Tehoupitoulas street eare start from
Canal street, near Cimp. thence up T'hotttli
toulns stre't to Louisiana Aveune. ltutrn by
Tehoupltoulasa street (double track) to Felifcity
Road, thence down Peters street to Canal to
stat ting point.
By this line tle visitor cal see the vtor manu
faetory and thegreti elevator. By a change of
care at Louisiatna Avtnue visitors 'an g o the
City lPrk, 8lxth District. and return by the
same route. At Louislana Avenue and Na
polean Avenue visitors (an take cars to return
to the city by Carrolltoitn ailroad cars.
ST. CHARLES HSTREET LINES.
These lines comprise two routes, which start
at the junction ofl t. Charles lnd C ilal streut s
near the Clay ISatute, one miarked Barotnell and
the other Dryades.
Both pass up St. Charles street. by a single
track, to Tivoli Clrtle,'thenen into Trition Walk.
The I.arullnne cars pass from Triton Walk intot'
Baronne street, then utp Baronane street to the
station at Eighth street.
The Dryands cars turn from Triton Walk Into
Dryades street, passing Dryales Market: thanorn
up Dryades street to St. Andrew, and ttirorugh
St. Andrew to Jlarolnne, thence by a commlnon
track to the station at Eighth street.
In returning, tthet cars of the line marked Bia
ronne turn into Carondolet street, and tlnllce
by a single track all the way down to Canal
street, and I)ack to the starting point.
The cars marked Dryades in returning from
the Eighth street station, pass out Eighth
street to St. Dents, tIiwn St. Dents into Dryade-s.
down Dryndes and through St. Andrew into
Rlampart, dow It Rampart to Canal, and thence
to the Clay Statue.
The cars of these lines. In golna out St.
Charles street, pass the Nt. Charles Hotttl, the
Masonitc Hall, thie Academy of Music. thet Ht.
Charles Theatre, the City Hall, fronting La
fayette Mqtuare, and the Exposition Building.
JACKHON RAILROAD DEPOT LINE.
Tie ears of this line start ata station on MI'g-.
nolia street, near the passeng r depot of the
Neow Orleans, St. Louis and Chicago Railroad
(formerly Jackson Railroad), and passes first
ltto Erato street, thence out Erato to Caron
dolet, down Carondeilt and across C(anal into
Bourbon. down lBourbon to Esplanade. out Es
planado anll through D)eoatur to a tation on
SIvrsian Flields , alongside of the Pontehar
train Railroad dtepot. At this point you can
take the passenger oars of the Poutehartraini
railroad. which will convoy you a dis'ance ol
seven miles to Mlilneburg, on Lake Pontchar
train, a very popular pltce of pleasure resort
for the New Orleans people. These cars leave
by locomotive power almost every hour.
In returning from the Pontchalrtrain Depot,
the ears pass out Elysian Fields to Roval, thonrc
down IRtyal to Canal,and'around the Clay Statue
Into St. Charles, thence up St. Charles to
Tivoli Circle and into Triton Walk. theonc to
Dryades street, and up I)ryades to Clin,.and out
Clio to the starting point near theJaokson Rail
road Depot.
In returning on Royal street these oars pass
the State IHouso. whlch was formerly the St
Louis Hotel. The frescoes in the rotunda of the
Htatet-Honse, by Canova, are the handsomest
productions of the kind in the United States.
DUMAINE AND FAIR GROUNDS LINE.
The cars of this line start on the river
side of the Clay Statute, opposite the en
trances to Royal and St. Charles streets. thence
go out Canal to Dauphine. down Dauphine
to Dumiine, out Dumaine to Broad. out Broad
to Laharpe. and thence to the car station. At
this point passengers disembark to enter the
Fair Grounds by the Gentilly Road gate. A
little further on is a station or stopping point
where passengers can enter the Fair Grounds
by a gate on Savage street, 0
In returning, these cars pass by the Grand
Route St, John, crossing Fsplanade street. and
going along the bank of the Bayou St. John to
Dumaine, thence down Dumaine to Broad, up
Broad to St. Peter, and thence by St. Peter to
Btrgutndy, and up Burgundy to Canal, and
beck to the Clay Statue.
In returning, one of the ears of this
line passes from the car station back
into Broad. thence by Broad Into Ursu
lines and along Ursulines to .lrgundy, and
thence by Burgundy to Canal, and back to the
starting point.
CANAL AND CLAIBORNE LINE. 00
The cars of this line start at the foot of Canal
street near the Love.s and go out Canal to
C1alborne. thence out Claiborne to Elysian
Fields, thence by Elysian Fields to Urquhatrt
street. thence by Urquhart to the station on La
fayette Avenue. In returning, the cars pass
from Lafayette Avenun Into Ooodebildren,
thence to Elysian Fields back to (Claiborne. and
through Claiborne Iya double track back to the
starting point on Canal street.
Claiborne Is one of the widest and most at
tramtive streets in the city.
C(arsof this line marked Canal and Common
streets. start from the same point near the
Levoe, thence go out Canal street to Rampart,
through Rampnrt to Comnmon, out Conmmton to
hhe station, betwoon Tonti and Rot.lohlave
;trea.ts. On retu rnlng. tilee t'ls pass bty a paral
1I double tra-k down Commton to Basin. out
Basin to Canal, and thence to the starting
potint.
This line ptasIst; on Comtmon street the oolo
rated Ctharity Hbspital and Hotel D)iu.
PONTCIIAITRAIN RAILROAD.
This is one of the first roads built on the
American continent for the transportation of
passengers.
It is five miles long. between the Mississippi
river and Lake Pontchartrain. In one straight
line. running nearly due north.
The trains are conveyed by steam engines.
and the depot, or starting point. is on Elysian
Fields, near its intersection with Chartres
street. I)lrect connection between this depot
and Canal street can be made by the red ears at
the corner of Bourbon and Canal, which pass
across the city from the Jackson to the Pont
chartrain Railroad depot. At the Lake termfi
nll of this road are the famous restaurants of
Bonudro, Mlguel. the Washlngt)n, (etc. and aro
plaoes of great resort for epicures and pleasure
seekers.
- * ~~----- -
Slight draughts intoxicate the brain.
But drinking detly sobers it again.--Pope.
Ergo bibite "Bollinler."
The llver Dollar.
(Clncinnati Enquirer.)
PTHIl,ADELIlPiA. Mnarch I.--It will be two
weeks before the first silver dollar will beotot,
but by April they will be eolning out at the
ratA, of 100.0nI day. Ga l. Ceo. M or gan, the
English engraver, wvlitoe design has boen ac
i'ptei, will htave the hubs linished on Mon
day, having done all the work possible prior
to the passage of the bill. The mianufacture
of the dies will Ie a work if ten days more',
after which coining will proceed as rapidly as
possible.
The mini, has I.een tlioroughlv overhauled.
the dirt cleared away, the furnace renlovated,.
and everything done to push the work as fast
as Plssslile. The government bought a lot of
silver a week ago. and has at lthe mint nearly
a quarter of a million, but will recoive $:l.o,000
more from New York hil-day. There need I,
no fear of idling. for the munts are anxious st
do all the work they can, and findawork for as
manly lpeople as possible. o
Army oflicers at Omaha anticipate an ae
tive campaign against the Indians beginning
early next month. Crook will probably heal
the foe.s, about 3000 strong, after deduct ions
for sickness and garrison and special duty,
while Sitting Ilull, with 7000 discontented In
dians, will be in the field against hin. By
way of allies, however, the whites will have
sonme 1200 Arapahoes, besides :tes. Shoshones
and loyal Sioux.
"'Bollinr" drr.y, extra quality.
If you want any and all kinds of decoratad
French china, go to E. Offner & Oo.'s. 174 Canal
The Young Man's Benevolent Association, re
nowned for their selet and highly successful
halls. intend to excel all previous ifforts Mardi
Gras night, at the St. Patrick's Hall.
Commercial and financial Matters.
It is said the fnlrt batch of new silver dollars
will be used to pay Congressmen.
The delsion of Judge Billings in the libel
ease of the ship Tornado, which was expected
to 1~ Ziven on Monday, will be rendered on
Wedulnesday.
A million dollars has been placed to the credit
of the Philadelphia mint. and s4oo,esn to the
credit of the Carson City mint, so that both can
begin work on silver dollars at once.
lUp to the first of March the receipts of sugar
at this port amounted to ae.000 hhds, against
oe.t00w hhds for the same time last year; of
molaessn 28t.190 bbs,. against 2277,esa bbls last
year.
Forty-eight thoulsandedollars, or more than
$'ntb0 a day, has boen expeufded thibis nIonth tby
the New York r4tret Commissioners in putting
the streets in what the New York herald says is
a condition to broed pestilence.
According to the Now York papers there was
considernble excitlement in th dry goods trade
of that city owing to a break in the prli'es of
cotton prints. Large sales were made on the
2th uilt. at redued prices. American fancies
deolined to oto. ,retonnes s.e. shirt lngs 4'ac.
not roles ..al, net garden fancies ,,5. andl Con
estoga sae,. It is believed this will lenad to cur
tailing the productillon at We stern print works.
It is said that nearly all the cotton anl woolen
mills in New England have been riunilng full
time, and are selling enormous quantities of
goods, but at a very sranil Irofit.
According to the New York Tribune's na
count. Johll Iarron, cashier, deo.rve ai mronu
mont. for in these days of absconding and em
bostling and rehypothecating it is no small
thing for a hink ofnhinal to lay down his life
rather than betray atrust. The story has been
told already in thedispaclhea from I)exter. Mo.,
but it cannot he repeatedl too often. The brave
man was discovereud Inst raturday morning ly
ing in the vault of the savings bank, hand
cuffed and g:ggel, with a rope around his
neck. He had bonn attackeud by three robbers
on the previous afternoon while replen
ishing the firn. The assailants vihlently
expectetd to find the safe unlooked, but
the doors were closed and the funds of the
bank were protected by a combinaton and a
time -lock. They put a rope around the cashier's
neck. struck him on the head and threatened
to kill him if he would not toll them the combi
nation and enable thomn to open the safe. iHe
preferred to die rather than help thonm plunder
the bank. So they lokeod him up in the vault to
die of suffocatolli and his wounlds, and ran
away with the change in the till and the moneoy
in his pocket-book. Courage, Ihroism and
fldelity such us he displayed, ought not to bc
forgolttn with the morning newspaper. Doubt
lons hil Inst thoughts in the agony and dark
nass of the vault worn of tihe wife and children
who were waiting for his return. If they ned
help, the bankers of Now England and New
York ought to raise n n ampln fud fortheir
bonleft; and the grave should not remain un
marked.
Close of Winter Pork Packing.
For many years the winter pork packing sea
son In the West closed on the first of March; but
Iast spring the Board of Trade of Chicago (the
controlling meat market on this continent )
changed this custom or law, and formally de
clared that all pork packed after that period of
the year which was sound and of full weight
should be considered standard. The Cincinnati
Price Current, however, continues to make up
its reports of the winter packing to the first of
March. From that most reliable journal we
take the following:
'With to-day ends th~ winter pork packing
season. It is safe to say that no one lIdentifloa
with the trade fully foresaw what may be termed
the extnt of the vinter crop of hogs in the
West; no one, previous to the first of January.
believed that Chicago packing would approach
2,500,000 head of hogs during the season, or that
the aggregate at the six larger cities would ap
proximate 4,700,000. It was shown that tho ao
parent basis of supply was ,1 to 20 per qt
greater in 1877 than in 1876-but the summi
racking In 1877 had exceeded that of 1876 by 250,
c0o head or more, and it was regarded likely that
this would appear to have been a pait of
the apparent Increase in supply, Again. the
warm weather which prevailad during DeDonm
bar had an effect in shaping the outrome oL the
season's supplies which diffored quite t ato
rially from tile opinions which were then being
formed as to the probabilities in this respect..
This wrmln weather in December. which made
the packing record show at deficit of upward of
600 oon heal on the first of January. as compared
with the previous winter, was doing more t)
overcome that deflolcncy and accomplish a re
markable increrse than wasgenerally calculated
upon; and the conditions following having bteen
of a most favlratble nature for the promotion of
a long crop, the outcome of the season has beien
quite diffrent from what would have seemed
likely by the evidences in )Decemtinr. * * *
Our table below shows the total parking for
theI winter at. the six largte itine to have reached
naproximatoly 4.485.000. This exhibit may be
modified or onlarged by final returns, but no
essential change is to be oxtportd. This shows
an increase of about 1.200,000 hogs packed at
these places. We have no IUseneri information
as yet from interior points, which it may be
safe to say have likely packed abouto 1,800,000
head. We shall otTer complete information as
soon as it is possible to ac(lolro the same from
the 5(xa Darking points in the W-st. The quality
of hogs during the winter has been excellent as
a rule, and weights will likely show from (;to to
pounds inorease, while the total number packed
will exceed any previous winter more than 500,
00oo0 hogs.
Th'ri number of hogs packed sinceo November
1 at the places named, according to latest mall
and telegraphic information received, compares
with last year as follows:
1877-78. 1876-77.
Feb. 28s. Samt date.
Cincinnatl ........... 6. . . , 0 523576
Chicago ............ ..2,450,0() 1,618.08
Nt. Louis................. 5,,00, 414,747
Indianapolis ............. 270, 294,19
Milwaukeoo ... .. ...... 0,000 225.u69
Louisville. 0 .... 2810(10 214.802
Total, six cities.... 4...4485000 3.291,065
Cedar Rapids ................ 125.0o 76,945
Kansas City ......... 18, 11,038
Cleveland............ . . 100,000 121,202
Des Moines ................ 00100 61,780
The following shows the total tnmber of hogs
packed in the West for each winter season for
the previous twenty-eight years, accordling to
returns:
14 .o 5-....... 1,5;2.2210 18H6(-fi6 . ..3.361,105
1 0 51 ...... 1.332.817 1584-i5..... 2,422.779
1851-i 2 .- .. .1.162 44 8 1 516 (l .... . 7...1,72 955
1 2-5 . . ...... 2,201.1 10 1811 67 . .....2.4 0,7 1
1 5 -5 ......2,5:4 770 11667 .........2,7 1 (0 4
1854-51 ... '2.121 4041 1 -l 9 .... 2 4.9,872
1855 56 ... ....2,44R ,502 14l59.-70 . ..... 2.635.312
18511-57 ... 1,1:L.4078 1870-71 .....(..:1,15,251
1857-68. . . 2,210 7 171-72..........4,831558
1858 59.. . 9 .2.46.5520 1872 73 2 ..... 410,314
185!-60...... 2.350.812' 1473-74 5.4i 6,2(00
16 .... ....2,5,70'2 1.474-75 . .... 56f 6,2228
1t61-t2 . . 2.R91 ((16 1975-71.. 4,( 40.135
1862-63:.... 4.069.520 1876-77........ 5,181:308
TMhlt Year's Cattle Drive to Kansas.
Those whothink that Western Texas has been
deprived of all her cattle by those who have
been driving to Kansas and the Territories
since the war are badly mistaken. True, cer
tain sections have been ridden of great num
bers of the long horns which used to roam over
them, yet in other parts the rapidly increasing
bovine seems as numerous as over. The drive
to Kansas this year will be an exteneive one.
and stock men with whom our reporter has
conversed are of the opinion that sales will be
effected with promptness and at paying rates.
The whole number of cattle to hbe driven, as re
Dorted by Mr. Richard Head. foreman of Elli
son & DeowesMn. is 223.400 head. The hulk of
th' s eant'le is destined for Fort Dodge. Kansas,
and Ogailala, Nebraska.-[San Antonio Express
A Monster Steamshlp.
The largest steamship excepot the Great Eas
torn ever built is n'w moored to the wharf of
the French Steamship Company, at Pier No. 50,
North river. She is named the Hoope-. and has
hernstofora been used in the laying of telegraph
cables. This is her first trip to this onuntry.
In the spring she will return to her rld work.
Shebwas hbtit at Newcastle-on-Tyne, by C. Mitch
ell, in 1a73. and is clasQed 100 A 1 at Ilord's.
She is 350 feet over all. 5s feet broad and at feet
deep. She is built of iron, and is rigged as a
three-masted schooner. She is registered as
4935 tons. but has a cannaity of 6000 tons, exclu
slve of passengers. She has two compound in
verted engines of 400o nominal horse power
built by T. Clark & Co.. Newcastle, and is firtl
with steam windlass, winches, crane and be'
and donkey engines. In her are thre 5r ·,
tanks, one 41 faot in diameter and 30 f o deep,
another 83 by so feet, and the third 6' 6p 8' feept.
In the center one have been stored 47.00 bushels
of corn. In the spaces between 'hese tanks she
has room for 400 tons of freighb . Rhe will carry
out the I,.rgst cargo that 'jver left the United
States.--[N. Y. Times.
. ..... .91.€,,.4t. . .....
FINANCIAL AND COMMERCIAL.
o o
MONWETARY. o
OFFICE NEW ORLEANS DEMOURAT.
0 Monday Evening, March 4, 1878. 1
4 EW ORLEANS OLEARING-HOUSE.
C'earings. Balances.
March .............. $i.0.87IH 03 $.272 070 79
March 4 ....... ................. Holiday.
To-day being a legal holiday no business of
import anre was tranllsated inl fnancial circles.
Thie itock Ex.changes, tanks and public institu
tions. generally wore closed.
We quotO excet,tional paper 7058 cent:
Al do [email protected]: second grade do 123--; loans on
collaterals 7185: Al mortgage paper 8t50lO:
second grade do [email protected] V cent per annum.
COMM.RCIAL. O
OFFICE NEW ORLEANS DEMOCRAT.
Moonday Evening. March 4. 18758.
(GENERAL IIEHAIKSM-To-day has been a
clear, cool and delightful day: and being a
legal holiday, tfle banks and publio institutions
were elosed.whltch put an effectual estoppel on
general business.
However, the news of the signing of the treaty
stipulations by the Russian and Turkish au
thorsitioes and thile consequerlnt improvonemnt in
the Cotton market at Liverpool and New York,
had a favorable effect upon our market. In the
fleecy staple. and the sales reacheld 1oon lales, at
an advance of '...',e ' pound, The sales
would havn been much larger, but holders gon
rally a(lvanced their prices to such a degren
thlatbuyers did not feel themselves justified in
meeting them.
In Provisions there Is no change worthy of
mention. Prices are about the same, with a
very little movement.
T''he Flour market continues quiet. althouglh
slightly easier to purhllasers, bit we cllnot
quotn the c'ommodity lower, while the demand
is fair.
,ince Saturlayi there have been fresh sup
plies of Corn Meal, which have been taken up
readily, but prices of this article havo under
gone no change.
Corn is firm, with Iales of 2200 barrels at prices
ranging from so to 53' per bushel.
The prices of Oa()t are steady aindl demand
moderate, the reported sales being 500 bags at
37 [email protected] per bushel.
COTTON--The tone of the market throueh
ollt thel day lhas been strong, lnder ith inftli
I'll of favorable advio's froml abroad. Not
withs ns diniIlg hra]ers na1 1d sellers were alpart in
their views, a moderate lblusiness was trl.aneacted.
the sales anlotllliug to 1;00 bales, at an advance
of (00lC,
The oml,,al closilng of tile Cotton Exchange
was as follows:
,r.. ~ r. vl ,-..,r w+w ,t
TO-DAY. YETICERDAY.
Low Ordinary ..........·.. 7. :T
Ordinary .................. 7'. 7
Good Ordinary .............. s' s
Low Middling ............... 99 .,
M iddling ................... 10% 1L,
Good Middling...... .. ..11'6 s ii
Middling Fair ............. ii 11
Sales to-day, ;oo bales. Market firm.
COTTON STATEMENT. O
In store and on shipboard Sept. 1. 1877.....21,856
Gross re'eipts since yesterday. 22,911
Gross receipts previously ......1,s6..0. -1,4.,09s
o Total supply .......... 1.41,:1..5
Exported to-day............. . 21.fc(
Exported previously ..... o. io.. 1,0o309-1,0o9.974
Total stocks this day .................... 341,191
Total stock this day last year ........... 301,439
The exports to-day were 10,511I hbles to Liver
pool. 7239 to Bremen, 26201 to 3arcelonla and 1249
to Genoa.
Ndt receipts since Saturday............. 21025
Receipts from other ports.............. . 1.91(;
Net receipts last Sunday and Monday 10,4u8
Net receipts this day last year.......... 2.873
Net'receipts since Friday ............... 22a,66
Not receipts same time last week .... 16.533
Net receipts same time last year ..... 3. 6,4e
Net receipts since September 1.........,15.4,24
Net receipts same time last year.........1.033,900
Cotton on shipboard as per account of the
Ootton Exchange, as follows: Liverpool 25,762
bales, Havre 28,020. Bremen 0370. Mediterranean
2653. North Bea 28.518, Spain --. Baltic ports
17.718; coastwise :038: total. 112.609 bales. This,
taken from the stock at noon. as noted at the
Exchange. leaves in presses 224.682 hales. o
The movement at ports as per telegrams to
the (CottonExchange for three days up to 12 m.
to-day, is given below:
o Recelved Same timen ame time
% sinuce Friday. last week. last year.
New Orleans..... 22.6(4 or;.a53 3.c02
Galveston ........ 3,82 3.430 1,04(0
Mobile............ 2,427 4 521 591
Savannah ....... 23.76 3.919 921
Charleston .....I 2,217 1,992 1,300
Wilmington ".... 410 1.007 227
Norfolk........... 1.993 2.0 2.132
Baltimore... 79 23 .
Now York......... 1,3;t 2,006 134
iBoston................ 1.5 922
Philadelphia..... 11 214 133
Other ports ..........
Total ........ 42,833 37.525 12,292
Recelts at ports since September 1 ......,600.s03
IReceip)tssame tirne last year............ 504,210
ReceipOlts same time year before... .....39,40r
The consolidated report for the week gives
exports to
O. P,. F'ee. Con. Chan. Rt'ks.
This week .2....20,6 3:07 30,064 1.550 797,428
Last week ......25.975 9,172 4.305 ..... 588,228
This week l't y'r 19,05H 974 540 ...... 861,613
OCEAN FREIGHTS-Are quoted as follows:
By steam-Cotton to Liverpool [email protected]; to
Bevel -d; to Bremen -d; to Boston, Provl
dence., Fall River, Philadelphia and Baltimore.,
via New York '6c; to New York hc; grain to
Liverpool los t.d, and - to Bromen f quarter.
By sail-Cotton to Liverpool 13-1207-lOd; to
Havre 'rc; to Bremen '7c; to Genoa ?..1lc;
grain to the Continent 7s8 d.
Steam rates to Northern ports are quoted at
$1 25 on molasses ' bbl to New York. and $t914 no
a hhd on sugar. By sail the rate on molasses to
New York is $1 25 I bbl.
SUGAR-In this article there was but a small
movement and prices are easy.
We quote: Inferior [email protected]'; common to
good common 5sl't6'kn; fair to good fair
prime 7 74(t70:c; gray clarified - @-c; yellow
clarified, as in quality, [email protected] .c; off whites, good
to choice, sI @sc: white clarlloed s'[email protected]>9.
MOLASSES--The market is nominal, and
the demand limited.
We quote: Common [email protected]; fair [email protected];
prime [email protected]; strictly prime 3323o50; choice
FLOUR--The market continues quiet, al
though somewhat easier to Itulyers, without
being quotatbly lower. The demand is fair, with
sales as follows: 4o bbls at S 975; Ito hbls at $61 lo;
50 bids at $s 211; 200 andt 201) bils at $ 45r,; 25 andt
10 at $6 50o bbl : too. 125 and 550 bbls on private
terms.
We quote tinle to superfine at [email protected] 28 single
extra $1 so; do1uble extraL S 75(905; trbleo
extra. low to c·hoi'e. $5 25(45 75: choice extra
$64)G 25: fancy cihoie $( 259(0 75 $ bbl. On
these pri ',s dealers obtain an advance of 50oc
on job s.aes.
CORN MEAL-Althoughb fresh supplies have
come in sine( Slaturday, the market is not ma
terially changed. The re',eipts wore about all
taken up as soon as landed. and the market is
steady on round lots at $2 791!2 75, dealers job
bing still at $2 950:1 " bbl.
Sales-50o bbls at $2 70; 1too0 bbls at $2 70; 100
bhls at $2 75, and 00o hbis on private terms.
CREAM AND PEARL MEAL--Western is
quoted at $b730 25 'S bbl ex landing, and $3 259,9
3 5o ex store.
GRITS-Supply good and demand steady:;
common to choice selling on the landing aF'$3q
3 21. and out of store at $3 [email protected] 50 .- bbl.
PORK-The market is quiet and easy. and
the demand is fair. especially in the order trahe.
We quote round lots firm at $11 [email protected] 37k.
Dealers rates are unchanged; retail and job
lots selling at $11 752912.
DRY SALT MEATS-Demand fair. and mar
ket steady and strong on shoulders at ":4.o for
loose, and [email protected] for packed goods. Sides
are quiet and easy at s'405 ;5c for loose and
packed clear ribe. and s53e for loose and packed
clear sides. Dealers' rates are So.Yce higher.
Sales-2 car loads of boxed shoulders at 4c, and
15 boxes do. out of store, at 4-.c.
BACON-The demand is moderate and prices
arb steady. Shoulders 4';95c. long clear 6;)f99
6',. cleear rib sides 6,';os . and clear sides [email protected]
64e. Deal-ors' rates are 3ii .'c higher.
HAMS-Are in limited demand and prices
easy. We quote plain hams [email protected] and choice
sugar-cured [email protected], as in brand and quality.
LARD-Continues quiet but steady with a
moderate inquiry, chiefly of a jobbing kind. and
we ote packers' tierce and kettle rendered at
tV'@7%e, and refined tierce at 7}[email protected]%o. Dealers'
rates are [email protected] higher.
BREAKFAST BACON-There is an abundant
supply and the market is dull and easy at 7
@Oe: dealers charging 8s%@90 for small lots.
FULTON BEEF-Half-bbls $975; extra West
ern mess s$ [email protected] I bbl.
PACKERS' HOG PRODUCTS-Dealers are
selling on orders in the job trade at$6 [email protected] 50 >
half bbl for pig pork, $10 [email protected] bbl for prime
mess pork, $90&9 50 for prime pork, and s9 75(
10 for rump pork. Pigs' feet are selling at
s$11 25 I keg. Ham sausages are dull and
quoted at [email protected] , lb. Pickled pigs' tongues are
quoted at 6e apiece. Pickled heads are offer
iug at $9 [email protected] 50 It tierce, .and jowls at $4 50
5 50 V barrel. Bologna sausage 6eo. Spare
ribs-none in market. Side ribs [email protected] O
CORN-Is firm. Sales--30 yellow at 5e(: 700
and roe white mixed at 52'.; 0oo and too mixed
at 5:1r' bushel.
OATl'-Prices are steady and the demand
moderate. Sales-v30o bags choice at, 37i, and
l00 do at 38sc ' bushel.
BRAN-None in first hands. Dealers are
holding at s1 ~r owt.
HlAY--Quiet but steady. Cholo 51([email protected]$17 50
Prmle$ s6rt15 toll.
COFFEE--Is quiet and unchanged.
QUOTATIONS FOR GOLD.
Cargoes. Job Lots.
Prime .. ............ [email protected]'; 1 1 @(i ',
Fair...................16 @(1o, 16ir%@1in,
Ordinary..... ......14'[email protected] 15 '4Q15.
Extremn rang............................. .13 20
TOBACCO- Dull. Stock on sale c600 hhds.
QUOTATIONS.
Inferior lugs ...........................2.. @ 21
Low lugs ............ ............. [email protected] s
Medium .......................... .. . 8s'[email protected] i5,
Good to fine....... ............ ....... 4 @ 43
Low leaf. ............................ [email protected] ~'s
Medium .................... ............. @ 7
o ....od............................... 7'[email protected] R
Fine ................................... 9 @10
elanctions ............................lo @12
BAGGING-tRtnady at 1lo In round lots; re
tailing at [email protected]'4e. Baling twine at 183e in
round lots: retailing at 14c.
BUTTER - Moderate stock. Demand fair.
Choice New Y,,rk creamery [email protected]: Now York
dairy, fine [email protected]; Nw York good [email protected]; low t01d
medium grades [email protected] Western-choice, fresh
packeod180i19: good do 15'.17; good fruit house
14i15; summer muncked 13'144; low grades 855
12; roll, wet packed ir10I; roll, tubs. [email protected]'20.
CHEESE-Prime Western factory 12 12 laK;
good do [email protected] New York cream [email protected],4.
WHISKY-Is easy, city made selling at Irreg
ular plrices from $1 [email protected] o03, and Western recti
fied at $1 [email protected] o06 gallon.
STARCH-In good demand at 303 loc in lots;
jobbing at [email protected] lb.
WOOL-More stocks offering than there is de
mand, and it is hold above the views of buyers,
Burry is qnloted at [email protected] Louisiana clear 26o0c.
clear lake 279~i29 ' lb .
SALT-Stock light, demand active. A cargo,
all coarse, sold at soc per sack afloat. We quote
prieos at the warehouse: Coarse [email protected], fine
$1 [email protected] 10. Turks Island neglotetl at 32e I
bushel. Table salt in pockets 1%@7Ko each, as
In size.
POULTRY-Old chickens $4'42 5. young $$2
2 50: ducks @33 50; geese [email protected];: turkeys [email protected]
I dozen.
EGGS-Western o1012c; Louisiana [email protected]
dozen.
RICE-Is firm. No. 2 8'0040, common 4'YR.e,
ordinary 5'd(50'e, fair 5%@i~50, good [email protected]'5,
prime . @.('sc, chooice 67e4 P lb.
ESCULENT'S-Potatoes are selling at $1 [email protected]
a25:; onions at $2 75(.5 50; apples at $1 50(53; 9
bbl:; cabbages at $5 s 100. and $2 [email protected] ( 50
crate.
Domestic Markets.
NEW YonK. March 4, 12 m.-Coffee quint: saPles
1075 per tlassnii at New Orleans at 16', : .o0
laraeanibo coffee here p. t.; "argoes ordlnary
14'[email protected]'- ; fair 10; good 16e;; prime 17'4: lots
14::915' ;tava20 :(221. RIawsugar quet ;sales
1014 hhds of grocery; Cuba fair to prime; 450
hoxes of Demerara; 9o100 bags. Refining fair to i
good fair 7 L4t47 .bid. ', high'r asked; prime 7. I
Reflned sugar quiet: yellow 7107N: extra C s'i
Rl'. ; standard A 8'[email protected]; off A w52 a', ; standard
srnsshed s9,@lo; powdered 9i ; granulated 9',
"0t; out loaf 10iS10o'. HyruDps-molasses 2)
35; sugar 340044; molasses. English islands [email protected]
36; New Orleans 33050,r).
Hiire-Carolina 5,[email protected]' ; Patna7'[email protected]',; Ran
goon WOO'e. P'runes-Frenioh. new 9t12; Turk
ish, new s'4ow10. iRaisons-seedless $2 75(04 25;
now layer $i [email protected] 55; Muscatel, new $1 70(9't 85;
Valencia, new '"b. Currants--nw 5%@,'i.
Figs-now layer 7tIt'll. Almonds-Ivaca 1501
15',; Languedoe 1i9q19'4: Tarragona 15.40119.
Brazil nuts 45)Ci4. Filberts-Barcelona 8'zj 9;
Hicily 9';@10. Sardines-quarters lai1? n;
halves 191''020. Spices-Afrloan ginger 6';
race 0: cassia 18seh'21; c'oves [email protected]; nutmegs
80_s85'i. Pepper-Singapore 12'i,&125; Suma
tra [email protected]; pimento 140114' . Soda-Dwight's
NEW YORa. March 4, 3:15 p. m.--Coffee quiet;
sales 996 Snowdrop, 1000 Eagle, private terms.
Rtw sugar quiet and firm; reflning-fair to
good fair generally held at 7%i"077' ; prime 7'4.
lUflned sugar easy.
CHICAno, March 4.-Wheat opens with sales
at st g0s April. Corn 43a' May, Pork $to 1o April:
sales at $10 cash. Nothing in other options.
Lard 7.20 April; 7.30 May.
11:45 a. m.-Ma'rket quiet. Wheat $1 [email protected]
1 os'; April. Corn 43t,@43', May. Dry salt
meats-Shoulders 3.50, long clear 5.25. short ribs
5.40.
1:30 p.m., Morning call.-Pork quiet; $19 02',
April; $1l 17' May. Lard 7.12%'i'7.15 April.
7,[email protected],' May. Dressed hogs $4. Meats s0
lower. Breadstuffl unsettled. Wheat $1 07'",1
1 07'6 March or cash, $1 os 4 April. Corn 42
cash; 424(142'd April; 425,@42% May. Oats 26'I
May.
CHICAOO, March 4. 3:30 p. m., Close,-Pork
steady; $10o o2'la1n o5r April: $10 17';(a59o 2o May.
Lard steady; 7.154.7.175, April; 7.256(i7.27'. May.
Breadstuffs unsettled. Wheat $1 07'91 1 no"
April. Corn 411a(41476 cash or March; 41'7i0
42 April; 42V&42'. May; 41' .Tune. Oats 217,[email protected] M
25 March: 24(53215' April; 230i May.
ST. LouIs. March 4.-Wheat--No. 2 red $1 22
bid cash; No. 3 red weak, $1 1sRI March, $1 I9l;
April. $1 18 cash. Corn weak; 414 March and
April 42 &42a3 May 41'i cash. Oats quiet: 25',
bid March. 2;', cash. P'ork lower and dull at
$10 so cash, $to 60 May. Cut meats lower and
market demoralized; shoulders 3',, clear rib
c(le5 or, cear sides 5.230d15'4. Biacon dill ; shoul
ders 4'¾ ,iN4. clear rib [email protected] clear sides (;'I.
Lard nominally 7.15417.20.
Foreig[n Markets.
LIVERPOOL. March 4, 12:15 p. m.-Cotton
ective and firmer. Middling uplands .'.a. Mid
dling Orleans Crlid; sales 15,500 bal's, of which
20on hales are for export andi speculation.
Wheat-Western spring 9s drClos leOd; West
ern winter 1s IOs10lSlls 6d. Flour-Western canal
21s 6d4127s. Corn-new 265 [email protected] old [email protected]
24s 6d. Oats-No.j2 Western 3s. Barley-No. 2
Western as lld. Canadian peas 36s 6d. Pork
erime Western 63s. Beef-prime mess 8.s.
Lard--prime W.stern 37s 9d. Cheese-good to
fine Ols. Bacon-long clear 289. short clear 29s,
Tallow D. y. c. London 39s Od, good to fine 405 6d.
MUNICIPAL ADVERTISEMENTS.
8EALED PROPOSALS.
DEPARTMENT OF POTCE,
Room 12 City Hall,
New Orleans. March 2, 1578.
Sealed proposals will be received at this office
until FRIDAY. March 9. at 12 o'clock m., for
furnishing SHILLS in such quantities as may
be required from time to time for the use of the
public squares.
The city reserves the right to reject any or all
bids.
ROBT. E. DIAMOND,
mh2 td Administrator.
SEALED PROPOSALS.
DEPARTMENT OF POLICE,
Room No. 12 City Hall,
Now Orleans. March 2, 1975.
HSaled proposals will be received at this office
until FRIDAY, March ,. at 12 o'clock m., for the
erection of a fence around the McCarthy
BSqare. in accordance with speHifications fur
nished by the City Surveyor, and now on fIle in
this office.
A certificate of deposit of twenty-five dollars
from the Administrator of Finance must nc
company each bid.
The city reserves the right to reject any or all
bids. ROBT. E. DIAMOND,
mhs td Administrator.
MEDICAL NOTICE.
DR. W. BILLE, Specialist for all Chronic Dis
eases. Private Diseases and Female Diseases
has just returned from Europe. Office, 154 Canal
street, between Baronne and Carondelet streets,
up stairs. Nervous Debility, Weakness, either
caused by abuse or age, ALWAYS cured in a
short time. Private Diseases treated after a new
sure and quick method. Female Diseases treated
with greatest success.
Dr. Bille's reputation as a skilled and success
ful physician Is already years ago established
in New Orleans and vicinity and he has cured
hundreds of cases here which other physiciavs
had failed to benefit,which is well known to the
public. Dr. Bille is a graduate from one of the
best colleges in Europe, and was for years as
sistant physician to Prof. Ricord, Paris. Con
sultations and correspondence strictly confl
dential. Charges moderate. 154 Canal street,
DB, W. BILLE 15 Ganal street, des tt
MIlICGIPAL ADV114TIE3.ER'
SNOTICE.
TO OWNERSt AND DRIVERS OF CCAA
RIAGE. AND CABD.
MAYORALTY OF NEw OL.ANS..
New orleans. March 4, .1878.
An ordinance fixing the rates which owners C
drivers of public hacks, cabs and carriag
may charge for the use of the same.
SECTION 1. Be it ordained by the City Gotul
of the city of New Orleans. That it shall not
lawful for any owner, driver or person havi
I charge or authority over a public hack,earri
or cab for hire, to charge more than the folio
ing rates for the use of the same:
For carriages drawn by two horses, any d|
tance not exceeding one mile, or twelvesquar
tor one or two persons, one dollar each, and f
each succeeding mile or less, seventy-five cea
ench.
For every such carriage hired by the ho
three dollars for the first hour and two dolli
for each succeeding hour or fractional
thereof, for the use of the entire carriage.
For cats or carriages drawn by one ho
any distanee not exceeding one mile (or twel
squares), for one or two persons, seventy-fl
oents each, and for each succeeding mic o
less. fifty cents.
For every such cab or carriage hired by tih
hour. $2 for the first hour and $1.50 for each sn
ceeding hour or fractional part thereof, for
entire cab or carriage.
These rates shall apply from sunrise till ml
night. From midnight till sunrise the prl
shall be fixed by agreement with the driver, b
in no case sha I double the above rates be e
ceeded : prori,led, however, that nothing in t
ordinance shall be so construed as to restr
the owner or driver of any of the vehicles me
tioned from contracting at a greater compe
tion than the rates fixed herein,
BrE.2. Be it further ordained, Thatanyown
or driver of a vehicle found violating the oro
visions of this ordinance shall be subjected to
fine not exceeding $1e, recoverable before a
recorder, and, in default of the payment, be in
prisoned not exceeding thirty days.
SEc, 3. Be it further ordained, That all ow4
ere or drivers of public vehicles to whom thf
ordinance may extend are required, under
penalty of $25, to have a copy of this ordinan
conspicuously posted in their cab or carriage
and in default of the payment of sa!d fine .
be imprisoned not exceeding ten days, or bo
at, the option of the recorder.
Sec. 4. Be it further ordained, That this on
nance shall take effect from and after the
teenth of February, 1872, and all ordinanee,
parts of ordinances in confllot herewith be A.
the same are hereby repealed.
Adopted by the Council of the city of NeO
leans. February 6, 1872.
Yeas-Cookrem. Shaw, Delassize, Remi
Lewis, Walton, Bonzano,
BENJ. F. FLANDERS. Mayor
A true copy:
Il. CONQUESRT CLARKE, Secrotary.
A true c1,y: E. L BOWER,
mh4 t. (,tief Clerk to Ed. Pilsbury Mayol
SPECIAL NOTICE.
DEPARTMENT OF IMPROVEMENTS,
tRom No. 10, Clty Hall,
0 New Orleans, March 8, 1878.
The attention of the public is respeotfull
called to the following city ordinance, concern.
Ing the cleanliness of streets and gutters. Par.
ties are recuested to deposit the refuse a
sweepings from dwellings, stores, etc.,
kitchen offal in tubs, barrels, baskets or othb
suitable receptacle. Any violation of this rul
will subject the party or parties so doing to th
full penalty of the law.
It is the wish of this department that a prope
disposition to comply with the ordinance O
the subject will be shown by the publio.
JOHN MoCAFFREY, Administrator.
MAYORALTY orF Nw Om.aAws, 1
City Hall. May 20, 175.
INo. 3126-Administration Series.
An ordinance to provide for the cleanliness o
streets. gutters, etc.
SEBaoN 1. Any person who shall keep, thro4
or deposit any offal, filth, foul or offensive mai
ter, corrupt or putrid water, or any shells. haW
straw. kitchen stuff, paper, cloth, vegetable ma
ter, or any substances of any kind that may b
offensive to smell, or injurious to health, or Ue
bln to become so, In any yard, lot, space
building, sidewalk, gutter, drain or canal,
shall suffer or allow or permit the same to
(lone or remain, shall be liable to a fine n
exceeding twenty dollars for each and every o
Tense; provided, that ordinary refuse and swee
I ings from stores, dwelling houses and othe
tenements. and kitchen offal shall be deposits
in tubs. boxes, barrels, baskets, or other suitabl
receptacle, and be placed on the outside of th
banquettes, convenient to be taken off by th
otTffal carts; and hereafter such deposits shall b
made not earlier than 3 a. m. nor latter than 8
m., and the receptacles as above shall not
left on the banquettes after the hour of 9:30
m.; and the phrAse "any person" shall be he"
to include not only the adjacent proprieto
resident, occupant or person actually doing, o
who has done any of the things named heret
but also any one whose duty it is by law or cod
tract, to remove, or caused to be removed,
carried away, any such matters, substances 6
things as heroin set forth or intended.
SEC. 2. No person shall impede or obst
the passage or flow of water in any gutte
ditch, draining pipe or drain, or in any mann
dam the same, under a penalty not exceedin
$10.
Adopted by the Council of the city of N
Orleans. May 18, 1876.
CHAS. J. LEEDS, Mayor.
A true copy:
J. HI HARDY, Secretary. mh3
IMPORTANT TO MACHINISTS.
DEPARTMENT OF IMPROVEMNTS,
Room is. City Hall,
New Orleans, March 1. 1,878.
Bealed proposals will be received at this o
until MONDAY, the first day of April. 1878. at
o'clock m.. for the construction of a draini
machino, to be erected on the banks of the
leans Canal. on the property known as the O
CITY PARK, Metairie Ridge, in accordan
with the specifications on file in the office of
City Surveyor. All bids must be properly
vcloped and indorsed as follows: "Proposal
Construction of Draining Machine."
The city reserves the right to reject any or
bids. JNO. McCAFFREY,
mb h Administrator
CITY LICENSES FOR 1s78.
DEPARTMENT OF FINAN
City Hall. New Orleans. Dec. 0o, 1877.
CITY LICENSES for 1878 will be received
this office on WEDNESDAY, January 2.
the following rates of discount for prompt p
ment, viz.:
20 per cent discount for first week in Janu
15 per cent discount for second week in J
uary.
to per cent discount for third week in Janu
5 per cent discount for fourth week in Ja
uary.
3 per cent discount during the month of FB
ruary. o
deao tf J. C. DEN.R Adminlstrato
0 p NOTICE TO BAKElN.
MAYOUAzrT o0 Nuw OaLhux
City Hall. February 2. 18.7.
The average priceof fresh flour being this d&
seven dollars; in accordance with said val
tion the price of bread for the week commes
ing on MONDAY. February 4. 1877. will be:
Sixty-two ounces for twenty cents.
Thirty-one ounces for ten cents.
SiBlxteen ounces for five cents.
Bakers of bread are required to use only t
best flour of the above value per barrel. and
ase of damaged or in ferior flour In bread offer
for sale in this city is prohibited, Oonsumw
of bread are requested to report to the near'
police station any violation of the above o
nanee. either in variation ot welght or a
material.
leo3 ED. PILJB~UY. Maot
xml | txt | https://chroniclingamerica.loc.gov/lccn/sn83026413/1878-03-05/ed-1/seq-8/ocr/ | CC-MAIN-2021-43 | refinedweb | 9,297 | 76.01 |
A pairs plot is a matrix of scatterplots that lets you understand the pairwise relationship between different variables in a dataset.
The easiest way to create a pairs plot in Python is to use the seaborn.pairplot(df) function.
The following examples show how to use this function in practice.
Example 1: Pairs Plot for All Variables
The following code shows how to create a pairs plot for every numeric variable in the seaborn dataset called iris:
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns #define dataset iris = sns.load_dataset("iris") #create pairs plot for all numeric variables sns.pairplot(iris)
The way to interpret the matrix is as follows:
- The distribution of each variable is shown as a histogram along the diagonal boxes.
- All other boxes display a scatterplot of the relationship between each pairwise combination of variables. For example, the box in the bottom left corner of the matrix displays a scatterplot of values for petal_width vs. sepal_length.
This single plot gives us an idea of the relationship between each pair of variables in our dataset.
Example 2: Pairs Plot for Specific Variables
We can also specify only certain variables to include in the pairs plot:
sns.pairplot(iris[['sepal_length', 'sepal_width']])
Example 3: Pairs Plot with Color by Category
We can also create a pairs plot that colors each point in each plot based on some categorical variable using the hue argument:
sns.pairplot(iris, hue='species')
By using the hue argument, we can gain an even better understanding of the data.
Additional Resources
How to Make Barplots with Seaborn
How to Make Heatmaps with Seaborn
How to Add a Title to Seaborn Plots | https://www.statology.org/pairs-plot-in-python/ | CC-MAIN-2022-27 | refinedweb | 281 | 60.55 |
Red Hat Bugzilla – Bug 429149
CVE-2008-0122 libbind off-by-one buffer overflow
Last modified: 2016-03-09 09:35:40 EST
CVE-2008-0122:
Off-by-one error in the inet_network function in libc in FreeBSD 6.2, 6.3, and
7.0-PRERELEASE and earlier allows context-dependent attackers to cause a denial
of service (crash) and possibly execute arbitrary code via crafted input that
triggers memory corruption.
Affected code is also used by ISC Bind library, which is affected by this
problem too.
Created attachment 292030 [details]
patch for this issue
Issue is already public for libbind:
GNU libc implementation seems to be based on the very same BSD code used by
FreeBSD and ISC Bind, but has this change applied in all versions shipped with
Red Hat Enterprise Linux (the oldest version is 2.2.4).
From inet/inet_net.c:
if (!digit)
return (INADDR_NONE);
if (pp >= parts + 4 || val > 0xff)
return (INADDR_NONE);
if (*cp == '.') {
*pp++ = val, cp++;
goto again;
}
Statement:
This issue did not affect the versions of GNU libc as shipped with Red Hat
Enterprise Linux 2.1, 3, 4, or 5.
This issue affects the versions of libbind as shipped with Red Hat Enterprise
Linux 2.1, 3, 4, and 5, however the vulnerable function is not used by any
shipped applications. The Red Hat Security Response Team has therefore rated
this issue as having low security impact, a future update may address this flaw.
bind-9.4.2-3.fc7 has been pushed to the Fedora 7 stable repository. If problems still persist, please make note of it in this bug report.
This problem allows an attacker to write 1 unsigned long int value (4 or 8
bytes, depending on the platform used) beyond the end of the buffer. This
overwrite is too short to modify function return address, so this problem does
not seem to be easily exploitable or verifiable using reproducer.
This was addressed via:
Red Hat Enterprise Linux version 5 (RHSA-2008:0300) | https://bugzilla.redhat.com/show_bug.cgi?id=429149 | CC-MAIN-2018-22 | refinedweb | 334 | 60.65 |
At 08:59 AM 2/12/2007 +0100, Thomas Lotze wrote: >Phillip J. Eby wrote: > > > It appears your goals are somewhat... confused. > >I don't think so. I'm sure I still have to learn about setuptools but I >think I know quite well what I want to achieve. I meant the operational goals for the code you wrote, not your overall goal. > > Remember that by definition a namespace package has no single "owner" > > project. It is potentially shared across multiple projects. When > > installed as an egg, each __init__.py is executed, true. But when a > > project is NOT installed via egg, but rather by a system packager, the > > __init__.py doesn't exist, and so cannot be executed. > >If we have to take into account distributions of a project as source code >bereft of its top-level namespace's __init__.py being expected to just >work, I give up. I assumed to always work with either intact source or >built eggs, the latter with or without their namespaces' __init__.py files >being used and with or without being installed by our egg tools. Built eggs contain namespace package __init__.py files, system-installed eggs do not. >The package remapping is only needed when running from source, and I don't >see a reason why the __init__.py shouldn't exist and be executed in that >case. Because 1) it won't be the only __init__.py for the package,. > > Therefore, your prototype code is horribly broken, as it will corrupt > > pkg_resources' internal data structures when it is run more than once -- > >I don't see why it couldn't be made to behave properly. Perhaps it could. I just don't see how! In order to set up the __path__'s for a specific project, the __init__.py must have knowledge of *that* project. Therefore, *each* project must contain such a file, *and* it must be executed.. (All of these things I'm saying are documented in the setuptools manual under the "Namespace Packages" heading, by the way.) > > (And I won't even get into the > > pointlessness of wrapping module-level code in an import lock.) > >I'd appreciate it if you did, as I haven't yet found a difference between >using the lock in modules and using it in pkg_resources.declare_namespace >which is being called by modules. Runtime code that requests activation of an egg can currently result in declare_namespace() being called (see Distribution.activate()), and the import lock thus won't be held at that point in time. | https://mail.python.org/pipermail/distutils-sig/2007-February/007282.html | CC-MAIN-2014-15 | refinedweb | 422 | 76.42 |
.
How to Get Type Name without full namespace in C# ?
If you want to find the full name of the type in C# , you can use the typeof keyword to do it as shown in the below code snippet.
var str1 = typeof (Author).ToString();
The problem with this method is that it displays the full name along with the namespace.
If you want to get only the class name without namespace , you can use the Name property of MemberInfo class as shown below.
var str2 = typeof(Author).Name; Console.WriteLine("using typeof(Author).Name results in " + str2);
Constant->static and readonly->instance field in C#
There; } }
3 options to return multiple values from a method in C#
There"; }
Failed to compare two elements in the array in C#
When you want to use the Sort method of the List<T> (without parameters) , you should be implementing the IComparable<T> interface.
Q&A #47 – Do you know what is Lightning ?
.NET Developers , have you heard of this term “Lightening” ?.
BUILD 2016 Live Streaming
Tilde (~) Symbol in the Enum definition in C#
During a casual discussion with one of my friend , I came across a question on whether the tilde(~) symbol can be used in the enum definition as shown below.
public enum TypeData { All = ~0, None = 0 }
Windows 10 Step by Step Tutorial – Copy and Paste Functionality
IntroductionThere are various ways in which you can exchange data between apps in Windows Apps. Some of the techniques include
- Copy and Paste
- Share Contract
- Drag and Drop
Tutorial – How to integrate Copy and Paste functionality in UWP apps?Integrating the Copy and paste functionality in a UWP app is a four step process 1. Add the namespace “Windows.ApplicationModel.DataTransfer” to the code behind file. Create an instance of the DataPackage class and specify the RequestedOperation property to the desired functionality.
DataPackage dataPackageobj = new DataPackage { RequestedOperation = DataPackageOperation.Copy };
How to run Visual Studio 2015 in safe mode?
There are times when you Visual Studio instance might not start up correctly. One of the best option during this time is to use Microsoft Visual Studio in safe mode. By running the Visual Studio in safe mode, you work with the default environment. In this mode, all the third party extensions would be disabled. This would help you identify if at all the problem was caused by any third party add-ins.
How to run Visual Studio 2015 in safe mode?
To run Visual Studio 2015 in safe mode, open Developer Command Prompt for VS2015 and type the command devenv.exe /safemode
After the command is executed, Microsoft Visual Studio 2015 will start in safe mode which is indicated in the title bar of Visual Studio 2015. | http://developerpublish.com/ | CC-MAIN-2016-22 | refinedweb | 452 | 62.98 |
In this article, we will continously learn with the Open Closed Principle. Let’s get started.
Table of contents
- Open Closed Principle
- OCP Implementation Strategies
- Appyling OCP for Frameworks and APIs
- Wrapping up
Open Closed Principle
The Open Closed Principle states that:
Classes, functions, and modules should be closed for modification, but open for extension.
But what does closed for modification and open for extension really mean?
Well, a class is closed for modification if for each feature that we need to add, we do not touch an existing source code. The source code basically becomes immutable.
At the same time, a component is open for extension if it allows us to make it behave in new ways by creating or writing new code. And the open closed principle tries to re-conciliate these two mantras.
Assume that we have a system with three classes, A, B and C.
We want to implement a new feature, and we go ahead and do that by modifying code in Class A. Do notice that Classes B and C depend upon Class A. When we modified Class A by mistake, we also broke Class B because Class B was dependent on it. That’s the main problem with modifying existing source code. There is a high risk of breaking other components, and this is just a very simple example.
In a real application, the dependency graph is much more complex, and changes to particular components can have ripple effects in various parts of the system. Again, this is fragility. A better approach would have been to implement that change and put it in a new component. Let’s call it as Class D.
If we do this, then we implement our feature, but we do not touch the existing system. Therefore, we have a very low risk of introducing regression bugs.
Why we should apply the OCP
New features can be added easily and with minimal cost.
Even in applications that are very tangled and old and complex, each time we need to make a change, the best way is to put that change in a separate component, write a unit test for it.
So, we can use the OCP in every application.
Minimizes the risk of regression bugs.
Enforces decoupling by isolating changes in specific components, works along with the SRP.
OCP Implementation Strategies
Modifying existing code is not the best approach when dealing with areas of an application that are very susceptible to change. There is a better way to implement changes without modifying existing code, and that is by extending its capabilities. There are two great ways to do that.
Using inheritance
Using strategy design pattern
For example, we have a BankAccount class, and it exposes a feature for transferring money internally in the same country. And now we have a new request to also handle international transfers. Now the worst approach to this would be to start modifying the existing transferMoney() method and put the logic for the international transfer.
public class BankAccount { // ... void transferMoney(double amount) { // business logic for local transfer } }
We are not going to do that. Instead, we are going to extend the capabilities of this class. The easiest way to do that is by using
inheritance.
public class InternationalBankAccount extends BankAccount { // ... @Override void transferMoney(double amount) { // business logic for international transfer } }
We can simply create a new class called
InternationalBankAccount, which extends the BankAccount class and simple overrides overrides the
transferMoney() method with business logic for international transfer. We are basically creating a new component that can handle international money tranfers, but we’re not touching the original BankAccount class. Iheritance is a good way to apply the Open Closed Principle. It does, however, have a small drawback. Inheritance produces coupling between the derived classes and the base class, especially when we are using a concrete class as the base class.
A better approach to applying the open closed principle is a design pattern called the strategy pattern. In the startegy pattern, we are not using inheritance, but we are using interfaces. So instead of creating new clases for each bank account transfer type, we are extracting that functionality into an interface.
public interface MoneyTransferProc { public void transferMoney(double amount); } public class BankAccount implements MoneyTransferProc { public void transferMoney(double amount) { ... } } public class IntlBankAccount implements MoneyTransferProc { public void transferMoney(double amount) { ... } }
We create classes BankAccount, IntlBankAccount that implement MoneyTransferProc interface, each of them can provide their own implementation for this method. However, BankAccount and IntlBankAccount are not linked in any other way. IntlBankAccount does not inherent from BankAccount. This means that these two classes can evolve independently. They have no coupling with each other.
public class MoneyTransferProcessorFactory { public void MoneyTransferProc build(TransferType type) { if (type == TransferType.Local) { return new BankAccount(); } else if (type == TransferType.Intl) { return new IntlBankAccount(); } } } void processPayment(double amount, TransferType type) { // ... MoneyTransferProc mtp = factory.build(type); mtp.transferMoney(amount); }
Afer we have out strategies, we need the factory that is capable to build them based on a particular property like a TransferType. The beaty of this is that every time we need to add new transfer capabilities, we do not need to modify this class. Nor do we need to modify existing strategies like BankAccount or IntlBankAccount. All we have to do is create a new component, implements the MoneyTransferProc interface, and provide that concrete implementation.
Which one should we choose?
If we start small, in the beginning, We do not have to create new components to implement changes for the first time. Instead, make those changes inline, and then if there is a real need, extract them to different components.
Also, don’t apply the open closed principle for bug fixing. If we have a broken component, we should change that component and make it work as expected.
If we have areas of our code that are likely to change over time, then we should probably consider one of the two alternatives for applying the OCP.
Start with inheritance, if that does the trick.
If we need something more powerful or more flexible, then we should consider design pattern like strategy.
Appyling OCP for Frameworks and APIs
When we’re working with many APIs, libraries or frameworks, sometimes we find that we want to modify the signature of methods to suitable our need. But we might use it in ways that we aren’t aware of.
So, it’s important to know how to apply the open closed principle when designing frameworks or SDKs.
For example, we create a framework that has a TaxCalculator class to calculate some taxes. We package our SDK into a JAR file, we put it on Maven, and then our clients can use it in their own applications.
public class TaxCalculator { public double calculate(Employee e) { // business logic } }
However, later on, we decide that we want to also include currency in the TaxCalculator, and we do that by violating the open closed principle. We basically modify the existing TaxCalculator, add we add the new parameter to the calculate() method.
public class TaxCalculator { public double calculate(Employee e, String currency) { // business logic } }
Although our code might work, when our clients get the updated version of the framework, their code will break. Changing existing functionality in publicly exposed frameworks can have devastating effects on the consumers.
How can we apply the open closed principle in this scenario?
We can make our library open for extension. For example, we could extract an interface called AbstractTaxCalculator. Then in our framework, we provide some implementations from default implementations for it. And when the customers are not satisfied with the default implementations, they can just create a new class, implement the AbstractTaxCalculator that we created, and provide their own logic. This is what an extesible framework looks like.
public interface AbstractTaxCalculator { public double calculate(Employee e, String currency); } public CustomerUSACalc implements AbstractTaxCalculator { public double calculate(Employee e, String currency) { // business logic } }
We provide our clients with interfaces that can act like extension points where they can hook up their custom logic with our framework.
Below is the best practices for changing APIs:
- Do not change existing public contracts: data classes, signatures.
- Expose abstractions to our customers and let them add new features on top of our framework.
- If a breaking change is inevitable, give our clients time to adapt.
Wrapping up
- API is a contract / agreement between different software components on how they should work together.
Refer:
SOLID Software Design Principles in Java | https://ducmanhphan.github.io/2020-01-07-Understanding-about-SOLID-part-2/ | CC-MAIN-2021-25 | refinedweb | 1,410 | 55.54 |
In this post a computer will learn basic algebra, from scratch! Not excited? Keep reading. This is an introduction to basic sequence-to-sequence learning using a Long short term memory (LSTM) module.
Sequences of varying length are everywhere around us. Yet most machine-learning problems are presented as "here are five features describing each instance, please predict these three properties". Or some variation on this. This is not a particularly good fit with sequences of varying length like: sentences, sound recordings, or time series data. In addition the order in which things occur in the sequence carries meaning. Let's take advantage of all that structure!
Imagine trying to shoehorn the task of translating English sentences to German sentences into a classical $N$ features and $M$ outputs setup. A bit of a nightmare. This is where sequence to sequence learning comes in. You feed in a sequence and produce a new sequence, potentially of different length.
You can use this for translating English to German, generating captions for images, or as we will do: learn how to do basic algebra.
The Problem¶
Given a string of characters representing a math problem
"3141+42" we would like
to generate a string of characters representing the correct solution:
"3183". Our
network will learn how to do addition, subtraction, multiplication and division.
The important part is that we will not first use our human intelligence to break the string up into integers and a mathematical operator. We want the computer to figure all that out by itself.
Let's go! This post will use the excellent
keras deep-learning
library and is based on one of their examples.
First some imports, and then we generate examples.
%matplotlib inline %config InlineBackend.figure_format='retina'
import operator import numpy as np import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = (8, 8) plt.rcParams["font.size"] = 14 from sklearn.cross_validation import train_test_split from sklearn.utils import check_random_state from keras.models import Sequential from keras.layers import Dense, RepeatVector, TimeDistributed, Activation from keras.layers.recurrent import LSTM from keras.optimizers import SGD
Using Theano backend.
OPS = ['+', '*', '-', '/'] ABC = '1234567890' + ''.join(OPS) + '. '
Creating Examples¶
Using simple algebra problems like this demonstrates all the basics of sequence to sequence learning and allows us to generate a lot of data very quickly (compared to say audio recordings).
We need a way to represent a sequence of characters as a sequence of
binary vectors, this is what
encode and
decode take care of. Each
character is one-hot encoded. The
make_maths_problem function uses them to generate a large set of
examples.
def encode(characters): """Encode a string as an array of integers.""" char_idx = dict((c, i) for i, c in enumerate(ABC)) X_ = np.zeros((len(characters), len(ABC))) for i, c in enumerate(characters): try: X_[i, char_idx[c]] = 1 except: print('chars:', characters) print(i, c, char_idx[c], X_.shape) return X_ def decode(X, calc_argmax=True): """Decode an array of integers to a string.""" idx_char = dict((i, c) for i, c in enumerate(ABC)) X = X.argmax(axis=-1) return ''.join(idx_char[i] for i in X) # Generate data def make_maths_problem(n_samples=1000, n_digits=3, invert=True, random_state=None): rng = check_random_state(random_state) X_ = [] y_ = [] assert all(op in ABC for op in OPS), "Not all operations are in the alphabet" math_op = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv} n_ops = len(OPS) # the one represents the character for the operator max_len = 2 * n_digits + 1 while len(X_) < n_samples: a, b = rng.randint(10**n_digits, size=2) op = rng.choice(OPS) a_op_b = "%i%s%i" % (a, op, b) if a_op_b not in X_: answer = math_op[op](a, b) if answer == np.inf or np.isnan(answer): continue if invert: X_.append(a_op_b.ljust(max_len)[::-1]) else: X_.append(a_op_b.ljust(max_len)) # make sure the string is white space padded but no longer # than the max length (could happen when representing 1/3) y_.append(str(answer).ljust(2 * n_digits)[:2 * n_digits]) X = np.zeros((n_samples, max_len, len(ABC)), dtype=np.bool) y = np.zeros((n_samples, 2 * n_digits, len(ABC)), dtype=np.bool) for i, x in enumerate(X_): X[i] = encode(x) for i, x in enumerate(y_): y[i] = encode(x) return (X, y)
encode("23+42")
array([[ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
Let's try out our math problem generator and check that we can correctly round trip problems:
X, y = make_maths_problem(10, n_digits=3) for i in range(10): # undo question reversal q = decode(X[i][::-1]) correct = decode(y[i]) print(q, '=', correct)
646/541 = 1.1940 31*70 = 2170 12+757 = 769 96*516 = 49536 291/612 = 0.4754 22+941 = 963 188*632 = 118816 370/824 = 0.4490 794*918 = 728892 136/201 = 0.6766
X, y = make_maths_problem(2*50000, n_digits=3, random_state=234) X_train,X_test, y_train,y_test = train_test_split(X, y, train_size=0.8)
def rnn_model(hidden_size=128, n_digits=3, abc_size=len(ABC)): model = Sequential() # encoder model.add(LSTM(hidden_size, input_shape=(None, abc_size))) # input for the decoder # this sets the length of the output sequence and has to # match the length we used when constructing the examples model.add(RepeatVector(2 * n_digits)) # decoder model model.add((LSTM(hidden_size, return_sequences=True))) # For each step of the output sequence, decide which character should be chosen model.add(TimeDistributed(Dense(abc_size))) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model
BATCH_SIZE = 128 model = rnn_model() # use same 10 examples for all iterations n_test = 10 idx = np.random.randint(len(X_test), size=n_test) Xs, ys = X_test[idx], y_test[idx] for iteration in range(3): print() print('-' * 50) print('After', 10 * (iteration + 1), 'epochs:') model.fit(X_train, y_train, batch_size=BATCH_SIZE, nb_epoch=10, verbose=False, validation_data=(X_test, y_test)) probas = model.predict_proba(Xs, verbose=0) for i in range(n_test): # undo question reversal q = decode(Xs[i][::-1]) correct = decode(ys[i]) guess = decode(probas[i]) print(q, '=', correct, '=?', guess)
-------------------------------------------------- After 10 epochs: 586/75 = 7.8133 =? 7.9211 943-826 = 117 =? 135 249/532 = 0.4680 =? 0.4999 241-660 = -419 =? -493 368*178 = 65504 =? 63392 110-948 = -838 =? -866 7/277 = 0.0252 =? 0.0192 522/956 = 0.5460 =? 0.5959 61*454 = 27694 =? 29992 260*994 = 258440 =? 289960 78*459 = 35802 =? 39992 79+450 = 529 =? 633 764+190 = 954 =? 992 335*477 = 159795 =? 163925 887*263 = 233281 =? 219999 183-864 = -681 =? -695 53-116 = -63 =? -15 453+214 = 667 =? 673 837+392 = 1229 =? 1235 924/134 = 6.8955 =? 5.5522 -------------------------------------------------- After 20 epochs: 586/75 = 7.8133 =? 7.28 943-826 = 117 =? 111 249/532 = 0.4680 =? 0.4414 241-660 = -419 =? -413 368*178 = 65504 =? 66444 110-948 = -838 =? -812 7/277 = 0.0252 =? 0.0211 522/956 = 0.5460 =? 0.5410 61*454 = 27694 =? 24444 260*994 = 258440 =? 251460 78*459 = 35802 =? 34444 79+450 = 529 =? 535 764+190 = 954 =? 966 335*477 = 159795 =? 154025 887*263 = 233281 =? 244441 183-864 = -681 =? -675 53-116 = -63 =? -75 453+214 = 667 =? 665 837+392 = 1229 =? 1225 924/134 = 6.8955 =? 6.2424 -------------------------------------------------- After 30 epochs: 586/75 = 7.8133 =? 8.23 943-826 = 117 =? 113 249/532 = 0.4680 =? 0.4765 241-660 = -419 =? -419 368*178 = 65504 =? 66664 110-948 = -838 =? -832 7/277 = 0.0252 =? 0.0251 522/956 = 0.5460 =? 0.5561 61*454 = 27694 =? 26332 260*994 = 258440 =? 265360 78*459 = 35802 =? 34776 79+450 = 529 =? 533 764+190 = 954 =? 954 335*477 = 159795 =? 153985 887*263 = 233281 =? 233351 183-864 = -681 =? -681 53-116 = -63 =? -67 453+214 = 667 =? 667 837+392 = 1229 =? 1229 924/134 = 6.8955 =? 6.2618
def fractional_difference(n_test=200): idx = np.random.randint(len(X_test), size=n_test) Xs, ys = X_test[idx], y_test[idx] probas = model.predict_proba(Xs, verbose=0) true_ = np.array([float(decode(ys[i])) for i in range(n_test)]) predicted_ = np.array([float(decode(probas[i])) for i in range(n_test)]) _ = plt.hist((true_ - predicted_)/true_, range=(-0.1, 0.1), bins=20) plt.xlabel('(true-guess)/true') plt.xlim(-0.11, 0.11) fractional_difference()
It looks as if after such a short amount of training we get within roughly 5% of the right answer, and frequently even closer. From monitoring the loss on an evaluation set I think this network would continue to improve if trained for a larger number of epochs.
Conclusion¶
While the network does not perform perfectly yet, this illustrates how to build a network that performs sequence-to-sequence learning. Without any knowledge about algebra or even digits it learnt to do reasonably well on basic math problems. It even figured out how to use the decimal point!
Some next steps could be:
- generating words instead of numbers, the network would output
"thirtytwo"instead of
"32";
- using images of digits as input instead of strings;
- using voice as input or output; or
- solving a completely different problem based around sequences.
Get in touch on twitter @betatim if you have questions or comments.
This post started life as a jupyter notebook, download it or view it online. | http://betatim.github.io/posts/algebra-from-scratch/ | CC-MAIN-2018-30 | refinedweb | 1,524 | 62.85 |
SYNOPSIS
#include <libaio.h>
int io_submit(aio_context_t ctx_id, long nr, struct iocb **iocbpp);
Link with -laio.
DESCRIPTION
io_submit() queues nr I/O request blocks for processing in the AIO con-
text ctx_id. iocbpp should be an array of nr AIO control blocks, which
will be submitted to context ctx_id.
RETURN VALUE
On success, io_submit() returns the number of iocbs submitted (which
may, August
2002.
CONFORMING TO
io_submit() is Linux-specific and should not be used in programs that
are intended to be portable.
NOTES
Glibc does not provide a wrapper function for this system call.
The wrapper provided in libaio for io)
COLOPHON | http://www.linux-directory.com/man2/io_submit.shtml | crawl-003 | refinedweb | 103 | 67.35 |
nsAString
From MDC
[edit] Summary
The
nsAString abstract class represents a character string composed of double-byte storage units. This class is typically used to represent Unicode character arrays.
#include "nsStringAPI.h" class nsAString { ... };
[edit] Typedefs
- char_type [PRUnichar]
- Storage unit for this class.
- self_type [nsAString]
- An alias for the type of this class.
- size_type [PRUint32]
- Type used to represent the number of double-byte units stored in the string.
- index_type [PRUint32]
- Type used to represent an offset into the string.
[edit]).
Assign
- The Assign family of functions sets the value of a string's internal buffer.
Replace
- The Replace family of functions sets the value of a string's internal buffer.
Append
- The Append family of functions appends a value to the end of a string's internal buffer.
Insert
- The Insert family of functions inserts a value into a string's internal buffer.
Cut
- The Cut function removes a section of the string's internal buffer.
[edit] Operators
operator=
- This operator is a shortcut for the
Assignfamily of functions.
operator+=
- This operator is a shortcut for the
Appendfamily of functions.
[edit] Remarks
The
nsAString class is never instantiated directly. It should be instantiated using a subclass, such as
nsEmbedString .
nsAString corresponds to the AString and DOMString XPIDL data types.
nsAString by itself does not imply a particular character encoding. That is, it may be used to store UTF-16 characters, UCS-2 characters, or any random double-byte data. The character encoding in use for a particular
nsAString instance depends on the context in which it is used. If used with XPIDL, then the character encodings of the corresponding XPIDL data types applies.
nsAString may even hold data with embedded null values. Thus, the length of the data contained in the
nsAString should be determined by calling the
nsAString::Length method.
The methods defined on
nsAString are implemented as inline wrappers around the XPCOM string functions, prefixed with NS_String. See, for example,
NS_StringGetData.
[edit] See Also
nsAString::Length,
EndReading,
NS_StringGetData,
nsEmbedString | http://developer.mozilla.org/en/docs/nsAString | crawl-001 | refinedweb | 332 | 50.53 |
Android write efficient code
There is no doubt that devices based on Android platform must be embedded devices. Modern handheld devices is not just a simple phone, it is a small handheld computer, but even the fastest of the most high-end handheld devices far smaller than a medium-performance desktop machine.
This is why the procedure in the preparation of Android moment when consider implementing Di efficiency, these systems Bushixiangxiang in the so fast, Bingju you consider Ta Hai Yao Neng Li battery's life. This means that there is little space left for you to go to waste, so, in the process when you write Android to make your code as possible while optimizing efficiency.
This page describes several Android allows developers to run a more efficient way. Some jump through the following link, you can learn how to make your program run more efficiently
Content
- Introduction
- To avoid creating an object
- Use their own methods
- Better than the use of virtual interfaces
- Better than using a static virtual
- Avoid internal use Setter and Getter
- Buffer attribute called
- Final statement of constant
- Prudent use of enhanced For loop
- Avoid Enums to avoid the type listed
- Package through the use of space within the joint class
- Avoid floating-point type
- Comparison of some of the standard operation of the time
- Conclusion
Introduction
How to determine a system for the irrational, there are two basic principles:
- Do not do unnecessary things to do.
- As much as possible to save memory usage.
All of the following methods are based on these two.
Some may think that this page has spent a lot of space to say how "preliminary optimization" (premature optimization). Although sometimes micro-optimization of the development of efficient data structures and algorithms is very difficult, but in the embedded handheld devices, you have no choice above. For example, if the desktop virtual machine migration to your Android system, you will find that you write your program will run out of memory. This will cause the program up and running extremely slow, even without considering the rest of its system of running the program.
This is why the above two principles are so important. Android's success is the development of procedures available to the user experience, user experience, good or bad, however, decided whether the code in your timely response and thus will not make people slow collapse. Because we all procedures to run in the same equipment, so we consider them as a whole. This test driver's license as you need to learn the rules of the road is the same: If the owner to comply with, things will be very smooth; but when you do not comply, you will crash.
Before we discuss substantive issues, there is a brief explanation: Regardless of whether the virtual machine is a Java compiler features all the views presented below are correct. If we have two ways to accomplish the same thing, but foo () to explain the implementation of faster than bar (), then foo () will not build speed than the bar () slow, only by compiling the code allows you to run speed boost is unwise.
As far as possible to create objects (Object)
Object creation is not without cost. Distribution with a thread pool of generational memory management mechanism will reduce the cost of creating temporary objects are not allocated memory does not allocate memory is not as good.
If you are in a cycle of the user interface assigned an object, you have to force the recall of memory, it would appear to make the user experience a little "hiccup" phenomenon.
Therefore, if there is no need you should not create the object instance. Here is a helpful example:
- When the input data from the original extract the string, try to return a child from the original string, string, rather than creating a copy. You will create a new string object, but it and your original data shared data space.
- If you have a return string to method, you should be aware of any case that the result is StringBuffer, change your the function of Definition and enforced so that function directly to return rather than Tongguo create a temporary object.
A more radical approach is to partition a multidimensional array into several parallel one-dimensional array:
- An array of type Int than an array of Integer type is better, but the same could be summarized in such a principle, two types of arrays Int than a (int, int) the efficiency of an array of objects to be much higher. For other primitive data types, this principle applies.
- If you need to create an object that contains a series of Foo and Bar containers (container), remember: two parallel Foo [] and Bar [] than a (Foo, Bar) array of objects much more efficient. (This example also has an exception, when you design the interface API when other code; in this case, the speed of a point on the loss would not have considered. But, in your code inside, you should try to write efficient code. )
In general, as much as possible to avoid creating short-term temporary objects. Less object creation means less garbage collection, which will improve the quality of your program's user experience.
Use their own methods (Use Native Methods)
When dealing with strings, do not hesitate to use as much as possible, such as String.indexOf (), String.lastIndexOf () method with this object itself. Because these methods use C / C + + to achieve, than in a java loop do the same thing 10-100 times faster.
Another point to add clear is that these methods use the cost of Zi Shen Jie Shi Guo's methods than those Gao Henduo, Yin Er, Duiyu minor operations, as Buyongzhelei method.
Better than the use of virtual interfaces
Suppose you have a HashMap object, you can declare it is a HashMap or is just a Map:
Map myMap1 = new HashMap(); HashMap myMap2 = new HashMap();
Which is better?
Generally wise to use the Map, because it can allow you to change the Map interface to implement any of these things, but this "sensible" approach is only applicable to regular programming, not suitable for embedded systems. Reference to the call through the interface will take more than 2 times the time, as opposed to through a specific reference to the virtual function call.
If you choose to use a HashMap, because it is more suited to your program, then use the Map will be worthless. Suppose you have a can restructure your code integrated coding environment, then call the Map of no use, even if you're not sure where at the beginning of your program. (Similarly, public of the API is an exception, the value of a good API is often greater than the efficiency at which point loss)
Better than using a static virtual
If you do not need to access the external object, then make your way to a static method. It will be faster call, because it does not need a virtual function-oriented form. It is also a good practice, because it tells you how to distinguish the nature of the method (signature), calling this method does not change the object state.
As far as possible avoid the use of inherent Get, Set Methods
Like C + + iyangde programming language, often using Get methods (for example
i = getCount()) to replace the direct access to the property (
i=mCount). This is in C + + programming which is a good habit, because the compiler will access method is set to Inline, and if you want to bind or debug attribute access, you only need to add some code at any time.
In the Android programming, this is not a very good idea. Virtual method call will generate a lot of costs, the cost of queries than the instance of the property even more. We should use the external call functions Get and Set, but internal calls, we should be called directly.
Buffer attribute called Cache Field Lookups
Access object property is much slower than access to local variables. You should not write your code:
for (int i = 0; i < this.mCount; i++) dumpItem(this.mItems[i]);
It should read:
int count = this.mCount; Item[] items = this.mItems; for (int i = 0; i < count; i++) dumpItems(items[i]);
(We direct use "this" that these are its member variables)
A similar principle: that no statement in a For the second time in calling a class method. For example, the following code will be implemented again and again getCount () method, which is a great way to waste than you hide it directly to a Int variable.
for (int i = 0; i < this.getCount(); i++) dumpItems(this.getItem(i));
This is a good way, when you call more than once a instances, the direct localization of this example, this example of some of the value assigned to a local variable.); } }
There are four attributes
mScrollBar call to
mScrollBar buffer to a stack variable among the four members of the property will become four times the call stack access, this will improve efficiency.
Incidentally, the method also can be the same as local variables with the same characteristics.
Final statement of constant
We can look at a class at the top of the following statements:
static int intVal = 42; static String strVal = "Hello, world!";
When a class of first use, the compiler will call a class initialization method -
<clinit>, this method will be 42 deposited into variable
intVal, and for
strVal string constant in the class file to extract a reference scale, when these values later reference, they will call the property directly.
We can use the keyword "final" to improve the code:
static final int intVal = 42; static final String strVal = "Hello, world!";
This class will not call es a
<clinit> method, because these constants are directly written into the class static attribute initialization file, this initialization directly from the virtual machine to handle. Code will be used to access
intVal 42 Integer types, access
strVal will use the relative savings in "constant string" to replace a property called.
A class or method declared as "final" and will not bring any benefits of implementation, it can carry out some of the most optimized. For example, if the compiler knows that a quilt class can not be overloaded Get method, it put the function set to Inline.
At the same time, you can also declare local variables final variable. However, this is meaningless. As a local variable, use the final only to make the code more clear (or you have to use inline anonymous access class).
Prudent use of Enhanced For loop
Enhanced For loop (which is often said the "For-each loop") is often used to collect Interface Iterable interface inheritance above. In these objects inside a iterator is assigned to an object to call its hasNext () and next () method. In an array list which you can access the perfunctory own it, in other collector inside, enhanced for loop is equivalent to the use of iterator.
Nevertheless, the following source code shows an acceptable enhanced for loop example: () function in each cycle of re-obtain the static properties of the two, get the array length of time.
one () function to everything into local variables, to avoid the class to find attribute called
two () function uses the Java language for the 1.5 version of the loop, the editor generated source code into account the reference copy of the array and the length of the array to a local variable is an array of cases over the better method, which in the main loop does have an additional loading and storage process (apparently saved the "a"), compared to the function one (), it's slowed down a little bit and 4 bytes of growth.
Conclusion, we can get: enhanced for loop in the array which performed well, but when and Iterable object when used with caution, because this creates more of an object.
Avoid Enums to avoid the type listed
Enumerated type is very easy to use, when taking into account the size and speed, they would seem costly, for example:
public class Foo { public enum Shrubbery { GROUND, CRAWLING, HANGING } }
This will be transformed into a 900 bytes of class file (Foo $ Shrubbery.class). First use, type De initialization Yaozai exclusive method of Qu Miaoshu listed above, call each item returned to load each one has its own Jingtaikongjian, the Pi stored in an array inside (1 Called "$ VALUE "static array). It was a lot of code and data, just to the three integer values.
Shrubbery shrub = Shrubbery.GROUND;
This will cause a static property of the call, if the Final GROUND is a static variable, the compiler will it as a constant in the code nested inside.
Another point to say, through the list, you can get a better API and some compile time checks. Therefore, a more balanced approach is: you should make every method in your public API to use list variables, when dealing with issues on the avoided as much as possible.
In some environments the following by
ordinal () method to get a list of integer variables is useful, for example: the following code
for (int n = 0; n < list.size(); n++) { if (list.items[n].e == MyEnum.VAL_X) // do stuff 1 else if (list.items[n].e == MyEnum.VAL_Y) // do stuff 2 }
Replace conditions, it will run faster, though not guaranteed.
Package through the use of space within the joint class
We look at the following class declaration
public class Foo { private int mValue; public void run() { Inner in = new Inner(); mValue = 27; in.stuff(); } private void doStuff(int value) { System.out.println("Value is " + value); } private class Inner { void stuff() { Foo.this.doStuff(Foo.this.mValue); } } }
Here we should note that we define an inline type, it calls the external class of private methods and private property. This is a legitimate call, the code should show "Value is 27".
The problem is, in theory Foo $ Inner (background on) should be a completely separate class, it calls irregularities in the private members of the Foo. To compensate for this shortcoming, the compiler produces a synthetic method:
/*package*/ static int Foo.access$100(Foo foo) { return foo.mValue; } /*package*/ static void Foo.access$200(Foo foo, int value) { foo.doStuff(value); }
When the in-class access from the outside "mValue" and called "doStuff" when the inline type will call these static methods, which means you do not directly access the class members, but by way of public access. We talked about the previous indirect access slower than direct access, so this is a language used by the invisible implementation example.
To have a package within the joint space of the direct statement of need to access class properties and methods, we can avoid this problem, philosophical poetry is package space, rather than private space. It runs faster and go in front of things in addition to generating functions. (Unfortunately, it also means that the property also can be the same package the other classes the following direct access to the Wei Fan a standard object-oriented of the principle of private property Shisuo You. Similarly, Ru Guo is a public API you design should carefully consider the use of this optimization)
Avoid the use of floating-point type
Before the release of the Pentium CPU, the game as much as possible the use of type Integer mathematical function is normal. Inside the Pentium processor, floating point processing into it a prominent feature, and the interactive use of floating point and integer integer comparison alone, the former will make your game run faster, the average desktop computer We can use the above free float.
Unfortunately, the embedded processors usually do not support floating-point processing, vaginal teeth all the "float" and "double" is done via software, and some basic floating point operation takes milliseconds to time.
Colleagues, even integer, a number of chips not only multiplication division. In these cases, the integer division and modulus operations are implemented by software. When you create a Hash Table, or a lot of math, this is what you need to consider.
Comparison of some of the standard operation of the time
In order to explain our point of view from, here is a table, including some of the basic operation of the approximate time used. Note that the time is not absolute time, absolute time, taking into account the CPU and clock frequency. Systems, the time will be different in size. Of course, this is a meaningful comparison, we can call different operation than the relative time spent. For example, add a member variable of time is to add a local variable of the four times.
Conclusion
Efficient embedded process writing the best way is to figure out what happened to your writing process. If you really want to assign an iterator class, all the way into a List in the use of enhanced for loop, make it a practice of knowingly, rather than an inadvertent omission, but a negative impact.
Prepared and find out what you are doing! You can if you own some of the code of conduct, but must pay attention to what your code is doing, and then start looking for ways to optimize it. | http://www.codeweblog.com/change-the-preparation-of-efficient-android-code/ | CC-MAIN-2016-30 | refinedweb | 2,880 | 55.98 |
And of course I meant import-sig. -- Eric. "Eric V. Smith" <eric at trueblade.com> wrote: I think restarting the discussion anew here on distutils-sig is appropriate. -- Eric. Guido van Rossum <guido at python.org> wrote: Martin has asked me to decide on PEP 382 vs. PEP 402 (namespace packages) in time for inclusion of the decision in Python 3.3. As people who attended the language-sig know, I am leaning towards PEP 402 but I admit that at this point I don't have enough information. If I have questions, should I be asking them on the import-sig or on python-dev? Is it tolerable if I ask questions even if the answer is somewhere in the archives? (I spent a lot of time reviewing the "pitchfork thread",, but that wasn't particularly fruitful, so I'm worried I'd just waste my time browsing the archives -- if the PEP authors did their jobs well the PEPs should include summaries of the discussion anyways.) -- --Guido van Rossum (python.org/~guido) _____________________________________________ Import-SIG mailing list Import-SIG at python.org -------------- next part -------------- An HTML attachment was scrubbed... URL: <> | https://mail.python.org/pipermail/import-sig/2012-March/000412.html | CC-MAIN-2014-10 | refinedweb | 192 | 74.69 |
Building A Stocks Price Notifier App Using React, Apollo GraphQL And Hasura that event to happen. The events-based terminology is also quite common in the world of software.
How awesome would that be if you could get the updates of the price of your favorite stock on your phone?
In this article, we’re going to build a Stocks Price Notifier application by using React, Apollo GraphQL, and Hasura GraphQL engine. We’re going to start the project from a
create-react-app boilerplate code and would build everything ground up. We’ll learn how to set up the database tables, and events on the Hasura console. We’ll also learn how to wire up Hasura’s events to get stock price updates using web-push notifications.
Here’s a quick glance at what we would be building:
Let’s get going!
An Overview Of What This Project Is About
The stocks data (including metrics such as high, low, open, close, volume) would be stored in a Hasura-backed Postgres database. The user would be able to subscribe to a particular stock based on some value or he can opt to get notified every hour. The user will get a web-push notification once his subscription criteria are fulfilled.
This looks like a lot of stuff and there would obviously be some open questions on how we’ll be building out these pieces.
Here’s a plan on how we would accomplish this project in four steps:
- Fetching the stocks data using a NodeJs script
We’ll start by fetching the stock data using a simple NodeJs script from one of the providers of stocks API — Alpha Vantage. This script will fetch the data for a particular stock in intervals of 5mins. The response of the API includes high, low, open, close and volume. This data will be then be inserted in the Postgres database that is integrated with the Hasura back-end.
- Setting up The Hasura GraphQL engine
We’ll then set-up some tables on the Postgres database to record data points. Hasura automatically generates the GraphQL schemas, queries, and mutations for these tables.
- Front-end using React and Apollo Client
The next step is to integrate the GraphQL layer using the Apollo client and Apollo Provider (the GraphQL endpoint provided by Hasura). The data-points will be shown as charts on the front-end. We’ll also build the subscription options and will fire corresponding mutations on the GraphQL layer.
- Setting up Event/Scheduled triggers
Hasura provides an excellent tooling around triggers. We’ll be adding event & scheduled triggers on the stocks data table. These triggers will be set if the user is interested in getting a notification when the stock prices reach a particular value (event trigger). The user can also opt for getting a notification of a particular stock every hour (scheduled trigger).
Now that the plan is ready, let’s put it into action!
Here’s the GitHub repository for this project. If you get lost anywhere in the code below, refer to this repository and get back to speed!
Fetching The Stocks Data Using A NodeJs Script
This is not that complicated as it sounds! We’ll have to write a function that fetches data using the Alpha Vantage endpoint and this fetch call should be fired in an interval of 5 mins (You guessed it right, we’ll have to put this function call in
setInterval).
If you’re still wondering what Alpha Vantage is and just want to get this out of your head before hopping onto the coding part, then here it is:
Alpha Vantage Inc. is a leading provider of free APIs for realtime and historical data on stocks, forex (FX), and digital/cryptocurrencies.
We would be using this endpoint to get the required metrics of a particular stock. This API expects an API key as one of the parameters. You can get your free API key from here. We’re now good to get onto the interesting bit — let’s start writing some code!
Installing Dependencies
Create a
stocks-app directory and create a
server directory inside it. Initialize it as a node project using
npm init and then install these dependencies:
npm i isomorphic-fetch pg nodemon --save
These are the only three dependencies that we’d need to write this script of fetching the stock prices and storing them in the Postgres database.
Here’s a brief explanation of these dependencies:
isomorphic-fetch
It makes it easy to use
fetchisomorphically (in the same form) on both the client and the server.
pg
It is a non-blocking PostgreSQL client for NodeJs.
nodemon
It automatically restarts the server on any file changes in the directory.
Setting up the configuration
Add a
config.js file at the root level. Add the below snippet of code in that file for now:
const config = { user: '<DATABASE_USER>', password: '<DATABASE_PASSWORD>', host: '<DATABASE_HOST>', port: '<DATABASE_PORT>', database: '<DATABASE_NAME>', ssl: '<IS_SSL>', apiHost: '', }; module.exports = config;
The
user,
host,
port,
database,
ssl are related to the Postgres configuration. We’ll come back to edit this while we set up the Hasura engine part!
Initializing The Postgres Connection Pool For Querying The Database
A
connection pool is a common term in computer science and you’ll often hear this term while dealing with databases.
While querying data in databases, you’ll have to first establish a connection to the database. This connection takes in the database credentials and gives you a hook to query any of the tables in the database.
Note: Establishing database connections is costly and also wastes significant resources. A connection pool caches the database connections and re-uses them on succeeding queries. If all the open connections are in use, then a new connection is established and is then added to the pool.
Now that it is clear what the connection pool is and what is it used for, let’s start by creating an instance of the
pg connection pool for this application:
Add
pool.js file at the root level and create a pool instance as:
const { Pool } = require('pg'); const config = require('./config'); const pool = new Pool({ user: config.user, password: config.password, host: config.host, port: config.port, database: config.database, ssl: config.ssl, }); module.exports = pool;
The above lines of code create an instance of
Pool with the configuration options as set in the config file. We’re yet to complete the config file but there won’t be any changes related to the configuration options.
We’ve now set the ground and are ready to start making some API calls to the Alpha Vantage endpoint.
Let’s get onto the interesting bit!
Fetching The Stocks Data
In this section, we’ll be fetching the stock data from the Alpha Vantage endpoint. Here’s the
index.js file:
const fetch = require('isomorphic-fetch'); const getConfig = require('./config'); const { insertStocksData } = require('./queries'); const symbols = [ 'NFLX', 'MSFT', 'AMZN', 'W', 'FB' ]; (function getStocksData () { const apiConfig = getConfig('apiHostOptions'); const { host, timeSeriesFunction, interval, key } = apiConfig; symbols.forEach((symbol) => { fetch(`${host}query/?function=${timeSeriesFunction}&symbol=${symbol}&interval=${interval}&apikey=${key}`) .then((res) => res.json()) .then((data) => { const timeSeries = data['Time Series (5min)']; Object.keys(timeSeries).map((key) => { const dataPoint = timeSeries[key]; const payload = [ symbol, dataPoint['2. high'], dataPoint['3. low'], dataPoint['1. open'], dataPoint['4. close'], dataPoint['5. volume'], key, ]; insertStocksData(payload); }); }); }) })()
For the purpose of this project, we’re going to query prices only for these stocks — NFLX (Netflix), MSFT (Microsoft), AMZN (Amazon), W (Wayfair), FB (Facebook).
Refer this file for the config options. The IIFE
getStocksData function is not doing much! It loops through these symbols and queries the Alpha Vantage endpoint
${host}query/?function=${timeSeriesFunction}&symbol=${symbol}&interval=${interval}&apikey=${key} to get the metrics for these stocks.
The
insertStocksData function puts these data points in the Postgres database. Here’s the
insertStocksData function:
const insertStocksData = async (payload) => { const query = 'INSERT INTO stock_data (symbol, high, low, open, close, volume, time) VALUES ($1, $2, $3, $4, $5, $6, $7)'; pool.query(query, payload, (err, result) => { console.log('result here', err); }); };
This is it! We have fetched data points of the stock from the Alpha Vantage API and have written a function to put these in the Postgres database in the
stock_data table. There is just one missing piece to make all this work! We’ve to populate the correct values in the config file. We’ll get these values after setting up the Hasura engine. Let’s get to that right away!
Please refer to the
server directory for the complete code on fetching data points from Alpha Vantage endpoint and populating that to the Hasura Postgres database.
If this approach of setting up connections, configuration options, and inserting data using the raw query looks a bit difficult, please don’t worry about that! We’re going to learn how to do all this the easy way with a GraphQL mutation once the Hasura engine is set up!
Setting Up The Hasura GraphQL Engine
It is really simple to set up the Hasura engine and get up and running with the GraphQL schemas, queries, mutations, subscriptions, event triggers, and much more!
Click on Try Hasura and enter the project name:
I’m using the Postgres database hosted on Heroku. Create a database on Heroku and link it to this project. You should then be all set to experience the power of query-rich Hasura console.
Please copy the Postgres DB URL that you’ll get after creating the project. We’ll have to put this in the config file.
Click on Launch Console and you’ll be redirected to this view:
Let’s start building the table schema that we’d need for this project.
Creating Tables Schema On The Postgres Database
Please go to the Data tab and click on Add Table! Let’s start creating some of the tables:
symbol table
This table would be used for storing the information of the symbols. For now, I’ve kept two fields here —
id and
company. The field
id is a primary key and
company is of type
varchar. Let’s add some of the symbols in this table:
symboltable. (Large preview)
stock_data table
The
stock_data table stores
id,
symbol,
time and the metrics such as
high,
low,
open,
volume. The NodeJs script that we wrote earlier in this section will be used to populate this particular table.
Here’s how the table looks like:
stock_datatable. (Large preview)
Neat! Let’s get to the other table in the database schema!
user_subscription table
The
user_subscription table stores the subscription object against the user Id. This subscription object is used for sending web-push notifications to the users. We’ll learn later in the article how to generate this subscription object.
There are two fields in this table —
id is the primary key of type
uuid and subscription field is of type
jsonb.
events table
This is the important one and is used for storing the notification event options. When a user opts-in for the price updates of a particular stock, we store that event information in this table. This table contains these columns:
id: is a primary key with the auto-increment property.
symbol: is a text field.
user_id: is of type
uuid.
trigger_type: is used for storing the event trigger type —
time/event.
trigger_value: is used for storing the trigger value. For example, if a user has opted in for price-based event trigger — he wants updates if the price of the stock has reached 1000, then the
trigger_valuewould be 1000 and the
trigger_typewould be
event.
These are all the tables that we’d need for this project. We also have to set up relations among these tables to have a smooth data flow and connections. Let’s do that!
Setting up relations among tables
The
events table is used for sending web-push notifications based on the event value. So, it makes sense to connect this table with the
user_subscription table to be able to send push notifications on the subscriptions stored in this table.
events.user_id → user_subscription.id
The
stock_data table is related to the symbols table as:
stock_data.symbol → symbol.id
We also have to construct some relations on the
symbol table as:
stock_data.symbol → symbol.id events.symbol → symbol.id
We’ve now created the required tables and also established the relations among them! Let’s switch to the
GRAPHIQL tab on the console to see the magic!
Hasura has already set up the GraphQL queries based on these tables:
It is plainly simple to query on these tables and you can also apply any of these filters/properties (
distinct_on,
limit,
offset,
order_by,
where) to get the desired data.
This all looks good but we have still not connected our server-side code to the Hasura console. Let’s complete that bit!
Connecting The NodeJs Script To The Postgres Database
Please put the required options in the
config.js file in the
server directory as:
const config = { databaseOptions: { user: '<DATABASE_USER>', password: '<DATABASE_PASSWORD>', host: '<DATABASE_HOST>', port: '<DATABASE_PORT>', database: '<DATABASE_NAME>', ssl: true, }, apiHostOptions: { host: '', key: '<API_KEY>', timeSeriesFunction: 'TIME_SERIES_INTRADAY', interval: '5min' }, graphqlURL: '<GRAPHQL_URL>' }; const getConfig = (key) => { return config[key]; }; module.exports = getConfig;
Please put these options from the database string that was generated when we created the Postgres database on Heroku.
The
apiHostOptions consists of the API related options such as
host,
key,
timeSeriesFunction and
interval.
You’ll get the
graphqlURL field in the GRAPHIQL tab on the Hasura console.
The
getConfig function is used for returning the requested value from the config object. We’ve already used this in
index.js in the
server directory.
It’s time to run the server and populate some data in the database. I’ve added one script in
package.json as:
"scripts": { "start": "nodemon index.js" }
Run
npm start on the terminal and the data points of the symbols array in
index.js should be populated in the tables.
Refactoring The Raw Query In The NodeJs Script To GraphQL Mutation
Now that the Hasura engine is set up, let’s see how easy can it be to call a mutation on the
stock_data table.
The function
insertStocksData in
queries.js uses a raw query:
const query = 'INSERT INTO stock_data (symbol, high, low, open, close, volume, time) VALUES ($1, $2, $3, $4, $5, $6, $7)';
Let’s refactor this query and use mutation powered by the Hasura engine. Here’s the refactored
queries.js in the server directory:
const { createApolloFetch } = require('apollo-fetch'); const getConfig = require('./config'); const GRAPHQL_URL = getConfig('graphqlURL'); const fetch = createApolloFetch({ uri: GRAPHQL_URL, }); const insertStocksData = async (payload) => { const insertStockMutation = await fetch({ query: `mutation insertStockData($objects: [stock_data_insert_input!]!) { insert_stock_data (objects: $objects) { returning { id } } }`, variables: { objects: payload, }, }); console.log('insertStockMutation', insertStockMutation); }; module.exports = { insertStocksData }
Please note: We’ve to add
graphqlURL in the
config.js file.
The
apollo-fetch module returns a fetch function that can be used to query/mutate the date on the GraphQL endpoint. Easy enough, right?
The only change that we’ve to do in
index.js is to return the stocks object in the format as required by the
insertStocksData function. Please check out
index2.js and
queries2.js for the complete code with this approach.
Now that we’ve accomplished the data-side of the project, let’s move onto the front-end bit and build some interesting components!
Note: We don’t have to keep the database configuration options with this approach!
Front-end Using React And Apollo Client
The front-end project is in the same repository and is created using the
create-react-app package. The service worker generated using this package supports assets caching but it doesn’t allow more customizations to be added to the service worker file. There are already some open issues to add support for custom service worker options. There are ways to get away with this problem and add support for a custom service worker.
Let’s start by looking at the structure for the front-end project:
Please check the
src directory! Don’t worry about the service worker related files for now. We’ll learn more about these files later in this section. The rest of the project structure looks simple. The
components folder will have the components (Loader, Chart); the
services folder contains some of the helper functions/services used for transforming objects in the required structure;
styles as the name suggests contains the sass files used for styling the project;
views is the main directory and it contains the view layer components.
We’d need just two view components for this project — The Symbol List and the Symbol Timeseries. We’ll build the time-series using the Chart component from the highcharts library. Let’s start adding code in these files to build up the pieces on the front-end!
Installing Dependencies
Here’s the list of dependencies that we’ll need:
apollo-boost
Apollo boost is a zero-config way to start using Apollo Client. It comes bundled with the default configuration options.
reactstrapand
bootstrap
The components are built using these two packages.
graphqland
graphql-type-json
graphqlis a required dependency for using
apollo-boostand
graphql-type-jsonis used for supporting the
jsondatatype being used in the GraphQL schema.
highchartsand
highcharts-react-official
And these two packages will be used for building the chart:
node-sass
This is added for supporting sass files for styling.
uuid
This package is used for generating strong random values.
All of these dependencies will make sense once we start using them in the project. Let’s get onto the next bit!
Setting Up Apollo Client
Create a
apolloClient.js inside the
src folder as:
import ApolloClient from 'apollo-boost'; const apolloClient = new ApolloClient({ uri: '<HASURA_CONSOLE_URL>' }); export default apolloClient;
The above code instantiates ApolloClient and it takes in
uri in the config options. The
uri is the URL of your Hasura console. You’ll get this
uri field on the
GRAPHIQL tab in the GraphQL Endpoint section.
The above code looks simple but it takes care of the main part of the project! It connects the GraphQL schema built on Hasura with the current project.
We also have to pass this apollo client object to
ApolloProvider and wrap the root component inside
ApolloProvider. This will enable all the nested components inside the main component to use
client prop and fire queries on this client object.
Let’s modify the
index.js file as:
const Wrapper = () => { /* some service worker logic - ignore for now */ const [insertSubscription] = useMutation(subscriptionMutation); useEffect(() => { serviceWorker.register(insertSubscription); }, []) /* ignore the above snippet */ return <App />; } ReactDOM.render( <ApolloProvider client={apolloClient}> <Wrapper /> </ApolloProvider>, document.getElementById('root') );
Please ignore the
insertSubscription related code. We’ll understand that in detail later. The rest of the code should be simple to get around. The
render function takes in the root component and the elementId as parameters. Notice
client (ApolloClient instance) is being passed as a prop to
ApolloProvider. You can check the complete
index.js file here.
Setting Up The Custom Service Worker
A Service worker is a JavaScript file that has the capability to intercept network requests. It is used for querying the cache to check if the requested asset is already present in the cache instead of making a ride to the server. Service workers are also used for sending web-push notifications to the subscribed devices.
We’ve to send web-push notifications for the stock price updates to the subscribed users. Let’s set the ground and build this service worker file!
The
insertSubscription related snipped in the
index.js file is doing the work of registering service worker and putting the subscription object in the database using
subscriptionMutation.
Please refer queries.js for all the queries and mutations being used in the project.
serviceWorker.register(insertSubscription); invokes the
register function written in the
serviceWorker.js file. Here it is:
export const register = (insertSubscription) => { if ('serviceWorker' in navigator) { const swUrl = `${process.env.PUBLIC_URL}/serviceWorker.js` navigator.serviceWorker.register(swUrl) .then(() => { console.log('Service Worker registered'); return navigator.serviceWorker.ready; }) .then((serviceWorkerRegistration) => { getSubscription(serviceWorkerRegistration, insertSubscription); Notification.requestPermission(); }) } }
The above function first checks if
serviceWorker is supported by the browser and then registers the service worker file hosted on the URL
swUrl. We’ll check this file in a moment!
The
getSubscription function does the work of getting the subscription object using the
subscribe method on the
pushManager object. This subscription object is then stored in the
user_subscription table against a userId. Please note that the userId is being generated using the
uuid function. Let’s check out the
getSubscription function:
const getSubscription = (serviceWorkerRegistration, insertSubscription) => { serviceWorkerRegistration.pushManager.getSubscription() .then ((subscription) => { const userId = uuidv4(); if (!subscription) { const applicationServerKey = urlB64ToUint8Array('<APPLICATION_SERVER_KEY>') serviceWorkerRegistration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey }).then (subscription => { insertSubscription({ variables: { userId, subscription } }); localStorage.setItem('serviceWorkerRegistration', JSON.stringify({ userId, subscription })); }) } }) }
You can check
serviceWorker.js file for the complete code!
Notification.requestPermission() invoked this popup that asks the user for the permission for sending notifications. Once the user clicks on Allow, a subscription object is generated by the push service. We’re storing that object in the localStorage as:
The field
endpoint in the above object is used for identifying the device and the server uses this endpoint to send web push notifications to the user.
We have done the work of initializing and registering the service worker. We also have the subscription object of the user! This is working all good because of the
serviceWorker.js file present in the
public folder. Let’s now set up the service worker to get things ready!
This is a bit difficult topic but let’s get it right! As mentioned earlier, the
create-react-app utility doesn’t support customizations by default for the service worker. We can achieve customer service worker implementation using
workbox-build module.
We also have to make sure that the default behavior of pre-caching files is intact. We’ll modify the part where the service worker gets build in the project. And, workbox-build helps in achieving exactly that! Neat stuff! Let’s keep it simple and list down all that we have to do to make the custom service worker work:
- Handle the pre-caching of assets using
workboxBuild.
- Create a service worker template for caching assets.
- Create
sw-precache-config.jsfile to provide custom configuration options.
- Add the build service worker script in the build step in
package.json.
Don’t worry if all this sounds confusing! The article doesn’t focus on explaining the semantics behind each of these points. We’ve to focus on the implementation part for now! I’ll try to cover the reasoning behind doing all the work to make a custom service worker in another article.
Let’s create two files
sw-build.js and
sw-custom.js in the
src directory. Please refer to the links to these files and add the code to your project.
Let’s now create
sw-precache-config.js file at the root level and add the following code in that file:
module.exports = { staticFileGlobs: [ 'build/static/css/**.css', 'build/static/js/**.js', 'build/index.html' ], swFilePath: './build/serviceWorker.js', stripPrefix: 'build/', handleFetch: false, runtimeCaching: [{ urlPattern: /this\\.is\\.a\\.regex/, handler: 'networkFirst' }] }
Let’s also modify the
package.json file to make room for building the custom service worker file:
Add these statements in the
scripts section:
"build-sw": "node ./src/sw-build.js", "clean-cra-sw": "rm -f build/precache-manifest.*.js && rm -f build/service-worker.js",
And modify the
build script as:
"build": "react-scripts build && npm run build-sw && npm run clean-cra-sw",
The setup is finally done! We now have to add a custom service worker file inside the
public folder:
function showNotification (event) { const eventData = event.data.json(); const { title, body } = eventData self.registration.showNotification(title, { body }); } self.addEventListener('push', (event) => { event.waitUntil(showNotification(event)); })
We’ve just added one
push listener to listen to push-notifications being sent by the server. The function
showNotification is used for displaying web push notifications to the user.
This is it! We’re done with all the hard work of setting up a custom service worker to handle web push notifications. We’ll see these notifications in action once we build the user interfaces!
We’re getting closer to building the main code pieces. Let’s now start with the first view!
Symbol List View
The
App component being used in the previous section looks like this:
import React from 'react'; import SymbolList from './views/symbolList'; const App = () => { return <SymbolList />; }; export default App;
It is a simple component that returns
SymbolList view and
SymbolList does all the heavy-lifting of displaying symbols in a neatly tied user interface.
Let’s look at
symbolList.js inside the
views folder:
Please refer to the file here!
The component returns the results of the
renderSymbols function. And, this data is being fetched from the database using the
useQuery hook as:
const { loading, error, data } = useQuery(symbolsQuery, {variables: { userId }});
The
symbolsQuery is defined as:
export const symbolsQuery = gql` query getSymbols($userId: uuid) { symbol { id company symbol_events(where: {user_id: {_eq: $userId}}) { id symbol trigger_type trigger_value user_id } stock_symbol_aggregate { aggregate { max { high volume } min { low volume } } } } } `;
It takes in
userId and fetches the subscribed events of that particular user to display the correct state of the notification icon (bell icon that is being displayed along with the title). The query also fetches the max and min values of the stock. Notice the use of
aggregate in the above query. Hasura’s Aggregation queries do the work behind the scenes to fetch the aggregate values like
count,
sum,
avg,
max,
min, etc.
Based on the response from the above GraphQL call, here’s the list of cards that are displayed on the front-end:
The card HTML structure looks something like this:
<div key={id}> <div className="card-container"> <Card> <CardBody> <CardTitle className="card-title"> <span className="company-name">{company} </span> <Badge color="dark" pill>{id}</Badge> <div className={classNames({'bell': true, 'disabled': isSubscribed})} id={`subscribePopover-${id}`}> <FontAwesomeIcon icon={faBell} </div> </CardTitle> <div className="metrics"> <div className="metrics-row"> <span className="metrics-row--label">High:</span> <span className="metrics-row--value">{max.high}</span> <span className="metrics-row--label">{' '}(Volume: </span> <span className="metrics-row--value">{max.volume}</span>) </div> <div className="metrics-row"> <span className="metrics-row--label">Low: </span> <span className="metrics-row--value">{min.low}</span> <span className="metrics-row--label">{' '}(Volume: </span> <span className="metrics-row--value">{min.volume}</span>) </div> </div> <Button className="timeseries-btn" outline onClick={() => toggleTimeseries(id)}>Timeseries</Button>{' '} </CardBody> </Card> <Popover className="popover-custom" placement="bottom" target={`subscribePopover-${id}`} isOpen={isSubscribePopoverOpen === id} toggle={() => setSubscribeValues(id, symbolTriggerData)} > <PopoverHeader> Notification Options <span className="popover-close"> <FontAwesomeIcon icon={faTimes} onClick={() => handlePopoverToggle(null)} /> </span> </PopoverHeader> {renderSubscribeOptions(id, isSubscribed, symbolTriggerData)} </Popover> </div> <Collapse isOpen={expandedStockId === id}> { isOpen(id) ? <StockTimeseries symbol={id}/> : null } </Collapse> </div>
We’re using the
Card component of ReactStrap to render these cards. The
Popover component is used for displaying the subscription-based options:
When the user clicks on the
bell icon for a particular stock, he can opt-in to get notified every hour or when the price of the stock has reached the entered value. We’ll see this in action in the Events/Time Triggers section.
Note: We’ll get to the
StockTimeseries component in the next section!
Please refer to
symbolList.js for the complete code related to the stocks list component.
Stock Timeseries View
The
StockTimeseries component uses the query
stocksDataQuery:
export const stocksDataQuery = gql` query getStocksData($symbol: String) { stock_data(order_by: {time: desc}, where: {symbol: {_eq: $symbol}}, limit: 25) { high low open close volume time } } `;
The above query fetches the recent 25 data points of the selected stock. For example, here is the chart for the Facebook stock open metric:
This is a straightforward component where we pass in some chart options to [
HighchartsReact] component. Here are the chart options:
const chartOptions = { title: { text: `${symbol} Timeseries` }, subtitle: { text: 'Intraday (5min) open, high, low, close prices & volume' }, yAxis: { title: { text: '#' } }, xAxis: { title: { text: 'Time' }, categories: getDataPoints('time') }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'middle' }, series: [ { name: 'high', data: getDataPoints('high') }, { name: 'low', data: getDataPoints('low') }, { name: 'open', data: getDataPoints('open') }, { name: 'close', data: getDataPoints('close') }, { name: 'volume', data: getDataPoints('volume') } ] }
The X-Axis shows the time and the Y-Axis shows the metric value at that time. The function
getDataPoints is used for generating a series of points for each of the series.
const getDataPoints = (type) => { const values = []; data.stock_data.map((dataPoint) => { let value = dataPoint[type]; if (type === 'time') { value = new Date(dataPoint['time']).toLocaleString('en-US'); } values.push(value); }); return values; }
Simple! That’s how the Chart component is generated! Please refer to Chart.js and
stockTimeseries.js files for the complete code on stock time-series.
You should now be ready with the data and the user interfaces part of the project. Let’s now move onto the interesting part — setting up event/time triggers based on the user’s input.
Setting Up Event/Scheduled Triggers
In this section, we’ll learn how to set up triggers on the Hasura console and how to send web push notifications to the selected users. Let’s get started!
Events Triggers On Hasura Console
Let’s create an event trigger
stock_value on the table
stock_data and
insert as the trigger operation. The webhook will run every time there is an insert in the
stock_data table.
We’re going to create a glitch project for the webhook URL. Let me put down a bit about webhooks to make easy clear to understand:
Webhooks are used for sending data from one application to another on the occurrence of a particular event. When an event is triggered, an HTTP POST call is made to the webhook URL with the event data as the payload.
In this case, when there is an insert operation on the
stock_data table, an HTTP post call will be made to the configured webhook URL (post call in the glitch project).
Glitch Project For Sending Web-push Notifications
We’ve to get the webhook URL to put in the above event trigger interface. Go to glitch.com and create a new project. In this project, we’ll set up an express listener and there will be an HTTP post listener. The HTTP POST payload will have all the details of the stock datapoint including
open,
high,
low,
volume,
time. We’ll have to fetch the list of users subscribed to this stock with the value equal to the
close metric.
These users will then be notified of the stock price via web-push notifications.
That’s all we’ve to do to achieve the desired target of notifying users when the stock price reaches the expected value!
Let’s break this down into smaller steps and implement them!
Installing Dependencies
We would need the following dependencies:
express: is used for creating an express server.
apollo-fetch: is used for creating a fetch function for getting data from the GraphQL endpoint.
web-push: is used for sending web push notifications.
Please write this script in
package.json to run
index.js on
npm start command:
"scripts": { "start": "node index.js" }
Setting Up Express Server
Let’s create an
index.js file as:
const express = require('express'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.json()); const handleStockValueTrigger = (eventData, res) => { /* Code for handling this trigger */ } on port ${process.env.PORT}`); });
In the above code, we’ve created
get listeners on the route
/.
get is simple to get around! We’re mainly interested in the post call. If the
eventType is
stock-value-trigger, we’ll have to handle this trigger by notifying the subscribed users. Let’s add that bit and complete this function!
Fetching Subscribed Users()); }
In the above
handleStockValueTrigger function, we’re first fetching the subscribed users using the
getSubscribedUsers function. We’re then sending web-push notifications to each of these users. The function
sendWebpush is used for sending the notification. We’ll look at the web-push implementation in a moment.
The function
getSubscribedUsers uses the query:
query getSubscribedUsers($symbol: String, $triggerValue: numeric) { events(where: {symbol: {_eq: $symbol}, trigger_type: {_eq: "event"}, trigger_value: {_gte: $triggerValue}}) { user_id user_subscription { subscription } } }
This query takes in the stock symbol and the value and fetches the user details including
user-id and
user_subscription that matches these conditions:
symbolequal to the one being passed in the payload.
trigger_typeis equal to
event.
trigger_valueis greater than or equal to the one being passed to this function (
closein this case).
Once we get the list of users, the only thing that remains is sending web-push notifications to them! Let’s do that right away!
Sending Web-Push Notifications To The Subscribed Users
We’ve to first get the public and the private VAPID keys to send web-push notifications. Please store these keys in the
.env file and set these details in
index.js as:
webPush.setVapidDetails( 'mailto:<YOUR_MAIL_ID>', process.env.PUBLIC_VAPID_KEY, process.env.PRIVATE_VAPID_KEY ); const sendWebpush = (subscription, webpushPayload) => { webPush.sendNotification(subscription, webpushPayload).catch(err => console.log('error while sending webpush', err)) }
The
sendNotification function is used for sending the web-push on the subscription endpoint provided as the first parameter.
That’s all is required to successfully send web-push notifications to the subscribed users. Here’s the complete code defined in
index.js:
const express = require('express'); const bodyParser = require('body-parser'); const { createApolloFetch } = require('apollo-fetch'); const webPush = require('web-push'); webPush.setVapidDetails( 'mailto:<YOUR_MAIL_ID>', process.env.PUBLIC_VAPID_KEY, process.env.PRIVATE_VAPID_KEY ); const app = express(); app.use(bodyParser.json()); sendWebpush = (subscription, webpushPayload) => { webPush.sendNotification(subscription, webpushPayload).catch(err => console.log('error while sending webpush', err)) }"); });
Let’s test out this flow by subscribing to stock with some value and manually inserting that value in the table (for testing)!
I subscribed to
AMZN with value as
2000 and then inserted a data point in the table with this value. Here’s how the stocks notifier app notified me right after the insertion:
Neat! You can also check the event invocation log here:
The webhook is doing the work as expected! We’re all set for the event triggers now!
Scheduled/Cron Triggers
We can achieve a time-based trigger for notifying the subscriber users every hour using the Cron event trigger as:
We can use the same webhook URL and handle the subscribed users based on the trigger event type as
stock_price_time_based_trigger. The implementation is similar to the event-based trigger.
Conclusion
In this article, we built a stock price notifier application. We learned how to fetch prices using the Alpha Vantage APIs and store the data points in the Hasura backed Postgres database. We also learned how to set up the Hasura GraphQL engine and create event-based and scheduled triggers. We built a glitch project for sending web-push notifications to the subscribed users.
| https://www.smashingmagazine.com/2020/12/stocks-price-notifier-app-react-apollo-graphql-hasura/ | CC-MAIN-2021-25 | refinedweb | 5,818 | 56.96 |
the new journal mode could reduce fsyncs without large changes on our side.
Created attachment 459835 [details] [diff] [review] patch v1.0
Created attachment 459920 [details] [diff] [review] patch v1.1 minor change. Notice this applies on top of bug 552023, landing this before will require moving the shutdown journal setup to PlacesDBFlush.
Comment on attachment 459920 [details] [diff] [review] patch v1.1 asking feedback instead of review for the dependency. It should be ready to review apart that but you could need to unbitrot it if willing to push before I'm back.
tentative blocking for I/O (fsyncs) win. WAL is a new journaling mode introduced in sqlite 3.7.0 that reduces I/O and fragmentation.
Created attachment 460037 [details] [diff] [review] patch v1.2
Comment on attachment 460037 [details] [diff] [review] patch v1.2 This looks fine. I'll do a proper review of it too.
OS/2 guys: maybe you want to see if this patch works on OS/2. As we don't have WAL support implemented in our SQLite port, it should fall-back, but might be good to check this before this lands. > nsresult >+nsNavHistory::SetJournaling(const nsCString& aJournalMode) { Just curious: is Mozilla (or places) migrating to a Java-like end-of-the line brace style?
Note that while using WAL will result in less fsyncs (one instead of three), it'll still sync on every commit. To take full advantage, the synchronous mode should be changed to normal ("PRAGMA synchronous = NORMAL"). I believe this setting is already mapped to a hidden pref ("toolkit.storage.synchronous"). With that setting, sqlite will only fsync the database when checkpointing the journal. This trades off durability (the last seconds of changes before a crash may be lost). If I read the documentation correctly, in WAL mode it's safe to use NORMAL (it doesn't increase the risk of corruption like it supposedly does for non-WAL databases)..
(In reply to comment #7) > OS/2 guys: maybe you want to see if this patch works on OS/2. As we don't have > WAL support implemented in our SQLite port, it should fall-back, but might be > good to check this before this lands. Please let us know if we'll need to ifdef this out or make special code for you guys. > Just curious: is Mozilla (or places) migrating to a Java-like end-of-the line > brace style? No, but that's something I'd catch in review. (In reply to comment #8) > Note that while using WAL will result in less fsyncs (one instead of three), > it'll still sync on every commit. Right, we are OK with having fsyncs (we want durability), but reducing them is a win. > To take full advantage, the synchronous mode should be changed to normal > ("PRAGMA synchronous = NORMAL"). I believe this setting is already mapped to a > hidden pref ("toolkit.storage.synchronous"). We will not be doing that though because we've seen an increase in database corruption in the past when we had it set to that. Places is always at synchronous = FULL. >. A large portion of places SQLite I/O is done on a background thread already to avoid fsyncs, writes, and reads on the main thread.
(In reply to comment #6) > Comment on attachment 460037 [details] [diff] [review] > patch v1.2 (In reply to comment #7) > OS/2 guys: maybe you want to see if this patch works on OS/2. As we don't have > WAL support implemented in our SQLite port, it should fall-back, but might be > good to check this before this lands. After a slight correction of the patch for bit rot it built fine, the browser comes up and stays alive. Any stress test I can do to find out whether there might be a not so obvious regression?
Ideally running the tests should do it. Also making sure history is saved when you restart.
Comment on attachment 460037 [details] [diff] [review] patch v1.2 >+++ b/toolkit/components/places/src/nsNavHistory.cpp >@@ -142,9 +143,12 @@ using namespace mozilla::places; > // Filename used to backup corrupt databases. > #define DATABASE_CORRUPT_FILENAME NS_LITERAL_STRING("places.sqlite.corrupt") > >-// We use the TRUNCATE journal mode to reduce the number of fsyncs. Without >-// this setting we had a Ts hit on Linux. See bug 460315 for details. >-#define DATABASE_JOURNAL_MODE "TRUNCATE" >+// We use the WAL journal mode to reduce the number of fsyncs. >+#define DATABASE_DEFAULT_JOURNAL_MODE NS_LITERAL_CSTRING("wal") >+// If the system does not support WAL, or we cannot use it, we will fallback >+// to this setting. Other journal modes caused a Ts hit on Linux. >+// See bug 460315 for details. >+#define DATABASE_FALLBACK_JOURNAL_MODE NS_LITERAL_CSTRING("truncate") We should use an enum for this at this point. > nsresult >+nsNavHistory::SetJournaling(const nsCString& aJournalMode) { >+ // Note: binding seems to be not working on pragma statements. yeah, it does not work, and I'm not sure the comment is really needed here. >+ // WARNING: >+ // Don't leave unfinalized statements around till journal mode has been set, >+ // some journaling mode does not like them and will fail to be set. nit: wording is a bit awkward >+ // Be sure to set journaling after cache_size and page_size, some mode will >+ // prevent that kind of changes. nit: journal mode >-. >+ // Set back journaling to a backwards compatible value. Newer journal modes >+ // like WAL make the database incomatible with old versions of the browser. >+ (void)SetJournaling(NS_LITERAL_CSTRING("memory")); We should link to the SQLite documentation about this too. >@@ -5483,38 +5527,14 @@ nsNavHistory::VacuumDatabase() > nsnull); > } > >- // Actually vacuuming a database is a slow operation, since it could take >- // seconds. Part of the time is spent in updating the journal file on disk >- // and this is particularly bad on devices with slow I/O. Temporary >- // moving the journal to memory could increase a bit the possibility of >- // corruption if we crash during this time, but makes the process really >- // faster. >- nsCOMPtr<mozIStorageStatement> journalToMemory; >- rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING( >- "PRAGMA journal_mode = MEMORY"), >- getter_AddRefs(journalToMemory)); >- NS_ENSURE_SUCCESS(rv, rv); >- >- nsCOMPtr<mozIStorageStatement> vacuum; >- rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING("VACUUM"), >- getter_AddRefs(vacuum)); >- NS_ENSURE_SUCCESS(rv, rv); >- >- nsCOMPtr<mozIStorageStatement> journalToDefault; >- rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING( >- "PRAGMA journal_mode = " DATABASE_JOURNAL_MODE), >- getter_AddRefs(journalToDefault)); >- NS_ENSURE_SUCCESS(rv, rv); >- >- mozIStorageBaseStatement *stmts[] = { >- journalToMemory, >- vacuum, >- journalToDefault >- }; So, why are we nuking all of this? >+++ b/toolkit/components/places/src/nsNavHistory.h >+ nsresult SetJournaling(const nsCString& aJournalMode); >+ nsCString mCurrentJournalMode; Both of these should take the previously mentioned enum I think.
Just a comment about the memory-journal-during-vacuum thing. The only difference between a memory journal and no journal is that the former allows you to rollback a transaction, whereas the latter doesn't. In both cases, a interruption will corrupt the database almost every time (1). A memory journal doesn't protect the database integrity at all. In the particular case of vacuum, there are two phases (creating the clean db and copying it back). A crash during the second phase without a disk journal will corrupt the database practically 100% of the time (the way everything is rearranged during a vacuum the chances of survival are almost zero). Moreover vacuum can't be inside any other transactions, and should have no reason to rollback (at the point where writes to the actual database file start no more disk space is needed). So a memory journal gives you exactly nothing. Either you risk the database during that time (journal off) or you don't (disk journal). Currently you do, and I don't think playing that lottery once a month or so is a reasonable game. Also, a memory journal during vacuum has an additional risk: a vacuum journal will reach the size of the database itself. If the db is large and the machine has little RAM and starts swapping, the time needed and therefore the risk window would be widened a lot (and the user will be more likely to end the process at that time since it stops responding). SQLite could probably be improved to vacuum faster on filesystems that support atomic rename (right now it generates a defragmented db on a temp file, and then copies it back over the original file; it could just rename the temporary file over the original one). This would also help defragment the files on-disk. (1)
And also the fact setting journal to another mode, vacuum, and go back to WAL will fail, because we have unfinalized statements. This will be a problem because we need to do vacuum out of wal if the page size is not the expected one (page size cannot be changed after entering wal mode). This issue should be moved to the global vacuum component bug, most likely when a vacuum+page_size change happens we will have to fallback to truncate mode till the browser is restarted to correctly do the page_size change. Btw, regarding the crash->corruption problems we are aware of them, but the chance of having a crash while copying back the file were smaller than the perf penalty we were paying. Actually I redid the same tests and looks like vacuum is now faster also in truncate mode (and almost as fast in wal mode), so the memory thing can go away with recent sqlite versions.
(In reply to comment #12) > >-. I'm not sure makes sense to check failures there, if we fail setting mode we will stay to the default DELETE mode, and browser can still work, the code will already warn in debug builds. If we check failure the database could be marked as corrupt, when maybe it's not and is instead just a filesystem not supporting that mode. That will cause us to be completely not working. Imo warnings are enough there.
Alright, I'm fine with it then.
Created attachment 462339 [details] [diff] [review] patch v2.0 Addresses comments and can land before temp tables removal.
Probably the suggestion to run checkpointing in a separate thread makes sense... but it would be hard to detect each transaction without using sqlite3_wal_hook(), so that should probably be exposed in Storage, or storage should automatically do checkpointing in a separate thread for all users (that seems to make sense)
btw, some checkpointing could already happen in a separate thread... if the query that causes wal to go over limit is an async query for example, checkpointing happens in that thread... since we are supposed to use async stmts more than sync ones, the problem could be fixed by itself.
Comment on attachment 462339 [details] [diff] [review] patch v2.0 For a review with more context with the comments, please see. on file: toolkit/components/places/src/nsNavHistory.h line 126 > JOURNAL_DELETE = 0 > // Can reduce fsyncs on Linux when journal is deleted (See bug 460315). > // We fallback to this mode when WAL is unavailable. > , JOURNAL_TRUNCATE > // Journal is never deleted, can cause a privacy hit. > , JOURNAL_PERSIST > // Unsafe in case of crashes on database swap or low memory. > , JOURNAL_MEMORY > // Can globally reduce number of fsyncs. We try to use this mode by default. > , JOURNAL_WAL > // Unsafe mode due to corruption on crashes. > , JOURNAL_OFF Not sure it's worthwhile to have modes here that we do not use. r=sdwilsh
Created attachment 464813 [details] [diff] [review] patch v2.1
Created attachment 464825 [details] [diff] [review] patch v2.2
Created attachment 464826 [details] [diff] [review] patch v2.3 forgot to qrefresh.
Looks like this regressed Ts on linux: Regression: Ts increase 25.7% on Linux Firefox Previous results: 450.368 from build 20100813121430 of revision da59cce7bfa2 at 2010-08-13 12:20:20 on talos-r3-fed-018 run # 0 New results: 566.211 from build 20100813121912 of revision dfd35987dd82 at 2010-08-13 12:50:31 on talos-r3-fed-004 run # 0
(In reply to comment #24) > Looks like this regressed Ts on linux: noticed, we are waiting for numbers from all platforms to decide.
forgot to mark
Just to annotate things down, since I think it's useful for everybody, while looking around for known perf issues on ext4, I found an article saying ext4 with barriers on can regress sqlite performances, and seeing how wal and barrries are working that could be a bad interaction. I asked catlee if it would be possible to run a Ts test on a linux box with barrier=0 on ext4, he said should be possible. If the regression is linux only that test would be really interesting. But I can't tell more till I see other filesystems results.
the global effect was Ts regressions on Linux and Windows, some of them are worrying too like a 52% on Win7... But a 10% Ts win on OS X. Seeing the fact max dirty profile loses less than min dirty profile, sounds like there is some fixed "setup time" to create the wal that hurts more small profiles in percentage. Btw, due to the fact this hurts 2 systems out of 3 i'm going to backout and we should ask SQLite team if they have evidence of these times.
Backed out Shawn, can we contact someone at SQLite and try to figure out if this expensiveness on creation is expected/fixable somehow?
To summarize, we saw the following regressions (sorted by platform): Ts increase 25.7% on Linux Firefox Ts, MIN Dirty Profile increase 23.8% on Linux Firefox Ts, MED Dirty Profile increase 24.7% on Linux Firefox Ts, MAX Dirty Profile increase 20.7% on Linux Firefox Ts Shutdown, Cold MIN Dirty Profile increase 9.3% on Linux Firefox Ts increase 30.8% on Linux x64 Firefox Ts, MIN Dirty Profile increase 21.8% on Linux x64 Firefox Ts, MED Dirty Profile increase 20.6% on Linux x64 Firefox Ts, MAX Dirty Profile increase 21.4% on Linux x64 Firefox Ts increase 37.3% on XP Firefox Ts, MIN Dirty Profile increase 27.4% on XP Firefox Ts, MED Dirty Profile increase 29.4% on XP Firefox Ts, MAX Dirty Profile increase 28.9% on XP Firefox Ts, Cold MIN Dirty Profile increase 21.6% on XP Firefox Ts, Cold MED Dirty Profile increase 30.6% on XP Firefox Ts, Cold MAX Dirty Profile increase 28% on XP Firefox Ts increase 52.7% on Win7 Firefox Ts, MIN Dirty Profile increase 44.4% on Win7 Firefox Ts, MED Dirty Profile increase 28% on Win7 Firefox Ts, MAX Dirty Profile increase 9.97% on Win7 Firefox Ts, Cold MIN Dirty Profile increase 48.4% on Win7 Firefox Ts, Cold MED Dirty Profile increase 26.9% on Win7 Firefox Ts, Cold MAX Dirty Profile increase 9.8% on Win7 Firefox Ts Shutdown increase 19.7% on Win7 Firefox Tp4 (Memset) increase 1.67% on Win7 Firefox Tp4 (%CPU) increase 10.4% on Win7 Firefox And the following improvements: Ts, MIN Dirty Profile decrease 10% on MacOSX 10.6.2 Firefox Ts, MAX Dirty Profile decrease 8.93% on MacOSX 10.6.2 Firefox Dromaeo (V8) increase 9.92% on XP Firefox (weird...probably unrelated to this change)
SQLite folks are looking into this.
Created attachment 467040 [details] Just enabling WAL I pushed this minimal changeset to the places branch () and this is the perf data comparison with changesets on mozilla-central (116f2046b9ef, 007d994cac53, 2dbb1278a15c, 34737d9895f8, and 40fa4ebeacbb) that should be a good baseline. It looks like Ts is basically even (small regressions at worst). What's more interesting is the Ts_generated results that show a regression for min, but med and max are OK. Cannot really explain that yet.
Created attachment 467194 [details] Just enabling WAL (better comparisons) OK, this fixes some issues with the compare-talos stuff and displays more information. I also had some more talos runs kicked off this morning (not sure if windows is reporting that yet though, but mac and linux should be). Same changesets as before. There's only one small possible regression here on windows for Ts_generated_max.
OK, just going to provide links at this point instead of doing HTML attachments. Just enabling WAL (): Just enabling WAL with SQLite 3.7.1 alpha build (): Converting the database at shutdown back to TRUNCATE on SQLite 3.7.0.1 (): (I will be filing a bug to get two more talos runs on this change shortly)
Interesting thing to note so far is that we aren't seeing the regressions from comment 30 (although we are seeing different regressions - weird).
Er...fun times. I've been testing against SQLite 3.6.23.1... Interesting that tests were not failing. Anywho, I just pushed mak's original change, and now I'm going to reland 3.7.1, and we'll get numbers on that.
All of these are with a snapshot of 3.7.1. mak's original set of changes: Just enabling WAL: Converting the database at shutdown back to TRUNCATE:
Based on comment 37, it looks like the regression is caused by switching back to TRUNCATE on shutdown.
Marco, I just talked to LegNeato about the possibility of getting 3.7.1 on 1.9.2 and he said that shipping it in beta 5 and letting people beat on it for a little bit would be enough for him to be comfortable. However, he is concerned about folks downgrading from 4.0 to 3.6, but wants to talk to Cww to see how often people downgrade. If push comes to shove, we can do a change to places2.sqlite as well, but I think we clearly cannot do the TRUNCATE switch on shutdown.
I have done some tests about switching out of WAL on an Win XP machine. Going to MEMORY or OFF instead of TRUNCATE roughly doubles the speed of the switch. I think this is safe. Using PRAGMA synchronous = OFF and then switching to any non-WAL mode is instantaneous, but that's probably not safe for the data if there's a crash at that very moment.
(In reply to comment #40) > I have done some tests about switching out of WAL on an Win XP machine. Going > to MEMORY or OFF instead of TRUNCATE roughly doubles the speed of the switch. I > think this is safe. If a crash were to happen, we'd be out of luck then though (at least for downgrades; might be OK for staying on the same version). > Using PRAGMA synchronous = OFF and then switching to any non-WAL mode is > instantaneous, but that's probably not safe for the data if there's a crash at > that very moment. Yeah, that's risky.. If there is no way to speed up the wal creation on SQLite side, the only solutions to the regression on our side are: - push sqlite 3.7.1 to 3.5.x and 3.6.x and pay the wal cost just once (or ignore 3.5.x since it's unlilely someone will downgrade to that one). - make places2.sqlite, manually migrate history from places.sqlite and delete it (expensive from a coding point of view)
(In reply to comment #42) >. Right, this is what I was trying to say. Sorry if it came across differently. > - push sqlite 3.7.1 to 3.5.x and 3.6.x and pay the wal cost just once (or > ignore 3.5.x since it's unlilely someone will downgrade to that one). I personally prefer this due to costs (and not worry about 1.9.1).
Shawn, so what's current plan for sqlite 3.7.1 on 1.9.2? Changing my patch to avoid truncate change at shutdown is pretty trivial but this is blocked by the downgrade compatibility issue.
(In reply to comment #44) > Shawn, so what's current plan for sqlite 3.7.1 on 1.9.2? > Changing my patch to avoid truncate change at shutdown is pretty trivial but > this is blocked by the downgrade compatibility issue. Needs to bake in a beta before we can land it there. We should take this change though but need to make sure we backport before final.
Stealing this.
Created attachment 474235 [details] [diff] [review] v2.4 Removes the bit rot (this isn't ready to land yet)
Created attachment 474264 [details] [diff] [review] v2.5 This just does the startup stuff and does not convert at shutdown. Going to have mak review this just to make sure I didn't do anything stupid, but this passes our xpchshell tests with flying colors.
Comment on attachment 474264 [details] [diff] [review] v2.5 ># HG changeset patch ># Parent a293b6b40cece8a2fed0121bdef9c2b8eba72878 ># User Marco Bonardo <mbonardo@mozilla.com>, Shawn Wilsher <me@shawnwilsher.com> didn't know setting multiple users was working this way. How does this appear in pushlog? > nsresult >+nsNavHistory::SetJournalMode(enum JournalMode aJournalMode) { >+ nsCAutoString journalMode; >+ switch (aJournalMode) { >+ case JOURNAL_DELETE: >+ journalMode.AssignLiteral("delete"); >+ break; >+ case JOURNAL_TRUNCATE: >+ journalMode.AssignLiteral("truncate"); >+ break; >+ case JOURNAL_MEMORY: >+ journalMode.AssignLiteral("memory"); >+ break; >+ case JOURNAL_WAL: >+ journalMode.AssignLiteral("wal"); >+ break; >+ default: >+ NS_ABORT_IF_FALSE(false, "Trying to set an unknown journal mode."); should be NS_NOTREACHED Also it's probably better to set default to a default mode, or we will try to ser journal to an empty string >+ NS_WARN_IF_FALSE(succeeded, >+ nsPrintfCString(128, "Setting journal mode failed: %s", >+ PromiseFlatCString(journalMode).get()).get()); >+ if (succeeded) { >+ mCurrentJournalMode = aJournalMode; >+ } >+ else { >+ return NS_ERROR_FAILURE; >+ } since there is already an if (succeeded) I'd convert the NS_WARN_IF_FALSE to a NS_WARNING inside the if >+nsresult > nsNavHistory::InitDB() > { >@@ -1832,9 +1887,7 @@ nsNavHistory::MigrateV9Up(mozIStorageCon > // reducing write times by a half, but will temporary consume more memory > // and increase risks of corruption if we should crash in the middle of this > // update. >- rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( >- "PRAGMA journal_mode = MEMORY")); >- NS_ENSURE_SUCCESS(rv, rv); >+ (void)SetJournalMode(JOURNAL_MEMORY); > > rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( > "UPDATE moz_places SET last_visit_date = " >@@ -1844,9 +1897,12 @@ nsNavHistory::MigrateV9Up(mozIStorageCon > NS_ENSURE_SUCCESS(rv, rv); > > // Restore the default journal mode. >- rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( >- "PRAGMA journal_mode = " DATABASE_JOURNAL_MODE)); >- NS_ENSURE_SUCCESS(rv, rv); >+ if (NS_FAILED(SetJournalMode(JOURNAL_WAL))) { >+ // Ignore errors, if we fail here the database could be considered corrupt >+ // and we won't be able to go on, even if it's just matter of a bogus file >+ // system. The default mode (DELETE) will be fine in such a case. >+ (void)SetJournalMode(JOURNAL_TRUNCATE); >+ } I'd remove these temporary journal changes in migrateV9Up: - first because from my testing latest sqlite versions are almost as fast, so the gain is ignorable - second because this code path is only touched by users upgrading from FX3.5.x, that is a small percentage - third because they are risky both for not being able to restore WAL, but also for dataloss on crashes. Since now tha gain is minor, the risk does not pay for it. >+ // If journal mode is WAL, a VACUUM cannot upgrade page_size value. >+ // If current page_size is not the expected one, journal mode must be >+ // changed to a rollback one. Once done we won't be able to go back to WAL >+ // mode though, since unfinalized statements exist. Just keep using >+ // compatible mode till next restart. from what you said, unfinalized is wrong, should be not-resetted > nsCOMPtr<mozIStoragePendingStatement> ps; > nsRefPtr<VacuumDBListener> vacuumDBListener = > new VacuumDBListener(mPrefBranch); >- rv = mDBConn->ExecuteAsync(stmts, NS_ARRAY_LENGTH(stmts), >- vacuumDBListener, getter_AddRefs(ps)); >+ rv = vacuum->ExecuteAsync(nsnull, getter_AddRefs(ps)); the callback should be vacuumDBListener, not nsnull r=me with the above fixed/answered
(In reply to comment #49) > didn't know setting multiple users was working this way. How does this appear > in pushlog? Shows up as the first person on the web, but hg stores it properly so if that ever gets fixed, things show up right. On the changeset page is also shows up correctly.
Perf comparisons will show up here:
Created attachment 476849 [details] [diff] [review] v2.6 Addresses review comments
Also includes Tp4 numbers:
(In reply to comment #49) > Comment on attachment 474264 [details] [diff] [review] > >+ NS_ABORT_IF_FALSE(false, "Trying to set an unknown journal mode."); > > should be NS_NOTREACHED We really should be using ABORTs instead of ASSERTIONs for new code.
where is this documented? If this is what we want, we should blog about it and add some deprecate annotation to nsDebug.h btw, using NS_ABORT here is fine.
(In reply to comment #54) > We really should be using ABORTs instead of ASSERTIONs for new code. Why?
It looks to me like we get the following performance wins with this patch: Tp4 win on windows and linux (32 and 64). ts_cold on linux (32 and 64). ...and the following regressions: memory usage regressions tp4 on osx 64-bit only (32-bit is fine) Notes: 1) the Ts generated places database results are weird and don't make any sense. This could be due to an artifact in how the databases are created (they aren't created with WAL). Some of the smaller sized databases are reporting regressions, and the bigger ones are reporting wins, which is not what I would expect. I've never really trusted these numbers because of their noise, and I'm not convinced they are real regressions (getting more data points on the before and after would likely help, but is difficult to do). 2) The increase in memory usage is expected since WAL uses shared memory to write to the files (mmap on unix, and I have no idea what it uses on windows). These are expected, but give us wins (and let us use less memory when we use more than one connection to a database like we will in bug 582703). Comment 53 has a link to the page I'm using to compare runs and. I'm going to ask for explicit approval to land this and to accept these regressions. If stuff shakes out that we didn't expect on mozilla-central, then I'll obviously need to backout and do more investigation.
And for the sake of interesting numbers, this is bug 573492 (WAL) and bug 552023 (kill temp tables) perf numbers:
See bug 583611 comment 19 on issues with upgrading to SQLite 3.7.1 on branch. We are in a bit of a sticky situation...
(In reply to comment #57) > ...and the following regressions: > memory usage regressions > tp4 on osx 64-bit only (32-bit is fine) Sorry, that's ts_cold. tp4 looks fine.
I might be a bit late to the table here... but I've been reading about WAL at and it very specifically says: ." How do we cater for people who do actually use a network filesystem? I'm sure there are folks who are using NFS...
(In reply to comment #61) > How do we cater for people who do actually use a network filesystem? I'm sure > there are folks who are using NFS... Firefox has never supported using the same profile in more than one running instance of Firefox, so this isn't a problem here.
Somebody want to tell this guy? But understood... though where is this in the documentation?
(In reply to comment #63) > Somebody want to tell this guy? > > That's a completely different issue. > But understood... though where is this in the documentation? To be clear, you can use a profile over NFS, you just can't have more than one copy of Firefox using that profile. This applies always, regardless of where your profile is located.
Ah! OK, that makes more sense now.
Shawn, regarding the Ts reg we see on Linux, could still make sense to investigate comment 27, it is still possible ext4 with barriers is hurting us, and that would explain why we suffer here an not on osx or win. Also if that would be the case, I'd not care much about perf when the user explicitly decided to drop perf for data coherence.
I believe that when I asked someone from releng, they said we were running ext3, not ext4 on the talos boxes. Should probably confirm that though...
well they told me the exact opposite on August, i.e. all boxes are on ext4 :(
(In reply to comment #69) > well they told me the exact opposite on August, i.e. all boxes are on ext4 :( Alright, let's check again and then report back here :)
<jhford-buildduty> sdwilsh: fedora talos slaves have barriers enabled
that "could" explain why sometimes linux shows regressions not shown by other OS, slower writes could do it.
Comment on attachment 476849 [details] [diff] [review] v2.6 <johnath> sdwilsh: do I want to approve the patch on bug 573492? <sdwilsh> johnath: it's part of the places branch...when that's ready to go in, it's going to be merged. By itself, it's a regression, with all of our stuff...well, see <sdwilsh> johnath: can probably cancel the request, fwiw | https://bugzilla.mozilla.org/show_bug.cgi?id=573492 | CC-MAIN-2017-30 | refinedweb | 4,747 | 64.91 |
Hello I am a beginner at C++ and I was given these questions to do for my homework. I would appreciate it if you could help me answer these questions.
Consider the following code when answering questions 1-5
#include <iostream> using namespace std; int someVar = 10 void f(intx, int&y); int g(int x); int main() { int someVar = 3 int a = 31, b = 99; f(a,b); //See Question 1 cout << "a = " << a << ", b = " << b << endl; f(2*a-3,b); // See question 2 cout << " a = " << a << ", b = " << b << endl; cout << "the value of someVar is" << someVar << endl; // See Question 3 cout << "g(3) returns the value" << g(3) << endl; // See Question 4 return 0; } void f(int x, int&y) { int someVar = 5; x = 2; y = 5*someVar; } int g(int x) { return someVar*x; }
Question 1
What will be the value stored in variables "a" and "b" after the call f(a,b)?
Question 2
What will be the value stored in variables "a" and "b" after the call f(2*a-3,b)?
Question 3
What will be the value printed out for someVar?
Question 4
What will be returned by the call to function g(3)?
Question 5
What is the difference between local and global variables? Use examples from the program to explain. | https://www.daniweb.com/programming/software-development/threads/418491/functions | CC-MAIN-2018-22 | refinedweb | 220 | 71.99 |
using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace Genesis_Solutions_CRMS { public partial class formNewAccount : Form { public formNewAccount() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Information info = new Information(); info.Name = txtName.Text; info.Occupation = txtOccupation.Text; info.Dob = double.Parse(txtDob.Text.ToString()); info.Nic = double.Parse(txtNic.Text.ToString()); info.ID = double.Parse(lblID.Text.ToString()); XMLConfigurarion.XMLConf(info, "DATA.xml"); } } }
- 5 Contributors
- forum4 Replies
- 35 Views
- 3 Years Discussion Span
- comment Latest Post by lithium112
I can easily help you with the XML, but I need to know what exactly you want written to the XML, and if you have specific structure in mind.
Details on what needs to be done, and some context would greatly help all of us (just throwing up some code with no backing causes even more questions).
lithium112
Hello Ali,
I really like to use the LINQ to XML approach to adding elements and attributes to the XML doc. You'll need to use 'using System.XML.Linq' in order to do this.
Here's an example you can go by:
Let's say I have stored users inside of my xml file. In order to add an entire element to my doc, I will first instantiate my XDocument like so:
private XDocument xDoc = new XDocument();
You will also want the path to your xml file:
private string path = YourXMLPath;
Now you want to load your xml file into xDoc:
xDoc = XDocument.Load(path);
Now you're set to start reading and writing to your xml document. In order to write to your document, it really depends on what your structure is, so here's a sample xml template:
<Table>
<User Name="Name1" Age="20" Gender="Male" Job="Sales" />
</Table>
Here's how you can create a brand new element under Users:
First, I want to put my template inside of an XElement variable:
XElement users = xmlDoc.Element("Table");
The variable addUserToXml will hold my user information from the xml file.
Now let's build a brand new User Element.
var addUser = new XElement("User", new XAttribute("Name", txtName.Text), new XAttribute("Age", txtAge.Text), new XAttribute("Gender", ddlGender.Text), new XAttribute("Job", txtJob.Text));
Next you want to go ahead and add that User element:
users.Add(new XElement(addUser));
Then save the file:
users.Save(path)
This will add a brand new element under the Table element for a new user every time a user signs up and hits the save button or however you want it setup.
I am going to go ahead and show you a nice elegant way you can read the information from the xml file as well using LINQ to XML. What I will typically do is create a totally new class and create a read function that I can call from anywhere to avoid duplication of code. I will typically have a class called XmlManager that manages all of my xml for me so that I can keep my code nice and clean.
public static DataTable GetUserInformation(){ var datatable = new DataTable(); datatable.Columns.Add("Name"); //Add all columns to DataTable xmlDoc = XDocument.Load(xmlPath); var linqQuery = from doc in xmlDoc.Elements("Table").Elements("User") select new{ Name = doc.Attribute("Name").Value, Age = doc.Attribute("Age").Value, Gender = doc.Attribute("Gender").Value, etc. } foreach (var user in linqQuery){ datatable.Rows.Add(user.Name, user.Age, user.Gender, etc.); } return datatable; }
Now you can read that data inside of the datatable. Or you could use a list or whatever you really want to read the data from the datatable. This was a little more info than what you asked for, but if you want to use LINQ to XML, I'd suggest using it with both read and write using XDocument. One other comment, if the file contains sensitive information, make sure that it is encrypted. If it is encrypted, you'll need to decrypt the file or string (depending on how you access the information) before manipulating the data. Hopefully others can benefit from this. I had to struggle through it and look up tons of documentation when I was learning to read and write from and to xml documents.
Here are some nice tutorials that may also help:
Happy Coding! | https://www.daniweb.com/programming/software-development/threads/499193/how-to-add-new-item-to-list-of-items-in-xml | CC-MAIN-2019-04 | refinedweb | 718 | 56.25 |
Tcl_SetVar2Ex, Tcl_SetVar, Tcl_SetVar2, Tcl_ObjSetVar2, Tcl_GetVar2Ex,
Tcl_GetVar, Tcl_GetVar2, Tcl_ObjGetVar2, Tcl_UnsetVar, Tcl_UnsetVar2 -
manipulate Tcl variables
#include <tcl.h>
Tcl_Obj * |
Tcl_SetVar2Ex(interp, name1, name2, newValuePtr, flags) |
CONST char *
Tcl_SetVar(interp, varName, newValue, flags)
CONST char *
Tcl_SetVar2(interp, name1, name2, newValue, flags)
Tcl_Obj *
Tcl_ObjSetVar2(interp, part1Ptr, part2Ptr, newValuePtr, flags)
Tcl_Obj * |
Tcl_GetVar2Ex(interp, name1, name2, flags) |
CONST char *
Tcl_GetVar(interp, varName, flags)
CONST char *
Tcl_GetVar2(interp, name1, name2, flags)
Tcl_Obj *
Tcl_ObjGetVar2(interp, part1Ptr, part2Ptr, flags)
int
Tcl_UnsetVar(interp, varName, flags)
int
Tcl_UnsetVar2(interp, name1, name2, flags)
Tcl_Interp *interp (in) Interpreter containing variable.
CONST char *name1 (in) Contains the name of an array
variable (if name2 is non-NULL)
or (if name2 is NULL) either the
name of a scalar variable or a
complete name including both
variable name and index. May
include :: namespace qualifiers
to specify a variable in a par-
ticular namespace.
CONST char *name2 (in) If non-NULL, gives name of ele-
ment within array; in this case
variable or an element of an
array.
CONST char *newValue (in) New value for variable, specified
as a null-terminated string. A
copy of this value is stored in
the variable.
Tcl_Obj *part1Ptr (in) Points to a Tcl object containing
the variable's name. The name
may include a series of :: names-
pace qualifiers to specify a
variable in a particular names-
pace. May refer to a scalar
variable or an element of an
array variable.
Tcl_Obj *part2Ptr (in) If non-NULL, points to an object
containing the name of an element
within an array and part1Ptr must
refer to an array variable.
_________________________________________________________________
These procedures are used to create, modify, read, and delete Tcl vari-
ables from C code.
Tcl_SetVar2Ex, Tcl_SetVar, Tcl_SetVar2, and Tcl_ObjSetVar2 will create |
a new variable or modify an existing one. These procedures set the |
given variable to the value given by newValuePtr or newValue and return |
a pointer to the variable's new value, which is stored in Tcl's vari- |
able structure. Tcl_SetVar2Ex and Tcl_ObjSetVar2 take the new value as |
a Tcl_Obj and return a pointer to a Tcl_Obj. Tcl_SetVar and Tcl_Set- |
Var2 take the new value as a string and return a string; they are usu- |
ally less efficient than Tcl_ObjSetVar2. Note that the return value |
may be different than the newValuePtr or newValue argument, due to mod-
ifications made by write traces. If an error occurs in setting the
variable (e.g. an array variable is referenced without giving an index
into the array) NULL is returned and an error message is left in
interp's result if the TCL_LEAVE_ERR_MSG flag bit is set.
Tcl_GetVar2Ex, Tcl_GetVar, Tcl_GetVar2, and Tcl_ObjGetVar2 return the |
current value of a variable. The arguments to these procedures are |
treated in the same way as the arguments to the procedures described |
above. Under normal circumstances, the return value is a pointer to |
the variable's value. For Tcl_GetVar2Ex and Tcl_ObjGetVar2 the value |
is returned as a pointer to a Tcl_Obj. For Tcl_GetVar and Tcl_GetVar2 |
the value is returned as a string; this is usually less efficient, so |
Tcl_GetVar2Ex or Tcl_ObjGetVar2 are preferred. If an error occurs
while reading the variable (e.g. the variable doesn't exist or an array
element is specified for a scalar variable), then NULL is returned and
The name of a variable may be specified to these procedures in four
ways:
[1] If Tcl_SetVar, Tcl_GetVar, or Tcl_UnsetVar is invoked, the vari-
able name is given as a single string, varName. If varName con-
tains an open parenthesis and ends with a close parenthesis,
then the value between the parentheses is treated as an index
(which can have any string value) and the characters before the
first open parenthesis are treated as the name of an array vari-
able. If varName doesn't have parentheses as described above,
then the entire string is treated as the name of a scalar vari-
able.
[2] If the name1 and name2 arguments are provided and name2 is non-
NULL, then an array element is specified and the array name and
index have already been separated by the caller: name1 contains
the name and name2 contains the index. An error is generated if |
name1 contains an open parenthesis and ends with a close paren- |
thesis (array element) and name2 is non-NULL. |
[3] ||
If name2 is NULL, name1 is treated just like varName in case [1] |
above (it can be either a scalar or an array element variable |
name).
The flags argument may be used to specify any of several options to the
procedures. It consists of an OR-ed combination of the following bits.
T.
TCL_NAMESPACE_ONLY
If this bit is set in flags then the variable is looked up only
in the current namespace; if a procedure is active its variables
are ignored, and the global namespace is also ignored unless it
is the current namespace.
TCL_LEAVE_ERR_MSG
If an error is returned and this bit is set in flags, then an
error message will be left in the interpreter's result, where it
can be retrieved with Tcl_GetObjResult or Tcl_GetStringResult.
If this flag bit isn't set then no error message is left and the
interpreter's result will not be modified.
TCL_APPEND_VALUE
arguments to these procedures are treated in the same way as the argu-
ments to Tcl_SetVar and Tcl_SetVar2. Under normal circumstances, the
return value is a pointer to the variable's value (which is stored in
Tcl's variable structure and will not change before the next call to
Tcl_SetVar or Tcl_SetVar2). Tcl_GetVar and Tcl_GetVar2 use the flag
bits TCL_GLOBAL_ONLY and TCL_LEAVE_ERR_MSG, both of which have the same
meaning as for Tcl_SetVar. If an error occurs in reading the variable
(e.g. the variable doesn't exist or an array element is specified for a
scalar variable), then NULL is returned.
Tcl_UnsetVar and Tcl_UnsetVar2 may be used to remove a variable, so
that future calls to Tcl_GetVar or Tcl_GetVar2 for the variable will
return an error. The arguments to these procedures are treated in the
same way as the arguments to Tcl_GetVar and Tcl_GetVar2. If the vari-
able is successfully removed then TCL_OK is returned. If the variable
cannot be removed because it doesn't exist then TCL_ERROR is returned.
If an array element is specified, the given element is removed but the
array remains. If an array name is specified without an index, then
the entire array is removed.
Tcl_GetObjResult, Tcl_GetStringResult, Tcl_TraceVar
array, get variable, interpreter, object, scalar, set, unset, variable
Tcl 8.1 Tcl_SetVar(3) | http://www.syzdek.net/~syzdek/docs/man/.shtml/man3/SetVar.3.html | crawl-003 | refinedweb | 1,077 | 57.91 |
ACTIVITY SUMMARY (2011-01-28 - 2011-02-04) Python tracker at To view or respond to any of the issues listed below, click on the issue. Do NOT respond to this message. Issues counts and deltas: open 2585 (+18) closed 20314 (+52) total 22899 (+70) Open issues with patches: 1102 Issues opened (49) ================== #10918: **kwargs unnecessarily restricted in concurrent.futures 'submi reopened by bquinlan #11023: pep 227 missing text reopened by r.david.murray #11048: "import ctypes" causes segfault on read-only filesystem opened by Arach #11049: add tests for test.support opened by brett.cannon #11050: email.utils.getaddresses behavior contradicts RFC2822 opened by Ivan.Egorov #11051: system calls per import opened by pitrou #11055: OS X IDLE 3.2 Save As menu accelerator opens two Save windows opened by ned.deily #11056: 2to3 fails for inner __metaclass__ class definition opened by nw #11062: mailbox fails to round-trip a file to a Babyl mailbox opened by r.david.murray #11063: uuid.py module import has heavy side effects opened by Keith.Dart #11067: Py_LIMITED_API breaks most PySomething_Check() functions opened by petere #11071: What's New review comments opened by ncoghlan #11072: Add MLSD command support to ftplib opened by giampaolo.rodola #11074: fix tokenize so it can be reloaded opened by brett.cannon #11076: Iterable argparse Namespace opened by vdupras #11077: Tkinter is not thread safe opened by PythonInTheGrass #11078: Have test___all__ check for duplicates opened by r.david.murray #11079: Make OS X entry in Applications like that in Windows opened by rhettinger #11085: expose _abcoll as collections.abc opened by rhettinger #11086: add lib2to3/__main__.py opened by brett.cannon #11087: Speeding up the interpreter with a few lines of code opened by jneb #11088: IDLE on OS X with Cocoa Tk 8.5 can hang waiting on input / raw opened by ned.deily #11089: ConfigParser 50x slower in 2.7 opened by vlachoudis #11090: Doc errors for unittest in Python 3.1 opened by michael.foord #11092: Setup.cfg isn't packaged when running sdist opened by Julien.Miotte #11093: test_future - rename not-unittest files to make regrtest.NOTTE opened by sandro.tosi #11096: Multiple turtle tracers opened by amcnerney13 #11097: MSI: Remove win32com dependency from installer generator opened by techtonik #11100: test_fdopen: close failed in file object destructor opened by ekrauss #11101: plistlib has no graceful way of handing None values opened by bobveznat #11102: configure doesn't find "major()" on HP-UX v11.31 opened by Oren_Held #11103: Python 3.2 installer doesn't register file extensions on Windo opened by darren #11104: distutils sdist ignores MANIFEST opened by jdennis #11105: Compiling evil ast crashes interpreter opened by benjamin.peterson #11107: Cache constant "slice" instances opened by scoder #11109: socketserver.ForkingMixIn leaves zombies opened by jwark #11110: Py_DECREF->Py_XDECREF in Module/_sqlite/module.c opened by brett.cannon #11112: UDPTimeoutTest derives from SocketTCPTest opened by rmtew #11113: html.entities mapping dicts need updating? opened by Brian.Jones #11114: TextIOWrapper.tell extremely slow opened by Laurens #11116: mailbox and email errors opened by sdaoden #11117: Implementing Async IO opened by jcea #1103350: send/recv SEGMENT_SIZE should be used more in socketmodule reopened by r.david.murray #11060: distutils2 sdist does not complain about version that is not P opened by gotcha #11061: Verify command option before parsing config file opened by sdouche #11066: cgi.py proposals : sys.stdout encoding + rewriting of parsing opened by quentel #11082: ValueError: Content-Length should be specified opened by William.Wu #11084: Serialization of decimal.Decimal to XML-RPC opened by gdr #1252236: Simplying Tkinter's event loop reopened by belopolsky Most recent 15 issues with no replies (15) ========================================== #11109: socketserver.ForkingMixIn leaves zombies #11101: plistlib has no graceful way of handing None values #11100: test_fdopen: close failed in file object destructor #11097: MSI: Remove win32com dependency from installer generator #11093: test_future - rename not-unittest files to make regrtest.NOTTE #11088: IDLE on OS X with Cocoa Tk 8.5 can hang waiting on input / raw #11074: fix tokenize so it can be reloaded #11072: Add MLSD command support to ftplib #11066: cgi.py proposals : sys.stdout encoding + rewriting of parsing #11063: uuid.py module import has heavy side effects #11062: mailbox fails to round-trip a file to a Babyl mailbox #11060: distutils2 sdist does not complain about version that is not P #11056: 2to3 fails for inner __metaclass__ class definition #11055: OS X IDLE 3.2 Save As menu accelerator opens two Save windows #11050: email.utils.getaddresses behavior contradicts RFC2822 Most recent 15 issues waiting for review (15) ============================================= #11116: mailbox and email errors #11110: Py_DECREF->Py_XDECREF in Module/_sqlite/module.c #11109: socketserver.ForkingMixIn leaves zombies #11104: distutils sdist ignores MANIFEST #11102: configure doesn't find "major()" on HP-UX v11.31 #11101: plistlib has no graceful way of handing None values #11093: test_future - rename not-unittest files to make regrtest.NOTTE #11090: Doc errors for unittest in Python 3.1 #11089: ConfigParser 50x slower in 2.7 #11086: add lib2to3/__main__.py #11082: ValueError: Content-Length should be specified #11079: Make OS X entry in Applications like that in Windows #11078: Have test___all__ check for duplicates #11076: Iterable argparse Namespace #11074: fix tokenize so it can be reloaded Top 10 most discussed issues (10) ================================= #11071: What's New review comments 20 msgs #10845: test_multiprocessing failure under Windows 12 msgs #7111: abort when stderr is closed 11 msgs #10227: Improve performance of MemoryView slicing 11 msgs #11114: TextIOWrapper.tell extremely slow 9 msgs #11082: ValueError: Content-Length should be specified 9 msgs #8914: Run clang's static analyzer 8 msgs #11037: State of PEP 382 or How does distutils2 handle namespaces? 8 msgs #11024: imaplib: Time2Internaldate() returns localized strings 8 msgs #2193: Cookie Colon Name Bug 7 msgs Issues closed (53) ================== #6045: Add more dict methods to dbm interfaces closed by eric.araujo #6465: email.feedparser regular expression bug (NLCRE_crack) closed by sandro.tosi #7074: Turtle module crashes python closed by belopolsky #8275: callback function on win64 results in bad behavior. mem corrup closed by pitrou #9124: Mailbox module should use binary I/O, not text I/O closed by r.david.murray #9127: subprocess.Popen.communicate() and SIGCHLD handlers closed by ned.deily #9418: Move _formatter_* methods from string type into _string module closed by eric.smith #9763: Crashes upon run after syntax error encountered in OSX 10.5.8 closed by ned.deily #9884: The 4th parameter of method always None or 0 on x64 Windows. closed by owenl #10480: cgi.py should document the need for binary stdin/stdout closed by v+python #10573: Consistency in unittest assert methods: order of actual, expec closed by michael.foord #10847: Distutils drops -fno-strict-aliasing when CFLAGS are set closed by eric.araujo #10939: imaplib: Internaldate2tuple raises KeyError parsing month and closed by belopolsky #10940: IDLE 3.2 hangs with Cmd-M hotkey on OS X 10.6 with 64-bit inst closed by ned.deily #10961: Pydoc touchups in new browser for 3.2 closed by georg.brandl #10989: ssl.SSLContext(True).load_verify_locations(None, True) segfaul closed by haypo #11025: Distutils2 install command without setup.py or setup.cfg creat closed by eric.araujo #11032: _string: formatter_field_name_split() and formatter_parser() d closed by eric.smith #11035: Segmentation fault closed by brett.cannon #11038: Some commands should stop if Name and Version are missing closed by eric.araujo #11040: After registering a project to PyPI, classifiers fields aren't closed by eric.araujo #11042: [PyPI CSS] Adding project urls onto a project page using regis closed by eric.araujo #11043: On GNU/Linux (Ubuntu) distutils2.mkcfg shouldn't create an exe closed by eric.araujo #11044: The description-file isn't handled by distutils2 closed by Julien.Miotte #11052: Fix OS X IDLE menu accelerators for Save As and Save Copy closed by ned.deily #11053: OS X IDLE 3 with Tk 8.4 appears to hang with syntax error closed by ned.deily #11054: OS X installer build script for 3.2 can no longer build with s closed by ned.deily #11057: Missing import of DistutilsOptionError closed by eric.araujo #11064: abc documentation version conflict closed by dustin.farris #11065: Fatal "can't locate locale" errors when zip file with director closed by ned.deily #11068: Python 2.7.1 Idle traceback on OS X (10.6.6) closed by r.david.murray #11069: IDLE crashes when Stack Viewer opened closed by georg.brandl #11070: test_capi crashes and fails closed by brian.curtin #11073: threading.Thread documentation can be improved closed by pitrou #11075: Using Turtle with IDLE on Mac OS X closed by amcnerney13 #11080: Win32Serial.read coding error for non-blocking read closed by brian.curtin #11081: from struct import * misses pack_into closed by belopolsky #11083: threading.Thread - start() rises RuntimeException? closed by brian.curtin #11091: Bug with reimport in pkg_resources closed by brett.cannon #11094: Runtime error closed by amaury.forgeotdarc #11095: subprocess popen broken for bytes and backslash closed by eric.smith #11098: syntax error at end of line in interactive python -u closed by r.david.murray #11099: Bytes pickled with 3.1 not unpickled with 2.7 correctly closed by r.david.murray #11106: python 2.6.6 and python 2.7.1 cannot be built successfully bec closed by skrah #11108: Intermittent AttributeError when using time.strptime in thread closed by amaury.forgeotdarc #11111: See "Gmail" on your Google homepage closed by belopolsky #11115: csv readers and writers should be context managers closed by r.david.murray #1613479: pydoc info for a package doesn't list all package contents closed by eric.araujo #10947: imaplib: Internaldate2tuple and ParseFlags require (and latter closed by lavajoe #11036: Allow multiple files in the description-file metadata closed by eric.araujo #11058: dist directory not created when running sdist command closed by kelseyhightower #11059: Mercurial fails on code.python.org repo closed by sdaoden #1647654: No obvious and correct way to get the time zone offset closed by belopolsky | https://mail.python.org/pipermail/python-dev/2011-February/107911.html | CC-MAIN-2017-30 | refinedweb | 1,668 | 59.6 |
News Brief by Kip Hansen
/>The Piping Plover, a tiny little sea bird, has been struggling to survive in modern times as beaches are developed for tourists with houses hugging the shorelines of the Eastern Seaboard of the United States and the Great Lakes region, up into Canada. In Florida, on Cocoa Beach, where the condos are built 50 feet inshore of the low six-foot high dunes, the dunes are surrounded with yellow warning tape (think “yellow plastic crime scene tape”) and signs are posted to keep people and animals off the dunes during nesting season of the Piping Plovers.
“The piping plover (Charadrius melodus) is a small sand-colored, sparrow-sized shorebird that nests and feeds along coastal sand and gravel beaches in North America.” [ Wiki ] The IUCN Red List records the Piping Plover as “Near Threatened C2a(i)”. The letters and numbers mean that this species has been listed as Near Threatened, which is one step “up” (towards Endangered) from Least Concern, for the following reasons:
/>
(C) Population size estimated to number fewer than 10,000 mature individuals
(2) A continuing decline, observed, projected, or inferred, in numbers of mature individuals AND at least one of the following (a–b): (in this case “a”)
(a) Population structure in the form of one of the following
(i) no subpopulation estimated to contain more than 1000 mature individuals,
In short, here is the problem for the Pipers in a single image: />
Piping plovers make those nests in the sand (or pebbles) in areas like the one with the posted sign above. In Cocoa Beach, Florida, these beach grass (sea oats or other grasses such as coastal beachgrass, beach grass, marram grass) dunes look like this:
/>
Up against the condos is a thin strip of 6-foot dunes sparsely planted with beach grass, back by some mangroves in many places. Paths — some sand, some wooden planked — lead from each condo, through the dunes, to the beach.
This particular area doesn’t have ten blocks of single family homes and apartments directly behind the condos as many other areas do. In those homes, and apartments, are dogs and cats, many of who run free onto the beach. Along with the cats and dogs are raccoons that inhabit nearly every area of human habitation. The cats, dogs, and raccoons hunt for and eat piper eggs and chicks (and pipers if they can catch them). These domestic and wild predators, along with human disturbances, are the greatest threat for, and cause, of reproductive failure.
This situation is repeated all up the Eastern seaboard through New Jersey and New England and westward on the Gulf Coast.
It is not all bad news, though, thanks to widespread and long-term conservation work — roping off nesting sites, “caging” plover nests to protect them from predators and in some cases, 24/7 human-guarding of nests — have increased piping plover numbers according to the IUCN “there have been overall population increases since 1991 as a result of intensive conservation management, so the species is listed as Near Threatened. It is still dependent on intensive conservation efforts, so if these cease, or if trends reverse, then it would warrant immediate uplisting again.”
The Really Good News?
/>Hurricane Sandy! While it may seem odd that Tropical Storm Sandy could bring good news to any environmental or ecological story, in this case, it is true. We see from the above that over-development of beachfront areas has been the biggest problem for the lovely little pipers. Well, we all know that hurricanes and tropical storms destroy human developments and re-organize beaches — especially those long thin sand bars called ‘barrier islands’. Cocoa Beach, Florida is on such a barrier island. And Fire Island, one of the barrier islands along the southern shore of Long Island, New York, is another.
This Good News comes via the New York Times in a piece titled “Who Liked Hurricane Sandy? These Tiny, Endangered Birds”, authored by Annie Roth; a lovely, if counter-intuitive bit of science reporting. Here’s the gist in images:
This is just a sample of the changes that Sandy made to Fire Island — the barrier island has been breached cutting a new channel across from the Atlantic to the enclosed waterway to the north. Huge new sand flats have been created — perfect for the lives and nests of the little Piping Plovers. In addition, Sandy basically washed completely over Fire Island, washing many homes, roads, and all those pesky, invasive predators — cats, dogs, raccoons, etc — into the sea. All to the benefit of the Piping Plovers:.
….
“Hurricane Sandy was obviously very catastrophic for human infrastructure on Fire Island, but on an ecosystem level, it worked wonders,” said Ms. Walker.
….
But on one island [ Fire Island ] that was heavily damaged by the big storm, the piping plover population has increased by 93 percent, Ms. Walker and colleagues reported in the journal Ecosphere this month.
The deeper cause and effect relationship lies in this bit as explained by Annie Roth in the NY Times’ piece:
“Barrier islands like Fire Island are known as early successional habitats [pdf], [assistant professor at SUNY College of Environmental Science and Forestry ].
The key point for “early successional habitats” is that they must be disturbed, disrupted, destroyed and allowed to return (as is the case with forests and wildfires) in order to retain their characteristics as early successional habitats.
The barrier islands of the US Eastern Seaboard, for instance, are regularly (on a multi-decadal scale) struck by hurricanes or powerful storms that re-shape, rebuild, partially destroy, and wipe out existing flora. These barrier islands subsequently, over time, go through a series of predictable successions of the return of plants and animals that occupy various niches on these islands. Many conservation efforts misguidedly try to keep things from being changed — to prevent disturbances — which is a death knoll for these very necessary types of habitats.
The plucky, lucky little Piping Plovers need the newly created sand flats, wiped clean of predators and human development, to really succeed. Nature will continue to provide new habitats for them as the unending succession of storms roll ashore as they have done for a very, very long time. We can help them along by enforcing restrictions of dogs and other human pets to their owner’s homes and keeping them from the beaches we share with nesting plovers (and other nesting seabirds), creation of wild seashore reserves, and continued conservation efforts along the waterfronts of the world. Not every beach need be covered with condos for the rich.
/>
The Pipers of Fire Island say “Thanks, Sandy!”
# # # # #
Author’s Comment Policy:
I like Piping Plovers — they dash from here to there pecking up little bits of sea life from the water’s edge, often reminding me somehow of the Keystone Cops. They don’t seem to have any of the bad habits of some of the other, larger seabirds; never trying to steal one’s chips or dropping their droppings on one’s beach blanket. There are a lot of YouTubes featuring the Pipers….one of which, though a little bit preachy, shows Pipers on Long Island.
My wife and I have watched Piping Plovers from the Caribbean (where they winter) all the way up to the coast of Maine. You need not fear for them — their numbers are rebounding. Lucky for them, they are little and cute and comical — just the right mixture to garner a lot of public sympathy and support.
Thanks, Sandy! …. and Thanks for Reading.
# # # # #
53 thoughts on “The Pipers of Fire Island”
Thanks Kip. Like the last one, good reading.
David ==> I have a ‘secret’ — I find a constant diet of nothing-but-climate-wars a little bit boring — important, but it gets a little old. A little variation into “interesting things” keeps the readers returning for more. (I hope!)
Thanks for the article, Kip Hansen.
We have the same problem with piping plovers here in the Midwest. Birds without an ounce of common sense* lay their eggs in sand-bolstered nests, and either have to be moved or fenced so that the offspring won’t be hit by stray volleyballs or kept awake all night with rock concerts. The problem is that if they raise their chicks where there are lots of people, they will keep coming back over and over and miss the properties that are set aside for wildlife like them.
*Birds without an ounce of common sense include Canada geese and ducks like mallards, because they will nest and hatch their eggs in silly places like gravel outside a busy office building, or in a popular space like a shopping mall. They need to be relocated. They just aren’t real bright.
Sara ==> Silly birds ought to be sent back to school to learn to read and forced to obey posted signs put up to protect them!
Seriously, if we want to protect them, we have to set aside the places they nest — these cute little birds are not particularly put off by the antics of humans — I’m not an eco-nut by anhy means, but there has to be some comon sense applied to our co-existence with wildlife — exactly why must rock concerts take place on beaches instead of at the air-conditioned stadiums we build for entertainment?
Sometimes I think it is the humans that don’t have an ounce of common sense.
This is about the history of a Texas beach with increasing human intrusion. Most species decreased, one increased, guess which one—Foster, C. R. 2007. Population and migration trends of coastal birds on Mustang Island, Texas. M. S. Thesis University of Texas. Not sure if it has been published. Shorebirds show up in the Gulf in the winter thought to be from explosions of prey populations. Some of these (at least some bigger sandpipers and plovers) can be seen picking in dead fish, maybe for insects. Some species also pick something from intertidal oyster reefs, but never saw that in the oyster literature.
PELICANS!!!
Ha! “…why must rock concerts take place on beaches instead of at the air-conditioned stadiums we build for entertainment?” Oh, that’s so that humans can trash the place, dontcha know.
The Stones recently held their concert at Soldiers Field in Chicago. I cannot think of a better place, unless it’s a baseball field. The ticket sales alone will bring in city revenue (taxes!) and the vendors, of course, will make money hand over fist. So why have a rock concert on the beaches of Lake Michigan, never mind volleyball contests? Because people think the beaches belong to THEM, not to wild birds. If the birds went further north, to the sandy shores of Lake Michigan near the marinas and the resort hotel, no one would bother them, but they want Montrose Beach, for Pete’s sake!
There are kildeers around here now. Some of them chose to nest in a yard full of (*junk) spare parts. They’re still there. Either the owner is feeding them, or they’ve got lots of bugs to hunt over at the nursery next door.
I will never understand why these feather flockers won’t go to a more natural area where they are relatively safe, but they don’t.
Sara ==> They are “bird brains”….
Sea creatures are the same — they happily make nests and congregate around any old junk thrown into the ocean and don’t discriminate between an old sunken yacht and a natural reef. I once tried to pickup a beer can from the bottom near a reef (we carried a net bag while snorkeling for litter patrol) only to have the can snatched back by the octopus that was using it as a door to its lair! Stupid thing didn’t realize that it was trash….
Octopi are one of the more intelligent creatures on the planet, but with a different type of brain that is difficult for us to imagine. The soda can door sounds like a pretty effective solution to a problem.
James P ==> And, it was conveniently at hand (or “at arm”, really). Octopi (or octopuses, your choice) are very secretive and in hundreds of hours snorkeling reefs we have seen only a few — the beer-can-man was one of them.
“They just aren’t real bright”
Well perhaps they are smarter than you think. I remember a mallard who nested in some shrubs next to a hangar on a busy AFB. Each year she led her chicks straight through the base, wriggled under the fence and into a nearby river. This was actually a very smart strategy since there were no foxes, cats, hunters or other predators around and the walk through the base was also quite safe since all traffic immediately came to a stop as soon as word spread that mammy duck was on the move.
tty ==> You see, the Air Force can be taught.
I’m curious though, what kept foxes, cats etc off the base? Was there an intentional suppression program?
The fences kept the foxes away, and the nearest cat-keeping civilians were a long way off.
tty ==> So no service family homes on base then….
Sara: I have Muscovy ducks and have had Pekin, Rowan and the Muscovy ducks. Not one of them actually laid eggs “where they are supposed to” and these are domestic ducks. I fought one hen this morning for the egg she laid in the 18″ grass and was defending with zeal. The Pekins were the worst—dropping eggs all over the place. Ducks just do not lay like chickens in their safe little houses.
Interesting. For nearly 3 decades we took Louisiana students to the Florida panhandle to show them what clear water looked like. Beside the point, but it was also less productive. I recall signs saying it was illegal to pick sea oats, logical, but I may have a picture of what we saw showing the sign and a bulldozer behind razing the dune, maybe building a condo. During that period a couple of hurricanes rearranged the beach and the condos. We also went by Mexico Beach in its early stages, among others, pointed out the potential.
Birds are one of the most important estuarine/ocean predators with relatively little work on their energetics in many places, direct food analysis not much allowed. They may take a greater biomass than fishermen. Saviour programs may now be somewhat distracting saving very common species, wonder what their current success rate is, but there has been progress improving populations. Breeding seabirds don’t always cooperate as also early season storms and variations in mean high water.
HD Hoese ==> Nature provides both nurture and danger for almost all species — seabirds included. The most successful breeding areas for ground nesting seabirds are nearly deserted sand-bar islands, both barrier islands and coral sand atolls albatrosses are an example.
These little fellows eat little worms and crustaceans that abound in the sand at the wave wash line.
Sleeping Bear Dunes is home to a growing Plover Population. Estimated nesting pairs in 1986 = 12, Nesting pairs today = 80. The single biggest threat are the %^(&^* tourists from places like Chicago and Detroit that are incapable of reading signs, they will walk right through a protected area totally clue-less.
As of this morning one of the rangers out at the Dunes told me that they expected a 50% survival rate for the chicks this year. With 3-4 eggs per pair that will be an additional 60-80 birds. The survival rate for the first year is low, but the dynamic is there for the populations to recover nicely over the next 8 to 10 years.
Other birds are also increasing in population here in dramatic fashion, especially a number of raptors like red-tails and harriers.
To any green-freak I just point out the facts. Unfortunately they still often fail to see that the environment is becoming more friendly.
mark from the midwest ==> Thanks for the good news from Sleeping Bear Dunes — — in northwestern Michigan on the shores of Lake Michigan — which reminds us that seabirds also live on freshwater lake shores.
A great article… you only fail to mention the local volunteers who do so much to protect the plovers nesting on their local beaches. It is those people who keep the plovers nesting…
Just one example
Nice story. Good to see that a reporter can actually report some science accurately.
Kevin Kilty ==> It was a relief to see some good solid science reporting in the ny Times. Annie Roth, the author, did not have a hyperlink on her name, as most regular NY Times journalists do — using the Imes’ search function, this appears to be her only piece there.
Dealing with feral cats would be a problem.
Shoot them on site ….. problem solved.
And draw fire from cat lovers and anti-gun activists.
Tom ==> Free-living/free-roaming cats can be eliminated by municipalities, counties, and States through the same type of regulations that reduced the numbers of feral dogs. Require licenses, vaccination, and restriction to the owners home/property or require them to be leashed in public. There is simply no excuse whatever to allow them to run loose. Cats found on the loose and unlicensed, feral or pre-owned, should be destroyed humanely or held until adopted (though there is no shortage of cats and kittens).
If you are interested in the topic, I suggest The Cat Wars by Peter P. Marra and Chris Santella.
Dealing with the cats would be fairly easy — it is the misguided cat lovers that is the problem.
Shooting cats is humane by the way, have always done it and always will. Instant death. The three s saying applies here. Shoot, shovel, and shut up.
Big T ==> Careful there, Big Guy … depending on where you live, that could be a serious crime according to the laws in your area.
might well be…but then so is roaming damned cats! im pleased to say that no cat coming into my yard that cant do zero to 60 in 3 seconds escapes, ditto foxes nd possums and rabbits.
if I have to register desex(or pay huge xxtra reg fees) and confine my dogs then cat owners can do the bl**dy same!
ozspeaksup ==> That’s the ticket, tiger. Go get ’em
I have two cats that were dumped. One was a kitten about 6 months old. I took her in to keep her from going after the birds around here. The other was an adult calico that was ear-tipped (meaning she’d been in the TNR program) but she was abandoned when her caretaker left the area, and I started feeding her to keep her from hunting the birds. Now she’s indoors, too and the birds are always looking for food, winter or summer.
Sara ==> I almost like cats — and can become skeptically fond of various family INDOOR-ALWAYS cats.
The Domestic cats is simply a vicious predator, a killing machine, when allowed to roam the natural environment, even in suburbia.
Keep ’em in….that’s my rule and I would pass it into law in a minute if it were left to me.
We have a cat. We live out in the county and rats/mice are a problem. Owls and snakes can’t keep up with them. Cat stays indoors or confined by us. Recently, we found an abandoned, injured kitten. We fed her then took her to a shelter. Little kitten may lose her tail. Hopefully, she’ll be adopted.
cdquarles ==> Barn cats has a role to play on farms. Barn cats have not been found to wander and prey on wildlife (other than the rodents and birds that inhabit the barns and barnyards themselves. I have no real objection to Working Animals (dogs and cats that perform a valuable function) as long as they are generally restricted to the owners property or buildings.
Cats will not usually kill full-grown rats in my experience. For that you need a good “ratter” — something like a dachshund which take to the task as if being paid for it.
I am not a cat hater — I just think we should keep out pets constrained to our homes or immediate property — working animals restrict themselves to their workplaces for the most part.
Best post in ages, by far.
Ecology, a bit of other science, the natural world. Excellent.
0% hysteria, 0% alarmism, well done.
We really do need a break from all that nonsense, it really is getting tiresome.
A Hat Tip and my compliments to Kip Hansen.
TonyL ==> Thank you sir….
“The Pipers of Fire Island” would be a great name for a pipe band.
Another species threatened by the encroachment of humans and vagabond racoons is the Perdido Key Beach Mouse. We must protect these endangered species by keeping people away from beaches with regulations, restrictions, and punishment for offenses, especially if inebriated or having too much fun.
/sarc
pochas94 ==> No need for the /sarc tag — the Peridio Key beach mouse is endangered, but probably not by beer swigging college kids having fun — the mouse is nocturnal and spends the hot days deep in its burrow in the cool sand, venturing out only at night to eat the seeds of various beach grasses, like sea oats.
Like the Pipers of Fire Island, it lives on a barrier island, subject to the vagaries of storms coming ashore from the Gulf of Mexico. Unlike the Pipers, it can’t fly away to a place of safety, and was reportedly nearly wiped out in the mid-1990s when hurricanes Erin and Opal battered the key. See my story here about the poor Bramble Cay melomys.
Of course, the little mouse is also threatened where human-habitation companion animals — mostly cats — are found living in the wild environment where they don’t belong.
A subspecies living on a single small island will always be threatened. The obvious thing to do would be to move some of them to another key, but that is probably illegal, or at least would require 20 years of research and litigation.
tty ==> It is surprising that a captive breeding program and re-introduction to near-by, very similar barrier islands hasn’t already begun or been carried out.
I fear for the little mice — they may well end up like the Bramble Cay melomys. (see link above).
That said, Perdido Key is not small — but goes for miles and miles, similar to Cape Canaveral-thru-Cocoa Beach-down past the Air Force base, all the way to Stuart, Florida (but not nearly as long.)
Ho hum.
Another species of ground nesting birds goes extinct.
Maybe someday they will decide to nest somewhere sensible, like Antarctica.
Ground nesting for birds is not a good idea. At least these guys can still fly and haven’t met the fate of the Dodo bird, or the dinosaurs.
Joel ==> It isn’t like they “choose” to be ground-nesting, that’s just their place in the web of life. The ground nesters are particularly prone to predation, particularly by human-pet animals (cats and dogs) and by those animals humans tend to drag along with them when they occupy an area — rats, pigs, goats, etc. Raccoons also tend to follow human habitation in modern day America — and can be very destructive.
For the Pipers, we humans have tended to overrun their natural habitat with beach homes, condos, and (according to one reader) rock concerts.
As long as they can survive the winter migration these little birds will be ok. Many of them make the trip to the Canadian prairies where they can nest in natural habitat pestered only by what they expect.
Len Pryor ==> Yes, they are amazing widespread, but rather thinly. Most of the concern comes from populations in danger of being locally extirpated … sensible steps will help local breeding populations.
Going overboard (eco-nutty) will estrange the general public and lose support.
Another fine piece, Mr. Hansen.
Thank you.
I will call it to the attention of my professional ornithologist friend.
‘Near threatened.’ Meaning they are not threatened. Yawn.
The U.S. has no such classification.
‘In Florida, on Cocoa Beach, where the condos are built 50 feet inshore of the low six-foot high dunes, the dunes are surrounded with yellow warning tape’
False characterization. The vast majority of the Atlantic coast is NOT like Cocoa Beach.
‘Today the world faces enormous challenges such as tackling climate change and ensuring food, nutrition and water security.’ – IUCN
Bunch of right wingers, eh?
Gamecock ==> I have sailed the Intracoastal waterway, up and down the Eastern seaboard eight times (maybe ten…) It mostly runs just inshore of the barrier islands which start with the southern shore of Long island, New York, then in New jersey (the Jersey shore), Most of delaware is really facing the Delaware Bay, but once exposed to the Atlantic, the barrier islands start again. Nearly the rest of the way down to the Keys has barrier island, and where not designated parks of preserves, if has houses and development.
Near Threatened is the IUCN classification.
Piping plovers taste like chicken.
Joey ==> Cute but they are really way too small to be eaten at all….sparrow sized.
tiny little
as opposed to big huge
Juice ==> Yes, I suppose so .. .. poetic license — this is explanatory writing here —
OK – and then there’s game wardens protecting piping plovers:. | https://wattsupwiththat.com/2019/06/28/the-pipers-of-fire-island/ | CC-MAIN-2020-50 | refinedweb | 4,262 | 69.41 |
This is in reply to Accepted Python Solution 4 lines. I wanted to take you up on a game of code golf ;) although my use of generator expressions may be considered less readable.
Brute Force in 2 lines, O(n^2) time, O(1) space:
(Edited first solution thanks to advice from StefanPochmann!)
def twoSum(s,n,t): return [[i,n.index(t-x)] for i,x in enumerate(n) if t-x in n[:i]][0]
Hash approach in 3 lines, O(n) time and space (two passes):
def twoSum(self, xs, sum): d = {x:i for i,x in enumerate(xs)} return next([i,d[sum-x]] for i,x in enumerate(xs) if sum-x in d and i!=d[sum-x])
Note the dict comprehensions [1] as well. This is super handy in interviews and works similarly for sets (omit the
: symbol).
[1] PEP uses "expression" and "comprehension" interchangeably in this context, as they are (transitively, via other languages) inspired by "set comprehensions" in mathematics.
For code golf, you're using far too many unnecessary characters :-)
(spaces and variable names longer than one character)
Your first version is wrong and doesn't get accepted. Update: got fixed.
Shorter hash approach:
def twoSum(_,n,t): j={x:i for i,x in enumerate(n)} return[[i,j[t-x]]for i,x in enumerate(n)if j.get(t-x)>i][0]
Aha, quite right :) I was only measuring lines at the time. And that bug! That's what I get for editing my code directly in the post without checking it.
Thanks! I updated the first approach above, but left the other one as is so your shorter hash approach would still make sense.
Oh, and cool use of
j.get(...) instead of
j[...]. I never thought to check what the difference was. | https://discuss.leetcode.com/topic/56215/two-line-brute-force-three-line-hash-approach-python-code-golf | CC-MAIN-2017-43 | refinedweb | 308 | 65.62 |
The QUdpSocket class provides a UDP socket. More...
#include <QUdpSocket>
Inherits QAbstractSocket.
Note: All the functions in this class are reentrant.
The QUdpSocket class provides a UDP socket.() to transfer data.() to read it.
Example:); } }.
Creates a QUdpSocket object.
parent is passed to the QObject constructor.
See also socketType().
Destroys the socket, closing the connection if necessary.
See also close().
Binds this socket to the address address and the port port. When bound, the signal readyRead() is emitted whenever a UDP datagram arrives on the specified address and port. This function is useful to write UDP servers.
On success, the functions returns true and the socket enters BoundState; otherwise it returns false.
See also readDatagram().
This is an overloaded member function, provided for convenience. It behaves essentially like the above function.
Binds to QHostAddress:Any on port port.().
Receives a datagram no larger than maxSize bytes and stores it in data. The sender's host address and port is stored in *address and *port (unless the pointers are 0)..
See also readDatagram().
This is an overloaded member function, provided for convenience. It behaves essentially like the above function.
Sends the datagram datagram to the host address host and at port port. | http://doc.trolltech.com/4.0/qudpsocket.html | crawl-001 | refinedweb | 201 | 63.36 |
they will be properly imported, so tax and duties paid etc please?
if they send me through ups or fedex, and declare the true value, is that ok ?
in uk I pay income tax
As long as the items are genuine, import duty, tax and VAT is paid then yes it would be legal.
You need to check the terms and conditions of Ebay and Amazon etc to see if they prohibit imported items.
But if not then yes, there is no reason why you can not.
Unless I can clarify anything for you, may I wish you a Happy Christmas.
do I need to apply eori number ?
Yes and you should apply to HMRC for that.
Economic Operator Registration and Identification (EORI) Scheme
HM Revenue & CustomsEORI Team13th Floor SouthGovernment BuildingsTy GlasLlanishenCardiffCF14 5FP
Does this help?
but i have heard manufacturer need to give permission before i can sell is that correct? otherwise they can say I breach the copyright law
If you have properly purchased them then you are not in breach of copyright.
You are not taking goods and passing them off as them.
They are the genuine products.
what means by the term 'properly purchased'
They can of course make things hard for you by cutting off your supply.
if I buy on ebay hongkong, is that properly?
Properly - means from genuine wholesaler abroad
It needs to be the genuine article.
all items are genuine no doubt about that
Yes.
If you have an audit trail for your purchases they should be ok,
how much is import duty? if you know
I dont, but VAT is 20% and duty around 5%.
You of course need to make sure they are advertised as imports and not UK sourced.
so say £1000 worth of goods before entering in UK , HMRC charge 5% which is £50 for import duty
Roughly.
does uk custom charge vat as well as duty?
Yes
so I need to pay about £1250 for the £1000 worth of goods
On the purchase price PLUS shipping
Yes but VAT is chargeable on the shipping cost too
so if the goods cost me say £1000 , it will cost me around £1250 before reach me in the UK right
import duty 5% (£50)+ vat 20% (£200)
Can I clarify anything for you about this today please?
yes
thanks
happy christ:
Happy Christmas to you too!
Can I help with anything else? | http://www.justanswer.co.uk/law/86pqi-thinking-selling-grey-imports-camera-lens-amazon.html | CC-MAIN-2017-17 | refinedweb | 402 | 80.51 |
Please help with my Arduino program (controlling servo)? Answered
I started trying the Arduino programming 1 days ago so I'm not sure what is wrong with my program (also, sorry for the messy look)
const int buttonPin = 2;
int buttonState = 0;
#include <Servo.h>
Servo myservo;
int n = 0;
int pos;
int lc = 0;
void setup() {
myservo.attach(9);
pinMode(buttonPin, INPUT);
myservo.write(pos);
}
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonPin == HIGH) {
if (lc == 0) {
for(pos = n; pos <= 180; pos++) {
myservo.write(pos);
buttonState = digitalRead(buttonPin);
if (buttonPin == LOW){
n = pos;
break; }
if (pos == 180) {
n=pos;
lc = 1;}
delay(15);
} }
else {
for(pos = n; pos>=0; pos--)
{
myservo.write(pos);
buttonState = digitalRead(buttonPin);
if (buttonPin == LOW){
n = pos;
break; }
if (n == 0) {
n = pos;
lc = 0;}
delay(15);
} }
}
}
Basically, it's to use a button to control the servo, if the button is press, the servo will spin (0 to 180 then 180 back to 0), if the button is released, it will stop the servo, and pressing the button will continues the servo movement (not resetting it). The "lc" int is used to show if the servo was moving from 0 to 180 (lc = 0) or 180 back to 0 (lc = 1). I only studied Pascal before so I have a bit trouble understand it so if there was big mistake in my program, please let me know.
Thanks for your help.
Discussions
Best Answer 5 years ago
First, make sure you can move the servo AT ALL from your code. Try setting its position to 180, and 0 depending on the state of the pin.
Have you got a pull up on your input pin ?
In your code, don't use a for loop and a break, its not good style, just use a while loop. Its also easier to do the sweep if you use a boolean for the state of the ramp, when its time to change direction, you just invert ic
if (ramp>=180) ic=!ic
if (ramp<=0) ic=!ic
If ic ramp-- else ramp++
Answer 5 years ago
I found the error in my code, it's a stupid mistake:
What I wrote:
buttonState = digitalRead(buttonPin);
if (buttonPin == HIGH)
I messed up the State and the Pin ¬¬"
Anyway, my code work now, I'll still gonna try your suggestion, thanks again
5 years ago
Describe what it ISN'T doing.
Answer 5 years ago
It doesn't do anything. When I press the button, it doesn't sweep | https://www.instructables.com/community/Please-help-with-my-Arduino-program-controlling-se/ | CC-MAIN-2021-04 | refinedweb | 419 | 67.69 |
This chapter is an excerpt from, Web Development with TIBCO General Interface: Building AJAX Clients for Enterprise SOA, authored by Anil Gurnani, published in the Addison-Wesley Professional Developer’s Library, ISBN 0321563298, Feb. 2009, Copyright 2009 Pearson Education, Inc. For more info please visit informIT and Safari Books Online subscribers can access the book here:..
This chapter provides a high-level architecture of TIBCO General Interface and its framework components and describes how General Interface applications work in the browser..
A General Interface application begins by executing some JavaScript code that can be called the boot loader. In the General Interface package is a JavaScript file, JSX30.js, that contains the functions to bootstrap a General Interface application and begin running it. The Deployment utility generates the code to load this file using HTTP protocol with the appropriate parameters for the application. As the HTML page that contains the General Interface application is loaded by the browser, a call to JSX30.js is made, and it begins to load the application.
The first file that is loaded for any application is the config.xml file, which defines application files and various properties. Among other things, config.xml has a list of JavaScript files that begin to be loaded into browser memory. In the file config.xml is a reference to a file that defines the startup screen. The startup screen definition is also an XML file that contains the layout of the General Interface application as well as controls and widgets and/or subcomponents within it.
At this point, an instance is created of the global Application Controller, which is the main orchestrator for the application being loaded. It serves as the global context and contains all other widgets and controls for the application. Figure 2.2 shows the typical life cycle of a General Interface application.
General Interface supports a dynamic class loader, which loads only the JavaScript and XML files that are needed. This allows you to modularize your application to make sure it is responsive and does not have to download large files. Only the files needed for the opening screen are loaded, and instances of the startup screen and the controls in it are created and rendered; next, the execution control is passed on to the user, who then drives the application. Additional JavaScript and XML/XSL files are loaded and processed as needed.
Components such as dialogs and other controls contained within those dialogs do not need to be loaded initially. The General Interface framework provides methods to dynamically insert these components into the Application Object Model as needed. For example, when the user clicks the Save button, the application can call a method to display the Save dialog, which is defined in a separate XML file. This component XML file is loaded by General Interface into memory. After the file is loaded, General Interface instantiates JavaScript classes that are referenced in that file, and then it inserts the new component into the Application Object Model hierarchy and renders it onscreen. When the dialog is closed, it is removed from the Application Object Model. After they are downloaded, the components can be cached in the browser memory so that another fetch will not be required when this component is needed again.
General Interface also includes a utility to compress and obfuscate JavaScript files. In a nutshell, this utility takes in a number of JavaScript files and combines them into a single JavaScript file. It also changes the names of variables and methods to use as few characters as possible to reduce the size of the resulting JavaScript file. This is in direct contrast to the concept of dynamic class loading. Application developers have to analyze and understand the impacts of each strategy and adopt one that suits their requirements and environment. For very large applications, it is possible to use a hybrid approach, where classes are grouped into a few key groups and compressed using a merge utility into a few separate files that are loaded dynamically on demand.
General Interface defines screens and controls at a higher level of abstraction than that of the HTML Document Object Model. This model, called the Application Object Model (AOM), maps to the native browser's DOM. This enables General Interface applications to run in any browser where General Interface's AOM is implemented. Figure 2.3 shows a designer view of application canvas for a sample application in TIBCO General Interface, and Figure 2.4 shows the XML definition of the same appCanvas.
As you can see, every element's properties are defined in XML, and it is associated with a JavaScript class. As the General Interface controller loads the components, it creates an instance of the associated JavaScript class to handle events and behaviors for the component. This provides a great degree of encapsulation for classes and widgets. It is possible to make use of the familiar concepts of object-oriented programming to extend built-in widgets (or create new ones). As you build your canvas in GI Builder, it builds this file, and you can view a user-friendly representation of this file in the Component Hierarchy quadrant in the GI Builder.
As stated earlier, all General Interface controls and widgets that consume data are driven by a backing XML model. The data must be in a format known as 'Common Data Format,' or CDF. CDF is a very simple format that defines a few key elements and leaves the attribute space open. Attributes are mapped to data elements in controls. The main advantage of CDF is that it can drive any widget in TIBCO General Interface, which makes it possible to have the same backing CDF for a grid as well as a chart. The Model part of the MVC pattern in General Interface can be thought of as a CDF in TIBCO General Interface.
JavaScript Object Notation (JSON) is a simple format for accessing and manipulating object properties. It is based on a subset of JavaScript Programming Language Standard, but is text based and is therefore language neutral. Because it is based on the JavaScript standard, it is inherently supported by TIBCO General Interface.
CDF Format also makes it very easy to manipulate the associated objects using a JSON paradigm. Each node in a CDF can be thought of as a JSON object where XML attributes map to JSON properties. It is possible, then, to use XSL/XPATH to manipulate this CDF when using an XSL style sheet, and at the same time, it's possible to update the fields using JSON syntax (for example, obj.property = x). Because TIBCO General Interface combines JavaScript and XML, this becomes a key convenience when dealing with the data structures in TIBCO General Interface applications.
Prototype framework version 1.5 was released in January 2007 and introduced the concepts of object-oriented programming to JavaScript. Prototype framework started out as a small set of functions written in JavaScript to make it easy for developers to write modular code in JavaScript.
Object-oriented programming has been very successful in the rest of the development world, but the JavaScript language does not inherently support the concept of classes, interfaces, inheritance, and polymorphism. JavaScript does, however, have the capability to create objects that may have properties, and it does support the concept of a function pointer. So a clever group of people used those features as building blocks to create a framework in JavaScript that allows developers to use object-oriented concepts to write JavaScript code. For example, you could create a class called Button and have a method in it called click(), and extend the class to create other types of buttons, such as ImageButton, RollOverImageButton, and so on.
click()
ImageButton
RollOverImageButton
The Prototype framework consists of a single JavaScript file that defines various functions that can be used to define custom classes. The Prototype framework now includes support for AJAX by providing some classes to wrap an AJAX request and response object. Figure 2.5 shows the documentation page for General Interface's JavaScript framework, which is loosely based on the Prototype framework.
TIBCO General Interface's JavaScript framework adds a Java-like package structure and organizes the code in class files, interfaces, and packages. This goes a long way toward making JavaScript look and feel like Java. There is even a dynamic class loader in TIBCO General Interface that can download classes as needed. General Interface framework adds functions to signal to the General Interface class loader when another class is required. All JavaScript code is written in smaller classes. Although a single source code file can contain multiple class definitions, it is advisable to keep the files small and define only one class in a single source file. This also helps with dynamic class loading because each class can be loaded quickly when needed. Remember, the classes are in JavaScript files, which live on the server but are used on the client, so class loading is done using an HTTP request. After they are loaded in the client, the JavaScript files are cached by the browser. It would be nice if this could be compiled code and executed much faster than JavaScript on the client side. Also, a compiler would aid at development time. The IDE provided with General Interface offers some assistance in this regard, but it's not really a compiler.
For more details on how to take advantage of the object-oriented approach in the General Interface framework, refer to Chapter 7, —Object-Oriented JavaScript—Extending General Interface Widgets."
TIBCO General Interface's JavaScript API is organized into packages similar to the Java Development Kit. The root package name for all JavaScript classes is jsx3. Base framework classes to manage defining classes and packages are in the jsx3.lang package. A word of caution here is that the concept of package is somewhat similar to that in Java, except that if a package is defined using the jsx3.lang.package it cannot be dynamically loaded by General Interface's class loader. TIBCO General Interface packages allow pulling together several classes into a single package and allow JavaScript programs to discover classes, methods, and properties of a package. Although that is a good feature, it is possible, and in fact even advisable, to not use a package at all. Packages can also be created by using appropriate namespaces in class names. The following subpackages are available:
TIBCO General Interface has a very rich set of features, and its framework includes numerous classes and methods. Product documentation includes a comprehensive API reference document similar to that available for Java. This section presents some of the more commonly used classes and APIs with specific use cases and sample code snippets.
General Interface has a high-level application controller that orchestrates various functions in a General Interface application. A single instance of this controller is created for every application. The name of this global controller class in General Interface is jsx3.app.Server. It is used frequently in custom code because it allows access to other parts of the same application. For example, from an event handling code in a Select component, if you need to call a method on the grid component of the same application, you could use the following:
jsx3.app.Server
this.getServer().findJSXByName('mygrid').getSelection();
In this statement, this refers to the instance of Select control that is making the call. If you are a Java or C++ developer, it's the same this pointer that is used to refer to the current instance of a class. Refer to Chapter 7 for details on writing custom classes in General Interface.
Cache is the global memory space that is available to an application with smart management similar to Java's garbage collection. In this class, General Interface has provided a very smart mechanism for storing data within the browser that can be accessed by any other function or at a later time. This class is also used to keep some key data for some of the controls. For example, the grid control keeps its backing data in an instance of the jsx3.app.Cache class. Applications can use this to store larger result sets locally in the client memory. However, care must be taken to not load too much into the client browser and avoid a memory overload of IE (or Firefox).
jsx3.app.Cache
The exhaustive set of functions available in General Interface's framework makes it possible to write complex logic in a very few lines of JavaScript code that can also be embedded within the properties of controls similar to event handlers like onClick in HTML elements. JavaScript that accompanies any General Interface application can be written in the usual way in files with the .js extension. When you start a new project in General Interface, it opens a file logic.js in the workspace where small JavaScript scriptlets to handle event handling or validation logic can be placed. However, the best practice when writing JavaScript for General Interface is to develop JavaScript classes similar to Java classes. Each .js file should have only a single class defined in it. The way to define a class in General Interface is to use the defineClass() function from the jsx3.lang package. Listing 2.1 shows partial source code for a class written using TIBCO General Interface's framework:
/* File: CommandHandler.js
* Description: Implements a command handler for online
* equity trading application
*
* This class follows Command pattern to implement
* a generic handler for all menu items from
* the main trading window
*/
jsx3.lang.Class.defineClass (
"com.tibcobooks.gi.chapter2.CommandHandler", // name of class
com.tibcobooks.gi.chapter2.BaseHandler, // similar to "extends"
part of Java class definition
[], // Similar to "implements" part of Java class definition
function ( CommandHandler ) {
CommandHandler.prototype.buyURL =
'';
CommandHandler.prototype.sellURL =
'';
CommandHandler.prototype.init = function()
{
// this is the constructor in General Interface framework
};
}
);
This framework can be used independently of General Interface by simply including some of the JavaScript files from the General Interface distribution. General Interface framework is open source, so there is no licensing nor cost implication of using it this way. It certainly makes JavaScript code much more modular and therefore easy to maintain.
The process of loading the class essentially downloads the JavaScript source file and executes it using the JavaScript method evaluate() to insert it dynamically into the current set of available JavaScript files. After the class has been loaded, other parts of the program can create instances of the class, or they may call any static methods or access static properties by directly referencing it with the fully qualified class name—for example:
evaluate()
com.tibcobooks.gi.chapter2.CommandHandler.sellURL =
''
To deliver high performance, TIBCO General Interface relies heavily on the XML/XSL engine to render HTML instead of using DOM manipulation using JavaScript. It includes a large number of XSL style sheets in the distribution. Framework's XSL style sheets are stored in the JSX\xsl folder within the General Interface installation directory. A quick look in that directory shows the following xsl files:
cf_creator.xsl
cf_resolver.xsl
jsxlib.xsl
jsxmatrix.xsl
jsxmen.xsl
jsxselect.xsl
jsxtable.xsl
jsxtree.xsl
xml.xsl
Additionally, there are two subfolders: ie and fx. They contain XSL style sheets for the now deprecated classes List and Grid and are provided for backward compatibility with previous versions of General Interface.
Onscreen rendering of controls in General Interface is always done using these XSL style sheets. The XML data in CDF format is merged with one of these XSL style sheets to render the HTML for the browser. Editing these style sheets is not generally recommended because they are part of the General Interface product and may change with versions.
General Interface provides some hooks into these style sheets to allow customization. This technique helps the developer in another way—the developers do not have to write long and complex style sheets to do complete rendering; instead, they need to write only small fragments known as 'value templates,' which are inserted by the General Interface runtime before running the merge with one of these prebuilt style sheets.
A common requirement when displaying large lists of data is to be able to apply styling depending on the contents of the cell. In Microsoft Excel this feature is presented as Conditional Formatting in the Tools menu in Office 97 through 2003 and in the Home tab in the Styles palette in Office 2007.
In General Interface applications, this sort of formatting or coloring of data is achieved using fragments of XSL style sheets known as 'value templates.' Columns of a Matrix component have a property field called value 'template' where XSL can be placed to affect the output during runtime. Value templates are discussed in detail in Chapter 8, "Advanced Features of Matrix."
Back-end systems do not always produce CDF. They should not be expected to produce it, either. Therefore, General Interface runs the XML through an intermediate style sheet that can be supplied by developer. XML Transformer is a property of data-driven General Interface controls that can contain a reference to a style sheet, which will be used to transform XML data before rendering it onscreen using the General Interface style sheet for that control. This allows for very elegant application design where the back end can supply data in a standard XML format, and clients such as General Interface can transform that data to the format they can use. XML Transformer can also be used to manipulate the data before rendering it onscreen; for example, data can be sorted on several keys before passing on to the General Interface handlers. General Interface allows fields to be designated as sort keys. However, XML Transformers can be used to sort the data using a fixed XPath expression before applying the single column sort offered by General Interface.
Note that when you have full control over the back-end XML generation, and/or the sole purpose of generated XML is to feed it to TIBCO General Interface front end, it is best to produce CDF directly because it saves one step in General Interface processing. Transformers are a fast and efficient way to convert XML that is already being generated by some back-end application or when there are other client applications that require the full power of XML.
Chapter 4, "Working with XML and XSL," and Chapter 8 in this book discuss XML Transformers in more detail and provide a complete example of using XML Transformers in General Interface applications.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) | http://www.codeproject.com/Articles/34007/Chapter-2-Understanding-General-Interface-Architec | CC-MAIN-2014-35 | refinedweb | 3,121 | 51.28 |
view raw
This is never print:
"Exception in threadfuncqueue handled by threadfuncqueue",
"Exception in threadfuncqueue handled by main thread" and
"thread test with queue passed". Never quitting!
from threading import Thread
from Queue import Queue
import time
class ImRaiseError():
def __init__(self):
time.sleep(1)
raise Exception(self.__class__.__name__)
# place for paste worked code example from below
print "begin thread test with queue"
def threadfuncqueue(q):
print "\n"+str(q.get())
while not q.empty():
try:
testthread = ImRaiseError()
finally:
print "Exception in threadfuncqueue handled by threadfuncqueue"
q = Queue()
items = [1,2]
for i in range(len(items)):
t = Thread(target=threadfuncqueue,args=(q,))
if(1 == i):
t.daemon = False
else:
t.daemon = True
t.start()
for item in items:
q.put("threadfuncqueue"+str(item))
try:
q.join() # block until all tasks are done
finally:
print "Exception in threadfuncqueue handled by main thread"
print "thread test with queue passed"
quit()
print "=========== procedure style test"
def threadfunc(q):
print "\n"+str(q)
while True:
try:
testthread = ImRaiseError()
finally:
print str(q)+" handled by process"
try:
threadfunc('testproc')
except Exception as e:
print "error!",e
print "procedure style test ==========="
print "=========== simple thread tests"
testthread = Thread(target=threadfunc,args=('testthread',))
testthread.start()
try:
testthread.join()
finally:
print "Exception in testthread handled by main thread"
testthread1 = Thread(target=threadfunc,args=('testthread1',))
testthread1.start()
try:
testthread1.join()
finally:
print "Exception in testthread1 handled by main thread"
print "simple thread tests ==========="
You're putting things in a queue and retrieving them, but if you're going to join a queue, you need to mark tasks as done as you pull them out of the queue and process them. According to the docs, every time you enqueue an item, a counter is incremented, and you need to call
q.task_done() to decrement that counter.
q.join() will block until that counter reaches zero. Add this immediately after your
q.get() call to prevent main from being blocked:
q.task_done()
Also, I find it odd that you're checking
q for emptiness after you've retrieved something from it. I'm not sure exactly what you're trying to achieve with that so I don't have any recommendations for you, but I would suggest reconsidering your design in that area.
Once you get this code working you should take it over to Code Review because it is a bit of a mess. Here are a few thoughts for you:
You're not actually "handling" the exception in
threadfuncqueue(q). All the
finally statement does is allow you to execute cleanup code in the event of an exception. It does not actually catch and handle the exception. The exception will still travel up the call stack. Consider this example, test.py:
try: raise Exception finally: print("Yup!") print("Nope!")
Output:
Yup!
Traceback (most recent call last):
File "test.py", line 2, in
raise Exception
Exception
Notice that "Yup!" got printed while "Nope!" didn't. The code in the
finally block was executed, but that didn't stop the exception from propagating up the stack and halting the interpreter. You need the
except statement for that:
try: raise Exception except Exception: # only catch the exceptions you expect print("Yup!") print("Nope!")
Output:
Yup!
Nope!
This time both are printed, because we caught and handled the exception.
Your current method of raising the exception in your thread is needlessly complicated. Instead of creating the whole
ImRaiseError class, just raise the exception you want with a string:
raise Exception('Whatever error message I want')
If you find yourself manually manipulating mangled names (like
self.__class__.__name__), you're usually doing something wrong.
Using parentheses around conditional expressions is generally frowned upon in Python:
if(1 == i): # unnecessary extra characters
Try to break the C/C++/Java habit and get rid of them:
if 1 == i:
I've already gone beyond the scope of this question, so I'm going to cut this off now, but there are a few other things you could clean up and make more idiomatic. Head over to Code Review when you're done here and see what else can be improved. | https://codedump.io/share/FS067lkT5sqY/1/how-to-handle-exception-in-threading-with-queue-in-python | CC-MAIN-2017-22 | refinedweb | 685 | 64.81 |
I want to install the MaxMind GeoIP C library, so that I can use GeoIP as part of Django. I’m working on Mac OS X.
I’ve downloaded
GeoIP-1.4.8.tar.gz from here and run:
./configure make make check make install
Without any problems. I’ve also downloaded
GeoIP.dat.gz and
GeoLiteCity.dat.gz, unzipped them and put them in a local directory.
Then I’ve set the following paths in my
settings.py:
GEOIP_PATH = 'path_to_dat_files' GEOIP_LIBRARY_PATH = 'path_to_c_files'
Now I’m trying to run
python manage.py migrate (which has a reference to GeoIP in a project I'm using), but I’m still getting this error:
from django.contrib.gis.utils import GeoIP ImportError: cannot import name GeoIP
Any ideas? | https://superuser.com/questions/303460/is-there-a-way-to-install-geoip-from-source-code-on-mac-os-x | CC-MAIN-2019-47 | refinedweb | 126 | 71 |
)
Shivani (14)
Mike Gold(7)
Dipal Choksi(4)
Catalini Tomescu(4)
sayginteh (3)
Shamim Ahmed(3)
Chris Rausch(3)
John O Donnell(3)
Pramod Singh(2)
Saurabh Nandu(2)
Bill Farley(2)
Dipal Choksi(2)
Levent Camlibel(2)
Imtiaz Alam(2)
R. Seenivasaragavan Ramadurai(2)
Jason Zadroga(1)
Abhijeet Warker(1)
Ian Stallings(1)
Robert Rybaric(1)
Kareem Bawala(1)
tamilselvan (1)
C Vinod Kumar(1)
Maheswara Rao(1)
K Niranjan Kumar(1)
Anders Carlsen(1)
Rajadurai P(1)
Christian Hanssom(1)
Prasad (1)
Daniel Stefanescu(1)
Vinay Khurana(1)
Sankar Ramanathan(1)
Ravindra Sadaphule(1)
Prasad H(1)
Narayana Rao Surapaneni(1)
Neelam Iyer(1)
G Gnana Arun Ganesh(1)
Vijay Cinnakonda(1)
andyhmcheung (1)
Abrar Hussain(1)
Kamran (1)
Mark.Tutt (1)
Jayachandran Ramadurai(1)
Chris Harrison..
PaintBrush in C# - II
Jan 30, 2001.
This is a PaintBrush Application. In this Paintbrush user can draw some images and he can save the images in a persistence storage and later time can retrive the images..
Mar 13, 2001.
In .NET framework, the Icon class represents a Windows icon, which is a small bitmap image used to represent an object. The icon class is defined in System.Drawing namespace..
Assemblies : The Ins and Out : Part I
Apr 13, 2001.
In Part 1, I will cover what exactly an assembly is, and what an assembly.
Wireless Model : How Does It Work?
May 09, 2001.
The browser sends an HTTP request to the Web server, which interprets the request and determines which resources to retrieve or execute. If the URL specifies a file, then the server sends it back..
Scaling an Image
Jul 13, 2001.
This code will show You on way to scale an image with .Net Beta 2..
Working with Status Bars
Aug 01, 2001.
An article on how work with status bars and pens and images to the pens....
Web Control Bulider
Sep 03, 2001.
The attached C# program can be used by users who dont have VS.NET IDE to generate the code for WebControls..
Web Based Front-End for SMTP Email Program
Sep 14, 2001.
I have written a web based front end for SMTP email program. I have compiled it into a DLL.
Screen Capturing a Form in .NET - Using GDI and GDI+
Sep 15, 2001.
This article shows way to do form capture in GDI is to get the device context to the screen and bit blast it to a Bitmap in memory..
Customizable Generic Form Validation Control
Oct 01, 2001.
This control performs form validations at the client-side irrespective of the web server.
Transactions in ASP.NET
Oct 01, 2001.
This article explain, how to process a transaction within ASP.Net web forms..
Creating your own Web Server using C#
Oct 15, 2001.
This article explains how to write a simple web server application using C#.
Creating your own Web Server using C#
Oct 15, 2001.
This article explains how to write a simple web server application using C#..
Mark Six on the Fly
Dec 04, 2001.
In this sample, I demonstrate how a WebForm can be called directly as an Image..
.
About image-in-Web-page. | http://www.c-sharpcorner.com/tags/image-in-Web-page-with-TypeScript | CC-MAIN-2016-36 | refinedweb | 524 | 68.06 |
Nicola Ken Barozzi wrote:
> Leo Simons wrote:
>
>> Nicola Ken Barozzi wrote:
>
>>> 2 - every project has this URL space where to publish the site:
>>>
>>>
>>
>> +1 (or under the wings of their TLP if they wish)
>
> Actually this is the point. I tend to think that they should publish
> the site here always.
Last time we talked about this, we agreed on some common goals. Those can
be accomplished in various ways. Continuously moving stuff around (like
moving
the lenya website now) just means lots of work no-one likes to do. I
suggest we're
as lenient and forgiving as possible until this becomes an issue.
>> imagine people being
>> smart and using cvs import (just one commit message per import), or
>> mail readers being smart and filtering out these commit messages.
>
> Ok, I see.
>
> I'm a bit ignorant on using imports for this. Could you please explain
> so that we can put this info up on the website?
easy:
cd $proj
maven site
cd target/docs
cvs -z3 -d $my_id@cvs.apache.org:/home/cvs \
import -m 'Maven-generated site' incubator-site/build/site/$proj \
maven_site Maven_Generated_$proj_Website_$(date +%Y%m%d)
replace '$proj' with the project name, replace $my_id with your
apache login id, replace $(date +%Y%m%d) with the current date
if you want. See
for more info. Note: the problem with using import in this way is that
its not easily combined with the use of commit (the above url explains
why).
cheers!
- LSD
---------------------------------------------------------------------
To unsubscribe, e-mail: general-unsubscribe@incubator.apache.org
For additional commands, e-mail: general-help@incubator.apache.org | http://mail-archives.apache.org/mod_mbox/incubator-general/200311.mbox/%3C3FB90233.6090202@apache.org%3E | CC-MAIN-2014-52 | refinedweb | 267 | 64.91 |
On 5/18/17 9:31 AM, Greg KH wrote:> On Fri, May 05, 2017 at 07:20:18PM -0400, Matt Brown wrote:>> This introduces the tiocsti_restrict sysctl, whose default is controlled via>> CONFIG_SECURITY_TIOCSTI_RESTRICT. When activated, this control restricts>> all TIOCSTI ioctl calls from non CAP_SYS_ADMIN users.>>>> This patch depends on patch 1/2>>>> This patch was inspired from GRKERNSEC_HARDEN_TTY.>>>> This patch would have prevented>> under the following>> conditions:>> * non-privileged container>> * container run inside new user namespace>>>>>>.>>>> Acked-by: Serge Hallyn <serge@hallyn.com>>> Reviewed-by: Kees Cook <keescook@chromium.org>>> Signed-off-by: Matt Brown <matt@nmatt.com>>> --->> Documentation/sysctl/kernel.txt | 21 +++++++++++++++++++++>> drivers/tty/tty_io.c | 6 ++++++>> include/linux/tty.h | 2 ++>> kernel/sysctl.c | 12 ++++++++++++>> security/Kconfig | 13 +++++++++++++>> 5 files changed, 54 insertions(+)>>>> diff --git a/Documentation/sysctl/kernel.txt b/Documentation/sysctl/kernel.txt>> index bac23c1..f7985cf 100644>> --- a/Documentation/sysctl/kernel.txt>> +++ b/Documentation/sysctl/kernel.txt>> @@ -89,6 +89,7 @@ show up in /proc/sys/kernel:>> - sysctl_writes_strict>> - tainted>> - threads-max>> +- tiocsti_restrict>> - unknown_nmi_panic>> - watchdog>> - watchdog_thresh>> @@ -987,6 +988,26 @@ available RAM pages threads-max is reduced accordingly.>> >> ==============================================================>> >> +tiocsti_restrict:>> +>> +This toggle indicates whether unprivileged users are prevented>> +from using the TIOCSTI ioctl to inject commands into other processes>> +which share a tty session.>> +>> +When tiocsti_restrict is set to (0) there are no restrictions(accept>> +the default restriction of only being able to injection commands into>> +one's own tty). When tiocsti_restrict is set to (1), users must>> +have CAP_SYS_ADMIN to use the TIOCSTI ioctl.>> +>> +When user namespaces are in use, the check for the capability>> +CAP_SYS_ADMIN is done against the user namespace that originally>> +opened the tty.>> +>> +The kernel config option CONFIG_SECURITY_TIOCSTI_RESTRICT sets the>> +default value of tiocsti_restrict.>> +>> +==============================================================>> +>> unknown_nmi_panic:>> >> The value in this file affects behavior of handling NMI. When the>> diff --git a/drivers/tty/tty_io.c b/drivers/tty/tty_io.c>> index c276814..fe68d14 100644>> --- a/drivers/tty/tty_io.c>> +++ b/drivers/tty/tty_io.c>> @@ -2297,11 +2297,17 @@ && !ns_capable(tty->owner_user_ns,CAP_SYS_ADMIN)) {>> + pr_warn_ratelimited("TIOCSTI ioctl call blocked for non-privileged process\n");>> + return -EPERM;> > Always follow the proper kernel coding style rules, as I don't want to> have someone else have to come along and fix up the error you have added> here :(> > checkpatch.pl is your friend, really...> My bad. Will fix these issues in v7.> And why not do a warning with the device that caused the problem to> happen? dev_warn has a ratelimit I think right? "raw" printk messages> like this don't help in trying to track down what/who caused the issue.> yes <linux/device.h> has dev_warn_ratelimited. I will use that in 7v.> And finally, can userspace see the namespace for the tty? Doesn't> things like checkpoint/restore need that in order to properly set the> tty connection back up when moving processes?This seems like we would need to expose the owner_user_ns of the tty in procfssomewhere. Section 1.7 Documentation/filesystems/proc.txt describes thefollowing files in /proc/tty:Table 1-11: Files in /proc/tty.............................................................................. File Content drivers list of drivers and their usage ldiscs registered line disciplines driver/serial usage statistic and status of single tty lines..............................................................................The drivers file is the one that gives the most information that we areinterested in.However, the current layout combines information about multiple ttys by driver.As I understand it, a single driver may have ttys that span across differentowner_user_ns. would it make sense to add a file /proc/tty/ns that wouldcontain the different tty to user namespace mappings? Or is there a better wayto do this? I would appreciate any feedback/ideas you have on this.> > v7? :)v7 will be on its way soon. I'm not currently sure how to address the concernof giving things like checkpoint/restore in userland a way to get theowner_user_ns.> > thanks,> > greg k-h> Thanks for the feedback,Matt Brown | http://lkml.org/lkml/2017/5/19/19 | CC-MAIN-2017-43 | refinedweb | 645 | 51.14 |
view raw
I want to load pegrp32c.dll for WINXP OS version and pegrp32d.dll for WIN7 version. How I can achieve this?
Also i dont have any idea about the above mention third party dll.
someone please expalain what it is how load difference version of dll to different version of windows
Well, you have to determine current Windows version first using
Version Helper functions. Then load a dll using
LoadLibrary method. Since you have not mentioned Windows Vista, I assume, that Windows XP rules will be applied for it.
#include <versionhelper.h> ///... HMODULE hLib = NULL; if(IsWindows7OrGreater()) { hLib = LoadLibrary(L"pegrp32d.dll"); }else { hLib = LoadLibrary(L"pegrp32c.dll"); } if(!hLib) //report an error
If you want to link statically against this libraries, you have to create different versions of your application for Windows XP and Windows 7. You could use
WINVER macro to determine target platform and
#pragma comment instruction to select lib file to link against.
#if WINVER >= _WIN32_WINNT_WIN7 #pragma comment(lib, "pegrp32d.lib") #else #pragma comment(lib, "pegrp32c.lib") #endif
References:
If you use old version of the Visual Studio you could install latest Platform SDK, or use
GetVersion API call, declared in the
windows.h. Be advised however, that this method could be unavailable since Windows 8.1 so that approach is not recommended. | https://codedump.io/share/8HYNdzBj6SwA/1/pegrp32cdll-and-pegrp32ddll-loading-in-different-types-of-windows | CC-MAIN-2017-22 | refinedweb | 219 | 67.86 |
TDD stands for Test Driven Development. For the purposes of this post, it refers to the practice of first writing a Test, and then finding the simplest way to make it pass. Typically this involves writing some code.
To demonstrate the use of TDD with CodeRush, we’ll have to do some TDD. In this case I’ll lead you through the start of a code kata.
“A code kata is an exercise in programming which helps a programmer hone their skills through practice and repetition” – Wikipedia
The particular kata we’re going to use is the Calculator Kata detailed by Roy Osherove. This Kata is a little involved for the purposes of a single blog post so we’ll concentrate on just the first part of it:
So how do we go from “File | New” to “Test Passes” using CodeRush and TDD?
First Steps:
Once your project references a supported testing framework, CodeRush will see this connection and adjust its help to suit. This means you can use the same techniques shown here, whether you’re using XUnit, MbUnit, NUnit or any other supported framework.
Let’s write a test
The full text of a basic NUnit test is: ------------------------------------------------------------- [TestFixture] public class Tests { [Test] public void Test() { } } ------------------------------------------------------------- There are 73 characters in that text including spaces, tabs and newlines. If you add the shift keys necessary to create those parentheses, square brackets, curly brackets and capital letters, then that’s another 14 characters. A total of 87 characters to write some stub code which, names aside, will never really change.
That seems like a lot of typing. I’m sure we can do better than that...
How about t<space>?
87 keys vs. 2. That’s a 97.7% saving, which is a bargain in anyone’s book.
See how CodeRush provides augmented output from its template. The important parts, the ones you’ll want to adjust, are highlighted. The first of these is also selected, so that you can immediately begin adding the final touches without having to navigate anywhere.
Next name the test itself. Use something simple and to the point.
Note: The naming scheme for tests is sometimes quite hotly debated. You should discuss this with your team and arrive at a scheme that suits as many as possible. The one thing everyone seems to agree on, is that the name of your test should reflect its purpose (as with any other method). It should help someone who has seen the test fail, to understand what exactly has failed.
Note: At this point I haven’t even got a Calculator class
According to the spec, the Calculator class has an Add function whose purpose is to parse a list of numbers and return the sum of their values.
According to our spec, the simplest possible case is where the string to be parsed is an empty string. In this case the function is to return a zero (0).
Therefore I will name my test Add_EmptyString_ReturnsZero(). Many will argue that there are better names out there, but IMHO this specifies exactly what our expectations are of this test.
Now let's write the body of the test.
We want to assert that passing String.Empty to our calculator will cause it to return zero.
The NUnit way of expressing this is by calling Assert.Equals, passing in your expectation and result:
Assert.Equals(0, Calculator.Add(""));
In CodeRush the ae<space> template with create the majority of this leaving you to fill out the expectation and actual parameters.
If, as in this case, you know the expectation is going to be zero, you can reduce the effort a little more through the use of the ae0<space> template.
(Excellent, that’s another 16 characters saved.)
The second parameter of this method call is the value we are testing. In this case it’s a call to the Add method described in the spec.
Once we’ve added this we should have:
This is all very well, but we don't yet have an 'Add' method. Come to think of it, we still don't have a Calculator class.
Ok let's fix that.
CodeRush builds you a new Calculator class complete with Add Method which takes a String and returns a decimal.
Awesome that's 133 characters created with just a couple of clicks.
Note: If you don't want a default constructor, you can remove it very quickly by placing your caret within it, and choosing the 'Remove Redundant Constructor' from the 'Refactor' SmartTag menu
We can quickly fix up our parameter name and then we can run our test.
Test Runner Shortcuts
Some CodeRush Test Runner Shortcuts (defaults):
Ctrl+T, S (Run tests in the current Solution.) Ctrl+T, P (Run tests in the current Project.) Ctrl+T, C (Run tests in the current Class.) Ctrl+T, F (Run tests in the current File.) Ctrl+T, T (Show the Test Runner Tool Window)
Since for the moment our tests and class are in the same file, Ctrl+T, F will suit us because we will be able to run the tests from anywhere in the file.
So let's run our test and see what happens.
Ctrl+T, F
Well the first thing to note is that our test failed.
This is a good thing. No really, it is. If your test doesn’t fail at first, then either your test is bad, or your code already works for the given scenario. In either case you should not mess with your class under test, until you have a better understanding of the situation.
In should be noted that CodeRush has several ways of telling us that our test failed:
Note: By hovering your mouse over the red cross, you can see a popup which containing details of the failure.
Obviously this view is a little sparse at the moment, because we only have 1 test, but you can see how this would be useful for viewing the state of all of your tests at a glance.
Let's fix our calculator so that the test passes.
Place your caret on the call to Calculator.Add and press F12. CodeRush drops a marker in your current location and moves your caret to the declaration of the Add method.
Have the method return 0; and then hit Esc to return to the calling test.
...now run our test again. (Ctrl+T, F)
… and we have a Passing Test! Wonderful!
Note that we have done the bare minimum to get the test to pass. The idea here is to use tests to drive out new functionality. So although this implementation is ultimately flawed, it serves the purpose of the existing test.
Naturally we want to improve this implementation, but before we do this TDD dictates that we should construct an additional test which will specify the behaviour we are after. This test should also be implemented in the simplest way possible.
Through repetition of this procedure, we will drive out a new set of requirements and tests to cover those cases and develop a comprehensive and robust test suite which will give us a great deal of confidence in our code.
Well I think that about wraps it up for an initial view of TDD with CodeRush.
I think you'll agree that we have help in spades during the creation of the tests, the creation of the class under test (and its methods) and of course the running of tests.
This has been a very quick tour from “File | New” to “Test Passes”.
In the future I'll give a more in-depth tour of the Unit testing facilities of CodeRush and perhaps we'll even run through a complete Kata from start to finish. :)
So go forth and Test using CodeRush and let. | https://community.devexpress.com/blogs/rorybecker/archive/2012/03.aspx | CC-MAIN-2017-43 | refinedweb | 1,307 | 80.62 |
JaronShockinglyGreen
Posts10
Joined
Last visited
About Jaron
Jaron's Achievements
Rare
Rare
Rare
Rare
Rare
Recent Badges
2
Reputation
-
GSAP ScrollTrigger
Jaron replied to Jaron's topic in GSAPYeah, you're right, this more of an issue to resolve with CSS as it is something specific to ScrollTrigger, and absolute seems the way to go. Thanks a lot for the help!
GSAP ScrollTrigger
Jaron posted a topic in GSAPLink would be greatly appreciated!
- Thanks Cassie for your CodePen. Its much appreciated. I actually learnt a new thing from your code regarding the 'getProperty' mothod. For reference this is what i had (specific to the question). function bearingDirection(currentBearing, targetBearing) { // Anything negative is anticlockwise, positive is clockwise // see return ((targetBearing - currentBearing + 540) % 360) - 180; } let currentBearing = gsap.getProperty(".circle-bg-svg", "rotation"); // get current rotation of .circle-bg-svg let targetBearing = 250; // Set new rotation (e.g 250) if (this.bearingDirection(currentBearing, targetBearing) > 0) { console.log("Clockwise"); } else { console.log("Anti-clockwise"); }
- Think i figured it out with the help from
- I'm currently setting a rotation value on an element and using the "_short" option - so it'll choose the shortest way to rotate to object . I need to alter some animations based on whether it decided to go clockwise or anti-clockwise but struggling to find the best way of finding this out. Any pointers appeciated?
- So I've been looking into this a little more, and I can't appear to get it to error on CodePen, however what is interesting, is that copying that exact code into my site, with all other JS modules I'm aware of commented out / disabled, still appears to cause the issue. It's clearly something within our site that's potentially getting in the way, but given I've removed all other JS modules I'm not sure what at this point. Another strange finding, is that when not paused() by default, it works fine. But having it paused() and then initiating it on click(), is when the error seems to occur. I'm going to keep digging, but does any of that give you any more ideas? I appreciate it's a tough one given the context! Thanks.
- Hi both, Firstly, thanks for the reply and help, it is very much appreciated. I'll be sure to take a look at the side notes too. In the CodePen itself I have not been able to reproduce thus far, but the code is very similar to what we have in real terms. I know it's not ideal though, not being able to reproduce the bug I'm asking about. Even on my local instance, where I can reproduce the bug, it's not consistent. 90% of the time, it's fine, but then on the rare occasion the toggle function will run twice, and I'm not sure why (I only know it runs twice due to it outputting two console.log() statements) It does seem to happen across Chrome, but when testing in IE11, I seem to be able to replicate the bug more often than in any other browser, which is equally baffling, but then, it is IE. Also, we do have quite a lot of other GSAP bits and pieces going off on the site, so your guess about something else potentially getting in the way might not be a bad one. I've just removed all other JS though and the issue still persists... The weird thing is, is that when I removed all other JS modules from the site, and all other non-related JS, the issue happens consistently and I can reproduce it... I will see if I can update the CodePen to at least try and get something you can reproduce, and I'll comment back here once done 🤞 Thanks again, I really appreciate the help.!
help Tweaking GSAP values for mobile - reverse() works unexpectedly
Jaron replied to Jaron's topic in GSAPHi Zach, Thanks, and thank you very much for the reply. That makes sense. It's always better to know why something is working so appreciate the help in understanding it. Have a good weekend and thanks again for the help.! | https://greensock.com/profile/45345-jaron/ | CC-MAIN-2022-33 | refinedweb | 700 | 61.87 |
The images I've provided you with come from the National Oceanic and Atmospheric Administration (NOAA), which is a US government agency and thus produces public domain content that we can freely reuse. Once they are copied into your project, Xcode will automatically build them into your finished app so that you can access them.
Behind the scenes, an iOS app is actually a directory containing lots of files: the binary itself (that's the compiled version of your code, ready to run), all the media assets your app uses, any visual layout files you have, plus a variety of other things such as metadata and security entitlements.
These app directories are called bundles, and they have the file extension .app. Because our media files are loose inside the folder, we can ask the system to tell us all the files that are in there then pull out the ones we want. You may have noticed that all the images start with the name "nssl" (short for National Severe Storms Laboratory), so our task is simple: list all the files in our app's directory, and pull out the ones that start with "nssl".
For now, we’ll load that list and just print it to Xcode’s built in log viewer, but soon we’ll make them appear in our app.
So, step 1: open ViewController.swift. A view controller is best thought of as being one screen of information, and for us that’s just one big blank screen. ViewController.swift is responsible for showing that blank screen, and right now it won’t contain much code. You should see something like this:
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } }
That contains four interesting things I want to discuss before moving on.
import UIKit, which means “this file will reference the iOS user interface toolkit.”
class ViewController: UIViewControllerline means “I want to create a new screen of data called ViewController, based on UIViewController.” When you see a data type that starts with “UI”, it means it comes from UIKit.
UIViewControlleris Apple’s default screen type, which is empty and white until we change it.
override func viewDidLoad()starts a method. As you know, the
overridekeyword is needed because it means “we want to change Apple’s default behavior from
UIViewController.”
viewDidLoad()is called by UIKit when the screen has loaded, and is ready for you to customize.
viewDidLoad()method contains one line of code saying
super.viewDidLoad()and one line of comment (that’s the line starting with
//). This
supercall means “tell Apple’s
UIViewControllerto run its own code before I run mine,” and you’ll see this used a lot.
We’ll come back to this code a lot in future projects; don’t worry if it’s all a bit hazy right now.
No line numbers? While you’re reading code, it’s frequently helpful to have line numbers enabled so you can refer to specific code more easily. If your Xcode isn't showing line numbers by default, I suggest you turn them on now: go to the Xcode menu and choose Preferences, then choose the Text Editing tab and make sure "Line numbers" is checked.
As I said before, the
viewDidLoad() method is called when the screen has loaded and is ready for you to customize. We're going to put some more code into that method to load the NSSL images. Add this beneath the line that says
super.viewDidLoad():
let fm = FileManager.default let path = Bundle.main.resourcePath! let items = try! fm.contentsOfDirectory(atPath: path) for item in items { if item.hasPrefix("nssl") { // this is a picture to load! } }
Note: Some experienced Swift developers will read that code, see
try!, then write me an angry email. If you’re considering doing just that, please continue reading first.
That’s a big chunk of code, most of which is new. Let’s walk through what it does line by line:
let fm = FileManager.defaultdeclares a constant called
fmand assigns it the value returned by
FileManager.default. This is a data type that lets us work with the filesystem, and in our case we'll be using it to look for files.
let path = Bundle.main.resourcePath!declares a constant called
paththat is set to the resource path of our app's bundle. Remember, a bundle is a directory containing our compiled program and all our assets. So, this line says, "tell me where I can find all those images I added to my app."
let items = try! fm.contentsOfDirectory(atPath: path)declares a third constant called
itemsthat is set to the contents of the directory at a path. Which path? Well, the one that was returned by the line before. As you can see, Apple's long method names really does make their code quite self-descriptive! The
itemsconstant will be an array of strings containing filenames.
for item in items {starts a loop that will execute once for every item we found in the app bundle. Remember: the line has an opening brace at the end, signaling the start of a new block of code, and there's a matching closing brace four lines beneath. Everything inside those braces will be executed each time the loop goes around.
if item.hasPrefix("nssl") {is the first line inside our loop. By this point, we'll have the first filename ready to work with, and it'll be called
item. To decide whether it's one we care about or not, we use the
hasPrefix()method: it takes one parameter (the prefix to search for) and returns either true or false. That "if" at the start means this line is a conditional statement: if the item has the prefix "nssl", then… that's right, another opening brace to mark another new code block. This time, the code will be executed only if
hasPrefix()returned true.
// this is a picture to load!is a comment – if we reach here,
itemcontains the name of a picture to load from our bundle, so we need to store it somewhere.
In this instance it’s perfectly fine to use
Bundle.main.resourcePath! and
try!, because if this code fails it means our app can't read its own data so something must be seriously wrong. Some Swift developers attempt to write code to handle these catastrophic errors at runtime, but sadly all too often they just mask the actual problem that occurred.
Right now our code loads the list of files that are inside our app bundle, then loops over them all to find the ones with a name that begins with “nssl”. However, it doesn’t actually do anything with those files, so our next step is to create an array of all the “nssl” pictures so we can refer to them later rather than having to re-read the resources directory again and again.
The three constants we already created –
fm,
path, and
items – live inside the
viewDidLoad() method, and will be destroyed as soon as that method finishes. What we want is a way to attach data to the whole
ViewController type so that it will exist for as long as our screen exists. So, this a perfect example of when to use a property – we can give our
ViewController class as many of these properties as we want, then read and write them as often as needed while the screen exists.
To create a property, you need to declare it outside of methods. We’ve been creating constants using
let so far, but this array is going to be changed inside our loop so we need to make it variable. We also need to tell Swift exactly what kind of data it will hold – in our case that’s an array of strings, where each item will be the name of an “nssl” picture.
Add this line of code before
viewDidLoad():
var pictures = [String]()
If you’ve placed it correctly, your code should look like this:
class ViewController: UIViewController { var pictures = [String]() override func viewDidLoad() { super.viewDidLoad() let fm = FileManager.default
That
pictures array will be created when the
ViewController screen is created, and exist for as long as the screen exists. It will be empty, because we haven’t actually filled it with anything, but at least it’s there ready for us to fill.
What we really want is to add to the
pictures array all the files we match inside our loop. To do that, we need to replace the existing
// this is a picture to load! comment with code to add each picture to the
pictures array.
Helpfully, Swift’s arrays have a built-in method called
append that we can use to add any items we want. So, replace the
// this is a picture to load! comment with this:
pictures.append(item)
That’s it! Annoyingly, after all that work our app won’t appear to do anything when you press play – you’ll see the same white screen as before. Did it work, or did things just silently fail?
To find out, add this line of code at the end of
viewDidLoad(), just before the closing brace:
print(pictures)
That tells Swift to print the contents of
pictures to the Xcode debug console. When you run the program now, you should see this text appear at the bottom of your Xcode window: “["nssl0033.jpg", "nssl0034.jpg", "nssl0041.jpg", "nssl0042.jpg", "nssl0043.jpg", "nssl0045.jpg", "nssl0046.jpg", "nssl0049.jpg", "nssl0051.jpg", "nssl0091.jpg”]”
Note: iOS likes to print lots of uninteresting debug messages in the Xcode debug console. Don’t fret if you see lots of other text in there that you don’t recognize – just scroll around until you see the text above, and if you see that then you’re good. | https://www.hackingwithswift.com/read/1/2/listing-images-with-filemanager | CC-MAIN-2021-43 | refinedweb | 1,649 | 70.63 |
Dear Forms Experts,
I have a question regarding smartforms.
There's a text node under one window in my smartform and it has the summary details as below with some ABAP code.
* Net Total : &WF_NET_PRICE_TOTAL&
/: if &WF_SURDIS& is not initial.
* Discount/Surcharges Totals : &WF_SURDIS&
/: endif.
* Functional Compensation : &WF_FUNCTIONAL_COMPENSATION&
* Handling Charges : &WF_HANDLING_CHARGES&
/: IF &WF_FREIGHT_TOTAL& IS NOT INITIAAL.
* Freight Charges : &WF_FREIGHT_TOTAL&
/: ENDIF.
* VAT : &WF_TOTAL_VAT_AMOUNT&
* Gross Total : &WF_FIN_TOT_AMOUNT&
My problem is the ABAP code if and endif are not executed at all instead its printing everything. My requirement is certain fields should be printed only when they are not initial.
I tried this in SAP Script before inside the text elements, it did work there but not working in smartforms.
Please provide me some clue why the ABAP code did not get executed in smartform text nodes.
Thanks,
Rajesh.
its not possible to do that in smartforms..
you need to split the whole content into single text and use the condition tab of the text..
You already have an active moderator alert for this content.
Add comment | https://answers.sap.com/questions/6659154/index.html | CC-MAIN-2019-18 | refinedweb | 174 | 66.54 |
What is used to represent Strings in Python.Is double quotes used for String representation or single quotes used for String representation in Python?
dhanya kumar
- Jan 12th, 2015
Most preferable way by PEP 8 is in double quotes
Agrim Sharma
- Dec 11th, 2014
Hi,
We can use both of them for string. But the best way is to use double quotes as we can input " s " of any character.
What is the method does join() in python belong to?
bibin
- Dec 23rd, 2014
Join used on string, list containing string items and tuple containing string items.
x.join(123) -> 1x2x3
x.join([12, 3]) -> 12x3, note if any of the item in the list is not a string, it throws an error
Saumya Saxena Gupta
- Jun 20th, 2014
Used for joining strng operations
What is the statement that can be used in Python if a statement is required syntactically but the program requires no action?
Sreekrishnan r
- Jun 25th, 2014
Pass
Saumya Saxena Gupta
- Jun 20th, 2014
Pass
How is memory managed in Python?
jayavanth
- Apr 29th, 2013
Like other programming language python also has garbage collector which will take care of memory management in python.
parthvora18
- Jun 3rd, 2008
Memory is managed through private heaps. Private heap is managed by python memory manager.
What is the built-in function used in Python to iterate over a sequence of numbers?
addy
- Oct 15th, 2012
Yup, I think youre right. enumerate will iterate over a list, and that list could have numbers in it e.g.:
>>> [ (i,j) for i,j in enumerate([9,10,11,12])]
[(0, 9), (1, 10), (2, 11), (3, 12)]
Nagappan
- Nov 13th, 2007
Range is the built-in function to be used for interating the sequence of numbers.for iter in range (0, 10): print iter # prints 0 to 9for iter in range (0, 10, 2): # The last argument is the sequence to use. Default is 1. print iter # prints 0, 2, 4, 6, 8
Python Popularity
Why Python is not that much of popular, when compared to other programming languages?
suji
- Mar 2nd, 2012
Python is not so useful in web environment where the user interface is the browser. Hence, lot of people are using PHP for different design goals. Google is tightly connected with python as they make ...
Phyton Advantages and Dis-Advantages
What are the advantage and dis-advantage of Phyton programming language?
suji
- Mar 2nd, 2012
Python is more like java and bit cumbersome, but it leads to a better design. Python is an interpreted language, high level programming, pure object-oriented, high performance server side scripting la...
Does python support switch or case statement in Python?If not what is the reason for the same?
Geek4Geek
- Jun 13th, 2011
No. Python does not have any switch or case statement. But it provides other ways of achieving multiway branching such as if-elif statements and dictionaries. Example 1: (Using if-elif-else)if x ...
Matt Brown
- Jun 9th, 2011
You can use a dictionary to simulate the switch statement.def doSomething(): print "doSomething() called"def doSomethingElse(): print "doSomethingEls...
Why can't lambda forms in Python contain statements?
muralic
- Feb 22nd, 2010
They are syntactically restricted to a single expression.
santosh malvi
- Apr 9th, 2007
A lambda statement is used to create new function objects and then return them at runtime thats why lambda forms in Python didn't contain statement.
How is the Implementation of Python's dictionaries done?
tomanihskb
- Feb 10th, 2009
A hash value of the key is computed using a hash function, The hash value addresses a location in an array of "buckets" or "collision lists" which contains the (key , value) pa...
dilbert_here00
- Dec 3rd, 2007
Using curly brackets -> {}eg: {'a':'123', 'b':'456'}
What is the optional statement used in a try ... except statement in Python?
Priya Patel
- Oct 20th, 2007
There are 2 optional clauses used in try...except statements: 1. else clause: It is useful for code that must be executed when the try block doesn't create any exception2. finally clause:Its is useful for code that must be executed irrespective of whether an exception is generated or not.
xeio
- Sep 25th, 2007
Try ... except (...) ... [finally]
What is List Comprehensions feature of Python used for?
Priya Patel
- Oct 19th, 2007
List comprehensions help to create and manage lists in a simpler and
clearer way than using map(), filter() and lambda. Each list comprehension
consists of an expression followed by a for clause, then zero or more for or
if clauses.
What is __slots__ and when is it useful?
Normally, all class objects have an __dict__ which allows new attributes to be bound to a class instance at runtime. When a class is defined with __slots__, only attributes whose names are present in the __slots__ sequence are allowed. This results in instances of this class not having an __dict__ attribute and not being able to bind new attributes at run time.__slots__ is useful because it eliminates...
What are all the operating system that Python can run on?
varsha5in
- Oct 2nd, 2007
Python can run of every operating system like UNIX/LINUX, Mac, Windows and others.
What are the disadvantages of the Python programming language?
sripri
- Apr 9th, 2007
One of the disadvantage of the Python programming language is it is not suited for fast and memory intensive tasks.
Why isn't all memory freed when Python exits?
stranger1
- Sep 28th, 2007
Objects referenced from the global namespaces of Python modules are not always deallocated when Python exits. This may happen if there are circular references. There are also certain bits of memory ...
Does Python support strongly for regular expressions? What are the other languages that support strongly for regular expressions?
stranger1
- Sep 28th, 2007
Yes python strongly support regular expression. Other languages supporting regular expressions are: Delphi, Java, Java script, .NET, Perl, Php, Posix, python, Ruby, Tcl, Visual Basic, XML schema, VB script, Visual Basic 6.
Why was the language called as Python?
stranger1
- Sep 28th, 2007
At the same time he began implementing Python, Guido van Rossum was also reading the published scripts from "Monty Python's Flying Circus" (a BBC comedy series from the seventies, in the...
Does Python support Multiple Inheritance?
What is the Java implementation of Python popularly known as?
Python Interview Questions
Ans | http://www.geekinterview.com/Interview-Questions/Programming/Python | CC-MAIN-2015-06 | refinedweb | 1,055 | 65.42 |
Stores meta-information about Object instances. More...
#include <mitsuba/mitsuba.h>
Stores meta-information about Object instances.
This class provides a thin layer of RTTI (run-time type information), which is useful for doing things like:
Construct a new class descriptor.
This method should never be called manually. Instead, use one of the MTS_IMPLEMENT_CLASS, MTS_IMPLEMENT_CLASS_S, MTS_IMPLEMENT_CLASS_I or MTS_IMPLEMENT_CLASS_IS macros to automatically do this for you.
Check whether this class derives from theClass.
Look up a class by its name.
Look up a class by its name. Avoids allocating heap space by taking a character array as parameter.
Return the name of the represented class.
Generate an instance of this class (if this is supported)
Does the class support instantiation over RTTI?
Does the class support serialization?
Check if the RTTI layer has been initialized.
Initializes the built-in RTTI and creates a list of all compiled classes.
Free the memory taken by staticInitialization()
Unserialize an instance of the class (if this is supported). | http://mitsuba-renderer.org/api/class_class.html | CC-MAIN-2019-26 | refinedweb | 163 | 52.36 |
Navigation menu
A portable, open-source, coherent noise-generating library for C++
In this tutorial, you'll write a terrain height map to a
Terragen terrain file (*.ter) and use Terragen
to create a 3D rendering from it. You'll create this height map using the
same group of
noise modules you
created in the previous tutorial.
Note: Because Terragen is an application that's currently
only available for the Windows and MacOS operating systems, this tutorial
won't be useful to you if you're running a flavor of UNIX. In this case,
you should proceed to the next tutorial.
Note: You don't need any Terragen experience for this
tutorial.
Terragen is an
application that produces very realistic renderings of terrain height
maps. It can apply procedural textures with near-infinite detail to the
terrain. One of its most impressive features is its atmospheric
lighting model, which is capable of generating sunbeams through clouds,
among other things.
Terragen is also relatively inexpensive for a terrain rendering application,
A reduced-functionality
free (as in
beer) version is also available. For this tutorial, you can use either
the freeware version or the full version.
Before moving to the next step of this tutorial, install Terragen first.
The current version as of this writing is 0.9.19. This
tutorial assumes that you've downloaded and installed that version.
In preparation for this tutorial, open the source file you created in
the previous tutorial. The code in that file
should look like this:
#include <noise/noise.h>
#include "noiseutils.h"
using namespace noise;
int main (int argc, char** argv)
{
module::RidgedMulti mountainTerrain;
module::Billow baseFlatTerrain;
baseFlatTerrain.SetFrequency (2.0);
module::ScaleBias flatTerrain;
flatTerrain.SetSourceModule (0, baseFlatTerrain);
flatTerrain.SetScale (0.125);
flatTerrain.SetBias (-0.75);
module::Perlin terrainType;
terrainType.SetFrequency (0.5);
terrainType.SetPersistence (0.25);
module::Select terrainSelector;
terrainSelector.SetSourceModule (0, flatTerrain);
terrainSelector.SetSourceModule (1, mountainTerrain);
terrainSelector.SetControlModule (terrainType);
terrainSelector.SetBounds (0.0, 1000.0);
terrainSelector.SetEdgeFalloff (0.125);
module::Turbulence finalTerrain;
finalTerrain.SetSourceModule (0, terrainSelector);
finalTerrain.SetFrequency (4.0);
finalTerrain.SetPower (0.125);
utils::NoiseMap heightMap;
utils::NoiseMapBuilderPlane heightMapBuilder;
heightMapBuilder.SetSourceModule (finalTerrain);
heightMapBuilder.SetDestNoiseMap (heightMap);
heightMapBuilder.SetDestSize (256, 256);
heightMapBuilder.SetBounds (6.0, 10.0, 1.0, 5.0);
heightMapBuilder.Build (); ();
return 0;
}
Since you're creating a Terragen terrain file instead of a Windows bitmap
file, remove the following highlighted code: ();
There's one problem with this source file: the terrain height map it
generates has elevations that range from -1 to +1, while the Terragen
writer class assumes that all elevation values are measured in
meters. If you don't make any changes to this height map, the
resulting Terragen terrain file will be very flat. Therefore, you'll add
another scale/bias
noise module to scale the
output values so that they are measured in meters.
You'll insert the new scale/bias
noise module between
the terrainSelector and the
finalTerrain noise modules as shown in the
following diagram:
To insert this new
noise module, add the
following highlighted code:
terrainSelector.SetEdgeFalloff (0.125);
module::ScaleBias terrainScaler;
terrainScaler.SetSourceModule (0, terrainSelector);
module::Turbulence finalTerrain;
finalTerrain.SetSourceModule (0, terrainSelector);
Now it's time to scale the output from the
terrainSelector
noise module by a factor
of 375. This will cause its output to range from
(-1 * 375) to (+1 * 375), or in other
words, -375 to 375. Add the following highlighted code:
module::ScaleBias terrainScaler;
terrainScaler.SetSourceModule (0, terrainSelector);
terrainScaler.SetScale (375.0);
Next, you'll apply a bias of +375 to the output from the
terrainSelector
noise module. This
will cause its output to range from (-375 + 375) to
(+375 + 375), or in other words, 0 to 750. You'll apply
this bias so that most of the elevations in the resulting terrain height
map are above sea level. Add the following highlighted code:
module::ScaleBias terrainScaler;
terrainScaler.SetSourceModule (0, terrainSelector);
terrainScaler.SetScale (375.0);
terrainScaler.SetBias (375.0);
In a scale/bias
noise module, the scaling
factor is always applied before the bias.
At this stage, the output of the
terrainSelector
noise module will
produce a terrain height map with elevations ranging from 0 to 750 meters
above sea level.
Now, you'll need to attach the
terrainScaler
noise module to the
finalTerrain noise module. Modify the following
highlighted code:
module::Turbulence finalTerrain;
finalTerrain.SetSourceModule (0, terrainScaler);
finalTerrain.SetFrequency (4.0);
finalTerrain.SetPower (0.125);
The noise modules are
now properly combined.
You'll also set the size of the terrain height map to 513 x 513, which is
the maximum terrain size that is supported by the freeware version of
Terragen. Modify the following highlighted code:
heightMapBuilder.SetSourceModule (finalTerrain);
heightMapBuilder.SetDestNoiseMap (heightMap);
heightMapBuilder.SetDestSize (513, 513);
heightMapBuilder.SetBounds (6.0, 10.0, 1.0, 5.0);
heightMapBuilder.Build ();
You'll now add some code that will write the resulting terrain height map
to a Terragen terrain file. Add the following highlighted code:
heightMapBuilder.Build ();
utils::WriterTER writer;
writer.SetSourceNoiseMap (heightMap);
writer.SetDestFilename ("terrain.ter");
writer.SetMetersPerPoint (15);
writer.WriteDestFile ();
return 0;
Note that you're calling the SetMetersPerPoint()
method. This method sets the spatial resolution — the distance
between adjacent elevation points — of the Terragen terrain file.
You've set the spatial resolution to 15 meters, so that the elevation
points are 15 meters apart.
You're now ready to create the Terragen terrain file. Compile and run
the program. Once it exits, you should see the
terrain.ter file in the current directory. In
the next section of this tutorial, you'll open this file in Terragen.
Now it's time to open your terrain height map in Terragen. When this
tutorial was written, the current version of Terragen was 0.9.19. This
section assumes you have version 0.9.19 installed, but other versions of
Terragen should work OK.
First, run the Terragen application. Depending on your operating system
and Terragen version, the Terragen main window should look like this:
Terragen has several windows within the main window. The
Rendering Control window shows the render
preview and also allows you to set the exact camera coordinates. The
Landscape window allows you to create a
Terragen terrain and create a surface map for it.
In the Landscape window, look for the
Terrain - [New] frame. In that frame, click
the Open... button. The
Terrain File dialog box appears:
Go to the directory containing your source file and look for the
terrain.ter file. Open this file. When you
open it, Terragen displays a top-down view of your terrain height map in
the Landscape window:
In the top-down view, black represents low elevations and white
represents high elevations.
If you were to now render this terrain height map, the surface of the
terrain would be colored in a single shade of gray. That doesn't sound
very interesting so you'll add some color to the terrain.
Terragen uses surface maps to specify the properties of the
terrain's procedural textures such as color and roughness. Terragen
comes with a few surface maps in the default installation. For this
tutorial, you'll use the "grass & snow" surface map.
In the Landscape window, look for the
Surface Map frame. In that frame, click the
Open... button. The
Surface Map File dialog appears:
Terragen stores these surface maps in the same directory as the Terragen
installation. On a Windows-based PC, the default installation directory is
c:\Program Files\Terragen. Go to the
directory where Terragen is installed, then select the
GrassAndSnow2.srf file and open it. In the
Surface Map frame within the
Landscape window, you'll see the contents
of the opened surface map:
If you examine the surface map, you'll see that it consists of rock,
grass, and snow textures. Elements that are lower in the surface map
list cover up the higher elements, so in this case, snow covers grass.
If you now render the terrain height map, the terrain will almost be
completely covered in snow. Because of this, you'll need to modify this
surface map so that the snow only appears at higher elevations.
In the Landscape window, look for the
Surface Map frame. In that frame,
double-click on the Snow element. This will open the
Surface Layer dialog:
The square section on the left side is a preview window that
shows the part of the terrain that is covered by the snow layer. As you
can see, nearly all the terrain is covered in snow. To reduce the snow
cover, you'll need to modify its advanced properties. Click on the
Advanced Distribution tab. You'll now see
a large number of controls that are used to define the areas of snow on
the terrain:
When you examine these controls, you'll note that the snow appears at a
minimum altitude of 450 meters below sea level. Since most of the
terrain is above sea level, you'll need to modify this value. Change
this value to 250 meters above sea level and click elsewhere in this
dialog box. When you look in the preview window, you'll note that the
snow has largely disappeared and now only appears in the mountains. The
surface map is now ready, so close the dialog box.
Now, you'll place the camera. In the
Landscape window, click on the top-down view
of the terrain height map. This will open the
Landscape View/Sclupt window, which contains
a much larger view of the height map:
To set up the camera, click the left mouse button at the position you
want to place the camera.
The camera looks at a position called a target. To set up the
target, click the right mouse button at the position you want to place the
target.
When I generated the images at the end of this tutorial, I placed the
camera in the valley on the right side and placed the target on the left
side.
Because Terragen takes forever and a day to render images, you should
render a quick preview first. In the
Rendering Control window, click on the
Render Preview button. Terragen creates a
small rendering in the top-left corner of the window:
If you're OK with the preview, it's time to render the real thing.
Click on the Render Image button. After
several seconds or a few minutes, the rendering should be complete:
Click on the image for a larger version:
You've now made a 3D rendering of your terrain height map!
Unfortunately, it's a little blocky. To increase the detail, you'll need
to move the Detail slider all the way to the
right. Once you do that, render the image again.
It'll be some time before the rendering is finished. Depending on your
computer, it should take anywhere from 30 seconds to 20 minutes. Time
to get a beer from the fridge. Once it is done, take a look:
You'll notice some nice details on the ground and cliffs. The clouds
also look realistic as well. Not bad for your first rendering.
In this tutorial, you've used the noiseutils library to create a Terragen
terrain file from your terrain height map. In Terragen, you've opened a
surface map containing grass and snow, modified it so that snow only
appears in the mountainous areas, and then made some renderings of the
height map.
For some more examples of libnoise-generated terrains rendered with
Terragen, take a look at the
complex planetary surface
example.
Play around with Terragen for awhile and see what kinds of renderings you
can create. Load one of the surface maps, or better yet, create your own.
If you want to do some more advanced Terragen tutorials, take a look at
TerraSource.
© 2003-2005 Jason Bevins | http://libnoise.sourceforge.net/tutorials/tutorial7.html | CC-MAIN-2016-07 | refinedweb | 1,960 | 57.98 |
Tutorial
How To Use the Python Filter Function
Introduction.
The basic syntax for the
filter() function is:
filter(function, iterable)
This will return a filter object, which is an iterable. We can use a function like
list() to make a list of all the items returned in a filter object.
The
filter() function provides a way of filtering values that can often be more efficient than a list comprehension, especially when we’re starting to work with larger data sets. For example, a list comprehension will make a new list, which will increase the run time for that processing. This means that after our list comprehension has completed its expression, we’ll have two lists in memory. However,
filter() will make a simple object that holds a reference to the original list, the provided function, and an index of where to go in the original list, which will take up less memory.
In this tutorial, we’ll review four different ways of using
filter(): with two different iterable structures, with a
lambda function, and with no defined function.
Using
filter() with a Function
The first argument to
filter() is a function, which we use to decide whether to include or filter out each item. The function is called once for every item in the iterable passed as the second argument and each time it returns
False, the value is dropped. As this argument is a function, we can either pass a normal function or we can make use of
lambda functions, particularly when the expression is less complex.
Following is the syntax of a
lambda with
filter():
filter(lambda item: item[] expression, iterable)
With a list, like the following, we can incorporate a
lambda function with an expression against which we want to evaluate each item from the list:
creature_names = ['Sammy', 'Ashley', 'Jo', 'Olly', 'Jackie', 'Charlie']
To filter this list to find the names of our aquarium creatures that start with a vowel, we can run the following
lambda function:
print(list(filter(lambda x: x[0].lower() in 'aeiou', creature_names)))
Here we declare an item in our list as
x. Then we set our expression to access the first character of each string (or character “zero”), so
x[0]. Lowering the case of each of the names ensures this will match letters to the string in our expression,
'aeiou'.
Finally we pass the iterable
creature_names. Like in the previous section we apply
list() to the result in order to create a list from the iterator
filter() returns.
The output will be the following:
Output['Ashley', 'Olly']
This same result can be achieved using a function we define:
creature_names = ['Sammy', 'Ashley', 'Jo', 'Olly', 'Jackie', 'Charlie'] def names_vowels(x): return x[0].lower() in 'aeiou' filtered_names = filter(names_vowels, creature_names) print(list(filtered_names))
Our function
names_vowels defines the expression that we will implement to filter
creature_names.
Again, the output would be as follows:
Output['Ashley', 'Olly']
Overall,
lambda functions achieve the same result with
filter() as when we use a regular function. The necessity to define a regular function grows as the complexity of expressions for filtering our data increases, which is likely to promote better readability in our code.
Using
None with
filter()
We can pass
None as the first argument to
filter() to have the returned iterator filter out any value that Python considers “falsy”. Generally, Python considers anything with a length of
0 (such as an empty list or empty string) or numerically equivalent to
0 as false, thus the use of the term “falsy.”
In the following case we want to filter our list to only show the tank numbers at our aquarium:
aquarium_tanks = [11, False, 18, 21, "", 12, 34, 0, [], {}]
In this code we have a list containing integers, empty sequences, and a boolean value.
filtered_tanks = filter(None, aquarium_tanks)
We use the
filter() function with
None and pass in the
aquarium_tanks list as our iterable. Since we have passed
None as the first argument, we will check if the items in our list are considered false.
print(list(filtered_tanks))
Then we wrap
filtered_tanks in a
list() function so that it returns a list for
filtered_tanks when we print.
Here the output shows only the integers. All the items that evaluated to
False, that are equivalent to
0 in length, were removed by
filter():
Output[11, 25, 18, 21, 12, 34]
Note: If we don’t use
list() and print
filtered_tanks we would receive a filter object something like this:
<filter object at 0x7fafd5903240>. The filter object is an iterable, so we could loop over it with
for or we can use
list() to turn it into a list, which we’re doing here because it’s a good way to review the results.
With
None we have used
filter() to quickly remove items from our list that were considered false.
Using
filter() with a List of Dictionaries
When we have a more complex data structure, we can still use
filter() to evaluate each of the items. For example, if we have a list of dictionaries, not only do we want to iterate over each item in the list — one of the dictionaries — but we may also want to iterate over each key:value pair in a dictionary in order to evaluate all the data.
As an example, let’s say we have a list of each creature in our aquarium along with different details about each of them:
aquarium_creatures = [ {"name": "sammy", "species": "shark", "tank number": "11", "type": "fish"}, {"name": "ashley", "species": "crab", "tank number": "25", "type": "shellfish"}, {"name": "jo", "species": "guppy", "tank number": "18", "type": "fish"}, {"name": "jackie", "species": "lobster", "tank number": "21", "type": "shellfish"}, {"name": "charlie", "species": "clownfish", "tank number": "12", "type": "fish"}, {"name": "olly", "species": "green turtle", "tank number": "34", "type": "turtle"} ]
We want to filter this data by a search string we give to the function. To have
filter() access each dictionary and each item in the dictionaries, we construct a nested function, like the following:
def filter_set(aquarium_creatures, search_string): def iterator_func(x): for v in x.values(): if search_string in v: return True return False return filter(iterator_func, aquarium_creatures)
We define a
filter_set() function that takes
aquarium_creatures and
search_string as parameters. In
filter_set() we pass our
iterator_func() as the function to
filter(). The
filter_set() function will return the iterator resulting from
filter().
The
iterator_func() takes
x as an argument, which represents an item in our list (that is, a single dictionary).
Next the
for loop accesses the values in each key:value pair in our dictionaries and then uses a conditional statement to check whether the
search_string is in
v, representing a value.
Like in our previous examples, if the expression evaluates to
True the function adds the item to the filter object. This will return once the
filter_set() function has completed. We position
return False outside of our loop so that it checks every item in each dictionary, instead of returning after checking the first dictionary alone.
We call
filter_set() with our list of dictionaries and the search string we want to find matches for:
filtered_records = filter_set(aquarium_creatures, "2")
Once the function completes we have our filter object stored in the
filtered_records variable, which we turn into a list and print:
print(list(filtered_records))
We’ll receive the following output from this program:
Output[{'name': 'ashley', 'species': 'crab', 'tank number': '25', 'type': 'shellfish'}, {'name': 'jackie', 'species': 'lobster', 'tank number': '21', 'type': 'shellfish'}, {'name': 'charlie', 'species': 'clownfish', 'tank number': '12', 'type': 'fish'}]
We’ve filtered the list of dictionaries with the search string
2. We can see that the three dictionaries that included a tank number with
2 have been returned. Using our own nested function allowed us to access every item and efficiently check each against the search string.
Conclusion
In this tutorial, we’ve learned the different ways of using the
filter() function in Python. Now you can use
filter() with your own function, a
lambda function, or with
None to filter for items in varying complexities of data structures.
Although in this tutorial we printed the results from
filter() immediately in list format, it is likely in our programs we would use the returned
filter() object and further manipulate the data.
If you would like to learn more Python, check out our How To Code in Python 3 series and our Python topic page. | https://www.digitalocean.com/community/tutorials/how-to-use-the-python-filter-function | CC-MAIN-2020-40 | refinedweb | 1,384 | 52.63 |
#include ) is advanced by the number of bytes successfully read. If an error occurs, the resulting value of the file-position indicator for the stream is unspecified. If a partial element is read, its value is unspecified.
The fread() function may mark the st_atime field of the file associated with stream for update. The st_atime field will be marked for update by the first successful execution of fgetc(3C), fgets(3C), fgetwc(3C), fgetws(3C), fread(), fscanf(3C), getc(3C), getchar(3C), getdelim(3C), getline(3C), gets(3C), or scanf(3C) using stream that returns data not supplied by a prior call to ungetc(3C) or ungetwc(3C).
Upon successful completion, fread() returns the number of elements successfully read, which is less than nitems only if a read error or end-of-file is encountered. If size or nitems is 0, fread() returns 0 and the contents of the array and the state of the stream remain unchanged. Otherwise, if a read error occurs, the error indicator for the stream is set and errno is set to indicate the error.
The following example reads a single element from the fp stream into the array pointed to by buf.
#include <stdio.h> ... size_t bytes_read; char buf[100]; FILE *fp; ... bytes_read = fread(buf, sizeof(buf), 1, fp); ...
The ferror() or feof() functions must be used to distinguish between an error condition and), getdelim(3C), getline(3C), gets(3C), printf(3C), putc(3C), puts(3C), attributes(5), standards(5) | https://docs.oracle.com/cd/E36784_01/html/E36874/fread-3c.html | CC-MAIN-2018-09 | refinedweb | 246 | 53 |
In C++ in Plain English, Second Edition (1999), there's a section in the book that says an "=" can be used to do initialization while calling the right constructor. Like given a class
CStr
CStr(char*)
Similarly, the final declaration calls the constructor CStr(char*):
CStr name3 = "Jane Doe";
std::string
using namespace std;
class CStr {
private:
string name;
public:
CStr(string s): name(s) {}
};
int main() {
CStr name3 = "Jane Doe";
}
"conversion from 'const char [9]' to non-scalar type 'CStr' requested".
string nameTest{"Jane Doe"};
Your book is old, but basically right[1]. Note that
"Jane Doe" is not
std::string, it's
const char[9] (and could decay to
const char*). So for
CStr name3 = "Jane Doe";, two user-defined conversion is needed, (i.e.
const char* ->
std::string and
std::string ->
CStr), which is not allowed in one implicit conversion.
This also demonstrates that if
CStr's construct takes
const char* as its parameter,
CStr name3 = "Jane Doe"; would work fine, because only one user-defined conversion is needed for it.
You could reduce one by adding explicit conversion:
CStr name3 = std::string("Jane Doe");
or use string literal (since C++14) directly, which is of type
std::string:
CStr name3 = "Jane Doe"s;
Why didn't initializing CStr::name to a string s = "Jane Doe" work? An string test like
string nameTest{"Jane Doe"};worked, so I thought this would work too.
Your question is not clear enough, anyway,
std::string nameTest{"Jane Doe"}; works because, (depends on your misunderstandings,) (1) only one implicit conversion (
const char* ->
std::string is needed here; (2)
string nameTest{"Jane Doe"}; is direct initialization.
As @LightnessRacesinOrbit commented, direct initialization (i.e.
CStr name3("Jane Doe") or
CStr name3{"Jane Doe"} (since C++11) ) would work fine, while
CStr name3 = "Jane Doe"; is copy initialization, they're different at some points:
It means, for a copy initialization, the argument
Jane Doe, which is a
const char*, has to be converted to
CStr directly; because two user-defined conversion is needed the code is rejected. For a direct initialization, it's fine to convert
Jane Doe (
const char*) to the argument of
CStr's constructor, i.e.
std::string firstly, then
CStr::CStr(std::string) will be invoked to construct the object.
[1]
"Jane Doe" is a c-style string literal which is const, from C++11 it's illegal to assign it to
char*, e.g.
char * pc = "Jane Doe"; // illegal const char * pcc = "Jane Doe"; // fine | https://codedump.io/share/OIlSbauHe8Qh/1/why-does-this-c-member-initializer-list-not-work | CC-MAIN-2017-26 | refinedweb | 416 | 56.59 |
When creating a script, you are essentially creating your own new type of component that can be attached to Game Objects just like any other component.
Just like other Components often have properties that are editable in the inspector, you can allow values in your script to be edited from the InspectorA Unity window that displays information about the currently selected GameObject, Asset or Project Settings, alowing you to inspect and edit the values. More info
See in Glossary too.
using UnityEngine; using System.Collections; public class MainPlayer : MonoBehaviour { public string myName; // Use this for initialization void Start () { Debug.Log("I am alive and my name is " + myName); } }
This code creates an editable field in the Inspector labelled “My Name”.
Unity creates the Inspector label by introducing a space wherever a capital letter occurs in the variable name. However, this is purely for display purposes and you should always use the variable name within your code. If you edit the name and then press Play, you will see that the message includes the text you entered.
In C#, you must declare a variable as public to see it in the Inspector.
Unity will actually let you change the value of a script’s variables while the game is running. This is very useful for seeing the effects of changes directly without having to stop and restart. When gameplay ends, the values of the variables will be reset to whatever they were before you pressed Play. This ensures that you are free to tweak your object’s settings without fear of doing any permanent damage.
Did you find this page useful? Please give it a rating: | https://docs.unity3d.com/Manual/VariablesAndTheInspector.html | CC-MAIN-2019-30 | refinedweb | 275 | 62.78 |
0
#include <iostream> using namespace std; template <typename T> T total(T numValues) { } int main() { cin.ignore(); cin.get(); return 0; }
Write a template for a function called total. The function should keep a running total of values entered by the user, then return the total. The argument sent into the function shuold be the number of values the function is to read. Test the template in a simple driver program.
This problem is easy enough to set up(like I did up top), but I dont exactly get what the function is supposed to do. Do I need to pass it an array or vector that is filled by a user in main using a loop? Then add the elements? How do you guys decipher this text =(
Thanks
Edited by clutchkiller: n/a | https://www.daniweb.com/programming/software-development/threads/266433/template-function-help | CC-MAIN-2017-51 | refinedweb | 134 | 73.88 |
Before teaching today I wrote a silly program to make sure that the bitwise complement of any 32-bit value is equal to one less than the two’s complement negation of that value:
#include <stdio.h> #include <limits.h> #include <assert.h> void foo (unsigned x) { unsigned x1 = ~x; unsigned x2 = -x - 1; assert (x1 == x2); } int main (void) { unsigned x = 0; long checked = 0; while (1) { foo (x); checked++; if (x==UINT_MAX) break; x++; } printf ("checked %ld values\n", checked); return 0; }
When the program terminated without any perceptible delay, I figured there was a bug, but nope: the code is good. It turns out that both GCC and Clang optimize the program into effectively this:
int main (void) { printf ("checked 4294967296 values\n"); return 0; }
The surprise (for me) was that at -O1 — which traditionally does not enable interprocedural optimizations or aggressive loop transformations — both compilers looked inside the function foo() closely enough to figure out that it is a nop, and also that both compilers were able to predict that a not-traditionally-structured loop executes 2^32 times. I do so many posts about compiler bugs here that I figured a bit of antidote would be nice.
This is gcc 4.2.1 and Apple LLVM version 4.2.
I’m guessing inlining+DCE is now common and “basic”, but the compile-time evaluation of ‘checked’ is cool! Is there a well-established dataflow algorithm for that?
Did the code work properly once, I assume, you changed the last line of foo to something like ” return x1 == x2″, then asserted on that in the main loop?
BTW, this is a much cleaner way of doing fast loops than I had seen before : calloc() an array such that it ends at a page boundary, then set permissions on the next page such that an access will cause an exception, then finish the loop in the handler!
Hi Eric, I believe that both GCC and LLVM use “scalar evolution” passes to compute loop counts. But I don’t know who developed these techniques and when.
Forgive my asking, but are you sure assert is even called? (It needs -Og or #define _DEBUG.) Maybe f00() was a NOP because without assert it has no outside effects.
Also, calling printf with just a string isn’t a very good optimisation because printf compares every character to ‘%’! (I know you meant to say printf(“checked %ld values\n”, UINT_MAX);).
Eric, that’s a nice trick! But I’d hardly call it clean ;-). Is it actually faster? I imagine it only really works if you have to loop over the same array many times.
Hi Magnus, I did double check that assertion by making it fail. GCC and Clang (for versions and platforms that I use, at least) only omit assertion checks when NDEBUG is defined.
I was expecting both compilers to turn the printf into a puts, but neither one did that.
Rewriting standard library functions seems a dubious pastime to me beyond builtins and obvious arithmetical optimizations. The assumptions compilers can make about them are limited. I wonder if rewriting printf() to puts() would actually pay off — nominally puts() is simpler since it skips the formatting, but you’d expect the I/O to be the bottleneck anyway. And the compiler needs to check that the string contains no formatting specifiers and the return value is not used (since the return value of puts() cannot be used to emulate the return value of printf()). All that for a library that for all you know might implement puts() by calling printf()…
Jeroen, I’m pretty sure that previous versions of GCC did the puts() optimization. Perhaps they backed off due to problems like the ones you mention. The real benefit of this replacement would be on embedded systems where (assuming the libraries are designed well or the linker is pretty smart) there would be some chance of not even linking printf() into the executable.
How many codes have you seen that checked the return value of printf()? I’m not sure I’ve ever seen it done “for real”.
Here we are:
(There’s a minor problem with the program on ILP32 platforms, as checked overflows to 0.)
Jeff, is it wrong to throw x86 under the bus? I hate that long long int stuff.
That day cannot come soon enough.
I believe if you declare x&checked volatile, the optimization will not happen. It’s a trick I have seen many times | http://blog.regehr.org/archives/1033 | CC-MAIN-2014-15 | refinedweb | 753 | 70.53 |
Python Requests Module Guide
We live in an interconnected world, applications are constantly exposing API’s to be consumed by others. Many times these are HTTP based such as Rest APIs. How can you consume HTTP based APIs? Python makes calling HTTP based APIs a breeze through the requests module. It’s motto is “HTTP for Humans”, and it makes consuming Rest APIs simple. In this article you’ll see how to use the python requests module to run various HTTP commands.
This guide is based on Python 3.
Install Requests Module
As is the case with python, installing is made easy with pip. Run the following command to install the requests module.
pip install requests
You can also run the following command.
python -m pip install requests
Requests Get Function
The two most common HTTP methods are a GET and POST. GET is used to request data from a source. When you browse insightsbot.com for example, you are issuing a GET command.
Let’s run python requests get function to issue a GET.
import requests r = requests.get('') print(r.content)
Straightforward right? Requests makes executing a GET very simple. The variable r is the response object which contains a server’s response to an HTTP request. It contains important properties such as content which contains the response in bytes. We print the content of the requests response and we see the Html that is returned by the server.
In our code above, our variable r holds other important properties. Run the following command to see all that is available.
print(r.__dict__)
You’ll notice the reponse header also contains interesting information such as the content type, the server that is running the site and others.
print(r.headers)
Let's print a few of these:
Done, let's continue to learn how to issue a POST.
Requests Post Function
HTTP Post is used when you want to submit data to the server for it to be stored or make a change. This is the second most commonly used HTTP verb.
In order to test this, we need a site we can submit a post method to. Luckily httpbin.org exists. It is a service to test HTTP requests and responses. Let’s now issue a post with python requests.
import requests Data = {'key1': 'value1', 'key2': 'value2'} r = requests.post("", data=Data) print(r.text)
As you can see above, we use the post function from the requests module. Data is submitted through the data parameter. In this case we are sending a dictionary of strings. The requests module encodes these into a form as you can see below.
Python Requests Basic Authentication
In HTTP transactions, basic authentication is a validation method in which a client provides a user name and password when making a request. This is then validated by the service and if found valid, the service responds, otherwise a validation error occurs.
Using python requests for basic auth is very similar to issuing a regular get command. Only difference is you add an auth parameter with the username and password such as below.
import requests r = requests.get('', auth=('USER_NAME', 'PASSWORD')) print(r.text)
Python Requests Download File
To download files with python requests, you will be issuing a python requests. If you recall, the content attribute contains the results in bytes. With this, all that is left is to write bytes to file with python.
First let’s issue a GET on the file you want.
import requests url_of_file = "" r = requests.get(url_of_file)
With the requests object, now write the bytes to a file. We will call our downloaded file PythonImage.png and use the open() function to save the requests content bytes to a file.
fileName= "PythonImage.png" with open(fileName, 'wb') as f: f.write(r.content)
Conclusion
You how now learned how to use the pythons requests module. This module is definitely made for humans as it makes calling http methods a breeze. You learned how to use the requests get and requests post functions and different variations such as basic authentication and using the module requests to download files from the internet. | http://www.insightsbot.com/blog/1HkyIJ/python-requests-module-guide | CC-MAIN-2019-18 | refinedweb | 693 | 67.55 |
◕ A new product.
Popular Google Pages:
This article is regarding Basic structure of a simple Java program.
Last updated on: 1st March 2017.
◕ Basic structure of a simple Java program.
We will write a Java program in which we will add the number of Redballs with the number of Blueballs.
The complete program is given bellow.
public class balls{
public static void main(String[] args){
int numBalls=0;
int redBalls=3;
int blueBalls=2;
numBalls = redBalls+blueBalls;
System.out.println("Total number of balls is: "+ numBalls); // This displays the result on screen.
}
}
■ If we run this program then it will produce the result:
Total number of balls is: 5
◕ Description
The description of the keywords that we used in the above program are given bellow:
public
This keyword specifies that the method main() is accessible from outside the class.
Here it specifies that the method main() is accessible from outside the class balls.
main()
This is a method.
Execution of a program always starts from the first executable statement of the method main().
int numBalls=0;
This line is the first statement of the body of the method main() to be execute.
numBalls = redBalls+blueBalls;
This line is a mathematic expression that calculate the total number of balls.
System.out.println("Total number of balls is: "+ numBalls);
This line displays the result or output on the screen.
Here the output is Total number of balls is: 5
numBalls, redBalls, blueBalls
These are variables and we initialize these variables with a value.
int
This keyword tells the compiler about the type of the variables.
system
This is the name of the class that contains the object out.
out
This is a static variable in the class system.
On the other hand we can say, this is an object in the class system
This contains the method println().
println()
This is a method in the object out.
This method is used to displays the text output.
■ Assignment Statement & Assignment Operator in Java
■ Increment a variable by a given amount in Java
Popular Google Pages:
Top of the page | http://riyabutu.com/java-articles/structure-of-java-program.php | CC-MAIN-2017-51 | refinedweb | 346 | 65.22 |
For Pakistan Market Conveniently Operate High Efficiency Bio Diesel Oil Gas Fired Steam Boiler
US $14500-115000 / Set
1 Set (Min. Order)
Bio Film Carrier MBBR Oil industry Wastewater Treatment
US $350-580 / Cubic Meter
1 Cubic Meter (Min. Order)
Arganmidas 100ML argan oil bio
500 Pieces (Min. Order)
2016 New Condition Heavy Oil And Bio Gas Fuel Boiler
US $200000-700000 / Set
1 Set (Min. Order)
bio oil
US $1.2-1.2 / Cartons
1000 Cartons (Min. Order)
100% Bio certified Organic Argan oil in glass bottle with dropper
US $3-5 / Piece
50 Pieces (Min. Order)
Bio Prickly Pear Seed Oil in Bulk
1 Liter (Min. Order)
leading manufacture of certified bio organic Avocado oil from india
US $20-30 / Kilogram
1 Kilogram (Min. Order)
Biotique Bio Bhringraj Fresh Growth Therapeutic Oil for Falling Hair, 120ml
US $3-7 / Piece
10 Pieces (Min. Order)
Bio Oil - Specialist Skin Care Oil
1000 Units (Min. Order)
Bio argan oil 100% Pure
US $1.2-2.6 / Piece
1 Piece (Min. Order)
Cactus organic bio certified oil
EUR 270-350 / Unit
1 Unit (Min. Order)
Pralash+ Bio Plant Hair Growth Essential Oil
US $3.5-4 / Piece
100 Pieces (Min. Order)
Bio Argan Oil 100 ml
80 Units (Min. Order)
leading manufacture of certified bio organic Argan Oil from india
US $10-13 / Liter
20 Liters (Min. Order)
100% pure Natural Bio Moroccan Argan Oil For Hair Treatment 16oz Press Pump Package
US $3.1-5.6 / Piece
1000 Pieces (Min. Order)
Sedative Substance Ylangylang Essential Oil Natural Bio Oil Quality Assured
US $20-45 / Kilogram
5000 Kilograms (Min. Order)
Extra Virgin Bio Organic Avocado Carrier Oil Used For The Skin Tightening
US $7.97-12.32 / Kilogram
1 Kilogram (Min. Order)
organic bio best-selling natural ginger extract oil
US $4-6 / Piece
10 Pieces (Min. Order)
Useful Factory Wholesale bio essence face massage oil
US $2.5-4.2 / Piece
500 Pieces (Min. Order)
Leading Manufacture of Certified bio Organic Oregano oil from China
US $1-30 / Kilogram
25 Kilograms (Min. Order)
Pure Bio Rosemary Oils from Herbal Lite
US $0.35-0.5 / Set
1 Set (Min. Order)
Organic skin care Shrinking-pores bio natural oil/ skin firming essential oil
US $3.5-5.4 / Piece
120 Pieces (Min. Order)
import argan oil wholesale/argan oil bio
US $1-50 / Kilogram
1 Kilogram (Min. Order)
pure bio rosemary essential oil
US $26.5-26.5 / Kilogram
1 Kilogram (Min. Order)
Argan Almond Oil Bio Natural
US $1-500 / Kilogram
1 Liter (Min. Order)
Bio Natural Type Bio Pumpkin Seed Oil
US $4-10 / Kilogram
1 Kilogram (Min. Order)
originate from Valensole Plateau lavender bio essence oil essential
US $1-3 / Piece
500 Pieces (Min. Order)
100% Pure Lavender Essential Oil Natural Bio Oil
US $6.9-12.9 / Piece
50 Pieces (Min. Order)
High quality ! hair oil brands/ bio olive oil
US $0.6-1.1 / Piece
500 Pieces (Min. Order)
Bio oil ganoderma lucidum spore oil
US $650-835 / Kilogram
1 Kilogram (Min. Order)
Bio slim Safflower Oil...
100 Cartons (Min. Order)
Cedar Leaf Thuja Essential Oil
US $15-35 / Kilogram
1000 Kilograms (Min. Order)
Marula Oil
1000 Units (Min. Order)
Buying Request Hub
Haven't found the right supplier yet ? Let matching verified suppliers find you. Get Quotation NowFREE
Do you want to show bio oil or other products of your own company? Display your Products FREE now!
Related Category
Product Features
Supplier Features
Supplier Types
Recommendation for you | http://www.alibaba.com/showroom/bio-oil.html | CC-MAIN-2017-04 | refinedweb | 583 | 69.58 |
.
I'm using javafx 2.1 and I'm trying this example on osx:
- javafx to javascript works
- javscript to javafx doesn't seem to work: I'm getting a javascript error "ReferenceError: Can't find variable: java".
I'm currenlty gearing up to try the example on linux to see if the problem persists or not (Need help)
Posted by Steve Nyemba on March 07, 2012 at 07:32 PM PST #
Hi,
I'd like to make Upcalls from JavaScript to JavaFX2 but after clicking "here" nothing happens.
Where should
JSObject jsobj = (JSObject) webEngine.executeScript("window");
jsobj.setMember("java", new Bridge());
Is there any special place where instructions such as
JSObject jsobj = (JSObject) webEngine.executeScript("window");
jsobj.setMember("java", new Bridge());
should go? E.g. before/after page
webEngine.load(s);
I'd appreciate if you could you please provide a complete example of such communication.
Regards
-Peter
Posted by guest on March 29, 2012 at 07:02 AM PDT #
Hi Steve and Peter,
setMember() should be called after the page has been loaded. The reason is, JavaScript world is recreated each time a new page is loaded. The newly created window object won't have any custom members installed. A fine place to call setMember() is from a listener attached to WebEngine.getLoadWorker().stateProperty().
We're currently working on an update for the JavaFX tutorial: . We plan to have some demo code there, too.
Thanks!
Posted by guest on March 29, 2012 at 10:46 PM PDT #
I have tried your example in the javafx tutorial but webEngine.executeScript("window");
win.setMember("app", new JavaApp());
does not work. When I click exit application nothing happens except the page goes blank.
Posted by guest on July 25, 2012 at 12:38 AM PDT #
Could you please try running the project from the tutorial?
It worked fine for me -- I was running it with the latest javafx 2.2 build.
Posted by peterz on July 26, 2012 at 02:45 AM PDT #
I believe the tutorial Peter is making referebce to is at
Posted by Nicolas Lorain on July 26, 2012 at 02:34 PM PDT #
Hi,
Calling from JavaScript to JavaFX does not work.
1. I register the Java object after page was loaded.
2. I wrap the JavaScript code with try/catch block, and print alerts to see if there is en error. I print alerts info by adding alerts handler to my JavaFX code. See example code below.
3. Result: alert handling messages shows that
- script is invoked with no error.
- you can even see that the java object is recognized in the DOM (see printing)
- The code within Java object is not invoked!!! Also debugger does not stop there.
Current workaround seems to be: Using the alerts handler for getting calls from within JavaScript. Use some special syntax your application knows in order to distinguish regular alerts from query messages. For example:
alert('hello') is regular alert
alert('@code[{class:MyObjClass, method:doSomeWork, args:{a:1, b:"some string"}}]')
So your application knows to parse the Json object and use reflection in order invoke some method. This is just an example. The syntax can be different.
If someone succeed making the original feature of calling from JavaScript to JavaFX work please inform.
P.S JavaScript to Apple work great.
function testCallToJava() {
alert("testCallToJava start: '" + window.javaObj.test + "'");
try {
window.javaObj.test();
alert("testCallToJava end");
}catch(ex) {
alert("Error call to java: " + ex);
}
}
Print:
WebEvent [source = javafx.scene.web.WebEngine@7ab03, eventType = WEB_ALERT, data = testCallToJava start: 'function test() {
[native code]
}']
WebEvent [source = javafx.scene.web.WebEngine@7ab03, eventType = WEB_ALERT, data = testCallToJava end]
As you can see: start/end alerts was invoked. So what in the middle was invoked too but no effect.
Posted by guest on August 11, 2012 at 04:34 AM PDT #
I didn't run your test since I don't have the complete code. However, the simple test below works for me: a message is printed when I click into the beige area. Could you try this test too please?
import javafx.application.Application;");
}
}
});
webEngine.loadContent(
"<div style='width: 100; height: 100; background: beige;' " +
"onclick='javaObj.test();' />"
);
Scene scene = new Scene(new Group(webView));
return scene;
}
@Override public void start(Stage stage) {
stage.setScene(createScene());
stage.sizeToScene();
stage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
Posted by guest on August 17, 2012 at 01:43 AM PDT #
Hi,
Ok I have some resolution now:
1. With jfxrt.jr of JavaFX version JavaFX 2.0 SDK: Not working
2. With jfxrt.jr of JavaFX version: JavaFX 2.1 Runtime: Work fine!
3. With jfxrt.jr of JavaFX version: JavaFX 2.1 SDK: Work Fine!
Regards,
Gilad.
Posted by Gilad Tiram on August 17, 2012 at 02:46 PM PDT #
Yes, JavaScript to Java communication vie the WebEngine was only introduced in JavaFX 2.1. This article was published a little earlier, as this feature was already available in the JavaFX 2.1 Developer Preview.
Posted by Nicolas Lorain on August 17, 2012 at 04:11 PM PDT #
Hello, i would like this Communicate with Javascript But my SDK is JavaFX 2.2 and won't work before my Application won't call back from Javascript. I have copied from Posting "Posted by guest on August 17, 2012 at 01:43 AM PDT"
I have tried this code:
import javafx.application.Application;
import javafx.application.Platform;");
}
public void exit() {
Platform.exit();
}
}");
JSObject win2 = (JSObject) webEngine.executeScript("window");
win2.setMember("app", new Bridge());
}
}
});
webEngine.loadContent(
"<div onclick='javaObj.test();' width='100' height='50'>"+
"Test"+
"</div><br /><div onClick='app.exit();' width='100' height='50'>"+
"Exit"+
"</div>"
);
Scene scene = new Scene(new Group(webView));
return scene;
}
@Override public void start(Stage stage) {
stage.setScene(createScene());
stage.sizeToScene();
stage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
Now i would like to call from WebLauncher but it doesn't work because it get unusabled?
What does it happen?
Posted by SourceSKyboxer on March 02, 2013 at 10:03 AM PST #
Hi,
Starting from 2.2.5 you need to declare class Bridge public. This is a security measure. Think of JavaScript as being in another package relative to your Java code.
Posted by Peter on March 04, 2013 at 10:19 PM PST # | https://blogs.oracle.com/javafx/entry/communicating_between_javascript_and_javafx | CC-MAIN-2014-10 | refinedweb | 1,050 | 67.35 |
This action might not be possible to undo. Are you sure you want to continue?
Gerry Hendrickx
Academiejaar 2011 – 2012
c Copyright K.U.Leuven Without written permission of the thesis supervisor and the author it is forbidden to reproduce or adapt in any form or by any means any part of this publication. Requests for obtaining the right to reproduce or utilize parts of this publication should be addressed to the Departement Computerwetenschappen, Celestijnenlaan 200A bus 2402, B-3001 Heverlee, +32-16-327700 or by email info@cs.kuleuven.be. A written permission of the thesis supervisor is also required to use the methods, products, schematics and programs described in this work for industrial or commercial use, and for submitting this publication in scientific het Departement Computerwetenschappen, Celestijnenlaan 200A bus 2402, B-3001 Heverlee, +32-16327700 of via e-mail info@cs.kuleuven.be.
I would like to take a moment to thank a number of people who have aided and supported me over the last year. First of all I’m grateful to Prof. E. Duval for giving me the opportunity to explore this self-proposed subject. I thank him for wanting to promote me and for the advice regarding the masterthesis during the year. A special thanks goes out to my supervisor Gonzalo Parra. He was always open for questions and provided helpful feedback and advice on a weekly basis. I also thank all the participants in the prototype tests for their honesty and comments, Céline Gladiné for creating the graphical design of the application, Tom Vermeulen and Glenn Vingerhoets for the extensive testing and advice and @Sergimtzlosa for his support regarding the iOS wrapper for Face.com. And last but not least I want to thank all my family and friends for being supportive throughout the year. Gerry Hendrickx
i
Contents
Preface Abstract List of Figures and Tables List of Abbreviations and Symbols 1 Introduction 1.1 Situating the problem . . . . . . . . . . . . . . . . . . . . . . . . . . 1.2 Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.3 Chapter overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 Research 2.1 Face recognition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.2 Augmented reality . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.3 Social network services (SNS) . . . . . . . . . . . . . . . . . . . . . . 3 Analysis 3.1 Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.2 Privacy concerns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 Design 4.1 Technology . . . . . . . . . 4.2 Storyboard . . . . . . . . . 4.3 Paper prototype iteration 1 4.4 Paper prototype iteration 2 4.5 Paper prototype iteration 3 5 Implementation 5.1 Digital prototype 1 5.2 Digital prototype 1 5.3 Digital prototype 2 5.4 Overview of classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i iv v x 1 1 2 2 5 5 10 13 17 17 20 23 23 24 27 29 35 41 41 47 51 56 59 59 60 61 63
implementation evaluation . . . implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6 Evaluation 6.1 Methodology . . . . . 6.2 Results and discussion 6.3 USE questionnaire . . 6.4 Real-life testing . . . . ii
Contents 6.5 A/B testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 67 67 68 69 69 73 73 75 77 78 81 81 83 85 86 89 89 91 93 94
7 Conclusion 7.1 Thesis summary . . 7.2 Goals . . . . . . . . 7.3 Reflection . . . . . . 7.4 Possible future work
A Paper prototype iteration 2 A.1 Usefulness questions . . . A.2 Ease of use questions . . . A.3 Ease of learning questions A.4 Satisfaction questions . . B Paper prototype iteration 3 B.1 Usefulness questions . . . B.2 Ease of use questions . . . B.3 Ease of learning questions B.4 Satisfaction questions . .
questionnaire results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . questionnaire results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
C Digital prototype iteration 1 questionnaire results C.1 Usefulness questions . . . . . . . . . . . . . . . . . . C.2 Ease of use questions . . . . . . . . . . . . . . . . . . C.3 Ease of learning questions . . . . . . . . . . . . . . . C.4 Satisfaction questions . . . . . . . . . . . . . . . . . D Digital prototype iteration 2 questionnaire results D.1 Usefulness questions . . . . . . . . . . . . . . . . . . D.2 Ease of use questions . . . . . . . . . . . . . . . . . . D.3 Ease of learning questions . . . . . . . . . . . . . . . D.4 Satisfaction questions . . . . . . . . . . . . . . . . . E Class diagram F Poster G Paper Bibliography
97 . 97 . 99 . 101 . 102 105 107 109 123
iii
Abstract
The internet has revolutionized the way people interact with each other. Different tools have been created to support communication on several levels. Social networks are starting to play a big role in the lives of their members and have their own focus. Because of this focus, people are joining different social networks, each one providing different benefits to the users. Their information is spread between these networks which in total forms the digital identity of the user, his online persona. It is due to this spread of information that discovering this digital identity is not a trivial task. The goal of this thesis is to simplify the access to a persons digital identity and do this by means of face recognition on mobile devices. The thesis discusses the research and related work study performed to scramble ideas to define the starting points. This research, combined with a brainstorm and small survey, are analysed and a concept is designed: an application that is able to recognize faces and display the digital identity of those faces in real-time on the screen of a mobile phone. The design and development of the application follow an iterative design process. It starts with paper prototypes of 3 different user interfaces, whereof one is selected and elaborated. This paper prototype of the interface is further designed and iteratively evaluated before starting the actual implementation. The development is done in 2 iterations: the first is focussing on the core functionality, the face recognition. This version is evaluated and produced a second digital prototype, which is a fully functioning application that allows the user to recognize people. The use of a database that stores social network handles of the users allows the application to link a recognized person to his social networks.
iv
List of Figures and Tables
List of Figures
2.1 2.2 2.3 2.4 2.5 2.6 2.7 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 4.10 4.11 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9 5.10 5.11 5.12 An example of reconstructed eigenfaces of the same person [3]. . . An example of a 3 dimensional reconstruction of a face [6]. . . . . Related face recognition applications . . . . . . . . . . . . . . . . . An example of a location-based AR app: Layar [18]. . . . . . . . . An example of a view-based AR app: Augmented driving [21]. . . An overview of prof. Erik Duval’s linked networks on FriendFeed. . The FriendStream app on an Android smartphone. [35] . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 7 10 11 12 14 15 25 26 30 30 31 33 34 35 38 39 40 42 43 45 46 49 50 51 53 55 55 56 56 v
Storyboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . User interface alternatives 2 and 3 . . . . . . . . . . . . . . . . . . . . . The new home, history and overview views in the second paper prototype The new setting views in the second paper prototype . . . . . . . . . . . A photo of the different parts used in the second paper prototype. . . . A boxplot representing statements A.2, A.3, A.4, A.5, A.7. . . . . . . . A boxplot representing statements A.9, A.12, A.14, A.16. . . . . . . . . A boxplot representing statements A.22, A.24, A.27, A.29. . . . . . . . . A boxplot representing statements B.2, B.3, B.4, B.5, B.7. . . . . . . . . A boxplot representing statements B.9, B.12, B.14, B.16. . . . . . . . . A boxplot representing statements B.22, B.24, B.27, B.29. . . . . . . . . A sequence diagram representing the face tracking process. . . . . Example screenshots of the face detection. . . . . . . . . . . . . . . A sequence diagram representing the face recognition process. . . . The different views of the first prototype. . . . . . . . . . . . . . . A boxplot representing statements C.2, C.3, C.4, C.5, C.7. . . . . . A boxplot representing statements C.9, C.12, C.14, C.16. . . . . . A boxplot representing statements C.22, C.24, C.27, C.29. . . . . . The different views of the second prototype. . . . . . . . . . . . . . A sequence diagram representing the information fetching process. The different views of the second prototype. . . . . . . . . . . . . . The Model-View-Controller pattern. [50] . . . . . . . . . . . . . . . The screen transition diagram of the application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
List of Figures and Tables 6.1 6.2 6.3 6.4 A boxplot representing statements D.2, D.3, D.4, D.5, D.7. A boxplot representing statements D.9, D.12, D.14, D.16. . A boxplot representing statements D.22, D.24, D.27, D.29. . A graph representing the average time to discover a persons with (WA) and without (WOA) the application. . . . . . . . . . . . . . . . . . . . . . . . . networks . . . . . . . . . . 61 62 63 65 74 74 74 74 74 74 74 74 75 75 75 75 75 75 76 76 76 76 76 77 77 77 77 79 79 79 79 79 79 79 82 82 82 82 82 82 82
A.1 The application helps me be more effective. . . . . . . . . . . . . . . . . A.2 The application helps me be more productive. . . . . . . . . . . . . . . . A.3 The application is useful. . . . . . . . . . . . . . . . . . . . . . . . . . . A.4 The application gives me more control over the activities in my life. . . A.5 The application makes the things I want to accomplish easier to get done. A.6 The application saves me time when I use it. . . . . . . . . . . . . . . . A.7 The application meets my needs. . . . . . . . . . . . . . . . . . . . . . . A.8 The application does everything I would expect it to do. . . . . . . . . . A.9 The application is easy to use. . . . . . . . . . . . . . . . . . . . . . . . A.10 The application is simple to use. . . . . . . . . . . . . . . . . . . . . . . A.11 The application is user friendly. . . . . . . . . . . . . . . . . . . . . . . . A.12 The application requires the fewest steps possible to accomplish what I want to do with it. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.13 The application is flexible. . . . . . . . . . . . . . . . . . . . . . . . . . . A.14 Using the application is effortless. . . . . . . . . . . . . . . . . . . . . . . A.15 I can use the application without written instructions. . . . . . . . . . . A.16 I don’t notice any inconsistencies as I use the application. . . . . . . . . A.17 Both occasional and regular users would like the application. . . . . . . A.18 I can recover from mistakes quickly and easily. . . . . . . . . . . . . . . A.19 I can use the application successfully every time. . . . . . . . . . . . . . A.20 I learned to use the application quickly. . . . . . . . . . . . . . . . . . . A.21 I easily remember how to use the application. . . . . . . . . . . . . . . . A.22 It is easy to learn to use the application. . . . . . . . . . . . . . . . . . . A.23 I quickly became skillful with the application. . . . . . . . . . . . . . . . A.24 I am satisfied with the application. . . . . . . . . . . . . . . . . . . . . . A.25 I would recommend the application to a friend. . . . . . . . . . . . . . . A.26 The application is fun to use. . . . . . . . . . . . . . . . . . . . . . . . . A.27 The application works the way I want it to work. . . . . . . . . . . . . . A.28 The application is wonderful. . . . . . . . . . . . . . . . . . . . . . . . . A.29 I feel I need to have it. . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.30 It is pleasant to use. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B.1 B.2 B.3 B.4 B.5 B.6 B.7 vi The The The The The The The application application application application application application application helps me be more effective. . . . . . . . . . . . . . . . . helps me be more productive. . . . . . . . . . . . . . . . is useful. . . . . . . . . . . . . . . . . . . . . . . . . . . gives me more control over the activities in my life. . . makes the things I want to accomplish easier to get done. saves me time when I use it. . . . . . . . . . . . . . . . meets my needs. . . . . . . . . . . . . . . . . . . . . . .
List of Figures and Tables The application does everything I would expect it to do. . . . . . . . . . The application is easy to use. . . . . . . . . . . . . . . . . . . . . . . . The application is simple to use. . . . . . . . . . . . . . . . . . . . . . . The application is user friendly. . . . . . . . . . . . . . . . . . . . . . . . The application requires the fewest steps possible to accomplish what I want to do with it. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B.13 The application is flexible. . . . . . . . . . . . . . . . . . . . . . . . . . . B.14 Using the application is effortless. . . . . . . . . . . . . . . . . . . . . . . B.15 I can use the application without written instructions. . . . . . . . . . . B.16 I don’t notice any inconsistencies as I use the application. . . . . . . . . B.17 Both occasional and regular users would like the application. . . . . . . B.18 I can recover from mistakes quickly and easily. . . . . . . . . . . . . . . B.19 I can use the application successfully every time. . . . . . . . . . . . . . B.20 I learned to use the application quickly. . . . . . . . . . . . . . . . . . . B.21 I easily remember how to use the application. . . . . . . . . . . . . . . . B.22 It is easy to learn to use the application. . . . . . . . . . . . . . . . . . . B.23 I quickly became skillful with the application. . . . . . . . . . . . . . . . B.24 I am satisfied with the application. . . . . . . . . . . . . . . . . . . . . . B.25 I would recommend the application to a friend. . . . . . . . . . . . . . . B.26 The application is fun to use. . . . . . . . . . . . . . . . . . . . . . . . . B.27 The application works the way I want it to work. . . . . . . . . . . . . . B.28 The application is wonderful. . . . . . . . . . . . . . . . . . . . . . . . . B.29 I feel I need to have it. . . . . . . . . . . . . . . . . . . . . . . . . . . . . B.30 It is pleasant to use. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C.1 C.2 C.3 C.4 C.5 C.6 C.7 C.8 C.9 C.10 C.11 C.12 The application helps me be more effective. . . . . . . . . . . . . . . . . The application helps me be more productive. . . . . . . . . . . . . . . . The application is useful. . . . . . . . . . . . . . . . . . . . . . . . . . . The application gives me more control over the activities in my life. . . The application makes the things I want to accomplish easier to get done. The application saves me time when I use it. . . . . . . . . . . . . . . . The application meets my needs. . . . . . . . . . . . . . . . . . . . . . . The application does everything I would expect it to do. . . . . . . . . . The application is easy to use. . . . . . . . . . . . . . . . . . . . . . . . The application is simple to use. . . . . . . . . . . . . . . . . . . . . . . The application is user friendly. . . . . . . . . . . . . . . . . . . . . . . . The application requires the fewest steps possible to accomplish what I want to do with it. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C.13 The application is flexible. . . . . . . . . . . . . . . . . . . . . . . . . . . C.14 Using the application is effortless. . . . . . . . . . . . . . . . . . . . . . . C.15 I can use the application without written instructions. . . . . . . . . . . C.16 I don’t notice any inconsistencies as I use the application. . . . . . . . . C.17 Both occasional and regular users would like the application. . . . . . . C.18 I can recover from mistakes quickly and easily. . . . . . . . . . . . . . . C.19 I can use the application successfully every time. . . . . . . . . . . . . . B.8 B.9 B.10 B.11 B.12 82 83 83 83 83 83 83 84 84 84 84 84 85 85 85 85 87 87 87 87 87 87 87 90 90 90 90 90 90 90 90 91 91 91 91 91 91 92 92 92 92 92 vii
List of Figures and Tables C.20 C.21 C.22 C.23 C.24 C.25 C.26 C.27 C.28 C.29 C.30 I learned to use the application quickly. . . . . . I easily remember how to use the application. . . It is easy to learn to use the application. . . . . . I quickly became skillful with the application. . . I am satisfied with the application. . . . . . . . . I would recommend the application to a friend. . The application is fun to use. . . . . . . . . . . . The application works the way I want it to work. The application is wonderful. . . . . . . . . . . . I feel I need to have it. . . . . . . . . . . . . . . . It is pleasant to use. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 93 93 93 95 95 95 95 95 95 95
D.1 The application helps me be more effective. . . . . . . . . . . . . . . . . 98 D.2 The application helps me be more productive. . . . . . . . . . . . . . . . 98 D.3 The application is useful. . . . . . . . . . . . . . . . . . . . . . . . . . . 98 D.4 The application gives me more control over the activities in my life. . . 98 D.5 The application makes the things I want to accomplish easier to get done. 98 D.6 The application saves me time when I use it. . . . . . . . . . . . . . . . 98 D.7 The application meets my needs. . . . . . . . . . . . . . . . . . . . . . . 98 D.8 The application does everything I would expect it to do. . . . . . . . . . 98 D.9 The application is easy to use. . . . . . . . . . . . . . . . . . . . . . . . 99 D.10 The application is simple to use. . . . . . . . . . . . . . . . . . . . . . . 99 D.11 The application is user friendly. . . . . . . . . . . . . . . . . . . . . . . . 99 D.12 The application requires the fewest steps possible to accomplish what I want to do with it. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 D.13 The application is flexible. . . . . . . . . . . . . . . . . . . . . . . . . . . 99 D.14 Using the application is effortless. . . . . . . . . . . . . . . . . . . . . . . 99 D.15 I can use the application without written instructions. . . . . . . . . . . 100 D.16 I don’t notice any inconsistencies as I use the application. . . . . . . . . 100 D.17 Both occasional and regular users would like the application. . . . . . . 100 D.18 I can recover from mistakes quickly and easily. . . . . . . . . . . . . . . 100 D.19 I can use the application successfully every time. . . . . . . . . . . . . . 100 D.20 I learned to use the application quickly. . . . . . . . . . . . . . . . . . . 101 D.21 I easily remember how to use the application. . . . . . . . . . . . . . . . 101 D.22 It is easy to learn to use the application. . . . . . . . . . . . . . . . . . . 101 D.23 I quickly became skillful with the application. . . . . . . . . . . . . . . . 101 D.24 I am satisfied with the application. . . . . . . . . . . . . . . . . . . . . . 103 D.25 I would recommend the application to a friend. . . . . . . . . . . . . . . 103 D.26 The application is fun to use. . . . . . . . . . . . . . . . . . . . . . . . . 103 D.27 The application works the way I want it to work. . . . . . . . . . . . . . 103 D.28 The application is wonderful. . . . . . . . . . . . . . . . . . . . . . . . . 103 D.29 I feel I need to have it. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 D.30 It is pleasant to use. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 E.1 The class diagram of the application . . . . . . . . . . . . . . . . . . . . 106 viii
List of Figures and Tables
List of Tables
2.1 2.2 3.1 3.2 3.3 4.1 5.1 6.1 Comparison of the different face recognition API’s . . . . . . . . . . . . Social networks and their focus. . . . . . . . . . . . . . . . . . . . . . . . Survey results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Results of social network survey. . . . . . . . . . . . . . . . . . . . . . . Results of survey on Facebook that polls to the privacy concerns. . . . . Comparison of the iOS and Android languages . . . . . . . . . . . . . . List of status messages on different phases of the recognition process. . . Table representing the times to discover social networks with the app (WA) and without the app (WOA). . . . . . . . . . . . . . . . . . . . . . 9 13 19 20 20 24 52
64
ix
List of Abbreviations and Symbols
Abbreviations
PCA API AR HWD SNS Principal Component Analysis Application Programming Interface Augmented Reality Head Worn Display Social Network Service
x
Chapter 1
Introduction
1.1 Situating the problem
The internet has revolutionized the way people interact with each other. Different tools have been created to support different levels of communication. Millions of people are online and are using social networks like Facebook, Twitter, Google+ and so on in order to connect with each other. However, each network has its own goal and functionalities, which results in people participating in multiple networks. Their presence on the internet, their digital identity, is divided among these services, and it is often a hard task to find all the information available of a certain person. This digital identity of a person can be useful to other people. Upon meeting an interesting person, you might want to get to know more about him, and this could be achieved by inspecting his digital presence. They can use it to get in touch or even to find common ground to talk about when they meet face to face. The main focus of this thesis is to allow a user to get efficient access to this information. This thesis tries to resolve this need by using smartphones. Such a device has a number of useful characteristics: • It’s always connected to the internet, either via Wifi or mobile networks and can thus serve as an access point to a person’s digital identity. • It has many features, like a camera, accelerometer, microphone, media playback possibilities,... that allow developers to create an immense amount of different applications. • Modern smartphones are powerful enough to process heavy algorithms and large datasets. These characteristics have made smartphones a gateway for new ideas and applications and made them well suited for a digital identity discovery application. We can use the camera of the smartphone to scan the surroundings for faces and use the face of a person as the link between his divided online information. This brings us to the subject of this thesis. The general idea is to use a smartphone to 1
1. Introduction recognize a person and allow the user to get quick access to all of his information on the internet. We will create an application that uses face recognition to recognize the person and collect information about him. This information will be a collection of the social networks to which the recognized person is subscribed, his digital identity.
1.2
Goals
The goals of this thesis are separated in different points. 1. A first step is to investigate the different possibilities of face recognition on a smartphone. A correctly functioning algorithm will need to be found that is both reliable and fast. False positives, which is matching a face to a wrong name, need to be kept to a minimum, because otherwise a persons face will be linked with the wrong digital identity. 2. A proper way to visualize the application will need to be found. A study of different options to display data is needed, along with an evaluation of the possibilities, to be able to make an informed decision. The information will have to be shown in clear and useful user interface. One visualization to try, is augmented reality (AR) [15]. AR is the augmentation of real life, by adding a layer of computer-generated content to the camera of the appliance. This modern technology can be used to display the digital identity in real-time next to the person on the camera view of the smartphone. Ways to display this need to be researched and evaluated. 3. The application should be efficient. It’s the objective to create a frictionless and reliable way to discover a digital identity. It should be faster than that person telling you where you can find him on social networks, or researching him yourself on the internet. The application is aimed at improving productivity in the field of discovering information, eliminating the need to gather the digital information manually. This thesis does not describe the creation of a specific face recognition application. It describes the examination of the possibilities to discover digital identities by using face recognition. It will explore different approaches and try to find the best way to visualize such an application. We will design the application based on a rapid prototyping approach with frequent user feedback cycles, in order to get feedback during the design.
1.3
Chapter overview
Chapter 2 presents concepts and state of the art applications related to the topic. It covers a literature study, describing recent progress in the fields of face recognition, augmented reality and social network aggregation. It contains a related work study, in which several applications of the 3 subjects will be discussed and compared to 2
1.3. Chapter overview see whether some useful lessons can be drawn from them. The chapter also has a comparison of multiple face recognition API’s that could have been used for the creation of this application. Chapter 3 covers the general analysis of the application. It composes a list of required functionalities along with a detailed description of the desired application. It prioritizes the different aspect of the application to get a clear view about what features are important and discusses the privacy concerns. Chapter 4 contains the first part of the iterative design, paper prototyping, which is a technique to create and evaluate a user interface in a quick but thorough way. The chapter covers three iterations, each with their setup, goals and evaluation. The first iteration deals with the visualization of the face recognition part of the application and the different ways a user interface can be created for the this functionality. The second iteration evaluates the interface of the entire application and looks for usability problems. The third iteration is an evaluation of the paper prototype with a number of experts from the department of human-machine interaction, in order to get an expert view on the user interface. Chapter 5 provides a description of the implementation of the application. It discusses the design of the digital prototypes. The implementation was also done iteratively, with the first iteration being merely the core of the application, a working face recognition application. The second iteration tweaks the application based on the results from the evaluation of the first prototype and finishes the implementation of the other features. Chapter 6 discusses the evaluation of the second and final digital prototype. It focusses on both the usability and usefulness of the application and tests whether the final application indeed provides a more efficient way to discover digital identities. Finally chapter 7 is the conclusion of this thesis. It summarizes the entire project, discusses the final results and checks whether the application has achieved its goals. It also suggests work that can still be done, should this thesis be continued.
3
Chapter 2
Research
The development of this application covers several different domains and concepts. It is therefore useful to examine the work that is already accomplished in these fields. This chapter is split up into different categories. The first section is about face recognition, which is the core technology driving the application. The second section discusses augmented reality to check whether this could be used to visualize the recognized faces. Finally the third section presents different social networks and techniques to aggregate and display information in a single environment.
2.1
Face recognition
Face recognition is defined by Princeton1 as "biometric identification by scanning a person’s face and matching it against a library of known faces". This means that to be able to recognize a face, you need two things: a device able to scan faces and a library of known faces to be able to find a possible match. In this thesis, the device to scan the faces will be a smartphone. Nearly every smartphone has a built-in camera that can capture photos or videos to be scanned by a face recognition algorithm. This algorithm will need to have an extensive set of known faces to match it to.
2.1.1
Face recognition techniques
There are many different approaches to match a face. In this study we will discuss 3 leading techniques: two traditional techniques and one modern technique. We do not focus on how these can be applied on mobile devices, because it is currently not feasible to have the entire set of known faces locally on any device. We assume that the face will be processed by a different device than the smartphone. Traditional face recognition techniques In the early years of face recognition, the process was limited to two main approaches: feature recognition and template matching [1]. These approaches can vary depending
1
5
2. Research on the exact matching methods, but the general idea behind each of them remains the same. Feature recognition is based on the characteristics of a face [1]. It identifies several points on the image, like the position of the nose, the eyes, the mouth and the eyebrows. The algorithm sees the face as a geometric shape, and tries to find the relation between the different aspects of that face. To be able to compare several images, the images need to be normalized, this means that all used images must be independent of scale, position and rotation of the face. One way to normalize is to compare the position of the eyes in a normalized image to the eyes in the yet to normalize image. You can scale and rotate the latter to match these eye positions. Many different approaches exist to match the geometric characteristics of faces, the most known being Principal Component Analysis (PCA) [2], also referred to as the use of eigenfaces. In this technique, the image is transformed into an eigenface, which is a multidimensional array of uncorrelated eigenvectors by using singular value decomposition, containing the important features of the face. In this highly compressed state, one is still able to reconstruct the picture in a simplified form, but with all characteristics intact (see figure 2.1). For each image, the weighted sum is calculated which represents the image. All faces are then compared by using this sum.
Figure 2.1: An example of reconstructed eigenfaces of the same person [3].
In template matching, the picture of the face is seen as a matrix of light intensities. For this technique, the image needs to be normalized in the same way as in the previous technique. The comparison of the images works only if the face in every image is faced the same way, has the same size and the same rotation. The image that contains the face that has to be recognized, is compared to all others in the database and a score is calculated per characteristic (nose, eyes, mouth,...). The database image with the highest score is the matched image. This is a very basic 6
2.1. Face recognition technique, because the images need to be similar to the ones in the database to give a correct match and it is very sensitive to illumination variations. Three-dimensional face recognition The techniques described in previous sections are some of the first attempts of face recognition. They are based on the comparison of two-dimensional images and the results are therefore dependent on the normalization of the image, which is a cumbersome process. More recently, other techniques are used to compare faces and are based on three-dimensional reconstruction [4]. This technique measures the distances between characteristics of the face (like nose, mouth and eyes, but also bone structure) and uses symmetry to construct a three dimensional model of the face as seen in figure 2.2. This modelling is, in contrast to the previous algorithms, less sensitive to lighting and rotation. Overexposure can still blur out the characteristics, but slight variations in lighting are no problem because the 3D model can still be constructed. The 3D representation can be rotated and then matched against the other 3D faces in a database. The model with the greatest similarity will be the most possible match [5].
Figure 2.2: An example of a 3 dimensional reconstruction of a face [6].
2.1.2
Face recognition API’s
Because of the numerous possibilities of applications on smartphones, multiple companies have set up an application-programming interface (API) for developers to easily include this functionality in different applications. This allows to bypass the implementation of a face recognition algorithm and instead focus on the application itself. Therefore, it is necessary to find a suitable API to take care of the recognition. This section compares some of these API’s. Face.com Face.com [7] is one of the most famous companies offering a face recognition API. They focus on a social experience and have built their database mostly 7
2. Research by using tagged photo’s from Facebook [8] and Twitter [24]. Their API allows developers to create their own face recognition applications without the need of a private database of faces. All the applications that use Face.com help their database to grow even further. Once a user of a Face.com powered application logs in through Facebook, the Face.com engine can train the algorithm with his face and all of his friends by using the tagged photos. At the moment, their database contains over 31 billion face images from over 100 million different persons. Users can recognize either their Facebook friends or the application can provide a private namespace with a collection of people to recognize. The algorithm behind Face.com is based on three-dimensional face recognition as described in the previous section [6]. It builds a 3D model of the faces and these are compared with the models from the database. Betaface Betaface offers a complete package to recognize persons in images and videos [9]. Their focus is mainly on indexing, allowing multimedia content to be scanned and indexed. For example, you can search the content of a video for the presence of certain celebrities. The software identifies known persons or can save unknown persons for later identification. Their algorithm for face recognition is undisclosed, but they do detect facial points and indicate biometric characteristics. Verilook Verilook [10] is a product developed by Neurotechnology. It’s a face recognition service built for use on personal computers and is able to extract faces from videos or images and match them against the database of the developer. Using this API thus requires us to construct our own database of faces. No information was found about the functioning of the algorithm. Other API’s PittPatt [11] and Viewdle [12] are two other promising API’s but can not be discussed due to several issues. PittPatt is recently acquired by Google and is currently not available. This application promised a face recognition API that could tell the viewing direction and scan for geometric characteristics. Viewdle has an iOS API (for iPhone and iPad development) which allows developers to integrate real-time face recognition along with augmented reality features. Unfortunately this is still in a beta stage and no invite was issued for testing. Comparison A comparison of these API’s is presented in table 2.1. Since our focus is to develop a mobile application, the API’s should support Java for Android and/or Objective-C for iOS. Betaface does not satisfy this requirement. Face.com supports both Objective-C and Java and Verilook supports Java. Face.com also provides a database based on Facebook’s shared photos. This is a big advantage because it provides a solid database to start from. It also allows a user to log into Facebook and the algorithm to be trained with all his friends faces. Verilook does not provide a database, so we would need to create our own, which will be a small, controlled set of images of a 8
2.1. Face recognition limited number of test persons. This limits the opportunities to test the application for broad audiences. A negative point of Face.com is that it is only able to process images, not video. However it is free, but has a rate limit of 5000 photos per hour. This seems sufficient for research and testing purposes. Verilook and Betaface are paid API’s, thus funding of the university will be required. Face.com Images Multiple (incl. Obj-C and Java) Returns face fea- Yes tures Social network Facebook and connection Twitter Database Provided Database size +31 billion Cost Free (limited) Supported media Platform Betaface Images and video .NET Yes None Provided Not given Paid Verilook Images and video Multiple (incl. Java) Yes None Not provided Not applicable Paid
Table 2.1: Comparison of the different face recognition API’s
2.1.3
Current applications
For the related applications we discuss a couple of smartphone apps that use face recognition. Looking at these applications can provide insights about the possibilities of face recognition on mobile devices. KLIK KLIK is a photo application made by Face.com [13]. It demonstrates the power of their API, allowing the user to point the camera at a person and the app will show his name in real time. The user can then capture a picture and edit it with multiple filters. It only recognizes the Facebook friends of the users, since Face.com is based on Facebook. It was released during the development of this thesis application and shows some functionalities that we envisioned as well, like the automatic recognition of multiple persons at the same time. The application is shown in figure 2.3(a). TAT Augmented ID TAT augmented ID is a concept application that serves as a social aggregator based on face recognition [14]. The concept is very related to the objective of this thesis, and shows a possible user interface to display social network links using augmented reality after recognizing a face. In their interface the icons of the networks float around the head of the recognized person, as presented in figure 2.3(b). 9
2. Research
(a) KLIK by Face.com [13]
(b) TAT Augmented ID [14]
(c) Viewdle Social Camera [12]
Figure 2.3: Related face recognition applications
Viewdle SocialCamera Viewdle SocialCamera is a showoff application that allows the user to snap pictures and will automatically recognize and tag the persons in the picture [12]. It does not display the names in real time like the two apps mentioned above, but it tags them after the picture is taken. This application presents an alternative for the suggested augmented reality approach. The application is shown in figure 2.3(c). Social annotations in augmented reality Social annotations in AR is a thesis of this department from the previous year, written by Niels Beukers [19]. The goal of the thesis was to create a face recognition application that annotates people in real-time with information from social networks and uses this information as a conversation enhancer. For the face recognition functionality, Face.com was used. The program is able to recognize only the Facebook friends of the user. A negative point is that the application needs to have a back-end in order to send the snapped images to Face.com and authenticate with Facebook through a different website. However, these challenges are not present anymore, because Face.com now provides multiple SDK’s for different programming languages covering these issues.
2.2
Augmented reality
Augmented reality (AR) is defined by Ronald Azuma as having the following properties [15]: 1. combines real and virtual objects in a real environment, 2. runs interactively and in real time and 10
2.2. Augmented reality 3. registers (aligns) real and virtual object with each other. These properties are technology independent. AR requires an input device to scan the real world, a processing unit to add virtual object and an output channel to display the augmented world. The input device is usually a camera. When the user wants to walk around using AR, the output device can be either a head worn display (HWD) or a handheld device like a smartphone. This thesis focuses on mobile devices, which are suitable for AR. Smartphones are equipped with a camera and have enough processing power to interpret the feed and add virtual objects. The screen can serve as both the display and the input device.
2.2.1
AR techniques on mobile devices
Basically there are two trends of AR on mobile devices at the moment: location-based and view-based. The distinction lies with processed data before displaying the AR to the user. Location-based AR is used to display information about fixed items. These items can be buildings, landmarks, and any other object that is fixed in one location. The coordinates of these locations are stored in a database along with the extra information, like a description, multimedia content,... A smartphone owner can use a location-based AR application to find his way to places, or to examine his environment. This technique does not need to scan the input from the camera, but instead uses the built-in GPS and compass to determine the users location and orientation. An example application can be seen in figure 2.4
Figure 2.4: An example of a location-based AR app: Layar [18].
View-based AR is a more complicated technique. It receives the input from the camera feed, processes it and displays extra objects or information. It needs to have the functionality to scan the feed for a certain type of object. An example of view-based AR can be seen in figure 2.5. 11
2. Research
Figure 2.5: An example of a view-based AR app: Augmented driving [21].
2.2.2
Current applications
The use of AR on the smartphone is a booming business [16]. Looking at how they are used now and the technologies behind it, can give us a clear view on what’s available. Layar Layar [17] is an Android and iOS application. See figure 2.4 for a screenshot. The company is one of the pioneers in smartphone AR. Originally the application used location-based AR to show the users information about places in their neighbourhood but they have recently expanded to view-based AR too. The unique part about Layar is that it uses, as you could expect, layers of information. For instance, you can choose the Wikipedia layer and it will show you Wikipedia information about your neighbourhood. Layar allows users to create their own layers of information, and this makes it a very open platform that people can experiment with. Augmented driving Augmented driving [21] is an iPhone application created by imaGinyze. It’s a great example of view-based AR. The camera feed scans the road ahead for lanes and cars and monitors your driving speed. It processes this data and displays an augmented view of the road on screen. Cars and lanes are highlighted, speed is indicated, distance to the car in front of you is given, and so on. It’s a well built application with a lot of features. It proves that modern smartphones are powerful enough to process a live camera feed in real-time. 12
2.3. Social network services (SNS) Social annotations in AR This work has already been presented in section 2.1.3. The application uses a HWD approach to display information about the recognized person [19]. However, this technology isn’t at the stage that it’s just a small set of goggles. The setup consisted of a set of AR goggles, combined with a laptop, carried in a backpack, a webcam mounted on top of the goggles and a mouse to navigate through the application. Another obstacle during this thesis was the use of OpenGL [20] to combine the video feed from the camera of his HWD with the annotations. Our work focuses on mobile devices, so both problems can be evaded. Our setup will consist of a smartphone, which already contains a camera, an input device (a touchscreen) and a display. The use of OpenGL will not be necessary as the mobile platforms offer their own solution for layering a video feed.
2.3
Social network services (SNS)
As said in the introduction, the digital identity of a person is represented by his presence on the Internet. Due to the increasing popularity of SNS’s, the industry has expanded and this has resulted in the birth of many different tools. The difference between all these tools lies in their main focus. Table 2.2 displays a list of some of the leading networks along with their specific focus [22]. Social network Facebook Google+ [25] Twitter LinkedIn [26] Last.fm [27] Flickr [28] Slideshare [29] DeviantART [30] Focus Social Social Microblogging Work/Jobs Music Pictures Presentations Art Members [22] 901,000,000+ 170,000,000 300,000,000 120,000,000 30,000,000 32,000,000 Not available 22,000,000
Table 2.2: Social networks and their focus. Because the focus is so diverse, most people are subscribed to a lot of networks, each covering another aspect. A person can also choose to subscribe to multiple SNS’s with the same focus. For instance, if a Dutch person is already subscribed to Hyves [31], which is a network with a social focus in the Netherlands, he might still want to join Facebook, because it’s more international or has more interesting functionalities. This difference in focus and freedom of the user to subscribe to as many networks as he wants, causes most people to have more than one social network account. Membership to multiple social networks causes their information to be spread. To help to create a clear overview of all the information of a user, social network aggregators have been developed. They serve as a platform to collect and display data from social network sources. 13
2. Research
2.3.1
SNS aggregation
One way to aggregate social networks and the information streams they provide is to create an umbrella application that brings them all together. This one application gives an overview of all the activities of the accounts you link to it, while also providing the option to post updates on multiple networks in a single click [32]. In this section, a couple of examples of aggregation applications are discussed and divided into 2 subclasses: aggregation by handles and aggregation by authentication. Aggregation by handles Aggregation by handles means that the linking of the networks happens by filling in social network handles. A handle is the username of a person in a SNS (for instance gerry.hendrickx on Facebook). In aggregation by handles, you can just fill in your Twitter handle and the application will link your Twitter account to your FriendFeed profile. There is no authentication with Twitter required, so the system trusts that you will provide correct account information. 2 examples of such aggregation are discussed:
Figure 2.6: An overview of prof. Erik Duval’s linked networks on FriendFeed.
FriendFeed FriendFeed has been created by former Google employees and is a social network itself. It offers real-time updates and allows users to share information, chat, etc. But FriendFeed’s most important feature is the option to link it with more than 50 other social networks. Status updates of the linked networks will then be displayed in the feed of FriendFeed. You can also easily find the social networks that are linked to the feeds of other persons, as you can see in figure 2.6. This makes it a great tool for discovering digital identities. More! More! [36] is a mobile social discovery web tool that focuses on Web2.0 and academic sources and is developed at the Katholieke Universiteit of Leuven. Similar to this thesis, More! aims to be a mobile discovery tool, allowing efficient and frictionless discovery of a person’s digital identity. The big difference is the approach More! uses to reach this goal. More! is based on QR codes [37]. The user has to scan the QR code of another user to be able to get the 14
2.3. Social network services (SNS) link to the overview web page of that persons networks. However, the test users experienced difficulties with scanning these codes. This was the weak point of the project. This thesis offers a solution to the problem by using face recognition instead of QR codes. Also, More! has a functioning back-end, which allows its users to fetch person information through a RESTful API. The database saves the social network handles, the email-address and academic information of More! users.
Aggregation by authentication The second example of social network aggregation focuses on mobile devices. HTC, one of the leading manufacturers of Android devices, ships with his Android phones an application called FriendStream [34]. FriendStream is, in contrast to Friendfeed, not a SNS by itself. It’s an aggregator in its purest form, simply combining the feeds and allowing users to post updates to multiple networks at a time. You can see the application in figure 2.7. Another difference with Friendfeed is the method to add an SNS to the application. FriendStream requires the user to authenticate with the network he wants to add. It requires specific permissions (like to post to your wall), and needs the social network authorization to do this. Because of this authentication, the number of SNS’s that you can link is limited at the moment, because linking means interacting with the API of the network, generating tokens, and authenticating. This would be a cumbersome task to do if FriendStream also wanted to be able to link more than 50 networks. FriendStream is currently limited to Facebook, Twitter and LinkedIn.
Figure 2.7: The FriendStream app on an Android smartphone. [35]
15
2. Research
Conclusion
This chapter researched the different aspects of this thesis. First, we looked at face recognition and different approaches to recognize a face. Feature recognition and template matching are outdated techniques and cannot match up to 3D face recognition. It would be best for this thesis to use an algorithm that uses this new technique, because it is less sensitive to light intensities and rotation and angle of the image. The research of available API’s showed that Face.com is the most promising, as it offers a large database, a direct link to the Facebook social network and supports both Java and Obj-C, the main mobile developing languages. The augmented reality study showed two kinds of applications on mobile devices: location-based apps and view-based apps. Location-based apps use fixed GPS-coordinates and do not process the incoming video feed, while view-based apps do. For face recognition, a view-based app should be created, so the incoming feed with the face can be analyzed and annotated. The social network research showed that people use multiple social networks because of the difference in focus of the networks. The existence of social network aggregators further prove this point. Social network aggregators can work either with just the handles, or with full authentication of the linked networks. More!’s back-end seemed to be very useful, as it already serves as aggregator of social network handles. Face recognition could work where QR codes failed.
16
Chapter 3
Analysis
After researching what is possible regarding face recognition, augmented reality and social aggregation on mobile devices, the idea behind the application can now be defined. In this chapter, use case scenarios and a survey are presented to examine the required functionalities. Finally, some privacy issues are discussed and a solution is proposed to deal with them.
3.1
Requirements
In this section we will define the functionalities that the application will support. To obtain these, we performed a brainstorm and posted a poll on Facebook.
3.1.1
Scenario brainstorming
A brainstorming session took place about possible face recognition applications that can be used in order to define the idea for our application. This resulted in the following scenario’s: Scenario 1: A face recognition application can be used to acquire a person’s Vcard [41], which is a file format standard for electronic business cards. It contains the persons name, email addresses, phone numbers, urls and so on. The user of the application may scan the persons face and obtain the Vcard. This could be saved to the address book of the phone. Scenario 2: The Vcard scenario can also be used to create an address book application. The application could have its own contact directory based on faces and the recognized picture can be used as profile picture of the person providing an image that could be remembered. Scenario 3: More! (as described in section 2.3.1) focuses on an academic context. You need to scan a QR code to access an overview of the papers and slides of a presenter on a conference. This allows the user to follow up on this presenter’s publications and work. Since the QR code scanning did not yield the required results, the same concept can be tried with face recognition. 17
3. Analysis Scenario 4: Also applicable on conferences, you could use the application to scan nearly all the faces in the room and have a real-time augmented reality overview of what people are tweeting about the conference by showing their last tweet above their head. Scenario 5: As in TAT augmented ID (described in section 2.1.3) the face recognition could be used to scan a person and have icons of his social networks float around his head in augmented reality. This gives the user an efficient way to quickly access a persons social networks. Scenario 6: Face recognition can also be used as access control. A security system can check whether a recognized person has access to a restricted area. This can be applied for access control in buildings instead of authentication badges; or on computers and mobile devices instead of passwords or pin codes. Scenario 7: You could also scan a celebrity for instance on a billboard or in a commercial. The application could link this face to their IMDB page or personal website. Scenario 8: Instead of using the application to recognize a face and get the name and info, you could also use it the other way around. You could give the application a name and let it search the room for you. When he finds the person that matches the name, he can highlight him by using augmented reality. Scenario 9: Prosopagnosia is a disorder that prevents people from recognizing faces. Studies show that nearly 2 percent of the world population suffers from this condition, albeit not equally severe [42]. Some people could have occasional trouble, while others never succeed in recognizing a face. The face recognition application could be used by prosopagnosia patients to scan a person and read his name, instead of recognizing him themselves. From these scenario’s we extract a final scenario that will be used for the application and describes the functionalities that will be supported. Multiple scenario’s are based on the same underlying functionalities. We see that scenario 1 to 5 and 7 all need to recognize a face and look for information about it. The required information varies, and ranges from social network information to personal information. Scenario 6, the security system, and scenario 9 are valid uses of face recognition, but require only a lookup of the name. Scenario 8 starts from the assumption that you know the name and look for the person and is in contrast with the other scenario’s. Because our focus is on discovering digital identities, scenario 1 to 5 and 7 are combined into 1 final scenario: the user of the application should be able to recognize the people around him and lookup information about them. The information will be displayed in augmented reality and will show status updates (scenario 4) and links to social networks (scenario 5). He can save this information to the address book of the phone (scenario 1) and look it up later in the history of the application (scenario 2). The information contains personal information, information from a number of social networks and academic information like publications or slides (scenario 3). 18
3.1. Requirements
3.1.2
Information needs survey
A survey was posted on Facebook to get a view on what information people would want to receive if they could recognize a person by using a smartphone. The results can be seen in table 3.1. Option Nothing, I would allow people to have some privacy. Contact information Links to SNS’s Last status updates Pictures from Facebook Name and where we last met Possibility to contact the person Table 3.1: Survey results Number of votes 14 9 6 3 1 1 0
As you can see in table 3.1, 14 out of a total of 34 voters (35%) voted for the option nothing. This is alarmingly high. People seem to be very protective about their privacy. More on this subject in section 3.2. If we leave the nothing option out of consideration, we see that 9 out of 20 votes go to contact information and 6 to links to social networks. 3 people want to see the recognized person last status update and only 1 person wants to see pictures or the last location they’ve met. Nobody wanted the possibility to quickly email or text the recognized person. When we combine the final scenario from the previous section with the results of this survey, we see that the application will measure up to the needs of the survey participants if it indeed supports the options to look up and save contact information, provides link to different social networks and displays status updates.
3.1.3
SNS survey
The main functionalities of this application are the face recognition and the information fetching. The application should be able to recognize a face and gather information about that person by requesting it with several social networks. To find out which networks are the most important, we’ve asked each test person during the year which networks they use. The results can be seen in table 3.2. The table shows us that all 25 test persons use Facebook. Twitter, LinkedIn and Google+ are also used a lot. More specific networks like Last.fm or academic networks like Mendeley or SlideShare are used less. However, the academic networks are being used by everyone of the academic participants. 3 people also used other social networks. These were Foursquare (2 votes) and Spotify (1 vote). Because the popularity of a social network varies from time to time, we should keep the supported networks as open as possible. The application should support the main 19
3. Analysis SNS Facebook Twitter Google+ LinkedIn Last.fm Mendeley SlideShare Other Number of votes 25 18 17 12 7 7 6 3
Table 3.2: Results of social network survey.
social networks (being Facebook, Twitter, LinkedIn and Google+), but should be easily adaptable to support other networks.
3.2
Privacy concerns
The results of the poll in table 3.1 were intriguing as privacy issues were not initially considered as an issue. First of all, the general idea behind this thesis was to use information that is publicly available on the Internet. There was no attempt to access private information. The connection to the social networks will always be through the API’s and authorization is required to access private information. To get an idea regarding people’s acceptance to being recognized, a second poll was posted on Facebook. You can see the results in table 3.3. Options I would not like to recognized at all. I wouldn’t mind because the information about me on the internet is controlled. I would’t mind being recognized mind. I would’t mind because there isn’t a lot of information about me on the internet. Number of votes 13 5 3 0
Table 3.3: Results of survey on Facebook that polls to the privacy concerns. 13 out of 21 participants (61%) refuse being recognized by a smartphone application. 5 voters do not care whether they are recognized because the information on the Internet about them is controlled. They know which information is publicly accessible and monitor it themselves. 3 voters just don’t mind being recognized, one of them expressed that he had accepted the general tendency of the internet becoming less and less private. This 61% is a number that cannot be ignored. Therefore a solution to the privacy concerns is necessary in order to gain more adepts. After a brainstorm and a deeper 20
3.2. Privacy concerns look at what the face recognition API’s offer, we’ve come a with a solution that we think is feasible and will satisfy the privacy concerns. As said in section 2.1.2, Face.com can recognize both Facebook friends and people in a private namespace. It is not possible to recognize everybody; you have to give a set of people to search for when running the Face.com request. For instance you can send friends@facebook.com along with an image to search this image for your Facebook friends. This limitation seems to be the solution to our privacy concerns. We can let the application only detect our Facebook friends, but this limits the discovery possibilities. Therefore we can also use the private namespace, and register all users of the application in this namespace. This way, a user can be recognized by other users. This follows the philosophy that you can’t be against people recognizing you, if you yourself recognize people and willingly accepted to use the application. The final set of people that are recognizable for a user will thus be his Facebook friends and all other users of the application.
Conclusion
This chapter described the brainstorm and Facebook survey that lead to the functionalities that should be supported by the application. The application should be able to save a history or let you synch the information found to your address book. It should also be extensible regarding supported SNS’s. It should include the popular networks like Facebook and Twitter, but also academic networks like Mendeley so that it can be used in different contexts. It should use augmented reality to display which networks are available for the recognized person together with basic information like the last status update. The privacy issues, that were apparent from the poll lead to consequences about who could be recognized. A compromise was found that allows a user to recognize his Facebook friends and other users of the application.
21
Chapter 4
Design
After deciding the functionalities of the application, we proceed to design the user interface. This chapter presents the methods applied to create the application. The followed approach is cyclic: first a prototype is designed, then evaluated. After the evaluation, the design is adapted and evaluated again. The cycle goes on until we are satisfied with the results of the evaluation. The first design step is a storyboard. This is an overview of the different screens in the application and presents a story on how the user might experience the application. Next is the paper prototyping. This method is an efficient way to test an interface. We draw the interface on paper and evaluate it with test persons in different iterations. This chapter discusses three iterations of the paper prototype. The first one is to decide which interface is the most usable, the second is an elaboration of the chosen interface and the third is an adjusted version of the second prototype, evaluated by experts in the field of human-machine interaction.
4.1
Technology
There are different operating systems for smartphones. It is therefore important to find a platform that best suits the demands of application. The technology needs to be decided before designing the application, because different platforms are subject to different user interface guidelines. Apple’s iOS for iPhones and iPads and Google’s Android for smartphones and tablets are the two biggest platforms in the current smartphone market. In March 2012, Android has a US market share of 51.0 percent. iOS has a market share of 30.7 percent [43]. RIM with their operating system for Blackberry has a share of 12.3 percent, followed by Microsoft and Symbian with respectively 3.9 and 1.4 percent. Both platforms are compared in table 4.1 and are object-based programming languages, but the objective-C language of iOS does not have garbage collection, therefore memory management needs to be supervised by the programmer. This is to make the programmer more aware of memory usage, since smartphones have limited memory. Android can be developed on Windows, Mac or Linux, using the Eclipse 23
4. Design iOS Objective-C Xcode Mac OSX Android Java Eclipse Windows, Mac OSX, Linux Well documented Yes (only images)
Language IDE Operating System
Documentation Well documented Built-in face detec- Yes (iOS5.0 and tion newer, video and images) Built-in face recogni- No tion
No
Table 4.1: Comparison of the iOS and Android languages
IDE. iOS however can only be used on Mac, using the Xcode IDE. More specific for our application are the face detection and recognition techniques provided by both languages. Android supports face detection in images. You can import an image and it will tell you where the faces are. iOS does the same but also for video. This is a huge plus, because the application needs to be able to detect faces in real-time. Neither of the platforms support face recognition, so an external face recognition API will have to be used. In conclusion, both platforms are great candidates, but the real-time video face detection of iOS is the deciding factor. The application will be developed for iPhone, using the iOS platform.
4.2
Storyboard
Figure 4.1 shows the initial storyboard created in PowerPoint. Screen 1 shows the initial view of the application. It represents the camera view and automatically starts the detection of the faces present in the camera feed. Once a face is detected it will be marked with a square box and the application will automatically start the recognition process. Screen 2 shows the state after a successful recognition. Below the face there will be a button to mark whether the recognition was incorrect; the name of the person is displayed above his face and an arrow icon shown at the right side. If the user clicks the arrow icon, information from social networks will be fetched and displayed, as shown in screen 3. Next to the face, the icons of the networks that the recognized person is a member of, are drawn. If the user chooses to click one, for instance the contact icon, he will arrive at screen 4 and the contact information will be shown next to the face. If he clicks the Twitter icon, he will see the last tweet of the recognized person. There is a button available in the contact view to synch the information with the contact book of the smartphone. The whole process will be using augmented reality, with the user pointing the phone at the person that he wants to recognize.
24
4.2. Storyboard
Figure 4.1: Storyboard
However, one of the concerns during the design of the storyboard, was the fact that it might be cumbersome for the user to keep his iPhone pointed to the recognized person in order to be able to read the information. It would also mean that the user would have to navigate through the application while holding the phone in the air. This concern needs to be further evaluated. To be able to compare the evaluation of this interface to possible alternatives, two other user interfaces were created. The storyboard with the alternative interfaces is shown in figure 4.2. Interface 1 is the user interface as presented in the storyboard in figure 4.1 and uses a fully augmented interface to display the information. Interface 2 uses a sidebar. This allows the user to keep using the camera and scan other people while he examines the fetched information. In this way, he does not need to keep the phone pointed at the recognized person, this is now optional. The use of augmented reality is reduced, as it might improve the usability. Interface 3 uses full screen information panels, which completely disables the augmented reality when looking at information. This provides the best overview of the fetched information, but removes the ability to continue using the camera while browsing through the information. These 3 user interfaces will be evaluated. 25
4. Design
Figure 4.2: User interface alternatives 2 and 3
26
4.3. Paper prototype iteration 1
4.3
Paper prototype iteration 1
To evaluate the different user interfaces, paper prototypes have been developed. Paper prototyping [38] takes place after the idea behind the application is decided and the required functionality has been found. It’s the process of creating a mock-up of the application in pen and paper by drawing out the user interface and cutting out the pieces. The designer uses these pieces to simulate the application. This gives him an initial idea of the user interface of the application without spending a big amount of time. He can evaluate this paper prototype by using test persons and letting them play out some scenario’s or execute some tasks. The test persons will need to find their way in the application while using a technique called think aloud [39] (they need to say what they think is going to happen or what they expect). This way the designer immediately gets feedback about which buttons are clear and which are not. The first iteration starts from the three different user interfaces from figures 4.1 and 4.2. All the different buttons and views were printed and cut out. The paper prototypes of the interfaces were tested with 11 subjects. All of them were between the age of 18 and 23, studying at the university of Leuven. Seven of them own a smartphone, and 4 of those own an iPhone. The other 4 had little or no smartphone experience. The tests were done by using think aloud, and they were given the following tasks to complete: 1. Find the last song that the person standing in front of you listened to. 2. Add that person to your iPhones contacts. 3. Notify the system of a wrong recognition. 4. Visit the Facebook profile of the person standing in front of you. 5. Try accessing data from multiple persons at the same time. These tasks needed to be completed for each of the user interfaces and are designed to test if the test subjects can find and use all the functionalities in the application. If they complete the tasks in the given order, they will discover every aspect of the application. Step 1 and 2 of figures 4.1 and 4.2 were simulated by the evaluator, because they should happen automatically in the final application. The user interaction for all interfaces starts at the end of step 2. Because paper prototyping uses static images, the camera feed was simulated by using a photo. Another possible option was to use transparent material, so that testers could see through the prototype and use the real world as camera feed. This was not done because all the loose pieces of the prototype would make it hard to lift.
27
4. Design
4.3.1
Results and discussion
Upon executing the tasks while using user interface 1, the test subjects were required to use their imagination and experience to create a picture of how they would use the application in the real world. All of them thought that the application was cumbersome to use. The fact that you should keep the phone pointing to a person at all times, even when just reading information, proved to be a big issue. 4 of the 11 persons commented that once they were reading the information, it would be frustrating if the recognized person kept on moving. The text would move over the screen, or worse, the recognized person could walk away. They would lose track of him and would have to recognize him again once he came back. 7 persons said that the underlying camera feed wasn’t a priority anymore once they had the information. The focus upon receiving the information shifts from recognizing to reading, and they would prefer to do it without following the recognized person.
User interface 2 (as seen in figure 4.2) had more positive feedback. It eliminated the problem of having to track the person while reading the information. The person could move away, out of the reach of the camera, and the users would still be able to read his data. However, 8 of the 11 persons said that the camera feed on the screen would not be useful. They did not like scenario 1 because they wanted to lower their phone and check the information. This scenario allows them to do this, but the camera will just show the ground and the space on the screen will not be used properly. The 3 remaining persons thought this would not be a problem and commented that the camera allowed them to recognize another person more quickly. The iPhone users also mentioned that using a third of the screen to display information would not be enough to create a clear information overview. Since the iPhone screen has a size of 5 cm width and 7 cm height, using a third of the height to display information would only give you a bit more than 2 cm. They reckoned that this was not enough.
User interface 3 was received positively. The 8 persons who did not see a use for the camera part with interface 2 or the persons who thought 2 cm was not enough to display the information, all saw interface 3 as the optimal one. It also did not face the problem of keeping track of the recognized person. In conclusion, when asked after the evaluation which scenario they preferred, none of them picked scenario 1. Although this might work with a head worn display (you would just have to keep looking at the person), holding up the phone for the entire time seemed a big issue for the users. 73% (8/11) of the test users preferred the 3rd interface, mainly due to the readability of the full screen information. The rest of the test users preferred the 2nd scenario, because of the ability to keep using the camera while viewing information. This would make the application more interactive. The percentage differs enough to pick interface 3 as the final scenario. This interface will now be elaborated and evaluated in a second paper prototype. 28
4.4. Paper prototype iteration 2
4.4
Paper prototype iteration 2
The previous prototype only contained the core screens of the application; these are the camera view, and a view where the information about the recognized person is shown, hereafter referred to as the overview view. In this second iteration, the prototype has been elaborated further. The overview view is split up in different views for each social network and one general screen (figure 4.3(c)). As discussed in previous sections, we have seen that in order to get an overview of someone’s social networks, that person needs to link these profiles to his account. We need a page that allows the user to log into his social network accounts and link them to his account in the application (see figure 4.4(b)). Prototype 2 also contains a history (figure 4.3(b)). This way we can test whether the users prefer the history, the adding to contacts, or both. To keep the camera view from being cluttered with buttons, a home view has been created (figure 4.3(a)), which links to the camera view, the history view and the settings view. The settings view (figure 4.4(a)) contains a link to the social network settings view and contains the following extra settings that might be useful: • Prevent screen lock: This disabled or enabled the automatic locking of the iPhone. • Launch in scan mode: If enabled, this opens the application directly in the camera view, instead of the home screen. • Delete all history: An efficient way to clear the recognition history of the application. The general style of the application tries to follow the iOS Human Interface Guidelines [44]. These are guidelines created by Apple, explaining how to use the standard iOS interface parts and giving the user predefined locations to place a button or label. These predefined parts are used in the prototype, along with some custom design for the overview view. A picture of the paper prototype can be seen in figure 4.5. The elaborated prototype was tested with 10 subjects, all between the age of 20 and 23. 4 of them study computer science, 3 are studying engineering and the remaining 3 were students from other faculties. The group consisted of 9 men and 1 women. 8 persons either owned an iOS device or had experience with one. This is important data, as people with experience on these devices will already be familiar with the UI. The 2 other persons had no smartphone experience, so they can offer insight on how difficult the application is for inexperienced users. The experience with AR applications was spread. 5 of the subjects had never used an AR application, 2 of them had used an AR app once and the other 3 had used multiple AR apps. The experience was not required, but people familiar with such apps could compare these apps with the prototype, providing valuable feedback.
29
4. Design
(a) Home View
(b) History View
(c) Overview View
Figure 4.3: The new home, history and overview views in the second paper prototype
(a) Settings View
(b) Social Networks Settings View
Figure 4.4: The new setting views in the second paper prototype
30
4.4. Paper prototype iteration 2
Figure 4.5: A photo of the different parts used in the second paper prototype.
The tasks from section 4.3 examined all functionalities of paper prototype one, but since the prototype was elaborated for this iteration, some tasks needed to be included: 1. Recognize the person in front of you. 2. Check his last tweet 3. Look for information about someone who is not around, but you have recognized him before. 4. Delete that person from your history. 5. Link your account with your Twitter and Mendeley accounts. 6. Set-up the program so that when someone recognizes you, they can access info from Mendeley, but not from Twitter. 7. Delete all history. 8. Scan the person in front of you, but correct the program when the person is not correctly identified. 9. Mail someone. 10. Add someone to your iPhone contacts. These test were designed to make the user discover all functionalities of the application. During the test the subjects needed to use the think aloud technique and they only received help if they really did not seem to find how to do something. 31
4. Design
4.4.1
Results and discussion
This section describes the results of the tasks. We list the problems that were discovered during the tests: • To be able to find more information about the recognized person, the user needed to click the face in order to move on to the overview view. 7 users immediately pressed the face. However, 3 users pressed the name in order to get to the information. After they had realised that this had no effect they pressed the face. • 6 out of 10 users mentioned that it required to many transactions to get from the overview view to the settings view. We should look for extra navigation options. • The intended gesture to remove someone from the history, was to hold your finger on the face. After a second, the face would wiggle and a close button would appear in the upper left corner. This gesture imitates the removal or closing of applications in the iPhone. The 2 persons without iPhone experience and 3 others failed to find this gesture. They even searched for a remove-button in the overview of a person. The other 5 found it and were very positive about it. • The Not him/her?-button is placed in the overview view. All users were able to find it but were not sure whether it belonged there. All 10 of them agreed that the button on the overview view was not appropriate, because at that stage, the app will already have fetched all the information of the wrong person. The placement of the button should be reviewed. • This task required the users to go to contacts overview view, which is reachable by clicking the contact icon in the overview view. The used icon was the same as Mac OSX uses for its contact application. However, only 4 out of 10 users recognized this icon and understood its purpose. Once they all figured that this was the contacts icon, they could predict to find the email address of the person there.. After the tests, it became clear which parts needed to be changed. First of all, the icon for the contacts tab was not clear enough and should be replaced. The gesture to remove someone from your history will be evaluated further to see if an alternative is necessary. We should try to find better navigation options and the button to indicate a wrong recognition should be relocated in the camera view, so that users can press it before fetching the wrong information.
4.4.2
USE questionnaire
After the tasks, the user needed to fill in a questionnaire in order to obtain the user’s perception of the application. The USE (Usefulness, Satisfaction, and Ease of use) 32
4.4. Paper prototype iteration 2 questionnaire was used [45]. This is a questionnaire to test user interface satisfaction and is based on 4 categories: usefulness, ease of use, ease of learning and satisfaction. The questionnaire consists of 30 statements that can be rated on a 7-point Likert rating scale, from strongly disagree to strongly agree [46]. All statements and answers can be seen in appendix A. Usefulness The application scores good on the general usefulness questions. For the discussion, we focus on the results of A.2, A.3, A.4, A.5, A.7, which are also presented in figure 4.6. These are the main indicators of usefulness along with some lower scoring statements. The most important statement, A.3 The application is useful had very good results with a median of 5.
Figure 4.6: A boxplot representing statements A.2, A.3, A.4, A.5, A.7.
A.2 The application helps me be more productive: The box plot shows spread results, although the median is 5. This spread could be caused by the goal of the application. It’s not an application that will improve the productivity of the user. A.4 The application gives me more control about the activities in my life: The results of this statement varied from 1 to 7 with a median of 4.5. This spread is also thought to be caused by the goal of the application. It is not meant to give you more control about the activities in your life. A.5 The application makes the things I want to accomplish easier to get done: The most voted numbers were 3 and 7, which point to a divided opinion. This might be connected to the pointing of the phone. People might think asking the name instead of recognizing a person is easier. 33
4. Design A.7 The application meets my needs: This question provided another very divided set of responses and has been answered negatively by the non-smartphone users. The persons that do not have a need for a smartphone, appear to have no interest to what a smartphone application can offer. Ease of use The application was perceived as easy to use. The majority of the votes for these statements were between 5 and 7. The discussed statements can be seen in figure 4.7 and contain the main indicators of ease of use and consistency of the application. A.9 The application is easy to use and A.16 I don’t notice any inconsistencies as I use the application were answered positively and are due to the standard iOS style, which creates uniformity and consistency over the entire application.
Figure 4.7: A boxplot representing statements A.9, A.12, A.14, A.16.
A.12 The application requires the fewest steps possible to accomplish what I want to do with it: Although the results are positive, with a median of 5, their were many complaints about the number of clicks required to return to the home view of the application. A.14 Using the application is effortless: The results are spread. Although the median is at 5.5 the results range from 2 to 7. This spread is related to the number of clicks required to get from one view to another in the application. Ease of learning and satisfaction In figure 4.8, you can see the answers to statements A.22, which is a good indicator of the ease of learning, A.24, A.27 and A.29, which are general satisfaction statements. The ease of learning statements were received very positive, each with a median of around 6 and with no answers below 5. A.22 It is easy to learn to use the application 34
4.5. Paper prototype iteration 3 scored high. We can conclude that the application is easy to learn, due to the used iOS standard, which makes the application familiar to iPhone users. The satisfaction perception of the application was good. A.24 I am satisfied with the application and A.27 The application works the way I want it to work were answered positively. The scores of A.29 I feel the need to have it varied from 1 to 6. The positive answers were given in general by the smartphone users, while the negative answers were given by the users without a smartphone. This indicates that people with a smartphone prefer the application.
Figure 4.8: A boxplot representing statements A.22, A.24, A.27, A.29. Finally, we can conclude by looking at the questionnaire results and the completed tasks that the application was received well, although some changes are required to improve usability. Therefore, adaptations were made and a third iteration was created and evaluated.
4.5
Paper prototype iteration 3
In this iteration, the paper prototype is adapted and evaluated again. A number of adjustments have been made to the previous prototype, based on the comments given while executing the tasks: 1. The icon for the contact view is replaced and is now the same icon that Apple uses for its contacts application on iOS devices. Since the application is developed for iPhones, users should be familiar with this icon. 2. Home-buttons are placed on nearly every screen of the application. Previously the home-button was only available in the camera view, settings view and history view. Now, every overview view has a home-button, so the users do not need to return to the camera first. 35
4. Design 3. The Not him/her?-button was generally perceived as misplaced. It was located on the overview view of a recognized person but it should have been accessible in the camera view, so that users could indicate a false match before all the information of the wrong person is being displayed. The button is now placed beneath the recognized face in the camera view, in the form of a big X icon followed by an Incorrect?-label. The test audience for this iteration consisted of experts in the field of humancomputer interaction. 7 members of the computer science department at the Katholieke Universiteit Leuven have evaluated the prototype. The occupation of the users range from phd student to professor. The group consisted of 1 woman and 6 men. 4 out of 7 test subjects own an iPhone, while the other 3 have some smartphone experience but not much with iOS devices. All test subjects have used augmented reality applications in the past, so they are familiar with the concept. The users needed to apply the think aloud technique and fulfil the same tasks as defined in the previous section.
4.5.1
Results and discussion
This section describes the results of the tasks. The same tasks were used as in the previous iteration. The problems and remarks of the users are the following: • When the users needed to find more information about the recognized person, they had to click the face. Again, some of the users (2 out of 7) pressed the name instead of the face. We can conclude that this is not a big problem since the majority of users do not experience any issues and other adapted to it pretty well. • One user was surprised to get to a Twitter overview page instead of the real Twitter application. This was asked to other users and all agreed that a direct link to the Twitter app might be better, because it provides the whole functionality of Twitter instead of just an overview. This idea will be used in the digital prototype. • To get from the Twitter overview view to the history view, the users needed to go back to the overview view where they could find a new home button. It takes 3 clicks to complete this, instead of 4 in the previous iteration. 3 users still complained about the length of the path, but the other 4 did not have problems with this. One of the users suggested a tab bar at the bottom of the screen with direct links to the history, camera, home and setting views. • To delete a person from the history, the users needed to press the face in the history for a second and an X-icon would appear that deleted that person. Some of the experts noted that this gesture is not used inside iOS applications and the user interface guidelines should be checked to see what is the proper way to do this. 36
4.5. Paper prototype iteration 3 • One of the users suggested a preview page, on which the user of the application could check how his profile would show when being recognized by others. All users saw this as a nice-to-have feature, but of lower priority. • The Delete history-button was found quickly, although 2 users noted that they would prefer to see this button on the history page. • The Not him/her?-button on the overview view was removed and placed as an incorrect-button on the camera view, below the face of the recognized person. However, 3 users saw this as clutter. They would prefer to just have the faces and the name labels on the camera view. They suggested a small X-icon or thumbs down icon next to the name. All agreed that the X-icon followed by the Incorrect?-label was confusing. The X could refer to removing the label instead of indicating a false tag. In general, the application was well received and some good suggestions were obtained. The problems of the previous iteration are mostly solved. Some users still felt like the path from one view to another was too long, even with the addition of extra home-buttons. However, if the application would link to other apps instead of giving an overview of each social network, it would have less screens and the path through the application would be shorter. This approach will be followed. The button to indicate a false recognition still caused problems and should be revised.
4.5.2
USE questionnaire
The users were asked to fill in the same questionnaire from the previous iteration, in order to be able to compare the results. The full results of the questionnaire are shown in appendix B. We will again discuss the general score of the 4 categories and examine some noteworthy results. In order to compare the scores to the previous iteration, the same statements are compared. Usefulness In general, the usefulness statements scored well in the questionnaire (see figure 4.9). The main indicator of usefulness, B.3 The application is useful had very good results. The median once again remained at 5, but none of the replies were lower. B.2 The application helps me be more productive: The median of the box plot has remained 5, but more than 50 percent of the answers were between 4 and 6, with a few lower scores and one extreme low score of 1. Overall, this is a better result than in the previous iteration and we can conclude that the experts found the app to increase their productivity. B.4 The application gives me more control about the activities in my life: The scores of this statement remain spread and on the lower side. This can not be improved, because the app does not aim to give the user more control about his activities. 37
4. Design
Figure 4.9: A boxplot representing statements B.2, B.3, B.4, B.5, B.7.
B.5 The application makes the things I want to accomplish easier to get done: In the previous iteration the scores were divided but they have improved drastically. The majority of the users gave a score of 5 out of 7, which means the application makes the discovery of digital identities easier to accomplish. B.7 The application meets my needs: The scores are improved compared to the previous iteration. This can be due to the new views of the application, that offer more functionalities.
Ease of use The ease of use of the application again scored high. The discussed statements can be seen in figure 4.10. B.9 The application is easy to use shows that the application is easy to use. B.12 The application requires the fewest steps possible to accomplish what I want to do with it: The median of the results has risen from 5 to 6. This means that the extra home-buttons lowered the steps needed to accomplish the goals. B.14 Using the application is effortless: The results are evenly spread between 4, 5 and 6. This is an improvement over the spread results of this statement in the previous iteration and is probably also caused by the extra home-buttons. B.16 I don’t notice any inconsistencies as I use the application: This statement scored less than in the previous iteration. One explanation is that the incorrectbutton is confusing. 38
4.5. Paper prototype iteration 3
Figure 4.10: A boxplot representing statements B.9, B.12, B.14, B.16.
Ease of learning and satisfaction The ease of learning statements were again answered very positively. In figure 4.11 you can see the box plot representation of figure B.22: It is easy to learn to use the application. Most of the users gave a score of 6 out of 7, which is a very good result. We still believe that this is due to the iOS style. The general satisfaction of the application was good. In figure 4.11, you can see the answers to statements B.24, B.27 and B.29. B.29 I feel the need to have it and B.27 The application works the way I want it to work were both answered positively. The users felt the need to have it and were satisfied with how it works. B.24 I am satisfied with the application is the main indicator of satisfaction and received a median of 6. The lower scores of 4 and 5 are believed to be due to the confusing incorrect-button. In general, the experts were very positive about the application. Points of improvement were found, but there were no big problems besides from the incorrectbutton. Useful suggestions were made by the participants. Instead of creating a view per social network, the application could refer to the social network application on the smartphone or the website. Another extra functionality is the preview of the users overview, so that he can know how other users see his profile once they have recognized him.
Conclusion
In this chapter, a comparison has been made of the two biggest mobile platforms on the market, the iOS and the Android platform. They are both good platforms for mobile application development, with well-documented SDK’s, but the built-in real-time face detection of iOS proved to be a decisive aspect.
39
4. Design
Figure 4.11: A boxplot representing statements B.22, B.24, B.27, B.29.
A storyboard was made based on the functionalities of chapter 3, which focussed on the user interface of the face recognition. The face recognition would happen automatically and the information would appear next to the head in real time. However, there was a growing concern about pointing the phone to the face of the person the entire time. To analyse this, 3 user interfaces were built and evaluated using a paper prototype. The scenario’s offered other approaches to displaying the information about the recognized person. After evaluation it became clear that the latter one was preferred by a majority of the test users. A prototype with full screen information views was elaborated and evaluated with a settings, home and history view. The test users needed to perform tasks in order to explore the functionalities of the application and fill in a USE questionnaire. After processing the results, some adjustments were made to the prototype and it was tested again with a new set of test users: experts in the field of human-computer interaction. They performed the tasks and filled in the USE questionnaire and came up with some good remarks and ideas during the testing. In general the application was received well. The scores of the questionnaires were positive apart from some minor weaknesses. The application is now ready to be implemented and there is no need for another paper prototype evaluation.
40
Chapter 5
Implementation
In this chapter we will describe the implementation process of the final application. First, a general explanation will be given about the development environment. Secondly, the initial implementation will be explained, featuring the core functionalities of the application. This initial implementation has been evaluated and adapted into a second and more complete implementation. In order to develop for iOS, the Xcode1 development environment needs to be used. It has a library of default objects (like buttons, text fields, types of views,...) that can be used to build the views in a way that corresponds to the iOS human interface guidelines [44]. The use of this standard library allows the developer to create applications that look familiar to iPhone users, and are built with standard parts of which the users already know the function. The programming language of iOS is Objective-C. It is an object-oriented extension of C, designed to be simple and straightforward [47]. It supports a number of frameworks, collectively called Cocoa Touch.
5.1
Digital prototype 1 implementation
The first digital prototype focusses in the core functionality of the application: the face recognition. This consists of 3 parts: face tracking, face recognition, and the connection with Facebook. For this prototype, information from other social networks will not yet be implemented and the history and settings will consist of static data.
5.1.1
Face tracking
In order to track faces, the iOS face detection will be used. This functionality is part of the iOS Core Image framework, which is able to process real-time images and video. To implement the face detection, the application needed to have a camera view. Apple provides a basic class that registers the camera feed and allows the user to take pictures, the UIImagePickerController. This class is also able to
1
41
5. Implementation display overlays on the camera feed. However, this feature only overlays the user interface of the camera. The class was not able to process each frame coming from the camera feed and could not be used to augment each frame seperately. If the camera feed could not be processed, the face detection would not be able to scan faces. The class AVCaptureSession can be used to specifically coordinate the flow coming from the input source and going to the output source. It is able to intercept all frames from the camera feed, process them and output them on the screen. This class could be used along with the face detection.
User
CameraViewController User opens the camera view
CIDetector
loop
Frame gets intercepted by AVCaptureSession getFaceFeatures(frame)
return faceFeatures
draw boxes based on faceFeatures
Figure 5.1: A sequence diagram representing the face tracking process. To detect the faces and highlight them on the camera, the following steps need to be executed: 1. Each separate frame needs to be intercepted before being put out on the screen. 2. The frame needs to be sent to the Core Image Detector (CIDetector), which is the face detection class. 3. The CIDetector scans the frame for face features and returns an array with all faces found. 4. For each CIFeature, the position of the nose and eyes are given. Based on these coordinates, a box can be drawn around the face. 42
5.1. Digital prototype 1 implementation
(a) Low accuracy
(b) High accuracy
Figure 5.2: Example screenshots of the face detection.
5. The frame along with a box for each face is displayed on the screen. This process is repeated for each frame of the camera feed and is shown in the sequence diagram of figure 5.1. The face detection is not limited to a number a faces at a time. It will scan each frame and return as many faces as are found in the frame. It has 2 accuracy options, CIDetectorAccuracyLow and CIDetectorAccuracyHigh. These two settings were tested and compared using the back camera of an iPad 2. The low accuracy setting is faster but will only detect faces up to 2 meters. This can be seen in figure 5.2 (a). The detection happens smoothly, with only a small noticable lag when moving the camera fast. The high accuracy setting can detect faces from more than 4 meters away, as can be seen in figure 5.2 (b). However, enabling the high accuracy slowed down the tracking process. Upon moving the device, the camera feed instantly moved with it, but the face detection boxes had a bigger delay reaching up to 2 seconds. The extra distance does not compensate for the amount of delay, so the lower accuracy was chosen.
5.1.2
Face recognition
In section 2.1.2 a comparison has been made between different face recognition API’s. Face.com appeared to be the most suited to use, because of its link with Facebook, the size of its database, and the existence of an Objective-C wrapper. The Face.com API was thus linked to the project. Because Face.com only works 43
5. Implementation with images and not with real-time video, snapshots of the camera feed need to be taken and sent to the Face.com servers. In the paper prototypes, the recognition was done automatically, but in order to provide control over the requests to the Face.com server, a recognize-button is added to the camera view. This button takes a screenshot in the form of a UIImage that can be sent to the Face.com server. This recognize-button is a temporary addition and will be removed once the implementation is finished. The API has a built-in Facebook API in order to get the correct permissions for Face.com to check images from Facebook friends of the logged-in user. To request the recognition of faces from an image, the API requires a FWObject (FaceWrapperObject) to be created. This object requires a set of data in order to build the request in the background. The data consists of the following items: 1. A snapshot from the camera feed, whereof the server will try to recognize the faces. 2. A boolean to select between recognition or detection. This is set to recognition. 3. A boolean to activate the possibility to recognize Facebook friends of the logged-in user. This is set to true. 4. A list of Facebook ID’s to look for in the image. This is only required if the boolean above is set to true. To check for all facebook friends, the ID friends@facebook.com is required. The list of ID’s to check can be expanded by using a private namespace. As described in section 3.2, the proposed solution for the privacy concerns is to allow the application to recognize both Facebook friends and other users of the application. For the initial implementation, the list of people to recognize is limited to the Facebook friends of the logged in user. After filling in the data, the FWObject is sent to the Face.com server in a separate thread, so that the camera feed does not freeze when waiting for the reply. Face.com processes the image, and sends a reply in JSON format of all found and recognized faces. The JSON reply contains a list of faces, and for each face some physical characteristics and a list of potential matches along with the confidence percentage. The match with the highest confidence value is considered to be the correct person. In order to prevent false matches, the list is filtered to only allow matches above 50 percent. If no match is found with a confidence level above 50 percent, the label above the face will say Try again! and the user will have to recognize again by sending a new image. This will be tested to check how many false positives the application produces. The recognition process is shown in figure 5.3. When the reply has been analysed, the Facebook ID with the highest match is returned together with the name. The name is assigned to a label floating above the face as shown in figure 5.4(b). This is a naive implementation, resulting in the same 44
5.1. Digital prototype 1 implementation
User Actor presses recognize button
CameraViewController
FaceWrapper
Face.com
Frame gets saved as UIImage FWObject gets constructed detectFaceWithFWObject send request Recognize faces
return JSON Reply return JSON Reply
Analyze reply Set face-label
Figure 5.3: A sequence diagram representing the face recognition process.
name appearing above each face detected on the camera. If you have recognized one person, and point the camera to another one, the first person’s name will still appear above the new face. To avoid this, the user should press the recognize-button again in order to discover the identity of the new person. This naive implementation will be used for now, but the algorithm will be improved. Furthermore, the application should be able to recognize multiple persons at a time. Face.com sends a reply containing all persons recognized in the image. The problem with assigning the correct label to multiple faces is that the face detection, as explained in the previous section, searches for faces on each frame. It is not able to say that a face in one frame will be the same face in the next frame. While the application is waiting for the Face.com reply, the people present in the scope of the camera could have traded places, or could be completely different persons. An extra algorithm should thus be implemented to keep track of each face, from the moment that they appear in the scope of the camera, until they disappear. The location of each face should be stored and compared to the location of the faces in the next frame in order to know which face belongs to which.
5.1.3
Connection with Facebook
When the face is recognized, the user should be able to press the box surrounding the face to get more information. The box needs to be clickable from the moment the face is recognized. Because the face gets detected each frame, the box surrounding the face is also redrawn again each frame. To make the box clickable, a button 45
5. Implementation
(a) Facebook login
(b) Camera view
(c) Overview view
Figure 5.4: The different views of the first prototype.
was created with the same size and location as the box and made invisible. The location of the box shifts each frame, so the button needs to be updated and redrawn as well. This redrawn process implies that the button is removed from the view, and recreated at another location. As this happens each frame, the timeframe in which the button exists is short. This causes a difficulty when pressing the button. This behaviour will be evaluated in the user tests. When the box is clicked, all information about the recognized person should be gathered. In this iteration, we focus only on Facebook information. Since Face.com returns Facebook ID’s, Facebook is the ideal starting point to gather information. In order to get more than just the ID, we needed to link the Facebook Graph API2 to the application. Facebook has released an Facebook iOS SDK, created specifically to link applications on iPhone and iPad to Facebook. It is written in Objective-C and grants the developer access to the Facebook Graph API [53]. The Graph API represents each person, event or page as an object with a unique ID. Information about the object can be accessed by sending a request to followed by the ID. For instance, to get information about ID 1283752014, the request should be:, which returns the following JSON object: { "id": "1283752014", "name": "Gerry Hendrickx", "link": "",
2
46
5.2. Digital prototype 1 evaluation "username": "gerry.hendrickx", "gender": "male", "locale": "en_US" } Since Face.com returns the Facebook ID’s of the recognized persons, this ID can directly be used in combination with the above URL to get basic information about the persons. The view with this information from Facebook can be seen in figure 5.4(c). When a request to Facebook is sent and there is no logged in user, the API will display a window to log in to Facebook (figure 5.4(a)).
5.2
Digital prototype 1 evaluation
The application was evaluated by 5 test subjects. The group of test users consisted of 3 men and 2 women, all between the age of 20 and 23. 4 of them were experienced smartphone users, whereof 3 owned an iPhone and one had iOS experience. 1 person did not have any smartphone experience which gave us some insight about whether the lack of experience had an influence on the usability of the application. All smartphone users had used an AR application before and were familiar with the concept. 2 of the smartphone users were already part of the second paper prototype tests. The tests focussed on the face recognition functionality. The goal was to check the user interface of the camera view and the correctness and robustness of the recognition process. This users were given a list of tasks to execute: 1. Start the application and recognize the evaluator of the usertest. 2. Find out more information about the evaluator. 3. Go to his Facebook profile. 4. Try to recognize yourself. For the tests, the evaluator was logged in to the application with his Facebook account and the recognition algorithm was trained by his Facebook friends. When you train Facebook friends on Face.com, the service will use your logged Facebook account to scan the tagged photo’s of your friends and add these scans to its database. This is necessary in order to be able to recognize the faces of friends, but is not yet built into the application. Also, all test users were Facebook friends of the evaluator and should thus be recognizable during the tests. The think aloud method was used once again to get a clear view on the user’s perception.
5.2.1
Results and discussion
The outcomes of the evaluation are discussed below and present the problems and remarks: 47
5. Implementation 1. After the users pressed the recognize-button, the reply from Face.com was received after an average of 8 seconds with extremes of 5 to 15 seconds. It is believed that the variations are due to the quality of the wireless internet connection and load on the Face.com servers. 4 out of 5 test users immediately had a correct match for the evaluator, while the other user did not receive a match with a confidence above 50 percent. The Try again!-label appeared and the user was able to restart the process. Because the label stays visible until Face.com sends a new reply, there was some confusion about whether or not the reply arrived, or if Face.com failed again to recognize the face; in which case the label would stay in its place. This resulted in the user repeatedly pressing the recognize button. He suggested some sort of status information about what was going on in the background. Eventually, Face.com replied with a correct match for the evaluator. 2. In order to get more information about the evaluator, the users needed to tap in the box surrounding his face on the camera view. The redrawing of the button for each frame indeed caused the button to be not clickable most of the time. Every test user tried to tap the face, but nobody was able to do this in their first try. This made them hesitate whether they are supposed to click the name or not. After the attempt to click the name also failed, the evaluator helped and told that they should press inside the box. After multiple tries, all of them eventually succeeded in clicking the button. Every user commented that this needed to change in order to make the click action discoverable. 3. In order to recognize themselves, all users pressed the button to change the view from the back camera to the front camera, instead of turning the back of the phone towards them. After they pressed the recognize-button again, the application crashed. After restarting the application, the users tried to recognize themselves. 3 users immediately received a correct reply and were able to check the information found about themselves. During the tests, only one person received an incorrect name. This means that Face.com matched the face to the face of another person with a higher confidence value than the match with his own face. Checking the logs revealed that the wrong name had a confidence percentage of 54%, while the correct name had a confidence percentage of 53%. This can be caused by overexposure of the camera feed while pressing the recognize-button.
5.2.2
USE questionnaire
The users were once again asked to fill in the USE questionnaire. The full results of the questionnaire are given in appendix C. We will discuss the general score of the 4 categories and examine some noteworthy results. The statements were rated from 1 to 7, with 1 being totally disagree and 7 being totally agree. The discussed statements were selected because of their importance in their respective categories. 48
5.2. Digital prototype 1 evaluation Usefulness In general, the usefulness statements scored well in the questionnaire. It appears that the test users generally perceived the app as useful. Some answers to the statements are displayed in figure 5.5. C.2 The application helps me be more productive, C.3 The application is useful and C.5 The application makes the things I want to accomplish easier to get done were all answered very positively.
Figure 5.5: A boxplot representing statements C.2, C.3, C.4, C.5, C.7.
C.4 The application gives me more control about the activities in my life: Once again this question scored lower in comparison to the other usefulness questions. The answers ranged from 3 to 5, with a median of 5. This is still considered to be due to the nature of the question, which the app does not aim to fulfil. C.7 The application meets my needs: A median of 5 but with one extreme of 1 given by the non-smartphone user shows that the application meets the needs of the smartphone users, but fails to be felt as needed by non-smarphone users. Because they don’t own a smartphone, they are not familiar with what applications can contribute to their life. Ease of use The ease of use of the application received high scores with the smartphone users but a low score from the non-smartphone user. This could be due to the iOS-style of the application, to which the smartphone users are used, but is new to the inexperienced user. The discussed statements can be seen in figure 5.6. C.9 The application is easy to use: The experienced smartphone users did not find any difficulties in using the application, but there was some kind of entry barrier for inexperienced users, that could be due to the knowledge required to work with iOS or due to the difficulty of clicking the button on a face. 49
5. Implementation
Figure 5.6: A boxplot representing statements C.9, C.12, C.14, C.16.
C.12 The application requires the fewest steps possible to accomplish what I want to do with it: The general flow to get from starting the application to information about a recognized person requires only 3 clicks. However the difficulty in clicking the face affected the results. C.14 Using the application is effortless: The application seems effortless to use, although we are surprised that the cumbersome clicking on the face did not cause this statement to score lower. C.16 I don’t notice any inconsistencies as I use the application: This statement obtained some lowers scores due to the clicking on the face and confusion upon trying to recognize again after a bad reply. Ease of learning and satisfaction The ease of learning statements were answered very positively. None of the ease of learning questions received a score below 6. In figure 5.7 you can see the box plot representation of statement C.22: It is easy to learn to use the application. The general satisfaction perception had to deal with an extreme low, again due to the user with no smartphone experience. However, C.27 The application works the way I want it to work received positive results. In figure 5.7, you can see the answers to statements C.24, C.27 and C.29. C.24 I am satisfied with the application: This statement is the main indicator of satisfaction and received a median of 5. This is lower than the score in the last paper prototype, and can be the result of the presence of some bugs, the cumbersome clicking on the button and the lack of information about the background processes. 50
5.3. Digital prototype 2 implementation
Figure 5.7: A boxplot representing statements C.22, C.24, C.27, C.29.
C.29 I feel the need to have it: This statement is one of the lowest scoring statements. Most users think it’s a nice-to-have application, but there is no strong need to have it. In conclusion, the first digital prototype obtained some positive results. The questionnaire showed that the application was perceived as useful and easy to use for iPhone users. All users thought that the application was easy to learn, but were not completely satisfied with it. The digital prototype will now be adapted and further elaborated to include the settings and history, and support information from more social networks.
5.3
Digital prototype 2 implementation
For the second digital prototype, the first prototype is adapted from the comments of its evaluation and new features are implemented. The adjustments resulting from the evaluation are: • The button on the face to go to the overview of a recognized person should be improved to make it clickable at each try. • Status messages should be provided to keep the user updated with the background processes of the application. This way they know whether the application is waiting for a reply or received and displayed the same response. The features that will be implemented are: • Social network settings: a view where the user can link the application to his social networks. • A history view: displays a list of recognized people. 51
5. Implementation • A settings view: the user can adjust some settings of the application. • Training possibility: to allow the logged in user to train the Face.com algorithm with his Facebook friends. We will now describe the implementation of the adjustments to the previous prototype and the new functionalities.
5.3.1
The face button
Due to the implementation of the button that allows users to click on a recognized face, the button failed in recognizing the touch as a click nearly 80 percent of the time. The cause for this is the redrawing of the button upon each frame. Since the button was removed and re-instantiated multiple times per second, the time frame in which it was clickable was far too short. This problem is solved by not removing the button each frame, but simply move it accordingly with the face on the new frame. This way, the button stays located at the same place until the new location of the face is established and it remains clickable at all times.
5.3.2
Status messages
Upon receiving a reply from Face.com with no matches with a confidence level above 50 percent, the Try again!- label is shown. When the users tried again, they were unsure whether the request was still busy, or whether Face.com gave another bad reply, meaning the label would stay in place. In order to prevent such confusion, the camera view was adapted to support and display labels. These status messages are updated whenever a new phase in the recognition process is reached. Table 5.1 displays which message is shown at what time. Phase Entering the camera view After pressing the recognize-button After receiving a bad reply (< 50%) from Face.com After receiving a good reply from Face.com Message Tracking faces. Click recognize. Recognizing faces... Please wait. Recognized 0 faces. Try again. Recognized 1 face.
Table 5.1: List of status messages on different phases of the recognition process. The evaluation of the prototype will reveal whether the status messages are readable and well placed. A screenshot of the camera view with status messages can be seen in figure 5.8 (a).
5.3.3
History view
The history view was introduced in the second paper prototype and positively received by the test users. However, the style used in the paper prototypes was not the 52
5.3. Digital prototype 2 implementation
(a) Camera view
(b) History view
(c) Settings view
Figure 5.8: The different views of the second prototype.
standard iOS way of interacting with a list of people. The gesture used to remove users (long-pressing until the pictures wiggle and pressing the X-icon) is not used in iOS applications. Therefore the design of the history view switched to the standard iOS tableview, a view designed specifically to show dynamic lists, allowing direct removal of an item of the list by using the standard iOS swipe gesture. An example can be seen in figure 5.8 (b). The HistoryTableViewController-class is created to display the list of previously recognized persons. This is a direct subclass of the TableViewController-class, and thus uses the same memory efficient way of displaying long lists. Such a class requires a datasource, where it fetches the data displayed in the list. This datasource is an NSArray which is saved in a persistent way in the application data storage, the NSUserDefaults. When a user accesses the overview view of a previously unrecognised user, this array gets updated with the new RecognizedPerson-object. When loading the history, the array gets pulled from the NSUserDefaults and shown in the tableview. Each item in the table is made clickable and opens the overview view of that recognized person.
5.3.4
Settings view
The settings of the application are limited in this iteration to some useful options. A SettingsViewController-class has been made, linking the buttons on the settings-view with the underlying functionality. The settings view can be seen in figure 5.8 (c). We’ve implemented the following settings: Open in camera mode This switch allows the user to select whether or not he 53
5. Implementation wants to start the application in camera mode, meaning it will skip the homeview and go straight to the camera-view. This allows the user to eliminate one click in order to use the face recognition. The setting of the switch is saved in the NSUserDefaults and checked upon starting the application. Log out of Facebook This button calls the Facebook API and logs the user out of Facebook. The saved authorization token is removed from the NSUserDefaults. This setting is useful when another person wishes to try it with his Facebook friends. When the next request to Face.com or Facebook is sent, the application will ask the new user to log in. Train Facebook friends This setting is important to new users of the application. In order to recognize their Facebook friends through Face.com, Face.com needs to be trained with their pictures. This settings constructs a request to the Face.com API with the command to train the ID friends@facebook.com. A notification is displayed when the training process has completed.
5.3.5
Support for multiple social networks
In order to comply to the goal of the application to offer efficient discovery of digital identities, the users should be able to discover information of the recognized person from multiple social networks. We have decided to use the back-end system that the More!-project (discussed in section 2.3.1) is using. This is an open-source web-app that uses a database to store social network handles. The database structure is based on the iTEC person data model [54], which is a data model constructed to describe persons in a database. The More! back-end provides a RESTful API, so the request can be done via HTTP GET or POST messages. It supports requests to fetch the social network handles of a person by providing the ID used in the system as a parameter. The application uses Facebook ID’s as identifiers throughout the application, so these ID’s will also be used as key identifiers in the database. When a user recognizes a person, he will arrive at the overview view. It’s controller, the OverviewTableViewController, will send a HTTP-request to the web service upon opening the view. When the reply is received, the available handles are parsed and the table is updated with links to the recognized persons profile on the found social networks. An example of the updated overview view can be seen in figure 5.10 (b). The back-end should be able to add new persons and their social network handles. The application needs to allow the users to link their handles to the user account in the application. A new view/controller pair is made to fulfil this requirement, the networks-view and NetworkViewController-class. This view can be seen in figure 5.10 (c) and supports handles of Twitter, LinkedIn, SlideShare and Google+. These networks are chosen based on table 3.2 in section 3.1.3. The list of supported social networks can be extended. If users want to link their social networks to their profile in the application, they need to fill in the respective textfields. When leaving the 54
5.3. Digital prototype 2 implementation
User
OverviewTableViewController
FBRequestWrapper
Database
User clicked on recognized face.
NSURLConnection initwithrequest:request getFBRequestWithGraphPath: facebookID Facebook request Facebook reply Facebook reply tableview.reloadData Database reply tableview.reloadData
Figure 5.9: A sequence diagram representing the information fetching process.
(a) Home view
(b) Overview view
(c) Networks view
Figure 5.10: The different views of the second prototype.
networks-view, the database will be updated with their handles and the overview view of the user will show the new networks (figure 5.10(b)). The More! back-end did not support adding persons and handles to the database. A new set of methods were written to enable making these additions directly from a HTTP-request. The complete process of fetching data for a recognized person is shown in the sequence diagram 5.9. The figure shows that the table gets reloaded twice: when Facebook replies with the Facebook-information and when the database replies with the social network handles. 55
5. Implementation
5.4
Overview of classes
iOS development is focussed on the model-view-controller pattern. In this programming pattern, you separate the user interface (the views) from the rest of the code (the controllers and the models). The view interacts with the controllers upon user interaction and the controller uses data from the model classes and interacts with other controllers. A schematic overview of the pattern can be seen in figure 5.11.
Figure 5.11: The Model-View-Controller pattern. [50] A brief overview of all created classes and their function is given below. Each controller class has its own respective view, which will not be discussed separately. Appendix E shows a class diagram displaying the relations between the classes. Figure 5.12 presents the screen transition diagram, which shows the links between the views.
Social network settings Settings Home open application Home Home Recognize History Home Home Tap on face Camera Camera Settings
Settings
Networks
History
Click on name History
Overview
Figure 5.12: The screen transition diagram of the application
SocialRecognizerViewController This is the class corresponding to the home view and can be seen in figure 5.10(a). The class serves as a pass-through class 56
5.4. Overview of classes from where most other views are reachable. It has limited functionality, but provides the link with the Facebook API, in order to log the user in before he uses the application. The Facebook pop-up will appear if the correct tokens are not found and the user can log in. These tokens will be stored in the NSUserDefaults. After logging in, an initial request will be made to Facebook to fetch the friend list of the logged in user. This list, with each friend’s name and ID is used with each recognition, in order to look up the ID and get the name without making an additional request to Facebook. CameraViewController This is the core class of the application. It implements the AVCaptureSession and has the camera view as it’s view. It contains the methods to detect the faces as described in section 5.1.1 and implements the recognize-button from the camera view. Upon clicking this button, the recognize-method is called which stores the current frame as an UIImage and constructs the FWObject as described in section 5.1.2. A callback method is implemented that receives the Face.com reply and filters the results based on the confidence percentage. The label is drawn above the face and the face becomes clickable in order to navigate to the overview view of the recognized person. A button to switch from the front to the back camera is also created in the UI, to allow the user to use both camera’s of the iPhone. An algorithm to draw the labels in the correct position for each orientation of the phone is also implemented in this class. OverviewViewController This controller manages the overview view of a recognized person. It requests information about the recognized ID and stores this information in a RecognizedPerson-object. It is a subclass of a UITableViewController, which is the standard iOS way to display data. It presents general information about the recognized person, along with links to his social networks. This link opens the application of the network instead of giving an overview of his profile in the application itself as suggested in section 4.5.1. FBRequestWrapper This class is a singleton class that handles all calls to the Facebook API. It has the functionality to log in and log out from Facebook and send requests to the Facebook Graph. The class is able to store the token provided by the API in a collection to store all user-dependant settings, the NSUserDefaults. The choice to use a singleton pattern to implement the link to the Facebook API, is based on the requirement of multiple classes to interact with Facebook. UserModel This is a model class used to store data. The class stores information about the currently logged in user of the application. For this iteration it stores the name and ID of the current user, along with a map of his friends, containing the ID’s and the full names. This map is filled upon starting the application, when the request is made by the SocialRecognizerViewController. RecognizedPerson This class is also a model class, containing information about the recognized person. It stores the information received from the request to 57
5. Implementation the Facebook graph and is used by the OverviewViewController to fill it’s table with data about the person. NetworksViewController This class allows users to fill in their social network handles. After leaving the networks view, the web service will be called to update these handles in the database. HistoryTableViewController This class fetches the list of recognized people from the NSUserDefaults and displays them in a standard iOS table view. SettingsViewController This controller is linked to the settings view and implements all the settings of the application. It offers the functionality to open the application in the camera view, to log the current user out of Facebook and to train Face.com with the friends of the logged in user.
Conclusion
This chapter described the implementation of the digital prototypes. A first prototype was created with the functioning core of the application: the face recognition. The prototype featured face tracking, face recognition and an overview of the information of the recognized person. The face tracking is implemented by using frame-per-frame analysis of the camera feed, with each frame being sent to the built-in face detection of iOS5. A recognize-button was added to allow the user to choose when he wants to start the recognition process. When the button is clicked, a snapshot of the camera feed is taken and sent to Face.com, along with some other parameters that define the request. When the reply is received, it is analysed to see whether there are matches with a confidence above 50 percent. If this is the case, the face is labelled with the match that has the highest confidence value. If this is not the case, a Try again!-label is shown. When the face is recognized, it becomes clickable and refers to the overview view, which shows basic Facebook information along with a link to the recognized person’s Facebook profile. This prototype was evaluated by 5 test persons. In general it was received positively, but the same remarks were given by each test person. The prototype was adapted and featured new views: the history-view, the settings-view and the networks-view. To support the discovery of multiple networks, a web application and a database was set up in order to store the social network handles of the users. When a person gets recognized by another user, the application will request the handles from the service and display them in the overview view of the recognized person. The final application will be tested and evaluated in the next chapter.
58
Chapter 6
Evaluation
This chapter presents the evaluation of the final application. The evaluation will follow the same structure as previous prototype evaluations and will assess whether the final application has reached it goals.
6.1
Methodology
The tests are split up into 2 parts: first the test users will have to fulfil a number of tasks. Secondly, one of the test subjects is given the task to use the application in a real-life environment and a comparison is made of the time it takes to discover the digital identity of a person with and without the application, in order to check if the application has fulfilled its goal. After the tests, the users were asked to fill in a USE questionnaire. The final application as described in section 5.3 was evaluated with 12 test subjects. The group of test users consisted of 10 men and 2 women, between the age of 20 and 25. All men had considerable smartphone experience and have worked with an iOS device (iPhone or iPad). The 2 women have no smartphone experience. 4 of the smartphone users have already tested the previous digital prototype. The test users need to complete the following tasks: 1. Recognize the evaluator and look for information about him. 2. Find a way to start the application in camera mode. 3. Find details about a certain person which you have scanned before, but is not around at the moment. 4. Delete this person from the history. 5. Alter the Twitter ID of the logged in user and check to see if the alterations have worked. 59
6. Evaluation These tasks are designed in a way that makes the user discover the full functionalities of the application. During these tasks they have to apply the think aloud-technique.
6.2
Results and discussion
The results of the tasks are discussed below: 1. As in the first digital prototype the home view was clear to all users. Once they arrived in the camera view, the notification Tracking faces. Click recognize. was displayed, but only 6 out of 12 users mentioned that they read it or followed its instructions. 3 of the users that did not read the notification were impatient and pressed the recognize-button again before Face.com had sent a reply. When asked why they had neglected the notifications, 4 users answered that the font size was too small and 2 said that the red colour was not visible enough. The 6 users who did pay attention to the notifications, said that the notifications guided them and the users received them very positively. The 4 users who tested the previous digital prototype also expressed that the notifications were a big improvement. We conclude that the notifications are a positive improvement, but that they should be displayed in a clearer way. The recognition succeeded in the first try with 11 of the 12 test users. The 12th user received the Try again!-label and after trying again, he received a correct recognition. Again, the recognition failed due to overexposure of the camera. After the recognition, all users pressed the face and arrived in the overview view. The 4 test users that had tested the previous iteration, noticed the improvement of the face-button. 2. No problems were experienced with the start in camera mode-button. After restarting the application, the users saw the effect of this settings and they all thought this was useful. It eliminates one click to get from starting the application to recognizing a person. 10 out of 12 users preferred camera mode to be enabled by default. 3. Due to the use of a standard iOS gesture (swipe over the name and a deletebutton appears) all experienced iOS users completed this task without problems. The 2 inexperienced users needed help to find this somewhat hidden feature. An edit-button that provides an alternative way to edit the lists might make it more clear for inexperienced users. 4. In order to alter the Twitter ID of the logged user, the users needed to find the networks view. Once arrived in the networks view, they all succeeded in altering the Twitter handle. In order to test the changes, they needed to return to the camera and recognize the evaluator (because he is the logged in user). A bug was found regarding the time to update the database. It should be noted that while loading the overview view, the request to the database timed out for about 20% of the time, which is also an issue that need to be looked at. 60
6.3. USE questionnaire
6.3
USE questionnaire
The users were once again asked to fill in the USE questionnaire. The full results of the questionnaire are given in appendix D. We will discuss the general score of the 4 categories and examine some noteworthy results.
6.3.1
Usefulness
The responses reflect a perceived usefulness of the tool. Some answers to the statements are displayed in figure 6.1. D.3 The application is useful, D.5 The application makes the things I want to accomplish easier to get done and D.7 The application meets my needs were received positively. It seems that the application is considered useful and meets the needs of the users.
Figure 6.1: A boxplot representing statements D.2, D.3, D.4, D.5, D.7.
D.2 The application helps me be more productive: We conclude that the app indeed helps the users be more productive. As proven in section 6.5 the application saves time when trying to find the social networks of a person. If we compare the scores to the previous prototype, we see that the median has remained at 5 out of 7. D.4 The application gives me more control about the activities in my life: The scores of this statement were lower but this is again considered to be due the nature of the question.
6.3.2
Ease of use
The application scored excellent on most ease of use statements, but considerably lower on some of them. The discussed statements can be seen in figure 6.2. D.9 61
6. Evaluation
Figure 6.2: A boxplot representing statements D.9, D.12, D.14, D.16.
The application is easy to use and D.14 Using the application is effortless received positive scores. The application seems to be considered as easy to use. D.12 The application requires the fewest steps possible to accomplish what I want to do with it: With the face button fixed in this iteration, the score for this statement has risen. The flow of the application seems to be experienced as good by the users. D.16 I don’t notice any inconsistencies as I use the application: The median of this score has lowered from 6 to 5 compared to the previous iteration. This can be due to the database server that timed out occasionally, which caused the overview view to display only Facebook at some times, and all networks at other times.
6.3.3
Ease of learning and satisfaction
The ease of learning statements were again answered very positively. In figure 6.3 you can see the box plot representation of figure D.22: It is easy to learn to use the application. The scores range from 6 to 7 with a median of 7. This is an excellent score. It seems that the notifications caused the scores to rise in comparison to the previous iteration. The satisfaction statements did not score as great as the ease of leaning questions, but still received some good ratings. In figure 6.3, you can see the answers to statements D.24, D.27 and D.29. D.27 The application works the way I want it to work was well received. The users think the application indeed works how they want it to work. D.24 I am satisfied with the application: The median of this statement has risen since the previous prototype. It seems that the users feel more satisfied with the application at this stage. This is thought to be caused by the new functionalities 62
6.4. Real-life testing
Figure 6.3: A boxplot representing statements D.22, D.24, D.27, D.29.
like the settings, that allow the users to tweak the application to their liking and the history that enables them to look up information from previous recognitions. D.29 I feel the need to have it: With a median of 5 and most scores between 4 and 5, this statement is one of the lower rated statements. This could be due to the privacy and disturbance issues. Using the application makes other persons uncomfortable, which could have caused this lower score.
6.4
Real-life testing
In order to test the real-life usefulness of the application, the application was given to a test user along with the task to try it out in the real world, in an uncontrolled environment. This test will provide insight in 2 mayor points: how the recognition process is received by people who aren’t familiar with the application and how the test subjects use and experience the application after a more extensive period of time. The test subject tested the application in a school environment, where he tried to recognize 4 persons. He logged in to the application with his own Facebook account and trained his friends via the button in the settings-view. This way he was able to recognize all his Facebook friends. When he found a friend to be recognized, he told him he was testing a new application and asked if he could try it. When they agreed he pointed the iPhone to their faces and recognized them. 3 out of 4 were immediately correctly recognized. The 4th one is believed not to have succeeded because of bad lightning circumstances. During the recognition process, the iPhone was kept pointed to their faces. This made them feel uncomfortable, because they thought he was filming them or taking pictures. When he afterwards showed them that they were recognized, they were stunned but not enthusiastic. When he told them that no pictures were saved, and that the application only provided information 63
6. Evaluation about them because the test user was their Facebook friend, they were a bit more relaxed. However, the general feel of the application with people that aren’t familiar with it, is uncomfortable. People do not like being kept in the frame of a camera, and are very attached to their privacy. The test subject expressed that due to the duration of the recognition process, the recognition can not be done in a subtle way and will always cause an uncomfortable 10 seconds, especially when tried on strangers.
Subject Started Recognition Time to time reach Twitter WA 11.3s 20.9s 10.4s 28s 31s 71s 10.4s 17.8s 8.8s 15.4s 14s 29.5s 12.3s 18s 8.3s 13s 7.8s 17.3s 15.6s 27.4s 10.2s 15.9s 10s 19.8s 12.508s 24.5s Time to reach LinkedIn WA 32.5s 38s 83.3s 25.2s 22.9s 44s 28.6s 21.3s 27.8s 39.3s 23.8s 30.5s 34.766s Time to reach Twitter WOA 42.3s 62s 47s 30.7s 55s 37.9s 45.7s 30.2s 35s 54.9s 24.1s 29.3s 41,175s Time to reach LinkedIn WOA 89.2s 129s 95.4s 62.4s 112.8s 73s 82s 67.4s 79.2s 128.1s 56.8s 49s 85,358s
1 2* 3 4 5 6 7 8 9 10* 11 12 Average
WA WA WA WA WA WA WOA WOA WOA WOA WOA WOA
Table 6.1: Table representing the times to discover social networks with the app (WA) and without the app (WOA).
6.5
A/B testing
The main goal of this thesis is to enable efficient discovery of digital identities through face recognition by using smartphones. In order to test whether this goals is achieved, the test persons were asked to fulfil a simple task with the application, and without the application. The task is split up in several parts. The first 6 test users start with the application and need to recognize the evaluator. After the recognition, they need to go to his Twitter profile and try to follow him. When this is done, they need to go to his LinkedIn profile and try to connect to the evaluator. Afterwards, the evaluator gives them the social networks handles of his Twitter and LinkedIn account verbally and they need to use the standard applications to look him up. This is a simplification of the normal discovery process, in which the user needs to look for the handles themselves (by i.e. using Google). The second part of test users starts without the application, and finished with the application. When asked for a preference, all users preferred the application above the manual lookups. The manual lookup was perceived as inefficient and all users found the application to be 64
6.5. A/B testing faster and more fun to use. There is no bias based on which application they started with. The duration of the task will be recorded and compared. The time it takes will be a measurement for the efficiency of the application.
Figure 6.4: A graph representing the average time to discover a persons networks with (WA) and without (WOA) the application. Table 6.1 shows the results of these tasks. There are no apparent differences between the users who started with the application and the users who started without. All users preferred the application above the manual lookups. Test subject 2 and 10 (marked with the * in the table) are the 2 users with no smartphone experience. They were expected to need more time to complete the tasks. Test subject 3 had trouble recognizing the evaluator, and this was caused by Face.com. At the time of testing, their servers were overloaded and took much longer to respond. The table also contains the average time to complete all tasks which is plotted in figure 6.4. The figure shows that there is an initial time to recognize the face (in average around 12 seconds), and subsequently a constant time per network that is visited (in average around 10 seconds). Without the application, each network needed to be visited manually, by opening the application of the network, entering the handle of the person that you’re looking for, and going to his profile. This lookup takes around 40 seconds per network. Our application has proven to be a lot faster than a manual lookup.
Conclusion
This chapter described the final evaluation of the application. The application was tested with 12 test persons. They needed to complete a number of tests to examine 65
6. Evaluation the usability of the application and discover the functionalities in the application. The notifications in the camera view were found positive, but for some of the users not visible enough. They should be adapted in a way that makes them clearer but that does not clutter the camera view. The settings view was found easily and the settings were clear to the users. The history was seen as a positive feature and the gesture to remove items from the history was found by the users with iOS experience, since this is a standard gesture to delete a row from a tableview. The linking of the application to the user’s social networks was also obvious for most users, although they did not always know what their handle was for some social networks. This could be prevented by instead of using handles, logging them in to the different networks so the application is authorized to lookup the handle for them. This also prevents users from providing false handles. The application was tested in a real-life situation, with people who weren’t aware of the goal of the application. The 4 persons that were recognized felt uneasy because the camera needed to be pointed to them for about 10 seconds. They also had privacy concerns, but once explained that the information was only visible because the application was being used by one of their Facebook friends, they felt more relaxed. Furthermore, the time it takes to get to the social networks of a person with and without the application was tracked. The application requires a 12-second timeframe in order to recognize the person but afterwards, via the direct links in the overview view, the discovery of the recognized person’s networks was faster than a regular method. We can conclude that the application enables the users to efficiently discover a person’s digital identity. The USE questionnaire was filled in by the 12 test users, and the results in general were good. The application was received as usefull, easy to use, easy to learn and the users were partially satisfied.
66
Chapter 7
Conclusion
7.1 Thesis summary
The goal of this thesis was to create an efficient way to discover the digital identity of a person by using face recognition on a mobile device. This covers 2 different topics: face recognition and social network aggregation. Chapter 2 studied the possibilities and related work of face recognition on mobile applications and how social networks can be aggregated. It also looked at augmented reality to determine different possibilities on how the application could display the information of a person. After researching about these aspects, a brainstorm and survey were presented and discussed, which lead to the functionalities that the application should implement. The application should be able to fetch information from different social networks of a person in real-time and use augmented reality to display this information on a camera view of the smartphone. Other functionalities, like a history of recognized people and settings, were also introduced by the analysis. We designed the application based on a rapid prototyping approach with frequent user feedback cycles. The first 3 cycles consisted of paper prototypes. 3 user interface mock-ups were created, displaying different ways to visualize the information of the recognized person. The chosen user interface was elaborated and evaluated again, which uncovered some navigation and visualization problems. After adjusting the prototype to the remarks of the users, a third prototype was evaluated and besides some minor issues, received positive by the test users. The implementation of the application was performed in 2 iterations. The first prototype focussed on the core functionality: the face recognition and was evaluated. This evaluation again uncovered some navigation problems, to which the application was adapted. The second and final prototype consisted of a fully functioning application. This was evaluated on its usability, its usefulness and its efficiency. The result of this thesis is an application that is able to recognize people and offer 67
7. Conclusion efficient access to their digital identities. It uses the Face.com API as face recognition algorithm, which proved to be reliable and efficient. The application is linked to the Facebook API in order to provide some basic information of the recognized persons. Some aspects of the application found their origin in other projects. The face tracking process, which implements the iOS5 built-in face detection, was based on the SquareCam-project [51]. This is an example project provided by Apple to demonstrate the use of the face detection. The link with Face.com was provided by the FaceWrapper project [52]. This is an iOS wrapper for Face.com that provides the functionalities to request face recognition for images and train the algorithm with Facebook friends. The web service and database are the same as used for the More! project and were adapted to be used with our application.
7.2
Goals
Section 1.2 introduced a number of goals that this thesis wanted to accomplish. We now discuss whether the application satisfies these goals. Use a stable and reliable face recognition algorithm After comparing several face recognition API’s in section 2.1.2, Face.com was chosen as face recognition service. During the testing of the digital prototypes, it proved to be a very stable and reliable service. The confidence percentages allowed us to filter the reply and the application succeeded most of the times in matching a correct name to a face. It’s method of 3D reconstruction only fails when the image is overexposed. However, if lighting conditions are good, Face.com will provide a correct match. The Face.com database is based on tagged Facebook images and thus provides a big and easily expandable set of trained faces. Find a proper way to visualise the information Multiple prototypes, both paper and digital, have been evaluated to ensure that the user interface of the application was clear and usable for users. The design followed the iOS user interface guidelines, so that user interaction would be familiar. The final USE questionnaire provided good results and leads us to the conclusion that the users are satisfied with the design of the user interface. Discovery of digital identities should be efficient In the last evaluation, we compared the time it took to visit 2 social networks of a user by using the application versus manually looking for his profile on these networks. The goal stated that the application should grant easier access and be less time consuming than the manual lookup. The comparison showed that, although the application consumes around 12 seconds of this task on the recognition process, the discovery was still much more efficient. It should be noted that although the application has met its goals, it is not as useful as we expected it to be. This is due to the cumbersome way of recognizing a person. Aiming the phone to the person and holding it up until the recognition 68
7.3. Reflection process has finished, caused a 12 second time frame that was uncomfortable for both the user and the recognized person. The application would be less inconvenient if it only took a fast snapshot of the person, so the phone would only need to be pointed to the person for a quick second.
7.3
Reflection
If we take a critical look at the project, we see some positive and negative points. We are very satisfied with the end product. The final application has met all of its goals and is a fully functioning face recognition application. It can be used to easily find the networks of friends, but it is open enough to be used in an academic context as well. Although the application currently only supports a limited amount of social networks, it can be expanded to support many more without a big effort. If social networks with an academic focus like Mendeley would be supported, the application would have potential as a research 2.0 app. We must state that the final application is not the fully augmented application that we envisioned at the start of this project. This is mainly because of the usefulness. Even now, with the application requiring to point the phone at the person for 12 seconds, it is perceived as uncomfortable. The envisioned idea would require the phone to be pointed at all times. Due to the use of short iterations, we have noticed this early enough and this resulted in a more useful application. However a fully augmented could work with a different hardware setup, like head-mounted displays. Although the final result covers most of the required functionalities, the application can still be improved (see the following section). We did not manage to implement all the functionalities. This is due to the problems that occurred during the implementation. iOS development was new to us and we’ve lost a serious amount of time by figuring out how everything works and how certain objects are meant to be used.
7.4
Possible future work
The development of the application was prioritized to ensure all necessary functionalities were implemented. In order to improve the application, some lower priority tasks could be implemented: Bug fixes Several known bugs should be fixed, the biggest being the bug that crashes the application when trying to recognize a second person. Other known bugs include the occasional timing out of the database request, and the crashing of the application when the user returns to the networks view before the database has processed the request. Improving the face recognition process The face tracking algorithm described in section 5.1.2 should be implemented in order to recognize multiple persons at the same time. The face recognition should also happen fully automatically as it was envisioned in the paper prototypes. 69
7. Conclusion Photo-based recognition Instead of improving the face tracking algorithm, we can choose to remove the augmented camera view of the application and work with pictures instead. If the application only requires the user to take a picture of the person he wants to recognize, the uncomfortable moment during recognition will disappear. Authentication from social networks At the moment, the application allows the user to fill in handles for his social networks. This way he can fill in whichever handle he wants. Authorization with the different networks could prevent this. This requires the API’s of all supported networks to be implemented in the application, which proves the identity of the user with those networks, but makes it harder to support many different networks. Recognition of application users Currently, the application is only able to recognize Facebook friends of the logged in user. This should be expanded to allow users to recognize other users of the application. This is possible by using the private namespace offered by Face.com. Recognizing Facebook friends was enough to prove the use of the application, but for it’s general applicability, it is more useful to be able to discover the digital identities of strangers than of Facebook friends.
70
Appendices
71
Appendix A
Paper prototype iteration 2 questionnaire results
On each graph, the x-axis represents the 7-point Likert rating scale with 1 representing totally disagree and 7 representing totally agree, the y-axis represents the number of persons.
A.1
Usefulness questions
73
A. Paper prototype iteration 2 questionnaire results
Figure A.1: The application helps me be more effective.
Figure A.2: The application helps me be more productive.
Figure A.3: The application is useful.
Figure A.4: The application gives me more control over the activities in my life.
Figure A.5: The application Figure A.6: The application makes the things I want to ac- saves me time when I use it. complish easier to get done.
Figure A.7: The application 74 meets my needs.
Figure A.8: The application does everything I would expect it to do.
A.2. Ease of use questions
A.2
Ease of use questions
Figure A.9: The application is easy to use.
Figure A.10: The application is simple to use.
Figure A.11: The application is user friendly.
Figure A.12: The application requires the fewest steps possible to accomplish what I want to do with it.
Figure A.13: The application is flexible.
Figure A.14: Using the application is effortless.
75
A. Paper prototype iteration 2 questionnaire results
Figure A.15: I can use the appli- Figure A.16: I don’t notice any cation without written instruc- inconsistencies as I use the aptions. plication.
Figure A.17: Both occasional and regular users would like the application.
Figure A.18: I can recover from mistakes quickly and easily.
Figure A.19: I can use the application successfully every time.
76
A.3. Ease of learning questions
A.3
Ease of learning questions
Figure A.20: I learned to use the application quickly.
Figure A.21: I easily remember how to use the application.
Figure A.22: It is easy to learn to use the application.
Figure A.23: I quickly became skillful with the application.
77
A. Paper prototype iteration 2 questionnaire results
A.4
Satisfaction questions
78
A.4. Satisfaction questions
Figure A.24: I am satisfied with the application.
Figure A.25: I would recommend the application to a friend.
Figure A.26: The application is fun to use.
Figure A.27: The application works the way I want it to work.
Figure A.28: The application is wonderful.
Figure A.29: I feel I need to have it.
Figure A.30: It is pleasant to use. 79
Appendix B
Paper prototype iteration 3 questionnaire results
On each graph, the x-axis represents the 7-point Likert rating scale with 1 representing totally disagree and 7 representing totally agree, the y-axis represents the number of persons.
B.1
Usefulness questions
81
B. Paper prototype iteration 3 questionnaire results
Figure B.1: The application helps me be more effective.
Figure B.2: The application helps me be more productive.
Figure B.3: The application is useful.
Figure B.4: The application gives me more control over the activities in my life.
Figure B.5: The application Figure B.6: The application makes the things I want to ac- saves me time when I use it. complish easier to get done.
Figure B.7: The application 82 meets my needs.
Figure B.8: The application does everything I would expect it to do.
B.2. Ease of use questions
B.2
Ease of use questions
Figure B.9: The application is easy to use.
Figure B.10: The application is simple to use.
Figure B.11: The application is user friendly.
Figure B.12: The application requires the fewest steps possible to accomplish what I want to do with it.
Figure B.13: The application is flexible.
Figure B.14: Using the application is effortless.
83
B. Paper prototype iteration 3 questionnaire results
Figure B.15: I can use the appli- Figure B.16: I don’t notice any cation without written instruc- inconsistencies as I use the aptions. plication.
Figure B.17: Both occasional and regular users would like the application.
Figure B.18: I can recover from mistakes quickly and easily.
Figure B.19: I can use the application successfully every time.
84
B.3. Ease of learning questions
B.3
Ease of learning questions
Figure B.20: I learned to use the application quickly.
Figure B.21: I easily remember how to use the application.
Figure B.22: It is easy to learn to use the application.
Figure B.23: I quickly became skillful with the application.
85
B. Paper prototype iteration 3 questionnaire results
B.4
Satisfaction questions
86
B.4. Satisfaction questions
Figure B.24: I am satisfied with the application.
Figure B.25: I would recommend the application to a friend.
Figure B.26: The application is fun to use.
Figure B.27: The application works the way I want it to work.
Figure B.28: The application is wonderful.
Figure B.29: I feel I need to have it.
Figure B.30: It is pleasant to use. 87
Appendix C
Digital prototype iteration 1 questionnaire results
On each graph, the x-axis represents the 7-point Likert rating scale with 1 representing totally disagree and 7 representing totally agree, the y-axis represents the number of persons.
C.1
Usefulness questions
89
C. Digital prototype iteration 1 questionnaire results
Figure C.1: The application helps me be more effective.
Figure C.2: The application helps me be more productive.
Figure C.3: The application is useful.
Figure C.4: The application gives me more control over the activities in my life.
Figure C.5: The application Figure C.6: The application makes the things I want to ac- saves me time when I use it. complish easier to get done.
Figure C.7: The application 90 meets my needs.
Figure C.8: The application does everything I would expect it to do.
C.2. Ease of use questions
C.2
Ease of use questions
Figure C.9: The application is easy to use.
Figure C.10: The application is simple to use.
Figure C.11: The application is user friendly.
Figure C.12: The application requires the fewest steps possible to accomplish what I want to do with it.
Figure C.13: The application is flexible.
Figure C.14: Using the application is effortless.
91
C. Digital prototype iteration 1 questionnaire results
Figure C.15: I can use the appli- Figure C.16: I don’t notice any cation without written instruc- inconsistencies as I use the aptions. plication.
Figure C.17: Both occasional and regular users would like the application.
Figure C.18: I can recover from mistakes quickly and easily.
Figure C.19: I can use the application successfully every time.
92
C.3. Ease of learning questions
C.3
Ease of learning questions
Figure C.20: I learned to use the application quickly.
Figure C.21: I easily remember how to use the application.
Figure C.22: It is easy to learn to use the application.
Figure C.23: I quickly became skillful with the application.
93
C. Digital prototype iteration 1 questionnaire results
C.4
Satisfaction questions
94
C.4. Satisfaction questions
Figure C.24: I am satisfied with the application.
Figure C.25: I would recommend the application to a friend.
Figure C.26: The application is fun to use.
Figure C.27: The application works the way I want it to work.
Figure C.28: The application is wonderful.
Figure C.29: I feel I need to have it.
Figure C.30: It is pleasant to use. 95
Appendix D
Digital prototype iteration 2 questionnaire results
On each graph, the x-axis represents the 7-point Likert rating scale with 1 representing totally disagree and 7 representing totally agree, the y-axis represents the number of persons.
D.1
Usefulness questions
97
D. Digital prototype iteration 2 questionnaire results
Figure D.1: The application helps me be more effective.
Figure D.2: The application helps me be more productive.
Figure D.3: The application is useful.
Figure D.4: The application gives me more control over the activities in my life.
Figure D.5: The application Figure D.6: The application makes the things I want to ac- saves me time when I use it. complish easier to get done.
Figure D.7: The application 98 meets my needs.
Figure D.8: The application does everything I would expect it to do.
D.2. Ease of use questions
D.2
Ease of use questions
Figure D.9: The application is easy to use.
Figure D.10: The application is simple to use.
Figure D.11: The application is user friendly.
Figure D.12: The application requires the fewest steps possible to accomplish what I want to do with it.
Figure D.13: The application is flexible.
Figure D.14: Using the application is effortless.
99
D. Digital prototype iteration 2 questionnaire results
Figure D.15: I can use the appli- Figure D.16: I don’t notice any cation without written instruc- inconsistencies as I use the aptions. plication.
Figure D.17: Both occasional and regular users would like the application.
Figure D.18: I can recover from mistakes quickly and easily.
Figure D.19: I can use the application successfully every time.
100
D.3. Ease of learning questions
D.3
Ease of learning questions
Figure D.20: I learned to use the application quickly.
Figure D.21: I easily remember how to use the application.
Figure D.22: It is easy to learn to use the application.
Figure D.23: I quickly became skillful with the application.
101
D. Digital prototype iteration 2 questionnaire results
D.4
Satisfaction questions
102
D.4. Satisfaction questions
Figure D.24: I am satisfied with the application.
Figure D.25: I would recommend the application to a friend.
Figure D.26: The application is fun to use.
Figure D.27: The application works the way I want it to work.
Figure D.28: The application is wonderful.
Figure D.29: I feel I need to have it.
Figure D.30: It is pleasant to use. 103
Appendix E
Class diagram
Figure E.1 represents the complete class diagram of the application. The arrows between the classes represent a use-relation.
105
106
UserModel CameraViewController NSArray *friendsInfo; NSDictionary *meInfo; NSString *name; NSString *facebookID; NSMutableArray *recognizedList; + defaultModel; - (void)parseJSONReply: (NSDictionary *)reply; - (NSString *)getNameFromID: (NSString *)facebookID; - (void)savePreferences; - (NSMutableArray *)loadRecognizedList; - (void)addRecognizedPerson: (RecognizedPerson *)recognizedPerson; - (void)removeRecognizedPerson: (RecognizedPerson *)recognizedPerson; UIView *previewView; UISegmentedControl *camerasControl; UIBarButtonItem *homeButton; AVCaptureVideoPreviewLayer *previewLayer; UIBarButtonItem *recognizeButton; AVCaptureVideoDataOutput *videoDataOutput; dispatch_queue_t videoDataOutputQueue; AVCaptureStillImageOutput *stillImageOutput; UIView *flashView; UIImage *square; BOOL isUsingFrontFacingCamera; CIDetector *faceDetector; UIImage *stillImage; UIButton *faceButton; NSString *currentID; UILabel *statusLabel; SocialRecognizerViewController CameraViewController *cameraViewController; SettingsViewController *settingsViewController; OverviewViewController *overviewViewController; HistoryTableViewController *historyTableViewController; - (void)checkForStartInCameraMode; HistoryTableViewController NSMutableArray *recognizedPersons OverviewViewController *overviewViewController; - (IBAction)homeButtonPressed:sender; - (IBAction)switchCameras:sender; + (CGRect)videoPreviewBoxForGravity:(NSString *)gravity frameSize:(CGSize)frameSize apertureSize: (CGSize)apertureSize; - (IBAction)recognize:sender; (AVCaptureVideoOrientation)avOrientationForDevice Orientation:(UIDeviceOrientation)deviceOrientation; - (void)logIosFaceDetection:(CIFaceFeature *)faceFeature; - (void)sendToFaceCom; - (UIImage *)scaleAndRotateImage:(UIImage *)image; - (void)setNameLabel:(NSDictionary *)faces; - (void)clickedOnFace; NetworksViewController FaceWrapper Face.com API SettingsViewController SpinnerView *spinnerView; NetworksViewController *networksViewController; UISwitch *cameraButton - (IBAction)trainFriends:sender; - (IBAction)facebookLogout:sender; - (void)trainFriendsFaceCom; - (IBAction)switchStartInCamera:sender; NSMutableData *responseData; UITextField *emailTextField; UITextField *twitterTextField; UITextField *googleTextField; UITextField *slideshareTextField; UITextField *linkedinTextField; - (void)updateDatabase; + (SpinnerView *)loadSpinnerIntoView: (UIView *)superView; - (void)removeSpinner; - (UIImage *)addBackground; SpinnerView
Facebook API
FBRequestWrapper
E. Class diagram
Facebook *facebook; BOOL isLoggedIn;
+ defaultManager; - (void)setIsLoggedIn:(BOOL)_loggedIn; - (void)FBSessionBegin:_delegate; - (void)FBLogout; - (void)getFBRequestWithGraphPath: (NSString *)_path andDelegate:_delegate; - (void)sendFBRequestWithGraphPath: (NSString *)_path params: (NSMutableDictionary *)_params andDelegate:_delegate;
OverviewTableViewController
NSMutableData *responseData; RecognizedPerson *recognizedPerson
- (void)setComingFromCameraForPerson: (NSString *)facebookID; - (void)setComingFromHistoryForPerson: (RecognizedPerson *)person; - (IBAction)backButtonPressed; - (IBAction)otherButtonPressed; - (void)fetchInfoFor:(NSString *)currentID; - (void)saveRecognizedPerson; - (void)getInfoFromDatabase; - (void)openMailApp;
Figure E.1: The class diagram of the application
RecognizedPerson
NSString *name; NSString *facebookID; NSString *email; NSString *location; NSString *gender; NSString *profilePicURL; NSString *profileThumbURL;
Appendix F
Poster
This chapter contains the poster.
107
Master Computer Science
Thesis Gerry Hendrickx
Academic Year 2011-2012
Promotor Prof. Erik Duval
Supervisor Gonzalo Parra
Discovering digital identities through face recognition on mobile devices
The Goal
Obtain the social network profiles of persons in an efficient way, by using face recognition.
The Application
• Augmented camera view • Social network profiles • History of tagged people aggregator
How it works
Evaluation
• Iterative design: • 3 interface designs
Privacy Concerns
Although public information, there were concerns è Limited to Facebook friends & app users.
Conclusions – Future Work
• 2 paper prototypes • 2 digital prototypes • Testing • Focus on smartphone users • Think aloud technique • USE questionnaire • Results Conclusions: • Augmented reality was not the way to go • Slow (5-10 seconds) recognition process • Discovering profiles is ~4x more efficient than without app. • Holding the phone up is tedious • Easily expandable for more social networks Future work: • Authentication of social networks • Recognize multiple persons • Stability improvements
Strongly disagree Strongly agree Strongly disagree Strongly agree Strongly disagree Strongly agree
Appendix G
Paper
This chapter contains both the English and the Dutch version of the scientific paper.
109
Discovering digital identities through face recognition on mobile devices
Gerry Hendrickx Faculty of Engineering, Department of Computer Science Katholieke Universiteit Leuven Hendrickx.gerry@gmail.com Abstract
This paper covers the current status and past work of the creation of an iPhone application. The application uses face recognition provided by Face.com [1] to recognize faces captured with the camera of the iPhone. The recognized faces will be named and enable the user to get access to the information of the person from different social networks, his digital identity. This paper describes the research, the related work, the user interface prototyping and the current state of the implementation. It covers 3 iterations of paper prototyping in which a user interface gets established and the initial implementation of the application. mechanism since iOS5 [2]. Android, the other option, does not have this built in feature. A brainstorm and a survey resulted in a list of requirements for the face recognition application. The survey asked about which information users would like to get if they were able to recognize a person by using a smartphone. The survey was answered by 34 persons. 14 out of 34 voters would respect the privacy of the recognized person and thus would not want any information. 9 wanted contact information, 6 wanted links to the social network profiles of the recognized person and 3 of the voters wanted the last status update of Facebook or Twitter. The 2 remaining votes went to pictures of the recognized person and the location where they last met. There was a strong need for privacy, so a policy was decided upon: The app could be limited to the recognition of the user’s Facebook friends, but the need to recognize your Facebook friends is lower than the need to recognize strangers. To broaden the scope of recognizable people, the other users of the application will also be recognizable. The general policy will be: if you use the application, you can be recognized. An eye for an eye. The brainstorm resulted in a list of functionalities or characteristics. First of all the application should work fast. Holding your smartphone up and pointed to another person is quite cumbersome, so the faster the recognition works, the smaller this problem becomes. The information about the person should be displayed in augmented reality (AR) [3]. This is a technology that augments a users view of the world. AR can add extra information to the screen, based on GPS data or image processing. AR could place information about a person around his face in real-time. The functionality requirements from the poll and brainstorm and thus the goals to achieve efficient discovery of digital identities by using face recognition are the following:
1. INTRODUCTION
The internet has revolutionized the way people interact with each other. Different social networks have been created to support different levels of communications. The presence of a person on these networks is called his digital identity. The goal of this thesis is to find an efficient way to discover the digital identity of a person, by using face recognition and a smartphone. This paper describes the process of creating a face recognition application for the iPhone. It uses face recognition to offer the user extra information about the persons seen through the camera. This extra information will come from various social networks, the most important being Facebook, Twitter and Google+. It aims to offer users access to online data and information that is publicly available on the internet. This can be used in a private context, to enhance conversations and find common ground with your discussion partner, or in an academic context, to be able to easily find information, like slides or publications of the speaker at an event you’re attending. The app will be created for iOS because the SDK offers a built in face detection
• Detection and recognition of all the faces in the field of view. • Once recognized, the name and other options (like available social networks) will appear on screen with the face. • Contact info will be fetched from the networks and can be saved in the contacts app. • Quick access to all social networks will be available, along with some basic information such as the last status update/tweet. Information available will differ from person to person. To add an extra layer of privacy settings, a user will be able to link his networks and choose to enable or disable them. When the user gets recognized, only his enabled networks will show up.
Another non-commercial related work is a masterthesis of 2010 at the Katholieke Universiteit Leuven [10]. The author created a head-mounted-display-based application to recognize faces and get information. From his work we learned that HMD’s are not the ideal practical setup (his app required a backpack with a laptop and heavy headgear), and that the technology used (OpenGL) is a cumbersome way to develop. Using iOS simplifies these aspects. The author used Face.com as face recognition API and was very satisfied with it. A comparison of face recognition API’s was made in order to find the one most suited to our goals. A quick summary of the positive and negative points: • Viewdle: As said above, we’ve tried to contact Viewdle to get more information about the API. Sadly, they did not respond, therefore Viewdle is no option. • Face.com: Face.com offers a well documented REST API. It offers Facebook and Twitter integration and a private namespace that will allow the application to apply the previously stated privacy policy . There is a rate limit on the free version of Face.com. • Betaface [8]: The only API to work with images and video. However, it is Windows only, hasn’t been used with iOS yet and is not free. • PittPatt [9]: PittPatt was a very promising service, but sadly it got acquired by Google. The service cannot be used at this time. It seemed that Face.com is the only, but the best option found. It has an iOS SDK and social media integration, which are both very useful in the context of this application.
2. RELATED WORK
For this masterthesis we went to search for related mobile applications. No existing application was found that does exactly the same as this project. However, some similarities were found with the following applications: • Viewdle [5]: Viewdle is a company focusing on face recognition. They have several projects ongoing, and have already created an application for Android, called Viewdle Social Camera. It recognizes faces in images based on Facebook. Viewdle has a face recognition iOS SDK available. • Animetrics [6]: Animetrics created applications to help government and law enforcing agencies. It has multiple products like FaceR MobileID, which can be used to get the names and percentage of the match of any random person. FaceR CredentialME can be used for authentication on your own smartphone. It recognizes your face and if it matches, it unlocks your data. Animetrics also focuses on home security face recognition. However they do not seem to have a public API, since their focus is not on the commercial market. • TAT Augmented ID [7]: TAT Augmented ID is a concept app. It recognizes faces in real-time and uses augmented reality to display icons around the face. The concept is the same, but the resulting user interface is different. Section 3 discusses why a fully augmented user interface is not preferred on mobile devices.
3. PAPER PROTOTYPING
Paper prototyping is the process of designing the user interface based on quick drawings of all the different parts of the user interface [11]. By doing this with paper parts, it becomes easy to quickly evaluate and adapt the interface. The prototyping phase consisted of 3 iterations: the interface decision, the interface evaluation and the expert opinion.
3.1. Phase one: interface decisions
The first phase of the paper prototyping was to decide which of the 3 possible interfaces would be used. The interfaces were:
• Interface 1: A box of information attached to the head of the recognized person. This is the best use of augmented reality, but you have to keep your phone pointed to the person in order to be able to read his information. See figure 1a. • Interface 2: A sidebar with information, which takes about 1/4th of the screen. This way, users lower their phone when a person is selected, but they can still use the camera if they want. See figure 1b. • Interface 3: A full screen information screen. This makes minimal use of augmented reality but offers a practical way to view the information. Users see the name of the recognized person in the camera view, and once tapped, they get referred to the full screen information window. See figure 1c. These interfaces are evaluated using 11 test subjects, aged 18 to 23, with mixed smartphone experience. The tests were done using the think aloud technique, which means they have to say what they think is going to happen when they click a button. The interviewer plays computer and changes the screens. The same simple scenario was given for all interfaces where the test subject needed to recognize a person and find information about him. After the test, a small custom-made questionnaire was given to poll the interface preference. None of the users picked interface 1 as their favourite. The fact that you should keep your phone pointed to the person in order to read and browse through the information, proved to be a big disadvantage. The choice between interface 2 and 3 was not unanimously decided. 27% chose interface 2, 73% chose interface 3. Thus interface 3 was chosen and elaborated for the second phase of paper prototyping. People liked the second idea where you could still see the camera, but then again they realized that, if interface 1 thought us that you would not keep your camera pointed at the crowd, you wouldn’t do this in interface 2, so the camera would be showing your table or pants. This reduces the use of the camera feed. The smartphone owners also pointed out that using only a part of the screen would be too small to actually put readable information on it.
(a) Interface 1
(b) Interface 2
3.2. Phase two: interface evaluation
For the second phase, 10 test subjects were used between the ages of 20 and 23, again with mixed smartphone experience. An extended scenario was created which explored the full scope of functionality in the application. The testers needed to recognize people, adjust settings, link social networks to their profile, indicate false positives and manage the recognition history.
(c) Interface 3
Figure 1: The different scenario’s
The think aloud technique was applied once again. At the end of each prototype test, the test subject needed to fill in a USE questionnaire [4]. This is a questionnaire consisting of 30 questions, divided into 4 categories to poll to different aspect of the evaluated application. The questions can be answered on a 7-point Likert rating scale, 1 representing totally disagree and 7 representing totally agree. The categories are usefulness, ease of use, ease of learning and satisfaction. 3.2.1. Usefulness. The overall results were good. The question about whether the application is useful receives a median score of 5 out of 7, with no result below 4. People seem to understand why the app is useful and it does what they would expect. The scores on whether it meets the need of the users were divided with scores going from 1 to 7, because some users (especially the users with some privacy concerns or without a smartphone) did not see the usefulness of the application. However, the target audience, the smartphone users, did see its usefulness, resulting in higher scores in this section. 3.2.2. Ease of use. From the ease of use questions the need to add or rearrange buttons became clear. Users complained about the number of screen transitions it took to get from one screen to somewhere else in the application and this could be seen in the results. The question whether using the application is effortless received scores ranging from 2 to 7 with a median of 5. The path through the application should be revised to see whether missing link can be found and corrected to improve the navigation. For instance, the home button to go to the main screen will be added on several other screens, instead of having to navigate back through all the previous screens. Using the application was effortless for all iPhone users, because the user interface was built using the standard iOS interface parts. 3.2.3. Ease of learning. None of the ease of learning questions scored below 5 on the 7-point Likert rating scale. This is also due to the standard iOS interface, which is developed by Apple to be easy to work with and easy to learn. 3.2.4. Satisfaction. Most people were satisfied with the functionality offered by the application and how it was presented in the user interface. Especially the iPhone users were very enthusiastic, calling it an innovative, futuristic application. The question whether the user was satisfied with the application received scores ranging from 5 to 6, with a median at 6 out of 7. Nonsmartphone users were more skeptical and did not see the need for such an application. Aside from this, the
application was fun to use and the target audience was satisfied. 3.2.5. Positive and negative aspects. The users were asked to give the positive and negative aspects of the application. The positive aspects were the iOS-style of working and the functionality and concept of the application. The negative aspects were more user interface related, such as not enough home buttons, and the suggested method to indicate a false positive. This button was placed on the full screen information window of a person. Everybody agreed that this was to late, because all the data of the wrongfully tagged person would then be displayed. So the incorrect tag-button should be placed on the camera view. Some useful ideas like enabling the user to follow a recognized person on Twitter were suggested.
3.3. Phase three: expert opinions
For this phase, the supervisor and 6 advisers of the thesis were used in the paper prototype test. The prototype was adjusted to the results of the second iteration. More home-buttons were placed and the incorrect tagbutton was placed on the camera view. The test subjects all had extensive experience in the field of humancomputer interaction and can thus be seen as experts. They took the tests and filled in the same questionnaire and gave their opinion on several aspects of the program. A small summary: • There were concerns about the image quality of the different iPhones. Tests should be done to test from what distance a person can be recognized. • The application should be modular enough. In a rapidly evolving 2.0 world, social network may need to be added or deleted from the application. If all the networks are implemented as modules, this will be a simpler task. • The incorrect tag-button could be implemented in the same way as the iPhoto application asks the user if an image is tagged correctly. • The social network information should not just be static info. The user should be able to interact directly from the application. If this is not possible, it would be better to refer the user directly to the Facebook or Twitter app. • More info could be displayed in the full screen information window. Instead of showing links to all networks, the general information about the person could already be displayed there.
When asked which social networks they would like to see in the application, nearly everybody said Facebook, Twitter and Google+. In an academic context, they would like to see Mendeley and Slideshare.
4. IMPLEMENTATION
Apart from some suggestions, the third paper prototype was received positively. The next step in the process is the implementation. The application is currently in development, and a small base is working. The main focus so far is on the crucial functionality, the face recognition. It is important to get this part up and running as fast as possible, because the entire application depends on it. So far the application is able to track faces using the iOS5 face detection. A temporary box frames the faces and follows them as the camera or person moves. This functionality could be used to test the quality of the face detection API. As you can see in figure 2, the face detection algorithm of iOS5 can detect multiple faces at ones, and in such depth that the smallest recognized face is barely bigger than a button. These are great results, because the algorithm appeared to be fast and reliable and detailed enough for our purpose. Detection of even smaller faces is not necessary, because the boxes will become harder to click if they are smaller than a button.
Figure 2: Face tracking results.
The next step was the face recognition. This is handled by Face.com. An iOS SDK is available on the website [12]. This SDK contains the functionality to send images to the Face.com servers, and receive a JSON response with the recognized faces. It also covers the necessary Facebook login, as Face.com requires the user to log in using his Facebook account. This login is only needed one time. One problem was that Face.com only accepts images, not video. To be able to test the face recognition as fast as possible, a recognize-button was added to the camera view. Once clicked, a snapshot is taken with the camera. This snapshot is send to the servers of Face.com and analyzed for different faces. The JSON response gets parsed and the percentage of the match and the list of best matches can be fetched from it. At the moment, only one face can be recognized at the same time, because there is no algorithm provided to check which part of the response should be matched to which face on the camera. This is temporarily solved by limiting the program to one face at a time. Figure 3 shows the current status of the application. A face is recognized and its Facebook ID is printed above.
Figure 3: Face recognized and matched with the correct Facebook ID.
5. NEXT STEPS AND FUTURE WORK
The next step in development is the further development of the user interface. Now that we have
a basic implementation of the main functionality, it is important to finish the mock-up of the application. This way, a dummy implementation of several screens can be used to test the interface in several iterations using the digital prototype. When these tests happen, the underlying functionality can be extended and implemented in parallel. Several big problems need to be solved. The biggest being the matching of faces detected by iOS5 face detection and the faces recognized by Face.com. Because Face.com recognizes faces by using images, a way needs to be found to match these results to the faces on screen. If the user moves the camera to other people after pressing the recognize-button, the results from Face.com will not match the faces on screen. The solution in mind is to use an algorithm to match the Face.com results with the face detection based on proportions. If we succeed in finding a correlation between for instance the eyes and the nose of a person in both services, it should be possible to find which detected face matches which Face.com result. Another way to match the faces to the reply is to keep track of the faces based on their coordinates on the screen. A suitable algorithm for this problem needs to be found. Another smaller problem is the use of the Face.com SDK. It has a limited Facebook graph API built into it. However, this API can not be used to fetch the name of an ID or to get status updates. Therefore the real Facebook iOS SDK should be used. To prevent the app from working with two separate API’s, the Face.com API needs to be adapted so that it uses the real Facebook iOS SDK instead of the limited graph API.
[4]
[5] [6] [7] [8] [9] [10] [11] [12]
reality, IEEE Computer Graphics And Applications, 21(6):34-47, 2001 Arnold M. Lund, Measuring Usability with the USE Questionnaire, in Usability and User Experience, vol. 8, no. 2, October 2001, measuring with use.html Niels Buekers, Social Annotations in Augmented Reality, Masterthesis at KULeuven, 2010-2011 Erik Duval, paper prototyping,, last checked on April 29, 2012 Sergiomtz Losa, FaceWrapper for iPhone,
6. CONCLUSION
This masterthesis is still a work in progress. We already have good results from paper prototyping, and the core of the application has already been implemented. In the following months, some problems will have to be solved and user testing is still required to make the application match its goal: a fast, new way to discover people using the newest technologies and networks.
References
[1] [2] CoreImage/Reference/CIDetector Ref/Reference/Reference.html [3] R. Azuma, Y. Baillot, R. Behreinger, S. Feiner, S. Julier, B. MacInture, Recent developments in augmented
Ontdekken van digitale identiteiten door middel van gezichtsherkenning op mobiele toestellen.
Gerry Hendrickx Ingenieurswetenschappen, Departement van Computerwetenschappen Katholieke Universiteit Leuven Hendrickx.gerry@gmail.com Samenvatting
Dit eindwerk behandelt de huidige staat en het reeds geleverde werk voor de ontwikkeling van een iPhone applicatie. De toepassing maakt gebruik van gezichtsherkenning, verleend door Face.com [1], om gezichten te herkennen die vastgelegd werden met de camera van de iPhone. De herkende gezichten zullen benoemd worden en de gebruiker toegang verschaffen tot de informatie van de persoon verkregen vanuit verschillende sociale netwerken: zijn digitale identiteit. Dit document beschrijft het onderzoek, het gerelateerde werk, het evalueren van prototypes van de gebruikersinterface en de huidige staat van de applicatie. Het overloopt 3 iteraties van papieren prototypes, waarin een gebruikersinterface wordt gecre¨ erd en de eerste implementae tie van de toepassing. die vrij toegankelijk is op het internet. Dit kan worden gebruikt in een private context, om gesprekken te verbeteren en een gezamelijke onderwerp te vinden met je gesprekspartner, of in een academische context, om de mogelijkheid te hebben om gemakkelijk informatie te vinden, zoals slides of publicaties van een spreker op een event waar je aanwezig bent. De applicatie zal gecre¨ erd worden voor IOS omdat de SDK een e ingebouwde gezichtsdetectiemechanisme levert sinds IOS5 [2]. Android, de andere optie, heeft dit built in feature niet. Uit een enquˆ te en een brainstorm ontstond een e lijst van gevraagde vereisten voor de gezichtsherkenningsapplicatie. De enquˆ te vroeg welke informatie e gebruikers zouden willen krijgen als ze de mogelijkheid hadden om een persoon te herkennen door het gebruik van een smarphone. De vraag werd beantwoord door 34 personen. 14 van de 34 stemmers zouden de privacy van de herkende persoon respecteren en zouden aldus geen enkele informatie wensen. 9 zouden graag contact informatie krijgen, 6 wilden links naar de sociale netwerkprofielen van de herkende persoon en 3 van de stemmers wilden de laatste status update van Facebook of Twitter. De 2 resterende stemmen gingen naar de foto’s van de herkende personen en naar de plaats waar ze het laatst hadden ontmoet. Uit de enquˆ te e volgende een duidelijke nood aan privacy, zodoende werd volgende beleid vastgesteld: de applicatie zou kunnen beperkt worden tot de herkenning van personen die behoren tot de Facebook vrienden van de gebruiker. Om de werkruimte van herkenbare gezichten te verbreden, zouden de andere gebruikers van de appilicatie ook herkenbaar zijn. De algemene tendens zal zijn: als je de applicatie gebruikt, zal je herkend kunnen worden. Oog om oog. De brainstorm resulteerde in een lijst van functio-
1. INTRODUCTIE
Het internet heeft een revolutie veroorzaakt in de manier waarop mensen met elkaar omgaan. Verschillende sociale netwerken werden gemaakt om verschillende niveaus van communicatie te ondersteunen. De aanwezigheid van een persoon op deze netwerken wordt zijn digitale identiteit genoemd. Het doel van deze thesis is om een effici¨ nte manier te vinden om e de digitale identiteit van een persoon te ontdekken, door gebruik te maken van gezichtsherkenning en smartphone. Dit document beschrijft het proces van de ontwikkeling van een gezichtsherkennings-applicatie voor de Iphone. Het gebruikt gezichtsherkenning om de gebruiker extra informatie te verschaffen betreffende de persoon, die gezien wordt door de camera. Deze extra informatie zal afkomstig zijn van verschillende sociale netwerken, de belangrijkste zijnde Facebook, Twitter en Google+. Het heeft tot doel om gebruikers toegang te verlenen tot online gegevens en informatie
naliteiten en kenmerken. Ten eerste zou de toepassing snel moeten werken. De smarphone omhoog houden, gericht op het gezicht van een ander persoon, is nogal omslachtig. Hoe sneller de herkenning werkt, hoe kleiner dit probleem wordt. De informatie over de persoon zou moeten verschijnen in toegevoegde realiteit (TR) [3]. Dit is een technologie die elementen aan de kijk van de gebruiker op de wereld toevoegt. TR kan extra informatie aan het scherm toevoegen, gebaseerd op GPS-gegevens of beeldverwerking. TR zou informatie van een persoon rond zijn hoofd kunnen plaatsen in re¨ le tijd. De functionaliteitseisen van de enquˆ te en e e brainstorm en de doelen om een effici¨ nte ontdekking e van digitale identiteiten te bereiken door het gebruik van herkenning zijn de volgende: • Opsporing en herkenning van alle gezichten in het gezichtsveld. • Eens herkend, zullen de naam en andere opties (zoals beschikbare sociale netwerken) verschijnen op het scherm bij het gezicht. • Contactgegevens zullen van de netwerken gehaald worden en zullen kunnen worden opgeslagen in de contacten applicatie van de iPhone • Snelle toegang tot alle sociale netwerken zal beschikbaar zijn, samen met basisinformatie zoals de laatste status update/tweet. Beschikbare informatie zal verschillen van persoon tot persoon. Om een extra privacy-instelling toe te voegen, zal de gebruiker de mogelijkheid hebben om zijn netwerken te linken en om te kiezen om ze in of uit te schakelen. Als de gebruiker herkend wordt, zullen alleen zijn ingeschakelde netwerken verschijnen.
handhaven te helpen. Het heeft verschillende producten zoals FaceR MobileID, wat kan gebruikt worden om zowel de namen als het percentage van de overeenkomsten van elk persoon te krijgen. FaceR Credential ME kan gebruikt worden voor authenticatie op je eigen smartphone. Het herkent je eigen gezicht en als het een correcte herkennig is, opent het uw gegevens. Animetrics focust ook op het herkennen van gezichten voor de veiligheid van uw woning. Ze lijken geen publieke API te hebben, omdat hun focus niet gericht is op de commerci¨ le markt. e • TAT Augmented ID [7]: TAT Augmented ID is een concept toepassing. Het herkent gezichten in re¨ le tijd en gebruikt toegevoegde realiteit om icoe nen rond het gezicht te tonen. Het concept is hetzelfde, maar de resulterende gebruikersinterface is verschillend. Section 3 bediscussieert waarom een volledig toegevoegde realiteit gebruikersinterface niet de voorkeur krijgt op mobiele apparaten. Een ander niet-commercieel gerelateerd werk is een masterthesis van 2010 aan de Katholieke Universiteit Leuven [10]. De schrijver maakte een head-mounted display-toepassing (HMD) om gezichten te herkennen en informatie te krijgen. Van zijn werk leerden we dat HMDs praktisch niet de ideale opstelling hebben (zijn toepassing vereiste een rugzak met een laptop en een headset) en dat de technologie die werd gebruikt (OpenGL) omslachtig is om mee te werken. Het gebruik van iOS maakt deze aspecten eenvoudiger, aangezien de hardware vereisten beperkt blijven tot de iPhone. De schrijver gebruikte Face.com als gezichtsherkenning en was er zeer tevreden over. Er werd een vergelijking van gezichtsherkenning API’s gemaakt, om de meest geschikte te vinden voor ons doel. Een kleine samenvatting van de positieve en de negatieve punten: • Viewdle: Zoals reeds vermeld, hebben we geprobeerd om Viewdle te contacteren om meer informatie te verkrijgen over de API, maar zonder antwoord. Viewdle is geen optie. • Face.com: Face.com biedt een goed gedocumenteerde REST API aan. Het beschikt over Facebook en Twitter integratie en een private namespace, die de toepassing zal toelaten om gebruik te maken van het eerder vermelde privacy beleid. Er is een gebruikslimiet op de gratis versie van Face.com. • Betaface [8]: De enige toepassing die zowel met foto’s en video’s kan werken. Ontwikkelen is ech-
2. GERELATEERD WERK
Voor deze masterthesis gingen we op zoek naar gerelateerde mobiele toepassingen. Er werd geen enkele bestaande toepassing gevonden die juist hetzelfde doet als in dit project. Sommige overeenkomsten werden gevonden in de volgende applicaties: • Viewdle [5]: Viewdle is een bedrijf gefocust op gezichtsherkenning. Ze hebben verschillende lopende projecten en hebben al een toepassing gemaakt voor Android, genoemd Viewdle Social Camera. Het herkent gezichten in foto’s op Facebook. Viewdle heeft een gezichtsherkennings iOS SDK beschikbaar. • Animetrics [6]: Animetrics maakt toepassingen om regeringen en agentschappen die het recht
ter alleen mogelijk in Windows, en het werd nog niet gebruikt met iOS. Bovendien is het niet gratis. • PittPatt [9]: Pittpatt was een veelbelovende service, maar spijtig genoeg werd het aangekocht door Google. De service kan op dit moment dan ook niet worden gebruikt. Het lijkt erop dat Face.com de enige en tevens ook de nuttigste gezichtsherkennings API is voor onze applicatie. Het heeft een iOS SDK en sociale media integratie, welke beiden erg nuttig zijn in de context van deze toepassing.
(a) Interface 1
3. PAPIEREN PROTOTYPES
Een papieren prototype maken is het proces van het ontwikkelen van de gebruikersinterface, gebaseerd op snelle tekeningen van alle verschilende delen van de gebruikersinterface [11]. Door dit te doen met papieren delen wordt het gemakkelijk om snel de interface te evalueren en aan te passen. De papieren prototype fase bestaat uit 3 iteraties: het beslissen van de interface, de evaluatie van de uitgewerkte interface en de evaluatie met experten.
(b) Interface 2
3.1. Fase 1: interface beslissen
De eerste fase van het papieren prototype was de beslissing welke van de 3 mogelijke interfaces gebruikt zouden worden: • Interface 1: een kader met informatie naast het hoofd van de herkende persoon. Dit is het beste gebruik van toegevoegde realiteit, maar je moet de iPhone op het hoofd van de persoon gericht houden om de informatie te kunnen lezen. Zie 1a. • Interface 2: een zijbalk met informatie, die ongeveer 1/4de van het scherm in beslag neemt. Op deze manier kunnen gebruikers hun iPhone lager houden wanneer een persoon is geselecteerd, maar ze kunnen de camera nog steeds gebruiken als ze willen. Zie figuur 1b. • Interface 3: een volledig informatiescherm. Dit maakt minimaal gebruik van de toegevoegde realiteit, maar biedt een praktische manier om de informatie te bekijken. Gebruikers zien de naam van de herkende persoon in het camerabeeld, en eens ze op het gezicht geklikt hebben, worden ze doorverwezen naar het scherm met volledige informatie. Zie figuur 1c.
(c) Interface 3
Figuur 1: De verschillende interfaces
Deze interfaces werden ge¨ valueerd door 11 teste personen, met een leeftijd van 18 tot 23 jaar, met verschillende smartphone ervaring. De testen werden gedaan door middel van de denk-luidop-techniek, wat betekent dat ze moeten zeggen wat ze denken dat zal gebeuren als ze een knop indrukken. De interviewer verandert de papieren schermen om de applicatie te simuleren. Hetzelfde simpel scenario werd gegeven voor al de interfaces, waarbij de testpersoon een persoon moest herkennen en informatie over die persoon moest vinden. Na de test werd een kleine, op maat gemaakte vragenlijst gegeven om de interface voorkeur na te gaan. Niemand van de gebruikers koos interface 1 als favoriet. Het feit dat je de iPhone op de persoon gericht moest houden om de informatie te lezen en door te nemen, bleek een ernstig nadeel te zijn. De keuze tussen Interface 2 en 3 was niet unaniem beslist. 27% koos interface 2 en 73% koos voor Interface 3. Dus werd Interface 3 gekozen en uitgewerkt voor het tweede deel van het papieren prototype. De smartphone gebruikers benadrukten ook dat als je enkel 1/4e van het scherm gebruikt voor informatie, dit te klein zou zijn om leesbare informatie weer te geven.
met privacy bedenkingen en deze zonder smartphone) geen nut zagen in het gebruik van de toepassing. Het doelpubliek, de smartphone gebruikers, zagen er wel het nut van in met hogere scores als gevolg in deze groep. 3.2.2. Gebruiksgemak. Uit deze vragen werd de nood aan een herschikking van sommige knoppen duidelijk. Gebruikers klaagden over het aantal schermovergangen dat ze moesten doorlopen om van 1 scherm naar ergens anders in de toepassing te gaan en dit was duidelijk in de resultaten. De vraag of het gebruik van de toepassing vlot verloopt, kreeg scores van 2 tot 7 met een gemiddelde van 5. De weg door de toepassing zou moeten worden herzien om te kijken of de ontbrekende schakels kunnen gevonden en verbeterd worden om de navigatie te bevorderen. Bij voorbeeld, de home-knop om naar het hoofdscherm te gaan, zal worden toegevoegd op verschillende andere schermen in plaats van steeds terug te moeten gaan via alle vorige schermen. Het gebruik van de toepassing verliep probleemloos voor alle iPhone gebruikers, omdat de gebruikersinterface gemaakt was met de standaard iOS interface delen. 3.2.3. Gemakkelijkheid om aan te leren. Geen enkele vraag in deze sectie scoorde lager dan 5 op de 7punten Likert schaal. Dit is ook te wijten aan de standaard iOS interface, die werd ontwikkeld door Apple met het oog op gebruiksgemak en gemakkelijkheid om aan te leren. 3.2.4. Tevredenheid. De meeste gebruikers waren tevreden over de functionaliteiten aangeboden door de toepassing en over hoe het werd voorgesteld in de gebruikersinterface. Vooral de iPhone gebruikers waren zeer enthousiast. Zij noemden het een vernieuwende toepassing. De vraag of de gebruiker tevreden was over de toepassing kreeg scores van 5 tot 6, met een gemiddelde van 6 op 7. Niet-smarphone gebruikers waren meer sceptisch en zagen het nut niet in van dergelijke toepassing. Dit terzijde, de toepassing was leuk en het doelpubliek was tevreden. 3.2.5. Positieve and negatieve aspecten. Er werd de gebruikers gevraagd om de postieve en negatieve aspecten van de toepassing te noteren. De positieve aspecten waren de iOS-stijl van werken, de functionaliteit en het idee van de toepassing. De negatieve aspecten waren meer interface-gerelateerd, zoals niet genoeg homeknoppen en de voorgestelde methode om een incorrecte herkenning aan te duiden. Deze knop werd echter geplaatst op het informatiescherm van een herkende persoon. Iedereen was het er over eens dat dit te laat was, omdat dan alle gegevens van de verkeerde persoon ge-
3.2. Fase 2: interface evaluatie
Voor de tweede fase werden 10 testpersonen gebruikt, tussen de 20 en 23 jaar oud, weer met verschillende smartphone ervaring. Een uitgebreidere interface werd gemaakt, die de volledige omvang van de functionaliteit onderzocht. De testers moesten mensen herkennen, instellingen aanpassen, sociale netwerken aan hun profiel linken, valse positieven aanduiden en de geschiedenis van de herkenning beheren. De denk- luidoptechniek werd weer toegepast. Aan het einde van de test moest de testpersoon een USE vragenlijst invullen [4]. Dit is een vragenlijst die bestaat uit 30 vragen, ingedeeld in 4 categorie¨ n om de verschillende aspecten e van de ge¨ valueerde toepassing te bevragen. De vrae gen kunnen beantwoord worden op een 7-punten Likert schaal, 1 vertegenwoordigt totaal niet akkoord en 7 helemaal akkoord. De categorie¨ n zijn nuttigheid, gee bruiksgemak, gemakkelijkheid om aan te leren en tevredenheid. 3.2.1. Nuttigheid. De algemene resultaten waren goed. De vraag of de toepassing nuttig is, kreeg een gemiddelde score van 5 op 7, met geen enkel cijfer onder de 4. Mensen lijken te verstaan waarom de toepassing nuttig is en ze doet wat ervan verwacht wordt. De scores op de vraag of het voldoet aan de nood van de gebruikers was verdeeld met cijfers gaande van 1 tot 7, omdat sommige gebruikers (vooral deze
toond zouden worden. Zodoende zou de incorrect tagbutton geplaatst moeten worden op het camera scherm. Enkele nuttige idee¨ n, zoals het de gebruiker mogelijk e maken om een herkend persoon te volgen op Twitter, werden voorgesteld.
3.3. Fase 3: de mening van experten
Voor deze fase werden de promoter en 6 raadgevers gebruikt als testpersonen. Het prototype was aangepast aan de resultaten van de tweede iteratie. Meer home-knoppen werden geplaatst en de incorrect tagknop werd op het camera scherm geplaatst. De testgebruikers hebben allemaal uitgebreide ervaring op het gebied van mens-computer interactie en kunnen aldus gezien worden als experten. Zij deden de tests, vulden dezelfde vragenlijsten in en gaven hun mening op verschillende aspecten van het programma. Een kleine samenvatting: • Er was ongerustheid omtrent de beeldkwaliteit van de verschillende iPhones. Er zouden tests moeten gebeuren om te kijken vanaf welke afstand een persoon herkend kan worden. • De toepassing zou voldoende modulair moeten zijn. In een snel evoluerende 2.0-wereld, zouden sociale netwerken moeten kunnen bijgevoegd of verwijderd worden van de toepassing. Als alle netwerken als modules worden ge¨mplementeerd, zou ı dit gemakkelijker worden. • De incorrect tag-knop zou op dezelfde wijze kunnen worden ge¨mplementeerd als knop in iPhoto ı die de gebruiker vraagt of een afbeelding juist is getagged. • De sociale netwerk informatie zou niet enkel statische info mogen geven. De gebruiker zou de mogelijkheid moeten hebben om onmiddellijk vanuit de toepassing te reageren. Als dit niet mogelijk is, zou het beter zijn om de gebruiker onmiddellijk naar Facebook of Twitter te verwijzen. • Er zou meer informatie kunnen worden getoond in het volledige scherm. In plaats van meer links naar alle netwerken te tonen, zou de algemene informatie rond een persoon hier al gegeven kunnen worden. Op de vraag welke sociale netwerken zij willen zien in de toepassing, zei bijna iedereen Facebook, Twitter en Google+. In een academische context zouden ze ook graag Mendeley en Slideshare zien.
Figuur 2: Gezichtsdetectie resultaten.
4. IMPLEMENTATIE
Afgezien van enkele suggesties werd het derde papieren prototype positief onthaald. De volgende stap in het proces is de implementatie. De toepassing is momenteel in ontwikkeling en een kleine basis werkt. De belangrijkste focus ligt nu op de hoofdfunctionaliteit: de gezichtsherkenning. Het is belangrijk om dit deel zo vlug mogelijk werkende te krijgen, omdat de volledige toepassing er op steunt. Tot hier toe slaagt de toepassing er in om gezichten op te sporen, gebruik makende van de iOS5 gezichtsdetectie. Een vierkant omkadert de gezichten en volgt ze wanneer de camera of de persoon beweegt. Deze functionaliteit zou kunnen worden gebruikt om de kwaliteit van de gezichts-herkenning API te testen. Zoals je kan zien in figuur 2, kan het gezichtsdetectie algoritme van iOS5 verschillende gezichten samen herkennen en dit in zulke diepte, dat het kleinste herkenbare gezicht nauwelijks groter is dan een knop. Dit zijn goede resultaten, omdat het algoritme snel, betrouwbaar en gedetailleerd genoeg bleek voor ons doel. Detectie van nog kleinere gezichten is niet nodig, omdat de kaders moeilijk worden om in te klikken wanneer ze kleiner zijn dan een knop. De volgende stap was de gezichtsherkenning. Dit wordt behandeld door Face.com. Een iOS SDK is beschikbaar op de website [12]. Dit SDK omvat de functionaliteit om beelden naar de Face.com servers te sturen en een JSON antwoord te ontvangen met de herkende gezichten. Het bevat ook de nodige Facebook
den worden om deze resultaten te vergelijken met de gezichten op het scherm. Als de gebruiker de camera richt op andere mensen nadat hij op de recognize-knop heeft geduwd, zal het resultaat van Face.com niet overeenkomen met het gezicht op het scherm. De oplossing in gedachte is om een algoritme te gebruiken om de Face.com resultaten te laten overeenkomen met de gezichtsdetectie gebaseerd op verhoudingen. Als we slagen om een correlatie te vinden tussen de ogen en de neus van een persoon in beide diensten, zou het mogelijk zijn om uit te zoeken welk gezicht op de camera overeenkomt met het Face.com resultaat. Een andere manier om de gezichten te laten overeenkomen met het antwoord van Face.com is het bijhouden van de gezichten gebaseerd op hun co¨ rdinaten op het scherm. Een o gepast algoritme voor dit probleem moet gevonden worden. Figuur 3: Gezicht is herkend en de correcte Facebook ID wordt getoont. login, want Face.com vraagt de gebruiker om in te loggen met zijn Facebook account. Deze login is slechts ´´ eenmalig. Een probleem was dat Face.com alleen maar beelden aanvaardt en geen video’s. Om het mogelijk te maken om de gezichtsherkenning zo vlug mogelijk te testen, is een recognize-knop toegevoegd aan het camerabeeld. Wanneer hierop geklikt wordt, wordt een foto genomen. Deze foto wordt verzonden naar de servers van Face.com en wordt geanalyseeerd voor gezichten. Het JSON antwoord wordt ontleed en per gezicht krijgt men een percentage van zekerheid en de lijst van mogelijke namen. Figuur 3 toont de huidige staat van de toepassing. Een gezicht wordt herkend en zijn Facebook ID wordt bovenaan geprint.
6. CONCLUSION
Deze masterthesis is een werk in uitvoering. We hebben goede resultaten van de papieren prototypes en de kern van de toepassing is reeds ge¨mplementeerd. ı Sommige problemen nog moeten worden opgelost en het testen met gebruikers is nog nodig om de toepassing zijn doel te laten bereiken: een effici¨ nte, nieuwe e manier om mensen te ontdekken, gebruik makende van de nieuwste technologie¨ n en netwerken. e
Referenties
[1] [2] CoreImage/Reference/CIDetector Ref/Reference/Reference.html [3] R. Azuma, Y. Baillot, R. Behreinger, S. Feiner, S. Julier, B. MacInture, Recent developments in augmented reality, IEEE Computer Graphics And Applications, 21(6):34-47, 2001 [4] Arnold M. Lund, Measuring Usability with the USE Questionnaire, in Usability and User Experience, vol. 8, no. 2, October 2001, measuring with use.html [5] [6] [7] [8] [9] [10] Niels Buekers, Social Annotations in Augmented Reality, Masterthesis at KULeuven, 2010-2011 [11] Erik Duval, paper prototyping,, last checked on April 29, 2012 [12] Sergiomtz Losa, FaceWrapper for iPhone,
5. VOLGENDE STAPPEN EN TOEKOMSTIG WERK
De volgende stap in de ontwikkeling is de verdere implementatie van de gebruikersinterface. Nu we een implementatie hebben van de hoofdfunctionaliteit, is het belangrijk om de mock-up van de toepassing te vervolledigen. Op deze wijze kan een dummy implementatie van verschillende schermen worden gebruikt om de interface te testen in verschillende iteraties, gebruik makende van het digitale prototype. Verschillende grote problemen moeten worden opgelost. Het grootste probleem is het identificeren van gezichten herkend door iOS5 gezichtsherkenning aan gezichten herkend door Face.com. Omdat Face.com gezichten herkent door gebruik te maken van foto’s moet er een manier gevon-
Bibliography
[1] R. Brunelli, T. Poggio, Face recognition, features vs templates, Massachusetts Institute Of Technology, Massachusetts USA, 1993 [2] Smith, Kelly, Face recognition, National Science and Technology Council, 2006 [3] Face recognition using eigenfaces, eigenfaces/, Princeton University, USA, last checked on April 24, 2012 [4] Alexander M. Bronstein, Michael M. Bronstein, Ron Kimmel, Three-Dimensional Face Recognition, Isreal, december 10, 2004 [5] Kevin Bonsor, Ryan Johnson, How facial recognition systems work, URL:ffworks.com/gadgets/high-tech-gadgets/facialrecognition.htm, last checked on April 25, 2012 [6] Yaniv Taigman, Lior Wolf, Leveraging Billions of Faces to Overcome Performance Barriers in Unconstrained Face Recognition, Face.com, 2011 [7] [8] [9] Face.com,, last checked on April 25, 2012 Facebook,, last checked on April 25, 2012 Betaface,, last checked on April 25, 2012
[10] Verilook,, last checked on April 25, 2012 [11] PittPatt,, last checked on April 25, 2012 [12] Viewdle,, last checked on April 25, 2012 itunes.apple.com/us/app/klik-by-face.com/ [13] KLIK by Face.com, id484990787?mt=8, last checked on April 25, 2012 [14] TAT augmented ID,, last checked on April 25, 2012 [15] R. Azuma, Y. Baillot, R. Behreinger, S. Feiner, S. Julier, B. MacInture, Recent developments in augmented reality, IEEE Computer Graphics And Applications, 21(6):34-47, 2001 123
Bibliography [16] Luis Freitas, place-your-bets-2010-location-based-services-augmented-reality, last checked April 26, 2012 [17] Layar,, last checked on April 26, 2012 [18] R. Scott Macintosh, Portable Real Estate Listings âĂŤ but With a Difference, 26iht-rear.html?_r=1, last checked on April 26, 2012 [19] Niels Beukers, Social annotations in augmented reality, KU Leuven, 2012 [20] OpenGL,, last checked on April 26, 2012 [21] Augmented driving,, last checked on April 26, 2012 [22] Unbiased data-driven comparisons,. com/, last checked on April 26, 2012 [23], last checked on May 20, 2012 [24] Twitter,, last checked on April 26, 2012 [25] Google+,, last checked on April 26, 2012 [26] LinkedIn,, last checked on April 26, 2012 [27] Last.fm,, last checked on April 26, 2012 [28] Flickr,, last checked on April 26, 2012 [29] Slideshare,, last checked on April 26, 2012 [30] DeviantART,, last checked on April 26, 2012 [31] Hyves,, last checked on April 26, 2012 [32] Adam Pash, 3 Social Media Aggregators That Bring It All Together, PCWorld, August 4, 2009 [33] FriendFeed,, last checked on April 29, 2012 [34] FriendStream,, last checked on April 29, 2012 [35] FriendStream screenshot, android-tips-htc-friend-stream/, last checked on April 29, 2012 [36] Gonzalo Parra, Joris Klerkx, Erik Duval, More!: Mobile Interaction with Linked Data, KU Leuven 124
Bibliography [37] QR codes,, last checked on April 29, 2012 [38] Erik Duval, paper prototyping, paper-prototyping-12082416, last checked on April 29, 2012 [39] Lewis, C. H., Using the "Thinking Aloud" Method In Cognitive Interface Design [40] Gary Perlman, User Interface Usability Evaluation with Web-Based Questionnaires,, last updated november 24, 2011, last checked on April 29, 2012 [41] Vcard,, last checked on May 1, 2012 Information about prosopagnosia,. [42] Dr Sarah Bate, prosopagnosiaresearch.org/index/information, last checked on May 1, 2012 [43] comScore Reports March 2012 U.S. Mobile Subscriber Market Share, comScore_Reports_March_2012_U.S._Mobile_Subscriber_Market_Share, last check May 2, 2012 [44] iOS Human Interface Guidelines, ios/DOCUMENTATION/UserExperience/Conceptual/MobileHIG/MobileHIG. pdf, Apple, 2007 [45] USE Questionnaire,, last checked on May 13, 2012 [46] Arnold M. Lund, Measuring Usability with the USE Questionnaire,. stcsig.org/usability/newsletter/0110_measuring_with_use.html, last checked on May 13, 2012 [47] The objective-c programming language, library/mac/documentation/Cocoa/Conceptual/ObjectiveC/ObjC.pdf, Apple, 2011 [48] Joe Conway, Aaron Hillegass, iOs programming, the big nerd ranch guide, The big nerd ranch, Atlanta USA, 2011 [49] Paul Hegarty, iPhone and iPad application development, Stanford University, California USA, 2011. [50] Cocoa Encyclopedia p.43, mac/documentation/General/Conceptual/CocoaEncyclopedia/ CocoaEncyclopedia.pdf, last updated February 16, 2012, last checked on May 19, 2012. 125
Bibliography [51] SquareCam, SquareCam/Introduction/Intro.html, last checked on May 20, 2012. [52] @Sergimtzlosa, FaceWrapper, faceWrapper-iphone, last checked on May 20, 2012. [53] Facebook iOS SDK Reference, reference/iossdk/, last checked on May 20, 2012. [54] Frans Van Assche, D9.1 - analysis and design documents for the directory, Deliverable for the ITEC project, p. 18.
126
K.U.Leuven Faculteit Ingenieurswetenschappen
2011 – 2012
Fiche masterproef
Student: Gerry Hendrickx Titel: Discovering digital identities through face recognition on mobile devices UDC : 681.3 Korte inhoud: Het internet heeft de manier waarop mensen met elkaar communiceren gerevolutionaliseerd. Verschillende sociale netwerken zijn ontstaan om deze communicatie op verschillende levels te ondersteunen. Ze beginnen een steeds grotere rol te spelen in de levens van hun leden en hebben elks hun eigen focus. Door deze focus gaan mensen zich inschrijven voor meerdere netwerken: één voor elke nood. Hun informatie is verdeeld onder deze netwerken en vormt in zijn geheel de digitale identiteit van de gebruiker, zijn online alter ego. Door deze verspreiding van informatie wordt het opzoeken van de digitale identiteit van een gebruiker een omslachtige taak. Het doel van deze thesis is om deze taak te versimpelen door gebruik te maken van gezichtsherkenning op mobiele toestellen. De thesis presenteert het onderzoek en de studie van gerelateerd werk dat uitgevoerd is om ideeën te verkrijgen en startpunten te vinden. Dit onderzoek, gecombineerd met een breinstorm en een enquête, werd geanalyseerd en leidde tot het volgende concept: een mobiele applicatie die in staat is mensen te herkennen en hun digitale identiteit weer te geven in reële tijd. Het ontwerp en de ontwikkeling van de applicatie zijn iteratief aangepakt. We bespreken de eerste papieren prototypes van 3 verschillende gebruikersinterfaces, waarvan er één geselecteerd en uitgewerkt is. Dit prototype van de gebruikersinterface werd tweemaal geëvalueerd en aangepast alvorens te starten aan de eigenlijke implementatie. De ontwikkeling gebeurde in 2 iteraties: de eerste focust op de hoofdfunctionaliteit van de applicatie, de gezichtsherkenning. Deze versie is geëvalueerd en leidde tot een tweede digitale prototype, dewelkde een volledig werkende gezichtsherkennings applicatie is die alle functionaliteiten ingebouwd heeft. Een database wordt gebruikt om de gebruikersnamen van sociale netwerken van de gebruikers op te slaan, wat de applicatie toelaat om een herkend persoon te linken aan zijn sociale netwerken.
This action might not be possible to undo. Are you sure you want to continue?
We've moved you to where you read on your other device.
Get the full title to continue reading from where you left off, or restart the preview. | https://www.scribd.com/document/97193828/Discovering-digital-identities-through-face-recognition-on-mobile-devices | CC-MAIN-2017-04 | refinedweb | 36,952 | 56.25 |
CrossTrainer: Practical Domain Adaptation with Loss Reweighting
Project description
CrossTrainer: Practical Domain Adaptation with Loss Reweighting
This is an implementation of the method described in "CrossTrainer: Practical Domain Adaptation with Loss Reweighting" by Justin Chen, Edward Gan, Kexin Rong, Sahaana Suri, and Peter Bailis.
Install
The crosstrainer package can be installed using pip.
pip install crosstrainer
Usage
CrossTrainer utilizes loss reweighting to train machine learning models using data from a target task with supplementary source data.
Inputs:
Base model, target data, source data.
Outputs:
Trained model with optimized weighting parameter alpha.
Example:
import crosstrainer from sklearn import linear_model lr = linear_model.LogisticRegression() ct = CrossTrainer(lr, k=5, delta=0.01) lr, alpha = ct.fit(X_target, y_target, X_source, y_source) y_pred = lr.predict(X_test)
More examples can be found in the tests file:
crosstrainer/tests/test_crosstrainer.py.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/crosstrainer/ | CC-MAIN-2021-21 | refinedweb | 157 | 50.84 |
Learn how to use CAShapeLayer to draw and stroke arbitrary paths thus creating cool effects in your apps.
This is a companion discussion topic for the original entry at
Learn how to use CAShapeLayer to draw and stroke arbitrary paths thus creating cool effects in your apps.
HI Caroline ,
I have been using this tutorial actually one of the finished challenged projects provided. I was wondering if you have ever cancelling the CA Layer animation in progress. I crash when I try to reset things mid-flight. Other than that it is running great. I use it to show time remaining a video clips. It shows the person how long for instance to keep their arms up in the air for stretch. Occasionally the video stops faster than the CAAnimation and i try to restart it before completing. I have seen videos referencing the coordination of the AVPlayer and CALayers but I don’t want to go there yet.
Thanks much
Hi Again,
My late my panic has subsided and I re-looked at your code and derived this to do the job.
Thanks again for your video !
func stopAnimation() { CATransaction.begin() fgLayer.removeAnimationForKey("stroke") CATransaction.commit() }
Thanks for letting me know you’ve fixed it
and sorry for not getting back to you earlier. I haven’t seen it crash, so was mulling it over.
Hey, caroline first of all you guys have awesome clarity in concept.
now to the Q.
I know we are supposed to create the projects from the starter one. but i went ahead and created my own from the scratch also instead of putting layouts programmatically i used labels (so without the programmatic constraints ) , but then my CAShapeLayer is not showing in the running app (but it shows in the storyboard (using @IBDesignable) )
import UIKit @IBDesignable class StatView: UIView { let margin : CGFloat = 10 let bgLayer : CAShapeLayer = CAShapeLayer() let fgLayer : CAShapeLayer = CAShapeLayer() @IBInspectable var bgColor : UIColor = UIColor.clearColor() { didSet{ configure() } } @IBInspectable var fgColor : UIColor = UIColor.clearColor(){ didSet{ configure() } } override func awakeFromNib() { super.awakeFromNib() print("Call in awakeFromNib recieved!") setup() configure() } override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() setup() configure() } func setup() { bgLayer.lineWidth = 10 bgLayer.fillColor = nil bgLayer.strokeEnd = 1 fgLayer.lineWidth = 10 fgLayer.fillColor = nil fgLayer.strokeEnd = 0.5 layer.addSublayer(bgLayer) layer.addSublayer(fgLayer) } func configure() { bgLayer.strokeColor = bgColor.CGColor fgLayer.strokeColor = fgColor.CGColor } func degreesToRadian(numberToBeConvertedIntoDegrees : Double) -> CGFloat { let num = (numberToBeConvertedIntoDegrees * M_PI) / 180 return CGFloat(num) } private func setupShapeLayer(shapeLayer : CAShapeLayer) { shapeLayer.frame = self.bounds let startAngle = degreesToRadian(135) let endAngle = degreesToRadian(45) let center = self.center let radius = min(self.bounds.width , self.bounds.height) * 0.35 let path : UIBezierPath = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true) shapeLayer.path = path.CGPath } override func layoutSubviews() { super.layoutSubviews() print("layoutaubviews called!") bgLayer.frame = self.bounds fgLayer.frame = self.bounds setupShapeLayer(bgLayer) setupShapeLayer(fgLayer) } }
this is my code for statView
Thanks in advance!
@darkknight - I can’t tell what’s wrong from that. Are you able to zip up the project and post it?
sorry to bother you…i figured it out! :-))
There is something that I don’t understand?
fgLayer.removeAnimationForKey(“stroke”)
fgLayer.addAnimation(animation, forKey: “stroke”)
why remove/add stroke and not strokeEnd instead?
Thanks!
@andreskwan - “strokeEnd” is the name of the actual property that you want to animate.
“stroke” is a name I made up.
If you put an “x” in front of “strokeEnd” then the property doesn’t exist and no animation will take place. I thought it would crash, but it just ignores it.
If you change “xstrokeEnd” back to “strokeEnd” and put an “x” in front of both "stroke"s it will work. Because this is a made-up name.
Hi @caroline!
Now I understand that forKey: stroke is the name that we made up for the animation we are adding to the render tree, could be anything! I though that it should be the name of the property we are animating.
Thanks so much!
why hasn’t subtitle in this video
?
Hi Caroline,
thanks for the tutorial, luckily it does not require a lot of tweaks to update it to Swift 3.
I feel that Layer Animations really deserve their own part and that introducing the concept in the challenge document only is a corner cut too much
The challenge is not really a challenge, more a tutorial. Not that this is a bad thing but I think it would be more clear if you dedicated it a separate episode.
Tomasz
@marszalcns - thanks for your feedback
Agreed. I already have a strong understanding of the subject of CALayer basics, but lack the same knowledge of CALayer animations. I watched the videos specifically for the animation portion and was disappointed to see it as a challenge.
When (If) this series is updated for the latest version of Swift, there should be another video added to cover this concept. In the meantime, here is a tutorial on the topic.
For the challenge, is there a disadvantage to simply calling:
fgLayer.strokeEnd = curValue/range
inside of the didSet property observer of curValue? It seems like this gives you the animation effect that we’re looking for in the challenge with just a single line of code. I assume that the challenge solution is the way that will allow for more customization, but is the above solution considered “hacky”?
@iosdevelopr - you’re right. I think from memory that it may have been for added understanding. (But not 100% sure.) There may be an update in the works
, and that will go through some unnecessary code for explanation and then reduce to the final
didSet.
I’ll be on the lookout for that video if/when it happens! I always enjoy your videos. Thank you! | https://forums.raywenderlich.com/t/video-tutorial-calayers-part-3-cashapelayer/7056 | CC-MAIN-2022-33 | refinedweb | 955 | 58.69 |
hi,
I am new to java programming.. I have to do a task where in i have to read a text delimeted file in an array.. For example.. If the file is as follows
Name place Value
adi goa 20
shri mumbai 30
riya bangalr 45
I want it to be read in java so as to get an array[row][columns]
This is something i am currently upto, but cant get any further.
import java.io.BufferedReader;
import java.io.FileReader;
public class generateGML{
public static void main(String[] argv)
throws Exception{
BufferedReader fh = new BufferedReader(new FileReader("miRTarbase.txt"));
String s;
while ((s=fh.readLine())!=null){
String[] columns = s.split("\t");
String name = columns[0];
String place = columns[1];
String value = columns[2];
It reads columns,But I want it two dimentionally,as in something like matrix[row_num][column_num].
Can anyone please suggest me.. | http://www.javaprogrammingforums.com/%20whats-wrong-my-code/8253-how-read-text-delimited-file-using-2-dimentional-array-java-printingthethread.html | CC-MAIN-2016-07 | refinedweb | 146 | 65.93 |
- Author:
- BHSPitMonkey
- Posted:
- April 1, 2014
- Language:
- Python
- Version:
- Not specified
- validation upload magic mimetype FileField
- Score:
- 0 (after 0 ratings)
This validator works well with FileField form fields and can validate that an uploaded file has an acceptable mimetype. Place this snippet in your app's
validators.py.
Requirements:
This snippet uses python-magic. To install:
pip install python-magic
Usage (in forms.py):
from validators import MimetypeValidator class MyForm(forms.Form): file = forms.FileField( allow_empty_file=False, validators=[MimetypeValidator('application/pdf')], help_text="Upload a PDF file" )
More like this
- A form field for valdating PDF and Microsoft Word document by jimmylam 6 years, 9 months ago
- Custom FileField with content type and size validation by nemesis 4 years, 11 months ago
- pyText2Pdf - Python script to convert plain text into PDF file. Modified to work with streams. by vsergeyev 5 years, 9 months ago
- Easy file upload handler by mattdw 6 years, 11 months ago
- Validate by file content type and size by macmichael01 6 years, 6 months ago
Please login first before commenting. | https://djangosnippets.org/snippets/3039/ | CC-MAIN-2015-35 | refinedweb | 174 | 53.31 |
Predict with a pre-trained model¶
A saved model can be used in multiple places, such as to continue training, to fine tune the model, and for prediction. In this tutorial we will discuss how to predict new examples using a pretrained model.
Prerequisites¶
Please run the previous tutorial to train the network and save its parameters to file. You will need this file to run the following steps.
[1]:
from mxnet import nd from mxnet import gluon from mxnet.gluon import nn from mxnet.gluon.data.vision import datasets, transforms from IPython import display import matplotlib.pyplot as plt
To start, we will copy a simple model’s definition.
[2]:))
In the last section, we saved all parameters into a file, now let’s load it back.
[3]:
net.load_parameters('net.params')
Predict¶
Remember the data transformation we did for training? Now we need the same transformation for predicting.
[4]:
transformer = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(0.13, 0.31)])
Now let’s try to predict the first six images in the validation dataset and store the predictions into
preds.
[5]:
mnist_valid = datasets.FashionMNIST(train=False) X, y = mnist_valid[:10] preds = [] for x in X: x = transformer(x).expand_dims(axis=0) pred = net(x).argmax(axis=1) preds.append(pred.astype('int32').asscalar())
Finally, we visualize the images and compare the prediction with the ground truth.
[15]:
_, figs = plt.subplots(1, 10, figsize=(15, 15)) text_labels = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat', 'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot'] display.set_matplotlib_formats('svg') for f,x,yi,pyi in zip(figs, X, y, preds): f.imshow(x.reshape((28,28)).asnumpy()) ax = f.axes ax.set_title(text_labels[yi]+'\n'+text_labels[pyi]) ax.title.set_fontsize(14) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.show()
Predict with models from Gluon model zoo¶
The LeNet trained on FashionMNIST is a good example to start with, but too simple to predict real-life pictures. Instead of training large-scale model from scratch, Gluon model zoo provides multiple pre-trained powerful models. For example, we can download and load a pre-trained ResNet-50 V2 model that was trained on the ImageNet dataset.
[7]:
from mxnet.gluon.model_zoo import vision as models from mxnet.gluon.utils import download from mxnet import image net = models.resnet50_v2(pretrained=True)
We also download and load the text labels for each class.
[8]:
url = '' fname = download(url) with open(fname, 'r') as f: text_labels = [' '.join(l.split()[1:]) for l in f]
We randomly pick a dog image from Wikipedia as a test image, download and read it.
[9]:
url = '\ Golden_Retriever_medium-to-light-coat.jpg/\ 365px-Golden_Retriever_medium-to-light-coat.jpg' fname = download(url) x = image.imread(fname)
Following the conventional way of preprocessing ImageNet data:
Resize the short edge into 256 pixes,
And then perform a center crop to obtain a 224-by-224 image.
[10]:
x = image.resize_short(x, 256) x, _ = image.center_crop(x, (224,224)) plt.imshow(x.asnumpy()) plt.show()
Now you may know it is a golden retriever (You can also infer it from the image URL).
The futher data transformation is similar to FashionMNIST except that we subtract the RGB means and divide by the corresponding variances to normalize each color channel.
[11]:
def transform(data): data = data.transpose((2,0,1)).expand_dims(axis=0) rgb_mean = nd.array([0.485, 0.456, 0.406]).reshape((1,3,1,1)) rgb_std = nd.array([0.229, 0.224, 0.225]).reshape((1,3,1,1)) return (data.astype('float32') / 255 - rgb_mean) / rgb_std
Now we can recognize the object in the image now. We perform an additional softmax on the output to obtain probability scores. And then print the top-5 recognized objects.
[12]:
prob = net(transform(x)).softmax() idx = prob.topk(k=5)[0] for i in idx: i = int(i.asscalar()) print('With prob = %.5f, it contains %s' % ( prob[0,i].asscalar(), text_labels[i]))
As can be seen, the model is fairly confident the image contains a golden retriever. | https://mxnet.apache.org/versions/1.6/api/python/docs/tutorials/getting-started/crash-course/5-predict.html | CC-MAIN-2020-34 | refinedweb | 669 | 52.76 |
Python based Assistance for Docker
Q: I can’t figure out why I would need this
A:
In traditional ways, we make aliases ourselves all over the Docker commands.
The reason why I develop this project is to encourage people to contribute and share their ideas and thoughts into plugins, which would give Tsaotun ability to do those things. And, the aboved thing is just one of things that Tsaotun can achieve, you will be able to load variety of plugins in the future as well.
Besides, if you are doing some projects involved running containers, Tsaotun has provide the higher level API for you. That is another helpful functionality.
Currently, I’m moving my previous project VWGen into one of Tsaotun’s plugin. Once I finish, everyone can just load the plugin and extend the power of Tsaotun.
Contents
1 Main features
- Run any commands docker can run on Tsaotun
- All written in Python with love of API of docker
- Simplify the process making your own implementation of docker command line tool
- Many Addons are upcoming
2 Installation (All platforms)
2.1 pip
A universal installation method (that works on Windows, Mac OS X, Linux, and always provides the latest version) is to use pip:
# Make sure we have an up-to-date version of pip and setuptools: $ pip install --upgrade pip setuptools $ pip install --upgrade tsaotun
(If pip installation fails for some reason, you can try easy_install tsaotun as a fallback.)
2.2 Docker hub
Pull from dockerhub, or build it yourself:
$ docker build -t tsaotun .
Verify that now we have installed the latest version, for example:
$ tsaotun version Client: Version: 0.8.1 Python version: 2.7.13 OS/Arch: Darwin/x86_64 Server: Version: 1.13.0-rc7 API version: 1.25 (minimum version 1.12) Go version: go1.7.3 Git commit: 48a9e53 Built: 5 days ago OS/Arch: linux/amd64 Kernel version: 4.9.3-moby Experimental: True
3 Usage
Hello World:
$ tsaotun [COMMAND]
Synopsis:
$ tsaotun [-h] [--console] [--color] [--debug] [--dry] [--host list] [--verbose] {version,info,inspect,container,image,network,volume,addon} ...
See also tsaotun --help.
4 Addon
Addon feature is testing right now, and each addon should has its own folder with __init__.py inside.
Addon folder struture shows like:
$HOME └───Tsaotun └───addons ├── addon_A - __init__.py, ... ├── addon_B - __init__.py, ... └───__init__.py
4.1 Best practices (Sample addon to remove “ALL” containers at once, no matter it’s dead or alive)
__init__.py: To specify how to override the original command
"""Configuration file for this addon""" from .Container import rm __override__ = {'Container.rm': 'Rm'} __argparse__ = [ { 'namespace': "Container", 'position': "Child", 'subcommand': "rm", 'actions': [ "add_argument('--clear', \ action='store_true', \ dest='clear', \ help='Remove all dead and alive containers. \ You still need to give a whatever container ID.')", ], }, ]
Container/rm.py
"""This module contains `docker container rm` class""" from docker.errors import APIError from tsaotun.lib.Docker.Container.command import Command from tsaotun.cli import Tsaotun class Rm(Command): """This class implements `docker container rm` command""" name = "container rm" require = [] def __init__(self): Command.__init__(self) self.settings[self.name] = None def eval_command(self, args): try: containers = args["containers"] clear = args["clear"] del args["containers"] del args["clear"] Ids = [] if clear: cli = Tsaotun() cli.send('ps -a --format {{Id}}') ress = cli.recv() if ress: ress = ress.split('\n') ress = [res[0:4] for res in ress] for Id in ress: Ids.append(Id) args['container'] = Id self.client.remove_container(**args) else: for Id in containers: Ids.append(Id) args['container'] = Id self.client.remove_container(**args) self.settings[self.name] = '\n'.join(Ids) except APIError as e: raise e def final(self): return self.settings[self.name]
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/tsaotun/ | CC-MAIN-2017-34 | refinedweb | 628 | 57.87 |
We have an Net-application using WPF for GUI and Entitiy Framework 4.3 for database connection.
We are using a repositorypattern with UnitOfWork-objects that holds the EF-context.
We have problem when we do a search against the database, the memory used by the application increases with every search.
All communication with the database goes through serviceclasses and we create a new instance of these classes for every search.
When we analyze the result from Ants Memory Profiler we see that all of our own objects seems to "die" between every search, the
number of instances does not increase.
But for some objets in the system.data-namespace, for example EntityKey , the number of instances and memory used increases for every search.
We wonder why the GC does not remove these objects? We create new instances of our UoW-object and EF-context in every instance of the serviceclasses. The UoW object implements IDisposable and dispose the EF-context.
We can see that a couple of the EntityKey-instances are "GCRoot Object" , can that be a cause to the problem?
Hi Hasse,
Welcome to the MSDN forum.
EF 5 is released now, could you please try it again to see if the problem still exists?
Have a nice day.
Alexander Sun [MSFT]
MSDN Community Support | Feedback to us | https://social.msdn.microsoft.com/Forums/en-US/6d1ce207-cf97-4b5c-ba99-ee713c106c0c/memory-problem-with-entity-framework-43?forum=adodotnetentityframework | CC-MAIN-2020-40 | refinedweb | 220 | 66.64 |
Published 2 weeks ago by RossUK
Hi, I am trying to do some unit/feature testing and take a TDD approach to a new Laravel project. I am trying to get my head around which tests I should be writing and also which tests are a feature or a unit. As an example to start off with I have a Customer model and a Contact model. When the app is finished an authenticated end user will be able to create edit and delete customers and contacts and also add contacts to a customer. Before any webforms exists what tests should/would be good to write for this.
here what I have so far but want to check I am not going completely in the wrong direction :)
<?php namespace Tests\Unit; use App\Customer; use Tests\TestCase; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Foundation\Testing\RefreshDatabase; class CustomerTest extends TestCase { /** * A basic test example. * * @return void */ use RefreshDatabase; use WithFaker; protected $customer; public function setUp() { parent::setUp(); $this->customer = factory('App\Customer')->create(); } /** @test */ public function testCustomerCanBeCreated() { $this->assertEquals(1, Customer::count()); } /** @test */ public function canEditCustomer() { //set test data $data = [ 'company_name' => "New Company Inc", ]; //make post request with test data to named route $this->post(route('customers.store'), $data)->assertStatus(201); $this->call('POST', '[email protected]', $data); //get first record $customer = Customer::first(); //check database values exist $this->assertEquals($data['company_name'], $customer->company_name); } public function canUpdateCustomer() {} public function canDeleteCustomer() {} public function canAddContactToCustomer() {} public function canGetCustomerContacts() {} }
Many Thanks
Instead of writing in detail how I would go about this I recommend watching the Unlocking Badges Workshop or Let's build a forum with TDD.
Jeffrey jumps between Feature and Unit tests. But when you start from zero, it makes sense to start with a feature of your app and write some feature tests. In the middle of those tests you might find the need to write a unit test and then go back to the feature test...
As for what is a Feature test and what is a Unit test: Watching those videos will explain it much better than I can... a feature test tests features (duh!) of your app, for example "An Authenticated User Can Delete Customers". That would probably test a http endpoint used to delete Customers.
While writing said test ("An Authenticated User Can Delete Customers") you might find you want to write a test to make sure that deleting a
Customer with the
Eloquent method
delete will not (or WILL, whatever is correct in your case) delete the
Contacts which "belonged" to the deleted Customer. That would belong to the unit tests, in my book.
But Jeffrey explains it much better ;-)
Your example falls more under Feature Tests - it tests routes or http endpoints of your application. A Feature is (in my opinion) something your App DOES.
A Unit is a small (the "smallest"?) part of your app, which can be tested in "isolation". For example, if you have methods on your model
Customer, you might (it is totally up to you) want to test each method separately in
Tests\Unit\CustomerTest.
Hi,
Thanks. I have been going through the forum tutorial and trying to apply the testing logic to my own example. Thanks for helping me clear up the differences between a feature and a unit.
Is testing at route level a typical work flow or would it be better to test at browser level therefore testing the routing at the same time? I suppose that's what Jeffery does in the forum tutorial :)
At browser level (you probably mean
Dusk) ist different. You will run into problems using
RefreshDatabase, for example.
But Dusk is a great tool! I use it to make sure clicking buttons and filling forms etc. works the way it is supposed to. Also it is great to test stuff that has been added to your site by JavaScript.
But will have to rely on certain DOM elements to exist and having specific classes, IDs or attributes - that is a specificity which should not matter in feature tests.
For testing routes I would stick to Feature Test (HTTP Tests) - it is much simpler, and in tests one should stick to the simplest possible way, I think.
The feature test should be
"An authenticated User can call
route('make-some-noise') and some noise should be made",
That test should keep working, no matter how you structure your frontend code.
You can of course write a Browser test:
"Someone visits the login page, fills in the login form (targeted by ìnput[name=username]` etc), clicks the Submit button, lands on another page, clicks the Button "Make some noise"....
And so on, but that probably should be broken up into multiple smaller test methods. And in my opinion this should not replace the Feature test.
Please sign in or create an account to participate in this conversation. | https://laracasts.com/discuss/channels/testing/unit-testing-advice?page=1 | CC-MAIN-2018-43 | refinedweb | 813 | 59.84 |
Summary
This blog post will show you how to create a COM (Component Object Model) object in C# that you can use in your classic ASP code. Why would anybody do that? Amazing as it might seem, there is a lot of classic ASP code out there in the form of legacy applications. It’s monstrously difficulty to replace this code due to the fact that classic ASP isn’t compatible with anything and it doesn’t play nice with any other language. So I’m going to show the basic mechanics of how to create a COM object in C# and how to incorporate it in your ASP code.
Writing Your First COM Program
First, let’s write the simplest program possible: Hello World. I am going to follow a similar path as this article (which is where I learned some of this from):
Creating a COM object from scratch with C#
There are a couple of changes I’m going to make because VS 2012 and above have a built-in GUID generator and I want to show how you can build something with no parameters, just to keep it ultra-simple.
Step 1 – Create your C# program
Create a new C# class library project. You’ll need to add a using statement for the interop services library to the top of your code:
using System.Runtime.InteropServices;
Step 2: Construct the Class
For my example, I’m going to make this just a simple class with one method:
public class Launcher
{
public string Hello()
{
return “Hello world“;
}
}
I’m leaving out the constructor, since it’s not used anyway.
Step 3: Presenting our Class Through an Interface
In order to access any methods or classes inside the COM module, we need to provide an interface.
public interface ILauncher
{
string Hello();
}
You’ll also need to add the interface name as the base class for the Launcher object.
Step 4: Making the Connection
We need to add an attribute to our class to make sure it doesn’t automatically generate another interface (we want to use the interface we typed up manually):
[ClassInterface(ClassInterfaceType.None)]
public class Launcher : ILauncher
{
public string Hello()
{
return “Hello world“;
}
}
Next, I’m going to deviate from the original article and allow early and late binding by adding the InterfaceIsDual attribute:
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface ILauncher
{
string Hello();
}
Step 5: Making them Unique
This is where I’m really going to deviate from the original article. You’ll need to generate GUID’s for both the interface and the class. Now go to the “Tools” menu and select “Create GUID”:
Choose #5, and click on the “Copy” button. Then paste it into your code:
[Guid(“6216B529-3E4A-4FE8-8F7A-BE99C33DB1F1“),
InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface ILauncher
{
string Hello();
}
[Guid(“41027763-2E19-415A-8525-F48F604EE810“),
ClassInterface(ClassInterfaceType.None)]
public class Launcher : ILauncher
{
public string Hello()
{
return “Hello world“;
}
}
You might have to remove the square brackets to make the syntax correct (as shown above).
Step 6: Going Underground with Cryptography
This is where you’ll have to drag out the “sn” utility and give your assembly a strong name. You’ll have to search your hard drive for the sn utility and there are probably more than one version. I found mine at this path:
“C:Program Files (x86)Microsoft SDKsWindowsv8.1AbinNETFX 4.5.1 Toolssn”
I chose the latest version that was installed on my PC. You’ll need to open a console window (go to your start menu and type “command” in the search box. Then navigate to the project directory of your application. Then execute the sn utility with the “-k key.snk” parameter:
“C:Program Files (x86)Microsoft SDKsWindowsv8.1AbinNETFX 4.5.1 Toolssn” -k key.snk
You’ll need to keep the path name quoted since it has spaces in it. Once you execute this command there will be a file generated in your project directory named “key.snk”. Now you need to add this file to your project as a link. So right-click on your project and select “Add -> Existing Item”. Don’t hit the “add” button, on the add button there is a down-arrow that allows you to select a different option:
Select “Add As Link”. To use this file, we need to go to the project properties (right-click on your project and select “Properties”). Then select the “Signing” tab. Now click on the “Sign the assembly” check box and choose the “key.snk” file from the drop-down list:
Save your changes.
Step 7: Wrapping it All Up
Before building your solution we need to modify some settings. In Deutschzuid’s article that I cited at the beginning of this blog post, you are directed to change your target build version at this point. I’m going to leave it at “any” (the default). Go back to your project properties and select the “Application” tab. Click on the “Assembly Information” button. Check the “Make Assembly COM-Visible” check box.
Now switch to the “Build” tab and check the “Register for COM interop” check box.
Step 8: Compiling it and Taking it for a Walk
Now you can build the solution.
First, let’s try this in ASP. Make sure you have IIS installed and running on your PC. Create a sub-directory in your C:inetpub directory named “aspcom”. You can startup the IIS control panel (go to your start menu and type “iis” in the search box) and create a new application under your default website. Name your application “aspcom” and point the directory to the new directory you just created. You’ll need to click on “Edit permissions” and the directory properties window will pop-up. Click on the “Security” tab. Click “Edit” then “Add”, then type in “IUSR” and click “Check Names”. Then click “OK”, then check the “allow full control” check box. Then “OK”,
Then repeat: “Edit”, “Add”, type “IIS_IUSRS” and click “Check Names”. You might need to change your domain to the local PC domain for this to check right. Then “OK”, then “allow full access”, then “OK” and last “OK” to close the properties window.
Now you’ll need to add those same two rights to the directory that contains your COM object project. Just navigate to your project directory and right-click on it. Then repeat the steps above to give full rights to “IUSR” and IIS_IUSRS”.
Restart IIS.
Now create a text file inside the C:inetpubaspcom directory named “home.asp” and type (or copy) this in:
<%
Dim MyComObject
Dim MyText
Set MyComObject = Server.CreateObject(“Launcher.Launcher”)
MyText = MyComObject.Hello()
%>
<html>
<head></head>
<body>
<%=MyText %>
</body>
</html>
In the IIS control panel is a link called “browse” with a url on it. You can click this link to get to the ASP directory, but you’ll have to add home.asp to the end of the path. Then you should see “hello world” printed on your browser.
Next, create a text file on your desktop and name it “test.html”. Now type or copy this into it:
<HTML>
<HEAD>
<SCRIPT language=”javascript”>
function Test() {
var objTest = new ActiveXObject(“Launcher.Launcher”);
alert(objTest.Hello());
}
</SCRIPT>
</HEAD>
<BODY>
<INPUT Type=”button” onClick=”Test()” Value=”Click here to test!”>
</BODY>
</HTML>
Now save it and double-click on the html file. You’ll have to allow blocked content then click the button. Then answer yes to the active-x control warning and you’ll see a text box displaying “hello world” in it.
Step 9: Deploying the dll on Another Machine
If you want to deploy the dll on another machine, you’ll have to add your dll to the registry by using the regasm utility. First, copy your dll to the target machine (just the dll). Then you need to find the regasm program on your pc, just like you did with the sn utility above. Choose the latest version. Navigate to your dll’s location and use this command:
regasm ComClassExample.dll /codebase /tlb /nologo
For testing purposes, you don’t need to use regasm.
Troubleshooting Tricks
OK, now there is an issue if you are attempting to change your COM program after you have executed it from an ASP program. That issue is that IIS has the DLL locked and you can’t re-compile. So you’ll need to reset your IIS before you re-build your application. Then you can run your ASP program again.
Next, you are going to want to know what is going on while you are troubleshooting this project. Especially if it doesn’t work the first time. So in the IIS console, click on your application (aspcom), double-click on the ASP icon:
Expand your “Debugging Properties” section and change “Enable Client-side Debugging” to true and also change “Enable Server-side Debugging” to true. Click on “apply”.
Now, if something blows up, you can attach a debugger and see where it breaks in Visual Studio. You can also get a good error message, like “permission denied”.
Don’t forget about the IIS log files. They are located in the C:inetpublogs directory. These are usually pretty cryptic, but sometimes they can shine some light on what’s wrong.
You can also open your home.asp page in Visual Studio and put a break-point on it. Then choose “Debug -> Attach to Process…”, then select w3wp.exe and click the “attach” button. Refresh the web page and the breakpoint should be hit. You cannot get tool tip help in asp, but you can put a variable in your watch list and see what is contained in the variable.
One other annoying thing you might run into. If you click the “Restart” button in the IIS control panel and your IIS does’t restart (it just sits there scanning, like it’s waiting for something) that means that there is a w3wp.exe process holding it up. Just CTRL-ALT-Delete and start task manager. Then find all w3wp.exe processes and “end process”. You’ll notice that your IIS control panel will suddenly respond.
Download the Source
You can download the source code from my GitHub account by clicking here. | http://blog.frankdecaire.com/2015/01/31/creating-a-com-object-for-classic-asp/ | CC-MAIN-2018-05 | refinedweb | 1,703 | 73.37 |
Today we will continue with our draw’s class in Pygame and in this article we will draw a Polygon object with the pygame.draw.polygon method. This polygon method will take in a few arguments. 1) The screen surface 2) The color of the Polygon 3) An array of tuples contain the x, y coordinate 4) An optional width value if stated then the pygame.draw.polygon method will draw a hollow Polygon object or else the Polygon will be filled with solid color.
In the following script, after you have clicked on any 5 locations on the screen then the pygame.draw.polygon method will start to draw Polygon on the surface of that screen!
import pygame from pygame.locals import * from sys import exit pygame.init() screen = pygame.display.set_mode((640, 480), 0, 32) cooordinate = [] while True: for event in pygame.event.get(): if event.type == QUIT: exit() if event.type == MOUSEBUTTONDOWN: #if mouse click then coordinate array will append x,y tuple cooordinate.append(event.pos) screen.fill((255,255,255)) screen.lock() if len(cooordinate) >= 5: pygame.draw.polygon(screen, (255,255,100), cooordinate, 3) screen.unlock() pygame.display.update()
Click on more positions on the screen and the shape will now change accordingly.
| http://gamingdirectional.com/blog/2016/08/28/draw-polygon-with-pygame/ | CC-MAIN-2019-18 | refinedweb | 209 | 60.41 |
inet6_option_append()
Append an IPv6 hop-by-hop or destination option to an ancillary data object
Synopsis:
#include <netinet/in.h> int inet6_option_append(struct cmsghdr *cmsg, const u_int8_t *typep, int multx, int plusy);
Arguments:
- cmsg
- A pointer to the cmsghdr structure that must have been initialized by inet6_option_init().
- typep
- A pointer to the 8-bit option type. It's assumed that this field is immediately followed by the 8-bit option data length field, which is then followed by the option data. You must initialize these three fields (the type-length-value, or TLV) before calling this function.
The option type must have a value from 2 to 255, inclusive. (0 and 1 are reserved for the Pad1 and PadN options, respectively.)
The option data length must be between 0 and 255, inclusive, and is the length of the option data that follows.
- multx
- The value x in the alignment term xn + y. It must have a value of 1, 2, 4, or 8.
- plusy
- The value y in the alignment term xn + y. It must have a value between 0 and 7, inclusive.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
This inet6_option_append() function appends a hop-by-hop option or a destination option to an ancillary data object that has been initialized by inet6_option_init().
See also:
-. | http://developer.blackberry.com/playbook/native/reference/com.qnx.doc.neutrino.lib_ref/topic/i/inet6_option_append.html | CC-MAIN-2019-35 | refinedweb | 224 | 64.61 |
Question:
In many discussions I have heard about Ruby in which people have expressed their reservations about the language, the issue of monkey patching comes up as one of their primary concerns.
However, I rarely hear the same arguments made in the context of Python although it is also permitted in the Python language.
Why this distinction?
Does Python include different types of safeguards to minimize the risks of this feature?
Solution:1
As a Python programmer who has had a taste of Ruby (and likes it), I think there is somewhat of an ironic parallel to when Python was beginning to become popular.
C and Java programmers would âbashâ Python, stating that it wasn't a real language, and that the dynamic nature of its types would be dangerous, and allow people to create âbadâ code. As Python became more popular, and the advantages of its rapid development time became apparent, not to mention the less verbose syntax:
// Java Person p = new Person();
# Python p = Person()
we began to see some more dynamic features appear in later versions of Java. Autoboxing and -unboxing make it less troublesome to deal with primitives, and Generics allow us to code once and apply it to many types.
It was with some amusement that I saw one of the key flexible features of Ruby â" Monkey Patching, being touted as dangerous by the Python crowd. Having started teaching Ruby to students this year, I think that being able to âfixâ the implementation of an existing class, even one that is part of the system, is very powerful.
Sure, you can screw up badly and your program can crash. I can segfault in C pretty easily, too. And Java apps can die flaming death.
The truth is, I see Monkey Patching as the next step in dynamic and meta-programming. Funny, since it has been around since Smalltalk.
Solution:2
It's a technique less practised in Python, in part because "core" classes in Python (those implemented in C) are not really modifiable. In Ruby, on the other hand, because of the way it's implemented internally (not better, just different) just about anything can be modified dynamically.
Philosophically, it's something that tends to be frowned on within the Python community, distinctly less so in the Ruby world. I don't know why you assert that it's more controversial (can you link to an authoritative reference?) - my experience has been that monkey-patching is an accepted technique if one where the user should be aware of possible consequences.
Solution:3
The languages might permit it, but neither community condones the practice. Monkeypatching isn't condoned in either language, but you hear about it more often in Ruby because the form of open class it uses makes it very, very easy to monkeypatch a class and because of this, it's more acceptable in the Ruby community, but still frowned upon. Monkeypatching simply isn't as prevalent or as easy in Python, which is why you won't hear the same arguments against it in that community. Python does nothing that Ruby doesn't do to prevent the practice.
The reason you hear/read about it more often in Ruby is that this in Ruby:
class MyClass def foo puts "foo" end end
class MyClass def bar puts "bar" end end
will give you a class that contains two methods,
foo and
bar, whereas this in Python:
class MyClass: def foo(self): print "foo"
class MyClass: def bar(self): print "bar"
will leave you with a class that only contains the method
bar, as redefinition of a class clobbers the previous definition completely. To monkeypatch in Python, you actually have to write this:
class MyClass: def foo(self): print "foo"
def bar(self): print "bar" MyClass.bar = bar
which is harder than the Ruby version. That alone makes Ruby code much easier to monkeypatch than Python code.
Solution:4
"Does Python include different types of safeguards to minimize the risks of this feature?"
Yes. The community refuses to do it. The safeguard is entirely social.
Solution:5
Actually in Python it's a bit harder to modify basic types.
For example imagine, that you redefine integer.
Ruby:
class Fixnum def *(n) 5 end end
Now 2*2 yields 5.
Python:
>>> class int(int): def __mul__(self, x): return 5 >>> 2*2 4 >>> int(2)*int(2) 5
Solution:6
In Python, any literal (
"",
{},
1.0, etc) creates an instance of the standard class, even if you tried to monkeypatch it and redefined the corresponding class in your namespace.
It just won't work how you intended:
class str(): # define your custom string type ... a = "foo" # still a real Python string a = str("foo") # only this uses your custom class
Solution:7
I think that monkey patching should only be used as the last solution.
Normally Python programmers know how a class or a method behave. They know that class xxx is doing things in a certain way.
When you monkey patch a class or a method, you are changing it's behavior. Other Python programmers using this class can be very surprised if that class is behaving differently.
The normal way of doing things is subclassing. That way, other programmers know that they are using a different object. They can use the original class or the subclass if they choose to.
Solution:8
If you want to do some monkey patching in Python, it is relatively easy, as long as you are not modifying a built-in type (int, float, str).
class SomeClass: def foo(self): print "foo" def tempfunc(self): print "bar" SomeClass.bar = tempfunc del tempfunc
This will add the bar method to SomeClass and even existing instances of that class can use that injected method.
Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
EmoticonEmoticon | http://www.toontricks.com/2018/05/tutorial-if-monkey-patching-is.html | CC-MAIN-2018-47 | refinedweb | 985 | 60.45 |
Hi,
I am migrating my components from Solution accelerator 111150 to 111181. I have modified the names spaces for task and removed the references of workflow.xsd and replaced it with "oramds:///soa/shared/workflow/WorkflowTask.xsd". I am facing the issue of mismatch for targetnamespace there after. While re-building the composite i get below error.
Error: Error loading schema from file:/C:/Sharing/ATFL/SourceCode/SupplierMaintenance/SupplierMaintenance.wsdl [Cause=mistmatch for targetNamespace between and for import]
and below that there are numerous errors. I believe those are due to this first line. where am i going wrong?
Regards.
In SupplierMaintenance.wsdl file look for name space task
<xsd:import namespace="" ............/>
check the schemaLocation attribute in the above element. Correct it and it should resolve your issue.
Ideally it should be
schemaLocation="oramds:///soa/shared/workflow/WorkflowTask.xsd"
Regards,
Vikrant Korde.
Target Namespace mismatch issue usually happens if the namespace declared and the one imported does not match.
Did you try to compare the schema namespace and the one declared in wsdl? | https://community.oracle.com/message/12582741 | CC-MAIN-2017-30 | refinedweb | 173 | 53.47 |
This article is not a substitute for the documentation contained within the web site. This site provides full documentation for the current version of the OpenMP API. In parallel computing, the strongest use of implicit threading is a specification called OpenMP. While considered to be an implicit threading library, OpenMP, or Open Multi-Processing, is an Application Program Interface (API) that may be used to explicitly direct multi-threaded, shared memory parallelism. OpenMP is not guaranteed to make the most efficient use of shared memory, so it is not meant for distributed memory parallel systems itself. OpenMP implements concurrency through special pragmas and directives inserted into your source code to indicate segments that are to be executed concurrently. These pragmas are recognized and processed by the compiler. This means that OpenMP capitalizes from the multi-core processor architecture. In short, it is vital to understand OpenMP in order to use these new multi-core processor architectures effectively.
Implicit threading libraries take care of much of the intricacies needed to create, manage, and (to some extent) synchronize threads. OpenMP is intended to be suitable for implementation on a broad range of SMP architectures, but it is not a new programming language. Rather, it is notations that can be added to a sequential program in FORTRAN, C, or C++ to describe how the work is to be shared among threads that will execute on different processors or cores and to order accesses to shared data as needed. The appropriate insertion of OpenMP features into a sequential program will allow many, perhaps most, applications to benefit from shared-memory parallel architectures, often with minimal modification to the code. In practice, many applications have considerable parallelism that can be exploited.
The success of OpenMP can be attributed to a number of factors. One is its strong emphasis on structured parallel programming. Another is that OpenMP is comparatively simple to use, since the burden of working out the details of the parallel program is up to the compiler. It has the major advantage of being widely adopted, so that an OpenMP application will run on many different platforms. But above all, OpenMP is timely. With the strong growth in deployment of both small and large SMPs and other multithreading hardware, the need for a shared-memory programming standard that is easy to learn and apply is accepted in the computing industry. This, in turn, means that all the major compilers--the Microsoft Visual C/C++ .NET for Windows and the GNU GCC compiler for Linux, and the Intel C/C++ compilers, for both Windows and Linux, also support OpenMP.
OpenMP directives demarcate code that can be executed in parallel (called parallel regions) and control how code is assigned to threads. The threads in an OpenMP code operate under the fork-join model. When the main thread encounters a parallel region while executing the application, a team of threads is forked off, and these threads begin executing the code within the parallel region. At the end of the parallel region, the threads within the team wait until all the other threads in the team have finished before being 'joined'. The main thread resumes serial execution with the statement following the parallel region. The implicit barrier at the end of all parallel regions (and most other constructs defined by OpenMP) preserves sequential consistency.
OpenMP's directives let the user tell the compiler which instructions to execute in parallel and how to distribute them among the threads that will run the code. An OpenMP directive is an instruction in a special format that is understood by OpenMP compilers only. In fact, it looks like a comment to a regular FORTRAN compiler or a pragma to a C/C++ compiler, so that the program may run just as it did beforehand if a compiler is not OpenMP-aware. The API does not have many different directives, but they are powerful when used effectively. So, stated crudely, OpenMP realizes a shared-memory (or shared address space) programming model. This model assumes, as its name implies, that programs will be executed on one or more processors that share some or all of the available memory. Shared-memory programs are typically executed by multiple independent threads (execution states that are able to process an instruction stream); the threads share data, but may also have some additional, private data.
Shared-memory approaches to parallel programming must provide, in addition to a normal range of instructions, a means for starting up threads, assigning work to them, and coordinating their accesses to shared data, including ensuring that certain operations are performed by one thread at a time. To reiterate, OpenMP implements concurrency through special pragmas and directives inserted into your source code to indicate segments that are to be executed concurrently. These pragmas are recognized and processed by the compiler. This pragma will be followed by a single statement or block of code enclosed with curly braces. When the application encounters this statement during execution, it will fork a team of threads, execute all of the statements within the parallel region on each thread, and join the threads after the last statement in the region.
In many applications, a large number of independent operations are found in loops. Using the loop worksharing construct in OpenMP, you can split up these loop iterations and assign them to threads for concurrent execution. The parallel for construct will initiate a new parallel region around the single for loop following the pragma, and divide the loop iterations among the threads of the team. Upon completion of the assigned iterations, threads sit at the implicit barrier at the end of the parallel region, waiting to join with the other threads. It is possible to split up the combined parallel for construct into two pragmas: a parallel construct and the for construct, which must be lexically contained within a parallel region. Use this separation when there is parallel work for the thread team other than the iterations of the loop. You can also attach a schedule clause to the loop worksharing construct to control how iterations are assigned to threads. The static schedule will divide iterations into blocks and distribute the blocks among threads before the loop iterations begin execution; round robin scheduling is used if there are more blocks than threads. The dynamic schedule will assign one block of iteration per thread in the team; as threads finish the previous set of iterations, a new block is assigned until all the blocks have been distributed. There is an optional chunk argument for both static and dynamic scheduling that controls the number of iterations per block. So, let's take a look at an example:
#include <stdio.h>
#include <stdlib.h>
int main(argc,argv)
int argc; char *argv[];
{
double sum;
double a [256], b [256];
int status;
int n=256;
int i;
for ( i = 0; i < n; i++) {
a [i] = i * 0.5;
b [i] = i * 2.0;
}
sum = 0;
#pragma omp parallel for reduction(+:sum)
for (i = 1; i <= n; i++ ) {
sum = sum + a[i]*b[i];
}
printf ("sum = %f \n", sum);
}
Compile: C:\..\..\>cl dot.c
sum = 5559680.000000
Under OpenMP, all data is shared by default. In this case, we are able to parallelize the loop simply by inserting a directive that tells the compiler to parallelize it, and identifying sum as a reduction variable. The details of assigning loop iterations to threads, having the different threads build partial sums, and their accumulation into a global sum are left to the compiler. To repeat, by default, almost all variables in an OpenMP threaded program are shared between threads. The exceptions to this shared access rule are: the loop index variable associated with a loop worksharing construct (each thread must have its own copy in order to correctly iterate through the assigned set of iterations), variables declared within a parallel region or declared within a function that is called from within a parallel region, and any other variable that is placed on the thread's stack (e.g., function parameters). If you use nested loops within a loop worksharing construct in C/C++, only the loop index variable immediately succeeding the construct will automatically be made private. If other variables must be local to threads, such as the loop index variables for nested loops, add a private clause to the relevant construct. A local copy of the variables in the list will be allocated for each thread. The initial value of variables that are listed within the private clause will be undefined, and you must assign value to them before they are read within the region of use.
OpenMP has synchronization constructs that ensure mutual exclusion to your critical regions. Use these when variables must remain shared by all threads, but updates must be performed on those variables in parallel regions. The critical construct acts like a lock around a critical region. Only one thread may execute within a protected critical region at a time. Other threads wishing to have access to the critical region must wait until no thread is executing the critical region. Now, because we said that by default almost all variables in an OpenMP threaded program are shared between threads (that is, there is data passed between the threads), we can recall the exception to this rule and put it to use, that this shared access rule has an exception: the loop index variable associated with a loop worksharing construct.
This code is an example of Loop-Work sharing. In this example, the iterations of a loop are scheduled dynamically across the team of threads. A thread will perform CHUNK iterations at a time before being scheduled for the next CHUNK of work:
#include <omp.h>
#include <sdio.h>
#include <stdlib.h>
#define CHUNKSIZE 10
#define N 100
int main (int argc, char *argv[])
{
int nthreads, tid, i, chunk;
float a[N], b[N], c[N];
/* Some initializations */
for (i=0; i < N; i++)
a[i] = b[i] = i * 1.0;
chunk = CHUNKSIZE;
#pragma omp parallel shared(a,b,c,nthreads,chunk) private(i,tid)
{
tid = omp_get_thread_num();
if (tid == 0)
{
nthreads = omp_get_num_threads();
printf("Number of threads = %d\n", nthreads);
}
printf("Thread %d starting...\n",tid);
#pragma omp for schedule(dynamic,chunk)
for (i=0; i<n; c[%d]="%f\n",tid,i,c[i]);")
c[i]="a[i]";
Number of threads = 1
Thread 0 starting...
Thread 0: c[0]= 0.000000
Thread 0: c[1]= 2.000000
Thread 0: c[2]= 4.000000
Thread 0: c[3]= 6.000000
Thread 0: c[4]= 8.000000
Thread 0: c[5]= 10.000000
Thread 0: c[6]= 12.000000
Thread 0: c[7]= 14.000000
Thread 0: c[8]= 16.000000
Thread 0: c[9]= 18.000000
Thread 0: c[10]= 20.000000
Thread 0: c[11]= 22.000000
Thread 0: c[12]= 24.000000
Thread 0: c[13]= 26.000000
Thread 0: c[14]= 28.000000
Thread 0: c[15]= 30.000000
Thread 0: c[16]= 32.000000
Thread 0: c[17]= 34.000000
Thread 0: c[18]= 36.000000
Thread 0: c[19]= 38.000000
Thread 0: c[20]= 40.000000
. . . stopped here for brevity's sake..
This next example involves combined parallel loop reduction. It demonstrates a sum reduction within a combined parallel loop construct. Notice that default data element scoping is assumed. There are no clauses specifying shared or private variables. OpenMP will automatically make loop index variables private within team:
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
int i, n;
float a[100], b[100], sum;
/* Some initializations */
n = 100;
for (i=0; i < n; i++)
a[i] = b[i] = i * 1.0;
sum = 0.0;
#pragma omp parallel for reduction(+:sum)
for (i=0; i < n; i++)
sum = sum + (a[i] * b[i]);
printf(" Sum = %f\n",sum);
}
Sum = 328350.000000
A common computation is to summarize or reduce a large collection of data to a single value. For example, this may include the sum of the data items or the maximum or minimum of the data set. The algorithm to do such computations has a dependence on the shared variable used to collect the partial and final answers. OpenMP provides a clause to handle the details of a concurrent reduction. The reduction clause requires associative and commutative operations for combining data, as well as a list of reduction variables. Each thread within the parallel team will receive a private copy of the reduction variables to use when executing the assigned computations. Unlike variables contained in a private clause, these private variables are initialized with a value that depends on the reduction operation. At the end of the region with a reduction clause, all local copies are combined using the operation noted in the clause, and the result is stored in the shared copy of the variable. So at this point, let's a look at a numerical computation program, to then look at a threaded parallelized second version.
In Calculus, when we want to compute the area underneath a curve, we draw rectangles that approach the curvilinear line. The curve is continuous, meaning that it has a tangent line at every point. That is, at every single point that comprises the curve, there is a change, a change in direction. This is also called a differential coefficient. Each rectangle has a mid-point, and the rectangle has a height and a width. The narrower the rectangles, the more of them there are to sum. This is called nearing the area. Actually, Numerical Integration is a method of computing an approximation of the area under the curve of a function, especially when the exact integral cannot be solved. For example, the value of the constant Pi can be defined by the following integral. However, rather than solve this integral exactly, we can approximate the solution by the use of numerical integration:
The code in the example shown below is an implementation of the numerical integration midpoint rectangle rule to solve the integral just shown. To compute an approximation of the area under the curve, we must compute the area of some number of rectangles (num_rects) by finding the midpoint (mid) of each rectangle and computing the height of that rectangle (height), which is simply the function value at that midpoint. We add together the heights of all the rectangles (sum) and, once computed, we multiply the sum of the heights by the width of the rectangles (width) to determine the desired approximation of the total area (area) and the value of Pi. This is not a threaded application, but is code to show how it can be threaded when we write the second example:
num_rects
mid
height
sum
width
area
#include <stdio.h>
static long num_rects=100000;
void main()
{
int i;
double mid, height, width, sum = 0.0;
double area;
width = 1.0/(double) num_rects;
for (i = 0; i < num_rects; i++){
mid = (i + 0.5) * width;
height = 4.0/(1.0 + mid*mid);
sum += height;
}
area = width * sum;
printf("Computed pi = %f\n",area);
}
Computed pi = 3.141593
The second application computes an approximation of the value for Pi using numerical integration and the midpoint rectangle rule, as in the first example. The code divides the integration range into num_rect intervals, and computes the functional value of 4.0/(1+x 2) for the midpoint of each interval (rectangle). In other words, the first step in creating an OpenMP program from a sequential one is to identify the parallelism it contains. Basically, this means finding instructions, sequences of instructions, or even large regions of code that may be executed concurrently by different processors:
num_rect
#include <stdio.h>
#include <stdlib.h>
static long num_rects = 1000000;
int main(int argc, char* argv[])
{
double mid, height, width, sum=0.0;
int i;
double area;
width = 1./(double)num_rects;
#pragma omp parallel for private(mid, height) reduction(+:sum)
for (i=0; i < num_rects; i++) {
mid = (i + 0.5)*width;
height = 4.0/(1.+ mid*mid);
sum += height;
}
area = width * sum;
printf("The value of PI is %f\n",area);
}
The value of Pi is 3.141593.
An OpenMP loop worksharing construct has been added. The OpenMP-compliant compiler will insert code to spawn a team of threads, give a private copy of the mid, height, and i variables to each thread, divide up the iterations of the loop between the threads, and finally, when the threads are done with the assigned computations, combine the values stored in the local copies of sum into the shared version. This shared copy of sum will be used to compute the Pi approximation when multiplied by the width of the intervals.
i
Finally, let's examine a matrix multiplication code:
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#define NRA 62 /* number of rows in matrix A */
#define NCA 15 /* number of columns in matrix A */
#define NCB 7 /* number of columns in matrix B */
int main (int argc, char *argv[])
{
int tid, nthreads, i, j, k, chunk;
double a[NRA][NCA], /* matrix A to be multiplied */
b[NCA][NCB], /* matrix B to be multiplied */
c[NRA][NCB]; /* result matrix C */
chunk = 10; /* set loop iteration chunk size */
/*** Spawn a parallel region explicitly scoping all variables ***/
#pragma omp parallel shared(a,b,c,nthreads,chunk) private(tid,i,j,k)
{
tid = omp_get_thread_num();
if (tid == 0)
{
nthreads = omp_get_num_threads();
printf("Starting matrix multiple example with %d threads\n",nthreads);
printf("Initializing matrices...\n");
}
/*** Initialize matrices ***/
#pragma omp for schedule (static, chunk)
for (i=0; i < NRA; i++)
for (j=0; j < NCA; j++)
a[i][j] = i + j;
#pragma omp for schedule (static, chunk)
for (i=0; i<NCA; i++)
for (j=0; j < NCB; j++)
c[i][j] = 0;
/*** Do matrix multiply sharing iterations on outer loop ***/
/*** Display who does which iterations for demonstration purposes ***/
printf("Thread %d starting matrix multiply...\n",tid);
#pragma omp for schedule (static, chunk)
for (i=0; i < NRA; i++) {
for (j=0; j < NCB; j++)
for (k = 0; k < NCA; k++)
c[i][j] += a[i][k] * b[k][j];
}
} // end of parallel region
//**Print Results**//
printf("******************************************************\n");
printf("Result Matrix:\n");
for (i=0; i < NRA; i++)
{
for (j = 0; j < NCB; j++)
printf("%6.2f ", c[i][j]);
printf("\n");
}
printf("******************************************************\n");
printf("Done\n");
}
Starting matrix multiple example with 2 threads
Initializing matrices...
Thread 0 starting matrix multiply...
Thread 1 starting matrix multiply...
Thread=0 did row=0
Thread=1 did row=10
Thread=0 did row=1
Thread=1 did row=11
Thread=0 did row=2
Thread=1 did row=12
Thread=0 did row=3
Thread=1 did row=13
Thread=0 did row=4
Thread=1 did row=14
Thread=0 did row=5
Thread=1 did row=15
Thread=0 did row=6
Thread=1 did row=16
Thread=0 did row=7
Thread=1 did row=17
Thread=0 did row=8
Thread=1 did row=18
Thread=0 did row=9
Thread=1 did row=19
Thread=0 did row=20
Thread=1 did row=30
Thread=0 did row=21
Thread=1 did row=31
Thread=0 did row=22
Thread=1 did row=32
Thread=0 did row=23
Thread=1 did row=33
Thread=0 did row=24
Thread=1 did row=34
Thread=0 did row=25
Thread=1 did row=35
Thread=0 did row=26
Thread=1 did row=36
Thread=0 did row=27
Thread=1 did row=37
Thread=0 did row=28
Thread=1 did row=38
Thread=0 did row=29
Thread=1 did row=39
Thread=0 did row=40
Thread=1 did row=50
Thread=0 did row=41
Thread=1 did row=51
Thread=0 did row=42
Thread=1 did row=52
Thread=0 did row=43
Thread=1 did row=53
Thread=0 did row=44
Thread=1 did row=54
Thread=0 did row=45
Thread=1 did row=55
Thread=0 did row=46
Thread=1 did row=56
Thread=0 did row=47
Thread=1 did row=57
Thread=0 did row=48
Thread=1 did row=58
Thread=0 did row=49
Thread=1 did row=59
Thread=0 did row=60
Thread=0 did row=61
******************************************************
Result Matrix:
0.00 1015.00 2030.00 3045.00 4060.00 5075.00 6090.00
0.00 1120.00 2240.00 3360.00 4480.00 5600.00 6720.00
0.00 1225.00 2450.00 3675.00 4900.00 6125.00 7350.00
0.00 1330.00 2660.00 3990.00 5320.00 6650.00 7980.00
0.00 1435.00 2870.00 4305.00 5740.00 7175.00 8610.00
0.00 1540.00 3080.00 4620.00 6160.00 7700.00 9240.00
0.00 1645.00 3290.00 4935.00 6580.00 8225.00 9870.00
0.00 1750.00 3500.00 5250.00 7000.00 8750.00 10500.00
0.00 1855.00 3710.00 5565.00 7420.00 9275.00 11130.00
0.00 1960.00 3920.00 5880.00 7840.00 9800.00 11760.00
0.00 2065.00 4130.00 6195.00 8260.00 10325.00 12390.00
0.00 2170.00 4340.00 6510.00 8680.00 10850.00 13020.00
0.00 2275.00 4550.00 6825.00 9100.00 11375.00 13650.00
0.00 2380.00 4760.00 7140.00 9520.00 11900.00 14280.00
0.00 2485.00 4970.00 7455.00 9940.00 12425.00 14910.00
0.00 2590.00 5180.00 7770.00 10360.00 12950.00 15540.00
0.00 2695.00 5390.00 8085.00 10780.00 13475.00 16170.00
0.00 2800.00 5600.00 8400.00 11200.00 14000.00 16800.00
0.00 2905.00 5810.00 8715.00 11620.00 14525.00 17430.00
0.00 3010.00 6020.00 9030.00 12040.00 15050.00 18060.00
0.00 3115.00 6230.00 9345.00 12460.00 15575.00 18690.00
0.00 3220.00 6440.00 9660.00 12880.00 16100.00 19320.00
0.00 3325.00 6650.00 9975.00 13300.00 16625.00 19950.00
0.00 3430.00 6860.00 10290.00 13720.00 17150.00 20580.00
0.00 3535.00 7070.00 10605.00 14140.00 17675.00 21210.00
0.00 3640.00 7280.00 10920.00 14560.00 18200.00 21840.00
0.00 3745.00 7490.00 11235.00 14980.00 18725.00 22470.00
0.00 3850.00 7700.00 11550.00 15400.00 19250.00 23100.00
0.00 3955.00 7910.00 11865.00 15820.00 19775.00 23730.00
0.00 4060.00 8120.00 12180.00 16240.00 20300.00 24360.00
0.00 4165.00 8330.00 12495.00 16660.00 20825.00 24990.00
0.00 4270.00 8540.00 12810.00 17080.00 21350.00 25620.00
0.00 4375.00 8750.00 13125.00 17500.00 21875.00 26250.00
0.00 4480.00 8960.00 13440.00 17920.00 22400.00 26880.00
0.00 4585.00 9170.00 13755.00 18340.00 22925.00 27510.00
0.00 4690.00 9380.00 14070.00 18760.00 23450.00 28140.00
0.00 4795.00 9590.00 14385.00 19180.00 23975.00 28770.00
0.00 4900.00 9800.00 14700.00 19600.00 24500.00 29400.00
0.00 5005.00 10010.00 15015.00 20020.00 25025.00 30030.00
0.00 5110.00 10220.00 15330.00 20440.00 25550.00 30660.00
0.00 5215.00 10430.00 15645.00 20860.00 26075.00 31290.00
0.00 5320.00 10640.00 15960.00 21280.00 26600.00 31920.00
0.00 5425.00 10850.00 16275.00 21700.00 27125.00 32550.00
0.00 5530.00 11060.00 16590.00 22120.00 27650.00 33180.00
0.00 5635.00 11270.00 16905.00 22540.00 28175.00 33810.00
0.00 5740.00 11480.00 17220.00 22960.00 28700.00 34440.00
0.00 5845.00 11690.00 17535.00 23380.00 29225.00 35070.00
0.00 5950.00 11900.00 17850.00 23800.00 29750.00 35700.00
0.00 6055.00 12110.00 18165.00 24220.00 30275.00 36330.00
0.00 6160.00 12320.00 18480.00 24640.00 30800.00 36960.00
0.00 6265.00 12530.00 18795.00 25060.00 31325.00 37590.00
0.00 6370.00 12740.00 19110.00 25480.00 31850.00 38220.00
0.00 6475.00 12950.00 19425.00 25900.00 32375.00 38850.00
0.00 6580.00 13160.00 19740.00 26320.00 32900.00 39480.00
0.00 6685.00 13370.00 20055.00 26740.00 33425.00 40110.00
0.00 6790.00 13580.00 20370.00 27160.00 33950.00 40740.00
0.00 6895.00 13790.00 20685.00 27580.00 34475.00 41370.00
0.00 7000.00 14000.00 21000.00 28000.00 35000.00 42000.00
0.00 7105.00 14210.00 21315.00 28420.00 35525.00 42630.00
0.00 7210.00 14420.00 21630.00 28840.00 36050.00 43260.00
0.00 7315.00 14630.00 21945.00 29260.00 36575.00 43890.00
0.00 7420.00 14840.00 22260.00 29680.00 37100.00 44520.00
*************************************************************************
Done.
Given the trend towards bigger SMPs and multithreading computers, it is vital that strategies and techniques for creating shared-memory parallel programs become widely known. Explaining how to use OpenMP in conjunction with major programming languages like Fortran, C, and C++ to write such parallel programs is the purpose of this article.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
General News Suggestion Question Bug Answer Joke Rant Admin
Man throws away trove of Bitcoin worth $7.5 million | http://www.codeproject.com/Articles/56984/A-Comprehensive-Look-at-Concurrency-through-the-Op?fid=1559948&df=10000&mpp=50&sort=Position&spc=Relaxed&tid=3369343 | CC-MAIN-2013-48 | refinedweb | 4,343 | 58.01 |
Version 1.23.0
For an overview of this library, along with tutorials and examples, see CodeQL for Java
.
An XML file.
import java
Gets a DTD associated with this XML file.
Gets a top-most element in an XML file.
Gets the encoding of this XML file.
Gets the XML file itself.
Gets the name of this XML file.
Gets a printable representation of this XML file. file or sub-folder in this container.
Gets the child element at a specified index of this XML parent.
Gets the depth in the tree. (Overridden in XMLElement.)
Gets the extension of this container, that is, the suffix of its base name after the last dot character, if any.
Gets the file in this container that has the given baseName, if any.
baseName
Gets the sub-folder in this container that has the given baseName, if any.
DEPRECATED: use getAbsolutePath() instead.
getAbsolutePath()
Gets the source location for this element.
Gets the number of places in the body of this XML parent where text occurs.
Gets the number of child XML elements of this XML parent..
getBaseName()
getStem()
Gets the stem of this container, that is, the prefix of its base name up to (but not including) the last dot character if there is one, or the entire base name if there is not.
Gets the text value contained in this XML parent.
Gets the total number of lines that this element ranges over, including lines of code, comment and whitespace-only lines.
Gets the URL of this file.
Holds if this element is at the specified location. The location spans column startcolumn of line startline to column endcolumn of line endline in file filepath. For more information, see Locations.
startcolumn
startline
endcolumn
endline
filepath
DEPRECATED: use getAbsolutePath(), getBaseName() or getStem() instead. | https://help.semmle.com/qldoc/java/semmle/code/xml/XML.qll/type.XML$XMLFile.html | CC-MAIN-2020-05 | refinedweb | 299 | 68.87 |
Hi
I've bought a licence and it works fine locally, but when I deploy to a remote server and run it through IIS, I get the following exception:ServiceStack.LicenseException: The free-quota limit on '10 ServiceStack Operations' has been reached.
I've tried setting my licence key through:
Please help.
This suggests that no license key was registered. If you added it as an Environment Variable on the remote computer you'll need to restart IIS to pick up the changes. Otherwise hard coding the license key definitely works.
Otherwise double-check that the server generating the License Exception is definitely the server where you're trying to register the License. If you continue to have issues please email team@servicestack.net with the License Key you're using and we can verify if you're using a valid License Key.
Hi @mythz
Thank you for the speedy response,
I've restarted the IIS and I've tried hardcoding the licence key in the code, but still getting the same error.
Do you know if there is a request to a external server to verify the licence maybe as the server's security is pretty locked down?
I'll email them, if you can't help me.
No there isn't anyway to determine if a Server is licensed remotely, in code you can call:
LicenseUtils.ActivatedLicenseFeatures();
Which returns an enum of which features are licensed. If a Business or Indie License was registered it will return LicenseFeature.All.
LicenseFeature.All
Yes, its return All.
Ok it wont be returning All from the Server that's throwing the License Exception. If the License Key was invalid it would've thrown an Invalid License Key error where as this License Exception suggests no License Key was registered at all. So my only suggestion is to double-check the server that's throwing the Exception is definitely the Licensed Server where the License Key was registered on.
All
You can also try deploying to a clean virtual directory, i.e. clear out the entire directory where it's deployed to, or just the /bin folder in-case you have some dirty .dll's that's causing the issue.
/bin
Another thing you can try is creating a Service that returns whether a License has been registered with:
[Route("/licensed")]
public class CheckLicense {}
public class MyServices : Service
{
public object Any(CheckLicense request) =>
(LicenseUtils.ActivatedLicenseFeatures() == LicenseFeature.All).ToString();
}
You'll need to temporarily comment out your other Service classes so you can get below the 10 operation free quota limit so ServiceStack AppHost is initialized.
This is going to return "False" in a server that doesn't have a license key registered but at least with the new Service you can verify deployments to your remote IIS Server are actually being done.
If it does return false, try registering the License Key in code and throwing a custom Exception immediately after, i.e:
protected void Application_Start(object sender, EventArgs e)
{
Licensing.RegisterLicense(@"replace with license key text");
if (LicenseUtils.ActivatedLicenseFeatures() != LicenseFeature.All)
throw new Exception("License Registration failed");
new AppHost().Init();
}
The Exception should never be thrown as registering a valid license key in code like this will always work.
My assumption is simply that the License Key isn't being registered on the server that's throwing the License Exception or there is an issue with deployments that's preventing new deployments.
Thanks,
I've managed to sort it out through Environment Variables, when I restarted the IIS I did it with the GUI. But it seems you need to do it with commandline.
With regards to setting it in code, I had to do it in the Program -> Main function, anything later than that seem to give me an error.
Thanks again for the help.
Great, glad to hear it.
I deleted my previous addition to this thread, but to anyone else stumbling in here because your xUnit / nunit tests fail:
If you are using some build system (TeamCity, Jenkins), add an environmental variable to be set when building. From what I can tell xUnit tests have no "Main" entry point, and calling RegisterLicenseKey in AppHost.Configure is too late - it will fail. | https://forums.servicestack.net/t/licence-key-works-fine-locally-and-in-local-docker-but-not-when-deployed-to-remote-server-iis/4974 | CC-MAIN-2019-22 | refinedweb | 703 | 54.52 |
+1
Hello very good, this is my first post in this forum. A week ago I finished the c ++ course on the page, and I am creating a practical application. As I create it, an existential doubt arises; Is there a possibility that the variables of member functions can be called in the main function, either by being in an access specifier as private, protected or declared in the member function itself.
Let's put it this way: I have a member function which asks the user to enter their date of birth day / month / year (here I declare 3 variables), then depending on what the user places, I will show it in a message but in the main function.
Within the same member function if this action can be done and call it in main, but I can not do it in the way that I am commenting
Would you put some example ?, or advise me.
Thank you very much.
7/19/2018 8:48:05 PM
9 Answers
+5
You could declare day public and access it everywhere, however, that violates OOP design. Hiding your data makes it so you can change it without effecting the code outside of the class. Now, you want day, month, and year. However, depending on the future coding, it might make more sense to keep track of the day within the year or some other way of storing the information. Using methods to get and set the data means those functions are the only thing that must change, when you change the data.
+3
This would be with getters:
+2
Code something to give a better idea of what you are looking for. Use comments for places you want something, but have no idea how to code, describing what you want done. Link it here so we can expand it into working code.
IMHO, one should ask here only... others can get benefit also from single post and different people can share their views...
0
use member functions getter and setter to access member variable....
Hi, thank you for answering, I still have doubts regarding this issue, will anyone have an email to which I can communicate?
If I agree friend, but still I can not solve my problem
look for setter and getter these define them and give parameters in the main (which before this were placed within the classes) I can not get an example where user enter data (this instruction I put in a member function). Help :(
it would be this way:
#include <iostream>
using namespace std;
class Frecuency
{
public:
//Function Member
int birthDate()
{
cout << "place your date of birth: (DD/MM/AA)";
cin >> d >> s >> m;
}
private:
int d,s,m;
};
int main()
{
Frecuency b1;
b1.birthDate; // Here I call the date of birth and place values
cout << "his birth date is"; // Here based on the numbers that are entered, I want to show them in cout
}
I know you will tell me, hey, but why do not you declare them in the member function ?, actually that would be a more comfortable way to solve my problem but I do not look for that solution since I have another function that also enters data and shows them, they do not fit as such if they are not: (first sampling date, and then the other) I have already tried to use line breaks or tabs to sort them but I can not do it.
What I want is that there is the possibility of removing the variables of the private function and placing them in main without losing their entered value. (I have already tried to match, use the betters and getters but it does not work out for me).
Thank you very much !!, look how easy it was! I appreciate it a lot. (Another question these commands can be valid for builders and calls from source codes attached to classes?).
GET THE FREE APP
Learn Playing. Play Learning
SoloLearn Inc. | https://www.sololearn.com/Discuss/1413691/doubt-about-pointers-c/ | CC-MAIN-2018-34 | refinedweb | 662 | 75.54 |
This article presents a control for the graphing of functions and parametric curves. The control will take a mathematically defined function and make a smooth representation of its graph using Bezier segments. Originally, this was part of some work on creating geometrical representations of curves using Bezier segments. As it evolved, I felt the need to verify that the geometries represented were the geometries I believed them to be. Grids, rules, ticks, and labels were all added for this purpose. In the end, a graphing control was produced that should prove useful in its own right.
This article uses calculus and some simple linear algebra and a bit of trigonometry. The curves are graphed directly from the information on the function or curve and its derivatives. As I was unable to find derivations or formulas of that nature, I was required to recreate them from scratch. If any kind reader knows of somewhere where this derivation is done, please let me know and I will joyfully update this article.
As this control graphs functions and curves, it would be best to start by defining exactly what definition of function or curve is being used. Put loosely, a function is a pair of methods, one that represents a value and one that represents a slope or derivative. The base class from which all functions derive is:
public abstract class FunctionBase
{
public abstract double Value(double x);
public abstract double Derivative(double x);
//... Other stuff
}
To graph a function, we call the AddFunction method of GraphDisplay.
AddFunction
GraphDisplay
public void AddFunction(FunctionBase f, double start,
double end, int segments, GraphStyle style)
For example:
GraphStyle curveStyle = new GraphStyle()
{Stroke = new SolidColorBrush(Colors.Red ) ,Thickness = 2};
Exp ex = new Exp() ;
gDisplay.AddFunction(exp, 1, 2, 5, curveStyle);
would use GraphDisplay gDisplay to graph the exponential function y= ex from x= 1 to x= 2 in the color red with a stroke of width 2 using five Bezier segments. However, we are not quite done. The control needs to know how to relate the values in the abstract mathematical space where the function resides.
gDisplay
gDisplay.YTop = 8 ;
gDisplay.YBottom 2;
gDisplay.XLeft =0;
gDisplay.XRight =3;
This gives a small bit of whitespace around the graphed exponential. We are not restricted in the number of functions that we can add to a GraphDisplay, but all of the functions use the same bounds.
Functions can be created by directly inheriting from FunctionBase. For example, let's say we want the function corresponding to f(x) = sin(x).
FunctionBase
public class Sin : Mathematics.BaseClasses.FunctionBase
{
public override double Value(double x)
{
return Math.Sin( x );
}
public override double Derivative(double x)
{
return Math.Cos(x);
}
}
Please note that this is a minimalist version of the Mathemaics.Functions.Sin class which corresponds to the family of functions of the form f(x) = ASin(nx + d).
Mathemaics.Functions.Sin
We can also create functions through the Function class. The function class is as follows:
Function
public sealed class Function:FunctionBase
{
private Func<double,> mF;
private Func<double,> mDF;
public Function( Func<double,double> f, Func<double,double> df)
{
mF = f;
mDF = df;
}
public override double Value(double x)
{
return mF(x);
}
public override double Derivative(double x)
{
return mDF(x);
}
}
We just pass in delegates for the function and its derivative. For example, we could again create f(x) = sin(x) via:
Function f = new Function(x=> Math.Sin(x), x=> Math.Cos(x));
Overriding is probably preferable for creating functions while the Function class works dynamically at runtime.
Functions can also be combined in various ways. It is important to remember that instances of classes that derive from FunctionBase are Calculus like functions, so the chain rule needs to be obeyed. Fortunately, there are several static methods in FunctionBase for combining functions. To compose y= 2x and y= sin(x) and get y=sin(2x), we could use the following code:
Function twoX = new Function (x=>2*x,x=>2);
Sin sin = new Sin();
Function composition = Function.Compose(sin ,twoX);
All of the complexity is hidden behind the scenes.
public static Function Compose(FunctionBase outerFunction, FunctionBase innerFunction)
{
//Change of variables for more readable code
FunctionBase f = outerFunction;
FunctionBase g = innerFunction;
return new Function(
x => f.Value(g.Value(x)), //Composition f(g(x))
x => f.Derivative(g.Value(x)) * g.Derivative(x)
//Chain Rule f'(g(x))*g'(x)
);
}
There are also static methods for the sum, difference, product, and quotient of functions. These functions can both be called directly or used via operators. With the same sin and twoX, f(x) = sin(x) + 2x can be done via:
sin
twoX
Function plus = Function.Sum(sin, twoX);
Function plus = sin + twoX ;
which calls:
public static Function Sum(FunctionBase f, FunctionBase g)
{
return new Function(x => f.Value(x) + g.Value(x),
x => f.Derivative(x) + g.Derivative(x)
);
}
f(x) = sin(x) - 2x can be made via:
Function minus = Function.Difference(sin, twoX);
Function minus = sin - twoX ;
public static Function Difference(FunctionBase f, FunctionBase g)
{
return new Function(x => f.Value(x) - g.Value(x),
x => f.Derivative(x) - g.Derivative(x)
);
}
f(x) = 2xsin(x) can be made via:
Function times = Function.Product( twoX ,sin);
Function times = twoX * sin;
public static Function Product(FunctionBase f, FunctionBase g)
{
return new Function(x => f.Value(x) * g.Value(x),
x => f.Derivative(x) * g.Value(x) +
g.Derivative(x) * f.Value(x) //Chain Rule f'(x)g(x) + f(x)g'(x)
);
}
f(x) = sin(x)/2x can be made via:
Function divides = Function.Product( sin , twoX);
Function divides = sin /twoX;
public static Function Quotient(FunctionBase numerator, FunctionBase denominator)
{
//Change of variables for more readable code
FunctionBase f = numerator;
FunctionBase g = denominator;
return new Function(x => f.Value(x) / g.Value(x),
//Chain rule (f'(x)g(x) - f(x)g'(x))/g(x)^2
x => (f.Derivative(x) * g.Value(x) - f.Value(x) *
g.Derivative(x)) / Math.Pow(g.Value(x), 2)
);
}
I have belabored these transformations because they are important. The main reason for creating FunctionBase is to have an entity that will naturally obey the chain rule.
alt="Image 2" data-src="/KB/WPF/BezierFunctionGraphing/Sinusoid.gif" class="lazyload" data-sizes="auto" data->
As a sample for the graphing of functions, we have the DampedSinusoid.
DampedSinusoid
public class DampedSinusoid : FunctionBase
{
public double A { get; private set; }
public double Gamma { get; private set; }
public double Omega { get; private set; }
public double Phi { get; private set; }
public DampedSinusoid(double a, double gamma, double omega, double phi)
{
A = a; Gamma = gamma; Omega = omega; Phi = phi;
}
public override double Value(double x)
{
return A * Math.Pow(Math.E, -Gamma * x) * Math.Cos(Omega * x + Phi);
}
public override double Derivative(double x)
{
return A * Math.Pow(Math.E, -Gamma * x) * Math.Cos(Omega * x + Phi) * (-Gamma)
- A * Math.Pow(Math.E, -Gamma * x) * Math.Sin(Omega * x + Phi) * Omega;
}
}
The sample shows two damped sinusoids and their sum. I might note that all of the values used in this class are set in the constructor and thereafter unalterable. I would strongly recommend following this policy.
A curve is very similar to a function except that there are four methods instead of two.
public abstract class CurveBase
{
public abstract Double X(double t);
public abstract Double Y(double t);
public abstract Double Dx(double t);
public abstract Double Dy(double t);
... other stuff
}
The is also a CyclicCurveBase. This should be used in cases where we have a closed curve. In general, we should not expect an end user to know the period of a function.
CyclicCurveBase
public abstract class CyclicCurveBase:CurveBase
{
public abstract double CycleStart {get;}
public abstract double CycleEnd{ get;}
}
Curves can be added via the AddCurve and AddCyclicCurve methods.
AddCurve
AddCyclicCurve
public void AddCurve(CurveBase c, double start, double end,
int segments, GraphStyle style){...}
public void AddCyclicCurve(CyclicCurveBase c, int segments, GraphStyle style){...}
At this point, looking at the class hierarchy for the descendents of CurveBase should be helpful.
CurveBase
alt="Image 3" data-src="/KB/WPF/BezierFunctionGraphing/Curves.gif" class="lazyload" data-sizes="auto" data->
In order to create a new curve to graph, we should either inherit from one of the abstract base classes (blue) or compose using the compositional classes (purple). This is one of those times when being able to employ multiple inheritance would be nice. For example, I would like to be able to inherit the cyclic properties from some cyclic base class and the polar properties from a polar base. The way things are implemented involves some regrettable duplication. The classes were designed for expansion without significant changes to the graphing control. For example, if bipolar coordinates were added to the mix, no changes would need to be made to the graphing control. We could reasonably add other types of curves such as bipolar, elliptic, or hyperbolic in the future. In that case, we should create four classes for each coordinate system, just as we have PolarCurveBase, PolarCurve, CyclicPolarCurveBase, and CyclicPolarCurve.
PolarCurveBase
PolarCurve
CyclicPolarCurveBase
CyclicPolarCurve
The PolarCurve class can be used to construct a curve if we have a function r= f(Θ)
public sealed class PolarCurve:PolarCurveBase
{
private Func<double, double> mR;
private Func<double, double> mDr;
public PolarCurve(Function r)
{
mR = r.Value;
mDr = r.Derivative;
}
public override double R(double theta)
{
return mR(theta);
}
public override double Dr(double theta)
{
return mDr(theta);
}
}
The thing to note is that the graphing control does not use r or Θ coordinates. This is handled by the base class.
public abstract class PolarCurveBase:CurveBase
{
public abstract double R(double theta);
public abstract double Dr(double theta);
private Curve mC;
static Cos sCos = new Cos();
static Sin sSin = new Sin();
protected PolarCurveBase() {
Function r = new Function(R,Dr);
mC = new Curve( r * sCos , r * sSin );
}
public override double X(double t)
{
return mC.X(t);
}
public override double Y(double t)
{
return mC.Y(t);
}
public override double Dx(double t)
{
return mC.Dx(t);
}
public override double Dy(double t)
{
return mC.Dy(t);
}
}
The interesting thing is the order in which the two constructors are called. PolarCurveBase's constructor is called before PolarCurve's.
This means that the curve transforming the function is created from overridden methods encapsulating the function before the function itself is introduced. The sample for polar curves is the Rose curve.
alt="Image 4" data-src="/KB/WPF/BezierFunctionGraphing/Rose.gif" class="lazyload" data-sizes="auto" data->
Bezier curves are extremely useful for the drawing of smooth curves, so a little motivation might be of value. Let's assume we have a curve that we are interested in creating a representation of. It starts at Point a = (ax, ay) and goes to point b = (bx, by). We could represent the curve between them by a pair of functions. Bx(t) where Bx(0)=ax and Bx(1)=bx along with By(t) where By(0)=ay and By(1)=by.
The simplest functions we could use for Bx and By (B is for Bezier) would be straight lines of the form f(x) = Ax + B, subject to the initial constraints. (A different equivalent formulation is usually used, but that adds complexity we don't need yet.) The important thing to notice is that we need 4 numbers to uniquely determine this line, two for Bx(t) and two for By(t). Fortunately, these are available in the x and y coordinates of the endpoints. With a little reorganization and notational change, this could be transformed to the customary definition of a Linear Bezier Curve.
B(t) = P0 + t(P1 - P0) where P0 is the starting point and P1 is the end point.
A line is not that good of an approximation to a curve, but it's worth keeping in mind that using it, we can use a lot of Bezier segments next to one another and that in the process of being displayed on the screen, our Bezier curves are converted back into line segments. The Geometry base class even has a GetFlattenedPathGeometry method to do just that. WPF supports this in spirit with the LineSegment class, if not in name.
Geometry
GetFlattenedPathGeometry
LineSegment
We can make a better approximation to our curve using a Quadratic (of the form f(x) = Ax2 + Bx + C) instead of a linear function. The thing to notice is that now we will need 6 numbers to define our segment. The obvious candidate for these numbers is the slope at the initial and final points. Put in vector form, we have:
B(t) = P0 (1-t)<sup>2</sup> + P1 2(1-t)t + P2t<sup>2</sup>
which corresponds to:
B<sub>x</sub>(t) = P0<sub>x</sub>(1-t)<sup>2</sup> + P1<sub>x</sub> 2(1-t)t + P2<sub>x</sub>t<sup>2</sup>
B<sub>y</sub>(t) = P0<sub>y</sub>(1-t)<sup>2</sup> + P1<sub>y</sub> 2(1-t)t + P2<sub>y</sub>t<sup>2</sup>
You might ask why we need to use this format instead of the simpler Ax2 + Bx + C. First, it is obvious that we can do this. Just multiply everything out and collect the terms to get A, B, and C. The benefit of this comes when we evaluate the conditions at the endpoints. If we start at Point a = (ax, ay) and go to point b = (bx, by), then we can immediately get P0x = ax and P0y = ay by evaluating at t=0. We get P2x = bx and P2y = by by evaluating at t=0. We then have the simpler problem of finding P1x and P1y. In WPF, Quadratic Bezier segments are supported by QuadraticBezierSegment. The constructor for QuadraticBezierSegment has a space for a P1 and a P2 but not a P0. At first, this might make it seem as if it only takes 4 rather than 6 numbers to define a Quadratic Bezier segment. This has much more to do with memory management than mathematics. If you have two consecutive segments in a path, P2 for the first acts as P0 for the second. Microsoft both saves memory and removes the chance for us to enter a wrong value by doing this. It does not change the dynamics of finding the values of P1. If we want to think in the Microsoft way, we must lose the two conditions at the initial point along with the requirement to find P0.
QuadraticBezierSegment
These are the type of segments that we are most likely to use. Notably, it is represented by a class named BezierSegment rather than CubicBezierSegment. These are also the segments you use in Adobe Illustrator with the pen tool. In vector form, it looks like:
BezierSegment
CubicBezierSegment
B(t) = P0 (1-t)<sup>3</sup> + P1 3(1-t)<sup>2</sup> t + P2 3(1-t)t<sup>2</sup> + P3 t<sup>3</sup>>
One of the nice things about the vector form is that it makes certain common transformations of Bezier segments easy. For instance, if we want to move the Bezier curve by 5 in the positive x direction, all we would need to do is add 5 to the x components of P0, P1, P2, and P3. In fact, any translation, reflection, or other transformation that can be accomplished by matrix multiplication has this property. Also, it means that when drawing pictures of Bezier segments, we lose no generality by rotating them, so they are easier to draw.
There is a very important relationship between the Ps and the derivatives at t =0 and t=1. It is just straightforward algebra, but unpleasant enough that I would advise using Mathematica or something similar rather than pencil and paper.
B'<sub>y</sub>(0) /B'<sub>x</sub>(0) = (P0<sub>y</sub> - P1<sub>y</sub>) /(P0<sub>x</sub> - P1<sub>x</sub>)
B'<sub>y</sub>(1) /B'<sub>x</sub>(1) = (P2<sub>y</sub> - P3<sub>y</sub>) /(P2<sub>x</sub> - P3<sub>x</sub>)
This means that the tangent line to the Bezier curve at Point P0 intersects P1, and that the tangent line at P3 intersects P2. So, if the only conditions that we have are the endpoints and the slopes at the ends, there is a large collection of possible P1s. Similar reasoning applies for P2.
Furthermore, let's say we wanted to choose a P1 such that it has a specified slope at P0. We could pick any point that is both on the tangent line and in the direction of P3, and it would have the correct slope at P0. For example, we could have the following possibilities:
alt="Image 6" data-src="/KB/WPF/BezierFunctionGraphing/CurveTypes.gif" class="lazyload" data-sizes="auto" data->
In the one called leaning, the curve extends further to the right than P3, P1 would have needed to be significantly further out for it to be more noticeable. As we can see, we can get significantly different Bezier segments that have the same endpoints and slopes at their endpoints.
By the same reasoning as with Quadratic curves, we need 8 numbers to define the segment, four of which are provided by the initial and final points.
Now that the preliminaries are out of the way, it's time to graph functions. I am assuming that f(x) and its derivative f'(x) also exist for the range that is being graphed. This type of function was chosen as the graphing sweet spot. Giving up the first derivative makes things significantly harder, and derivatives higher than the first add a lot less than we would like.>
a = P0<sub>x</sub>
f(a) = P0<sub>y</sub>
b = P3<sub>x</sub>
f(b) = P3<sub>y</sub>
f'(a) = (P0<sub>y</sub> - P1<sub>y</sub>) /(P0<sub>x</sub> - P1<sub>x</sub>)
f'(b) = (P2<sub>y</sub> - P3<sub>y</sub>) /(P2<sub>x</sub> - P3<sub>x</sub>)
After a bit of simplification, we get:
P1<sub>y</sub> -f'(a) P1<sub>x</sub> = f(a) - af'(a)
<sub>y</sub> -f'(b) P2<sub>x</sub> = f(b) - bf'(b)
It looks a bit better, but we still have two equations and four unknowns, and as we have already seen, this leaves a lot of possible segments. So we need more constraints. We have two, although they are not expressed in the form of equalities. First, we are graphing a function. By definition, that means that for every x, there must be exactly one f(x). That makes Bezier segments that loop and lean unacceptable representations of the function. Also, we expect that as a and b get closer together, the Bezier segment will match its portion of the curve more closely, just as it would if we were approximating the curve with line segments.
To go further, we need more conditions that are in the form of equations. Let's consider the following two:
P1<sub>x</sub> =( 2 a + b)/3
P2<sub>x</sub> =( a + 2 b)/3
We will later see that these are excellent choices for conditions, but it is worth noting that they are not the only choices we could have made, and this choice puts the curve in the normal category. It also matches with the illustrator pen tool rule of thumb, that control handles should be about 1/3 of the way between nodes. With these conditions, we get:
P1<sub>y</sub> =( 3 f(a) - a f'(a) + b f'(a))/3
P2<sub>y</sub> =( 3 f(b) - a f'(b) + b f'(b))/3
This is exactly the sort of result we would hope for. P1y and P2y are expressed as linear combinations of the conditions at the endpoints. There is no denominator that could possibly go to zero. One of the major reasons that Quadratic Bezier segments are not used is that there is a denominator that can go to zero, which causes artifacts in the graph. So, in summary, we have the following result:>
P0<sub>x</sub> = a , P0<sub>y</sub> = f(a)
P1<sub>x</sub> = ( 2 a + b)/3 , P1<sub>y</sub> =( 3 f(a) - a f'(a) + b f'(a))/3
P2<sub>x</sub> =( a + 2 b)/3 , P2<sub>y</sub> =( 3 f(b) - a f'(b) + b f'(b))/3
P3<sub>x</sub> = b , P3<sub>y</sub> = f(b)
For a parametric curve, we have a curve defined by two functions: x = x(t) and y=y(t). By long standing tradition, t is used for the parameter (t is a good letter for time), It should be remembered that this t is not the same t as in Bx(t) and By(t). For a curve going from t = a to t= b, and functions x(t) and y(t), we have:>
x(a) = P0<sub>x</sub>
y(a) = P0<sub>y</sub>
x(b) = P3<sub>x</sub>
y(b) = P3<sub>y</sub>
y'(a)/x'(a) = (P0<sub>y</sub> - P1<sub>y</sub>) /(P0<sub>x</sub> - P1<sub>x</sub>)
y'(b)/x'(b) = (P0<sub>y</sub> - P1<sub>y</sub>) /(P0<sub>x</sub> - P1<sub>x</sub>)
Again, we need more conditions. Loops and points can occur in parametric curves such as the Lissajous curve, but should not be added as artifacts of our algorithm. One of the implications of this is that P1 cannot be entirely determined from the behavior at P0. To see this, consider bringing b closer and closer to a. Eventually, we would get a pointed looped or leaning curve for the Bezier segment.
We could consider the same idea we used while graphing functions. Since the argument for P1 is completely analogous to the one for P2, the discussion will focus solely on P1. The difference is that instead of moving horizontally 1/3 of the x distance, we could put P1 on the line that intersects the segment connecting P0 and P3. In doing this, we define a triangle and so are able to find P1.
alt="Image 8" data-src="/KB/WPF/BezierFunctionGraphing/Parametric2.gif" class="lazyload" data-sizes="auto" data->
First, we know the angle α. The slopes of the lines between P0 and P3 is known since P0 and P3 are known. The slope of the line between P0 and P1 is just y'(a)/x'(a), which again is known. Via a well known formula tan(α) = (mb - ms)/ (1+ mb ms), where mb is the bigger slope and ms is the smaller slope. Due to the law of Sines, we know that the length of the segment from P0 to P1 is 1/3 the distance between P0 and P3 divided by the sine of pi/2 - α.
Once we have the length between P0 and P1, call it h, we can get P1.
P1<sub>x</sub> =P0<sub>x</sub> + h cos(μ) where μ is the angle made by the tangent line at P0 with the X axis
P1<sub>y</sub> =P0<sub>y</sub> + h sin(μ)
Since we have dx and dy separately, we can simplify this a bit as cos(μ) = dx/(dx2 + dyx2)1/2 and sin(μ) = dy/(dx2 + dyx2)1/2. This gives us a way to find P1. It is not nearly as good a solution as was found for the functional case, but it provides a procedure that can be used to plot curves.
Up until now, coordinates have been taken for granted. Functions and curves have been defined in an abstract space of numbers, but they must be displayed on the screen in terms of screen coordinates. This involves changes in translation, scale, and orientation. On the screen, we need to graph a TransformedFunction rather than the original FunctionBase.
TransformedFunction
public class TransformedFunction
{
private FunctionBase mF;
private FunctionBase mXTrans;
private FunctionBase mYTrans;
public TransformedFunction(FunctionBase f,
FunctionBase xTrans, FunctionBase yTrans)
{
mF = f; mXTrans = xTrans; mYTrans = yTrans;
}
public double Input(double x)
{
return mXTrans.Value(x);
}
public double Value(double x)
{
return mYTrans.Value(mF.Value(x));
}
public double Derivative(double x)
{
return (mYTrans.Derivative(mYTrans.Value(x)) /
mXTrans.Derivative(x)) * mF.Derivative(x);//Chain Rule
}
}
The only things to note are that all three items must be transformed, the input (x), the output (y), and the derivative (dy/dx). Also, we should remember that the chain rule is not optional. The interesting bits are the two FunctionBases that transform the x and y coordinates.
mXTransform = new Function(x => (DisplayCanvas.ActualWidth /
(XRight - XLeft)) * (x - XLeft), x => DisplayCanvas.ActualWidth / (XRight - XLeft));
mYTransform = new Function(y => (DisplayCanvas.ActualHeight / (YBottom - YTop)) *
(y - YTop), y => DisplayCanvas.ActualHeight / (YBottom - YTop));
This takes care of all three aspects including the fact that in our functional space, increasing y goes up, while on the canvas, it goes down. This is not the only function we could use. A slightly different expression would give a logarithmic scaling. There is very little difference in this respect between curves and functions, so I will omit the discussion.
When graphing a function, we just add it to the GraphDisplay:
public void AddFunction(FunctionBase f, double start, double end,
int segments, GraphStyle style)
{
Path p = new Path();
TransformedFunction tf =
new TransformedFunction(f, mXTransform, mYTransform);
p.Data = BezierGeometry(tf, start, end, segments);
p.Fill = style.Fill;
p.Stroke = style.Stroke;
p.StrokeThickness = style.Thickness;
DisplayCanvas.Children.Add(p);
}
This utilizes the BezierGeometry method to produce the geometry.
BezierGeometry
private PathGeometry BezierGeometry(TransformedFunction tf,
double start, double end, int segments)
{
PathFigure pF = new PathFigure();
pF.StartPoint = new Point(tf.Input(start),tf.Value(start));
pF.IsClosed = false;
Func<double, double> f = tf.Value; //for readability
Func<double, double> df = tf.Derivative; //for readability
for (int i = 0; i < segments; i++)
{
double aOrig = i * (end - start) / segments + start;
double a = tf.Input(aOrig);
double bOrig = (i + 1) * (end - start) / segments + start;
double b = tf.Input(bOrig);
Point P1 = new Point((2 * a + b) / 3,
(3 * f(aOrig) - a * df(aOrig) + b * df(aOrig)) / 3);
Point P2 = new Point((2 * b + a) / 3,
(3 * f(bOrig) + a * df(bOrig) - b * df(bOrig)) / 3);
Point P3 = new Point(b, f(bOrig));
BezierSegment bs = new BezierSegment(P1, P2, P3, true);
pF.Segments.Add(bs);
}
PathGeometry pGeo = new PathGeometry();
pGeo.Figures.Add(pF);
return pGeo;
}
The code for adding a curve or cyclic curve is virtually identical.
public void AddCurve(CurveBase c, double start,
double end, int segments, GraphStyle style)
{
Path p = new Path();
TransformedCurve tf = new TransformedCurve(c, mXTransform, mYTransform);
p.Data = BezierGeometry(tf, start, end, segments);
p.Fill = style.Fill;
p.Stroke = style.Stroke;
p.StrokeThickness = style.Thickness;
DisplayCanvas.Children.Add(p);
}
The only difference lies in the BezierGeometry method. The algorithm described above is used for generating the Bezier segments. However, the algorithm for generating the curve's geometry is not as stable as in the functional case. Rapid changes of direction are not handled well. For example, Lissajous figures can have spikes in them. These are handled less than optimally.
For this reason, there are two distinct algorithms being used in calculating the Bezier segments: BezierBuilder and AjustingBezierBuilder.
BezierBuilder
AjustingBezierBuilder
private PathGeometry BezierGeometry(TransformedCurve tc,
double start, double end, int segments)
{
PathFigure pF = new PathFigure();
pF.StartPoint = new Point(tc.X(start), tc.Y(start));
pF.IsClosed = false;
Stack<double> boundaries = new Stack<double>();
for (int i = segments; i >= 0; i--)
{
boundaries.Push(i * (end - start) / segments + start);
}
for (int i = 0; i < segments; i++)
{
double a = boundaries.Pop();
double b = boundaries.Peek();
AjustingBezierBuilder abb = new AjustingBezierBuilder(tc, a, b);
abb.AddTo( pF);
}
PathGeometry pGeo = new PathGeometry();
pGeo.Figures.Add(pF);
return pGeo;
}
The BezierGeometry method first creates a Stack of boundaries to define the start and end points for calculating the Bezier segments. This replaces the loop used in the functional case. This step of creating the stack may appear odd, but it was chosen to be able to harmonize with several different optimization strategies that in the end did not make it to this edition of the graphing control. Under normal circumstances, the results of AjustingBezierBuilder will be the same as for when BezierBuilder will be used for the segment. Normal circumstances means that the distance between the starting and ending points is less than the distance from the points to their nearby control points. This is just following the procedure described in the mathematical area.
Stack
public BezierBuilder(CurveBase c, double a, double b)
{
A = a;
B = b;
Point InitialPoint = new Point(c.X(a), c.Y(a));
FinalPoint = new Point(c.X(b), c.Y(b));
//The distance between the endpoints is calculated.
double distance = Geometry.Distance(InitialPoint, FinalPoint) ;
//Check if endpoints are close enough to approximate with a straight line.
if (distance < tolerance) //optimization
{
mBs = new LineSegment(FinalPoint, true);
IsStable = true;
}
else
{
//The slope of the lines to the control points is determined
//from the derivatives of the curve at the enpoints.
double curveSlopeA = c.Slope(a); ///dy(a) / dx(a);
double curveSlopeB = c.Slope(b); ///dy(b) / dx(b);
//The slope of the line connecting
// the endpoints of the segment is detemined.
double slope = Geometry.Slope(InitialPoint, FinalPoint);
//The Angles between the slope at the endpoints
//and the endpoint connecting lines is determined from the slopes.
double angleA = Geometry.AngleBetweenLines(slope, curveSlopeA);
double angleB = Geometry.AngleBetweenLines(slope, curveSlopeB);
//The length of the segments connecting the Endpoints
//to the control points is determined via the law of sines
Double distanceIn = distance / 3; //our extra condition
Double lengthAlongLineA = distanceIn /
(Math.Sin(Math.PI / 2 - angleA)); //Law of Sines
Double lengthAlongLineB = distanceIn /
(Math.Sin(Math.PI / 2 - angleB)); //Law of Sines
//The Control points are determined by moving along the line
//conecting the enpoints to the control points
//the distance to the control points.
Point controlPointA = Geometry.AtDistanceFromPointOnLine(InitialPoint,
c.Dx(a), c.Dy(a), lengthAlongLineA);
Point controlPointB = Geometry.AtDistanceFromPointOnLine(FinalPoint,
-c.Dx(b), -c.Dy(b), lengthAlongLineB);
//The BezierSegment is created from the control points and the endpoints.
mBs = new BezierSegment(controlPointA, controlPointB, FinalPoint, true);
//Mark if Bezier segment is Stable
IsStable = distance > lengthAlongLineA &&
distance > lengthAlongLineB;
PointDistance = Geometry.Distance(InitialPoint, FinalPoint);
}
}
This works reasonably well. However, it handled spikes less well than could be hoped for. To handle this situation, AdjustingBezierBuilder is used.
AdjustingBezierBuilder
public AjustingBezierBuilder(CurveBase c, double a, double b)
{
BezierBuilder bb = new BezierBuilder(c,a,b);
if ( bb.IsStable) // No Need to Adjust
{
mSegments = new List<pathsegment>();
mSegments.Add(bb.Segment);
}else{
LinkedList<bezierbuilder> builders = new LinkedList<bezierbuilder>();
LinkedListNode<bezierbuilder> current=
builders.AddFirst(new BezierBuilder(c, a, (a + b) / 2));
builders.AddAfter(current, new BezierBuilder(c, (a + b) / 2,b ));
while (current != null )
{
if (current.Value.IsStable) //No Problems
{
current = current.Next;
}
else // There is a problem with the current Bezier builder
{
//Slices BezierBuilder into two samller Bezier builders
builders.AddAfter(current, new BezierBuilder(c,
(current.Value.A + current.Value.B) / 2, current.Value.B));
LinkedListNode<bezierbuilder> newcurrent =
builders.AddAfter(current,
new BezierBuilder(c, current.Value.A,
(current.Value.A + current.Value.B) / 2));
builders.Remove(current );
current = newcurrent;
}
}
mSegments = (from bld in builders select bld.Segment).ToList();
}
}
When BezierBuilder is normal, AdjustingBezierBuilder defaults to the BezierBuilder's segment. Otherwise, AdjustingBezierBuilder splits the segment that the Bezier segment is made from into two. Each of those segments defines a new BezierBuilder which is checked. If that too is unstable, then it is split again. This process continues until all of the BezierBuilder objects are marked as stable. We know that this process will stop since, once the distance between the endpoints goes below the static value of the Tolerance in the BezierBuilder, the process will stop. It should be noted that each distinct BezierBuilder is only created and tested once. If a BezierBuilder is not found to be stable, it is replaced by two new ones, or equivalently, two new ones are added after the original and then the original is removed. A linked-list was employed to make this more efficient.
Tolerance
I hope that this graphing control serves you well. This is something that would have been significantly harder to do just a few years ago. It is also just a preliminary to a new set of functional geometries that I hope to have ready. | https://www.codeproject.com/Articles/58280/GraphDisplay-a-Bezier-based-control-for-graphing-f?msg=3418427#xx3418427xx | CC-MAIN-2022-05 | refinedweb | 5,396 | 55.44 |
My major achievement for today is writing the following five lines of code:
let a: ~u8 = ~('A' as u8); stdio::putc(*a); let b: ~u8 = ~('B' as u8); stdio::putc(*a); stdio::putc(*b);
and having them do the wrong thing. One would normally expect this to print “AAB”. But for me, right now, until I stop goofing off, it prints “ABB”. Why is that?
Well, it’s because my
malloc implementation looks like this:
static mut base: uint = 0x200000; pub extern "C" fn malloc(len: uint) -> *mut u8 { unsafe { let ret: uint = base; return base as *mut u8; } }
This means that every time I allocate memory, I get the same pointer
back, and so
a and
b will always be equal no matter what. And for
that matter any variable I create will always have the same value.
This is of course a terrible idea in real life, but it is really
fun.
Here’s my real
malloc function (that causes the above code to print
“AAB”, like it should):
pub extern "C" fn malloc(len: uint) -> *mut u8 { unsafe { let ret: uint = base; base += len + size_of::<uint>(); // Align next allocation to 4-byte boundary. if(base % 4 != 0) { base += 4 - (base % 4); } *(base as *mut uint) = len; return (ret + size_of::<uint>()) as *mut u8; } } pub extern "C" fn free(ptr: *mut u8) { // meh. }
The hardest part about this was not actually writing
malloc. Writing
malloc is easy, as long as you never need to free memory. I also
just wrote this by copying it from a C implementation. You just need
to keep a counter and keep incrementing it.
The hard part was getting the type of the function right, because Rust :). This is entirely made up for by being able to play silly memory games. | https://jvns.ca/blog/2013/12/10/day-39-i-wrote-a-malloc/ | CC-MAIN-2017-51 | refinedweb | 298 | 77.67 |
Moves the current read-write file pointer by an offset expressed as a 32-bit.
PR_Seek64.
Syntax
#include <prio.h> PRInt32 PR_Seek( PRFileDesc *fd, PRInt32 offset, PRSeekWhence whence);
Parameters
The function has the following parameters:
fd
- A pointer to a
PRFileDescobject.
offset
- A value, in bytes, used with the whence parameter to set the file pointer. A negative value causes seeking in the reverse direction.
whence
- A value of type
PRSeekWhencethat specifies how to interpret the
offsetparameter in setting the file pointer associated with the fd parameter. The value for the
whenceparameter can be one of the following:
PR_SEEK_SET. Sets the file pointer to the value of the
offsetparameter.
PR_SEEK_CUR. Sets the file pointer to its current location plus the value of the
offsetparameter.
PR_SEEK_END. Sets the file pointer to the size of the file plus the value of the
offsetparameter.
Returns
The function returns one of the following values:
- If the function completes successfully, it returns the resulting file pointer location, measured in bytes from the beginning of the file.
- If the function fails, the file pointer remains unchanged and the function returns -1. The error code can then be retrieved with
PR_GetError.
Description
Here's an idiom for obtaining the current location of the file pointer for the file descriptor
fd:
PR_Seek(fd, 0, PR_SEEK_CUR)
See Also
If you need to move the file pointer by a large offset that's out of the range of a 32-bit integer, use
PR_Seek64. New code should use
PR_Seek64 so that it can handle files larger than 2 GB. | https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSPR/Reference/PR_Seek | CC-MAIN-2020-05 | refinedweb | 259 | 62.88 |
Hi Developers!
As you know the application errors live in ^ERRORS global. They appear there if you call:
d e.Log()
in a Catch section of Try-Catch.
With @Robert Cemper's approach, you can now use SQL to examine it.
Inspired by Robert's module I introduced a simple IRIS Analytics module which shows these errors in a dashboard:
And you can drill to lines if click on the charts:
How to use it?
You can install the module with the following ZPM command:
USER>zpm "install objectscript-errors-analytics"
If you have errors in this namespace (e.g. in USER) you can check the dashboard in browser:
And you can generate some random errors with the following command:
do ##class(shvarov.objectscript.errors.analytics.setup).GenerateErrors()
And to refresh the data and rebuild the cube:
do ##class(shvarov.objectscript.errors.analytics.setup).Run()
What is cool about this project, that it uses a new feature of 0.2.5 ZPM version to deploy IRIS Analytics resources.
Looking for your feedback and collaboration!
@Evgeny Shvarov GREAT ! I had never expected this practical value!
Our community works) And collaboration ;) And the curiosity too )
And this was a perfect case to test the new ZPM feature ;)
I think chart by the error origin would be interesting.
Could you provide an example? and what do you mean by origin?
The line of code which generated the error.
You can also translate the line of int code back into cls using this snippet.
To leave a comment or answer to post please log in
Please log in | https://community.intersystems.com/post/application-errors-analytics | CC-MAIN-2020-40 | refinedweb | 264 | 58.58 |
The goal of StructuredText is to make it possible to express
structured text using a relatively simple plain text format. Simple
structures, like bullets or headings are indicated through
conventions that are natural, for some definition of
"natural". Hierarchical structures are indicated through
indentation. The use of indentation to express hierarchical
structure is inspired by the Python programming language.
Use of StructuredText consists of one to three logical steps. In the
first step, a text string is converted to a network of objects using
the StructuredText.Basic facility, as in the following
example:
StructuredText.Basic
raw=open("mydocument.txt").read()
import StructuredText
st=StructuredText.Basic(raw)
The output of StructuredText.Basic is simply a
StructuredTextDocument? object containing StructuredTextParagraph?
objects arranged in a hierarchy. Paragraphs are delimited by strings
of two or more whitespace characters beginning and ending with
newline characters. Hierarchy is indicated by indentation. The
indentation of a paragraph is the minimum number of leading spaces
in a line containing non-white-space characters after converting tab
characters to spaces (assuming a tab stop every eight characters).
StructuredTextNode? objects support the read-only subset of the
Document Object Model (DOM) API. It should be possible to process
StructuredTextNode hierarchies using XML tools such as XSLT.
StructuredTextNode
The second step in using StructuredText is to apply additional
structuring rules based on text content. A variety of differentText
rules can be used. Typically, these are used to implement a
structured text language for producing documents, but any sort of
structured text language could be implemented in the second
step. For example, it is possible to use StructuredText to implement
structured text formats for representing structured data. The second
step, which could consist of multiple processing steps, is
performed by processing, or "coloring", the hierarchy of generic
StructuredTextParagraph? objects into a network of more specialized
objects. Typically, the objects produced should also implement the DOM
API to allow processing with XML tools.
A document processor is provided to convert a StructuredTextDocument?
object containing only StructuredTextParagraph? objects
into a StructuredTextDocument? object containing a richer collection
of objects such as bullets, headings, emphasis, and so on using
hints in the text. Hints are selected based on conventions of the
sort typically seen in electronic mail or news-group postings. It
should be noted, however, that these conventions are somewhat
culturally dependent, fortunately, the document processor is easily
customized to implement alternative rules. Here's an example of
using the DOC processor to convert the output of the previous example:
doc=StructuredText.Document(st)
The final step is to process the colored networks produced from the
second step to produce additional outputs. The final step could be
performed by Python programs, or by XML tools. A Python outputter is
provided for the document processor output that produces Hypertext Markup
Language (HTML) text:
html=StructuredText.HTML(doc)
One of the most important features of StructuredText is it's
customizability. For information on customizing StructuredText, see:
> StructuredTextNode objects support the read-only subset of the
> Document Object Model (DOM) API. It should be possible to process
> StructuredTextNode hierarchies using XML tools such as XSLT.
No, they don't.
First of all, they don't support the API. They may have calls that
do the same thing as DOM calls, but that's not the same as supporting
the API.
Second, even if they were named properly, the calls aren't very
compliant. There are differences.
Why am I being a standards wonk? The DOM is a very basic interface.
It's meant for random complex tools to work with it. Those tools need the
standard to be followed to work, little differences break them.
The upshot is, I'd be surprised if any XML tools such as XSLT worked with
these objects. This shouldn't be advertised as a possibility. STX
shouldn't be advertised as supporting any DOM until there's a reason
to believe that it does.
I want the DOm? to be supported, and ParsedXML? has a great DOM test
suite that works with any DOM implementation. Unfortunately,
the tests are very interdependent right now - no readonly
tests, for example, you have to write to test reading. I hope that
this gets fixed and becomes useful to make STX a real DOM. | http://old.zope.org/Members/jim/StructuredTextWiki/NGDocumentation/wikipage_view | CC-MAIN-2014-41 | refinedweb | 708 | 50.33 |
me at least, the git@gitlab.com user identification didn't work. Cloning the repo without a user did work:
git clone
Possibility for integration tests of Excel:
For example, a test could be:
import xlwings as xw
with xw.Book(r'/path/to/drawdown.xlsx') as workbook:
sheet1 = workbook.sheets['Sheet1']
cell_A1 = sheet1.range('A1').value
ASSERT_EQ(cell_A1, 37)
Current status:
integration test using xlwings and Excel can work with some compromises:
a) on MacOS, may have to enable macros within Excel. Otherwise it prompts to Enable Macros every time the sheet is opened, and I haven't found a good way to handle this automatically.
b) on MacOS, can not have a workbook already open. Otherwise it tries to launch another instance of Excel, which raises a weird protected worksheet error.
Expecting to have tests/excel_integration_test.py with a setup() function to start a flask process on an unassigned TCP port, check whether Excel already has a workbook open and fail if it does (to survive 1.b.), and then test cases for each xlsm file which will open the file, write the URL="" to a cell, and then check the values of a few output cells again known golden values.
I will be heading with daughter to track practice at 5:30 | https://gitter.im/code-earth/Lobby?at=5b9161814be56c5918f02b12 | CC-MAIN-2020-29 | refinedweb | 215 | 64.71 |
Details
- Type:
Bug
- Status:
Open
- Priority:
Major
- Resolution: Unresolved
- Affects Version/s: 1.1-beta-1
- Fix Version/s: None
- Component/s: documentation
- Labels:None
- Environment:All
- Number of attachments :
Description
Brett recently posted a suggestion to someone who asked how to access the contents of "plugin a" from the context of "plugin b" or from maven.xml. Brett stated that "plugin a" would have to be initialized before it could be accessed, and that from what I could understand he recommended 1 or 2 ways to do that:
1) reference the artifact plugin's namespace in the project tag
2) specify <j:set (I think that this is the proper syntax, but I'm not sure
.
Thierry Lach, who asked the question this time around, reported that using the artifact namespace didn't work in his instance, but that setting the scope to parent did. I'm hoping that we can put together a fairly comprehensive explanation about what is going on here, and if that means explaining why the project gave up on Jelly and switched to M2, then so be it.
See for the postings
Given that during the last couple of months Vincent Massol recommended that people use the now deprecated <dependency-handle> mechanism on the mavenbook.org site (see Tip #2), I should think that there ought to be a priority on documenting this issue in an obvious place, probably the FAQ, but also on the Maven Jelly tags get and set entries.
If this is actually explicitly documented somewhere, I'm sorry to have wasted anyone's time. I have seen several plugins that have successfully used the artifact namespace tag, so there must be some way that people have learned this. I simply wish that I knew how they had done so.
I'm willing to write the doco if someone would explain the details.
Activity
explanation I gave Andy. To date I haven't been able to distill this into a user readable form:
Variables in a plugin are in its own, separate, jelly context.
However, this context is only created when the plugin is first loaded,
which is when it is first used.
Unfortunately, maven:set does not initialise the plugin context. It
was intended to, but caused some other problems that are documented in
the JIRA issue. So, you cannot use maven:set (or get) before the
plugin context is initialised.
When the plugin context is initialised, it uses the variables from the
current context, so anything set with j:set (no scope) is added. So
using this before the plugin gets used works, but not afterwards.
Using scope="parent" always works, as it puts it into the root
context, shared by all - as long as the plugin has not overridden the
variable in its own context.
The plugin is initialised when:
a) the goal you are in has a preGoal on a goal from that plugin
b) attainGoal has been called for that plugin
c) you have a namespace dependency on the plugin (This seems to have
been unreliable and only work if you actually use a tag from the
plugin though - hence the dependency handle)
It is much better to use a or b if possible, then use maven:set/get
exclusively. If you know the plugin has not been initialised and need
to set a var, you must use j:set without a scope. j:set with a scope
of parent is a last resort that will work in most but not all
situations.
It's a mess, and that's why m2 was a rewrite
OK! I've checked out the Maven 1 code. I've read through faq.fml and I have an idea about what I'd like to say and where I think that it ought to go.
I've looked at the code for the Maven Jelly tags, and I have a partial understanding about the mechanisms by which the Jelly tag documentaion pages are generated.
So, I've got a couple of questions.
I'm tempted to put some substantive comments into the GetTag.java and the SetTag.java files that explain the issues concerning the injection/retrival of values into/from maven plugins via Jelly scripts. At a minimum, I'd like to add a "see such and such reference", BUT either of those ideas seem to be BAD because it binds the documentation of the code to the larger issue of documenting Maven and Maven's use by its progammer customers. An improper separation of concerns if ever there was one.
I see, under the Codehaus Confluence pages, that there is an "Aiding Maven Adoption" page" I've got a bunch of suggestions concerning that topic, but I'll spare you for now. What I would like to know is, is there any intention of adding a "Why We Rewrote Maven" page to the Maven 1 site anytime soon? Putting the information about the differences between the 2 releases on the Maven 2 pages doesn't help the kind of Maven 1 users that I used to be, before I got religion, that is.
If there were a highlighted link on the Maven 1 page to such a discussion, and possibly a link from the Maven 1 faq to same, then I would feel comfortable leaving the code unmodified; because we would have discharged our documentation obligations to the community. In teh future when someone asks the inevitable ignorant questions on the user list, we could simply respond, "RTFM, look at the 'Why We Rewrote Maven pages.!"
So, after that multi paragraph "rant", I guess that I'm asking whether there is any interest in my writing the documentation about injection/retrieval in the context of a "Why We Rewrote Maven" piece that I would write. I'd be happy to submit it for proper vetting by the appropriate eyes.
I think that bound to the larger context, lets say in a "Tips and Tricks" section at the end of the piece, people would be more likely to read and remember it when it came time for them to make this sort of attempt.
Thanks, waiting for some feedback,
Andy
Andy, sorry I missed this from a while back. If you want a disucssion, it might be easier on te mailing list.
If you are still interested in doing the "Why we rewrote Maven" piece you'll find some material in my SJUG slides under the "Articles" part of the Maven 1.x site.
Hope this helps...
To be documented if it's not yet done
The author can't write too well, and so the title is a bit off - it ought to read: Doco that explains the protocols required to allow maven.xml or any plugin.jelly to inject values into or retrieve values from another plugin | http://jira.codehaus.org/browse/MAVEN-1656 | CC-MAIN-2013-20 | refinedweb | 1,140 | 65.96 |
Scrapy Fake User Agents: How to Manage User Agents When Scraping
After you've learned the basics of web scraping (how to send requests, crawl websites and parse data from the page), one of the main challenges we face is avoiding our requests getting blocked.
The two keys we can achieve this is be using proxies and managing the user-agents we send to the website we are scraping.
In this guide, we will go through:
- What Are User-Agents & Why Do We Need To Manage Them?
- How To Set A User Agent In Scrapy
- How To Rotate User Agents
- How To Manage Thousands of User Agents
First, let's quickly go over some the very basics.
Need help scraping the web?
Then check out ScrapeOps, the complete toolkit for web scraping.
What Are User-Agents & Why Do We Need To Manage Them?
User Agents are strings that let the website you are scraping identify the application, operating system (OSX/Windows/Linux), browser (Chrome/Firefox/Internet Explorer), etc. of the user sending a request to their website. They are sent to the server as part of the request headers.
When scraping a website, you also need to set user-agents on every request as otherwise the website may block your requests because it knows you aren't a real user.
In the case of Scrapy. When you use Scrapy with the default settings, the user-agent your spider sends is the following by default:
Scrapy/VERSION (+)
This user agent will clearly identify your requests as coming from a web scraper, so the website can easily block you from scraping the site.
That is why we need to manage the user-agents Scrapy sends with our requests.
How To Set A Fake User-Agent In Scrapy
There are a couple of ways to set new user agent for your spiders to use.
1. Set New Default User-Agent'
2. Add A User-Agent To Every Request
Another option is to set a user-agent on every request your spider makes by defining a user-agent in the headers of your request:
## myspider.py
def start_requests(self):
for url in self.start_urls:
return Request(url=url, callback=self.parse,
headers={"User-Agent": "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148"})
Both of these options work, however, you will have the same user-agent for every single request which the target website might pick up on and block you for. That is why we need to have a list of user-agents and select a random one for every request.
How To Rotate User Agents
Rotating through user-agents is also pretty straightforward, and we need a list of user-agents in our spider and use a random one with every request we make using a similar approach to option #2 above.
## myspider.py
import random
user_agent_list = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36',
'Mozilla/5.0 (iPhone; CPU iPhone OS 14_4_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Mobile/15E148 Safari/604.1',
'Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1)',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36 Edg/87.0.664.75',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18363',
]
def start_requests(self):
for url in self.start_urls:
return Request(url=url, callback=self.parse,
headers={"User-Agent": user_agent_list[random.randint(0, len(user_agent_list)-1)]})
This works but it has 2 drawbacks:
- We need to manage a list of user-agents ourselves.
- We would need to implement this into every spider, which isn't ideal.
A better approach would be to use a Scrapy middleware to manage our user agents for us.
How To Manage Thousands of Fake User Agents
The best approach to managing user-agents in Scrapy is to build or use a custom Scrapy middleware that manages the user agents for you.
You could build a custom middleware yourself if your project has specific requirements like you need to use specific user-agents with specific sites. However, in most cases using a off-the-shelf user-agent middleware is enough.
Developers have realised of user-agent middlewares for Scrapy, however, for this guide we will use ScrapeOps Fake User-Agent API as it is one of the best available.
ScrapeOps Fake User-Agent API
The ScrapeOps Fake User-Agent API is a free user-agent API, that returns a list of fake user-agents that you can use in your web scrapers to bypass some simple anti-bot defenses.
To use the ScrapeOps Fake User-Agents API you just need to send a request to the API endpoint to retrieve a list of user-agents.
You first need an API key which you can get by signing up for a free account here.
Example response from the API:
{
"result": [
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.53 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Windows; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.1.2 Safari/603.3.8",
"Mozilla/5.0 (Windows NT 10.0; Windows; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Safari/605.1.15",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.53 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Safari/605.1.15",
"Mozilla/5.0 (Windows NT 10.0; Windows; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.53 Safari/537.36"
]
}
The best way to integrate the Fake User-Agent API is to create a Downloader middleware and have a fake user-agent be added to every request. Here is an example middleware you can use:
## middlewares.py
from urllib.parse import urlencode
from random import randint
import requests
class ScrapeOpsFakeUserAgentMiddleware:
@classmethod
def from_crawler(cls, crawler):
return cls(crawler.settings)
def __init__(self, settings):
self.scrapeops_api_key = settings.get('SCRAPEOPS_API_KEY')
self.scrapeops_endpoint = settings.get('SCRAPEOPS_FAKE_USER_AGENT_ENDPOINT', '?')
self.scrapeops_fake_user_agents_active = settings.get('SCRAPEOPS_FAKE_USER_AGENT_ENABLED', False)
self.scrapeops_num_results = settings.get('SCRAPEOPS_NUM_RESULTS')
self.headers_list = []
self._get_user_agents_list()
self._scrapeops_fake_user_agents_enabled()
def _get_user_agents_list(self):
payload = {'api_key': self.scrapeops_api_key}
if self.scrapeops_num_results is not None:
payload['num_results'] = self.scrapeops_num_results
response = requests.get(self.scrapeops_endpoint, params=urlencode(payload))
json_response = response.json()
self.user_agents_list = json_response.get('result', [])
def _get_random_user_agent(self):
random_index = randint(0, len(self.user_agents_list) - 1)
return self.user_agents_list[random_index]
def _scrapeops_fake_user_agents_enabled(self):
if self.scrapeops_api_key is None or self.scrapeops_api_key == '' or self.scrapeops_fake_user_agents_active == False:
self.scrapeops_fake_user_agents_active = False
self.scrapeops_fake_user_agents_active = True
def process_request(self, request, spider):
random_user_agent = self._get_random_user_agent()
request.headers['User-Agent'] = random_user_agent
Note: This middleware example requires the installation of Python Requests via
pip install requests.
And then enable it in your project in the
settings.py file. Remembering to swap the
YOUR_PROJECT_NAME for the name of your project (
BOT_NAME in your
settings.py file):
## settings.py
SCRAPEOPS_API_KEY = 'YOUR_API_KEY'
SCRAPEOPS_FAKE_USER_AGENT_ENDPOINT = True
DOWNLOADER_MIDDLEWARES = {
'YOUR_PROJECT_NAME.middlewares.ScrapeOpsFakeUserAgentMiddleware': 400,
}
Or in the spider itself using the
custom_settings attribute.
## your_spider.py
import scrapy
from demo.items import QuoteItem
class QuotesSpider(scrapy.Spider):
name = "demo"
start_urls = [""]
## Enable ScrapeOps Fake User Agent API Here
custom_settings = {
'SCRAPEOPS_API_KEY': 'YOUR_API_KEY',
'SCRAPEOPS_FAKE_USER_AGENT_ENDPOINT': True,
'DOWNLOADER_MIDDLEWARES': {
'YOUR_PROJECT_NAME.middlewares.ScrapeOpsFakeUserAgentMiddleware': 400,
}
}
def parse(self, response):
pass
When activated, the ScrapeOpsFakeUserAgentMiddleware will download a list of the most common user-agents from the API and use a random one with every request, so you don't need to create your own list.
To see all the configuration options, then check out the docs here.
More Scrapy Tutorials
So that's why you need to use user-agents when scraping and how you can manage them with Scrapy.
Managing user-agents is only half the battle when it comes to not getting blocked whilst web scraping. The more important part is using proxies. If you want to learn how you can integrate proxies into your spiders then check out our Scrapy Proxy Guide here.
If you would like to learn more about Scrapy in general, then be sure to check out The Scrapy Playbook. | https://scrapeops.io/python-scrapy-playbook/scrapy-managing-user-agents/ | CC-MAIN-2022-40 | refinedweb | 1,495 | 60.51 |
Type: Posts; User: modirizwanmodi
Hi
Thanks for the quick reply can u please send me the mfc example of creating a toolbar using my icons
how to create a new toolbar with my icons in vc++????
Actually i am new to this and i have taken code from net. yes i debug the code but i am not clear where the error is .. as u said the szname, buf size is less(200) compare to the given size(256). i...
Dear Victor,
i am unable to identify where exactly error is coming. could you please help me with little briefly reply. so that i can finish the program.
AutoWrap(DISPATCH_METHOD, NULL, pXlSheet, L"SaveAS", 1, fname);
this code work fine but the issue is i am updating the excel file regularly and each time the excel file asking me saveas. i want the...
//this is my full code
#undef _UNICODE
#undef UNICODE
#include <iostream>
#include <windows.h>
#include <conio.h>
#include <string.h>
HI, i am developing a program where i have to auto save the excel file. i try putting some integer data's in excel and auto save the file it works perfect. while i try to auto save the file with some... | http://forums.codeguru.com/search.php?s=7548132e63de65734142ee1bf79cae63&searchid=5103961 | CC-MAIN-2014-41 | refinedweb | 205 | 75.1 |
DEBSOURCES
Skip Quicknav
sources / aolserver4 / 4.0.10
2005-01-18 tag aolserver_v40_r10
2005-01-18 Dossy Shiobara <dossy@panoptic.com>
* include/ns.h (1.55.2.19): Added missing prototype for
Ns_CompressGzip.
BUMP: 4.0.10
2005-01-12 Dossy Shiobara <dossy@panoptic.com>
* nsd/nsd.h (1.77.2.8), nsd/adpcmds.c (1.14.2.1), nsd/adprequest.c
(1.16.2.2), nsd/compress.c (1.1.2.3), nsd/server.c (1.27.2.1),
nsd/tclcmds.c (1.38.2.1), tests/new/http-test-config.tcl
(1.1.2.2), tests/new/ns_adp_compress.test (1.1.2.1),
tests/new/servers/server1/pages/ns_adp_compress.adp (1.1.2.1):
Support on-the-fly gzip compression of ADP page responses based
on HTTP request's Accept-Encoding header and ns_adp_compress
control mechanism.
2004-12-01 Dossy Shiobara <dossy@panoptic.com>
* include/ns.h (1.55.2.17): Provide NS_VERSION_NUM definition to
make conditionalized testing of AOLserver version at build time
easy.
2004-11-22 Dossy Shiobara <dossy@panoptic.com>
* include/ns.h (1.55.2.16): BUMP: 4.0.10a
2004-11-22 tag aolserver_v40_r9
2004-11-22 Dossy Shiobara <dossy@panoptic.com>
* include/ns.h (1.55.2.15): BUMP: 4.0.9
2004-11-20 Dossy Shiobara <dossy@panoptic.com>
* nsd/tclsched.c (1.5.2.1): Option parsing needed to be more
careful, leading to segfaults when a bad command like
[ns_schedule_proc -thread -only] is executed. Closes SF Bug
#1068836. Backport from HEAD.
2004-11-19 Dossy Shiobara <dossy@panoptic.com>
* configure (1.15.2.8), configure.in (1.13.2.6): autoconf now
detects if libgcc is built shared, in which case LIBS needs
-lgcc_s. Without it, the nsd binary will fail to link because of
unresolved symbols __umoddi3 and __udivdi3 in nsd/dsprintf.c.
2004-11-19 Dossy Shiobara <dossy@panoptic.com>
* nsd/Makefile (1.39.2.2): Adding -lz to LIBS is now redundant.
2004-11-19 Dossy Shiobara <dossy@panoptic.com>
* include/nsthread.h (1.24.2.4): Need to include <inttypes.h> on
some platforms (OS X, Solaris 10) to get C99 "uint32_t" and other
types. Backport from HEAD.
2004-11-19 Dossy Shiobara <dossy@panoptic.com>
* configure (1.15.2.7), configure.in (1.13.2.5),
include/Makefile.global.in (1.16.2.1), nsd/compress.c (1.1.2.2):
Add --with-zlib configure option (on by default) and add ifdef's
to nsd/compress.c. Backport from HEAD.
2004-11-17 Dossy Shiobara <dossy@panoptic.com>
* nsd/adprequest.c (1.16.2.1): Don't send Content-Length if
streaming is on. Backport from HEAD.
2004-11-15 Dossy Shiobara <dossy@panoptic.com>
* nsd/nsmain.c (1.52.2.3): AOLserver will now allow setting the fd
limit (via "ulimit -Hn", etc.) and only log a warning if it
exceeds FD_SETSIZE. Do this at your own risk, as things which
still use select(), i.e., Tcl, are likely to break. Backported
from HEAD.
2004-11-05 Dossy Shiobara <dossy@panoptic.com>
* nsd/sockcallback.c (1.12.2.3): Dereferencing cbPtr->nextPtr is
dangerous since cbPtr could have been freed.
2004-09-30 tag aolserver_v40_r9_b2
2004-09-30 Dossy Shiobara <dossy@panoptic.com>
* include/ns.h (1.55.2.13): BUMP: 4.0.9b
2004-09-30 Dossy Shiobara <dossy@panoptic.com>
* include/ns.h (1.55.2.12), nsd/tclhttp.c (1.16.2.5),
nsd/sockcallback.c (1.12.2.2): Implement
Ns_SockCancelCallbackEx() in order to correctly cancel actions in
the SockCallbackThread. Fix for SF Bug #1037196. Backported
from HEAD for 4.0.9.
2004-09-29 Dossy Shiobara <dossy@panoptic.com>
* include/ns.h (1.55.2.11), nsd/tclhttp.c (1.16.2.4),
nsd/sockcallback.c (1.12.2.1): Fix a thread hang issue when
ns_http fails but HttpCancel() never executes because poll()
returns revent == POLLPRI. Closes SF Bug #1037196. Backported
from HEAD for 4.0.9.
2004-09-24 Dossy Shiobara <dossy@panoptic.com>
* include/nsthread.h (1.24.2.2): Win32 supports the
get{addr,name}info() API, so use it. Backported from HEAD for
4.0.9.
2004-09-24 Dossy Shiobara <dossy@panoptic.com>
* nsd/dns.c (1.7.2.3): Small memory leak introduced on platforms w/
getaddrinfo. Closes SF Bug #1033575. Backport from HEAD for
4.0.9.
2004-09-22 Dossy Shiobara <dossy@panoptic.com>
* configure (1.15.2.6), configure.in (1.13.2.4): get{addr,name}info
on Solaris 9 is in -lsocket. Backported from HEAD.
2004-09-21 Dossy Shiobara <dossy@panoptic.com>
* configure (1.15.2.5), configure.in (1.13.2.3): Ensure we use the
compiler from the Tcl build during AOLserver configure process,
unless it's explicitly overrided during the AOLserver build.
Backported from HEAD for 4.0.9.
2004-09-21 Dossy Shiobara <dossy@panoptic.com>
* aclocal.m4 (1.1.4.3): Make detection of gethostby{addr,name}_r
more robust. Closes SF Bug #1032231. Backported from HEAD for
4.0.9.
2004-09-20 Dossy Shiobara <dossy@panoptic.com>
* nsd/: nsmain.c (1.52.2.2), nsd.h (1.77.2.7), unix.c (1.15.2.5):
Need to set the dumpable flag on Linux in order to get a core
file after uid/gid is changed. Closes SF Bug #1031599.
Backported from HEAD for 4.0.9a.
2004-09-17 Dossy Shiobara <dossy@panoptic.com>
* nsd/connio.c (1.12.2.2): Ns_ConnSend() now bubbles up the error
from NsSockSend() on first send, which is what the C API
documentation says. Closes SF Bug #1029512. Backported from
HEAD for 4.0.9a.
2004-09-17 Dossy Shiobara <dossy@panoptic.com>
* nsd/driver.c (1.17.2.9): "stopped" already initalized to 1, which
means NsWaitDriversShutdown() will never timeout even when it
should, which means trigPipe always gets closed immediately which
causes DriverThread to Ns_Fatal() on line 848. Closes SF Bug
#1029918.
2004-09-08 Dossy Shiobara <dossy@panoptic.com>
* nslog/nslog.html (1.1.10.1): Updated nslog module documentation.
Closes SF Bug #466236. Backported from HEAD.
2004-09-08 Dossy Shiobara <dossy@panoptic.com>
* nscgi/nscgi.html (1.1.10.2): Add datatype for config options to
doc. Backported from HEAD.
2004-09-07 Dossy Shiobara <dossy@panoptic.com>
* include/ns.h (1.55.2.10): BUMP: 4.0.9a
2004-09-07 tag aolserver_v40_r8
2004-09-07 Dossy Shiobara <dossy@panoptic.com>
* include/ns.h (1.55.2.9): BUMP: 4.0.8
2004-09-07 Dossy Shiobara <dossy@panoptic.com>
* README (1.4.2.1): Updated for 4.0.8.
2004-09-03 Dossy Shiobara <dossy@panoptic.com>
* nscgi/nscgi.html (1.1.10.1): Updated nscgi module documentation
for 4.0. Closes SF Bug #465907. Backported from HEAD.
2004-08-25 Dossy Shiobara <dossy@panoptic.com>
* nsd/queue.c (1.23.2.1): If reqPtr is NULL, close the connection
too.
2004-08-25 Dossy Shiobara <dossy@panoptic.com>
* nsd/driver.c (1.17.2.8): Previous code to eat leading blanks
assumed CR/LF, but some clients only send LF. Code has been
cleaned up and corrected to handle this properly.
2004-08-20 Dossy Shiobara <dossy@panoptic.com>
* Makefile (1.44.2.2), tests/new/all.tcl (1.1.2.1),
tests/new/harness.tcl (1.2.2.1), tests/new/ns_hrefs.test
(1.1.2.1), tests/new/test-ns_addrbyhost.adp (1.1.2.1),
tests/new/test-ns_hostbyaddr.adp (1.1.2.1),
tests/new/test-ns_hrefs.adp (1.1.2.1): Implement automated tests
that can be run from a stand-alone tclsh. New Makefile target
added called "test" which runs the tests.
2004-08-18 Dossy Shiobara <dossy@panoptic.com>
* tcl/fastpath.tcl (1.8.2.2): If _ns_dirlist gets an URL without a
trailing slash, issue a 302 redirect back to the same url WITH
the trailing slash. Fixes SF Bug #935907. Backported from HEAD.
2004-08-17 Dossy Shiobara <dossy@panoptic.com>
* nsd/fastpath.c (1.18.2.2): Minor change to eliminate Win32
compile-time warning. Closes SF Bug #696806. Backported from
HEAD.
2004-08-14 Dossy Shiobara <dossy@panoptic.com>
* aclocal.m4 (1.1.4.2), configure (1.15.2.3), nsd/dns.c (1.7.2.2):
Solaris 7 uses gethostbyaddr_r(), and the autoconf and GetHost()
versions didn't work. Fixed now. Backported from HEAD.
2004-08-14 Dossy Shiobara <dossy@panoptic.com>
* nsd/dns.c (1.7.2.1), aclocal.m4 (1.1.4.1), configure.in
(1.13.2.2), configure (1.15.2.2): gethostbyaddr() and
gethostbyname() are not thread-safe. Use the new getaddrinfo()
and getnameinfo() API where available, otherwise use
gethostbyaddr_r() and gethostbyname_r() if available. Otherwise,
continue to use the non-safe versions but emit a warning at
configure time. Fixes SF Bug #1008721. Backported from HEAD.
2004-08-13 Dossy Shiobara <dossy@panoptic.com>
* win32/: nscgi/nscgi.dsp (1.5.2.1), nscp/nscp.dsp (1.5.2.1),
nsd/nsd.dsp (1.14.2.1), nsdb/nsdb.dsp (1.1.2.1), nslog/nslog.dsp
(1.5.2.1), nsperm/nsperm.dsp (1.5.2.1), nssock/nssock.dsp
(1.8.2.1), nsthread/nsthread.dsp (1.7.2.1),
threadtest/threadtest.dsp (1.5.2.1): Change Win32 .dsp files to
reflect change in Tcl from "tcl84td.lib" to "tcl84tg.lib". Fixes
SF Bug #996342. Backported from HEAD.
2004-08-13 Dossy Shiobara <dossy@panoptic.com>
* nsd/tclmisc.c (1.30.2.1): ns_hrefs is now more robust. Fixes SF
Bug #995078. Backported from HEAD.
2004-08-11 Dossy Shiobara <dossy@panoptic.com>
* nsd/nsconf.c (1.32.2.3): Inability to resolve nsconf.hostname to
set nsconf.address is no longer fatal, and instead defaults to
"0.0.0.0". Fixes SF Bug #994072. Backported from HEAD.
2004-08-11 Dossy Shiobara <dossy@panoptic.com>
* nsd/driver.c (1.17.2.7): Fixed crash bug when virtual servers are
configured, but the "hostname" parameter didn't match any of the
virtual servers. Fixed by introducing new "defaultserver"
parameter in the comm. config that must refer to one of the
virtual servers being defined. Backported from HEAD.
2004-08-11 Dossy Shiobara <dossy@panoptic.com>
* sample-config.tcl (1.11.2.2): Add "defaultserver" parameter in
sample config. Backported from HEAD.
2004-08-05 Rob Crittenden <rcrittenden0569@aol.com>
* nsd/tclhttp.c: Add new option to ns_http wait, -servicetime, so
you can capture how long the HTTP request took.
2004-07-28 Dossy Shiobara <dossy@panoptic.com>
* include/ns.h (1.55.2.8): BUMP: 4.0.8a
2004-07-28 Dossy Shiobara <dossy@panoptic.com>
* configure (1.15.2.1), configure.in (1.13.2.1): Clean up
configure.in, regenerate configure with autoconf2.13, and clear
CCRPATH/LDRPATH if CCRFLAGS/LDRFLAGS are empty. Closes SF Bug
#640754. Backported from HEAD.
2004-07-19 tag aolserver_v40_r7
2004-07-19 Dossy Shiobara <dossy@panoptic.com>
* include/ns.h (1.55.2.7, aolserver_v40_r7): BUMP: 4.0.7
2004-07-18 Dossy Shiobara <dossy@panoptic.com>
* nsd/return.c (1.33.2.6): Fix bug where internal redirect for 401
omitted including the HTTP auth. "WWW-Authenticate:" header.
Fixes bug #674033. Backported from HEAD.
2004-07-18 Dossy Shiobara <dossy@panoptic.com>
* nsd/: nsd.h (1.77.2.6), init.c (1.5.2.1), nsconf.c (1.32.2.2):
Ns_GetAddrByHost() reports errors via Ns_Log(), so calls to it
should be done after Ns_Log has been initialized, otherwise very
unhelpful error messages are produced. In particular, this
happens when the server is started and the hostname as returned
by gethostname() cannot be resolved, because the network
interface is down AND no entry exists in /etc/hosts. Closes SF
Bug #868362. Backported from HEAD.
2004-07-16 Dossy Shiobara <dossy@panoptic.com>
* nsd/driver.c (1.17.2.6): Setting request->method to static
storage, which later gets ns_free()'d in Ns_FreeRequest(), caused
server to crash.
2004-07-16 Dossy Shiobara <dossy@panoptic.com>
* include/ns.h (1.55.2.6): BUMP: 4.0.7a
2004-07-16 tag aolserver_v40_r6
2004-07-16 Dossy Shiobara <dossy@panoptic.com>
* include/ns.h (1.55.2.5): BUMP: 4.0.6
2004-07-15 Tim Suh <suhti@aol.com>
* nsd/return.c: keepalive is enabled for response codes other than 200
2004-07-13 Dossy Shiobara <dossy@panoptic.com>
* nsd/: driver.c (1.17.2.5), op.c (1.11.2.1): Change to make HTTP
request "Host:" header mandatory for HTTP/1.1 connections by
returning 400 Bad Request response. Closes SF Bug #787728.
Also, changed virtual server code to use the "hostname" param
from the "ns/module/nssock" section to map the default virtual
server based on the value (hostname) from the
"ns/module/nssock/servers" section, when the "Host:" header is
either not specified (HTTP/1.0) or is not found in the virtual
server table. Closes SF Bug #812036. Backport from HEAD, but
not straight patch due to difference in conn/request handling in
4.0 vs. 4.1.
2004-07-13 Dossy Shiobara <dossy@panoptic.com>
* nslog/nslog.c (1.14.2.1): conn->headers can be NULL causing
segfault. Closes SF Bug #990439. Backported from HEAD.
2004-07-13 Dossy Shiobara <dossy@panoptic.com>
* include/nsthread.h (1.24.2.1): OpenBSD 3.5 doesn't define
ENOTSUP, so we'll define it ourselves. Closes SF Bug #985076.
Backported from HEAD.
2004-07-02 Dossy Shiobara <dossy@panoptic.com>
* nsd/mimetypes.c (1.11.2.1): Ns_GetMimeType() was returning
defaultType instead of noextType if the path contained a
directory with a "." but the filename component had no extension.
Fixes bug #739049. Backported from HEAD.
2004-07-02 Dossy Shiobara <dossy@panoptic.com>
* nsd/: fastpath.c (1.18.2.1), return.c (1.33.2.4): Enable ADP/Tcl
code to override Last-Modified: header from ns_respond when
-headers AND -file are specified. Closes bug #879076. Backport
from HEAD, for 4.0.6.
2004-07-02 Dossy Shiobara <dossy@panoptic.com>
* nsd/tclresp.c (1.16.2.1): lots of refactoring of ns_respond code
to remove duplication. Backport from HEAD.
2004-07-02 Dossy Shiobara <dossy@panoptic.com>
* nsd/init.tcl (1.30.2.1): ns_eval of script containing comments
(i.e., lines starting with "#") cause an error because $args is a
list, which gets evaluated differently than a plain string
script. Fixes bug #833940. Backported from HEAD.
2004-07-01 Dossy Shiobara <dossy@panoptic.com>
* nsd/: nsd.h (1.77.2.5), nsmain.c (1.52.2.1): Ensure that
supplementary groups from /etc/group are set if -u username is
specified, or dropped if a uid is specified so that the nsd
doesn't run with root's supplementary groups. Closes bug
#425401. Backport from HEAD.
2004-07-01 Dossy Shiobara <dossy@panoptic.com>
* nsd/nsd.h (1.77.2.4): trivial - eliminate compiler warning for
nsd/nsmain.c
2004-07-01 Dossy Shiobara <dossy@panoptic.com>
* nsthread/tls.c (1.2.2.1): Make the Tcl_Panic() message from
Ns_TlsGet() and Ns_TlsSet() include the full function name to aid
in debugging. (Backport from HEAD.)
2004-06-30 17:20 Dossy Shiobara <dossy@panoptic.com>
* nsd/unix.c: Ensure synchronous signals are handled correctly
under LinuxThreads. Possible fix for Bug #982955.
Backported from HEAD for 4.0.6.
2004-06-30 01:24 Dossy Shiobara <dossy@panoptic.com>
* include/ns.h: Fix build on alpha arch, removing extra INT64
typedef. Closes bug #896962. (Backport from HEAD.)
2004-06-23 Rob Crittenden <rcrittenden0569@aol.com>
* nsd/log.c: ns_log now logs to a custom logger as well.
2004-06-14 20:41 Dossy Shiobara <dossy@panoptic.com>
* nsd/return.c: unnecessary test for data != NULL actually caused
part of bug #971016 when fastpath.cache=false and
fastpath.mmap=true and the file requested is zero bytes, mmap()
returns 0 which gets passed along as data == NULL, causing
ReturnCharData() to not flush the queued headers. removing the
if is safe as Ns_WriteConn will simply flush any queued data
2004-06-14 20:40 Dossy Shiobara <dossy@panoptic.com>
* nsd/connio.c: If nsend == 0, we would never call Ns_WriteConn to
flush the queued headers. This could happen when we're sending
zero bytes of data as a response. This fixes bug #971016 in the
case where fastpath.cache=false and fastpath.mmap=false and a
zero byte file is requested.
2004-06-14 16:40 Dossy Shiobara <dossy@panoptic.com>
* nsd/return.c: one-liner fix for sending Content-Length header
for content of zero bytes (Bug #971016)
2004-06-03 Rob Crittenden <rcrittenden0569@aol.com>
* TAG aolserver_v40_r5
2004-06-03 Rob Crittenden <rcrittenden0569@aol.com>
* Makefile: remove Makefile.module during distclean
* include/ns.h, nsd/log.c: Allow users to override logging functions.
* nsd/str.c: Fix crash bug in Ns_Trim* when trimming NULL strings.
* nsd/: nsconf.c, driver.c, return.c, nsd.h: Add new bool config
option, keepaliveallmethods, which enables HTTP/1.0 Keep-Alives for
all valid methods. By default this is false.
2004-03-26 Mark Page <mpagenva@aol.com>
* nsd/nsd.h:
* nsd/driver.c:
* sample-config.tcl: Add configurable logging of errors which cause the
driver to drop a incoming connection socket. Logging goes to the
server log. Following new bool config params are added to the socket
driver's section (e.g., nssock, etc): readtimeoutlogging,
serverrejectlogging, sockerrorlogging,
sockshuterrorlogging.
2004-02-27 14:14 Dossy Shiobara <dossy@panoptic.com>
* include/ns.h: fix for bug #906011 "include/ns.h version not
bumped"
2004-02-26 14:37 Dossy Shiobara <dossy@panoptic.com>
* nsd/unix.c: uid_t is supposed to be unsigned, but apparently
isn't on OSX, apparently.
2004-02-19 13:22 Dossy Shiobara <dossy@panoptic.com>
* nsdb/: dbinit.c, dbtcl.c: fix "ns_db gethandle -timeout" so that
when timeout < 0 it blocks forever, timeout == 0 is poll, and
timeout > 0 times out after timeout seconds
2004-02-18 11:35 Dossy Shiobara <dossy@panoptic.com>
* nsperm/nsperm.c: fixed bug #899364, restoring old nsperm
functionality as it was in 3.x.
2003-11-23 mpagenva <mpagenva@aol.com>
* nsd/tclhttp.c: remove validity check on method param to ns_http
queue, since methods in addition to put and post can be valid.
* tcl/fastpath.tcl: make configuable: a) logging to serverlog
fastpath update requests (some configs may be fine with the
logging to the access log which can be easily obtained).
b) automatic backfill of implied directory tree on put.
2003-11-19 pkhincha <pkhincha@aol.com>
* maxinput to throttle the # of bytes
* on request.
* Removed ThreadJoin of driver thread.
2003-11-03 pkhincha <pkhincha@aol.com>
* nsd/urlspace.c: removed initing of mutex
* nsd/nsmain.c: calling NsWaitDriversShutdown
2003-11-01 Zoran Vasiljevic <zv@archiware.com>
* tcl/file.tcl: fixed broken argument convention for the
unused argument of ns_sourceproc.
2003-10-28 Zoran Vasiljevic <zv@archiware.com>
* nsd/tclatclose.c: fixed typo in command usage text
2003-10-09 Mark Page <mpagenva@aol.com>
* TAG aolserver_v4_r0_beta_20
* doc/ns_job.n:
* tests/api/ns_job.adp:
* nsd/tcljob.c: Change timeout specification to be ns_time
based.
2003-10-21 Elizabeth Thomas <eathomas93@aol.com>
* nsd/init.tcl: Removing lazyproc code from 4.0 to enable it
to be declared GM. Solution is being refined and may be added
in later release or add-on module.
2003-10-14 Paul Moosman <pwmoosman@aol.com>
* nsd/tcljob.c: Fix to ns_job, where it was attempting to access
a deleted queue.
2003-10-09 Mark Page <mpagenva@aol.com>
* TAG aolserver_v4_r0_beta_18
2003-10-09 Elizabeth Thomas <eathomas93@aol.com>
* nsd/init.tcl: Fix syntax error in check for null proc.
2003-10-08 Mark Page <mpagenva@aol.com>
* TAG aolserver_v4_r0_beta_17
* nsd/init.tcl (ns_eval): Minor change to track change to ns_job.
2003-10-08 Paul Moosman <pwmoosman@aol.com>
* nsd/tcljob.c: Minor change to ns_job joblist return to be
consistent with similar aolserver api's.
2003-10-07 Mark Page <mpagenva@aol.com>
* TAG aolserver_v4_r0_beta_16
* nsd/init.tcl (ns_eval): The early 4.0 ns_eval had been
waiting for the completion of integrating script changes into the
server's init script. This change adds the ability to return
without waiting for the init script integration completion (as the
default). A new switch modifies this behavior to force it to wait
for the completion of init script integration. Added another
switch to request a report of ns_eval backlog.
* nsd/adpeval.c (LogError): Limit the amount of script text added
into the errorInfo string, to keep from flowing adp script texts
of unlimited length into the server log.
2003-10-06 Paul Moosman <pwmoosman@aol.com>
* nsd/tcljob.c: Replaced ctime_r with ns_ctime to fix a win32
compile problem. This change should fix bug #811802.
Fixed a potential deadlock case.
Fixed a problem where the maxthreads option was getting ignored.
2003-10-01 Elizabeth Thomas <eathomas93@aol.com>
* nsd/init.tcl: Fix to _ns_lzproc_load to handle subtle behavior with
respect to namespaces and the test to see if the proc will be successfully
recognized. Also, fix to protect against infinite loop on unknown processing
if null command is executed.
2003-09-22 Mark Page <mpagenva@aol.com>
* TAG aolserver_v4_r0_beta_15
2003-09-22 Paul Moosman <pwmoosman@aol.com>
* nsd/tcljob.c: Add options to ns_job Api, for waitany, delete(queue),
listjobs, etc.
2003-09-19 Mark Page <mpagenva@aol.com>
* nsd/adprequest.c:
nsd/adpeval.c: Fix error where
xxx.adp --> ns_adp_parse --> ns_adp_include --> ns_adp_puts results in
the puts text going directly into the final result buffer, rather then
to the intermediate buffer to be returned by ns_adp_parse to the xxx.adp
page code.
2003-09-12 Mark Page <mpagenva@aol.com>
* TAG aolserver_v4_r0_beta_14
2003-09-11 Elizabeth Thomas <eathomas93@aol.com>
* nsd/init.tcl: Add 'lazyproc' functionality. Controlled by
ns/parameters config parm 'lazyprocdef' (defaults to 'false')
When 'true', we do not put proc definitions in the interp
init script, but instead wrap the tcl 'unknown' command and
evaluate them on the first reference. Also wraps the tcl 'info'
command to intercept queries about procs not yet in the interpreter.
2003-09-03 Mark Page <mpagenva@aol.com>
* TAG aolserver_v4_r0_beta_13
* nsd/tclinit.c (NsTclICtlObjCmd): Fix intermittant core dumps
occurring during oncleanup processing. The error is in the Tcl_Obj
for the script passed into ns_ictl on* callbacks was being saved
and passed to the callbacks (this Tcl_Obj was then being shared
amoung Interps, which is not allowed).
Now, extract a copy of the script string, and pass that to the callbacks.
2003-08-27 Elizabeth Thomas <eathomas93@aol.com>
* nsd/adprequest.c: Complete 8/12 fix of not
logging error for ns_adp_break
2003-08-26 Mark Page <mpagenva@aol.com>
* TAG aolserver_v4_r0_beta_12
2003-08-26 Elizabeth Thomas <eathomas93@aol.com>
* nsd/tclinit.c: Fix the 'oncleanup' option of ns_ictl.
Modify behavior of Ns_RegisterAtDelete so callbacks are
run before the interp is destroyed. Expose with new 'ondelete'
option to ns_ictl.
2003-08-25 Mark Page <mpagenva@aol.com>
* nsd/adprequest.c (): Suppress production of the result data for
requests with SKIPBODY set.
* nsd/return.c (ReturnCharData): Allow headers to be returned for
requests with SKIPBODY; e.g., HEAD requests.
2003-08-21 Zoran Vasiljevic <zoran@archiware.com>
* nsd/tclfile.c: properly detach and attach the Tcl channel
out and in the current interpreter.
2003-08-19 Rahul Bhargava <rahul032213@aol.com>
* nsd/return.c: Updated to support HTTP/1.1 Transfer Chunk Encoding
Headers only.
2003-08-19 Nathan Folkman <shmooved@aol.com>
* nsd/return.c: Updated to include status code from:
RFC 2616 (Hypertext Transfer Protocol -- HTTP/1.1) and
RFC 2518 (HTTP Extensions for Distributed Authoring -- WEBDAV).
2003-08-12 Elizabeth Thomas <eathomas93@aol.com>
* nsd/adprequest.c: Don't log ns_adp_abort or ns_adp_break as errors.
2003-08-08 Elizabeth Thomas <eathomas93@aol.com>
* nsd/mimetypes.c:
* sample_config.tcl: Add support for xhtml mime type. (RFE #563417)
* TAG aolserver_v4_r0_beta_11
2003-08-06 Elizabeth Thomas <eathomas93@aol.com>
* nsd/tclset.c: Fix ns_set split argument checking. (#757849)
2003-08-05 Elizabeth Thomas <eathomas93@aol.com>
* nsd/conn.c:
* nslog/nslog.c:
* include/ns.h:
* sample-config.tcl: Merge in feature from 3.5 branch (with simpler
implementation) for logging of request execution time in access log.
To turn on feature add:
ns_section "ns/server/${servername}/module/nslog"
ns_param logreqtime true
By default the option is disabled. If enabled the connection's
request time will be appended to the access log before the
extended headers (if configured).
2003-07-18 Elizabeth Thomas <eathomas93@aol.com>
* nsd/tclinit.c: Add optional mutex to serialize interp initialization.
With large init scripts and many threads, there is severe malloc
lock contention while tcl evaluates the init script (and populates
its memory pool). Serializing the initialization reduces the thrashing and
results in faster startup.
* nsd/nsconf.c, nsconf.h, nsd.h: Add config variable 'tclinitlock'
which activates the above. Defaults to false if not specified.
* TAG aolserver_v4_r0_beta_10
>>>>>>> 1.190
2003-07-18 Mark Page <mpagenva@aol.com>
* nsd/adpeval.c (AdpEval): Check adp.outputPtr validity before
use. It can get reset within this adp evaluation loop from
commands like ns_respond (when it does an internal redirect for
the file not found case). In this case, it's appropriate that
further text from this page code is not appended to the result, as
other code had determined that the result was complete.
2003-07-12 Zoran Vasiljevic <zoran@archiware.com>
* nslog/nslog.c: the "X-Forwarded-For" header existence is examined
when logging the remote user. This allows for logging the real
remote user wnen it commes from some proxy and/or load balancer.
Thanks for Gustaf Neumann of XOTcl for the patch. This implements
the RFE #770054.
2003-07-10 Mark Page <mpagenva@aol.com>
* TAG aolserver_v4_r0_beta_9
2003-07-01 Mark Page <mpagenva@aol.com>
* nsd/init.tcl (ns_eval): Protect against nested ns_eval calls,
which would otherwise lead to deadlocks.
2003-06-26 Mark Page <mpagenva@aol.com>
* nsd/adpeval.c: Fix problem where ns_adp_include was not propogating
errors.
2003-06-25 Mark Page <mpagenva@aol.com>
* nsd/init.tcl: (ns_eval) Fix thread-safety issue with ns_eval,
where multiple simultanous usages can clobber a change.
(_ns_getscript) suppress saving the Tcl global variable 'env' into
the init script. Tcl's init takes care of 'env', and including it
into the init script would cause SetEnvs at interp create that are
unneeded and undesired.
2003-06-18 Mark Page <mpagenva@aol.com>
* nsthread/thread.c (Ns_ThreadCreate): Fix typo in Ns_ThreadCreate
that was causing it to ignore the stacksize parameter.
* nsd/init.tcl (_ns_eval): Fix ns_eval to prevent it's bleeding of
unintended Tcl environment change to the global interp state.
2003-06-06 Zoran Vasiljevic <zoran@archiware.com>
* nsd/queue.c: fixed "connsperthread" config parameter
as reported in bug item #749801. Default is set to
"0" i.e. thread will perform unlimited number of
connections (never exit) unless it's idle timer
(if configured) expires.
2003-05-31 Zoran Vasiljevic <zoran@archiware.com>
* nsd/config.c: uses Ns_TclDestroyInterp instead of the
Tcl_DeleteInterp.
* nsthread/nsthreadtest.c:
* nsd/info.c:
* nsd/nsmain.c:
* include/Makefile.module.in:
* configure:
* configure.in: added --disable-shared so we can now build the
nsd image statically.
2003-05-31 Zoran Vasiljevic <zoran@archiware.com>
* nsd/cache.c:
* include/ns.h:
* doc/Ns_Cache.3: added C-API for Ns_CacheTryLock as in RFE #725704
2003-05-30 Mark Page <mpagenva@aol.com>
* nsd/tclthread.c: fix problem in ns_thread begindetached api.
This code was failing to create the new thread as detached.
Also corrected for the Ns_TclDetachedThread C api. As a
result of this change, non-detached threads will return their
TclEval result to Ns_ThreadExit, making it available to a
thread join.
2003-05-28 Mark Page <mpagenva@aol.com>
* TAG aolserver_v4_r0_beta_8
2003-05-28 Mark Page <mpagenva@aol.com>
* nsd/tclimg.c: Use binary channel to read img (Thanks to Dossy).
Eliminate double error string; Corrrect compiler warning on Seek.
* tcl/form.c: Fix to ns_querygetall to suppress null sublists. Also,
make the defaulting semantics work as described.
2003-05-24 Zoran Vasiljevic <zoran@archiware.com>
* nsd/info.c: added workaround for Tcl_GetMemoryInfo() which
is not defined in Tcl if somebody undefines USE_THREAD_ALLOC.
Generally, this call should be avoided altogether.
* nsd/tclinit.c: added call to Tcl_FinalizeThread() in the
DeleteInterps() to properly finalize Tcl data on thread exit,
thus closing the re-appearing memory leak from V3.3 nsd.
2003-05-20 Mark Page <mpagenva@aol.com>
* TAG aolserver_v4_r0_beta_7
2003-05-20 Mark Page <mpagenva@aol.com>
* nsd/tclimg.c: Addition error checks in gif size read.
* nsd/adpcmds.c: Error check calls to ns_adp funcs.
* nsd/tclinit.c: Error check calls to Ns_TclGetConn and Ns_TclServerInterp.
2003-05-19 Mark Page <mpagenva@aol.com>
* nsd/tclinit.c: suppress byte-compile for interp init scripts
* nsd/tclthread.c: fix fmr.
2003-05-16 Zoran Vasiljevic <zoran@archiware.com>
* nsdb/dbinit.c: fixed hash table initialization in IncrCount
to TCL_ONE_WORD_KEYS instead of TCL_STRING_KEYS. Credits to
Jean-Fabrice RABAUTE for the bug report.
2003-05-14 Zoran Vasiljevic <zoran@archiware.com>
* nsd/tclthread.c: fixed NsTclCondObjCmd to be compatible
to the 3.x pendant in way it threats the optional timeout
argument. The 3.x reverted to indefinite (i.e. non-timewait)
condvar waits when the optional "timeout" argument was given
as zero.
The 4.x version just exited with NS_TIMEOUT (= 0) in such
cases breaking Tcl scripts written for 3.x.
The corrective measure is to check the passed timeout value
and if == 0, revert to non-timewait condition waits as the
3.x does (did).
2003-05-13 Mark Page <mpagenva@aol.com>
* TAG aolserver_v4_r0_beta_6
2003-05-12 Mark Page <mpagenva@aol.com>
* nsd/urlencode.c : (bug fix) urlencode was passing through too
many characters unencoded. In particular, the '+' was getting
passed through, which causes unsymmetric encode/decode since
'+' in encoded string translates to ' '(space).
2003-04-25 Mark Page <mpagenva@aol.com>
* nsd/tclvar.c (NsTclNsvArrayObjCmd): (bug fix) nsv_array exists
must return true if an nsv exists, regardless of the number of
array elements in the nsv.
2003-04-24 Mark Page <mpagenva@aol.com>
* nsd/queue.c (ConnRun): Ensure that a Internal Error status is
returned to the client if an error status is returned from a
pre-auth filter. Previously, the connection was simply closed,
causing difficult to diagnose problems to the client. Also
allow traces to run in this situation, so that access logging can
occur.
2003-04-23 Mark Page <mpagenva@aol.com>
* nsd/log.c (NsTclLogObjCmd): (bug fix) Tweeked previous fix to
suppress trailing space on output.
2003-04-22 Nathan Folkman <shmooved@aol.com>
* nsd/log.c: (bug fix) Fixed bug causing first two string
args of "ns_log" to be improperly concatendated.
2003-04-16 Mark Page <mpagenva@aol.com>
* nsd/modload.c (NsLoadModules): (bug) Failed parsing the explicit
initialization specification properly.
2003-04-10 Mark Page <mpagenva@aol.com>
* TAG aolserver_v4_r0_beta_5
2003-04-07 Mark Page <mpagenva@aol.com>
* nsd/tclthread.c (NsTclThread): ensure that the server has
completed it's initializtion prior to initiating TclEval.
* nsd/nsmain.c (Ns_WaitForStartup): add dirty-read of the
conf.started flag.
2003-04-04 Mark Page <mpagenva@aol.com>
* nsd/tclinit.c:
* nsd/tclcmds.c: Moved interp tracing functionality into ns_ictl
api as one of it's subfunctions, removing the
ns_register_interptrace api previously created.
2003-04-03 Mark Page <mpagenva@aol.com>
* nsd/tclinit.c:
* nsd/tclcmds.c: Provide tcl api that exposes Ns_TclInitInterps
and Ns_TclRegisterTrace. ns_register_interptrace.
2003-03-30 Scott S. Goodwin <scott@scottg.net>
* include/ns.h:
nsd/driver.c:
nssock/nssock.c:
nsssl/nsssl.c: Modified Ns_DriverInit. Instead of passing all args
as parameters to Ns_DriverInit, a comm module must now create an
Ns_DriverInitData structure and populate it with appropriate values
(see include/ns.h) and pass that in the call to Ns_DriverInit. The
Ns_DriverInitData structure is versioned so that we can extend it
later without affecting other modules.
2003-03-28 Mark Page <mpagenva@aol.com>
* nsd/tclhttp.c: (bug) Fix uninitialized hdrs var, was causing segfault.
2003-03-21 Mark Page <mpagenva@aol.com>
* TAG aolserver_v4_r0_beta_4
2003-03-19 Mark Page <mpagenva@aol.com>
* nsd/tclhttp.c: Added method argument to ns_http queue api to
allow sending POSTs as well as GETs.
2003-03-19 Mark Page <mpagenva@aol.com>
* nsext/nsext.c: Change back to using ns_socketpair for local
proxies, to retain PEEK functionality.
2003-03-19 Zoran Vasiljevic <zoran@archiware.com>
* nsd/modload.c: added fallback for loading regular
shared libraries in addition to bundles on Darwin.
* include/tcl.h: added set of version macros
* nsd/config.c: added Ns_GetVersion API call.
2003-03-10 Scott S. Goodwin <scott@scottg.net>
* nscgi/nscgi.c: (bug) SERVER_NAME is now set correctly.
2003-03-10 Mark Page <mpagenva@aol.com>
* nsd/sched.c: (bug) Fix problem with shutting down event threads
(these service detachted thread processing) on a server shutdown.
2003-03-07 Nathan Folkman <shmooved@aol.com>
* TAG aolserver_v4_r0_beta_3
2003-03-07 Zoran Vasiljevic <zoran@archiware.com>
* include/ns.h:
* nscgi/nscgi.c:
* nscp/nscp.c:
* nsd/adpeval.c:
* nsd/adpparse.c:
* nsd/binder.c:
* nsd/config.c:
* nsd/conn.c:
* nsd/connio.c:
* nsd/dns.c:
* nsd/driver.c:
* nsd/dstring.c:
* nsd/encoding.c:
* nsd/fastpath.c:
* nsd/index.c:
* nsd/info.c:
* nsd/lisp.c:
* nsd/listen.c:
* nsd/log.c:
* nsd/modload.c:
* nsd/nsmain.c:
* nsd/pidfile.c:
* nsd/queue.c:
* nsd/request.c:
* nsd/rollfile.c:
* nsd/sched.c:
* nsd/sockcallback.c:
* nsd/tclatclose.c:
* nsd/tclfile.c:
* nsd/tclhttp.c:
* nsd/tclimg.c:
* nsd/tclinit.c:
* nsd/tcljob.c:
* nsd/tclmisc.c:
* nsd/tclshare.c:
* nsd/tclsock.c:
* nsd/tclvar.c:
* nsd/tclxkeylist.c:
* nsd/urlencode.c:
* nsd/urlspace.c:
* nsdb/dbinit.c:
* nsdb/dbtcl.c:
* nsext/nsext.c:
* nslog/nslog.c:
* nspd/log.c:
* nspd/main.c:
* nsperm/nsperm.c:
* nsthread/mutex.c:
* nsthread/nsthreadtest.c:
* nsthread/pthread.c:
o. removed unused variables
o. fixed warnings about non-initialized vars
o. CONST-ified according to Tcl 8.4+ rules
* bin/init.tcl: _ns_getscript forces import of
namespaced commands
* tcl/init.tcl: sets auto_path to start with
our private library first
* include/Makefile.global.in: allows for building
with Solaris 2.6 and later
2003-03-06 Mark Page <mpagenva@aol.com>
* nsd/adpeval.c: Change defn of objs field of InterpPage to size
1, since some compilers don't like 0 sized arrays.
* nsd/urlencode.c:
* nsd/queue.c:
* nsd/server.c:
* nsd/urlencode.c:
* nsd/encoding.c:
* nsd/nsd.h:
* nsd/form.c:
* nsd/conn.c:
* include/ns.h:
* tcl/form.tcl:
* tcl/charsets.tcl(new): Added Tcl I18N support functions from
OACS, with some changes to work within 4.0.
2003-03-05 Zoran Vasiljevic <zoran@archiware.com>
* nsd/init.tcl: added handling of commands imported from
other namespaces in _ns_getscript procedure.
2003-03-05 Mark Page <mpagenva@aol.com>
* nsd/adpeval.c: (fix) Fixed handling of Tcl errors from script.
2003-03-05 Mark Page <mpagenva@aol.com>
* nsd/adpeval.c:
* nsd/adpcmds.c:
* nsd/nsd.h: (patch) Added optional switches to ns_adp_parse;
-cwd <path>, -savedresult <varname>
-savedresult supports usages which require the adp script's result
separate from the output buffer (which is the func result)
-cwd supports prespecifying the initial cwd for which the script
will be executed.
2003-03-03 Nathan Folkman <shmooved@aol.com>
* nscgi/nscgi.c: (bug fix) Applied patch to set SCRIPT_NAME
which is passed as an environment variable to the CGI script.
SF bug 230479.
2003-02-25 Nathan Folkman <shmooved@aol.com>
* nsd/init.tcl: (patch) Added logging of errorInfo
and errorCode globals to _ns_sourcefile command.
SF patch 690025.
* sample-config.tcl:
* tcl/fastpath.c: (bug fix) Added fast path configuration
example. Fixed bug that was adding an extra slash to
directory listings in _ns_dirlist. SF bug 682077.
* nsd/tclimg.c: (bug fix) Fixed ns_jpegsize command for
images which contained a DHT. Removed AppendDims command
which has been replaced with AppendObjDims. SF bug 685055.
2003-02-07 Elizabeth Thomas <eathomas93@aol.com>
* TAG aolserver_v4_r0_beta_2
* tcl/sendmail.tcl: (bug fix) SF bugs 669217/669844
Fix handling of addressees so we don't lose friendly address name
* configure: fix additional defaults from cc to gcc
2003-02-06 Mark Page <mpagenva@aol.com>
* nsd/return.c: (bug fix) SF bug 674033.
(bug fix) Correct the status code for BadRequest returns.
2003-02-06 Jamie Rasmussen <jrasmuss@mle.ie>
* nsthread/winthread.c: (bug fix) SF bug 675033.
(bug fix) Fixed crash on second DLL_THREAD_DETACH.
2003-02-05 Elizabeth Thomas <eathomas93@aol.com>
* nsext.c: Fix LocalProxy function to call Ns_CloseOnExec
after the file descriptors have been opened instead of before
2003-02-04 Jamie Rasmussen <jrasmuss@mle.ie>
* include/nsthread.h:
* include/ns.h:
* nscgi/nscgi.c:
* nscp/nscp.c:
* nsd/adpeval.c:
* nsd/driver.c:
* nsd/encoding.c:
* nsd/exec.c:
* nsd/fastpath.c:
* nsd/fd.c:
* nsd/info.c:
* nsd/init.c:
* nsd/listen.c:
* nsd/modload.c:
* nsd/nsd.h:
* nsd/nsmain.c:
* nsd/pathname.c:
* nsd/request.c:
* nsd/server.c:
* nsd/sock.c:
* nsd/sockcallback.c:
* nsd/tclenv.c:
* nsd/tclfile.c:
* nsd/tclhttp.c:
* nsd/tclimg.c:
* nsd/tclsock.c:
* nsd/tclxkeylist.c:
* nsd/urlencode.c:
* nsd/urlopen.c:
* nsd/getopt.c:
* nsd/getopt.h:
* nsd/nswin32.c:
* nssock/nssock.c:
* win32: Added Win32 support and build files
2003-02-04 Nathan Folkman <shmooved@aol.com>
* nsd/tclmisc.c: (bug fix) Fixed arg checking bug in
NsTclStrftimeObjCmd (ns_fmttime) API.
2003-02-03 Jamie Rasmussen <jrasmuss@mle.ie>
* tcl/sendmail.tcl: (bug fix) SF bug 632265.
* Fixed minor spelling errors in comments.
2003-02-01 Nathan Folkman <shmooved@aol.com>
* tcl/stats.tcl: Consolidated web based stats interface into
a single Tcl file.
* sample-config.tcl: Added web stats configuration.
2003-01-31 Mark Page <mpagenva@aol.com>
* nsd/conn.c:
* nsd/connio.c:
* nsd/encoding.c:
* nsd/form.c:
* nsd/nsconf.c:
* nsd/nsd.h:
* nsd/queue.c:
* nsd/return.c:
* nsd/tclcmds.c:
* nsd/tclresp.c:
* nsd/urlencode.c:
* include/ns.h: added in I18N capabilities derived from the OACS
I18N design. This set of changes is just those which are
supported within the nsd C-code.
* sample-config.tcl: Add text for I18N specific config.
2003-01-28 Nathan Folkman <shmooved@aol.com>
* nsd/server.c:
* tcl/fastpath.tcl: (bug fix) Tcl code was updated to reflect a
a change made earlier to server.c, in which all fast path related
configuration was moved from ns/server/<server> to
ns/server/<server>/fastpath. This change will require you to
update your configuration file to reflect the new configuration
path for any fast path options.
*** INCOMPATIBILITY ***
2003-01-28 Nathan Folkman <shmooved@aol.com>
* nsd/init.tcl: (bug fix) Updated ns_eval command to mark Tcl interp for
deletion in the case of a TCL_ERROR only. Updated ns_eval to properly
handle an arbitrarly long number of args. SF bug 675506.
2003-01-24 Elizabeth Thomas <eathomas93@aol.com>
* include/Makefile.global.in:
* README: Added $(PURIFY) variable back from 3.4 to facilitate
easy purify compile.
* configure: Made gcc the default value for $CC instead of cc.
2003-01-23 Elizabeth Thomas <eathomas93@aol.com>
* Tagged first 4.0 beta: aolserver_v4_r0_beta_1
2003-01-19 Nathan Folkman <shmooved@aol.com>
* nscp/nscp.c: Cleaned up log messages to be more consistent
with other server messages. Moved user name from thread name into
log notice. Control port logging now disabled by default. Added
more detailed configuration instructions to sample-config.tcl.
2003-01-18 Jim Davidson <jgdavidson@aol.com>
* nsd/auth.c:
* nsd/conn.c:
* nsd/form.c:
* nsd/httptime.c:
* nsd/info.c:
* nsd/log.c:
* nsd/mimetypes.c:
* nsd/nsconf.c:
* nsd/nsd.h:
* nsd/nsmain.c:
* nsd/pathname.c:
* nsd/random.c:
* nsd/tclcmds.c:
* nsd/tclfile.c:
* nsd/tclhttp.c:
* nsd/tclimg.c:
* nsd/tclinit.c:
* nsd/tclmisc.c:
* nsd/tclrequest.c:
* nsd/tclresp.c:
* nsd/tclset.c:
* nsd/tclsock.c:
* nsd/tclthread.c:
* nsd/urlencode.c:
* nsd/urlopen.c: Removed old string commands.
* nsd/conn.c:
* nsd/connio.c:
* nsd/driver.c:
* nsd/init.c:
* nsd/nsd.h:
* nsd/queue.c:
* nsd/return.c:
* nsd/server.c:
* nsd/tclinit.c: Moved Host header mapping code from
queue.c to driver.c to catch cases of unmapped Host's.
Also, updated the Conn and Sock structures to maintain the
servPtr and location correctly Host header based connections.
* nsthread/Makefile:
* nsthread/cond.c (removed):
* nsthread/error.c:
* nsthread/memory.c:
* nsthread/mutex.c:
* nsthread/nsthreadtest.c:
* nsthread/pthread.c (added):
* nsthread/reentrant.c:
* nsthread/thread.c:
* nsthread/thread.h:
* nsthread/time.c:
* nsthread/tls.c:
* nsthread/winthread.c (added):
* include/nsthread.h: Brought forward nsthread library
from 3.5 which includes support for Win32.
2003-01-18 Zoran Vasiljevic <zoran@archiware.com>
* nsd/init.tcl: Summary of changes:
o. added _ns_getpackages to enable "package require".
o. fixed various issues in ns_getscript proc related to
of standard Tcl commands.
o. fixed ns_eval to return value/error and made compatible
with standard Tcl "eval" and AOLserver "ns_eval" from 3.x
o. made the entire file little bit more readable.
2003-01-17 Mark Page <mpagenva@aol.com>
* nsd/driver.c: Change to SockRead; if request has a
content-length, null-terminate the content at the specified
length. This fixes a problem when some browsers add extra CRLF
characters beyond the specified content-length on a POST (see this
by using IE to POST data).
2003-01-16 Elizabeth Thomas <eathomas93@aol.com>
* nsd/tclmisc.c: Fix WordEndsInSemi so that ns_striphtml correctly
* handles ampersands that are not followed by a space or semicolon
2002-11-06 Jeremy Collins <jcollins@phpsource.net>
* nsd/adpparse.c: Changed ParseAtts to make it compatible with
how parsing works in 3.x.
* nsd/init.tcl: Fixed namespace bug.
2002-11-05 Jeremy Collins <jcollins@phpsource.net>
* nsd/adpparse.c: Fixed a bug in Parse. It was not parsing
registered tags inside of html tags (ex. <td bgcolor='<tag n='v'>'> )
* nsd/tclset.c: Fixed a bug with ns_set tcl commands.
ns_set idelkey|delkey would not actually delete the key.
2002-11-02 Jim Davidson <jgdavidson@aol.com>
* nsd/fastpath.c: Fixed bug with non-server specific cache names.
2002-11-01 Jeremy Collins <jcollins@phpsource.net>
* nsd/adpparse.c: Fixed a small bug in ParseAtts. It failed
to properly parse attribute values with spaces in them.
2002-10-29 Jim Davidson <jgdavidson@aol.com>
* sample-config.tcl: Updated with examples for connection
thread pools and Host header virtual servers.
* Makefile: Uses /bin/sh to invoke install-doc.
* doc/install-doc: Uses /bin/sh to invoke mkLinks.
* nsd/form.c:
* nsd/conn.c:
* tcl/form.tcl: Changed "ns_conn files" command to just
return names of file upload widgets, moving access to other
meta data to new fileoffset, filelength, and fileheaders
subcommands. Also, removed the ns_conn string command
instead of updating.
* nsd/nsd.h:
* nsd/driver.c:
* nsd/nsmain.c:
* nsd/server.c:
* nsd/queue.c: Implemented multiple named thread pools
for virtual servers and Host header based virtual server
selection. See sample-config.tcl for config example.
* nsd/info.c: Fixed crash bug with NULL server.
* nsd/tclcmds.c: Removed NsTclConnCmd and NsTclServerCmd
string commands.
2002-10-14 Jim Davidson <jgdavidson@aol.com>
* doc/install-doc (new): New script to install and cross
link the man pages.
* Makefile:
* include/Makefile.module: Added .PHONY targets and man
page install target.
* nsd/conn.c: Made "ns_conn copy" use Tcl_Write instead
of Tcl_WriteChars to fix binary file upload bug.
* nsd/form.c: Fixed bug where Ns_ConnGetQuery (i.e.,
ns_conn form) could not handle binary data in multpart file
uploads. Also, "ns_conn files" now returns file type.
* nsd/log.c: Thread ids are now formatted as unsigned
long.
* include/ns.h:
* nsd/config.c:
* nsd/tclinit.c:
* nsd/tclcmd.c:
* nsd/tclsock.c:
* nsd/main.c: Added support for libnsd.so to be loaded
into a standard (thread enabled) tclsh or linked into a
custom tclsh. Calling Ns_TclInit from a custom tclsh or
non-server AOLserver commands (e.g., adds ns_set but not
ns_adp_puts).
* nsd/server.c:
* nsd/tcljob.c: Changed ns_job command to create and queue
jobs to named queues instead of per-server queues.
* nsd/tclthread.c: Added a special Tcl address object type
to speed access to the object id's.
* nsd/sched.c: Threaded events now use a thread pool
instead of create/delete each time.
* tcl/form.tcl: Fixed bug accessing uploaded binary files
with the ns_getform proc and added ns_getformfile proc to
address the ".tmpfile" security issue.
2002-09-28 Jim Davidson <jgdavidson@aol.com>
* nsd/adpparse.c:
* nsd/auth.c:
* nsd/conn.c:
* nsd/connio.c:
* nsd/driver.c:
* nsd/dstring.c:
* nsd/filter.c:
* nsd/init.c:
* nsd/log.c:
* nsd/main.c:
* nsd/modload.c:
* nsd/nsd.h:
* nsd/nsmain.c:
* nsd/queue.c:
* nsd/return.c:
* nsd/server.c:
* nsd/tclenv.c:
* nsd/tclinit.c:
* nsd/tclthread.c:
* include/ns.h: Added missing AOLserver 3.x API's including
static module support, Ns_TclRegisterAt traces, connection
I/O functions, loadable comm driver stubs, and more.
* configure:
* configure.in:
* nsd/exec.c: Removed weird USE_PROCTHREAD code.
* nsd/init.tcl: Uses "ns_ictl modules" for module list.
* nscgi/nscgi.c: Uses Ns_CopyEnviron, renamed from
Ns_GetEnvironment.
* Makefile: Fixed install bug for install-sh.
* README: Updated to match AOLserver 3.5. Various outdated
docs removed.
2002-09-10 Jim Davidson <jgdavidson@aol.com>
* Makefile:
* INSTALL (new):
* aclocal.m4 (new):
* configure (new):
* configure.in (new):
* include/Makefile.global (removed):
* include/Mkaefile.global.in (new):
* include/Makefile.module: New autoconf-based configuration
and build.
* nsd/log.c:
* nsd/tclenv.c: Updated to used new autoconf-based compile
info.
2002-08-24 Jim Davidson <jgdavidson@aol.com>
* nsd/filter.c:
* nsd/server.c:
* nsd/tclatclose.c:
* nsd/tclvar.c:
* nsd/tclinit.c:
* nsd/tcljob.c:
* nsd/nsd.h: Moved private struct definitions out of nsd.h
back to files which depend on them, e.g., struct Filter.
* nsd/tclatclose.c:
* nsd/tclinit.c: Moved Ns_TclRegisterDeferred to tclinit.c.
* nsd/adpeval.c:
* nsd/tclsock.c:
* nsd/tclinitc: Eliminated NsTclEval in favor of Tcl_EvalEx.
* nsd/log.c:
* nsd/nsconf.h:
* nsd/nsconf.c: Removed complicated and dubious log
buffering option. The new ns_logctl feature can be used
to batch noisy requests.
* nsd/tclinit.c:
* nsd/tclcmds.c:
* nsd/init.tcl: Added new ns_init command to replace the
nsv-based namespace copy/update mechanism. The init.tcl
is now called only at startup.
* conn.c:
* driver.c:
* queue.c:
* nsd.h: Connection times and timeouts now maintained with
Ns_Time-based microsecond resolution.
2002-07-14 Jim Davidson <jgdavidson@aol.com>
* nsd/log.c:
* nsd/tclcmds.c: Added the ns_logctl command with options
to hold, release, flush, etc. the log messages in a thread.
* nsd/adpcmds.c:
* nsd/urlopen.c: Switched to more object-correct
Tcl_ObjSetVar2.
2002-07-08 Jim Davidson <jgdavidson@aol.com>
* nsd/tclthread.c: Cleaned up the object-based commands
by collecting common argument and new object allocation
code into single GetArgs function.
2002-07-07 Jim Davidson <jgdavidson@aol.com>
* nsd/tclvar.c: Removed string commands because it was
messy maintaining both.
* nsd/info.c:
* nsd/queue.c:
* nsd/tclcmds.c:
* nsd/tclset.c: Added object commands.
* nsd/tclobj.c:
* nsd/tclmisc.c: Updated Ns_Time type code to handle simple
single-integer times without microsecond resolution.
* include/ns.h:
* include/Makefile.global:
* Makefile: Updated for AOLserver beta4 release to coincide
with Tcl beta1 release.
Otherwise, minor edits to new object commands in several
places.
2002-07-05 Jim Davidson <jgdavidson@aol.com>
* nsd/nsd.h:
* nsd/adpcmds.c:
* nsd/adpeval.c:
* nsd/adprequest.c:
* nsd/tclcmds.c: Updated remaining ADP commands to be
object-based. Because the NsInterp->adp struct now uses
Tcl_Obj's for call frame args, the string commands were
just dumped.
2002-06-25 Scott S. Goodwin <scott@scottg.net>
* nsd/tclvar.c:
* nsd/tclcmds.c: Reimplemented nsv commands as object commands.-06-12 Jeremy Collins <jeremy.collins@phpsource.net>
* nsd/conn.c:
* nsd/tclcmds.c: Reimplemented "ns_conn" as an obj based
command. In the process I also modified NsTclConnObjCmd to use
Tcl_GetIndexFromObj. This should improve performance as well as
the readability of the code.
* nsd/auth.c:
* nsd/form.c:
* nsd/httptime.c:
* nsd/log.c:
* nsd/mimetypes.c:
* nsd/nsmain.c:
* nsd/pathname.c:
* nsd/random.c:
* nsd/tclatclose.c:
* nsd/tclfile.c:
* nsd/tclhttp.c:
* nsd/tclimg.c:
* nsd/tclinit.c:
* nsd/tclmisc.c:
* nsd/tclrequest.c:
* nsd/tclresp.c:
* nsd/tclsock.c:
* nsd/tclthread.c:
* nsd/urlencode.c:
* nsd/urlopen.c: Cleaned up the way we were setting the result
on tcl errors.
2002-06-12 Jim Davidson <jgdavidson@aol.com>
* include/nsthread.h:
* nsthread/mutex.c:
* nsthread/thread.c:
* nsd/info.c: Rename Ns_MutexEnum and Ns_ThreadEnum to
Ns_MutexList and Ns_ThreadList to not conflict with pre-4.0
definitions of removed functions.
* nsthread/Makefile
* nsthread/nshtreadtest.c (new file): Added simple program
to test thread interface.
* nsthread/thread.h:
* nsthread/cslock.c:
* nsthread/rwlock.c: Added new NsMutexInitNext function
to consistantly name mutexes in internal objects.
* nsthread/sema.c: Restored AOLserver 3.x implementation
using Ns_Mutex and Ns_Cond objects. The API's in <semaphore.h>
were not implemented on OS/X.
2002-06-10 Jim Davidson <jgdavidson@aol.com>
* include/Makefile.global:
* include/Makefile.module: Added support for dynamic
library init procs set via the LIBINIT make variable.
* Makefile:
* nsthread/compat.c:
* nsthread/cond.c:
* nsthread/cslock.c
* nsthread/error.c:
* nsthread/fork.c:
* nsthread/master.c:
* nsthread/memory.c:
* nsthread/mutex.c:
* nsthread/osxcompat.c:
* nsthread/osxcompat.h:
* nsthread/reentrant.c:
* nsthread/rwlock.c:
* nsthread/sema.c:
* nsthread/signal.c:
* nsthread/thread.c:
* nsthread/thread.h (new file):
* nsthread/time.c:
* nsthread/tls.c: Moved from nsd as separate nsthread
library.
* include/ns.h:
* include/nsthread.h: Include of tcl.h moved to nsthread.h
from ns.h.
* nsd/Makefile
* nsd/init.c (new file):
* nsd/binder.c:
* nsd/cache.c:
* nsd/config.c:
* nsd/encoding.c:
* nsd/exec.c:
* nsd/info.c:
* nsd/listen.c:
* nsd/log.c:
* nsd/mimetypes.c:
* nsd/modload.c:
* nsd/nsd.h:
* nsd/nsmain.c:
* nsd/nsconf.c:
* nsd/proc.c:
* nsd/sched.c:
* nsd/server.c:
* nsd/tclinit.c:
* nsd/urlspace.c: Various runtime initializations collected
into dynamic library load time init via NsdInit in init.c.
2002-06-08 Jim Davidson <jgdavidson@aol.com>
* include/Makefile.global
* include/Makefile.module: Support for building programs
along with dynamic libraries and modules. Also, fixed bug
setting -install_name on OS/X.
* nsd/Makefile: Use of updated Makefile.module and include
osxcompat.o on OS/X.
* nsd/nsd.h:
* nsd/osxcompat.h:
* nsd/osxcompat.c: Compat functions moved from ../nsosx.
* nsosx/README (removed):
* nsosx/Makefile (removed):
* nsosx/nsosx.c (removed): Tcl no longer requires any
compat functions, remainder moved into nsd.
Otherwise, minor tweaks throughout to silence compiler
warnings.
2002-06-05 Jim Davidson <jgdavidson@aol.com>
* Makefile:
* include/Makefile.global: Added tclmemdbg flag to compile
Tcl and AOLserver with TCL_MEM_DEBUG option.
* nsd/unix.o:
* nsosx/README (new file):
* nsosx/Makefile (new file):
* nsosx/nsosx.o (new file): Hacks for Apple OS/X removed
from nsd/unix.o and moved to nsosx.o as a Tcl compat object.
See README for instructions.
* nsd/nsd.h:
* nsd/server.c:
* nsd/adpparse.c:
* nsd/adpcmds.c:
* nsd/adpeval.c: Added support for new ns_adp_safeeval
and ns_adp_registerproc commands. Also, registered tags
can now be modified after startup.
* include/Makefile.module: Updated to allow building of
dynamic library of public routines to go with dynamic
module, e.g., libnsdb.so with nsdb.so.
* nsext/Makefile:
* nspd/Makefile:
* nspd/msg.c (removed):
* nsext/msg.c (moved from nspd): Moved Ns_Ext API from
libnspd.a static library to libnsext.so dynamic library as
it's used by both nsext.so and proxy drivers.
* nsdb/Makefile:
* nsdb/nsext.c (new file): Moved public API for nsdb out
of nsdb.so module and into libnsdb.so dynamic library.
2002-05-15 Jim Davidson <jgdavidson@aol.com>
* Makefile:
* include/Makefile.global:
* tcl8.3.4 (removed): As of Tcl version 8.4., no modifications
to the Tcl sources are required for AOLserver. Therefore,
the hacked 8.3.4 sources have been removed. Going forward
you'll need to checkout the Tcl source from Sourceforge
into the directory specified in include/Makefile.global
(currently ../tcl8.4). The top level Makefile includes
the "tcl-checkout" and "tcl-update" targets which should
* include/ns.h:
* nsd/server.c:
* nsd/nsd.h:
* nsd/tclcmds.c:
* nsd/tclinit.c:
* nsd/init.tcl:
* nsd/dbdrv.c (removed):
* nsd/dbinit.c (removed):
* nsd/dbtcl.c (removed):
* nsd/dbutil.c (removed):
* nsdb/dbinit.c (new):
* nsdb/dbdrv.c (new):
* nsdb/dbtcl.c (new):
* nsdb/dbutil.c (new):
* include/nsdb.h (new): Moved the NsDb interface from core
to new nsdb module. Simply loading nsdb.so should work as
before. Goal is to enable full replacement of NsDb in the
future.
* nsd/cache.c:
* nsd/callbacks.c:
* nsd/listen.c:
* nsd/nsconf.c:
* nsd/op.c:
* nsd/sched.c:
* nsd/server.c:
* nsd/sockcallback.c:
* nsd/urlspace.c:
* nsext/nsext.c:
* nslog/nslog.c:
* nslog/nslog.c: Simple mutex name updates.
* nscgi/nscgi.c: Minor bug fixes
* nsd/adpeval.c: Fixed read of freed data.
* nsd/tclinit.c: Fixed crash bug of null interp delete.
* nsd/exec.c:
* include/Makefile.global: Support for process manager
thread enabled with -DUSE_PROCTHREAD to route all process
create/wait through a single thread for Linux threads.
2002-02-24 Jim Davidson <jgdavidson@aol.com>
* nsd/nsd.h
* nsd/unix.c:
* tcl8.3.4/unix/tclLoadDyld.c: Hacks for routines missing
from OS/X. The implementation of sigwait() is not strictly
correct but appears good enough for AOLserver's use.
* Makefile:
* nsd/Makefile:
* nsmain/Makefile:
* include/Makefile.global:
* include/Makefile.module:
* include/Makefile.library (removed): Updates for linking
modules against the nsd shared library and for library
filenames which don't end in .so.
* nsext/Makefile
* nspd/Makefile: Moved proxy message code from nsext to
nspd, now a static library.
* nsd/main.c:
* nsd/init.c:
* nsd/Makefile:
* nsmain/*:
* sample-config.tcl:
* tcl2ini.tcl:
* ini2tcl.tcl:
* Makefile: Moved build and install of nsd and init.tcl
into nsd directory and install of sample config to top
level Makefile. Added tcl2ini.tcl and ini2tcl.tcl config
file utilities.
2002-02-07 Jeff Hobbs <jeffh@ActiveState.com>
* nsmain/init.tcl:
* nsmain/sample-config.tcl:
* nsssl/keygen.tcl:
* tcl/debug.tcl:
* tcl/fastpath.tcl:
* tcl/file.tcl:
* tcl/form.tcl:
* tcl/http.tcl:
* tcl/nsdb.tcl:
* tcl/sendmail.tcl:
* tcl/util.tcl: code cleanup to brace exprs and fix indentation
2001-12-05 Jim Davidson <jgdavidson@aol.com>
* nsd/tclthread: Tcl threads now return their string result
via ns_thread wait.
2001-12-20 Scott S. Goodwin <scott@scottg.net>
* include/Makefile.library: Changed RFLAG to RPATH, and took out
$(AOLSERVER)/lib:
$(LDSO) -o $(LIB) $(OBJS) $(LIBS) $(RFLAG) $(AOLSERVER)/lib
now reads:
$(LDSO) -o $(LIB) $(OBJS) $(LIBS) $(RPATH)
which is what I think was intended. Still have the problem
that $(AOLSERVER)/lib must already exist.
2001-11-05 Jim Davidson <jgdavidson@aol.com>
* Removed support for Win32, removing both the build/test
environment and updating the code to be standard Unix style.
Among other style changes such as changing SOCKET's to
simple Unix style int's, the short lived Ns_Buf structure
was also eliminated in favor of the Unix standard struct
iovec.
* Removed support for older non-pthread Unix platforms such
as HP/10 and SGI native.
* Updated Tcl to version to Tcl 8.3.4, replacing tclAlloc.c
with a modified version of what was libnsthread's fast pool
allocator including support for fast direct Tcl_Obj
allocation. Also added a few functions to tclUnixThrd.c
for thread safety (e.g., readdir_r and localtime_r support)
and fixed up tcl.m4 for better FreeBSD 4.4 and Solaris
thread builds.
* ns_malloc, Ns_ThreadMalloc, and Ns_PoolAlloc all now
simply call Tcl_Alloc which is always enabled. The previous
-z (enable) and -p (disable) command line flags are ignored.
* Integrated remainder of libnsthread, now standard pthreads
and compatible with Tcl pthread code, into libnsd.so.
* Updated libnsd.so to use poll() instead of select() where
possible.
* Removed the code which would attempt to determine when
the sock callbacks and scheduler were idle before completing
startup. The code was overly complex and not strictly
correct.
* Removed the -k and -K shutdown/restart options which was
not entirely safe.
* Removed the child-process privleged port Ns_SockListen
code in nsd/binder.c. Binding privleged ports (e.g., port
80) now requires the -b or -B command line methods introduced
in 3.4, e.g., "nsd -ft nsd.tcl -b myhost:80". The binder
code, while clever, was a potential security risk.
* Cleaned up some lingering sloppy uses of Ns_ConfigGet
and other older macros. Old macro and function definitions
can be disabled by defining NS_NOCOMPAT as is done when
compiling the core server and modules.
* Incremented version to 4.0b2.
2001-08-29 Scott S. Goodwin <scott@scottg.net>
* https.tcl: made fixes to ns_httppost per Rick Lansky at
bom.com. He also suggested I allow the Content-type to be
passed in as a parameter, so I've added that too.
2001-08-27 Scott S. Goodwin <scott@scottg.net>
* https.tcl: added ns_httppost, that is called with url,
rqset, qsset and timeout. The qsset is an ns_set with
key/values that will be turned into user=scottg&pass=1234,
for example, and passed as content in the POST.
2001-08-17 Scott S. Goodwin <scott@scottg.net>
* tcl/http.tcl: moved rqset to be the last arg passed to
ns_httpget so it wouldn't break existing code. I should
have done it that way in the first place.
2001-08-15 Scott S. Goodwin <scott@scottg.net>
* tcl/http.tcl: add the rqset param as the second argument to
ns_httpget, which in turn calls ns_httpsopen and passes the rqset
to it. The change is for consistency so that you can use cookies
with ns_httpget as well.
2001-07-16 Scott S. Goodwin <scott@scottg.net>
* tcl/http.tcl: you can now do ns_httpopen GET /index.html;
the script will automatically prepend
to the url.
2001-06-30 Dossy Shiobara <scott@scottg.net>
* nsd/conn.c, tests/api/ns_conn.adp: fixed ns_conn
outputheaders as per bug #433676 submitted by Yon Derek
(yond).
2001-05-22 Scott S. Goodwin <scott@scottg.net>
* nsd/conn.c: changed Ns_ConnDriverContext in 4.x to return
the actual conn-specific, module-specific context back,
which is how it works in 3.x. For some reason this API call
was changed to always return NULL, but nsopenssl and
potentially other comm drivers need to get their conn-specific
info back.
2001-04-25 Dossy Shiobara <dossy@panoptic.com>
* Implemented [ns_localtime ?tz?] as per "[ #418890 ]
ns_localtime should accept timezone".
2001-03-15 Dossy Shiobara <dossy@panoptic.com>
* include/Makefile.win32 win32/*/Makefile: initial attempts
at Makefiles suitable for NMAKE for building on Win32
* include/ns.h: define typedef __int64 INT64 for Win32
2001-03-12 Scott S. Goodwin <scott@scottg.net>
* nsmain.c: Segmentation fault when using -g <group> flag:
line 294 should read Ns_GetGid(garg) instead of Ns_GetGid(optarg).
2001-03-12 Jim Davidson
Initial checkin of AOLserver 4.0 (beta), now supporting
vitual servers and (finally) removing supporting for Tcl
7.6.
2001-03-08 Kris Rehberg
*** AOLserver 3.3 RELEASED ***
2001-03-08 Jim Davidson
* Added NsTclFinalizeThread() at end of Tcl TLS cleanup to
finalize Tcl 8.x thread data. This fix was the last hurdle
for finalizing nsd8x.
2001-01-31 Kris Rehberg
* Makefile (MODULES): nsunix, nsvhr, and nsodbc moved to
the Module Collection.
2001-01-16 Jim Davidson
* Cleaned up sloppy use of the nsServer global wherever
it's used.
2001-01-04 Kris Rehberg
* nsd/tclmisc.c: Ticket 13090. ns_striphtml crashing-bug
in nsd8x fixed.
2000-12-14 Kris Rehberg
* tcl/http.tcl: Corrected typo _ns_ns_http_readable.
* nsd/dstring.c (Ns_DStringPrintf): Ticket 12765.
Ns_DStringPrintf uses vsnprintf instead of vsprintf with
specified buffer size. Thanks to "??".
* nsd/return.c (Ns_ConnConstructHeaders): Ticket 12764.
If-Modified-Since (304) works with keepalive now. Thanks
to Jim "??".
2000-12-13 Kris Rehberg
* include/Makefile.global: Builds with architecture-specific
optimization options. Auto-detects architecture for most
platforms. Auto-select compiler and Purify usage from
command line, e.g.:
gmake nativeme=1 (all non-free Unix)
gmake gccme=1 (some non-free Unix) gmake
PURIFY=/path/to/purify/executable (Solaris and Irix only)
* nssock/Makefile*: now installs The Right Things in The
Right Places.
* nsd/Makefile: nsd8x is the default AOLserver now (nsd
symlinks to nsd8x).
* nsd/sample-config.tcl: Added some tuning parameters for
easy reference.
2000-12-12 Kris Rehberg
* nsvhr/nsvhr.c (UDSProxy): More type changes.
* nslog/nslog.c (Ns_ModuleInit): pointer-to-function casted.
* nscp/nscp.c (GetLine): buf changed to char *; casted
AcceptProc.
2000-12-12 Jim Davidson
* nssock/sock.cpp: Fixed multiple-load problems, added
sndbuf, rcvbuf, sendwait, and recvwait options. Added
configurable backlog via Ns_SockListenEx. Fixed compile
bugs for ssl. Restructured the socket module to wait in
server busy situations instead of sending the server busy
message. Also, moved the graceful close burden to the
SockThread from the connection thread.
* thread/win32.cpp: Moved WinThread allocation to DllMain,
eliminating GetWinThread function. Also, disabled thread
cleanup for final thread to avoid any TLS cleanup callbacks
attempting to invoke code in unloaded libraries like Tcl.
Removed call to NsInitThread no longer needed. Switched to
rolling condition broadcast wakeup as in the sproc code.
More fixes for new Thread context model.
* thread/tls.c: Changed NsLock API's to return 1/0 instead
of NS_OK/NS_TIMEOUT and more use of Ns_MasterLock to keep
things simple.
* thread/thread.c: Changed thread enum to return Ns_Thread,
not Ns_Thread pointer which didn't make much sense. Updated
"ns_info pools" command to reflect change. Fixed bugs with
Ns_ThreadEnum and pool counters. Update of the Ns_Pool API
to support more stats gathering available via new Ns_PoolStats
API. Remove Thread->etime and NsPool API's. Moved sprintf
of default thread name from NsThreadMain to NsInitThread
under protection of threads lock. Added comment for
NsInitThread. More fixes for new Thread context model.
Updated sproc.cpp code for new Thread management and removed
the wait for thread startup which shouldn't be needed.
* thread/test.c: Cleaned up code a bit to quiet compiler.
Better test for PTHREAD_TEST. Fixed undefined var bug for
sproc. Added some comments, a native pthread test, and a
recursive stack checker.
* thread/tcl8x.c: Added Tcl_JoinThread for benefit of
Tcl8.4.
* thread/sproc.cpp: Changed NsLock API's to return 1/0
instead of NS_OK/NS_TIMEOUT and more use of Ns_MasterLock
to keep things simple. Fixed some comment bugs, update
thrPtr->tid after fork. Added call the NsInitThread. Updated
sproc.cpp code for new Thread management and removed the
wait for thread startup which shouldn't be needed.
* thread/pthread.cpp: Changed NsLock API's to return 1/0
instead of NS_OK/NS_TIMEOUT and more use of Ns_MasterLock
to keep things simple. Fixed bug of not setting the tid
correctly. Added call the NsInitThread.
* thread/pool.c: Added Ns_PoolEnum to get at pool stats as
with mutexes and threads, removing the old Ns_PoolStats
API's and updating the "ns_info pools" command. Fixed bugs
with Ns_ThreadEnum and pool counters. Update of the Ns_Pool
API to support more stats gathering available via new
Ns_PoolStats API. Removed <mutex.h> for sgi which shouldn't
have been there. Removed the sbrk() code for now, was
crashing SGI (probably not thread safe). Use sbrk() on Unix
instead of malloc to avoid any malloc overhead or contention.
Reduced the zippy allocator page size to 16k from 64k.
* thread/pool.c, thread.c, sproc.cpp: Re-structured management
of the Thread context to better support threads created
without Ns_ThreadCreate (e.g., Java VM threads).
* thread/mutex.c: Changed NsLock API's to return 1/0 instead
of NS_OK/NS_TIMEOUT and more use of Ns_MasterLock to keep
things simple.
* thread/cs.c, memory.c, mutex.c, pool.c, pthread.cpp,
reentrant.c, rwlock.c, sema.c, sproc.cpp, tcl8x.c, test.c,
thread.c, win32.cpp: Restructured the thread interfaces,
moving the master lock to the platform interface code,
integrating the zippy allocator with Ns_Pool/Ns_ThreadAlloc
and use of a new simple direct allocator for all thread
objects.
* win32/nsthread/nsthread.dsp: Removed master.c and
oldpools.c.
* nsd/unix.c: Made ns_eval command disabled by default to
avoid using SIGUSR2.
* nsd/tclthread.c: Changed SETOBJ macro to SetObj function
which no longer sprintf's directly into interp->result.
* nsd/tclmisc.c: Added Ns_PoolEnum to get at pool stats as
with mutexes and threads, removing the old Ns_PoolStats
API's and updating the "ns_info pools" command. Changed
thread enum to return Ns_Thread, not Ns_Thread pointer
which didn't make much sense. Updated "ns_info pools"
command to reflect change. Added more info for "ns_info
pools". Added "ns_info pools" command to dump memory pool
stats.
* nsd/tclinit.c: Added nsconf.quiet and nsconf.startuptimeout.
Made ns_eval command disabled by default to avoid using
SIGUSR2. Added nsConfQuiet flag to quiet down the startup
messages with the -q flag.
* nsd/sock.c: Added Ns_SockListenEx.
* nsd/serv.c: Ensured the conn thread name was set first.
Added Ns_RegisterAtReady callbacks for indicating server
no longer busy.
* nsd/sched.c, nsmain.c, serv.c, sockcallback.c: Added code
to wait for conn thread, sock callback, and sched idle at
startup to help alleviate code start problems.
* nsd/nsmain.c: Shuffled initialization to ensure command
line args are read before calling any Ns API's, ensuring
zippy malloc can be set if needed.
* nsd/nsconf.c: Added nsconf.quiet and nsconf.startuptimeout.
Made ns_eval command disabled by default to avoid using
SIGUSR2.
* nsd/dstring.c: Remove unused vars. Uses ns_realloc to
grow strings and maintains dstring stack in the staticSpace
instead of the *addr pointer for compatibility with Tcl
dstrings.
* nsd/callbacks.c: Added Ns_RegisterAtReady callbacks for
indicating server no longer busy.
* nsd/binder.c: Added Ns_SockListenEx.
2000-12-12 Kris Rehberg
* nsvhr/nsvhr.c (VHRProc): Matches hostnames regardless of
case.
* nssock: Supports Rainbow CryptoSwift SSL accelerators
(compile-time option; requires the Swift SDK from).
* nsd/nsmain.c (Ns_Main): Changed order of some config
default initialization. Config options cleaned up a lot.
Usage message very less glib. SUNWspro dumped core on
usage message due to nsconf.argv0 quigglyness.
2000-10-20 Kris Rehberg
*** AOLserver 3.2 RELEASED ***
2000-10-20 Jim Davidson
* win/tclWinSock.c: Fixed deadlock in sockets init code.
* nsd/nswin32.c: Fixed service install code to allow long
pathnames with spaces. Added/use ns_pipe which set's
close-on-exec like ns_sockpair.
2000-10-17 Kris Rehberg
* nssock/sock.cpp: extra padding on Server Busy message to
defeat MSIE friendly error messages.
* nsd/nsconf.h: All configuration option defaults have been
moved to nsconf.h as #defines.
* Makefile (install): Tcl library for nsd8x is now installed
into $(PREFIX)/lib/tcl8.3.
* tcl/http.tcl (ns_httpopen): Host:port is now sent to
remote host if != 80. Suggested by Jerry Asher.
* tcl/fastpath.tcl (_ns_dirlist): All kinds of Win32
pathnames should now be working. Thanks to Eric Klein.
* nsd/return.c (Ns_ConnReturnNotice): New options
"errorminsize", to pad error messages to defeat MSIE friendly
errors (fix suggested by ArsDigita) and "noticedetail" to
return more detailed information on notice pages.
* nslog/nslog.c: suppressquery option added to suppress
logging of query data.
* nslog/nslog.c: LogExtendedHEaders option added. Contributed
by ArsDigita.
* nsd/tclfile.c: Input string to mktemp is copied, because
mktemp edits the string in-place and that's generally a
bad thing to do with argv's. Contributed by ArsDigita.
* nsd/tclnsshare.cpp (ShareTraceProc): Patch to tclnsshare.cpp
to avoid race conditions if the shared value is a list.
Contributed by ArsDigita.
* tcl/http.tcl (ns_httpopen): CRLF now returned in ns_httpopen.
Contributed by ArsDigita.
* tcl8.3.2/generic/tclCmdIL.c: Nonsense case of lsorting
a list with length <= 0 caused a memory leak. Fixed.
Contributed by ArsDigita.
* nsd/adpfancy.c: We now use the Arsdigita version of
adpfancy. Contributed by ArsDigita.
* nsd/adp.c: Sundry ArsDigita changes.
2000-10-16 Kris Rehberg
* tcl/init.tcl: Initialize errorCode and errorInfo like
tclsh does. From ArsDigita.
* nsd/nsd.h, nsd/tclcmds.c, nsd/tclvar.c: nsv_names Tcl
command lists names of nsv's in memory.
* tcl8.3.2: The complete Tcl 8.x distributions are now
included. They aren't installed with AOLserver's "gmake
install", but you can install them manually if you want to
use them for the i18n encodings and stuff like that. It
will install into the "lib/tcl8.3" directory of the binary
distribution with AOLserver 3.3 and later.
* nsd/nsmain.c (Ns_Main): Had to move Ns_ThreadSetName
below the stdin/stdout/stderr reassignment to fix a fd
problem with running nsd on Irix in "installed" or "daemon"
mode that would prevent the server from starting up. Sigh.
(Ns_Main): Took out little note about -k|-K being deprecated.
2000-10-13 Kris Rehberg
* nsd/nsmain.c (Ns_Main): gid of the specified user is set even if
it's not specified.
(UsageError): -K and -k give a "deprecated" warning.
(Ns_Main): -f gives a "deprecated" warning.
* nsd/binder.c (PreBind): Didn't really tell us if it was
successful at pre-binding. Helpful to know if you're
wondering what happened to that port you wanted to pre-bind.
(Binder): backlog variables (2) initialized to nsconf.backlog.
* nssock/sock.cpp, nsd/return.c: Made an attempt at
standardizing the error codes and error page content.
2000-10-13 Jim Davidson
* sproc.cpp: Fixed Wakeup() error message and update child's
sproc pid after fork.
* nsd/random.c: Put back log message when generating seeds.
* nsd/nsconf.c: Fixed memory overwrite bug in stats and
increased the default buffer value.
* nsd/keepalive.c: Fixed array overwrite with maxkeep=0
bug. Contributed by ArsDigita.
* nsd/tclkeylist.c: A more modern version added that's
compatible with Tcl 8.3.2 (nsd8x).
* nsd/stamp.c: Forces the build date reported by AOLserver
to be absolutely the last possible moment before the link
step happens, not just the last time nsmain.c was built.
* nsd/binder.c: New option "-b" to prebind ports as root
(but not listen on them). This allows AOLserver to start
up on MacOS X on ports 80 and 443 like this: "nsd ..blah..
-b 10.0.0.1:80".
* nssock/: Building nsssl is much less of a debacle and
doesn't rebuild itself three times anymore.
* various: fork() calls in all kinds of code were changed
to use ns_fork. ns_fork now lives in the thread library
(thread/ directory).
* tcl8.3.2/generic/tclIO.c: Fixed memory leak that leaks
around 112 bytes each time a file descriptor is closed.
Thanks to Rob Mayoff for finding this and proposing a
solution.
2000-10-09 Kris Rehberg
* sample-config.tcl: nsd.tcl is now sample-config.tcl so
that existing users can look at the new reference configuration.
* nsd/nsmain.c (Ns_InfoNameOfExecutable): new function just
returns nsconf.nsd which is determined elsewhere.
* nscp/nscp.c (Login): Tells you lots of harmless info
about the machine once you log in. Also, nscp does not
run unless configuration is explicitly set
* nsd/nsmain.c: Some typo or other.
* General: Files were re-arranged and some were renamed.
The sample SSL key/cert files are sample-certfile,
sample-keyfile. The nsd.tcl is now called sample-config.tcl
(so that existing installations always have a current
reference copy of the configuration). Other minor changes.
* tests/: Moved from its hiding place in scripts/test.
Install them with "gmake install-tests".
* nsd/tclxkeylist.c, nsd/tclcmds.c, nsd/Makefile: Re-added
TclX keyl* commands that were in AOLserver 2.x. These are
inferior to ns_set which is why they were left out in the
first place.
2000-10-04 Jim Davidson
* binder.c: Set close-on-exec on received fd from binder.
* sock.c: Removed cthread errno API's, Mac OS X now has
thread-safe errno.
* nsd/nsmain.c, include/Makefile.global, nsd/nsthread.h,
nspd/main.c, nsunix/nsunix.c, nsvhr/nsvhr.c, thread/Makefile,
thread/osthread, thread/reentrant.c, thread/signal.c:
Updates for Mac OS X. Use MACOSX instead of APPLE; use
HAVE_BSDSETPGRP, HAVE_CMMSG, use pthreads instead of
cthreads.
* nssock/sock.c: Removed setting bufsize to uninitialized
value on ssl.
* include/ns.h: Removed Ns_CacheTimedGetValue which was an
odd interface not used anywhere.
* nsd/nsd.h: Update to version 3.11.
* tcl/namespace.tcl: Added namespace export to init script.
* thread/pthread.cpp: Stopped using pthread_once as it
appears to require a lock.
2000-10-04 Kris Rehberg
* win32/nsssl/nsssl.dsp: nsssl project for win32.
* win32/aolserver.dsw: main installation keeps DLL's as
DLL's now.
* scripts/nsd.tcl: shared library extension is now
platform-dependent
* nssock/ssltcl.c: Changed name of ReadFile adn WriteFile
to avoid Win32 naming conflicts.
2000-09-28 Kris Rehberg
* scripts/tests/nstelemetry.adp: added "Expires: now" header
to ensure it gets run each time it's visitted.
* nsd/serv.c (NsConnArgProc): Race condition when threads
exit while [ns_info threads] is run; arg can be NULL. Seen
mostly by people who regularly visit nstelemetry.adp.
(AppendConn): same thing but with connPtr. This may be a
losing battle. It appears to work on a busy Irix server,
so I'm declaring victory for now.
2000-09-28 Jim Davidson
* nssock/sock.c: Fixed bufferred read code in SockRead,
resulting in a big performance boost and system load
reduction. Special thanks to Zachary Girouard.
2000-09-05 Kris Rehberg
*** AOLserver 3.1 Released ***
2000-09-05 (various: Jerry Asher, Jim Davidson, "Dossy," Curtis Galloway,
Scott S. Goodwin, Rob Mayoff, Kris Rehberg)
* thread/win32.cpp: Sets thread stack size as on other
platforms.
* thread/thread.c: NULL out thread arg at exit to avoid
Ns_ThreadEnum checking arg info for possibly deallocated
context as seen in ns_info threads. Also, moved read of
firstPtr in Ns_ThreadEnum inside lock. Added Ns_ThreadCreate2
in thread.c needed for upgrade to Tcl 8.3.1 in tcl8x.c
* thread/pthread.cpp: ETIME bug work around not causes
wakeup in Ns_CondWait and Ns_CondTimeWait instead of waiting
again. This is more conservative and should avoid problems
some have had with threads missing wakeup.
* thread/pool.c: Added a simple 1-byte range check to -z
allocator.
* thread/Makefile: Added dependency for osthread.o to
Makefile.
* tcl/namespace.tcl: Added namespace export to init script.
* nsvhr/nsvhr.c: Switched to Ns_WriteConn in TimedSockDump
to ensure all data was sent.
* nssock(nsssl): SSL module includes a fake 40-bit/512-bit
export-grade SSL keyfile.pem and certfile.pem for immediate
use on installation. Adjusted for use with BSAFE 4 and 5.
* nspd: Library now installed to binary distribution.
* nsd/tclsock.c: Fixed crash bug in error message in
ns_socknread.
* nsd/tclcmds.c: Added ns_adp_registertag command as
documented.
* nsd/serv.c: Added missing break for unauthorized case in
ConnRun.
* nsd/random.c: Fixed deadlock between Ns_DRand/Ns_GenSeeds.
* nsd/nsmain.c: Fixed some message formatting problems.
* nsd/mimetypes.c: Added .png type, "image/png".
* nsd/dbtcl.c: Removed unused variables in GetCsvCmd. Use
a dstring to create the column list instead of incrementally
setting the output variable with Tcl_SetVar. This was
necessary to avoid conflicting definitions of the needed
TCL_ flags between 7.6 and 8.x.
* nsd/dbinit.c: MOdified current per-thread handle count
to use a single TLS slot instead of a slot per pool.
* nsd/tclinit.c,adp.c,conn.c: The use of thread-local
storage (Tls) is now self-initializing in the conn, ADP,
Tcl, etc. This allows ns_conn commands to be used outside
a connection thread as well as other uses of Tls where it
may not be ready for use.
* nscp/nscp.c: Password non-echo code confuses Win32 and
some free Unix telnet clients so it has been disabled by
default for now, though it can be enabled by setting
"echopassword" in the nscp module section of nsd.tcl.
2000-08-21 Kris Rehberg
* nscp/nscp.c: Makes some attempt to recognize and handle
telnet IAC codes like CTRL-C and CTRL-D to force a logout.
This implementation of the telnet protocol is dirt-cheap,
so only standard Unix telnet is supported. On Win32, IAC
handling is completely disabled because the client is too
chatty with its IAC codes.
2000-08-20 Kris Rehberg
* nsftp, nspostgres, nssolid, nssybpd moved to $TOP level.
2000-08-17 Jim Davidson
* nsd/dbtcl: Removed unused variables in GetCsvCmd.
* nsd/adp.c: Fixed bug of not truncating output buffer when
an error was thrown during an ns_adp_parse. Fix suggested
by Rob Mayoff.
* tcl7.6 and tcl8.2.3: Switched to blocking Tcl_WaitPid to
avoid zombies as suggested by Rob Mayoff.
* thread: NULL out thread arg at exit to avoid Ns_ThreadEnum
checking arg info for possibly deallocated context as seen
in ns_info threads. Also, moved read of firstPtr in
Ns_ThreadEnum inside lock.
2000-08-17 Kris Rehberg
* nssock/sock.c (SockThread): warning sent to log when
Server Busy is returned.
* All the Makefiles should be in line with each other.
Typing "gmake", "gmake install" and "gmake clean" should
work in any directory. NSHOME is paid attention to by all
Makefiles.
* nsd: Ns_Log and Ns_Fatal statements are hopefully more
standardized and more useful to admins and developers.
* Irix now builds as -o32 using the native compiler by
default. See Makefile.global on how to change.
2000-08-15 Kris Rehberg
* include/Makefile.global (INSTLOG): should have pointed
to $(INST)/lib, not $(INST)/modules/lib.
* Makefile: nsunix resurrected. All modules are built.
If a module is missing a library, it is not built, but it
won't stop the AOLserver build process (no error is thrown).
The build will continue with the next module.
* nsftp: guesses if you have TCP_WRAPPERS available.
* nsext: Ten guesses why $(NSHOME)/include/nsextmsg.h was
duplicated here.
* nssybpd: Hopefully, the log statements will be easier to
understand by both admins and developers. It's still messy
since it uses syslog. Makefile redone to use standard
AOLserver rules. RPATH is used a little more intelligently.
Removed files that had no business living there.
* include/Makefile.global: Took stab at RPATH support on
Solaris to perhaps remove the need for LD_LIBRARY_PATH on
an intelligenly-administered system. New rule for libnspd.a.
2000-08-14 Kris Rehberg
* Makefile: nsvhr has been resurrected and enjoys our full
support.
* nsexample/Makefile: The include at the bottom wasn't using
$(NSHOME).
2000-08-14 Jim Davidson
* Tcl 8.x library upgraded to tcl8.3.2.
* thread/pool.c: A spiffy range-checker added to the Zippy
(-z) memory allocator.
2000-08-11 Kris Rehberg
* nsvhr/nsvhr.c: Always add "Connection: close" to the
request line to satisfy HTTP 1.1 RFC -- this would break
MSIE in HTTP 1.1 mode. HTTP_EOL of "\r\n" used on all
request lines for stupid web servers on the other end.
Protocol "tcp" added as synonym of "http" for old-time Unix
heads. Lots of folks lended a hand on this one -- Satyam
Priyadarshy, Jerry Asher, Kriston Rehberg, and special
thanks to Wanda G. at AOL for adding a CNAME in DNS so
quickly.
2000-08-09 Kris Rehberg
* nsd/serv.c: A whole lot less chatty about conns starting
and exiting. If you want to see them, turn on the Debug
flag.
* doc/*: lots of updates. Title page extremely simplified.
SSL docs updated. Release notes updated. NSV docs corrected
(thanks to Todd Levy.
2000-08-09 Jim Davidson
* tcl7.6/generic/tclFHandle.c: Removed needed fileTable
which could result in crashes when fd's where reused quickly
[fixes a rare multiple-exec crashing bug in nsd76 --kris].
* thread/tcl8x.c: Added a wrapper startup for Tcl_CreateThread
for the benefit of Win32.
* nsd/log.c: Removed severityRank array.
* nsd/tclmisc.c: Fixed bug with ns_info pid. [I can't code --kris]
* nsd: keepalive.c,nsmain.c,sched.c,serv.c: Re-ordered
shutdowns to ensure connection threads are stopped before
other shutdowns begin (e.g., sched, sockcallback).
* tcl8.3.1 replaces tcl8.3.0. README.AOLSERVER added to
tcl8.3.1 directory. Original copies of changed are named
*.orig.
* include/Makefile.global: Build environment now uses gcc
-shared -nostartfiles as the default LDSO.
* nsthread/thread.c: Added Ns_ThreadCreate2 with extra
flags argument used by Tcl_CreateThread to create a detached
thread.
2000-08-06 Scott S. Goodwin
* nsd/log.c: Segmentation fault was occuring when writing
to the log file because file pointer was being assigned to
incorrectly - it wasn't NULL and it wasn't a valid address
within processes memory. Fixed.
2000-08-06 Scott S. Goodwin
* nssock: You can now compile with BSAFE versions 4 and 5.
You'll need to specify the path to your BSAFE libaries and
the BSAFE version in the nssock/Makefile before compiling.
If you don't have BSAFE and want to compile without SSL at
all, edit the toplevel Makefile and take out all the "SSL=1"
text. The files changed were nssock/Makefile and
nssock/t_stdlib.c.
2000-08-02 Kris Rehberg
* Build process is a little more rule-oriented. The cleaning
rules "distclean" and "clobber" were removed. The Tcl
libraries are always distcleaned when "gmake clean" is
invoked. Rules that can be used as dependencies were made
for libnsthread and the Tcl libraries -- their names are
"libnsthread," "libtcl76," and "libtcl8x," respectively.
PREFIX is now used as the installation directory (along
with INST), so the more familiar "gmake install
PREFIX=/usr/local/aolserver" will work. Additionally,
gmaking in a subdirectory with dependencies now works.
* nsd/log.c: The sourge of modlog has been removed. All
code included with AOLserver that used Ns_ModLog now doesn't.
Many log statements are now hopefully more standardized.
This will be a continuing improvement over the next several
updates. I would like to use gcc's __FUNCTION__ macro but
it doesn't work on native compilers, but we may start using
__LINE__ and __FILE__ instead or replace Ns_Log with a
smart macro that takes care of all this stuff for us.
* nsd/tclmisc.c (NsTclInfoCmd): ns_info pid added to return
the process id.
2000-08-01 Kris Rehberg
* nsd/adp.c (Ns_AdpRequest): The enableexpire option was
putting an Expires header even if it already existed.
* nsd/return.c (Ns_ConnReturnNotice): Yikes, /face should
have been /font. No more fonts, colors, etc, on default
notice pages.
* nsd/tclsock.c (NsTclSockOpenCmd): Removed spurious Ns_Log
Notice from ns_sockopen.
* tcl/form.tcl (ns_getform): MSIE presents the wrong stuff
to the server when a multipart/formdata POST is redirected.
Workaround contributed by Joseph Bank.
* tcl/fastpath.tcl (_ns_dirlist): base href removed --
links are now fully-qualified.
* Makefile (install): include and lib dirs are now included
in binary distribution.
* tcl/http.tcl (_ns_http_gets): \n replaced by \r in all
but _ns_http_gets so that arbitrary headers get set correctly.
* tcl7.6/generic/tclPosixStr.c (Tcl_SignalMsg): Patch to
Tcl 7.6 for Red Hat on SPARC architectures. Contributed
by Mike Chan.
2000-07-13 Kris Rehberg
* scripts/nsd.tcl: nssslmodule names the nsssl/nsssle
binary's filename. nscp_port tells nscp what port to
listen.
* nssock: nssock.c renamed sock.c, SSL support has been
merged back with nssock so that both nsssl and nssock use
identical socket code.
* nsssl2: directory removed; nsssl is in the nssock directory
now.
2000-05-09 Kris Rehberg
* Re-added doc directory which has had the online docs
removed.
2000-05-02 Kris Rehberg
* Makefile, include/Makefile.global, include/Makefile.module,
nsexample/Makefile: Now uses NSHOME variable to locate
AOLserver. NSHOME is automatically figured out in the
top-level Makefile and all the lower Makefiles still use
relative directory paths. The intention of NSHOME is for
modules that do NOT live in the AOLserver source directory
tree. The nsexample/Makefile explains how this works.
* nsftp module added. Contributed by Eric O'Laughlen.
2000-04-12 Kris Rehberg
*** AOLserver 3.0 FINAL Released *** | https://sources.debian.org/src/aolserver4/4.0.10-3/ChangeLog/ | CC-MAIN-2020-34 | refinedweb | 14,016 | 53.88 |
Welcome to Cisco Support Community. We would love to have your feedback.
For an introduction to the new site, click here. And see here for current known issues.
Hello,
I know this question was asked many times, but I'm still not able to finalize my configuration on 871w. LAN part works fine, but wireless clients do not get DHCP IP. here is the config:
Building configuration...
Current configuration : 2092 bytes
!
version 12.4
no service pad
service timestamps debug datetime msec
service timestamps log datetime msec
no service password-encryption
hostname WROUTER
boot-start-marker
boot-end-marker
logging message-counter syslog
logging buffered 4096
no aaa new-model
dot11 syslog
dot11 ssid sputnik
vlan 1
authentication open
ip source-route
no ip dhcp use vrf connected
ip dhcp excluded-address 192.168.1.254
ip dhcp pool vlan1
network 192.168.1.0 255.255.255.0
default-router 192.168.1.254
dns-server 167.206.245.7 167.206.245.71
lease 10
ip cef
no ip domain lookup
no ipv6 cef
multilink bundle-name authenticated
archive
log config
hidekeys
bridge irb
interface FastEthernet0
interface FastEthernet1
interface FastEthernet2
interface FastEthernet3
interface FastEthernet4
ip address dhcp
ip nat outside
ip virtual-reassembly
duplex auto
speed auto
no cdp enable
interface Dot11Radio0
no ip address
!
encryption vlan 1 mode wep mandatory
encryption key 1 size 128bit 0 0D9E3A3AF78EA7A156A6D6FB09 transmit-key
ssid sputnik
speed basic-1.0 basic-2.0 basic-5.5 basic-6.0 basic-9.0 basic-11.0 basic-12.0 basic-18.0 basic-24.0 basic-36.0 basic-48.0 basic
interface BVI1
ip address 192.168.1.254 255.255.255.0
ip nat inside
ip forward-protocol nd
ip route 0.0.0.0 0.0.0.0 dhcp
ip http server
no ip http secure-server
ip nat inside source list 1 interface FastEthernet4 overload
access-list 1 permit 192.168.1.0 0.0.0.255
control-plane
bridge 1 protocol ieee
bridge 1 route ip
line con 0
no modem enable
line aux 0
line vty 0 4
scheduler max-task-time 5000
end
I'dliket o have LAN and WLAN clients in same 192.168.1.0 subnet.
Thanks.
try removing the VLAN statement under the SSID, and the encryption lines. Just place the main Dot11Radio0 Interface in Bridge-group 1 and see how that works for you. SO:
authentication open
no interface dot0.1
int dot0
bridge-group 1
HTH,
Steve
thank you.
I read this forum and i found that I need vlan 1 for each encryption line. Here is the config that works for me:
Current configuration : 2130 bytes
hostname xxxxx
guest-mode
encryption vlan 1 key 1 size 128bit 0 0D9E3A3AF78EA7A156A6D6FB09 transmit-key
speed basic-1.0 2.0 5.5 6.0 9.0 11.0 12.0 18.0 24.0 36.0 48.0 54.0
password cisco
This is what I got and it has been working for me. From my modem to my RV016 to my 871w. Once I figure out the PPPOE the 871w will be my only router running, and figure out the port forwarding, but most important I need to configure PPPOE.
mr-r1#sh star
Using 3825 out of 131072 bytes
! Last configuration change at 08:10:30 PCTime Sun Oct 28 2012 by ramosm
! NVRAM config last updated at 08:10:33 PCTime Sun Oct 28 2012 by ramosm
service timestamps debug datetime msec localtime
service timestamps log datetime msec localtime
hostname mr-r1
logging buffered 64000
logging rate-limit 20
enable secret 5 $1$PDK9$YSz8GsnVsDYevR1hVGMG70
aaa new-model
aaa authentication login default local
aaa authorization exec default local
aaa session-id common
clock timezone PCTime -8
clock summer-time PCTime date Apr 6 2003 2:00 Oct 26 2003 2:00
crypto pki trustpoint TP-self-signed-3978252741
enrollment selfsigned
subject-name cn=IOS-Self-Signed-Certificate-3978252741
revocation-check none
rsakeypair TP-self-signed-3978252741
crypto pki certificate chain TP-self-signed-3978252741
certificate self-signed 01 nvram:IOS-Self-Sig#B.cer
dot11 ssid ramfam
vlan 55
authentication open
mbssid guest-mode
ip dhcp excluded-address 10.25.55.1 10.25.55.49
ip dhcp excluded-address 10.25.55.76 10.25.55.254
ip dhcp excluded-address 10.25.50.1 10.25.50.49
ip dhcp excluded-address 10.25.50.76 10.25.50.254
ip dhcp pool Data
import all
network 10.25.50.0 255.255.255.0
dns-server 10.55.55.1 4.2.2.1
domain-name MR-Lab1
default-router 10.25.50.1
lease 25
ip dhcp pool Wireless
network 10.25.55.0 255.255.255.0
default-router 10.25.55.1
dns-server 10.55.55.1 4.2.2.2
ip domain name MR-Lab1.com
ip name-server 10.55.55.1
username ramosm privilege 15 secret 5 $1$J2cq$abQJlRlZgmIlEDPX/jd8A1
log config
hidekeys
no ip ftp passive
description AirNet 1100
speed 100
spanning-tree portfast
description Extra cat5
description Ubuntu PC
description PS3
description Internet Wan Port
ip address 10.55.55.105 255.255.255.0
ip nat outside
ip virtual-reassembly
full-duplex
no ip address
encryption vlan 55 key 1 size 128bit 0 AB2081CA12B126DD2F95ABCF32 transmit-key
encryption vlan 55 mode wep mandatory
broadcast-key vlan 55 change 30
ssid ramfam
mbssid
speed basic-1.0 basic-2.0 basic-5.5 6.0 9.0 basic-11.0 12.0 18.0 24.0 36.0
station-role root
interface Dot11Radio0.55
encapsulation dot1Q 55 native
bridge-group 1 subscriber-loop-control
bridge-group 1 spanning-disabled
bridge-group 1 block-unknown-source
no bridge-group 1 source-learning
no bridge-group 1 unicast-flooding
ip address 10.25.50.1 255.255.255.0
ip nat inside
interface Vlan55
ip address 10.25.55.1 255.255.255.0
ip route 0.0.0.0 0.0.0.0 10.55.55.1
ip http authentication local
ip http secure-server
ip nat inside source list 2 interface FastEthernet4 overload
access-list 1 remark SDM_ACL Category=2
access-list 1 permit 10.25.50.0 0.0.0.255
access-list 2 remark SDM_ACL Category=2
access-list 2 permit 10.25.55.0 0.0.0.255
exec-timeout 30 0
password Cisco
logging synchronous
no modem enable
exec-timeout 20 0
mr-r1# | https://supportforums.cisco.com/t5/getting-started-with-wireless/871w-wireless-configuration/td-p/1189118 | CC-MAIN-2017-43 | refinedweb | 1,080 | 55.84 |
At 01:40 PM 6/28/01 -0700, Mark McEahern wrote: >I'm a Zope and Python newbie and I'm trying to utilize Persistence, but I've >seen two different ways: > > import ZODB > from Persistence import Persistent As Michel said, this is only for non-Zope use. In this case the 'import ZODB' statement does some funky stuff with the namespace. ;-) But I do not even attempt to understand that now. Next year maybe... If anyone knows about some nice documentation discussing/explaining this behavior, could you post the link? Regards, Stephan -- Stephan Richter CBU - Physics and Chemistry Student Web2k - Web Design/Development & Technical Project Management _______________________________________________ Zope-Dev maillist - [EMAIL PROTECTED] ** No cross posts or HTML encoding! ** (Related lists - )
- [Zope-dev] persistence Mark McEahern
- Re: [Zope-dev] persistence Michel Pelletier
- Stephan Richter | https://www.mail-archive.com/zope-dev@zope.org/msg07243.html | CC-MAIN-2017-39 | refinedweb | 134 | 53.81 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.